id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
21,100
from typing import Optional from sparseml.pytorch import recipe_template The provided code snippet includes necessary dependencies for implementing the `create_sparse_transfer_recipe` function. Write a Python function `def create_sparse_transfer_recipe( model: Optional["Module"] = None, # noqa: F821 quant: bo...
Convenience function to create a sparse transfer recipe :param model: an instantiated PyTorch Module, or the local path to a torch.jit loadable *.pt file, if supplied then the recipe is built according to this architecture :param quant: `True` if quantization needs to be applied else `False`. Defaults to `True` :param ...
21,101
from typing import Optional from sparseml.pytorch import recipe_template The provided code snippet includes necessary dependencies for implementing the `create_pruning_recipe` function. Write a Python function `def create_pruning_recipe( model: Optional["Module"] = None, # noqa: F821 method: str = "true", ...
Convenience function to create a pruning recipe :param model: an instantiated PyTorch Module, or the local path to a torch.jit loadable *.pt file, if supplied then the recipe is built according to this architecture :param method: pruning algorithm to use in the recipe, can be any of the following, `true` (represents Ma...
21,102
from typing import Optional from sparseml.pytorch import recipe_template The provided code snippet includes necessary dependencies for implementing the `create_quantization_recipe` function. Write a Python function `def create_quantization_recipe( model: Optional["Module"] = None, # noqa: F821 method: bool = ...
Convenience function to create a quantization recipe :param model: an instantiated PyTorch Module, or the local path to a torch.jit loadable *.pt file, if supplied then the recipe is built according to this architecture :param method: `True` if quantization needs to be applied else `False`. Defaults to `True` :param lr...
21,103
import os from typing import Any, Dict import numpy import torch from torch import device as device_class from ultralytics.yolo.utils import LOGGER EP_list = ["CUDAExecutionProvider", "CPUExecutionProvider"] def preprocess( batch: Dict[str, Any], device: device_class, half: bool = False ) -> Dict[str, Any]: """...
Export sample model input and output for testing with the DeepSparse Engine :param data_loader: path to data loader to take samples from :param model: model to be exported. Used to generate torch outputs :param save_dir: directory to save samples to :param device: device to run the inference (output generation) on :par...
21,104
import glob import os import warnings from argparse import Namespace from typing import Any, Dict import yaml from ultralytics.yolo.data.dataloaders.v5loader import create_dataloader from ultralytics.yolo.data.utils import ROOT from ultralytics.yolo.engine.model import DetectionModel from ultralytics.yolo.engine.traine...
Checks if the argument 'data' is coco128.yaml and if so, replaces it with coco128-seg.yaml. :param args: arguments to check :return: the updated arguments
21,105
import glob import os import warnings from argparse import Namespace from typing import Any, Dict import yaml from ultralytics.yolo.data.dataloaders.v5loader import create_dataloader from ultralytics.yolo.data.utils import ROOT from ultralytics.yolo.engine.model import DetectionModel from ultralytics.yolo.engine.traine...
null
21,106
import glob import os import warnings from argparse import Namespace from typing import Any, Dict import yaml from ultralytics.yolo.data.dataloaders.v5loader import create_dataloader from ultralytics.yolo.data.utils import ROOT from ultralytics.yolo.engine.model import DetectionModel from ultralytics.yolo.engine.traine...
Given a dataset name, fetch the yaml config for the dataset from the Ultralytics dataset repo, overwrite its 'path' attribute (dataset root dir) to point to the `dataset_path` and finally save it to the current working directory. This allows to create load data yaml config files that point to the arbitrary directories ...
21,107
import os import re import shutil import subprocess import sys import tempfile import warnings from copy import copy, deepcopy from datetime import datetime, timedelta from functools import partial from pathlib import Path from typing import List, Optional import torch from sparseml.optim.helpers import load_recipe_yam...
Generates and returns command for distributed training.
21,108
import os import re import shutil import subprocess import sys import tempfile import warnings from copy import copy, deepcopy from datetime import datetime, timedelta from functools import partial from pathlib import Path from typing import List, Optional import torch from sparseml.optim.helpers import load_recipe_yam...
null
21,109
import functools from typing import Optional from sparseml.base import check_version _DEF_TF_MIN_VERSION = "2.1.0" _DEF_KERAS_MIN_VERSION = "2.4.3" def check_keras_install( min_tf_version: Optional[str] = _DEF_TF_MIN_VERSION, max_tf_version: Optional[str] = None, min_native_version: Optional[str] = _DEF_KER...
Decorator function to require use of keras. Will check that keras package is installed and within the bounding ranges of min_version and max_version if they are set before calling the wrapped function. See :func:`check_keras_install` for more info. :param min_tf_version: The minimum version for keras that it must be gr...
21,110
import functools from typing import Optional from sparseml.base import check_version _KERAS2ONNX_MIN_VERSION = "1.0.0" def check_keras2onnx_install( min_version: Optional[str] = _KERAS2ONNX_MIN_VERSION, max_version: Optional[str] = None, raise_on_error: bool = True, ) -> bool: """ Check that the ker...
Decorator function to require use of keras2onnx. Will check that keras2onnx package is installed and within the bounding ranges of min_version and max_version if they are set before calling the wrapped function. See :func:`check_keras2onnx_install` for more info. param min_version: The minimum version for keras2onnx th...
21,111
import logging from sparseml.sparsification import SparsificationInfo _LOGGER = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `sparsification_info` function. Write a Python function `def sparsification_info() -> SparsificationInfo` to solve the following pro...
Load the available setup for sparsifying model within keras. :return: The sparsification info for the keras framework :rtype: SparsificationInfo
21,112
from typing import Tuple import tensorflow The provided code snippet includes necessary dependencies for implementing the `random_scaling_crop` function. Write a Python function `def random_scaling_crop( scale_range: Tuple[int, int] = (0.8, 1.0), ratio_range: Tuple[int, int] = (3.0 / 4.0, 4.0 / 3.0), )` to sol...
Random crop implementation which also randomly scales the crop taken as well as the aspect ratio of the crop. :param scale_range: the (min, max) of the crop scales to take from the orig image :param ratio_range: the (min, max) of the aspect ratios to take from the orig image :return: the callable function for random sc...
21,113
import random from typing import Tuple, Union import tensorflow as tf from sparseml.keras.datasets.classification import ( ImageFolderDataset, SplitsTransforms, imagenet_normalizer, ) from sparseml.keras.datasets.helpers import random_scaling_crop from sparseml.keras.datasets.registry import DatasetRegistry...
null
21,114
import random from typing import Tuple, Union import tensorflow as tf from sparseml.keras.datasets.classification import ( ImageFolderDataset, SplitsTransforms, imagenet_normalizer, ) from sparseml.keras.datasets.helpers import random_scaling_crop from sparseml.keras.datasets.registry import DatasetRegistry...
null
21,115
import glob import os import random from typing import Callable, Iterable, NamedTuple, Tuple, Union import numpy import tensorflow from sparseml.keras.datasets.dataset import Dataset from sparseml.keras.datasets.helpers import random_scaling_crop from sparseml.keras.datasets.registry import DatasetRegistry from sparsem...
null
21,116
def get_layer_name_from_param(param: str): known_weights = ["kernel", "bias"] pos = param.rfind("/") if pos > -1: suff = param[pos + 1 :] found = False for s in known_weights: colon_pos = suff.rfind(":") if suff[:colon_pos] == s: found = True...
null
21,117
import abc import collections import inspect from typing import List, Union import tensorflow from sparseml.keras.optim.mask_pruning_creator import ( PruningMaskCreator, load_mask_creator, ) from sparseml.keras.utils import keras _LAYER_PRUNABLE_PARAMS_MAP = { keras.layers.Conv1D: ["kernel"], keras.laye...
null
21,118
import abc import collections import inspect from typing import List, Union import tensorflow from sparseml.keras.optim.mask_pruning_creator import ( PruningMaskCreator, load_mask_creator, ) from sparseml.keras.utils import keras class MaskedLayer(keras.layers.Wrapper): """ Masked layer is a layer wrapp...
Remove pruning masks from a model that was pruned using the MaskedLayer logic :param model: a model that was pruned using MaskedLayer :return: the original model with pruned weights
21,119
from typing import List, Tuple, Union from tensorflow import Tensor from sparseml.keras.utils import KerasLogger, keras from sparseml.optim import ( BaseModifier, BaseScheduled, BaseUpdate, ModifierProp, ModifierYAML, ) from sparseml.utils import KERAS_FRAMEWORK The provided code snippet includes n...
:param epoch: the (fractional) epoch to convert to the proper number of steps :param steps_per_epoch: number of steps (batches) taken per epoch while training :param min_epoch: if the epoch is less than this, will be set to it. Default 0 :return: the number of steps representing the epoch and state of the epoch
21,120
from abc import ABC, abstractmethod from typing import Any, Callable, Iterable, List, Tuple, Union import numpy import tensorflow class PruningMaskCreator(ABC): """ Base abstract class for a sparsity mask creator. Subclasses should define all methods for creating masks and their initializers """ def...
:param obj: Formatted string or iterable of block_shape specifying SparsityMaskCreator object to return :return: SparsityMaskCreator object created from obj
21,121
import logging from typing import Any from sparseml.base import Framework, get_version from sparseml.framework import FrameworkInferenceProviderInfo, FrameworkInfo from sparseml.keras.base import check_keras_install, is_native_keras, keras, tensorflow from sparseml.keras.sparsification import sparsification_info from s...
:param item: The item to detect the support for :type item: Any :return: True if the item is supported by keras, False otherwise :rtype: bool
21,122
import logging from typing import Any from sparseml.base import Framework, get_version from sparseml.framework import FrameworkInferenceProviderInfo, FrameworkInfo from sparseml.keras.base import check_keras_install, is_native_keras, keras, tensorflow from sparseml.keras.sparsification import sparsification_info from s...
Detect the information for the keras framework such as package versions, availability for core actions such as training and inference, sparsification support, and inference provider support. :return: The framework info for keras :rtype: FrameworkInfo
21,123
from inspect import getmembers, isfunction from typing import Union from sparseml import get_main_logger from sparseml.keras.models.registry import ModelRegistry from sparseml.keras.utils import keras _supported_model_funcs = ["ResNet50"] def _registry_constructor_wrapper(key, model_func): # wraps the keras_applica...
null
21,124
from typing import List, Union import tensorflow from tensorflow.keras import backend as K from tensorflow.keras import layers from tensorflow.keras.models import Model from sparseml.keras.models.registry import ModelRegistry from sparseml.keras.utils import keras BN_EPSILON = 1e-5 def _expand_name(prefix: str, suffix:...
null
21,125
from typing import List, Union import tensorflow from tensorflow.keras import backend as K from tensorflow.keras import layers from tensorflow.keras.models import Model from sparseml.keras.models.registry import ModelRegistry from sparseml.keras.utils import keras class ResNetSection(object): """ Settings to de...
Standard ResNet50 implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the ResNet architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param num_classes: The number of classes to classify :param class_type: One of [singl...
21,126
from typing import List, Union import tensorflow from tensorflow.keras import backend as K from tensorflow.keras import layers from tensorflow.keras.models import Model from sparseml.keras.models.registry import ModelRegistry from sparseml.keras.utils import keras class ResNetSection(object): """ Settings to de...
Standard ResNet101 implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the ResNet architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param num_classes: The number of classes to classify :param class_type: One of [sing...
21,127
from typing import List, Union import tensorflow from tensorflow.keras import backend as K from tensorflow.keras import layers from tensorflow.keras.models import Model from sparseml.keras.models.registry import ModelRegistry from sparseml.keras.utils import keras class ResNetSection(object): """ Settings to de...
Standard ResNet152 implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the ResNet architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param num_classes: The number of classes to classify :param class_type: One of [sing...
21,128
import tensorflow from sparseml.keras.utils import keras The provided code snippet includes necessary dependencies for implementing the `sparsity` function. Write a Python function `def sparsity(model: keras.Model)` to solve the following problem: Retrieve sparsity of a Keras model :param model: a Keras model :return:...
Retrieve sparsity of a Keras model :param model: a Keras model :return: (1) model sparsity, (2) dictionary of layer sparsity
21,129
import tensorflow def assign(lhs, rhs, name=None): if hasattr(tensorflow, "assign"): return tensorflow.assign(lhs, rhs, name=name) else: return lhs.assign(rhs, name=name)
null
21,130
import threading from contextlib import contextmanager from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union from sparseml.core.event import EventType from sparseml.core.framework import Framework from sparseml.core.helpers import log_model_info, should_log_model_info from spar...
A method to initialize the active session for sparsification :param framework: the framework to use for the sparsification :param recipe: the recipe to use for the sparsification, can be a path to a recipe file, a raw recipe string, a recipe object, or a list of recipe objects. :param recipe_stage: the stage to target ...
21,131
import threading from contextlib import contextmanager from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union from sparseml.core.event import EventType from sparseml.core.framework import Framework from sparseml.core.helpers import log_model_info, should_log_model_info from spar...
Method to finalize the active session for sparsification :param kwargs: additional kwargs to pass to the lifecycle's finalize method :return: the modified state of the active session after finalizing
21,132
import json import logging import os import re from dataclasses import dataclass from typing import Any, Dict, List, Optional, Union import yaml from pydantic import Field, root_validator from sparseml.core.framework import Framework from sparseml.core.modifier import StageModifiers from sparseml.core.modifier.modifier...
null
21,133
import json import logging import os import re from dataclasses import dataclass from typing import Any, Dict, List, Optional, Union import yaml from pydantic import Field, root_validator from sparseml.core.framework import Framework from sparseml.core.modifier import StageModifiers from sparseml.core.modifier.modifier...
extract YAML front matter from markdown recipe card. Copied from sparseml.optim.helpers:_load_yaml_str_from_file :param file_path: path to recipe file :param yaml_str: string read from file_path :return: parsed yaml_str with README info removed
21,134
import json import logging import os import re from dataclasses import dataclass from typing import Any, Dict, List, Optional, Union import yaml from pydantic import Field, root_validator from sparseml.core.framework import Framework from sparseml.core.modifier import StageModifiers from sparseml.core.modifier.modifier...
Create a recipe string from a list of Modifier instances (Note: this pathway assumes there's only one stage in the recipe associated by the modifier_group_name, if None, a dummy default group_name will be assigned.) :param modifiers: The list of Modifier instances :param modifier_group_name: The stage_name of the recip...
21,135
import logging import os import time import warnings from abc import ABC from contextlib import contextmanager from datetime import datetime from logging import CRITICAL, DEBUG, ERROR, INFO, WARN, Logger from pathlib import Path from types import ModuleType from typing import Any, Callable, Dict, List, Optional, Union ...
null
21,136
from typing import Literal, Optional, Union LogStepType = Union[int, float, None] The provided code snippet includes necessary dependencies for implementing the `log_ready` function. Write a Python function `def log_ready( current_log_step: Optional[LogStepType], last_log_step: Optional[LogStepType], log_f...
Check if we are ready to log again based on the given parameters (Stateless version of FrequencyManager().log_ready) Conditions for readiness: - log frequency is not None - current log step is None - current log step greater than or equal to the last log step plus the log frequency - if check_model_update is True, then...
21,137
from typing import Literal, Optional, Union The provided code snippet includes necessary dependencies for implementing the `_basic_normalization` function. Write a Python function `def _basic_normalization(value: str) -> str` to solve the following problem: Basic normalization for string values. Removes leading and tr...
Basic normalization for string values. Removes leading and trailing whitespace and converts to lowercase. :param value: The value to normalize :return: The normalized value
21,138
from typing import Any, Generator, Optional, Tuple, Union from sparseml.core.logger import LoggerManager from sparseml.core.model.base import ModifiableModel from sparseml.core.state import State class ModifiableModel(Generic[MT, LT, PT], MultiFrameworkObject): """ A MultiFrameWorkObject for holding a model. A...
Check if we should log model level info Criteria: - model has a loggable_items method - state has a logger manager - logger manager is ready to log based on cadence and last log epoch :param model: The model whose info we want to log :param loggers: The logger manager to log to :param current_log_step: The current epoc...
21,139
from typing import Any, Generator, Optional, Tuple, Union from sparseml.core.logger import LoggerManager from sparseml.core.model.base import ModifiableModel from sparseml.core.state import State def _log_current_step( logger_manager: LoggerManager, current_log_step: Union[float, int] ): """ Log the Current...
Log model level info to the logger Relies on `state.model` having a `loggable_items` method that returns a generator of tuples of the loggable item name and value. Also relies on `state.loggers` being a `LoggerManager` instance. :param state: The current state of sparsification :param current_log_step: The current log ...
21,140
from contextlib import contextmanager import sparseml.core.session as session_manager The provided code snippet includes necessary dependencies for implementing the `session_context_manager` function. Write a Python function `def session_context_manager()` to solve the following problem: A context manager to setup a f...
A context manager to setup a fresh session and reset it after the context is exited.
21,141
import copy import logging from typing import List, Optional, Set, Tuple, Union import numpy import onnx from onnx import ModelProto, NodeProto, TensorProto, ValueInfoProto, numpy_helper from sparseml.exporters.transforms.onnx_transform import OnnxTransform from sparseml.onnx.utils import ONNXGraph ALLOWED_NODES_FOLLOW...
Injects a cache (value or key) into the graph for a given Matmul node. :param model: Model to update :param node: MatMul node that follows the cache injection point :param cache_input_idx: Index of the input (where the cache will be injected) to the MatMul :param cache_input_name: Name of cache input :param cache_outpu...
21,142
import copy import logging from typing import List, Optional, Set, Tuple, Union import numpy import onnx from onnx import ModelProto, NodeProto, TensorProto, ValueInfoProto, numpy_helper from sparseml.exporters.transforms.onnx_transform import OnnxTransform from sparseml.onnx.utils import ONNXGraph def is_value_matmul(...
null
21,143
import copy import logging from typing import List, Optional, Set, Tuple, Union import numpy import onnx from onnx import ModelProto, NodeProto, TensorProto, ValueInfoProto, numpy_helper from sparseml.exporters.transforms.onnx_transform import OnnxTransform from sparseml.onnx.utils import ONNXGraph def _value_input_id...
null
21,144
import copy import logging from typing import List, Optional, Set, Tuple, Union import numpy import onnx from onnx import ModelProto, NodeProto, TensorProto, ValueInfoProto, numpy_helper from sparseml.exporters.transforms.onnx_transform import OnnxTransform from sparseml.onnx.utils import ONNXGraph def _use_uint8_if_q...
null
21,145
import copy import logging from typing import List, Optional, Set, Tuple, Union import numpy import onnx from onnx import ModelProto, NodeProto, TensorProto, ValueInfoProto, numpy_helper from sparseml.exporters.transforms.onnx_transform import OnnxTransform from sparseml.onnx.utils import ONNXGraph def _set_attention_...
null
21,146
import json import logging from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Type, Union from pydantic import BaseModel, Field from sparseml.exporters.transforms import OnnxTransform from sparseml.exporters.transforms.kv_cache.transforms_codegen import ( AdditionalTransformsCodeGen, ) fr...
Get the kv cache config for the model at the given path. :param model_path: The path to the directory containing the transformers model. It is assumed that the `config.json` file (as supplied by the transformers models) is in this directory. :param supported_configs: The list of supported configs. If the model type is ...
21,147
import logging from typing import List from onnx import ModelProto, NodeProto from sparseml.exporters.transforms.onnx_transform import OnnxTransform from sparseml.onnx.utils import ONNXGraph _LOGGER = logging.getLogger(__name__) def _delete_quantize_nodes(graph: ONNXGraph, quantize_nodes: List[NodeProto]): # delet...
null
21,148
from typing import List, Optional, Union from onnx import NodeProto, TensorProto from sparseml.onnx.utils import ONNXGraph _OPTIONAL_TAG = "Optional-" The provided code snippet includes necessary dependencies for implementing the `optional_node` function. Write a Python function `def optional_node(op_type: str) -> str...
Tells :func:`get_structural_matches` that this op type is an optional one. e.g. ```python get_structural_matches( ..., children_ops=[ [ optional_node("Transpose") "QuantizeLinear", ] ] ) ```
21,149
from typing import List, Optional, Union from onnx import NodeProto, TensorProto from sparseml.onnx.utils import ONNXGraph _ANY_TAG = "Any-" The provided code snippet includes necessary dependencies for implementing the `any_of` function. Write a Python function `def any_of(*op_type: str) -> str` to solve the followin...
Tells :func:`get_structural_matches` that this can be a set of op types ```python get_structural_matches( ..., children_ops=[ [ any_of("QuantizeLinear", "DequantizeLinear"), ] ] ) ```
21,150
from typing import List, Optional, Union from onnx import NodeProto, TensorProto from sparseml.onnx.utils import ONNXGraph def _match_structure( graph: ONNXGraph, node: Union[NodeProto, TensorProto], op_type: str, parent_ops: Optional[List[List[str]]] = None, children_ops: Optional[List[List[str]]] ...
Gathers all nodes in the `graph` that match the `op_type` and the have the specified parent/children structure, controlled via parent_ops/children_ops. ### op_type example A simple example just matching against op_type: ```python matches = get_structural_matches(graph, op_type="Identity") for match in matches: id_node ...
21,151
import logging from typing import Any, List, NamedTuple, Set, Union import numpy from onnx import AttributeProto, ModelProto, NodeProto, numpy_helper from sparseml.onnx.utils import ONNXGraph, remove_node_and_params_from_graph QUANTIZE_OP_NAMES = ["QuantizeLinear", "DequantizeLinear"] QuantizationParams = NamedTuple( ...
:param model: ONNX model to read from or ONNXGraph object :param node: A QuantizeLinear or DequantizeLinear Node :param include_target: Set True include quantization target. If False, target value will be returned as None. Default is None :return: QuantizationParams object with scale and zero point, will include the qu...
21,152
import logging from typing import Any, List, NamedTuple, Set, Union import numpy from onnx import AttributeProto, ModelProto, NodeProto, numpy_helper from sparseml.onnx.utils import ONNXGraph, remove_node_and_params_from_graph QUANTIZE_OP_NAMES = ["QuantizeLinear", "DequantizeLinear"] The provided code snippet include...
Deletes a QuantizeLinear or DequantizeLinear and its parameters from the model :param model: ONNX model to modify :param node: the QuantizeLinear or DequantizeLinear node to delete :param keep_weight: set true to not delete the weight param possibly stored as an initializer to the first input of this node
21,153
import logging from typing import Any, List, NamedTuple, Set, Union import numpy from onnx import AttributeProto, ModelProto, NodeProto, numpy_helper from sparseml.onnx.utils import ONNXGraph, remove_node_and_params_from_graph The provided code snippet includes necessary dependencies for implementing the `assert_node_...
Checks if a node is of the given op type :param node: the node to check :param op: the operation type to check for :return: True if the node has the given op type, False otherwise
21,154
from typing import Optional, Tuple import numpy import onnx from onnx import ModelProto, NodeProto, TensorProto, numpy_helper from sparseml.exporters.transforms.utils.helpers import ( QuantizationParams, attribute_to_kwarg, quantize_array, ) def _create_mul_node( cast_node_output: str, rescale_scale...
Helper function for conversion of qat parameterized gemms, matmuls, or convs to conv/matmul integer add blocks. Adds new quantized ops to graph, does not perform any checks or deletions (should be called by the operator main conversion function)
21,155
from typing import Union import torch.nn.functional as TF from torch import Tensor, clamp from torch.nn import LeakyReLU, Module, PReLU from torch.nn import ReLU as TReLU from torch.nn import ReLU6 as TReLU6 The provided code snippet includes necessary dependencies for implementing the `swish` function. Write a Python...
Swish layer functional implementation: x * sigmoid(x). More information can be found in the paper `here <https://arxiv.org/abs/1710.05941>`__. :param x_tens: the input tensor to perform the swish op on :return: the output of x_tens * sigmoid(x_tens)
21,156
from typing import Union import torch.nn.functional as TF from torch import Tensor, clamp from torch.nn import LeakyReLU, Module, PReLU from torch.nn import ReLU as TReLU from torch.nn import ReLU6 as TReLU6 The provided code snippet includes necessary dependencies for implementing the `hard_swish` function. Write a P...
| Hardswish layer implementation: | 0 for x <= -3 | x for x >= 3 | x * (x + 3) / 6 otherwise More information can be found in the paper `here <https://arxiv.org/abs/1905.02244>`__. :param x_tens: the input tensor to perform the swish op on :param inplace: True to run the operation in place in memory, False otherwise :r...
21,157
from typing import Union import torch.nn.functional as TF from torch import Tensor, clamp from torch.nn import LeakyReLU, Module, PReLU from torch.nn import ReLU as TReLU from torch.nn import ReLU6 as TReLU6 def create_activation( act_type: str, inplace: bool, num_channels: int, **kwargs ) -> Module: """ Cr...
General function to replace the activation for a specific layer in a Module with a new one. :param module: the module to replace the activation function in :param name: the name of the layer to replace the activation for :param act_type: the type of activation to replace with; options: [relu, relu6, prelu, lrelu, swish...
21,158
from typing import Union import torch.nn.functional as TF from torch import Tensor, clamp from torch.nn import LeakyReLU, Module, PReLU from torch.nn import ReLU as TReLU from torch.nn import ReLU6 as TReLU6 def create_activation( act_type: str, inplace: bool, num_channels: int, **kwargs ) -> Module: """ Cr...
General function to replace all activation functions in a Module with a new one. :param module: the module to replace the activation function in :param act_type: the type of activation to replace with; options: [relu, relu6, prelu, lrelu, swish, silu] :param inplace: True to create the activation as an inplace, False o...
21,159
from typing import Dict, List, Union import torch import torch.nn.functional as TF from torch import Tensor from torch.nn import Module, Parameter, ReLU def _apply_permuted_channels(apply_fn, tens: Tensor, **kwargs): if len(tens.shape) < 3: return apply_fn(tens, **kwargs) perm = [ind for ind in range(...
null
21,160
from typing import Dict, List, Union import torch import torch.nn.functional as TF from torch import Tensor from torch.nn import Module, Parameter, ReLU def fat_relu(tens: Tensor, threshold: Union[Tensor, float], inplace: bool) -> Tensor: """ Apply a FATReLU function to a tensor (forced activation threshold): ...
Apply a piecewise separable FATReLU function to a tensor (forced activation threshold): f(x, t, c) = 0 if x <= (t - t/c); x if x >= t; c(x - (t - t/c)) if x > (t - t/c) and x < t :param tens: the tensor to apply the piecewise fat relu to :param threshold: the threshold at which all values will be zero or interpolated b...
21,161
from typing import Dict, List, Union import torch import torch.nn.functional as TF from torch import Tensor from torch.nn import Module, Parameter, ReLU The provided code snippet includes necessary dependencies for implementing the `fat_sig_relu` function. Write a Python function `def fat_sig_relu(tens: Tensor, thresh...
Create a sigmoid approximated FATReLU function to a tensor (forced activation threshold): f(x, t, c) = x / e^(c*(t-x)) Note: there is no option for inplace with this function. :param tens: the tensor to apply the sigmoid fat relu to :param threshold: the threshold at which all values will be zero or approximated in the...
21,162
from typing import Dict, List, Union import torch import torch.nn.functional as TF from torch import Tensor from torch.nn import Module, Parameter, ReLU The provided code snippet includes necessary dependencies for implementing the `fat_exp_relu` function. Write a Python function `def fat_exp_relu(tens: Tensor, thresh...
Create a piecewise separable exp approximated FATReLU function to a tensor (forced activation threshold): f(x, t, c) = 0 if x <= 0; = x if x >= t; = x * e^(c(x-t)) if x > 0 and x < t Note: there is no option for inplace with this function :param tens: the tensor to apply the exponential fat relu to :param threshold: th...
21,163
from typing import Dict, List, Union import torch import torch.nn.functional as TF from torch import Tensor from torch.nn import Module, Parameter, ReLU class FATReLU(Module): """ Applies a FAT ReLU (forced activation threshold) over the input. Instead of setting all negative values to 0 like with ReLU, ...
Replace all of the ReLUs in a module with FATReLU instances. Note: only works if the ReLUs are layers in the module, will not work with torch.functional ones. :param module: the module to replace all ReLUs with FATReLU :param kwargs: the kwargs to pass to the FATReLU constructor :return: a dictionary containing a mappi...
21,164
import logging from collections import defaultdict from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from sparseml.pytorch.recipe_template.description import DESCRIPTION from sparseml.pytorch.sparsification import ( ACDCPruningModifier, ...
Returns a valid yaml or md recipe based on specified arguments :param pruning: optional pruning algorithm to use in the recipe, can be any of the following,`true` (represents Magnitude/Global-Magnitude pruning according to global_sparsity), `false` (No pruning), `acdc`, `mfac`, `movement`, `obs` or `constant`. Can also...
21,165
import json import os from typing import Any, Dict, Optional, Union import torch from torch.nn import Module from torch.utils.data import DataLoader from tqdm import tqdm import click from sparseml import get_main_logger from sparseml.pytorch.image_classification.utils import cli_helpers, helpers from sparseml.pytorch....
Utility method to export the model and data :param model: loaded model architecture to export :param val_loader: A DataLoader for validation data :param save_dir: Directory to store checkpoints at during exporting process :param use_zipfile_serialization_if_available: Whether to use zipfile serialization during export ...
21,166
import json import os from typing import Any, Dict, Optional, Union import torch from torch.nn import Module from torch.utils.data import DataLoader from tqdm import tqdm import click from sparseml import get_main_logger from sparseml.pytorch.image_classification.utils import cli_helpers, helpers from sparseml.pytorch....
null
21,167
import json import os from typing import Any, Dict, Optional, Tuple, Union import torch import click from sparseml import get_main_logger from sparseml.pytorch.image_classification.utils import ( DEFAULT_OPTIMIZER, OPTIMIZERS, ImageClassificationTrainer, cli_helpers, helpers, ) from sparseml.pytorch...
Utility function to run the training loop :param trainer: The ImageClassificationTrainer object :param save_dir: The directory to save checkpoints to :param max_eval_steps: The number of steps to run for validation :param eval_mode: Whether to run in evaluation mode :param is_main_process: Whether this is the main proc...
21,168
import json import os from typing import Any, Dict, List, Optional, Union from torch.nn import Module from torch.utils.data import DataLoader import click from sparseml import get_main_logger from sparseml.pytorch.image_classification.utils import cli_helpers, helpers from sparseml.pytorch.optim import ( pruning_lo...
Utility function for pruning sensitivity analysis :param model: loaded model architecture to analyse :param train_loader: A DataLoader for training data :param save_dir: Directory to save results :param loggers: List of loggers to use during analysis :param approximate: Whether to use one shot analysis :param device: D...
21,169
import json import os from typing import Any, Dict, Optional, Union from torch.nn import Module from torch.optim import SGD from torch.utils.data import DataLoader import click from sparseml import get_main_logger from sparseml.pytorch.image_classification.utils import cli_helpers, helpers from sparseml.pytorch.optim i...
Utility function to run learning rate sensitivity analysis :param model: loaded model architecture to analyse :param train_loader: A DataLoader for training data :param save_dir: Directory to save results :param init_lr: Initial learning rate to use for analysis :param optim_args: Additional arguments to pass to the op...
21,170
import os from pathlib import Path from typing import Any, Callable, Dict, Optional, Tuple, Union import torch from pydantic import Field from sparseml.export.export_data import create_data_samples as create_data_samples_ from sparseml.integration_helper_functions import ( IntegrationHelperFunctions, Integratio...
A contract to create a model and optional dictionary of loaded_model_kwargs (any relevant objects created along with the model) :param source_path: Path to the model files :return: A tuple of the - torch model - (optionally) loaded_model_kwargs (any relevant objects created along with the model)
21,171
import os from pathlib import Path from typing import Any, Callable, Dict, Optional, Tuple, Union import torch from pydantic import Field from sparseml.export.export_data import create_data_samples as create_data_samples_ from sparseml.integration_helper_functions import ( IntegrationHelperFunctions, Integratio...
A contract to create a model and optional dictionary of loaded_data_loader_kwargs (any relevant objects created along with the data_loader) :param batch_size: The batch size to use for the dataloader creation :param device: The device to use for the model and dataloader instantiation :return: A tuple of the - a data_lo...
21,172
import os from pathlib import Path from typing import Any, Callable, Dict, Optional, Tuple, Union import torch from pydantic import Field from sparseml.export.export_data import create_data_samples as create_data_samples_ from sparseml.integration_helper_functions import ( IntegrationHelperFunctions, Integratio...
A contract to create a dummy input for a model :param data_loader: The validation dataloader to get a batch from. If None, a fake batch will be created :param image_size: The image size to use for the dummy input :return: The dummy input as a torch tensor
21,173
import os from pathlib import Path from typing import Any, Callable, Dict, Optional, Tuple, Union import torch from pydantic import Field from sparseml.export.export_data import create_data_samples as create_data_samples_ from sparseml.integration_helper_functions import ( IntegrationHelperFunctions, Integratio...
null
21,174
import json import os from typing import Any, Dict, Tuple import click The provided code snippet includes necessary dependencies for implementing the `parse_json_callback` function. Write a Python function `def parse_json_callback(ctx, params, value: str) -> Dict` to solve the following problem: Parse a json string in...
Parse a json string into a dictionary :param ctx: The click context :param params: The click params :param value: The json string to parse :return: The parsed dictionary
21,175
import json import os from typing import Any, Dict, Tuple import click The provided code snippet includes necessary dependencies for implementing the `create_dir_callback` function. Write a Python function `def create_dir_callback(ctx, params, value: str)` to solve the following problem: Create and return directory if...
Create and return directory if it doesn't exist. :param ctx: The click context :param params: The click params :param value: The value to create the directory from :returns: The directory path
21,176
import json import os from typing import Any, Dict, Tuple import click The provided code snippet includes necessary dependencies for implementing the `parse_into_tuple_of_ints` function. Write a Python function `def parse_into_tuple_of_ints(ctx, params, value) -> Tuple[int, ...]` to solve the following problem: Parse ...
Parse a string into a tuple of ints. :param ctx: The click context :param params: The click params :param value: The value to parse :return: Tuple of ints
21,177
import json import os from typing import Any, Dict, Tuple import click The provided code snippet includes necessary dependencies for implementing the `parameters_to_dict` function. Write a Python function `def parameters_to_dict(ctx) -> Dict[str, Any]` to solve the following problem: Grab all the click parameters as a...
Grab all the click parameters as a dict (where keys are parameter names and values are parameter values). :param ctx: The click context :return: Dictionary containing parameter names and values
21,178
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
Takes the `training_outputs_dir` (the directory where the pipeline saves its training artifacts), and saves the training artifacts to `output_dir` as a sparsezoo Model class object. :param output_dir: The output path where the artifacts are saved (adhering to the structure of sparsezoo Model class object) :param traini...
21,179
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
:param task: The current task being performed :param is_main_process: Whether this is the main process or not :param save_dir: The directory to save the model :param logs_dir: The directory to save logs :param arch_key: The architecture key of the image classification model :param model_tag: A str tag to optionally tag...
21,180
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
Retrieve the label-to-class-mapping for the chosen dataset If dataset is not recognized, returns None :param dataset: string identifier of the dataset (e.g. "imagenet") :return: mapping from labels to class strings if found. Otherwise None
21,181
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
:param checkpoint_path: Path to the checkpoint to load. `zoo` for downloading weights with respect to a SparseZoo recipe :param num_classes: Integer representing the number of output classes :param recipe_path: Path or SparseZoo stub to the recipe for downloading, respective model. Defaults to `None` :param arch_key: T...
21,182
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
:param train_dataset: dataset representing training data :param val_dataset: dataset representing validation data :param dataset: name of the dataset :param model_kwargs: keyword arguments used for model creation :return: An integer representing the number of classes
21,183
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
Utility method to read and return the arch_key from the checkpoint, if it is not passed and exists in the checkpoint. if passed the passed value is returned :param arch_key: Optional[str] The arch_key to use for the model :param checkpoint_path: Optional[str] The path to the checkpoint :return: str The arch_key to use ...
21,184
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
Utility method to initialize process group and set seeds :param local_rank: The local rank of the process
21,185
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
:return loss_wrapper: A Cross Entropy Loss Wrapper with extra metrics
21,186
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
Move model to device and wrap in DistributedDataParallel if necessary. :param device: device to move model to :param local_rank: local rank of current process :param model: model to move :param rank: rank of current process :return: A tuple of the following form (ddp_state, device, model)
21,187
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
Extract metadata from the training arguments. :param metadata_args: List of keys we are attempting to retrieve from `training_arg` and pass as metadata :param training_args_dict: Dictionary extracted from the TrainingArguments of the pipeline :return: metadata
21,188
import logging import os import warnings from contextlib import nullcontext from enum import Enum, auto, unique from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch.nn import Module from torch.optim import Optimizer from torch.utils.data import DataLoader, Dataset ...
null
21,189
import json import logging import os from typing import Any, Dict, List, Optional import torch from torch.nn import Module import sparseml.core.session as session_manager from sparseml.core.framework import Framework from sparseml.pytorch.sparsification.quantization.helpers import ( initialize_channel_wise_scale_zp...
Reload the model state dict from a specified checkpoint if provided :model: loaded pytorch module :checkpoint: path to checkpoint file to load
21,190
import json import logging import os from typing import Any, Dict, List, Optional import torch from torch.nn import Module import sparseml.core.session as session_manager from sparseml.core.framework import Framework from sparseml.pytorch.sparsification.quantization.helpers import ( initialize_channel_wise_scale_zp...
:return: pytorch module stored by the active SparseSession, or None if no session is active
21,191
import json import logging import os from typing import Any, Dict, List, Optional import torch from torch.nn import Module import sparseml.core.session as session_manager from sparseml.core.framework import Framework from sparseml.pytorch.sparsification.quantization.helpers import ( initialize_channel_wise_scale_zp...
Given a checkpoint directory for a staged run, get the list of stages that have completed in a prior run if the checkpoint_dir is a string :param checkpoint_dir: path to staged checkpoint :return: list of completed stage names
21,192
import json import logging import os from typing import Any, Dict, List, Optional import torch from torch.nn import Module import sparseml.core.session as session_manager from sparseml.core.framework import Framework from sparseml.pytorch.sparsification.quantization.helpers import ( initialize_channel_wise_scale_zp...
Save a list of completed stages to a checkpoint directory :param checkpoint_dir: model checkpoint directory to save stages to :param completed_stages: list of stage names that have been run
21,193
import collections import logging import os import warnings from copy import deepcopy from typing import Any, Dict, Iterable, List import onnx import torch from packaging import version from sparseml.exporters import transforms as sparseml_transforms from sparseml.exporters.base_exporter import BaseExporter from sparse...
Get name of output tensors :param out: outputs of the model :return: list of names
21,194
import collections import logging import os import warnings from copy import deepcopy from typing import Any, Dict, Iterable, List import onnx import torch from packaging import version from sparseml.exporters import transforms as sparseml_transforms from sparseml.exporters.base_exporter import BaseExporter from sparse...
null
21,195
import functools import os from typing import Optional from sparseml.base import check_version _TORCH_MIN_VERSION = "1.0.0" _TORCH_MAX_VERSION = os.environ.get("MAX_TORCH", "2.1.10") def check_torch_install( min_version: Optional[str] = _TORCH_MIN_VERSION, max_version: Optional[str] = _TORCH_MAX_VERSION, ra...
Decorator function to require use of torch. Will check that torch package is installed and within the bounding ranges of min_version and max_version if they are set before calling the wrapped function. See :func:`check_torch_install` for more info. :param min_version: The minimum version for torch that it must be great...
21,196
import functools import os from typing import Optional from sparseml.base import check_version def check_torchvision_install( min_version: Optional[str] = None, max_version: Optional[str] = None, raise_on_error: bool = True, ) -> bool: """ Check that the torchvision package is installed. If rais...
Decorator function to require use of torchvision. Will check that torchvision package is installed and within the bounding ranges of min_version and max_version if they are set before calling the wrapped function. See :func:`check_torchvision_install` for more info. :param min_version: The minimum version for torchvisi...
21,197
import random from abc import ABC, abstractmethod from copy import deepcopy from typing import List, Optional, Union import torch from torch import Tensor from sparseml.pytorch.utils import memory_aware_threshold class PruningMaskCreator(ABC): """ Base abstract class for a sparsity mask creator. Subclasses ...
:param mask_type: type of mask creator to use, can be 'unstructured', for unstructured mask creator, 'block4' for 1x4 block pruning, 'N:M' where N and M are integers for N:M pruning, or a list of two integers for custom block pruning (does not support padding) :return: mask creator object created from the mask type
21,198
import logging import math import os from abc import ABC, abstractmethod from functools import wraps from typing import Any, Dict, List, Optional, Union import torch import torch.distributed as dist from torch import Tensor from torch.nn import Module, Parameter from torch.nn.parallel.parallel_apply import parallel_app...
Determine which FisherInverse algorithm to use. :param grads: tensor of gradient samples to compute the Hessian inverse representation with. Should have shape (num_samples, num_parameters) :param damp: dampening factor, default is 1e-5 :param fisher_block_size: optional value to enable blocked computation of the Fisher...
21,199
import logging import math import os from abc import ABC, abstractmethod from functools import wraps from typing import Any, Dict, List, Optional, Union import torch import torch.distributed as dist from torch import Tensor from torch.nn import Module, Parameter from torch.nn.parallel.parallel_apply import parallel_app...
null