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 image_as_type(image: _InputImgT, typ: type[_OutputImgT]) -> _OutputImgT:
"""Converts between :class:`torch.Tensor` and :class:`PIL.Image.Image` image representations.
Args:
image (torch.Tensor | PIL.Image.Image): A single image
represented as a :class:`PIL.Image.Image` or
a ... | Converts between :class:`torch.Tensor` and :class:`PIL.Image.Image` image representations.
Args:
image (torch.Tensor | PIL.Image.Image): A single image
represented as a :class:`PIL.Image.Image` or
a rank 2 or rank 3 :class:`torch.Tensor` in ``HW`` or ``CHW`` format.
A ra... | image_as_type | python | mosaicml/composer | composer/algorithms/utils/augmentation_common.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/utils/augmentation_common.py | Apache-2.0 |
def map_pillow_function(f_pil: Callable[[PillowImage], PillowImage], imgs: _OutputImgT) -> _OutputImgT:
"""Lifts a function that requires pillow images to also work on tensors.
Args:
f_pil ((PIL.Image.Image) -> PIL.Image.Image): A callable that takes maps :class:`PIL.Image.Image` objects.
t... | Lifts a function that requires pillow images to also work on tensors.
Args:
f_pil ((PIL.Image.Image) -> PIL.Image.Image): A callable that takes maps :class:`PIL.Image.Image` objects.
to other :class:`PIL.Image.Image` objects.
imgs (torch.Tensor | PIL.Image.Image): a :class:`PIL.Image.Im... | map_pillow_function | python | mosaicml/composer | composer/algorithms/utils/augmentation_common.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/utils/augmentation_common.py | Apache-2.0 |
def posterize(pil_img: Image.Image, level: float):
"""Posterize an image.
.. seealso:: :func:`PIL.ImageOps.posterize`.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
"""
level = _int_parameter(_sample_level(leve... | Posterize an image.
.. seealso:: :func:`PIL.ImageOps.posterize`.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
| posterize | python | mosaicml/composer | composer/algorithms/utils/augmentation_primitives.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/utils/augmentation_primitives.py | Apache-2.0 |
def rotate(pil_img: Image.Image, level: float):
"""Rotate an image.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
"""
degrees = _int_parameter(_sample_level(level), 30)
if np.random.uniform() > 0.5:
degr... | Rotate an image.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
| rotate | python | mosaicml/composer | composer/algorithms/utils/augmentation_primitives.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/utils/augmentation_primitives.py | Apache-2.0 |
def solarize(pil_img: Image.Image, level: float):
"""Solarize an image.
.. seealso:: :func:`PIL.ImageOps.solarize`.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
"""
level = _int_parameter(_sample_level(level),... | Solarize an image.
.. seealso:: :func:`PIL.ImageOps.solarize`.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
| solarize | python | mosaicml/composer | composer/algorithms/utils/augmentation_primitives.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/utils/augmentation_primitives.py | Apache-2.0 |
def shear_x(pil_img: Image.Image, level: float):
"""Shear an image horizontally.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
"""
level = _float_parameter(_sample_level(level), 0.3)
if np.random.uniform() > 0.5... | Shear an image horizontally.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
| shear_x | python | mosaicml/composer | composer/algorithms/utils/augmentation_primitives.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/utils/augmentation_primitives.py | Apache-2.0 |
def shear_y(pil_img: Image.Image, level: float):
"""Shear an image vertically.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
"""
level = _float_parameter(_sample_level(level), 0.3)
if np.random.uniform() > 0.5:
... | Shear an image vertically.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should
be in ``[0, 10]``.
| shear_y | python | mosaicml/composer | composer/algorithms/utils/augmentation_primitives.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/utils/augmentation_primitives.py | Apache-2.0 |
def brightness(pil_img: Image.Image, level: float):
"""Enhance brightness on an image.
.. seealso:: :class:`PIL.ImageEnhance.Brightness`.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should be
in ``[0, 10]``.
"""
level = _symmetric_sam... | Enhance brightness on an image.
.. seealso:: :class:`PIL.ImageEnhance.Brightness`.
Args:
pil_img (PIL.Image.Image): The image.
level (float): The intensity, which should be
in ``[0, 10]``.
| brightness | python | mosaicml/composer | composer/algorithms/utils/augmentation_primitives.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/utils/augmentation_primitives.py | Apache-2.0 |
def _standardize_weights(W: torch.Tensor):
"""Function to standardize the input weight ``W``"""
reduce_dims = list(range(1, W.dim()))
W_var, W_mean = torch.var_mean(W, dim=reduce_dims, keepdim=True, unbiased=False)
return (W - W_mean) / (torch.sqrt(W_var + 1e-10)) | Function to standardize the input weight ``W`` | _standardize_weights | python | mosaicml/composer | composer/algorithms/weight_standardization/weight_standardization.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/weight_standardization/weight_standardization.py | Apache-2.0 |
def apply_weight_standardization(module: torch.nn.Module, n_last_layers_ignore: int = 0):
"""`Weight Standardization <https://arxiv.org/abs/1903.10520>`_ standardizes convolutional weights in a model.
Args:
module (torch.nn.Module): the torch module whose convolutional weights will be parametrized.
... | `Weight Standardization <https://arxiv.org/abs/1903.10520>`_ standardizes convolutional weights in a model.
Args:
module (torch.nn.Module): the torch module whose convolutional weights will be parametrized.
n_last_layers_ignore (int, optional): the number of layers at the end of the module to not a... | apply_weight_standardization | python | mosaicml/composer | composer/algorithms/weight_standardization/weight_standardization.py | https://github.com/mosaicml/composer/blob/master/composer/algorithms/weight_standardization/weight_standardization.py | Apache-2.0 |
def reduce_value(
value: Union[int, float],
model_device: torch.device,
reduce_op: str = 'mean',
):
"""Reduce a value across distributed processes.
Args:
value (Union[int, float]): The value to reduce.
model_device (torch.device): The device on which the model is located.
re... | Reduce a value across distributed processes.
Args:
value (Union[int, float]): The value to reduce.
model_device (torch.device): The device on which the model is located.
reduce_op (str, optional): The reduction operation to perform. One of 'mean', 'avg', 'sum', 'min', 'max'.
Def... | reduce_value | python | mosaicml/composer | composer/callbacks/memory_monitor.py | https://github.com/mosaicml/composer/blob/master/composer/callbacks/memory_monitor.py | Apache-2.0 |
def _get_time(self, state: State) -> int:
"""Different benchmarks log different units of time."""
benchmark_time = {
'resnet': state.timestamp.epoch.value,
'bert': state.timestamp.sample.value,
}
return benchmark_time[self.benchmark] | Different benchmarks log different units of time. | _get_time | python | mosaicml/composer | composer/callbacks/mlperf.py | https://github.com/mosaicml/composer/blob/master/composer/callbacks/mlperf.py | Apache-2.0 |
def after_loss(self, state: State, logger: Logger):
"""Check if loss is NaN and raise an error if so."""
if isinstance(state.loss, torch.Tensor):
if torch.isnan(state.loss).any():
raise RuntimeError('Train loss contains a NaN.')
elif isinstance(state.loss, Sequence):
... | Check if loss is NaN and raise an error if so. | after_loss | python | mosaicml/composer | composer/callbacks/nan_monitor.py | https://github.com/mosaicml/composer/blob/master/composer/callbacks/nan_monitor.py | Apache-2.0 |
def _get_elapsed_duration(self, state: State) -> Optional[float]:
"""Get the elapsed duration.
Unlike `state.get_elapsed_duration`, this method computes fractional progress in an epoch
provided at least 1 epoch has passed by recording how many batches were in each epoch.
"""
if ... | Get the elapsed duration.
Unlike `state.get_elapsed_duration`, this method computes fractional progress in an epoch
provided at least 1 epoch has passed by recording how many batches were in each epoch.
| _get_elapsed_duration | python | mosaicml/composer | composer/callbacks/runtime_estimator.py | https://github.com/mosaicml/composer/blob/master/composer/callbacks/runtime_estimator.py | Apache-2.0 |
def download_file(
source_uri: str,
destination_path: str,
node_ranks: Optional[list[int]] = None,
num_attempts: int = 5,
):
"""Downloads a file (object) from the specified URI to the specified directory.
Args:
source_uri (str): The URI to download the file from or a symlink to the URI.... | Downloads a file (object) from the specified URI to the specified directory.
Args:
source_uri (str): The URI to download the file from or a symlink to the URI.
destination_path (str): The directory to download the file to.
node_ranks (list[int]): The ranks of the nodes that will download th... | download_file | python | mosaicml/composer | composer/checkpoint/download.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/download.py | Apache-2.0 |
def download_and_extract_symlink(source_uri) -> str:
"""Downloads a symlink file from the specified URI and returns the path it points to.
Args:
source_uri (str): The URI to download the symlink from.
Returns:
str: The path the symlink points to.
"""
object_store = maybe_create_obj... | Downloads a symlink file from the specified URI and returns the path it points to.
Args:
source_uri (str): The URI to download the symlink from.
Returns:
str: The path the symlink points to.
| download_and_extract_symlink | python | mosaicml/composer | composer/checkpoint/download.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/download.py | Apache-2.0 |
def download_monolithic_checkpoint(
source_uri: str,
destination_path: str,
global_rank_zero_only: bool = True,
):
"""Downloads a monolithic checkpoint from the specified URI to the specified directory.
Args:
source_uri (str): The URI to download the checkpoint from or symlink that points t... | Downloads a monolithic checkpoint from the specified URI to the specified directory.
Args:
source_uri (str): The URI to download the checkpoint from or symlink that points to the URI.
destination_path (str): The directory to download the checkpoint to.
global_rank_zero_only (bool): If True,... | download_monolithic_checkpoint | python | mosaicml/composer | composer/checkpoint/download.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/download.py | Apache-2.0 |
def load_checkpoint(
load_path: str,
load_options: Optional[Union[CheckpointLoadOptions, dict]],
model: Optional[Union[ComposerModel, nn.Module]] = None,
optim: Optional[Optimizer] = None,
state: Optional[State] = None,
model_child_path: Optional[str] = None,
optim_child_path: Optional[str] ... | Optionally download and load a checkpoint according to the options into specified state.
Args:
load_path (str): The path or uri to the checkpoint to load or symlink to the path/uri. If URI specified then files will be downloaded first.
load_options (CheckpointLoadOptions): The options for loading t... | load_checkpoint | python | mosaicml/composer | composer/checkpoint/load.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/load.py | Apache-2.0 |
def load_model_checkpoint(
model: Union[ComposerModel, nn.Module],
load_path: Optional[str] = None,
load_options: Optional[Union[CheckpointLoadOptions, dict]] = None,
seed: int = 42,
) -> tuple[list, dict]:
"""Load a a model checkpoint from the specified path into the model.
Args:
model... | Load a a model checkpoint from the specified path into the model.
Args:
model (Union[ComposerModel, nn.Module]): The model to load the checkpoint into.
load_path (Optional[str]): The path to the checkpoint to load.
load_options (Optional[Union[CheckpointLoadOptions, Dict]]): The options for... | load_model_checkpoint | python | mosaicml/composer | composer/checkpoint/load.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/load.py | Apache-2.0 |
def load_optim_checkpoint(
model: Union[ComposerModel, nn.Module],
optim: torch.optim.Optimizer,
load_path: str,
load_options: Optional[Union[CheckpointLoadOptions, dict]] = None,
):
"""Load an optimizer checkpoint from the specified path into the optimizer.
Args:
model (Union[ComposerM... | Load an optimizer checkpoint from the specified path into the optimizer.
Args:
model (Union[ComposerModel, nn.Module]): The model to load the optimizer checkpoint into.
optim (torch.optim.Optimizer): The optimizer to load the checkpoint into.
load_path (Optional[str]): The path to the check... | load_optim_checkpoint | python | mosaicml/composer | composer/checkpoint/load.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/load.py | Apache-2.0 |
def torch_set_model_state_dict(
model: torch.nn.Module,
model_state_dict: dict,
strict: bool,
cpu_offload: bool,
sharded_state_dict: bool = True,
):
"""Set the model state dict with the given options.
Args:
model (torch.nn.Module): The model to set the state dict to.
model_s... | Set the model state dict with the given options.
Args:
model (torch.nn.Module): The model to set the state dict to.
model_state_dict (dict): The model state dict to set.
strict (bool): Whether to set the state dict strictly.
cpu_offload (bool): Whether to offload the state dict to C... | torch_set_model_state_dict | python | mosaicml/composer | composer/checkpoint/load.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/load.py | Apache-2.0 |
def torch_set_optimizer_state_dict(
model: torch.nn.Module,
optim: torch.optim.Optimizer,
optim_state_dict: dict,
strict: bool,
cpu_offload: bool,
sharded_state_dict: bool = True,
):
"""Set the optimizer state dict with the given options.
Args:
model (torch.nn.Module): The model... | Set the optimizer state dict with the given options.
Args:
model (torch.nn.Module): The model to set the state dict to.
optim (torch.optim.Optimizer): The optimizer to set the state dict to.
optim_state_dict (dict): The optimizer state dict to set.
strict (bool): Whether to set the ... | torch_set_optimizer_state_dict | python | mosaicml/composer | composer/checkpoint/load.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/load.py | Apache-2.0 |
def download_and_load_sharded_state_dict(
load_path: str,
device_mesh: Optional[Any],
state_dict: dict,
load_planner: Optional[Any] = None,
):
"""A helper function to download and load a sharded state dict.
Args:
load_path (str): The path to the checkpoint to load.
device_mesh (... | A helper function to download and load a sharded state dict.
Args:
load_path (str): The path to the checkpoint to load.
device_mesh (Optional[Any]): The device mesh to use for loading the checkpoint.
state_dict (dict): The state dict to load.
load_planner (Optional[Any]): The load p... | download_and_load_sharded_state_dict | python | mosaicml/composer | composer/checkpoint/load.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/load.py | Apache-2.0 |
def load_resumption_checkpoint(state: State, load_path: str):
"""Load the resumption state from the specified path into the state.
Args:
state (State): The state to load the resumption state into.
load_path (str): The path to the resumption state to load.
"""
load_path = str(_ensure_va... | Load the resumption state from the specified path into the state.
Args:
state (State): The state to load the resumption state into.
load_path (str): The path to the resumption state to load.
| load_resumption_checkpoint | python | mosaicml/composer | composer/checkpoint/load.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/load.py | Apache-2.0 |
def save_checkpoint_to_disk(
destination_dir: str,
state: State,
options: Optional[Union[CheckpointSaveOptions, dict]] = None,
):
"""Saves a checkpoint to disk.
Args:
state (State): The state to save.
options (Optional[Union[CheckpointSaveOptions, Dict]]): The options for saving the... | Saves a checkpoint to disk.
Args:
state (State): The state to save.
options (Optional[Union[CheckpointSaveOptions, Dict]]): The options for saving the checkpoint.
If None, destination_dir must be provided.
destination_dir (Optional[str]): The directory to save the checkpoint to.... | save_checkpoint_to_disk | python | mosaicml/composer | composer/checkpoint/save.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/save.py | Apache-2.0 |
def save_model_to_disk(
model: Union[ComposerModel, torch.nn.Module],
destination_dir: str,
sharded_checkpoint: bool = False,
precision: str = 'fp32',
include_keys: Optional[Union[str, Sequence[str]]] = None,
ignore_keys: Optional[Union[str, Sequence[str]]] = None,
overwrite: bool = False,
... | Saves a model to disk.
Args:
model (Union[ComposerModel, torch.nn.Module]): The model to save.
destination_dir (str): The directory to save the model to.
Model will be saved as distination_dir/model.pt if sharded_checkpoint is False,
otherwise all shards will be saved as des... | save_model_to_disk | python | mosaicml/composer | composer/checkpoint/save.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/save.py | Apache-2.0 |
def save_optim_to_disk(
model: Union[ComposerModel, torch.nn.Module],
optimizer: torch.optim.Optimizer,
destination_dir: str,
sharded_checkpoint: bool = False,
precision: str = 'fp32',
overwrite: bool = False,
save_format: str = 'pt',
) -> Optional[str]:
"""Saves an optimizer to disk.
... | Saves an optimizer to disk.
Args:
model (Union[ComposerModel, torch.nn.Module]): The model to save.
optimizer (torch.optim.Optimizer): The optimizer to save.
destination_dir (str): The directory to save the optimizer to.
Optimizer will be saved as destination_dir if sharded_chec... | save_optim_to_disk | python | mosaicml/composer | composer/checkpoint/save.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/save.py | Apache-2.0 |
def save_composer_metadata_to_disk(
destination_file_path: str,
model: Optional[Union[ComposerModel, torch.nn.Module]] = None,
sharded_state_dict: Optional[bool] = None,
precision: Optional[Union[str, torch.dtype]] = None,
device: Optional[Device] = None,
device_train_microbatch_size: Optional[U... | Saves metadata about the model to disk.
Args:
destination_file_path (str): The path to save the metadata to.
model (Optional[Union[ComposerModel, torch.nn.Module]]): The model to save metadata about.
sharded_state_dict (Optional[bool]): Whether the model is sharded.
precision (Optio... | save_composer_metadata_to_disk | python | mosaicml/composer | composer/checkpoint/save.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/save.py | Apache-2.0 |
def save_resumption_state_to_disk(
state: State,
destination_file_path: str,
):
"""Saves the resumption state to disk.
Args:
state (State): The state to save.
destination_file_path (str): The path to save the resumption state to.
"""
resumption_state_dict = get_resumption_state_... | Saves the resumption state to disk.
Args:
state (State): The state to save.
destination_file_path (str): The path to save the resumption state to.
| save_resumption_state_to_disk | python | mosaicml/composer | composer/checkpoint/save.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/save.py | Apache-2.0 |
def save_state_dict_to_disk(
state_dict: dict[str, Any],
destination_file_path: str,
overwrite: bool = False,
save_format: str = 'pt', # or hf, safetensor
) -> Optional[str]:
"""Saves a state dict to local disk.
Args:
state_dict (Dict[str,Any]): The state dict to save.
destinat... | Saves a state dict to local disk.
Args:
state_dict (Dict[str,Any]): The state dict to save.
destination_file_path (str): The path to save the state dict to. If sharded,
this should be the pth to a directory. Otherwise, it should be a path to a file.
overwrite (bool): If True, the ... | save_state_dict_to_disk | python | mosaicml/composer | composer/checkpoint/save.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/save.py | Apache-2.0 |
def is_state_dict_sharded(state_dict: dict[str, Any]) -> bool:
"""Determines if the state dict is sharded.
Args:
state_dict (Dict[str, Any]): The state dict to check.
Returns:
bool: Whether the state dict is sharded.
"""
for value in state_dict.values():
if isinstance(value... | Determines if the state dict is sharded.
Args:
state_dict (Dict[str, Any]): The state dict to check.
Returns:
bool: Whether the state dict is sharded.
| is_state_dict_sharded | python | mosaicml/composer | composer/checkpoint/save.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/save.py | Apache-2.0 |
def get_model_state_dict(
model: Union[ComposerModel, nn.Module],
sharded_state_dict: bool = False,
precision: Union[str, torch.dtype] = 'fp32',
include_keys: Optional[Union[str, Sequence[str]]] = None,
ignore_keys: Optional[Union[str, Sequence[str]]] = None,
cpu_offload: Optional[bool] = None,
... | Generate the state dict of the model.
Args:
model: The model to get the state dict from.
sharded_state_dict: Whether the model state dict should be sharded or not. If True, every rank returns the state dict of its shards.
If False, then rank 0 returns the state dict of the entire model ... | get_model_state_dict | python | mosaicml/composer | composer/checkpoint/state_dict.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/state_dict.py | Apache-2.0 |
def _is_model_fsdp(model) -> bool:
"""Indicates if FSDP is enabled.
Args:
model: The model to check if FSDP is enabled.
Returns:
True if FSDP is enabled, False otherwise.
"""
for module in model.modules():
if isinstance(module, FSDP):
return True
return Fal... | Indicates if FSDP is enabled.
Args:
model: The model to check if FSDP is enabled.
Returns:
True if FSDP is enabled, False otherwise.
| _is_model_fsdp | python | mosaicml/composer | composer/checkpoint/state_dict.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/state_dict.py | Apache-2.0 |
def _get_model_state_dict_with_fsdp_context_manager(model: nn.Module, sharded_state_dict: bool,
cpu_offload: bool) -> dict[str, Any]:
"""Get the model state dict with the FSDP context manager.
Args:
model: The model to get the state dict from.
... | Get the model state dict with the FSDP context manager.
Args:
model: The model to get the state dict from.
sharded: Whether the model state dict should be sharded or not. If True, every rank returns the state dict of its shards.
If False, then rank 0 returns the state dict of the entire... | _get_model_state_dict_with_fsdp_context_manager | python | mosaicml/composer | composer/checkpoint/state_dict.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/state_dict.py | Apache-2.0 |
def get_resumption_state_dict(state: State) -> dict[str, Any]:
"""Generate the state dict for any objects needed for resumption.
This includes:
* timestamp
* scheduler
* dataset_state
* scaler
* rank_zero_seed
* callbacks
* algorithms
Returns:
... | Generate the state dict for any objects needed for resumption.
This includes:
* timestamp
* scheduler
* dataset_state
* scaler
* rank_zero_seed
* callbacks
* algorithms
Returns:
The state dict containing the objects needed for resumption.
| get_resumption_state_dict | python | mosaicml/composer | composer/checkpoint/state_dict.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/state_dict.py | Apache-2.0 |
def get_dataset_state_dict(
train_dataloader: Optional[Union[DataLoader, Iterable]],
timestamp: Timestamp,
) -> dict[str, Any]:
"""Collect the state dict(s) of our train and eval dataset(s).
Returns:
Dict[str, Any]: The state dict(s).
"""
dataset_state_dict = {
'train': None,
... | Collect the state dict(s) of our train and eval dataset(s).
Returns:
Dict[str, Any]: The state dict(s).
| get_dataset_state_dict | python | mosaicml/composer | composer/checkpoint/state_dict.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/state_dict.py | Apache-2.0 |
def _get_optim_state_dict_with_fsdp_context_manager(
model: nn.Module,
optimizer: torch.optim.Optimizer,
sharded_state_dict: bool,
cpu_offload: bool,
) -> dict[str, Any]:
"""Get the optimizer state dict with the FSDP context manager.
Args:
model: The model containing the parameters that... | Get the optimizer state dict with the FSDP context manager.
Args:
model: The model containing the parameters that the optimizer is optimizing.
optimizer: The optimizer to get the state dict from.
sharded_state_dict: Whether the optimizer state dict should be sharded or not. If True, every r... | _get_optim_state_dict_with_fsdp_context_manager | python | mosaicml/composer | composer/checkpoint/state_dict.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/state_dict.py | Apache-2.0 |
def get_optim_state_dict(
model: Union[ComposerModel, nn.Module],
optimizer: torch.optim.Optimizer,
sharded_state_dict: bool = False,
precision: str = 'fp32',
include_keys: Optional[Union[str, Sequence[str]]] = None,
ignore_keys: Optional[Union[str, Sequence[str]]] = None,
cpu_offload: Optio... | Generate the state dict of the optimizer.
Args:
model: The model containing the parameters that the optimizer is optimizing.
optimizer: The optimizer to get the state dict from.
sharded: Whether the optimizer is sharded or not. If True, every rank returns the state dict of its shards.
... | get_optim_state_dict | python | mosaicml/composer | composer/checkpoint/state_dict.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/state_dict.py | Apache-2.0 |
def _dataset_of(dataloader: Optional[Union[Evaluator, DataSpec, DataLoader, Iterable]]) -> Optional[Dataset]:
"""Get the dataset contained by the given dataloader-like object.
Args:
dataloader (Evaluator | DataSpec | DataLoader | Iterable, optional): The dataloader, wrapped dataloader, or
g... | Get the dataset contained by the given dataloader-like object.
Args:
dataloader (Evaluator | DataSpec | DataLoader | Iterable, optional): The dataloader, wrapped dataloader, or
generic python iterable to get the dataset of, if applicable.
Returns:
Dataset: Its dataset, if there is ... | _dataset_of | python | mosaicml/composer | composer/checkpoint/state_dict.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/state_dict.py | Apache-2.0 |
def upload_file(
dest_dir: str,
source_path: Optional[str]=None,
symlink_granularity: Optional[str]=None, # file, dir, or None
symlink_name: Optional[str]='latest.symlink',
async_upload: bool = True,
state: Optional[State] = None,
overwrite: bool = False,
):
"""Standalone function for up... | Standalone function for uploading a checkpoint file.
This function does not actually upload the checkpoint; it initiates the RemoteUploader's uploading of it
Args:
source_path (str): The path to the file to upload.
dest_dir (str): The directory/uri to upload the file to.
symlink_granula... | upload_file | python | mosaicml/composer | composer/checkpoint/upload.py | https://github.com/mosaicml/composer/blob/master/composer/checkpoint/upload.py | Apache-2.0 |
def _patch_env(**environs: str):
"""Returns a context manager that patches ``os.environ`` with ``environs``.
The original ``os.environ`` values are restored at the end.
"""
# Adapted loosely from https://stackoverflow.com/a/34333710
# Capture the original environ values
original_environs = {k: ... | Returns a context manager that patches ``os.environ`` with ``environs``.
The original ``os.environ`` values are restored at the end.
| _patch_env | python | mosaicml/composer | composer/cli/launcher.py | https://github.com/mosaicml/composer/blob/master/composer/cli/launcher.py | Apache-2.0 |
def run_event(self, event: Event, state: State, logger: Logger) -> None:
"""Called by the engine on each event.
Args:
event (Event): The event.
state (State): The state.
logger (Logger): The logger.
"""
event_cb = getattr(self, event.value)
re... | Called by the engine on each event.
Args:
event (Event): The event.
state (State): The state.
logger (Logger): The logger.
| run_event | python | mosaicml/composer | composer/core/callback.py | https://github.com/mosaicml/composer/blob/master/composer/core/callback.py | Apache-2.0 |
def _default_split_batch(batch: Any, microbatch_size: Union[int, float]) -> Sequence:
"""Splits batch into chunks of size `microbatch_size` for gradient accumulation.
Works with tensors, dictionaries of tensors, (x, y) tuples, and lists where ``batch`` is the 2nd dimension.
Args:
batch (Any): outp... | Splits batch into chunks of size `microbatch_size` for gradient accumulation.
Works with tensors, dictionaries of tensors, (x, y) tuples, and lists where ``batch`` is the 2nd dimension.
Args:
batch (Any): output from the dataloader.
microbatch_size (int | float): Size of microbatches to batch ... | _default_split_batch | python | mosaicml/composer | composer/core/data_spec.py | https://github.com/mosaicml/composer/blob/master/composer/core/data_spec.py | Apache-2.0 |
def ensure_data_spec(dataloader: Union[DataSpec, Iterable, dict]) -> DataSpec:
"""Ensures that the ``dataloader`` is a :class:`.DataSpec`.
Args:
dataloader (DataSpec | Iterable | dict): A DataSpec, DataLoader, or dict of DataSpec kwargs.
Returns:
DataSpec: A DataSpec
"""
if isinsta... | Ensures that the ``dataloader`` is a :class:`.DataSpec`.
Args:
dataloader (DataSpec | Iterable | dict): A DataSpec, DataLoader, or dict of DataSpec kwargs.
Returns:
DataSpec: A DataSpec
| ensure_data_spec | python | mosaicml/composer | composer/core/data_spec.py | https://github.com/mosaicml/composer/blob/master/composer/core/data_spec.py | Apache-2.0 |
def run_event(
self,
event: Union[Event, str],
) -> Traces:
"""Runs the sequence of algorithms and callbacks (see :class:`.Callback`).
Filters algorithms by calling each one's :meth:`.Algorithm.match` method, internally checks for conflicting
algorithms, then runs each algor... | Runs the sequence of algorithms and callbacks (see :class:`.Callback`).
Filters algorithms by calling each one's :meth:`.Algorithm.match` method, internally checks for conflicting
algorithms, then runs each algorithm's :meth:`.Algorithm.apply` method to make in-place changes to the
``state``.
... | run_event | python | mosaicml/composer | composer/core/engine.py | https://github.com/mosaicml/composer/blob/master/composer/core/engine.py | Apache-2.0 |
def run_marker_only_event(
self,
event: Union[Event, str],
) -> None:
"""Runs the marker for an event if the profiler is enabled.
This is primarily used to complete the dataloader marker at the end of the dataloader. In
this scenario, the dataloader marker has started from E... | Runs the marker for an event if the profiler is enabled.
This is primarily used to complete the dataloader marker at the end of the dataloader. In
this scenario, the dataloader marker has started from Event.BEFORE_DATALOADER, but
Event.AFTER_DATALOADER cannot be called as no batch was yielded f... | run_marker_only_event | python | mosaicml/composer | composer/core/engine.py | https://github.com/mosaicml/composer/blob/master/composer/core/engine.py | Apache-2.0 |
def register_pass(self, algorithm_pass: passes.AlgorithmPass, index: int = -1):
"""Registers an algorithm pass with the Engine.
Args:
algorithm_pass (passes.AlgorithmPass): A method that maps a list of
algorithms to a list of algorithms.
index (int, optional): Th... | Registers an algorithm pass with the Engine.
Args:
algorithm_pass (passes.AlgorithmPass): A method that maps a list of
algorithms to a list of algorithms.
index (int, optional): The index to insert into the list of passes.
If -1 (default), the pass will b... | register_pass | python | mosaicml/composer | composer/core/engine.py | https://github.com/mosaicml/composer/blob/master/composer/core/engine.py | Apache-2.0 |
def _compile(
self,
algorithms_to_run: Sequence[Algorithm],
event: Event,
) -> Sequence[Algorithm]:
"""Runs compilation passes that modify the order and content of a list of algorithms.
Currently, runs the algorithms in a FILO queue for the ``before_`` and ``after_`` events.... | Runs compilation passes that modify the order and content of a list of algorithms.
Currently, runs the algorithms in a FILO queue for the ``before_`` and ``after_`` events. For example,
algorithms will run in order ABCD during ``before_loss``, and in DCBA during ``after_loss``. The motivation
h... | _compile | python | mosaicml/composer | composer/core/engine.py | https://github.com/mosaicml/composer/blob/master/composer/core/engine.py | Apache-2.0 |
def _run_callbacks(
self,
event: Union[Event, str],
callbacks: Optional[Sequence[Callback]] = None,
):
"""Runs a sequence of callbacks by calling the function for an event.
Args:
event (Event | str): The current :class:`.Event`.
callbacks (Callback | ... | Runs a sequence of callbacks by calling the function for an event.
Args:
event (Event | str): The current :class:`.Event`.
callbacks (Callback | Sequence[Callback], optional): The callbacks to run.
If None is specified, will use all the callback in state (self.state).
... | _run_callbacks | python | mosaicml/composer | composer/core/engine.py | https://github.com/mosaicml/composer/blob/master/composer/core/engine.py | Apache-2.0 |
def _debug_log(self, event: Event, msg: str):
"""Helper to include timestamp and event info in log messages."""
timestamp = f'[ep={int(self.state.timestamp.epoch)}][ba={int(self.state.timestamp.batch)}]'
# for eval or pr
if event.is_eval:
timestamp += f'[eval_ba={int(self.st... | Helper to include timestamp and event info in log messages. | _debug_log | python | mosaicml/composer | composer/core/engine.py | https://github.com/mosaicml/composer/blob/master/composer/core/engine.py | Apache-2.0 |
def close(self) -> None:
"""Shutdown the engine.
As part of the shutdown procedure, :meth:`.Callback.close` and :meth:`.Callback.post_close` are invoked
for each callback. Note that :meth:`.Callback.post_close` is invoked only for callbacks that did not raise
an exception during :meth:`... | Shutdown the engine.
As part of the shutdown procedure, :meth:`.Callback.close` and :meth:`.Callback.post_close` are invoked
for each callback. Note that :meth:`.Callback.post_close` is invoked only for callbacks that did not raise
an exception during :meth:`.Callback.close`.
This meth... | close | python | mosaicml/composer | composer/core/engine.py | https://github.com/mosaicml/composer/blob/master/composer/core/engine.py | Apache-2.0 |
def _close(state: State, logger: Logger):
"""The actual shutdown logic, as a static method, so the underlying engine can still be garbage collected."""
log.debug('Closing the engine.')
callback_to_has_exception: dict[Callback, bool] = {}
for callback in state.callbacks:
try:
... | The actual shutdown logic, as a static method, so the underlying engine can still be garbage collected. | _close | python | mosaicml/composer | composer/core/engine.py | https://github.com/mosaicml/composer/blob/master/composer/core/engine.py | Apache-2.0 |
def ensure_evaluator(evaluator: Union[Evaluator, DataSpec, Iterable, dict[str, Any]], default_metric_names: list[str]):
"""Ensure that ``evaluator`` is an :class:`.Evaluator`.
Args:
evaluator (Evaluator | DataSpec | Iterable | dict[str, Any]): A dataloader,
:class:`.DataSpec` instance, dict... | Ensure that ``evaluator`` is an :class:`.Evaluator`.
Args:
evaluator (Evaluator | DataSpec | Iterable | dict[str, Any]): A dataloader,
:class:`.DataSpec` instance, dictionary of :class:`.DataSpec` kwargs, or existing evaluator.
default_metric_names (list[str]): The names of the metrics ... | ensure_evaluator | python | mosaicml/composer | composer/core/evaluator.py | https://github.com/mosaicml/composer/blob/master/composer/core/evaluator.py | Apache-2.0 |
def _get_initial_device_eval_microbatch_size(
device_eval_microbatch_size: Optional[Union[int, str, float]],
auto_microbatching: bool,
dataloader: Iterable,
) -> Union[int, float]:
"""Sets initial value of device_eval_microbatch_size.
If auto_microbatching, sets initial `device_eval_microbatch_size... | Sets initial value of device_eval_microbatch_size.
If auto_microbatching, sets initial `device_eval_microbatch_size` to per rank batch size.
| _get_initial_device_eval_microbatch_size | python | mosaicml/composer | composer/core/evaluator.py | https://github.com/mosaicml/composer/blob/master/composer/core/evaluator.py | Apache-2.0 |
def canonical_name(self) -> str:
"""The name of the event, without before/after markers.
Events that have a corresponding "before" or "after" event share the same canonical name.
Example:
>>> Event.EPOCH_START.canonical_name
'epoch'
>>> Event.EPOCH_END.canon... | The name of the event, without before/after markers.
Events that have a corresponding "before" or "after" event share the same canonical name.
Example:
>>> Event.EPOCH_START.canonical_name
'epoch'
>>> Event.EPOCH_END.canonical_name
'epoch'
Retur... | canonical_name | python | mosaicml/composer | composer/core/event.py | https://github.com/mosaicml/composer/blob/master/composer/core/event.py | Apache-2.0 |
def sort_selective_backprop_first(algorithms: Sequence[Algorithm], event: Event) -> Sequence[Algorithm]:
"""Selective Backprop should run before any algorithms modify the loss.
:class:`.SelectiveBackprop` runs after the dataloader returns the batch and executes an extra forward pass to rank
and prune the e... | Selective Backprop should run before any algorithms modify the loss.
:class:`.SelectiveBackprop` runs after the dataloader returns the batch and executes an extra forward pass to rank
and prune the examples in the batch by loss. To ensure a clean estimate of loss, :class:`.SelectiveBackprop` should
run bef... | sort_selective_backprop_first | python | mosaicml/composer | composer/core/passes.py | https://github.com/mosaicml/composer/blob/master/composer/core/passes.py | Apache-2.0 |
def sort_low_precision_layernorm_last(
algorithms: Sequence[Algorithm],
event: Event,
) -> Sequence[Algorithm]: #noqa: D403
"""LowPrecisionLayerNorm should run after other algorithms that add LayerNorms (e.g. GatedLinearUnits).
This ensures that all LayerNorms are converted to the intended precision.
... | LowPrecisionLayerNorm should run after other algorithms that add LayerNorms (e.g. GatedLinearUnits).
This ensures that all LayerNorms are converted to the intended precision.
| sort_low_precision_layernorm_last | python | mosaicml/composer | composer/core/passes.py | https://github.com/mosaicml/composer/blob/master/composer/core/passes.py | Apache-2.0 |
def set_filo_order(algorithms: Sequence[Algorithm], event: Event) -> Sequence[Algorithm]:
"""Establish a FILO order of algorithms ``before_`` and ``after_`` events.
For the events that follow the ``before_*`` and ``after_*`` pattern (e.g., :attr:`.Event.BEFORE_LOSS`
and :attr:`.Event.AFTER_LOSS), the order... | Establish a FILO order of algorithms ``before_`` and ``after_`` events.
For the events that follow the ``before_*`` and ``after_*`` pattern (e.g., :attr:`.Event.BEFORE_LOSS`
and :attr:`.Event.AFTER_LOSS), the ordering of algorithms is reversed for the ``after_*`` events.
For example, four given algorithms ... | set_filo_order | python | mosaicml/composer | composer/core/passes.py | https://github.com/mosaicml/composer/blob/master/composer/core/passes.py | Apache-2.0 |
def warn_if_multiple_loss_interpolation(algorithms: Sequence[Algorithm], event: Event) -> Sequence[Algorithm]:
"""Multiple algorithms that interpolate the loss may have unexpected behavior."""
from composer.algorithms.warnings import NotIntendedUseWarning
is_interpolate = [a for a in algorithms if hasattr(... | Multiple algorithms that interpolate the loss may have unexpected behavior. | warn_if_multiple_loss_interpolation | python | mosaicml/composer | composer/core/passes.py | https://github.com/mosaicml/composer/blob/master/composer/core/passes.py | Apache-2.0 |
def _validate_precision(precision: Precision, device: Device):
"""Validate the precision and device combination."""
if isinstance(device, DeviceCPU) and precision != Precision.FP32:
raise ValueError(f'{precision} is not supported for CPU training.') | Validate the precision and device combination. | _validate_precision | python | mosaicml/composer | composer/core/precision.py | https://github.com/mosaicml/composer/blob/master/composer/core/precision.py | Apache-2.0 |
def get_precision_context(
precision: Union[str, Precision],
precision_config: Optional[dict[str, Any]] = None,
fp8_autocast_enabled: bool = True,
) -> Generator[None, None, None]:
"""Returns a context manager to automatically cast to a specific precision.
Args:
precision (str | Precision):... | Returns a context manager to automatically cast to a specific precision.
Args:
precision (str | Precision): Precision for the context
precision_config (Optional[dict[str, Any]]): Config for FP8 scaling strategy. See parameters for
`DelayedScaling <https://docs.nvidia.com/deeplearning/tr... | get_precision_context | python | mosaicml/composer | composer/core/precision.py | https://github.com/mosaicml/composer/blob/master/composer/core/precision.py | Apache-2.0 |
def fsdp_state_dict_type_context(module: torch.nn.Module, state_dict_type: str = 'full'):
"""Context manager for materializing or loading an fsdp module's state dict.
Args:
module (torch.nn.Module): The torch module that you want to call `state_dict()`
or `load_state_dict()` on.
sta... | Context manager for materializing or loading an fsdp module's state dict.
Args:
module (torch.nn.Module): The torch module that you want to call `state_dict()`
or `load_state_dict()` on.
state_dict_type (str, optional): which of the three state dict types you want to use.
ch... | fsdp_state_dict_type_context | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def _dataset_of(self, dataloader: Optional[Union[Evaluator, DataSpec, DataLoader, Iterable]]) -> Optional[Dataset]:
"""Get the dataset contained by the given dataloader-like object.
Args:
dataloader (Evaluator | DataSpec | DataLoader | Iterable, optional): The dataloader, wrapped dataloader... | Get the dataset contained by the given dataloader-like object.
Args:
dataloader (Evaluator | DataSpec | DataLoader | Iterable, optional): The dataloader, wrapped dataloader, or
generic python iterable to get the dataset of, if applicable.
Returns:
Dataset: Its d... | _dataset_of | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def train_dataloader(self, train_dataloader: Optional[Union[Iterable, DataLoader]]):
"""Set the train dataloader.
Args:
train_dataloader (Iterable | DataLoader, optional): The dataloader.
"""
self._train_dataloader = train_dataloader
# Load dataset state from checkpo... | Set the train dataloader.
Args:
train_dataloader (Iterable | DataLoader, optional): The dataloader.
| train_dataloader | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def get_elapsed_duration(self) -> Optional[Time[float]]:
"""Get the elapsed training duration.
Returns:
Optional[Time[float]]: The elapsed duration, in :attr:`TimeUnit.DURATION`.
``Time(0.0, TimeUnit.DURATION)`` represents the beginning of training and ``Time(1.0, TimeUnit.D... | Get the elapsed training duration.
Returns:
Optional[Time[float]]: The elapsed duration, in :attr:`TimeUnit.DURATION`.
``Time(0.0, TimeUnit.DURATION)`` represents the beginning of training and ``Time(1.0, TimeUnit.DURATION)``
represents a completed training process. ... | get_elapsed_duration | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def _iteration_length(self, iteration_length: Optional[Union[str, Time[int]]]):
"""Sets the length of an iteration.
An iteration must be defined as multiple epochs or tokens. See composer/core/event.py.
"""
if iteration_length is None:
self.__iteration_length = None
... | Sets the length of an iteration.
An iteration must be defined as multiple epochs or tokens. See composer/core/event.py.
| _iteration_length | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def stop_training(self):
"""Gracefully stop training.
The current batch of training will finish, and any scheduled evaluation,
logging, and evaluation for that batch, as well as any epoch end events.
"""
# Set the max_duration to the current time in its unit, except if the unit ... | Gracefully stop training.
The current batch of training will finish, and any scheduled evaluation,
logging, and evaluation for that batch, as well as any epoch end events.
| stop_training | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def fsdp_config(self, value: FSDPConfig | FSDP2Config):
"""Sets the FSDP configuration, handling both FSDP1 and FSDP2 configurations."""
if isinstance(value, FSDPConfig):
self._fsdp_config = value
self._fsdp2_config = None
elif isinstance(value, FSDP2Config):
... | Sets the FSDP configuration, handling both FSDP1 and FSDP2 configurations. | fsdp_config | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def fsdp_config_version(self) -> int:
"""Return the version of the FSDP config.
Version 0 means DDP.
Version 1 means using torch's FullyShardedDataParallel.
Version 2 means using torch's fully_shard and Dtensor.
Returns:
int: The version of the FSDP config.
... | Return the version of the FSDP config.
Version 0 means DDP.
Version 1 means using torch's FullyShardedDataParallel.
Version 2 means using torch's fully_shard and Dtensor.
Returns:
int: The version of the FSDP config.
| fsdp_config_version | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def _get_integrations_state_dict(self) -> dict[str, Any]:
"""Gets a dictionary of information about integrations to store in the state dict.
This metadata is used for loading things from state dict that need to be done outside
of the normal Composer load path (e.g. HuggingFace model/tokenizer).... | Gets a dictionary of information about integrations to store in the state dict.
This metadata is used for loading things from state dict that need to be done outside
of the normal Composer load path (e.g. HuggingFace model/tokenizer).
| _get_integrations_state_dict | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def _get_state_metadata(self) -> dict[str, Any]:
"""Gets a dictionary of metadata to store in the state dict.
This metadata is used for checking compatibility between the current environment/setup
and the environment/setup that was used for the checkpoint that is being loaded in
"""
... | Gets a dictionary of metadata to store in the state dict.
This metadata is used for checking compatibility between the current environment/setup
and the environment/setup that was used for the checkpoint that is being loaded in
| _get_state_metadata | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def _dataset_state_dict(self) -> dict[str, Any]:
"""Collect the state dict(s) of our train and eval dataset(s).
Returns:
dict[str, Any]: The state dict(s).
"""
obj = {
'train': None,
'eval': {},
}
dataset = self._dataset_of(self.train... | Collect the state dict(s) of our train and eval dataset(s).
Returns:
dict[str, Any]: The state dict(s).
| _dataset_state_dict | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def get_model_state_dict(self) -> dict[str, Any]:
"""Collect the state dict for the model.
Returns:
dict[str, Any]: The state dict for the model.
"""
if self.fsdp_state_dict_type not in [None, 'full', 'sharded']:
raise NotImplementedError(
textwra... | Collect the state dict for the model.
Returns:
dict[str, Any]: The state dict for the model.
| get_model_state_dict | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def get_optim_state_dict(self) -> dict[str, Any]:
"""Collect the state dict for the optimizer.
Returns:
dict[str, Any]: The state dict for the optimizer.
"""
if self.fsdp_state_dict_type not in [None, 'full', 'sharded']:
raise NotImplementedError(
... | Collect the state dict for the optimizer.
Returns:
dict[str, Any]: The state dict for the optimizer.
| get_optim_state_dict | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def state_dict(self) -> dict[str, Any]:
"""Collect the state dicts of our serializable attributes.
Returns:
dict[str, Any]: The state dict.
"""
state_dict = {}
for attribute_name in self.serialized_attributes:
attribute_value = getattr(self, attribute_nam... | Collect the state dicts of our serializable attributes.
Returns:
dict[str, Any]: The state dict.
| state_dict | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def _apply_required_algorithms(
self,
state_dict: dict[str, Any],
logger: Logger,
exclude_algorithms: Optional[list[str]] = None,
algorithm_passes: Optional[list[AlgorithmPass]] = None,
):
"""Applies required algorithms which haven't been specified and aren't in the e... | Applies required algorithms which haven't been specified and aren't in the exclude list.
Args:
state_dict (dict[str, Any]): State from checkpoint.
logger (Logger): Logger to use.
exclude_algorithms (list[str], optional): list of algorithm names to exclude. (default: ``None``... | _apply_required_algorithms | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def _legacy_load_optim_state(self, state_dict: dict[str, Any]):
"""Load the optimizer state.
Args:
state_dict (dict[str, Any]): The state to load.
"""
serialized_value = state_dict['optimizers']
for optimizer in ensure_tuple(self.optimizers):
# Broadcast ... | Load the optimizer state.
Args:
state_dict (dict[str, Any]): The state to load.
| _legacy_load_optim_state | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def _load_dataset_state(self, obj: dict[str, Any]) -> None:
"""Load the dataset state.
Args:
obj (dict[str, Any]): The state to load.
"""
dataset = self._dataset_of(self.train_dataloader)
if hasattr(dataset, 'load_state_dict'):
dataset.load_state_dict(obj... | Load the dataset state.
Args:
obj (dict[str, Any]): The state to load.
| _load_dataset_state | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def load_model_state(
self,
state_dict: dict[str, Any],
logger: Logger,
strict: bool,
exclude_algorithms: Optional[list[str]] = None,
algorithm_passes: Optional[list[AlgorithmPass]] = None,
):
"""Loads the model's state from a ``state_dict``.
Args:
... | Loads the model's state from a ``state_dict``.
Args:
state_dict (dict[str, Any]): The state dict, generated from a previous call to :meth:`state_dict`.
logger (Logger): The logger.
strict (bool): Whether the keys (i.e., model parameter names) in the model state dict should
... | load_model_state | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def load_optim_state(self, state_dict: dict[str, Any], strict: bool = True):
"""Load the optimizer state.
Args:
state_dict (dict[str, Any]): The state to load.
strict (bool): Whether the keys (i.e., optimizer parameter names) in the optimizer
state dict should pe... | Load the optimizer state.
Args:
state_dict (dict[str, Any]): The state to load.
strict (bool): Whether the keys (i.e., optimizer parameter names) in the optimizer
state dict should perfectly match the keys in the optimizer instance.
| load_optim_state | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def load_state_dict(
self,
state: dict[str, Any],
logger: Logger,
strict: bool = False,
exclude_algorithms: Optional[list[str]] = None,
algorithm_passes: Optional[list[AlgorithmPass]] = None,
):
"""Loads the state.
Args:
state (dict[str, A... | Loads the state.
Args:
state (dict[str, Any]): object returned from call to :meth:`state_dict`.
logger (Logger): The logger.
strict (bool): whether the keys in the ``state["model"]`` should perfectly match the keys in the
``self.model``. Defaults to False.
... | load_state_dict | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def set_dataloader(
self,
dataloader: Optional[Iterable] = None,
dataloader_label: Optional[str] = None,
dataloader_len: Union[int, Time[int]] = -1,
):
"""Update the active dataloader and dataloader label.
Args:
dataloader (Iterable, optional): The datalo... | Update the active dataloader and dataloader label.
Args:
dataloader (Iterable, optional): The dataloader. Defaults to None.
dataloader_label (str, optional): The dataloader label. Must be ``None`` if and only if
``dataloader`` is None. Defaults to None.
datal... | set_dataloader | python | mosaicml/composer | composer/core/state.py | https://github.com/mosaicml/composer/blob/master/composer/core/state.py | Apache-2.0 |
def verify_wct(timestamp: str) -> str:
"""Return a valid datetime formated wct timestamp if input is a valid wct.
Args:
timestamp (str): A string that represents a timestamp in wct.
Returns:
str: a properly formatted datetime if input is valid else None
"""
if 'h' not in timestamp:... | Return a valid datetime formated wct timestamp if input is a valid wct.
Args:
timestamp (str): A string that represents a timestamp in wct.
Returns:
str: a properly formatted datetime if input is valid else None
| verify_wct | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def from_timedelta(cls, timestring: str) -> Time:
"""Create a :class:`Time` with units of :attr:`TimeUnit.SECOND`.
Equivalent to ``Time(batch, TimeUnit.SECOND)``.
Args:
timestring (int): timedelta string in _h_m_s.
Returns:
Time: :class:`Time` instance, in seco... | Create a :class:`Time` with units of :attr:`TimeUnit.SECOND`.
Equivalent to ``Time(batch, TimeUnit.SECOND)``.
Args:
timestring (int): timedelta string in _h_m_s.
Returns:
Time: :class:`Time` instance, in seconds.
| from_timedelta | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def from_input(
cls,
i: Union[str, int, float, 'Time'],
default_int_unit: Optional[Union[TimeUnit, str]] = None,
) -> Time:
"""Parse a time input into a :class:`Time` instance.
Args:
i (str | int | Time): The time input.
default_int_unit (TimeUnit, op... | Parse a time input into a :class:`Time` instance.
Args:
i (str | int | Time): The time input.
default_int_unit (TimeUnit, optional): The default unit to use if ``i`` is an integer
>>> Time.from_input("5ep")
Time(5, TimeUnit.EPOCH)
>>> Time.from_input(5, TimeUnit... | from_input | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def from_timestring(cls, timestring: str) -> Time:
"""Parse a time string into a :class:`Time` instance.
A time string is a numerical value followed by the value of a :class:`TimeUnit` enum. For example:
>>> Time.from_timestring("5ep") # describes 5 epochs.
Time(5, TimeUnit.EPOCH)
... | Parse a time string into a :class:`Time` instance.
A time string is a numerical value followed by the value of a :class:`TimeUnit` enum. For example:
>>> Time.from_timestring("5ep") # describes 5 epochs.
Time(5, TimeUnit.EPOCH)
>>> Time.from_timestring("3e4tok") # describes 30,000 to... | from_timestring | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def epoch_in_iteration(
self,
epoch_in_iteration: Union[int, Time[int]], # pyright: ignore[reportPropertyTypeMismatch]
):
"""Sets epoch count in the current iteration."""
epoch_in_iteration = Time.from_input(epoch_in_iteration, TimeUnit.EPOCH)
if epoch_in_iteration.unit != T... | Sets epoch count in the current iteration. | epoch_in_iteration | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def get(self, unit: Union[str, TimeUnit]) -> Time[int]:
"""Returns the current time in the specified unit.
Args:
unit (str | TimeUnit): The desired unit.
Returns:
Time: The current time, in the specified unit.
"""
unit = TimeUnit(unit)
if unit ==... | Returns the current time in the specified unit.
Args:
unit (str | TimeUnit): The desired unit.
Returns:
Time: The current time, in the specified unit.
| get | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def to_next_batch(
self,
samples: Union[int, Time] = 0,
tokens: Union[int, Time] = 0,
duration: Optional[datetime.timedelta] = None,
):
"""Create a new :class:`.Timestamp`, advanced to the next batch.
Equivalent to:
.. testsetup::
from composer.... | Create a new :class:`.Timestamp`, advanced to the next batch.
Equivalent to:
.. testsetup::
from composer.core.time import Timestamp
import datetime
timestamp = Timestamp()
samples = 1
tokens = 2
duration = datetime.timedelta(se... | to_next_batch | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def to_next_epoch(
self,
duration: Optional[datetime.timedelta] = None,
):
"""Create a new :class:`.Timestamp`, advanced to the next epoch.
Equivalent to:
.. testsetup::
from composer.core.time import Timestamp
import datetime
timestamp... | Create a new :class:`.Timestamp`, advanced to the next epoch.
Equivalent to:
.. testsetup::
from composer.core.time import Timestamp
import datetime
timestamp = Timestamp()
duration = datetime.timedelta(seconds=0)
.. doctest::
>>>... | to_next_epoch | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def to_next_iteration(
self,
duration: Optional[datetime.timedelta] = None,
):
"""Create a new :class:`.Timestamp`, advanced to the next iteration.
Equivalent to:
.. testsetup::
from composer.core.time import Timestamp
import datetime
t... | Create a new :class:`.Timestamp`, advanced to the next iteration.
Equivalent to:
.. testsetup::
from composer.core.time import Timestamp
import datetime
timestamp = Timestamp()
.. doctest::
>>> timestamp.copy(
... iteration=ti... | to_next_iteration | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def copy(
self,
iteration: Optional[Union[int, Time[int]]] = None,
epoch: Optional[Union[int, Time[int]]] = None,
batch: Optional[Union[int, Time[int]]] = None,
sample: Optional[Union[int, Time[int]]] = None,
token: Optional[Union[int, Time[int]]] = None,
epoch_in... | Create a copy of the timestamp.
Any specified values will override the existing values in the returned copy.
Args:
iteration (int | Time[int], optional): The iteration.
epoch (int | Time[int], optional): The epoch.
batch (int | Time[int], optional): the batch.
... | copy | python | mosaicml/composer | composer/core/time.py | https://github.com/mosaicml/composer/blob/master/composer/core/time.py | Apache-2.0 |
def batch_to_device(self, batch: T_Batch) -> T_Batch:
"""Invoked by the :class:`.Trainer` move all tensors items in a batch to device.
Supports nested sequences and mappings of tensors. Ignores non-tensor items. Preserves sequence and mapping types
when possible; otherwise, sequences are conver... | Invoked by the :class:`.Trainer` move all tensors items in a batch to device.
Supports nested sequences and mappings of tensors. Ignores non-tensor items. Preserves sequence and mapping types
when possible; otherwise, sequences are converted to lists, and mappings are converted to dictionaries.
... | batch_to_device | python | mosaicml/composer | composer/devices/device.py | https://github.com/mosaicml/composer/blob/master/composer/devices/device.py | Apache-2.0 |
def optimizer_to_device(self, optimizer: Optimizer) -> Optimizer:
"""Invoked by the :class:`.Trainer` to move the optimizer's state onto the device.
Args:
optimizer (Optimizer): The optimizer to move to the device
Returns:
Optimizer: The optimizer on the device
... | Invoked by the :class:`.Trainer` to move the optimizer's state onto the device.
Args:
optimizer (Optimizer): The optimizer to move to the device
Returns:
Optimizer: The optimizer on the device
| optimizer_to_device | python | mosaicml/composer | composer/devices/device.py | https://github.com/mosaicml/composer/blob/master/composer/devices/device.py | Apache-2.0 |
def _map_batch(batch: Any, map_fn: Callable) -> Any:
"""Recursively maps a function to all items in a batch.
Args:
batch: Nested lists and dictionaries.
map_fn: A function to invoke on each element.
Returns:
Collections: The result of applying ``map_fn`` on each element of the ``ba... | Recursively maps a function to all items in a batch.
Args:
batch: Nested lists and dictionaries.
map_fn: A function to invoke on each element.
Returns:
Collections: The result of applying ``map_fn`` on each element of the ``batch``.
The type of ``batch`` is preserved.
| _map_batch | python | mosaicml/composer | composer/devices/device.py | https://github.com/mosaicml/composer/blob/master/composer/devices/device.py | Apache-2.0 |
def generate_default_check_fn(model: nn.Module) -> Callable:
"""Generates the default check fn for activation checkpointing/offloading."""
def _check_fn(module: torch.nn.Module) -> bool:
if hasattr(module, '_activation_checkpointing'):
return bool(module._activation_checkpointing)
#... | Generates the default check fn for activation checkpointing/offloading. | generate_default_check_fn | python | mosaicml/composer | composer/distributed/activation_checkpointing.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/activation_checkpointing.py | Apache-2.0 |
def generate_composer_model_check_fn(composer_model: nn.Module) -> Callable:
"""Generates a check function for activation checkpointing/offloading that is compatible with ComposerModel.
This function creates a mapping for each module in the ComposerModel, determining whether
its activations should be check... | Generates a check function for activation checkpointing/offloading that is compatible with ComposerModel.
This function creates a mapping for each module in the ComposerModel, determining whether
its activations should be checkpointed or offloaded. It follows a hierarchical approach:
1. The ComposerModel ... | generate_composer_model_check_fn | python | mosaicml/composer | composer/distributed/activation_checkpointing.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/activation_checkpointing.py | Apache-2.0 |
def apply_ac(
model: nn.Module,
activation_checkpointing: bool,
activation_cpu_offload: bool,
check_fn: Optional[Callable] = None,
) -> None:
"""Apply activation checkpointing to the model. This is orthogonal to FSDP2 so it can be applied pre-sharding or post-sharding.
This method follows the s... | Apply activation checkpointing to the model. This is orthogonal to FSDP2 so it can be applied pre-sharding or post-sharding.
This method follows the same logic as FSDP1 as well as TorchTitan's AC example.
Args:
model (nn.Module): The model to apply activation checkpointing to.
activation_check... | apply_ac | python | mosaicml/composer | composer/distributed/activation_checkpointing.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/activation_checkpointing.py | Apache-2.0 |
def ddp_sync_context(state: State, is_final_microbatch: bool, sync_strategy: Union[str, DDPSyncStrategy]):
"""A context manager for handling the :class:`DDPSyncStrategy`.
Args:
state (State): The state of the :class:`.Trainer`.
is_final_microbatch (bool): Whether or not the context is being use... | A context manager for handling the :class:`DDPSyncStrategy`.
Args:
state (State): The state of the :class:`.Trainer`.
is_final_microbatch (bool): Whether or not the context is being used during the final
microbatch of the gradient accumulation steps.
sync_strategy (str | DDPSync... | ddp_sync_context | 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_ddp_module(module: torch.nn.Module, find_unused_parameters: bool) -> torch.nn.Module:
"""Wraps the module in a :class:`torch.nn.parallel.DistributedDataParallel` object if running distributed training.
Args:
module (torch.nn.Module): The module to wrap.
find_unused_parameters (bool)... | Wraps the module in a :class:`torch.nn.parallel.DistributedDataParallel` object if running distributed training.
Args:
module (torch.nn.Module): The module to wrap.
find_unused_parameters (bool): Whether or not to do a pass over the autograd graph
to find parameters to not expect gradie... | prepare_ddp_module | python | mosaicml/composer | composer/distributed/dist_strategy.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/dist_strategy.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.