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 """Core code for sequence length warmup.""" import logging import textwrap from typing import Dict, Mapping, Optional import torch import torch.utils.data from composer.core import Algorithm, Batch, Event, State, TimeUnit, get_precisio...
composer-dev
composer/algorithms/seq_length_warmup/seq_length_warmup.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Sequence length warmup progressively increases the sequence length during training of NLP models. See the :doc:`Method Card </method_cards/seq_length_warmup>` for more details. """ from composer.algorithms.seq_length_warmup.seq_lengt...
composer-dev
composer/algorithms/seq_length_warmup/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 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 from composer.loggers import Logger from co...
composer-dev
composer/algorithms/squeeze_excite/squeeze_excite.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Adds Squeeze-and-Excitation blocks (`Hu et al, 2019 <https://arxiv.org/abs/1709.01507>`_) after the :class:`~torch.nn.Conv2d` modules in a neural network. See :class:`~composer.algorithms.SqueezeExcite` or the :doc:`Method Card </meth...
composer-dev
composer/algorithms/squeeze_excite/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Replaces all instances of :class:`torch.nn.LayerNorm` with a low precision :class:`torch.nn.LayerNorm` (either float16 or bfloat16). By default, torch.autocast always runs torch.nn.LayerNorm in float32, so this surgery forces a lower p...
composer-dev
composer/algorithms/low_precision_layernorm/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Low Precision LayerNorm.""" 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 packaging import version from t...
composer-dev
composer/algorithms/low_precision_layernorm/low_precision_layernorm.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Replaces all instances of `torch.nn.Dropout` with a `GyroDropout`. By masking Dropout layer, this usually improves accuracy. """ from composer.algorithms.gyro_dropout.gyro_dropout import GyroDropout, GyroDropoutLayer, apply_gyro_drop...
composer-dev
composer/algorithms/gyro_dropout/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 # Written by Gihyun Park, Junyeol Lee, and Jiwon Seo import logging import warnings from typing import Dict, Optional, Type import numpy as np import torch from composer.algorithms.warnings import NoEffectWarning from composer.core imp...
composer-dev
composer/algorithms/gyro_dropout/gyro_dropout.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Replaces the Linear layers in the feed-forward network with `Gated Linear Units <https://arxiv.org/abs/2002.05202>`_. This leads to improved convergence with a slight drop in throughput. Using no bias terms in the GLU is highly recomm...
composer-dev
composer/algorithms/gated_linear_units/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 from typing import Callable import torch class BERTGatedFFOutput(torch.nn.Module): """ Defines a single feed-forward block that uses `Gated Linear Units <https://arxiv.org/abs/2002.05202>`_. Args: d_embed (int): Th...
composer-dev
composer/algorithms/gated_linear_units/gated_linear_unit_layers.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 Callable, Dict, Optional, Sequence, Type, Union import torch from composer.models.huggingface import ...
composer-dev
composer/algorithms/gated_linear_units/gated_linear_units.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Core code for Stochastic Weight Averaging.""" from __future__ import annotations import logging import warnings from typing import Any, Dict, List, Optional import torch from torch.optim.swa_utils import SWALR, AveragedModel from c...
composer-dev
composer/algorithms/swa/swa.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Stochastic Weight Averaging (SWA; `Izmailov et al, 2018 <https://arxiv.org/abs/1803.05407>`_) averages model weights sampled at different times near the end of training. This leads to better generalization than just using the final tr...
composer-dev
composer/algorithms/swa/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Core AugMix classes and functions.""" import functools import textwrap import weakref from typing import List, TypeVar import numpy as np import torch import torch.utils.data from PIL import Image from PIL.Image import Image as Pillo...
composer-dev
composer/algorithms/augmix/augmix.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """AugMix (`Hendrycks et al, 2020 <http://arxiv.org/abs/1912.02781>`_) creates multiple independent realizations of sequences of image augmentations, applies each sequence with random intensity, and returns a convex combination of the aug...
composer-dev
composer/algorithms/augmix/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 # type: ignore from typing import Optional import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.common_types import _size_2_t from torch.nn.modules.utils import _pair def _default_2d_filte...
composer-dev
composer/algorithms/blurpool/blurpool_layers.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """`BlurPool <http://proceedings.mlr.press/v97/zhang19a.html>`_ adds anti-aliasing filters to convolutional layers to increase accuracy and invariance to small shifts in the input. See :class:`~composer.algorithms.BlurPool` or the :doc:`...
composer-dev
composer/algorithms/blurpool/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import functools import logging import warnings from typing import Optional, Sequence, Union import numpy as np import torch from torch.optim import Optimizer from composer.algorithms.blurpool.blurpoo...
composer-dev
composer/algorithms/blurpool/blurpool.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Core ColOut classes and functions.""" from __future__ import annotations import logging import textwrap import weakref from typing import Any, Callable, Tuple, TypeVar, Union import torch import torch.utils.data from PIL.Image impor...
composer-dev
composer/algorithms/colout/colout.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Drops a fraction of the rows and columns of an input image. If the fraction of rows/columns dropped isn't too large, this does not significantly alter the content of the image, but reduces its size and provides extra variability. See ...
composer-dev
composer/algorithms/colout/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Optimizers and learning rate schedulers. Composer is compatible with optimizers based off of PyTorch's native :class:`~torch.optim.Optimizer` API, and common optimizers such However, where applicable, it is recommended to use the opti...
composer-dev
composer/optim/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Optimizers with weight decay decoupled from the learning rate. These optimizers are based off of `Decoupled Weight Decay Regularization <https://arxiv.org/abs/1711.05101>`_, which proposes this decoupling. In general, it is recommende...
composer-dev
composer/optim/decoupled_weight_decay.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Stateless learning rate schedulers. Stateless schedulers solve some of the problems associated with PyTorch's built-in schedulers provided in :mod:`torch.optim.lr_scheduler`. The primary design goal of the schedulers provided in this ...
composer-dev
composer/optim/scheduler.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Retry helper.""" from __future__ import annotations import collections.abc import functools import random import time from typing import Any, Callable, Sequence, Type, TypeVar, Union, cast, overload TCallable = TypeVar('TCallable', ...
composer-dev
composer/utils/retrying.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Miscellaneous Helpers.""" import socket from contextlib import contextmanager from typing import Type import torch from packaging import version from torch.nn.parallel import DistributedDataParallel __all__ = [ 'is_model_deepspe...
composer-dev
composer/utils/misc.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 # To keep the typing organized for this file, see iter_helpers.pyi # All typing annotations are in there # All methods signatures must be defined in there. """Utilities for iterating over collections.""" import collections.abc import io ...
composer-dev
composer/utils/iter_helpers.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Dynamically import a Python object (e.g. module, class, function, ...).""" import importlib from typing import Any, Optional __all__ = ['MissingConditionalImportError', 'import_object'] class MissingConditionalImportError(ImportErr...
composer-dev
composer/utils/import_helpers.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Utilities for working with training checkpoints.""" from __future__ import annotations import contextlib import fnmatch import logging import os import shutil import tarfile import tempfile import textwrap import warnings from pathli...
composer-dev
composer/utils/checkpoint.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Device-related helper methods and utilities.""" from typing import TYPE_CHECKING, Optional, Union import torch.cuda if TYPE_CHECKING: from composer.devices import Device __all__ = ['get_device', 'is_tpu_installed'] def get_de...
composer-dev
composer/utils/device.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Helpers to get items and set items in a batch.""" from operator import attrgetter, itemgetter from typing import Any, Callable, Sequence, Union, cast __all__ = ['batch_get', 'batch_set'] def batch_get(batch: Any, key: Union[str, in...
composer-dev
composer/utils/batch_helpers.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Helpers to gather system information for debugging and bug reporting. Leverages PyTorch's :mod:`torch.utils.collect_env` package to gather pertinent system information. The following information is additionally collected to faciliate ...
composer-dev
composer/utils/collect_env.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Helper utilities for configuring deterministic training to ensure reproducibility. .. note:: For deterministic model initialization, :func:`~.seed_all` and/or :func:`~.configure_deterministic_mode` should be invoked befor...
composer-dev
composer/utils/reproducibility.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Helper utilities.""" from composer.utils.auto_log_hparams import (convert_flat_dict_to_nested_dict, convert_nested_dict_to_flat_dict, extract_hparams) from composer.utils.batch_helpers impo...
composer-dev
composer/utils/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Contains helper functions for auto-logging hparams.""" from typing import Any, Dict, List, Tuple __all__ = ['extract_hparams', 'convert_nested_dict_to_flat_dict', 'convert_flat_dict_to_nested_dict'] def extract_hparams(locals_dict:...
composer-dev
composer/utils/auto_log_hparams.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """FX-based model transformation and optimization. Provides utilities to do FX-based model transformations. """ import logging import operator import re from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union impo...
composer-dev
composer/utils/fx_utils.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Inference-related utility functions for model export and optimizations. Used for exporting models into various formats such ONNX, torchscript etc. and apply optimizations such as fusion. """ from __future__ import annotations import ...
composer-dev
composer/utils/inference.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Base class for Enums containing string values.""" from __future__ import annotations import textwrap import warnings from enum import Enum class StringEnum(Enum): """Base class for Enums containing string values. This class...
composer-dev
composer/utils/string_enum.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Modify model architectures. Algorithms, such as :class:`~composer.algorithms.blurpool.BlurPool`, replace model parameters in-place. This module contains helper functions to replace parameters in :class:`~torch.nn.Module` and :class:`~...
composer-dev
composer/utils/module_surgery.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Helper methods for :mod:`torch.distributed`. To use :mod:`torch.distributed`, launch your training script with the :ref:`composer launcher for distributed training <distributed-training>`. For example, the following command launches a...
composer-dev
composer/utils/dist.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Helpers for working with files.""" from __future__ import annotations import logging import os import pathlib import re import tempfile import uuid import warnings from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, U...
composer-dev
composer/utils/file_helpers.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """OCI-Compatible object store.""" from __future__ import annotations import os import pathlib import uuid from typing import Callable, Optional, Union from composer.utils.import_helpers import MissingConditionalImportError from compos...
composer-dev
composer/utils/object_store/oci_object_store.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Utility for uploading to and downloading from cloud object stores.""" import io import os import pathlib import uuid from typing import Any, Callable, Dict, Optional, Union from requests.exceptions import ConnectionError from urllib3....
composer-dev
composer/utils/object_store/libcloud_object_store.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """S3-Compatible object store.""" from __future__ import annotations import os import pathlib import uuid from typing import Any, Callable, Dict, Optional, Union from composer.utils.import_helpers import MissingConditionalImportError f...
composer-dev
composer/utils/object_store/s3_object_store.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Object store base class and implementations.""" from composer.utils.object_store.libcloud_object_store import LibcloudObjectStore from composer.utils.object_store.object_store import ObjectStore, ObjectStoreTransientError from compose...
composer-dev
composer/utils/object_store/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Utility for uploading to and downloading from cloud object stores.""" from __future__ import annotations import contextlib import os import pathlib import urllib.parse import uuid from typing import Any, Callable, Dict, Optional, Uni...
composer-dev
composer/utils/object_store/sftp_object_store.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Abstract class for utilities that upload to and download from object stores.""" import abc import pathlib from types import TracebackType from typing import Callable, Optional, Type, Union __all__ = ['ObjectStore', 'ObjectStoreTransi...
composer-dev
composer/utils/object_store/object_store.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The models module contains the :class:`.ComposerModel` base class along with reference implementations of many common models. Additionally, it includes task-specific convenience :class:`.ComposerModel`\\s that wrap existing Pytorch mod...
composer-dev
composer/models/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Module Initializers.""" from typing import Callable import torch from torch import nn as nn from composer.utils import StringEnum class Initializer(StringEnum): """Sets the initialization scheme for different layers of a PyTor...
composer-dev
composer/models/initializers.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A wrapper class that converts 🤗 Transformers models to composer models""" from __future__ import annotations import inspect import json import logging import tempfile import textwrap from collections import UserDict from pathlib imp...
composer-dev
composer/models/huggingface.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A wrapper class that converts mmdet detection models to composer models""" from __future__ import annotations from typing import TYPE_CHECKING, Any, List, Optional import numpy as np import torch from torchmetrics import Metric from...
composer-dev
composer/models/mmdetection.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The ComposerModel base interface.""" from __future__ import annotations import abc import copy import warnings from typing import Any, Dict, Optional, Sequence, Union import torch from torch import Tensor from torchmetrics import Met...
composer-dev
composer/models/base.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A convenience class that creates a :class:`.ComposerModel` for classification tasks from a vanilla PyTorch model. :class:`.ComposerClassifier` requires batches in the form: (``input``, ``target``) and includes a basic classification t...
composer-dev
composer/models/tasks/classification.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Model tasks are ComposerModels with forward passes and logging built-in for many common deep learning tasks.""" from composer.models.tasks.classification import ComposerClassifier as ComposerClassifier __all__ = ['ComposerClassifier'...
composer-dev
composer/models/tasks/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The ResNet model family is a set of convolutional neural networks described in `Deep Residual Learning for Image Recognition <https://arxiv.org/abs/1512.03385>`_ (He et al, 2015). ResNets can be used as the base for a variety of vision...
composer-dev
composer/models/resnet/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A :class:`.ComposerClassifier` wrapper around the torchvision implementations of the ResNet model family.""" import logging import textwrap import warnings from typing import List, Optional import torchvision from packaging import ve...
composer-dev
composer/models/resnet/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """ViT Small Patch 16 for image classification.""" from composer.models.vit_small_patch16.model import vit_small_patch16 as vit_small_patch16 __all__ = ['vit_small_patch16'] _task = 'Image Classification' _dataset = 'ImageNet' _name = ...
composer-dev
composer/models/vit_small_patch16/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Implements ViT-S/16 as a :class:`.ComposerClassifier`.""" from composer.models.tasks import ComposerClassifier __all__ = ['vit_small_patch16'] def vit_small_patch16(num_classes: int = 1000, image_size: int = 2...
composer-dev
composer/models/vit_small_patch16/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 ## Code adapted from https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/Segmentation/nnUNet/ import numpy as np import torch import torch.nn as nn normalizations = { 'instancenorm3d': nn.InstanceNorm3d, 'instance...
composer-dev
composer/models/unet/_layers.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A U-Net model extending :class:`.ComposerModel`.""" import logging from typing import Any, Dict, Optional, Sequence, Union import torch import torch.nn as nn from torchmetrics import Metric from composer.metrics.metrics import Dice ...
composer-dev
composer/models/unet/unet.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The Unet architecture used in image segmentation. The example we are using is for BRATS medical brain tumor dataset. See the :doc:`Model Card </model_cards/unet>` for more details. """ from composer.models.unet.unet import UNet as UN...
composer-dev
composer/models/unet/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The Unet architecture used in image segmentation. The example we are using is for BRATS medical brain tumor dataset. See the :doc:`Model Card </model_cards/unet>` for more details. """ import torch.nn as nn from composer.models.unet...
composer-dev
composer/models/unet/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A wrapper around `timm.create_model() <https://rwightman.github.io/pytorch-image-models/#load-a-pretrained-model>`_ used to create :class:`.ComposerClassifier`.""" from composer.models.timm.model import composer_timm as composer_timm ...
composer-dev
composer/models/timm/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A wrapper around `timm.create_model() <https://rwightman.github.io/pytorch-image-models/#load-a-pretrained-model>`_ used to create :class:`.ComposerClassifier`.""" from typing import Optional from composer.models.tasks import Compose...
composer-dev
composer/models/timm/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 from typing import Callable, Optional import torch from torch import nn as nn def round_channels( channels: float, width_multiplier: float, divisor: int = 8, min_value: Optional[int] = None, ) -> int: """Round numbe...
composer-dev
composer/models/efficientnetb0/_layers.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The EfficientNet model family is a set of convolutional neural networks that can be used as the basis for a variety of vision tasks, but were initially designed for image classification. The model family was designed to reach the highe...
composer-dev
composer/models/efficientnetb0/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A :class:`.ComposerClassifier` wrapper around the EfficientNet-b0 architecture.""" from composer.models.efficientnetb0.efficientnets import EfficientNet from composer.models.tasks import ComposerClassifier __all__ = ['composer_efficie...
composer-dev
composer/models/efficientnetb0/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """EfficientNet model. Adapted from `(Generic) EfficientNets for PyTorch. <https://github.com/rwightman/gen-efficientnet-pytorch>`_. """ import math import re from typing import Callable, Optional import torch import torch.nn as nn fr...
composer-dev
composer/models/efficientnetb0/efficientnets.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The `BERT <https://huggingface.co/docs/transformers/master/en/model_doc/bert>`_ model family using `Hugging Face Transformers <https://huggingface.co/transformers/>`_.""" from composer.models.bert.model import create_bert_classificati...
composer-dev
composer/models/bert/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Implements a BERT wrapper around a :class:`.ComposerTransformer`.""" from __future__ import annotations from typing import Optional from torchmetrics import MeanSquaredError from torchmetrics.classification import MatthewsCorrCoef, ...
composer-dev
composer/models/bert/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A simple example convolutional neural network which can be used to classify MNIST data.""" from composer.models.classify_mnist.model import mnist_model as mnist_model __all__ = ['mnist_model'] _task = 'Image Classification' _dataset ...
composer-dev
composer/models/classify_mnist/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A simple convolutional neural network extending :class:`.ComposerClassifier`.""" from typing import List, Optional, Sequence, Union import torch import torch.nn as nn from torch.nn import functional as F from composer.models.initial...
composer-dev
composer/models/classify_mnist/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """A ResNet model family adapted for CIFAR10 image sizes. See the :doc:`Model Card </model_cards/cifar_resnet>` for more details. """ from composer.models.resnet_cifar.model import composer_resnet_cifar as composer_resnet_cifar __all__...
composer-dev
composer/models/resnet_cifar/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """ResNet models for CIFAR extending :class:`.ComposerClassifier`.""" from typing import List, Optional from composer.models.initializers import Initializer from composer.models.resnet_cifar.resnets import ResNet9, ResNetCIFAR from comp...
composer-dev
composer/models/resnet_cifar/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The CIFAR ResNet torch module. See the :doc:`Model Card </model_cards/resnet>` for more details. """ # Code below adapted from https://github.com/facebookresearch/open_lth # and https://github.com/pytorch/vision from typing import L...
composer-dev
composer/models/resnet_cifar/resnets.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The GPT-2 model family is set of transformer-based networks for autoregressive language modeling at various scales. This family was originally proposed by OpenAI, and is trained on the OpenWebText dataset. It is useful for downstream l...
composer-dev
composer/models/gpt2/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """GPT-2 model based on `Hugging Face GPT-2 <https://huggingface.co/docs/transformers/master/en/model_doc/gpt2>`_. Implemented as a wrapper using :class:`.ComposerTrainer`. """ from __future__ import annotations from typing import Opti...
composer-dev
composer/models/gpt2/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """DeepLabV3 for image segmentation.""" from composer.models.deeplabv3.model import composer_deeplabv3 as composer_deeplabv3 __all__ = ['composer_deeplabv3']
composer-dev
composer/models/deeplabv3/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """DeepLabV3 model extending :class:`.ComposerClassifier`.""" import functools import textwrap import warnings from typing import Dict, Optional, Sequence import torch import torch.distributed as torch_dist import torch.nn.functional as...
composer-dev
composer/models/deeplabv3/model.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Composer CLI."""
composer-dev
composer/cli/__init__.py
#!/usr/bin/env python3 # Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The Composer CLI launcher for distributed training.""" import contextlib import datetime import logging import os import signal import subprocess import sys import tempfile import time import traceback from argp...
composer-dev
composer/cli/launcher.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Runs the Composer CLI.""" import sys from composer.cli.launcher import main sys.exit(main())
composer-dev
composer/cli/__main__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Profiler Schedules.""" from typing import Callable from composer.core.state import State from composer.profiler.profiler_action import ProfilerAction __all__ = ['cyclic_schedule'] def cyclic_schedule( skip_first: int = 0, ...
composer-dev
composer/profiler/profiler_schedule.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Outputs profiling data in JSON trace format.""" from __future__ import annotations import gzip import json import os import pathlib import queue import tempfile import textwrap import time from typing import TYPE_CHECKING, Dict, List...
composer-dev
composer/profiler/json_trace_handler.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Profiler to collect :mod:`torch` performance metrics during training.""" from __future__ import annotations import json import os import textwrap from typing import TYPE_CHECKING, Optional, OrderedDict import torch.profiler from tor...
composer-dev
composer/profiler/torch_profiler.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Performance profiling tools. The profiler gathers performance metrics during a training run that can be used to diagnose bottlenecks and facilitate model development. The metrics gathered include: * Duration of each :class:`.Event` ...
composer-dev
composer/profiler/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Action states for the :class:`Profiler` that define whether or not events are being recorded to the trace file.""" from composer.utils import StringEnum __all__ = ['ProfilerAction'] class ProfilerAction(StringEnum): """Action s...
composer-dev
composer/profiler/profiler_action.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Profiler Marker.""" from __future__ import annotations import functools import time from types import TracebackType from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union from composer.pr...
composer-dev
composer/profiler/marker.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Merge trace files together. To run: .. code-block:: python -m composer.profiler.json_trace_merger -o merged_trace_output.json path/to/input_file_1.json path/to/input_file_2.json ... To view the traces, open a Google Chrome brow...
composer-dev
composer/profiler/json_trace_merger.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Profiler to record system level metrics.""" from __future__ import annotations import threading import time from typing import TYPE_CHECKING, Dict, cast import psutil from composer.core import Callback if TYPE_CHECKING: from c...
composer-dev
composer/profiler/system_profiler.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Profiler Trace Handler.""" from __future__ import annotations import abc import pathlib from typing import TYPE_CHECKING, Dict, List, Tuple, Union from composer.core.callback import Callback if TYPE_CHECKING: from composer.core...
composer-dev
composer/profiler/trace_handler.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Composer Profiler.""" from __future__ import annotations import logging import pathlib from typing import TYPE_CHECKING, Callable, Dict, List, Sequence, Tuple, Union from composer.profiler.marker import Marker from composer.profiler...
composer-dev
composer/profiler/profiler.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Functional API for applying algorithms in your own training loop. .. code-block:: python from composer import functional as cf from torchvision import models model = models.resnet50() # replace some layers with blur...
composer-dev
composer/functional/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Helpers for running distributed data parallel training.""" import collections import logging import warnings from contextlib import contextmanager, nullcontext from typing import Any, Callable, ContextManager, Dict, Optional, Sequence...
composer-dev
composer/trainer/dist_strategy.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 # Released under BSD 3-Clause License, # Copyright (c) Facebook, Inc. and its affiliates. """Updates FSDPs _auto_wrap to enable module_kwargs and custom process_group cache.""" import functools import warnings from typing import Any, Ca...
composer-dev
composer/trainer/mosaic_fsdp.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Helpers for the `DeepSpeed <https://www.deepspeed.ai>`_ integration with Composer.""" import copy import warnings from typing import Any, Dict, cast import torch import torch.utils.data from composer.core import Batch, Precision, St...
composer-dev
composer/trainer/_deepspeed.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Train models with flexible insertion of algorithms.""" from composer.trainer.trainer import Trainer __all__ = ['Trainer']
composer-dev
composer/trainer/__init__.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 # Source code is compiled from a modified version of: # https://github.com/pytorch/pytorch/blob/v1.13.0/torch/nn/modules/module.py # Link to PyTorch License File: https://github.com/pytorch/pytorch/blob/master/LICENSE # TODO: This code wi...
composer-dev
composer/trainer/meta_safe_apply.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 from collections import defaultdict from typing import Optional, Union import torch from torch.cuda.amp.grad_scaler import GradScaler, OptState, _refresh_per_optimizer_state from torch.optim import Optimizer from composer.utils import d...
composer-dev
composer/trainer/_scaler.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 from collections import Counter from torch.optim.lr_scheduler import CosineAnnealingLR, CosineAnnealingWarmRestarts, ExponentialLR, MultiStepLR, StepLR from composer.core import PyTorchScheduler def scale_pytorch_scheduler(scheduler: ...
composer-dev
composer/trainer/_scale_schedule.py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Train models.""" from __future__ import annotations import collections.abc import contextlib import datetime import itertools import logging import os import random import re import time import warnings from collections import defaul...
composer-dev
composer/trainer/trainer.py