id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
21,500 | import functools
import os
from typing import Optional
from sparseml.base import check_version
_TF2ONNX_MIN_VERSION = "1.0.0"
def check_tf2onnx_install(
min_version: Optional[str] = _TF2ONNX_MIN_VERSION,
max_version: Optional[str] = None,
raise_on_error: bool = True,
) -> bool:
"""
Check that the tf... | Decorator function to require use of tf2onnx. Will check that tf2onnx 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_tf2onnx_install` for more info. :param min_version: The minimum version for tf2onnx that it must ... |
21,501 | 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 tensorflow. :return: The sparsification info for the tensorflow framework :rtype: SparsificationInfo |
21,502 | from typing import Tuple
from sparseml.tensorflow_v1.utils import tf_compat
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.08, 1.0), ratio_range: Tuple[int, int] =... | 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 :param name: name for the scope to put the o... |
21,503 | from typing import Tuple
from sparseml.tensorflow_v1.utils import tf_compat
def resize(image_size: Tuple[int, int], name: str = "resize"):
"""
Resize an image tensor to the desired size
:param image_size: a tuple containing the height, width to resize to
:param name: name for the scope to put the ops un... | Take a square crop centered in the a image :param padding: additional padding to apply to all sides of the image to crop away :param name: name for the scope to put the ops under :return: the callable function for square crop op, takes in the image and outputs the cropped image |
21,504 | from abc import ABCMeta, abstractmethod
from typing import Any, Callable, Dict, Iterable, List, Tuple
from sparseml.tensorflow_v1.utils import tf_compat
def _make_initializable_iterator(dataset: tf_compat.data.Dataset):
"""
Make initializable iterator with different versions of TF
:param dataset: the datase... | Create an iterators handle for switching between datasets easily while training. :param split_datasets: the datasets to create the splits and handle for :return: a tuple containing the handle that should be set with a feed dict, the iterator used to get the next batch, and a list of the iterators created from the split... |
21,505 | import os
import pickle
import tarfile
from typing import Union
import numpy as np
from PIL import Image
from tqdm import tqdm
from sparseml.tensorflow_v1.datasets.classification.imagefolder import (
ImageFolderDataset,
SplitsTransforms,
)
from sparseml.tensorflow_v1.datasets.registry import DatasetRegistry
fro... | The default preprocessing function for train set as defined in Resnet paper for Cifar datasets :param image: the image tensor :return: the preprocessed image |
21,506 | import os
import pickle
import tarfile
from typing import Union
import numpy as np
from PIL import Image
from tqdm import tqdm
from sparseml.tensorflow_v1.datasets.classification.imagefolder import (
ImageFolderDataset,
SplitsTransforms,
)
from sparseml.tensorflow_v1.datasets.registry import DatasetRegistry
fro... | The default preprocessing function for test set as defined in Resnet paper for Cifar datasets :param image: the image tensor :return: the preprocessed image |
21,507 | import glob
import os
import random
from typing import Callable, Dict, Iterable, NamedTuple, Tuple, Union
import numpy
from sparseml.tensorflow_v1.datasets.dataset import Dataset
from sparseml.tensorflow_v1.datasets.helpers import (
center_square_crop,
random_scaling_crop,
resize,
)
from sparseml.tensorflow... | Normalize an image using mean and std of the imagenet dataset :param img: The input image to normalize :return: The normalized image |
21,508 | import collections
from typing import Dict, List, Optional, Tuple
import numpy as np
from tensorflow.python.framework import tensor_util
from toposort import toposort
from sparseml.optim import AnalyzedLayerDesc
from sparseml.tensorflow_v1.utils.helpers import tf_compat
from sparseml.tensorflow_v1.utils.variable import... | Analyze a module at certain layers :param session: running session encapsulating the analyzed module :param graph: graph of the module; if None then the session is required, and the encapsulated graph is to be analyzed :param op_names: list of names of layers to be analyzed; if None then all layers are analyzed for an ... |
21,509 | from collections import namedtuple
from typing import Callable, Dict, List, Tuple, Union
import numpy
from tqdm import auto
from sparseml.optim import (
PruningLossSensitivityAnalysis,
default_pruning_sparsities_loss,
)
from sparseml.tensorflow_v1.optim.mask_creator_pruning import (
PruningMaskCreator,
... | Edit the graph for to inject pruning ops and vars to allow for a ks loss sensitivity analysis. Note: this must be run outside of a session for it to take effect. :param graph: the graph to inject pruning ops and vars into, if not supplied uses get_default_graph() :param var_names: List of variable names or regex patter... |
21,510 | from collections import namedtuple
from typing import Callable, Dict, List, Tuple, Union
import numpy
from tqdm import auto
from sparseml.optim import (
PruningLossSensitivityAnalysis,
default_pruning_sparsities_loss,
)
from sparseml.tensorflow_v1.optim.mask_creator_pruning import (
PruningMaskCreator,
... | Approximated kernel sparsity (pruning) loss analysis for a given model. Returns the results for each prunable param (conv, linear) in the model. Approximated by taking the magnitudes of the weights. :param graph: the graph to inject pruning ops and vars into, if not supplied uses get_default_graph() :param sess: the se... |
21,511 | from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple, Union
from sparseml.sparsification import LearningRateModifier as BaseLearningRateModifier
from sparseml.sparsification import (
SetLearningRateModifier as BaseSetLearningRateModifier,
)
from sparseml.tensorflow_v1.optim.modifier import ... | null |
21,512 | from collections import namedtuple
from typing import List, Tuple
from sparseml.tensorflow_v1.optim.mask_creator_pruning import PruningMaskCreator
from sparseml.tensorflow_v1.utils import (
clean_tensor_name,
get_ops_and_inputs_by_name_or_regex,
get_tensor_var,
is_prunable_op,
tf_compat,
tf_comp... | Create TensorBoard summary ops in the current graph for the given list of PruningOpVars. :param pruning_op_vars: the list of named tuples containing the masked input to the pruned op to record sparsity for in TensorBoard. :return: the created summaries for the pruned op vars |
21,513 | from collections import namedtuple
from typing import List, Tuple
from sparseml.tensorflow_v1.optim.mask_creator_pruning import PruningMaskCreator
from sparseml.tensorflow_v1.utils import (
clean_tensor_name,
get_ops_and_inputs_by_name_or_regex,
get_tensor_var,
is_prunable_op,
tf_compat,
tf_comp... | Apply the masks to the original ops input var so that it can be saved with the desired sparsity for later. :param pruning_op_vars: the list of named tuples containing the sparse mask and the op variable to apply the sparse mask to :param ks_group: the group to create the assign ops under :param sess: the session to use... |
21,514 | from collections import namedtuple
from typing import List, Tuple
from sparseml.tensorflow_v1.optim.mask_creator_pruning import PruningMaskCreator
from sparseml.tensorflow_v1.utils import (
clean_tensor_name,
get_ops_and_inputs_by_name_or_regex,
get_tensor_var,
is_prunable_op,
tf_compat,
tf_comp... | Gets or creates model pruning (kernel sparsity) ops and vars in the graph to be applied over a specific schedule. Creates them for the var_names in the graph such that they follow a schedule from begin_step to end_step starting at init_sparsity and ending at final_sparsity. :param graph: the tf graph to pull the operat... |
21,515 | from collections import namedtuple
from typing import List, Tuple
from sparseml.tensorflow_v1.optim.mask_creator_pruning import PruningMaskCreator
from sparseml.tensorflow_v1.utils import (
clean_tensor_name,
get_ops_and_inputs_by_name_or_regex,
get_tensor_var,
is_prunable_op,
tf_compat,
tf_comp... | Creates constant model pruning ops. Does not modify the graph. :param graph: the tf graph to pull the operator out of for applying the pruning to :param global_step: the global optimizer step for the training graph :param var_names: a list of names or regex patterns to create constant ops for within the graph :param be... |
21,516 | from typing import Any, Dict, List, Tuple, Union
from sparseml.optim import (
BaseModifier,
BaseScheduled,
BaseUpdate,
ModifierProp,
ModifierYAML,
)
from sparseml.tensorflow_v1.utils import tf_compat
from sparseml.utils import TENSORFLOW_V1_FRAMEWORK
The provided code snippet includes necessary dep... | :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,517 | from typing import List
from sparseml.tensorflow_v1.utils import tf_compat
The provided code snippet includes necessary dependencies for implementing the `step_lr_schedule` function. Write a Python function `def step_lr_schedule( global_step: tf_compat.Tensor, start_step: int, end_step: int, step_size:... | Create an exponential learning rate schedule in the current graph. Multiplies init_lr by gamma after each step_size interval has passed. Ex: lr = init_lr * (gamma ** NUM_UPDATES) :param global_step: the global step used for training :param start_step: the step to start the exponential schedule on :param end_step: the s... |
21,518 | from typing import List
from sparseml.tensorflow_v1.utils import tf_compat
The provided code snippet includes necessary dependencies for implementing the `multi_step_lr_schedule` function. Write a Python function `def multi_step_lr_schedule( global_step: tf_compat.Tensor, start_step: int, milestone_steps: ... | Create a multi step learning rate schedule in the current graph. Multiplies init_lr by gamma after each milestone has passed. Ex: lr = init_lr * (gamma ** NUM_UPDATES) :param global_step: the global step used for training :param start_step: the step to start the exponential schedule on :param milestone_steps: a list of... |
21,519 | import itertools
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import tensorflow as tf
from sparseml.optim import (
BaseManager,
BaseScheduled,
add_framework_metadata,
load_recipe_yaml_str,
parse_recipe_variables,
validate_metadata,
)
from sparseml.tensorflow_v1.optim.modi... | null |
21,520 | import logging
from typing import Any
from sparseml.base import Framework, get_version
from sparseml.framework import FrameworkInferenceProviderInfo, FrameworkInfo
from sparseml.sparsification import SparsificationInfo
from sparseml.tensorflow_v1.base import check_tensorflow_install, tf_compat
from sparseml.tensorflow_... | :param item: The item to detect the support for :type item: Any :return: True if the item is supported by tensorflow, False otherwise :rtype: bool |
21,521 | import logging
from typing import Any
from sparseml.base import Framework, get_version
from sparseml.framework import FrameworkInferenceProviderInfo, FrameworkInfo
from sparseml.sparsification import SparsificationInfo
from sparseml.tensorflow_v1.base import check_tensorflow_install, tf_compat
from sparseml.tensorflow_... | Detect the information for the tensorflow 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 tensorflow :rtype: FrameworkInfo |
21,522 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import (
conv2d_block,
dense_block,
depthwise_conv2d_block,
pool2d,
)
from sparseml.tensorflow... | null |
21,523 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import (
conv2d_block,
dense_block,
depthwise_conv2d_block,
pool2d,
)
from sparseml.tensorflow... | Standard MobileNet implementation with width=1.0; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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_... |
21,524 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import (
conv2d_block,
dense_block,
depthwise_conv2d_block,
pool2d,
)
from sparseml.tensorflow... | null |
21,525 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import (
conv2d_block,
dense_block,
depthwise_conv2d_block,
pool2d,
)
from sparseml.tensorflow... | null |
21,526 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import (
conv2d_block,
dense_block,
depthwise_conv2d_block,
pool2d,
)
from sparseml.tensorflow... | null |
21,527 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import (
conv2d_block,
dense_block,
depthwise_conv2d_block,
pool2d,
)
from sparseml.tensorflow... | Standard MobileNet V2 implementation with width=1.0; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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 cla... |
21,528 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import activation, conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
def _i... | null |
21,529 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import activation, conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
def _i... | null |
21,530 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import activation, conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class ... | Standard ResNet18 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,531 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import activation, conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class ... | null |
21,532 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import activation, conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class ... | Standard ResNet34 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,533 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import activation, conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class ... | 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,534 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import activation, conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class ... | 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,535 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import activation, conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class ... | 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,536 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class VGGSection(o... | Standard VGG 11 implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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,537 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class VGGSection(o... | Standard VGG 11 batch normalized implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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_t... |
21,538 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class VGGSection(o... | Standard VGG 13 implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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,539 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class VGGSection(o... | Standard VGG 13 batch normalized implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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_t... |
21,540 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class VGGSection(o... | Standard VGG 16 implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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,541 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class VGGSection(o... | Standard VGG 16 batch normalized implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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_t... |
21,542 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class VGGSection(o... | Standard VGG 19 implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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,543 | from typing import List, Union
from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import conv2d_block, dense_block, pool2d
from sparseml.tensorflow_v1.utils import tf_compat
class VGGSection(o... | Standard VGG 19 batch normalized implementation; expected input shape is (B, 224, 224, 3) :param inputs: The input tensor to the MobileNet 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_t... |
21,544 | from sparseml.tensorflow_v1.models.estimator import ClassificationEstimatorModelFn
from sparseml.tensorflow_v1.models.registry import ModelRegistry
from sparseml.tensorflow_v1.nn import activation, conv2d, fc
from sparseml.tensorflow_v1.utils import tf_compat
BASE_NAME_SCOPE = "mnist_net"
The provided code snippet inc... | A simple convolutional model created for the MNIST dataset :param inputs: the inputs tensor to create the network for :param num_classes: the number of classes to create the final layer for :param act: the final activation to use in the model, supported: [None, relu, sigmoid, softmax] :return: the logits output from th... |
21,545 | import functools
import logging
from typing import Callable, Dict
from sparseml.tensorflow_v1.utils import tf_compat as tf
def _check_slim_availability():
if nets_factory is None or slim is None:
raise ValueError(
"TensorFlow slim not setup in environment, please install first"
)
def get... | Modified from slim/nets/nets_factory Returns a network_fn such as `logits, end_points = network_fn(images)`. :param name: The name of the network. :param num_classes: The number of classes to use for classification. If 0 or None, the logits layer is omitted and its input features are returned instead. :param weight_dec... |
21,546 | from typing import Any
from sparseml.tensorflow_v1.utils.helpers import tf_compat
tf_compat = (
tf
if not hasattr(tf, "compat") or not hasattr(getattr(tf, "compat"), "v1")
else tf.compat.v1
)
The provided code snippet includes necessary dependencies for implementing the `write_simple_summary` function. Wr... | Write a simple value summary to a writer :param writer: the writer to write the summary to :param tag: the tag to write the value under :param val: the value to write :param step: the current global step to write the value at |
21,547 | import os
from collections import OrderedDict
from typing import Dict, List, Union
import numpy
import onnx
from sparseml.tensorflow_v1.utils.helpers import tf_compat
from sparseml.tensorflow_v1.utils.variable import clean_tensor_name
from sparseml.utils import (
clean_path,
create_dirs,
create_parent_dirs,... | null |
21,548 | import re
from typing import List, Tuple, Union
import numpy
from sparseml.tensorflow_v1.utils.helpers import tf_compat
def clean_tensor_name(var_tens: Union[str, tf_compat.Tensor]) -> str:
"""
:param var_tens: the tensor to get a variable for
:return: the cleaned version of the name for a variable tensor
... | Get the variable associated with a given tensor. Raises a ValueError if not found :param tens: the tensor to find a variable for :return: the found variable matching the given tensor |
21,549 | import re
from typing import List, Tuple, Union
import numpy
from sparseml.tensorflow_v1.utils.helpers import tf_compat
def get_op_input_var(
operation: tf_compat.Operation,
var_index: Union[str, int] = VAR_INDEX_FROM_TRAINABLE,
) -> tf_compat.Tensor:
"""
Get the input variable for an operation.
Ex:... | Get tuples of operations and the inputs for inputs of operations that match a regex pattern in the list params. :param var_names: List of full names or regex patterns to match variable names by. :param graph: the graph to get the prunable operations from. If not supplied, then will use the default graph :return: a list... |
21,550 | import re
from typing import List, Tuple, Union
import numpy
from sparseml.tensorflow_v1.utils.helpers import tf_compat
def eval_tensor_density(
tens: tf_compat.Tensor, sess: tf_compat.Session = None
) -> float:
"""
Get the density (fraction of non zero values) in a tensor
:param tens: the tensor to get... | Get the sparsity (fraction of zero values) in a tensor :param tens: the tensor to get the sparsity for :param sess: the session to use for evaluating the tensor, if not supplied will use the default session :return: the sparsity of the tensor |
21,551 | from sparseml.tensorflow_v1.utils.helpers import tf_compat
tf_compat = (
tf
if not hasattr(tf, "compat") or not hasattr(getattr(tf, "compat"), "v1")
else tf.compat.v1
)
The provided code snippet includes necessary dependencies for implementing the `batch_cross_entropy_loss` function. Write a Python functi... | Standard cross entropy loss that reduces across the batch dimension. :param logits: the logits from the model to use :param labels: the labels to compare the logits to :return: the cross entropy loss |
21,552 | from sparseml.tensorflow_v1.utils.helpers import tf_compat
tf_compat = (
tf
if not hasattr(tf, "compat") or not hasattr(getattr(tf, "compat"), "v1")
else tf.compat.v1
)
The provided code snippet includes necessary dependencies for implementing the `accuracy` function. Write a Python function `def accuracy... | Standard evaluation for accuracy. :param logits: the logits from the model to use :param labels: the labels to compare the logits to :param index: the index in the tensors to compare against :return: the accuracy |
21,553 | import argparse
import logging
import os
from abc import ABC, abstractmethod
from typing import Any, Dict, Iterable, Iterator, Optional
from tqdm import auto
from sparseml.base import Framework, execute_in_sparseml_framework
from sparseml.benchmark.serialization import (
BatchBenchmarkResult,
BenchmarkConfig,
... | Loads the benchmark configuration from a file or raw json and reruns the benchmark. If load exists as a path, will read from the file and use that. Otherwise will try to parse the input as a raw json str. :param model: model to benchmark :param data: data to benchmark :param load: Either a file path to a json file or a... |
21,554 | import argparse
import logging
import os
from abc import ABC, abstractmethod
from typing import Any, Dict, Iterable, Iterator, Optional
from tqdm import auto
from sparseml.base import Framework, execute_in_sparseml_framework
from sparseml.benchmark.serialization import (
BatchBenchmarkResult,
BenchmarkConfig,
... | null |
21,555 | from sparseml.pytorch.utils.distributed import record
from yolov5.export import export_run
from yolov5.export import parse_opt as parse_export_args
from yolov5.train import parse_opt as parse_train_args
from yolov5.train import run as train_run
from yolov5.val import parse_opt as parse_val_args
from yolov5.val import v... | Hook to call into train.py in YOLOv5 fork |
21,556 | from sparseml.pytorch.utils.distributed import record
from yolov5.export import export_run
from yolov5.export import parse_opt as parse_export_args
from yolov5.train import parse_opt as parse_train_args
from yolov5.train import run as train_run
from yolov5.val import parse_opt as parse_val_args
from yolov5.val import v... | Hook to call into val.py in YOLOv5 fork |
21,557 | from sparseml.pytorch.utils.distributed import record
from yolov5.export import export_run
from yolov5.export import parse_opt as parse_export_args
from yolov5.train import parse_opt as parse_train_args
from yolov5.train import run as train_run
from yolov5.val import parse_opt as parse_val_args
from yolov5.val import v... | Hook to call into export.py in YOLOv5 fork |
21,558 | import glob
import logging
import os
import shutil
from sparsezoo import setup_model
def _assert_correct_model_onnx_name(onnx_file_or_parent_directory_path: str):
# get a pointer to a single onnx file
# (either direct path to the onnx file or to its parent directory)
# and rename it to MODEL_ONNX_NAME if ne... | 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,559 | import json
from collections import OrderedDict
from typing import Any, Dict, List, Tuple, Union
import numpy
import pandas
import matplotlib.pyplot as plt
from sparseml.utils.helpers import clean_path, create_parent_dirs, interpolated_integral
The provided code snippet includes necessary dependencies for implementing... | The default sparsities to use for checking pruning effects on the loss :param extended: extend the sparsties to return a full range instead of a subset of target sparstiies :return: the sparsities to check for effects on the loss |
21,560 | import json
from collections import OrderedDict
from typing import Any, Dict, List, Tuple, Union
import numpy
import pandas
import matplotlib.pyplot as plt
from sparseml.utils.helpers import clean_path, create_parent_dirs, interpolated_integral
The provided code snippet includes necessary dependencies for implementing... | :return: the sparsities to check for effects on the loss |
21,561 | import json
import logging
import math
from collections import OrderedDict
from copy import deepcopy
from functools import cmp_to_key
from typing import Any, Dict, Generator, Iterable, List, Optional, Tuple, Union
from sparseml.optim.modifier import BaseModifier, BaseObject, ModifierProp
from sparseml.sparsification.ty... | null |
21,562 | import json
import logging
import math
from collections import OrderedDict
from copy import deepcopy
from functools import cmp_to_key
from typing import Any, Dict, Generator, Iterable, List, Optional, Tuple, Union
from sparseml.optim.modifier import BaseModifier, BaseObject, ModifierProp
from sparseml.sparsification.ty... | :return: the minimum epochs required by any of the modifiers provided |
21,563 | import json
import logging
import math
from collections import OrderedDict
from copy import deepcopy
from functools import cmp_to_key
from typing import Any, Dict, Generator, Iterable, List, Optional, Tuple, Union
from sparseml.optim.modifier import BaseModifier, BaseObject, ModifierProp
from sparseml.sparsification.ty... | :return: the maximum number of epochs required by any of the modifiers provided |
21,564 | import json
import logging
import platform
import re
from contextlib import suppress
from copy import deepcopy
from typing import Any, Dict, Optional, Tuple, Union
import yaml
from sparseml import version as sparseml_version
from sparseml.utils import (
FRAMEWORK_METADATA_KEY,
RECIPE_METADATA_KEY,
UnknownVa... | :param file_path: path to recipe yaml or markdown or raw recipe yaml str :return: dictionary of recipe variable name to value |
21,565 | import json
import logging
import platform
import re
from contextlib import suppress
from copy import deepcopy
from typing import Any, Dict, Optional, Tuple, Union
import yaml
from sparseml import version as sparseml_version
from sparseml.utils import (
FRAMEWORK_METADATA_KEY,
RECIPE_METADATA_KEY,
UnknownVa... | Parse input recipe_variables into a dictionary that can be used to overload variables at the root of a recipe. Supports dictionaries as well as parsing a string in either json or csv key=value format :param recipe_variables: the recipe_variables string or dictionary to parse for variables used with overloading recipes ... |
21,566 | import json
import logging
import platform
import re
from contextlib import suppress
from copy import deepcopy
from typing import Any, Dict, Optional, Tuple, Union
import yaml
from sparseml import version as sparseml_version
from sparseml.utils import (
FRAMEWORK_METADATA_KEY,
RECIPE_METADATA_KEY,
UnknownVa... | :param recipe_yaml_str: YAML string of a SparseML recipe :return: the YAML string with any expressions based on valid metadata and recipe variables and operations |
21,567 | import json
import logging
import platform
import re
from contextlib import suppress
from copy import deepcopy
from typing import Any, Dict, Optional, Tuple, Union
import yaml
from sparseml import version as sparseml_version
from sparseml.utils import (
FRAMEWORK_METADATA_KEY,
RECIPE_METADATA_KEY,
UnknownVa... | null |
21,568 | import json
import logging
import platform
import re
from contextlib import suppress
from copy import deepcopy
from typing import Any, Dict, Optional, Tuple, Union
import yaml
from sparseml import version as sparseml_version
from sparseml.utils import (
FRAMEWORK_METADATA_KEY,
RECIPE_METADATA_KEY,
UnknownVa... | Adds the information (in the form of a nested dictionary) about the relevant frameworks used by the user to the metadata. :param metadata: Validated metadata :param extra_metadata: Optional framework metadata, specific for the given framework (e.g. for pytorch integration 'add_framework_metadata(metadata, pytorch_versi... |
21,569 | import json
import logging
import platform
import re
from contextlib import suppress
from copy import deepcopy
from typing import Any, Dict, Optional, Tuple, Union
import yaml
from sparseml import version as sparseml_version
from sparseml.utils import (
FRAMEWORK_METADATA_KEY,
RECIPE_METADATA_KEY,
UnknownVa... | Compare the metadata (previous_metadata) carried over from the recipe (`yaml_str`) with the new, incoming metadata ('metadata'). If attempting to overwrite previous metadata with the new metadata, the script throws a warning and overwrites the previous metadata. Otherwise, it propagates the new metadata in the correct ... |
21,570 | import logging
def _create_console_stream(level: int, format_: str, datefmt: str):
stream = logging.StreamHandler()
stream.setLevel(level)
formatter = logging.Formatter(format_, datefmt)
stream.setFormatter(formatter)
return stream | null |
21,571 | import logging
NM_ROOT_LOGGER = logging.getLogger("sparseml")
NM_ROOT_LOGGER.setLevel(DEFAULT_LOG_LEVEL)
NM_ROOT_LOGGER.addHandler(
_create_console_stream(
DEFAULT_LOG_LEVEL,
"%(asctime)s %(name)-12s %(levelname)-8s %(message)s",
"%Y-%m-%d %H:%M:%S",
)
)
MAIN_LOGGER = logging.getLogger("... | Set the logging level for the MAIN and NM_ROOT loggers along with all loggers created in the sparseml namespace :param level: the log level to set; ex: logging.INFO |
21,572 | import logging
NM_ROOT_LOGGER = logging.getLogger("sparseml")
NM_ROOT_LOGGER.setLevel(DEFAULT_LOG_LEVEL)
NM_ROOT_LOGGER.addHandler(
_create_console_stream(
DEFAULT_LOG_LEVEL,
"%(asctime)s %(name)-12s %(levelname)-8s %(message)s",
"%Y-%m-%d %H:%M:%S",
)
)
The provided code snippet includ... | :return: the logger used for the sparseml root package that all other loggers in that namespace are created from |
21,573 | import logging
MAIN_LOGGER = logging.getLogger("__main__")
MAIN_LOGGER.setLevel(DEFAULT_LOG_LEVEL)
MAIN_LOGGER.addHandler(
_create_console_stream(
DEFAULT_LOG_LEVEL,
"%(asctime)s %(name)-12s %(levelname)-8s %(message)s",
"%Y-%m-%d %H:%M:%S",
)
)
The provided code snippet includes necess... | :return: a main logger that can be used in external scripts for logging in a standard format that is consistent with other loggers in sparseml |
21,574 | import argparse
import logging
import os
from collections import OrderedDict
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
from sparseml.base import Framework, execute_in_sparseml_framework
from sparseml.sparsification.info import SparsificationInfo
from sparseml.utils import clean_... | Load the framework info from a file or raw json. If load exists as a path, will read from the file and use that. Otherwise will try to parse the input as a raw json str. :param load: Either a file path to a json file or a raw json string. :type load: str :return: The loaded framework info. :rtype: FrameworkInfo |
21,575 | import argparse
import logging
import os
from collections import OrderedDict
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
from sparseml.base import Framework, execute_in_sparseml_framework
from sparseml.sparsification.info import SparsificationInfo
from sparseml.utils import clean_... | null |
21,576 | import inspect
from typing import Dict, List, Tuple
import torch
import torch.nn as nn
from sparseml.experimental.sparsegpt.quant import WeightFakeQuantizer
from sparseml.experimental.sparsegpt.sparsegpt import SparseGPT
def _find_dependency_order(layer, subset, an_input, **kwargs):
order = []
def exe_input(n... | null |
21,577 | import inspect
from typing import Dict, List, Tuple
import torch
import torch.nn as nn
from sparseml.experimental.sparsegpt.quant import WeightFakeQuantizer
from sparseml.experimental.sparsegpt.sparsegpt import SparseGPT
def _find_layers(module, layers=[nn.Conv2d, nn.Linear], name=""):
def _find_quant_layers(module, l... | null |
21,578 | import contextlib
import math
import warnings
from typing import Dict, Tuple
import torch
import torch.nn as nn
from einops import rearrange
from llmfoundry import (
COMPOSER_MODEL_REGISTRY,
build_finetuning_dataloader,
build_text_denoising_dataloader,
)
from llmfoundry.data.text_data import build_text_data... | null |
21,579 | import contextlib
import math
import warnings
from typing import Dict, Tuple
import torch
import torch.nn as nn
from einops import rearrange
from llmfoundry import (
COMPOSER_MODEL_REGISTRY,
build_finetuning_dataloader,
build_text_denoising_dataloader,
)
from llmfoundry.data.text_data import build_text_data... | null |
21,580 | import contextlib
import math
import warnings
from typing import Dict, Tuple
import torch
import torch.nn as nn
from einops import rearrange
from llmfoundry import (
COMPOSER_MODEL_REGISTRY,
build_finetuning_dataloader,
build_text_denoising_dataloader,
)
from llmfoundry.data.text_data import build_text_data... | null |
21,581 | import os
import time
import torch
from sparseml.experimental.sparsegpt.dispatch import (
evaluate_perplexity,
load_data,
load_model,
prepare_sparsegpt,
)
from sparseml.optim.helpers import load_recipe_yaml_str
def load_recipe_yaml_str(
file_path: str,
**variable_overrides,
) -> str:
def _save... | null |
21,582 | import torch
from sparseml.experimental.sparsegpt.dispatch import evaluate_perplexity, load_model
from sparseml.experimental.sparsegpt.main import sequential
from sparseml.experimental.sparsegpt.opt import load_data
from sparseml.modifiers.obcq.utils.helpers import ppl_eval_general
from sparseml.transformers.sparsifica... | null |
21,583 | import torch
from sparseml.experimental.sparsegpt.dispatch import evaluate_perplexity, load_model
from sparseml.experimental.sparsegpt.llama2 import load_data
from sparseml.experimental.sparsegpt.main import sequential
from sparseml.modifiers.obcq.utils.helpers import ppl_eval_general
from sparseml.transformers.sparsif... | null |
21,584 | import torch
from sparseml.experimental.sparsegpt.layer_compressor import BaseCompressor
from sparseml.experimental.sparsegpt.model_preprocessor import (
QuantizationModelPreprocessor,
)
from sparseml.experimental.sparsegpt.sequential import SequentialSparseGPT
from sparseml.experimental.sparsegpt.utils import (
... | null |
21,585 | SUPPORTED_MODELS = ["opt", "mpt", "llama-2"]
def _get_model_key(args):
def ppl_eval(
args,
model,
dataloader,
dev,
nsamples=None,
max_samples_per_iteration=128,
):
def ppl_eval(
args,
model,
dataloader,
dev,
nsamples=None,
max_samples_per_iteration=128,
):
def evaluate... | null |
21,586 | import numpy as np
import torch
from sparseml.experimental.sparsegpt.layer_compressor import (
BaseCompressor,
LayerCompressor,
)
from sparseml.experimental.sparsegpt.model_preprocessor import (
QuantizationModelPreprocessor,
)
from sparseml.experimental.sparsegpt.sequential import SequentialSparseGPT
from ... | null |
21,587 | import numpy as np
import torch
from sparseml.experimental.sparsegpt.layer_compressor import (
BaseCompressor,
LayerCompressor,
)
from sparseml.experimental.sparsegpt.model_preprocessor import (
QuantizationModelPreprocessor,
)
from sparseml.experimental.sparsegpt.sequential import SequentialSparseGPT
from ... | null |
21,588 | from math import ceil
from typing import Dict, Tuple
import torch
import torch.nn as nn
from sparseml.pytorch.optim.manager import ScheduledModifierManager
class ScheduledModifierManager(BaseManager, Modifier):
"""
The base modifier manager, handles managing multiple ScheduledModifers.
| Lifecycle:
| ... | null |
21,589 | import argparse
import collections
import copy
import inspect
import logging
import math
import os
import shutil
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Union
from torch.nn import Module
from transformers import AutoConfig
from transformers import TrainingArguments as HFTrainingA... | null |
21,590 | import argparse
import collections
import copy
import inspect
import logging
import math
import os
import shutil
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Union
from torch.nn import Module
from transformers import AutoConfig
from transformers import TrainingArguments as HFTrainingA... | null |
21,591 | import logging
import os
from pathlib import PosixPath
import datasets
import transformers
from transformers import AutoConfig, DefaultDataCollator, HfArgumentParser, set_seed
import sparseml.core.session as session_manager
from sparseml.core.framework import Framework
from sparseml.core.recipe import Recipe, StageRunT... | CLI entrypoint for running training |
21,592 | import logging
import os
from pathlib import PosixPath
import datasets
import transformers
from transformers import AutoConfig, DefaultDataCollator, HfArgumentParser, set_seed
import sparseml.core.session as session_manager
from sparseml.core.framework import Framework
from sparseml.core.recipe import Recipe, StageRunT... | CLI entrypoint for running evaluation |
21,593 | import logging
import os
from pathlib import PosixPath
import datasets
import transformers
from transformers import AutoConfig, DefaultDataCollator, HfArgumentParser, set_seed
import sparseml.core.session as session_manager
from sparseml.core.framework import Framework
from sparseml.core.recipe import Recipe, StageRunT... | CLI entrypoint for running oneshot calibration |
21,594 | import logging
import os
from pathlib import PosixPath
import datasets
import transformers
from transformers import AutoConfig, DefaultDataCollator, HfArgumentParser, set_seed
import sparseml.core.session as session_manager
from sparseml.core.framework import Framework
from sparseml.core.recipe import Recipe, StageRunT... | null |
21,595 | import logging
import os
from pathlib import PosixPath
import datasets
import transformers
from transformers import AutoConfig, DefaultDataCollator, HfArgumentParser, set_seed
import sparseml.core.session as session_manager
from sparseml.core.framework import Framework
from sparseml.core.recipe import Recipe, StageRunT... | null |
21,596 | import logging
import os
from pathlib import PosixPath
import datasets
import transformers
from transformers import AutoConfig, DefaultDataCollator, HfArgumentParser, set_seed
import sparseml.core.session as session_manager
from sparseml.core.framework import Framework
from sparseml.core.recipe import Recipe, StageRunT... | null |
21,597 | import logging
import os
from pathlib import PosixPath
import datasets
import transformers
from transformers import AutoConfig, DefaultDataCollator, HfArgumentParser, set_seed
import sparseml.core.session as session_manager
from sparseml.core.framework import Framework
from sparseml.core.recipe import Recipe, StageRunT... | null |
21,598 | import logging
import os
from typing import Any, Callable, Dict, List, Optional
import torch
from datasets import Dataset, load_dataset
from torch.utils.data import DataLoader, RandomSampler
from transformers.data import default_data_collator
The provided code snippet includes necessary dependencies for implementing t... | Restructures the datasets dictionary based on what tasks will be run (train, eval, predict) :param tokenized_datasets: dictionary of processed datasets :param do_train: Whether to store the train dataset :param do_eval: Whether to store the validation dataset :param do_predict: Whether to store the test dataset :param ... |
21,599 | import logging
import os
from typing import Any, Callable, Dict, List, Optional
import torch
from datasets import Dataset, load_dataset
from torch.utils.data import DataLoader, RandomSampler
from transformers.data import default_data_collator
def transform_dataset_keys(data_files: Dict[str, Any]):
"""
Transform... | Get a dictionary of custom datasets from a directory path. Support HF's load_dataset for local folder datasets https://huggingface.co/docs/datasets/loading This function scans the specified directory path for files with a specific extension (default is '.json'). It constructs a dictionary where the keys are either subd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.