python_code stringlengths 0 187k | repo_name stringlengths 8 46 | file_path stringlengths 6 135 |
|---|---|---|
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Base class for logger callback."""
from __future__ import annotations
import pathlib
from abc import ABC
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Union
import numpy as np
import torch
from composer.core.call... | composer-dev | composer/loggers/logger_destination.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Logs metrics to the console and show a progress bar."""
from __future__ import annotations
import os
import sys
from typing import TYPE_CHECKING, Any, Dict, List, Optional, TextIO, Union
import tqdm.auto
import yaml
from composer.c... | composer-dev | composer/loggers/progress_bar_logger.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Base classes, functions, and variables for logger."""
from __future__ import annotations
import collections.abc
import operator
import pathlib
from functools import reduce
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequen... | composer-dev | composer/loggers/logger.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Log files to an object store."""
from __future__ import annotations
import logging
import multiprocessing
import os
import pathlib
import queue
import shutil
import tempfile
import threading
import time
import uuid
import warnings
fr... | composer-dev | composer/loggers/remote_uploader_downloader.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Logs to a file."""
from __future__ import annotations
import os
import queue
import sys
import textwrap
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, TextIO
from composer.loggers.logger import Logger, format_log_d... | composer-dev | composer/loggers/file_logger.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Logs metrics to the console and without a progress bar."""
from __future__ import annotations
import sys
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, TextIO, Union
import numpy as np
import yaml
from composer.co... | composer-dev | composer/loggers/console_logger.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Log to `Comet <https://www.comet.com/?utm_source=mosaicml&utm_medium=partner&utm_campaign=mosaicml_comet_integration>`_."""
from __future__ import annotations
import textwrap
from typing import Any, Dict, Optional, Sequence, Union
i... | composer-dev | composer/loggers/cometml_logger.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Base module for callbacks."""
from __future__ import annotations
import abc
from typing import TYPE_CHECKING, Any
from composer.core.serializable import Serializable
if TYPE_CHECKING:
from composer import Event, State
from c... | composer-dev | composer/core/callback.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Base class for algorithms that improve a model's quality or efficiency."""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Dict, Optional
from composer.core.serializable ... | composer-dev | composer/core/algorithm.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Utilities to track training progress in terms of epochs, batches, samples, and tokens.
Callbacks, algorithms, and schedulers can use the current training time to fire at certain points in the training
process.
The :class:`~.time.Time... | composer-dev | composer/core/time.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Training Loop Events."""
from composer.utils import StringEnum
__all__ = ['Event']
class Event(StringEnum):
"""Enum to represent training loop events.
Events mark specific points in the training loop where an :class:`~.core... | composer-dev | composer/core/event.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Serialization interface used by checkpointing."""
from __future__ import annotations
from typing import Any, Dict
__all__ = ['Serializable']
class Serializable:
"""Interface for serialization; used by checkpointing."""
de... | composer-dev | composer/core/serializable.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Central components used by other modules.
Central parts of composer such as :class:`~.engine.Engine`, base class for critical components such as
:class:`~.algorithm.Algorithm` and :class:`~.callback.Callback` and other useful function... | composer-dev | composer/core/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Specifications for operating and training on data."""
from __future__ import annotations
import collections.abc
import math
import textwrap
import warnings
from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Mapping, Opti... | composer-dev | composer/core/data_spec.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Reference for common types used throughout the composer library.
Attributes:
Batch (Any): Alias to type Any.
A batch of data can be represented in several formats, depending on the application.
PyTorchScheduler (torch.... | composer-dev | composer/core/types.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Enum class for the numerical precision to be used by the model."""
import contextlib
import os
import textwrap
from typing import Generator, Union
import torch
from composer.utils import StringEnum
try:
import transformer_engin... | composer-dev | composer/core/precision.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Engine is a coordinator for running algorithms and resolving ordering conflicts among them for composition.
.. currentmodule:: composer
The order in which algorithms are run matters significantly during composition. For example, the
... | composer-dev | composer/core/engine.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Algorithm Passes reorder or modify the execution of algorithms by the Engine.
The order in which algorithms are run matters significantly during composition. For example, the
:class:`.SelectiveBackprop` algorithm runs on the :attr:`.E... | composer-dev | composer/core/passes.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""A wrapper for a dataloader to include metrics that apply to a specific dataset."""
from __future__ import annotations
import math
import textwrap
import warnings
from typing import Any, Callable, Dict, Iterable, List, Optional, Union... | composer-dev | composer/core/evaluator.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""The state of the trainer."""
from __future__ import annotations
import collections.abc
import logging
import textwrap
import warnings
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterabl... | composer-dev | composer/core/state.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""A collection of custom loss functions and loss function related utilities."""
from composer.loss.loss import DiceLoss, binary_cross_entropy_with_logits, loss_registry, soft_cross_entropy
__all__ = [
'DiceLoss',
'binary_cross_... | composer-dev | composer/loss/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Custom loss functions."""
from __future__ import annotations
import warnings
from typing import Optional
import torch
from torch import Tensor
from torch.nn import functional as F
from torch.nn.modules.loss import _Loss
from compos... | composer-dev | composer/loss/loss.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Loss-related utilities."""
from __future__ import annotations
import warnings
from typing import Optional
import torch
__all__ = ['infer_target_type', 'ensure_targets_one_hot', 'check_for_index_targets']
def infer_target_type(inp... | composer-dev | composer/loss/utils.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Estimate total time of training."""
from __future__ import annotations
import time
import warnings
from typing import Dict, List, Optional
from composer.core import Callback, State, TimeUnit
from composer.loggers import Logger
__all... | composer-dev | composer/callbacks/runtime_estimator.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Create a submission for MLPerf Training benchmark."""
import json
import logging
import os
import platform
import subprocess
import sys
import warnings
from typing import Any, Dict, Iterable, Optional
import torch
from torch.utils.da... | composer-dev | composer/callbacks/mlperf.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Monitor throughput during training."""
from __future__ import annotations
import warnings
from collections import deque
from typing import Any, Callable, Deque, Dict, Optional, Union
import torch
from composer.core import Callback, ... | composer-dev | composer/callbacks/speed_monitor.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Threshold stopping callback."""
from typing import Any, Callable, Optional, Union
import torch
from composer.core import Callback, State
from composer.loggers import Logger
class ThresholdStopper(Callback):
"""Halt training wh... | composer-dev | composer/callbacks/threshold_stopper.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Callbacks that run at each training loop :class:`.Event`.
Each callback inherits from the :class:`.Callback` base class. See detailed description and
examples for writing your own callbacks at the :class:`.Callback` base class.
"""
fr... | composer-dev | composer/callbacks/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Monitor learning rate during training."""
from composer.core import Callback, State
from composer.loggers import Logger
__all__ = ['LRMonitor']
class LRMonitor(Callback):
"""Logs the learning rate.
This callback iterates ov... | composer-dev | composer/callbacks/lr_monitor.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Callback to save checkpoints during training."""
from __future__ import annotations
import logging
import os
import pathlib
import tempfile
import textwrap
from typing import Callable, List, Optional, Union
from composer.core import... | composer-dev | composer/callbacks/checkpoint_saver.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Callback to export model for inference."""
from __future__ import annotations
import logging
from copy import deepcopy
from typing import Any, Optional, Sequence, Union
import torch.nn as nn
from composer.core import Callback, Stat... | composer-dev | composer/callbacks/export_for_inference.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Monitor gradients during training."""
import torch
from composer.core import Callback, State
from composer.loggers import Logger
from composer.utils import dist
__all__ = ['OptimizerMonitor']
class OptimizerMonitor(Callback):
... | composer-dev | composer/callbacks/optimizer_monitor.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Check GPU Health during training."""
import logging
import os
from collections import deque
from datetime import datetime
from typing import List, Optional, Tuple
import numpy as np
import torch
from composer.core import Callback, St... | composer-dev | composer/callbacks/health_checker.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Early stopping callback."""
from __future__ import annotations
import logging
from typing import Any, Callable, Optional, Union
import torch
from composer.core import Callback, State, Time, TimeUnit
from composer.loggers import Log... | composer-dev | composer/callbacks/early_stopper.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Monitor train and eval images."""
from typing import Any, Callable, Sequence, Tuple, Union
import torch
from composer.core import Callback, State, Time, TimeUnit
from composer.loggers import Logger
from composer.loss.utils import inf... | composer-dev | composer/callbacks/image_visualizer.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Log memory usage during training."""
import logging
import math
import warnings
from typing import Dict, Optional, Union
import torch.cuda
from composer.core import Callback, State
from composer.loggers import Logger
log = logging.g... | composer-dev | composer/callbacks/memory_monitor.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""C4 (Colossal Cleaned Common Crawl) dataset.
This dataset is a colossal, cleaned version of Common Crawl's web crawl corpus and it is based on the `Common Crawl
<https://commoncrawl.org>`_ dataset.
"""
import logging
from typing import... | composer-dev | composer/datasets/c4.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Synthetic datasets used for testing, profiling, and debugging."""
from __future__ import annotations
from typing import Callable, Optional, Sequence, Union
import torch
import torch.utils.data
from PIL import Image
from torchvision.... | composer-dev | composer/datasets/synthetic.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
import logging
from typing import Optional
import numpy as np
from composer.core import Dataset
from composer.utils import MissingConditionalImportError
try:
import ffcv
ffcv_installed = True
except ImportError:
ffcv_instal... | composer-dev | composer/datasets/ffcv_utils.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""ImageNet classification streaming dataset.
The most widely used dataset for Image Classification algorithms. Please refer to the `ImageNet 2012 Classification
Dataset <http://image-net.org/>`_ for more details.
"""
import os
from typ... | composer-dev | composer/datasets/imagenet.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
# This code is based on the implementation in https://github.com/EleutherAI/lm-evaluation-harness/blob/8c048e266a22a1c85ccbdb0c209ac712e4f39989/lm_eval/base.py#L221-L330
from __future__ import annotations
import random
from typing import... | composer-dev | composer/datasets/in_context_learning_evaluation.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Natively supported datasets."""
from composer.datasets.ade20k import (ADE20k, build_ade20k_dataloader, build_streaming_ade20k_dataloader,
build_synthetic_ade20k_dataloader)
from composer.datasets.... | composer-dev | composer/datasets/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""BraTS (Brain Tumor Segmentation) dataset.
Please refer to the `Brain Tumor Segmentation (BraTS) challenge <https://www.med.upenn.edu/cbica/brats2021/>`_ for more
details about this dataset.
"""
import glob
import os
import random
im... | composer-dev | composer/datasets/brats.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""ADE20K Semantic segmentation and scene parsing dataset.
Please refer to the `ADE20K dataset <https://groups.csail.mit.edu/vision/datasets/ADE20K/>`_ for more details about this
dataset.
"""
import os
from math import ceil
from typing... | composer-dev | composer/datasets/ade20k.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
import logging
from typing import List, cast
from torch.utils.data import DataLoader, Dataset
from composer.utils import MissingConditionalImportError, dist
log = logging.getLogger(__name__)
def build_lm_dataloader(
datadir: List... | composer-dev | composer/datasets/lm_dataset.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Utility and helper functions for datasets."""
import logging
import textwrap
from typing import Callable, List, Tuple, Union
import numpy as np
import torch
from PIL import Image
from torchvision import transforms
from torchvision.da... | composer-dev | composer/datasets/utils.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""CIFAR image classification dataset.
The CIFAR datasets are a collection of labeled 32x32 colour images. Please refer to the `CIFAR dataset
<https://www.cs.toronto.edu/~kriz/cifar.html>`_ for more details.
"""
import os
import textwra... | composer-dev | composer/datasets/cifar.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from typing import Any
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from composer.core import MemoryFormat
from composer.datasets.synthetic import SyntheticBatchPairDataset
from composer.utils imp... | composer-dev | composer/datasets/mnist.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
class NoEffectWarning(Warning):
"""Warns when an algorithm did not have an effect.
An algorithm should emit this warning when its application resulted in no changes to the trainer :class:`~.State`.
For example, if surgery al... | composer-dev | composer/algorithms/warnings.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Efficiency methods for training.
Examples include :class:`.LabelSmoothing` and adding :class:`.SqueezeExcite` blocks,
among many others.
Algorithms are implemented in both a standalone functional form (see :mod:`composer.functional`)... | composer-dev | composer/algorithms/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core Exponential Moving Average (EMA) classes and functions."""
from __future__ import annotations
import itertools
import logging
from typing import Any, Dict, Optional, Union
import torch
from composer.callbacks.checkpoint_saver ... | composer-dev | composer/algorithms/ema/ema.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Exponential moving average maintains a moving average of model parameters and uses these at test time.
See the :doc:`Method Card </method_cards/ema>` for more details.
"""
from composer.algorithms.ema.ema import EMA as EMA
from compo... | composer-dev | composer/algorithms/ema/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Low Precision GroupNorm."""
from __future__ import annotations
import logging
import warnings
from typing import Dict, Optional, Sequence, Type, Union
import torch
import torch.nn.functional as F
from torch.optim import Optimizer
f... | composer-dev | composer/algorithms/low_precision_groupnorm/low_precision_groupnorm.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Replaces all instances of :class:`torch.nn.GroupNorm` with a low precision :class:`torch.nn.GroupNorm` (either float16 or bfloat16).
By default, torch.autocast always runs torch.nn.GroupNorm in float32, so this surgery forces a lower p... | composer-dev | composer/algorithms/low_precision_groupnorm/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core CutOut classes and functions."""
from __future__ import annotations
import logging
from typing import Any, Callable, Optional, TypeVar, Union
import numpy as np
import torch
from PIL.Image import Image as PillowImage
from torch... | composer-dev | composer/algorithms/cutout/cutout.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""`Cutout <https://arxiv.org/abs/1708.04552>`_ is a data augmentation technique that works by masking out one or more
square regions of an input image.
See the :doc:`Method Card </method_cards/cutout>` for more details.
"""
from compos... | composer-dev | composer/algorithms/cutout/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Applies Fastai's `progressive resizing <https://github.com/fastai/fastbook/blob/780b76bef3127ce5b64f8230fce60e915a
7e0735/07_sizing_and_tta.ipynb>`__ data augmentation to speed up training.
Progressive resizing initially reduces input... | composer-dev | composer/algorithms/progressive_resizing/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core Progressive Resizing classes and functions."""
from __future__ import annotations
import logging
import textwrap
from functools import partial
from typing import Any, Callable, Optional, Tuple, Union
import torch
import torch.n... | composer-dev | composer/algorithms/progressive_resizing/progressive_resizing.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""ALiBi (Attention with Linear Biases; `Press et al, 2021 <https://arxiv.org/abs/2108.12409>`_) dispenses with position
embeddings for tokens in transformer-based NLP models, instead encoding position information by biasing the query-key... | composer-dev | composer/algorithms/alibi/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core ALiBi classes and functions."""
from __future__ import annotations
import logging
from typing import Optional, Sequence, Union
import torch
from torch.optim import Optimizer
from composer.core import Algorithm, Event, State
fr... | composer-dev | composer/algorithms/alibi/alibi.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
import math
from types import MethodType
from typing import Optional, Tuple
import torch
from torch import nn
from transformers.models.bert.modeling_bert import BertEmbeddings, BertSelfAttention
from transformers.models.roberta.modeling_... | composer-dev | composer/algorithms/alibi/attention_surgery_functions/_bert.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
# Import files that add functions to the `policy_registry` registry in order to actually
# register those functions.
from composer.utils import MissingConditionalImportError
try:
from composer.algorithms.alibi.attention_surgery_funct... | composer-dev | composer/algorithms/alibi/attention_surgery_functions/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
import inspect
import logging
import math
from operator import attrgetter
from typing import Callable, Dict, Optional, Type
import torch
log = logging.getLogger(__name__)
# Alibi applies module surgery to registered modules using their... | composer-dev | composer/algorithms/alibi/attention_surgery_functions/utils.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from types import MethodType
from typing import Tuple
import torch
from transformers.models.gpt2.modeling_gpt2 import GPT2Attention, GPT2Model
from composer.algorithms.alibi.attention_surgery_functions.utils import (policy_registry, reg... | composer-dev | composer/algorithms/alibi/attention_surgery_functions/_gpt2.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""NoOpModel algorithm and class."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Dict, Optional
import torch
import torch.nn.functional as F
from torchmetrics import Metric
from torchmetrics... | composer-dev | composer/algorithms/no_op_model/no_op_model.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Replaces model with a dummy model of type :class:`NoOpModelClass`.
The algorithm runs on :attr:`Event.INIT`. It replaces the model in the state with
a :class:`.NoOpModelClass` and then updates the parameters in the optimizer
through m... | composer-dev | composer/algorithms/no_op_model/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from composer.algorithms.weight_standardization.weight_standardization import \
WeightStandardization as WeightStandardization
from composer.algorithms.weight_standardization.weight_standardization import \
apply_weight_standardiz... | composer-dev | composer/algorithms/weight_standardization/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
import logging
import textwrap
import torch
import torch.nn.utils.parametrize as parametrize
from torch import nn
from torch.fx import symbolic_trace
from composer.core import Algorithm, Event, State
from composer.loggers import Logger
... | composer-dev | composer/algorithms/weight_standardization/weight_standardization.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""SAM (`Foret et al, 2020 <https://arxiv.org/abs/2010.01412>`_) wraps an existing optimizer with a
:class:`SAMOptimizer` which makes the optimizer minimize both loss value and sharpness.This can improves model
generalization and provide ... | composer-dev | composer/algorithms/sam/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""SAM algorithm and optimizer class."""
from __future__ import annotations
import logging
import warnings
from typing import Optional
import torch
from composer.core import Algorithm, Event, State
from composer.loggers import Logger
... | composer-dev | composer/algorithms/sam/sam.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Clips all gradients in a model based on their values, their norms,
and their parameters' norms.
See the :doc:`Method Card </method_cards/gradient_clipping>` for more details.
"""
from composer.algorithms.gradient_clipping.gradient_cl... | composer-dev | composer/algorithms/gradient_clipping/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core gradient clipping classes and functions."""
from __future__ import annotations
import logging
from typing import Iterable, Optional, Union
import torch
from packaging import version
from composer.core import Algorithm, Event, ... | composer-dev | composer/algorithms/gradient_clipping/gradient_clipping.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core Label Smoothing classes and functions."""
from __future__ import annotations
from typing import Any, Callable, Optional, Tuple, Union
import torch
from composer.core import Algorithm, Event, State
from composer.loggers import ... | composer-dev | composer/algorithms/label_smoothing/label_smoothing.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Shrinks targets towards a uniform distribution to counteract label noise. Introduced in `Rethinking the Inception
Architecture for Computer Vision <https://arxiv.org/abs/1512.00567>`_.
See the :doc:`Method Card </method_cards/label_sm... | composer-dev | composer/algorithms/label_smoothing/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Randomly applies a sequence of image data augmentations
(`Cubuk et al, 2019 <https://arxiv.org/abs/1909.13719>`_) to an image. See
:class:`.RandAugment` or the :doc:`Method Card
</method_cards/randaugment>` for details.
"""
from compo... | composer-dev | composer/algorithms/randaugment/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core RandAugment code."""
import functools
import textwrap
import weakref
from typing import List, TypeVar
import numpy as np
import torch
import torch.utils.data
from PIL.Image import Image as PillowImage
from torchvision.datasets i... | composer-dev | composer/algorithms/randaugment/randaugment.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Replaces batch normalization modules with `Ghost Batch Normalization <https://arxiv.org/abs/1705.08741>`_ modules
that simulate the effect of using a smaller batch size.
See :class:`~composer.algorithms.GhostBatchNorm` or the :doc:`Me... | composer-dev | composer/algorithms/ghost_batchnorm/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
import logging
import math
from typing import Optional, Sequence, Union
import torch
from torch.optim import Optimizer
from composer.core import Algorithm, Event, State
from composer.loggers import Logger
from composer.utils import modu... | composer-dev | composer/algorithms/ghost_batchnorm/ghost_batchnorm.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""`CutMix <https://arxiv.org/abs/1905.04899>`_ trains the network on non-overlapping combinations of pairs of examples
and iterpolated targets rather than individual examples and targets.
This is done by taking a non-overlapping combina... | composer-dev | composer/algorithms/cutmix/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core CutMix classes and functions."""
from __future__ import annotations
import logging
from typing import Any, Callable, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from composer.core import Alg... | composer-dev | composer/algorithms/cutmix/cutmix.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core SelectiveBackprop class and functions."""
from __future__ import annotations
import inspect
from typing import Any, Callable, Optional, Sequence, Tuple, Union
import numpy as np
import torch
from torch.nn import functional as F... | composer-dev | composer/algorithms/selective_backprop/selective_backprop.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""`Selective Backprop <https://arxiv.org/abs/1910.00762>`_ prunes minibatches according to the difficulty of the
individual training examples, and only computes weight gradients over the pruned subset, reducing iteration time and
speedin... | composer-dev | composer/algorithms/selective_backprop/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Implements stochastic depth (`Huang et al, 2016 <https://arxiv.org/abs/1603.09382>`_) for ResNet blocks.
See :class:`.StochasticDepth`, the sample-wise stochastic depth :doc:`method card
</method_cards/stochastic_depth_samplewise>`, o... | composer-dev | composer/algorithms/stochastic_depth/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Modules and layers for applying the Stochastic Depth algorithm."""
from __future__ import annotations
import functools
import logging
from typing import Optional, Type, Union
import torch
from torchvision.models.resnet import Bottle... | composer-dev | composer/algorithms/stochastic_depth/stochastic_depth.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Stochastic forward functions for ResNet Bottleneck modules."""
from typing import Optional
import torch
import torch.nn as nn
from torch.fx import GraphModule
from torchvision.models.resnet import Bottleneck
__all__ = ['make_resnet_... | composer-dev | composer/algorithms/stochastic_depth/stochastic_layers.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from typing import Callable, Iterable, Type, TypeVar, cast
import torch
import torchvision.transforms.functional
from PIL.Image import Image as PillowImage
_InputImgT = TypeVar('_InputImgT', torch.Tensor, PillowImage)
_OutputImgT = TypeV... | composer-dev | composer/algorithms/utils/augmentation_common.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Helper utilities for algorithms."""
from composer.algorithms.utils.augmentation_primitives import augmentation_sets
__all__ = ['augmentation_sets']
| composer-dev | composer/algorithms/utils/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Helper functions to perform augmentations on a :class:`PIL.Image.Image`.
Augmentations that take an intensity value are normalized on a scale of 1-10,
where 10 is the strongest and maximum value an augmentation function will accept.
... | composer-dev | composer/algorithms/utils/augmentation_primitives.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core Layer Freezing classes and functions."""
from __future__ import annotations
import logging
import textwrap
import warnings
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import torch
from torch.optim impor... | composer-dev | composer/algorithms/layer_freezing/layer_freezing.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Progressively freeze the layers of the network during training, starting with the earlier layers.
See the :doc:`Method Card </method_cards/layer_freezing>` for more details.
"""
from composer.algorithms.layer_freezing.layer_freezing ... | composer-dev | composer/algorithms/layer_freezing/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Replaces all instances of `torch.nn.LayerNorm` with a `apex.normalization.fused_layer_norm.FusedLayerNorm
<https://nvidia.github.io/apex/layernorm.html>`_.
By fusing multiple kernel launches into one, this usually improves GPU utiliza... | composer-dev | composer/algorithms/fused_layernorm/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
# Copyright 2022 MosaicML. All Rights Reserved.
from __future__ import annotations
import logging
import warnings
from typing import Dict, Optional, Sequence, Type, Union
import torch
try:
from apex.normalization.fused_layer_norm ... | composer-dev | composer/algorithms/fused_layernorm/fused_layernorm.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import abc
import math
from typing import Optional, Tuple, Union, cast
import numpy as np
import torch
from torch import nn
from torch.nn.common_types import _size_2_t
from composer.algorithms.factori... | composer-dev | composer/algorithms/factorize/factorize_modules.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Decomposes linear operators into pairs of smaller linear operators.
See :class:`.Factorize` or the :doc:`Method Card </method_cards/factorize>` for details.
"""
from composer.algorithms.factorize.factorize import Factorize as Factori... | composer-dev | composer/algorithms/factorize/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
import dataclasses
from typing import Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
@dataclasses.dataclass
class LowRankSolution:
"""Bundles tensors used by a factorized linear operator.
... | composer-dev | composer/algorithms/factorize/factorize_core.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import logging
from typing import Optional, Sequence, Type, Union, cast
import torch
from torch.optim import Optimizer
from composer.algorithms.factorize.factorize_modules import (FactorizedConv2d, Fa... | composer-dev | composer/algorithms/factorize/factorize.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core MixUp classes and functions."""
from __future__ import annotations
import logging
from typing import Any, Callable, Optional, Tuple, Union
import numpy as np
import torch
from composer.core import Algorithm, Event, State
from ... | composer-dev | composer/algorithms/mixup/mixup.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Create new samples using convex combinations of pairs of samples.
This is done by taking a convex combination of x with a randomly permuted copy of x.
See the :doc:`Method Card </method_cards/mixup>` for more details.
"""
from compo... | composer-dev | composer/algorithms/mixup/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Changes the memory format of the model to ``torch.channels_last``.
This usually improves GPU utilization. See the :doc:`Method Card </method_cards/channels_last>` for more details.
"""
from composer.algorithms.channels_last.channels_... | composer-dev | composer/algorithms/channels_last/__init__.py |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""ChannelsLast algorithm."""
from __future__ import annotations
import logging
from typing import Optional
import torch
from composer.core import Algorithm, Event, State
from composer.loggers import Logger
log = logging.getLogger(__... | composer-dev | composer/algorithms/channels_last/channels_last.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.