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 tf2onnx package is installed. If raise_on_error, will raise an ImportError if it is not installed or the required version range, if set, is not installed. If not raise_on_error, will return True if installed with required version and False otherwise. :param min_version: The minimum version for tf2onnx that it must be greater than or equal to, if unset will require no minimum version :type min_version: str :param max_version: The maximum version for tf2onnx that it must be less than or equal to, if unset will require no maximum version. :type max_version: str :param raise_on_error: True to raise any issues such as not installed, minimum version, or maximum version as ImportError. False to return the result. :type raise_on_error: bool :return: If raise_on_error, will return False if tf2onnx is not installed or the version is outside the accepted bounds and True if everything is correct. :rtype: bool """ if tf2onnx_err is not None: if raise_on_error: raise tf2onnx_err return False return check_version("tf2onnx", min_version, max_version, raise_on_error) The provided code snippet includes necessary dependencies for implementing the `require_tf2onnx` function. Write a Python function `def require_tf2onnx( min_version: Optional[str] = _TF2ONNX_MIN_VERSION, max_version: Optional[str] = None, )` to solve the following problem: 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 be greater than or equal to, if unset will require no minimum version :type min_version: str :param max_version: The maximum version for tf2onnx that it must be less than or equal to, if unset will require no maximum version. :type max_version: str Here is the function: def require_tf2onnx( min_version: Optional[str] = _TF2ONNX_MIN_VERSION, max_version: Optional[str] = None, ): """ 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 be greater than or equal to, if unset will require no minimum version :type min_version: str :param max_version: The maximum version for tf2onnx that it must be less than or equal to, if unset will require no maximum version. :type max_version: str """ def _decorator(func): @functools.wraps(func) def _wrapper(*args, **kwargs): check_tf2onnx_install(min_version, max_version) return func(*args, **kwargs) return _wrapper return _decorator
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 be greater than or equal to, if unset will require no minimum version :type min_version: str :param max_version: The maximum version for tf2onnx that it must be less than or equal to, if unset will require no maximum version. :type max_version: str
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 problem: Load the available setup for sparsifying model within tensorflow. :return: The sparsification info for the tensorflow framework :rtype: SparsificationInfo Here is the function: def sparsification_info() -> SparsificationInfo: """ Load the available setup for sparsifying model within tensorflow. :return: The sparsification info for the tensorflow framework :rtype: SparsificationInfo """ _LOGGER.debug("getting sparsification info for tensorflow") info = SparsificationInfo(modifiers=[]) # TODO: fill in once available _LOGGER.info("retrieved sparsification info for tensorflow: %s", info) return info
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] = (3.0 / 4.0, 4.0 / 3.0), name: str = "random_scaling_crop", )` to solve the following problem: 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 ops under :return: the callable function for random scaling crop op, takes in the image and outputs randomly cropped image Here is the function: def random_scaling_crop( scale_range: Tuple[int, int] = (0.08, 1.0), ratio_range: Tuple[int, int] = (3.0 / 4.0, 4.0 / 3.0), name: str = "random_scaling_crop", ): """ 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 ops under :return: the callable function for random scaling crop op, takes in the image and outputs randomly cropped image """ def rand_crop(img: tf_compat.Tensor): with tf_compat.name_scope(name): orig_shape = tf_compat.shape(img) scale = tf_compat.random_uniform( shape=[1], minval=scale_range[0], maxval=scale_range[1] )[0] ratio = tf_compat.random_uniform( shape=[1], minval=ratio_range[0], maxval=ratio_range[1] )[0] height = tf_compat.minimum( tf_compat.cast( tf_compat.round( tf_compat.cast(orig_shape[0], dtype=tf_compat.float32) * scale / ratio ), tf_compat.int32, ), orig_shape[0], ) width = tf_compat.minimum( tf_compat.cast( tf_compat.round( tf_compat.cast(orig_shape[1], dtype=tf_compat.float32) * scale ), tf_compat.int32, ), orig_shape[1], ) img = tf_compat.random_crop(img, [height, width, orig_shape[2]]) return img return rand_crop
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 ops under :return: the callable function for random scaling crop op, takes in the image and outputs randomly cropped image
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 under :return: the callable function for resize op, takes in the image and outputs the resized image """ def res(img: tf_compat.Tensor): with tf_compat.name_scope(name): try: img = tf_compat.image.resize(img, image_size) except Exception: img = tf_compat.image.resize_images(img, image_size) return img return res The provided code snippet includes necessary dependencies for implementing the `center_square_crop` function. Write a Python function `def center_square_crop(padding: int = 0, name: str = "center_square_crop")` to solve the following problem: 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 Here is the function: def center_square_crop(padding: int = 0, name: str = "center_square_crop"): """ 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 """ def cent_crop(img: tf_compat.Tensor): with tf_compat.name_scope(name): orig_shape = tf_compat.shape(img) min_size = tf_compat.cond( tf_compat.greater_equal(orig_shape[0], orig_shape[1]), lambda: orig_shape[1], lambda: orig_shape[0], ) if padding > 0: orig_shape_list = img.get_shape().as_list() resize( (orig_shape_list[0] + 2 * padding, orig_shape_list[1] + 2 * padding) ) padding_height = tf_compat.add( tf_compat.cast( tf_compat.round( tf_compat.div( tf_compat.cast( tf_compat.subtract(orig_shape[0], min_size), tf_compat.float32, ), 2.0, ) ), tf_compat.int32, ), padding, ) padding_width = tf_compat.add( tf_compat.cast( tf_compat.round( tf_compat.div( tf_compat.cast( tf_compat.subtract(orig_shape[1], min_size), tf_compat.float32, ), 2.0, ) ), tf_compat.int32, ), padding, ) img = tf_compat.image.crop_to_bounding_box( img, padding_height, padding_width, min_size, min_size ) return img return cent_crop
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 dataset to create the iterator :return: an iterator """ if hasattr(tf_compat.data, "make_initializable_iterator"): return tf_compat.data.make_initializable_iterator(dataset) else: return dataset.make_initializable_iterator() The provided code snippet includes necessary dependencies for implementing the `create_split_iterators_handle` function. Write a Python function `def create_split_iterators_handle(split_datasets: Iterable) -> Tuple[Any, Any, List]` to solve the following problem: 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_datasets Here is the function: def create_split_iterators_handle(split_datasets: Iterable) -> Tuple[Any, Any, List]: """ 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_datasets """ output_types = None output_shapes = None split_iterators = [] for split_dataset in split_datasets: # get_output_types and shapes are not available in TF 1.13 and prior # hence the following conditional assignments output_types = ( tf_compat.data.get_output_types(split_dataset) if hasattr(tf_compat.data, "get_output_types") else split_dataset.output_types ) output_shapes = ( tf_compat.data.get_output_shapes(split_dataset) if hasattr(tf_compat.data, "get_output_shapes") else split_dataset.output_shapes ) split_iterators.append(_make_initializable_iterator(split_dataset)) handle = tf_compat.placeholder(tf_compat.string, shape=[]) iterator = tf_compat.data.Iterator.from_string_handle( handle, output_types, output_shapes ) return handle, iterator, split_iterators
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_datasets
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 from sparseml.tensorflow_v1.utils import tf_compat, tf_compat_div from sparseml.utils import create_dirs from sparsezoo.utils import download_file _PADDING = 4 The provided code snippet includes necessary dependencies for implementing the `preprocess_for_train` function. Write a Python function `def preprocess_for_train(image: tf_compat.Tensor)` to solve the following problem: The default preprocessing function for train set as defined in Resnet paper for Cifar datasets :param image: the image tensor :return: the preprocessed image Here is the function: def preprocess_for_train(image: tf_compat.Tensor): """ The default preprocessing function for train set as defined in Resnet paper for Cifar datasets :param image: the image tensor :return: the preprocessed image """ with tf_compat.name_scope("train_preprocess"): image = tf_compat.cast(image, dtype=tf_compat.float32) rand_choice = tf_compat.random_uniform( shape=[], minval=0, maxval=2, dtype=tf_compat.int32 ) padding = _PADDING image = tf_compat.cond( tf_compat.equal(rand_choice, 0), lambda: tf_compat.pad( image, [[padding, padding], [padding, padding], [0, 0]] ), lambda: tf_compat.image.random_flip_left_right(image), ) distorted_image = tf_compat.image.random_crop(image, [32, 32, 3]) return distorted_image
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 from sparseml.tensorflow_v1.utils import tf_compat, tf_compat_div from sparseml.utils import create_dirs from sparsezoo.utils import download_file The provided code snippet includes necessary dependencies for implementing the `preprocess_for_eval` function. Write a Python function `def preprocess_for_eval(image: tf_compat.Tensor)` to solve the following problem: The default preprocessing function for test set as defined in Resnet paper for Cifar datasets :param image: the image tensor :return: the preprocessed image Here is the function: def preprocess_for_eval(image: tf_compat.Tensor): """ The default preprocessing function for test set as defined in Resnet paper for Cifar datasets :param image: the image tensor :return: the preprocessed image """ with tf_compat.name_scope("test_preprocess"): image = tf_compat.cast(image, dtype=tf_compat.float32) image = tf_compat_div(image, 255.0) image = tf_compat.image.random_crop(image, [32, 32, 3]) return image
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_v1.datasets.registry import DatasetRegistry from sparseml.tensorflow_v1.utils import tf_compat, tf_compat_div from sparseml.utils import clean_path from sparseml.utils.datasets import IMAGENET_RGB_MEANS, IMAGENET_RGB_STDS The provided code snippet includes necessary dependencies for implementing the `imagenet_normalizer` function. Write a Python function `def imagenet_normalizer(img)` to solve the following problem: Normalize an image using mean and std of the imagenet dataset :param img: The input image to normalize :return: The normalized image Here is the function: def imagenet_normalizer(img): """ Normalize an image using mean and std of the imagenet dataset :param img: The input image to normalize :return: The normalized image """ img = tf_compat_div(img, 255.0) means = tf_compat.constant(IMAGENET_RGB_MEANS, dtype=tf_compat.float32) stds = tf_compat.constant(IMAGENET_RGB_STDS, dtype=tf_compat.float32) img = tf_compat_div(tf_compat.subtract(img, means), stds) return img
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 get_op_input_var def _validate(session: tf_compat.Session, graph: tf_compat.Graph): """ Check and make sure the session and graph are consistent. Provided session and graph might be reassigned for consistency. :param session: Current session :param graph: Current graph """ if not session and not graph: raise ValueError("Either session or graph must be provided") if session: if graph != tf_compat.get_default_graph(): raise ValueError("Inconsistent session and graph") graph = tf_compat.get_default_graph() else: session = tf_compat.Session(graph=graph) def _analyze_ops( session: tf_compat.Session, graph: tf_compat.Graph, ops: List[tf_compat.Operation] ) -> Dict[str, AnalyzedLayerDesc]: """ Analyze operations for their properties :param session: Current session :graph: Current graph :ops: List of operations in the graph to be analyzed :return A dictionary of AnalyzedLayerDesc object for each operation name """ exec_orders = _op_exec_order(graph) ops_desc = {} for op in ops: assert type(op) == tf_compat.Operation desc = AnalyzedLayerDesc(op.name, op.type) desc.params = _count_parameters(session, op) desc.zeroed_params = _count_parameters(session, op, "zeroed") desc.prunable_params = _count_parameters(session, op, "prunable") desc.params_dims = _get_parameters_dims(op) desc.prunable_params_dims = _get_parameters_dims(op) desc.execution_order = exec_orders[op.name] desc.input_shape = tuple( [tuple(_from_tensor_shape(ten.shape)) for ten in op.inputs] ) desc.output_shape = tuple( [tuple(_from_tensor_shape(ten.shape)) for ten in op.outputs] ) ops_desc[op.name] = desc op_flops = _profile_flops(graph, ops) for op in ops: ops_desc[op.name].flops = -1 # Unused ops_desc[op.name].total_flops = op_flops[op.name] return ops_desc 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 `analyze_module` function. Write a Python function `def analyze_module( session: Optional[tf_compat.Session], graph: Optional[tf_compat.Graph], op_names: Optional[List[str]] = None, op_types: Optional[List[str]] = None, )` to solve the following problem: 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 aggregated result :param op_types: the operation types that will be analyzed, default (Conv2D, MatMul) :return: the analyzed layer descriptions or the module description if no op_names Here is the function: def analyze_module( session: Optional[tf_compat.Session], graph: Optional[tf_compat.Graph], op_names: Optional[List[str]] = None, op_types: Optional[List[str]] = None, ): """ 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 aggregated result :param op_types: the operation types that will be analyzed, default (Conv2D, MatMul) :return: the analyzed layer descriptions or the module description if no op_names """ if op_types is None: op_types = ["Conv2D", "MatMul"] _validate(session, graph) ops = [ o for o in graph.get_operations() if (o.type in op_types) and (op_names is None or o.name in op_names) ] ops_desc = _analyze_ops(session, graph, ops) # Dict[str, AnalyzedLayerDesc] return ops_desc
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 aggregated result :param op_types: the operation types that will be analyzed, default (Conv2D, MatMul) :return: the analyzed layer descriptions or the module description if no op_names
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, load_mask_creator, ) from sparseml.tensorflow_v1.optim.mask_pruning import PruningScope, create_op_pruning from sparseml.tensorflow_v1.utils import get_ops_and_inputs_by_name_or_regex, tf_compat SparsePruningOpVars = namedtuple("SparsePruningOpVars", ("op_vars", "sparsity")) def pruning_loss_sens_one_shot( op_vars: List[SparsePruningOpVars], loss_tensor: tf_compat.Tensor, steps_per_measurement: int, add_ops_creator: Callable[[int], List[tf_compat.Tensor]] = None, feed_dict_creator: Callable[[int], Dict[str, tf_compat.Tensor]] = None, sess: tf_compat.Session = None, sparsity_levels: List[int] = default_pruning_sparsities_loss(False), show_progress: bool = True, ) -> PruningLossSensitivityAnalysis: """ Run a one shot sensitivity analysis for kernel sparsity. It does not retrain, and instead puts the model to eval mode. Moves operation by operation to calculate the sensitivity analysis for each and resets the previously run layers. Subsequent sparsity checks for layers and levels will be much faster. Note: this should be run once a session has been created and the variables have been created for the model. Note: the graph should be recreated for later training as this creates extra ops in the graph that should be reused before continuing in the system. :param op_vars: the created pruning op vars from ks_loss_sensitivity_op_vars :param loss_tensor: the loss tensor in the model to measure for the sensitivity :param steps_per_measurement: the number of session.run calls to run through for each sparsity level on each layer :param add_ops_creator: a callback to create an op/tens list to be run through the session for each measurement. Called for each measurement :param feed_dict_creator: a callback to create a feed dict to be run through the session for each measurement. Called for each measurement :param sess: the session to use :param sparsity_levels: the sparsity levels to check for each layer to calculate sensitivity :param show_progress: track progress of the runs if True :return: the sensitivity results for every op that is prunable """ if not sess: sess = tf_compat.get_default_session() analysis = PruningLossSensitivityAnalysis() sess.run(tf_compat.variables_initializer([var.op_vars.mask for var in op_vars])) bar = ( auto.tqdm( desc="KS Analysis", total=len(op_vars) * len(sparsity_levels) * steps_per_measurement, ) if show_progress else None ) for op_index, sparse_op_vars in enumerate(op_vars): for sparsity_level in sparsity_levels: sess.run( sparse_op_vars.op_vars.update, feed_dict={sparse_op_vars.sparsity: sparsity_level}, ) for step in range(steps_per_measurement): ops = [loss_tensor] add_ops = add_ops_creator(step) if add_ops_creator else None feed_dict = feed_dict_creator(step) if feed_dict_creator else None if add_ops: ops.extend(add_ops) values = sess.run(ops, feed_dict=feed_dict) loss = values[0].item() analysis.add_result( None, sparse_op_vars.op_vars.op_input.name, op_index, sparsity_level, loss, baseline=sparsity_level < 1e-9, ) if bar is not None: bar.update(1) sess.run( sparse_op_vars.op_vars.update, feed_dict={sparse_op_vars.sparsity: 0.0} ) if bar is not None: bar.close() return analysis class PruningMaskCreator(ABC): """ Base abstract class for a sparsity mask creator. Subclasses should define all methods for creating masks and their initializers """ def get_mask_initializer( self, tensor: tf_compat.Tensor, ) -> Callable[[], tf_compat.Tensor]: """ :param tensor: A tensor of a model layer's weights :return: Tensor initializer function for this sparsity mask """ raise NotImplementedError() def create_sparsity_mask( self, tensor: tf_compat.Tensor, sparsity: tf_compat.Tensor, ) -> tf_compat.Tensor: """ :param tensor: A tensor of a model layer's weights :param sparsity: the target sparsity to use for assigning the masks :return: A sparsity mask close to the set sparsity based on the values of the input tensor """ raise NotImplementedError() def load_mask_creator(obj: Union[str, Iterable[int]]) -> PruningMaskCreator: """ :param obj: Formatted string or iterable of block_shape specifying SparsityMaskCreator object to return :return: SparsityMaskCreator object created from obj """ if isinstance(obj, str) and obj in mask_creator_name_to_constructor_lambda: constructor_lambda = mask_creator_name_to_constructor_lambda[obj] return constructor_lambda() # Checking for a BlockSparsityMaskCreator string if ("[" in obj and "]" in obj) or ("(" in obj and ")" in obj): stripped_str = obj.strip("[|]|(|)") block_shape = [int(s) for s in stripped_str.split(",")] return BlockPruningMaskCreator(block_shape) if isinstance(obj, list) or isinstance(obj, tuple): return BlockPruningMaskCreator(obj) raise ValueError( "Invalid mask type string: {}, could not map to an object".format(obj) ) class PruningScope(object): """ Convenience class for dealing with scope and names for kernel sparsity in the tf graph. """ NM_KS = "nm_ks" NM_KS_OPS = "nm_ks_ops" OPS = "ops" OPS_INPUT = "input_ops" OPS_UPDATE = "update_ops" OPS_SUMMARY = "summary_ops" OPS_SCHEDULE = "schedule_ops" OPS_SPARSITY = "sparsity_ops" OP_COND_UPDATE = "nm_conditional_update" OP_SPARSITY = "nm_sparsity" OP_UPDATE_READY = "nm_update_ready" OP_MASKED_VAR = "nm_masked_var" OP_MASK_ASSIGN = "nm_mask_assign" OP_PRUNE_VARS_ASSIGN = "nm_prune_vars_assign" OP_MASK_UPDATE_NO_OP = "nm_mask_update_no_op" OP_MASK_UPDATE = "nm_mask_update" OP_WEIGHT_UPDATE = "nm_weight_update" OP_SAVE = "nm_save" VAR_MASK = "nm_mask" VAR_THRESHOLD = "nm_threshold" def general(ks_group: str, additional: str = None, trailing_slash: bool = False): """ Create a general kernel sparsity scope in the tf graph. Use cases are for generic ops like target sparsity, conditional updates, etc. :param ks_group: the group identifier the scope should be created under :param additional: any additional scope that should be added to the end :param trailing_slash: include a trailing forward slash if True, else False :return: the proper scope """ scope = PruningScope._format(PruningScope.NM_KS_OPS, ks_group) scope = PruningScope._format( scope, additional=additional, trailing_slash=trailing_slash ) return scope def model( op_tens: tf_compat.Tensor, ks_group: str, additional: str = None, trailing_slash: bool = False, ) -> str: """ Create a model specific kernel sparsity scope in the tf graph. Use cases are for the specific mask, threshold, etc variables to induce sparsity along with the ops to update those vars. :param op_tens: the op tensor to create the scope for :param ks_group: the group identifier the scope should be created under :param additional: any additional scope that should be added to the end :param trailing_slash: include a trailing forward slash if True, else False :return: the proper scope """ op_name = clean_tensor_name(op_tens) scope = PruningScope._format( "{}_{}".format(op_name, PruningScope.NM_KS), ks_group ) scope = PruningScope._format( scope, additional=additional, trailing_slash=trailing_slash ) return scope def collection_name(ks_group: str, name: str) -> str: """ Create a predictable name for a given variable / op in a group for lookup / storage in a collection :param ks_group: the group identifier the name belongs under :param name: the name of the op or variable to be stored or retrieved :return: the formatted name for use in a collection """ return "nm_ks_collection_{}_{}".format(ks_group, name) def _format( current: str, additional: str = None, trailing_slash: bool = False ) -> str: scope = current if additional is not None: scope = "{}/{}".format(current, additional) if trailing_slash: scope += "/" return scope def create_op_pruning( op: tf_compat.Operation, op_input: tf_compat.Tensor, sparsity: tf_compat.Tensor, update_ready: tf_compat.Tensor, leave_enabled: bool, is_after_end_step: tf_compat.Tensor, ks_group: str, mask_creator: PruningMaskCreator, ) -> PruningOpVars: """ Creates the necessary variables and operators to gradually apply sparsity to an operators variable. Handles setting a mask on an operator to the given sparsity. Sets the mask based on pruning away the lowest absolute magnitude weights. :param op: the operation to prune to the given sparsity :param op_input: the variable of the parameter within op to prune :param sparsity: the target sparsity to use for assigning the masks :param update_ready: the tensor where if true will update the mask from sparsity, if false will not update the mask :param leave_enabled: True to continue masking the weights after end_epoch, False to stop masking :param is_after_end_step: tensor that is true if the current global step is after end_epoch :param ks_group: the group identifier the scope should be created under :param mask_creator: object to define sparisty mask creation :return: a named tuple containing the assignment op, mask variable, threshold tensor, and masked tensor """ initial_vars = create_op_pruning_no_update( op, op_input, ks_group, leave_enabled, is_after_end_step ) op = initial_vars.op op_var_tens = initial_vars.op_input mask = initial_vars.mask masked = initial_vars.masked def _update(): # create the update ops using the target sparsity tensor with tf_compat.name_scope( PruningScope.model( op, ks_group, additional=PruningScope.OPS_UPDATE, trailing_slash=True, ) ): new_mask = mask_creator.create_sparsity_mask(op_var_tens, sparsity) weight_var = get_tensor_var(op_var_tens) return tf_compat.group( tf_compat.assign(mask, new_mask, name=PruningScope.OP_MASK_ASSIGN), tf_compat.assign( weight_var, tf_compat.multiply(new_mask, op_var_tens), name=PruningScope.OP_WEIGHT_UPDATE, ), ) def _no_update(): with tf_compat.name_scope( PruningScope.model( op, ks_group, additional=PruningScope.OPS_UPDATE, trailing_slash=True, ) ): # return no op wrapped in group to match update type return tf_compat.group( tf_compat.constant( 0.0, dtype=op_var_tens.dtype, name=PruningScope.OP_MASK_UPDATE_NO_OP ) ) with tf_compat.name_scope( PruningScope.model( op, ks_group, additional=PruningScope.OPS_UPDATE, trailing_slash=True, ) ): mask_update = tf_compat.cond( update_ready, _update, _no_update, name=PruningScope.OP_MASK_UPDATE ) # add return state to collections tf_compat.add_to_collection( PruningScope.collection_name(ks_group, PruningScope.OP_MASK_UPDATE), mask_update ) return PruningOpVars(op, op_var_tens, mask_update, mask, masked) The provided code snippet includes necessary dependencies for implementing the `pruning_loss_sens_op_vars` function. Write a Python function `def pruning_loss_sens_op_vars( graph: tf_compat.Graph = None, var_names: Union[List[str], Tuple[str]] = ("re:.*",), mask_type: Union[str, List[int], PruningMaskCreator] = "unstructured", ) -> List[SparsePruningOpVars]` to solve the following problem: 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 patterns of variables to get the op vars for. Defaults to matching all variables :param mask_type: String to define type of sparsity (options: ['unstructured', 'channel', 'filter']), List to define block shape of a parameter's in and out channels, or a SparsityMaskCreator object. default is 'unstructured' :return: the created pruning op vars to be used in approx_ks_loss_sensitivity and one_shot_ks_loss_sensitivity Here is the function: def pruning_loss_sens_op_vars( graph: tf_compat.Graph = None, var_names: Union[List[str], Tuple[str]] = ("re:.*",), mask_type: Union[str, List[int], PruningMaskCreator] = "unstructured", ) -> List[SparsePruningOpVars]: """ 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 patterns of variables to get the op vars for. Defaults to matching all variables :param mask_type: String to define type of sparsity (options: ['unstructured', 'channel', 'filter']), List to define block shape of a parameter's in and out channels, or a SparsityMaskCreator object. default is 'unstructured' :return: the created pruning op vars to be used in approx_ks_loss_sensitivity and one_shot_ks_loss_sensitivity """ if not graph: graph = tf_compat.get_default_graph() mask_creator = mask_type if not isinstance(mask_type, PruningMaskCreator): mask_creator = load_mask_creator(mask_type) ks_group = pruning_loss_sens_one_shot.__name__ prunable_ops_and_inputs = get_ops_and_inputs_by_name_or_regex(var_names, graph) op_vars = [] with graph.as_default(): for prune_op, prune_op_input in prunable_ops_and_inputs: with tf_compat.name_scope( PruningScope.model(prune_op, ks_group, trailing_slash=True) ): sparsity = tf_compat.placeholder( dtype=tf_compat.float32, name="sparsity_placeholder" ) update = tf_compat.constant(True, tf_compat.bool) prune_op_var = create_op_pruning( prune_op, prune_op_input, sparsity, update, True, None, ks_group, mask_creator, ) op_vars.append(SparsePruningOpVars(prune_op_var, sparsity)) return op_vars
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 patterns of variables to get the op vars for. Defaults to matching all variables :param mask_type: String to define type of sparsity (options: ['unstructured', 'channel', 'filter']), List to define block shape of a parameter's in and out channels, or a SparsityMaskCreator object. default is 'unstructured' :return: the created pruning op vars to be used in approx_ks_loss_sensitivity and one_shot_ks_loss_sensitivity
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, load_mask_creator, ) from sparseml.tensorflow_v1.optim.mask_pruning import PruningScope, create_op_pruning from sparseml.tensorflow_v1.utils import get_ops_and_inputs_by_name_or_regex, tf_compat The provided code snippet includes necessary dependencies for implementing the `pruning_loss_sens_magnitude` function. Write a Python function `def pruning_loss_sens_magnitude( graph: tf_compat.Graph = None, sess: tf_compat.Session = None, sparsity_levels: Union[ List[float], Tuple[float, ...] ] = default_pruning_sparsities_loss(True), ) -> PruningLossSensitivityAnalysis` to solve the following problem: 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 session to use :param sparsity_levels: the sparsity levels to calculate the loss for for each param :return: the analysis results for the model Here is the function: def pruning_loss_sens_magnitude( graph: tf_compat.Graph = None, sess: tf_compat.Session = None, sparsity_levels: Union[ List[float], Tuple[float, ...] ] = default_pruning_sparsities_loss(True), ) -> PruningLossSensitivityAnalysis: """ 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 session to use :param sparsity_levels: the sparsity levels to calculate the loss for for each param :return: the analysis results for the model """ if not graph: graph = tf_compat.get_default_graph() if not sess: sess = tf_compat.get_default_session() prunable_ops_and_inputs = get_ops_and_inputs_by_name_or_regex(["re:.*"], graph) analysis = PruningLossSensitivityAnalysis() for op_index, (_, op_tens) in enumerate(prunable_ops_and_inputs): weight = sess.run(op_tens) values = numpy.sort(numpy.abs(weight.reshape(-1))) prev_index = 0 for sparsity in sparsity_levels: val_index = round(sparsity * len(values)) if val_index >= len(values): val_index = len(values) - 1 if sparsity <= 1e-9: baseline = True sparsity = 0.0 sparse_avg = 0.0 else: baseline = False if val_index > prev_index: sparse_avg = values[prev_index:val_index].mean().item() prev_index = val_index else: sparse_avg = values[val_index].item() prev_index = val_index + 1 analysis.add_result( None, op_tens.name, op_index, sparsity, sparse_avg, baseline ) return analysis
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 session to use :param sparsity_levels: the sparsity levels to calculate the loss for for each param :return: the analysis results for the model
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 ( EXTRAS_KEY_LEARNING_RATE, EXTRAS_KEY_SUMMARIES, NM_RECAL, ScheduledModifier, ScheduledUpdateModifier, TensorFlowModifierYAML, ) from sparseml.tensorflow_v1.optim.schedule_lr import ( multi_step_lr_schedule, step_lr_schedule, ) from sparseml.tensorflow_v1.utils import tf_compat EXTRAS_KEY_LEARNING_RATE = "learning_rate" EXTRAS_KEY_SUMMARIES = "summaries" def _add_lr_extras( mod_extras: Dict, learning_rate: tf_compat.Tensor, ): mod_extras[EXTRAS_KEY_LEARNING_RATE] = learning_rate mod_extras[EXTRAS_KEY_SUMMARIES] = [ tf_compat.summary.scalar("Train/learning_rate", learning_rate) ]
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_compat_div, ) PruningOpVars = namedtuple( "PruningOpVars", ["op", "op_input", "update", "mask", "masked"] ) The provided code snippet includes necessary dependencies for implementing the `create_summaries_pruning` function. Write a Python function `def create_summaries_pruning(pruning_op_vars: List[PruningOpVars])` to solve the following problem: 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 Here is the function: def create_summaries_pruning(pruning_op_vars: List[PruningOpVars]): """ 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 """ summaries = [] for op_vars in pruning_op_vars: try: zero_fraction = tf_compat.zero_fraction except Exception: def zero_fraction(inp: tf_compat.Tensor): nonzero = tf_compat.cast( tf_compat.reduce_sum( tf_compat.cast(tf_compat.not_equal(inp, 0), tf_compat.int64) ), tf_compat.float32, ) size = tf_compat.size(inp, out_type=tf_compat.float32) return 1 - tf_compat_div(nonzero, size) if is_prunable_op(op_vars.op): sum_op = tf_compat.summary.scalar( "Modifier_Pruning/{}".format(clean_tensor_name(op_vars.op)), zero_fraction(op_vars.masked), ) summaries.append(sum_op) return summaries
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_compat_div, ) PruningOpVars = namedtuple( "PruningOpVars", ["op", "op_input", "update", "mask", "masked"] ) class PruningScope(object): """ Convenience class for dealing with scope and names for kernel sparsity in the tf graph. """ NM_KS = "nm_ks" NM_KS_OPS = "nm_ks_ops" OPS = "ops" OPS_INPUT = "input_ops" OPS_UPDATE = "update_ops" OPS_SUMMARY = "summary_ops" OPS_SCHEDULE = "schedule_ops" OPS_SPARSITY = "sparsity_ops" OP_COND_UPDATE = "nm_conditional_update" OP_SPARSITY = "nm_sparsity" OP_UPDATE_READY = "nm_update_ready" OP_MASKED_VAR = "nm_masked_var" OP_MASK_ASSIGN = "nm_mask_assign" OP_PRUNE_VARS_ASSIGN = "nm_prune_vars_assign" OP_MASK_UPDATE_NO_OP = "nm_mask_update_no_op" OP_MASK_UPDATE = "nm_mask_update" OP_WEIGHT_UPDATE = "nm_weight_update" OP_SAVE = "nm_save" VAR_MASK = "nm_mask" VAR_THRESHOLD = "nm_threshold" def general(ks_group: str, additional: str = None, trailing_slash: bool = False): """ Create a general kernel sparsity scope in the tf graph. Use cases are for generic ops like target sparsity, conditional updates, etc. :param ks_group: the group identifier the scope should be created under :param additional: any additional scope that should be added to the end :param trailing_slash: include a trailing forward slash if True, else False :return: the proper scope """ scope = PruningScope._format(PruningScope.NM_KS_OPS, ks_group) scope = PruningScope._format( scope, additional=additional, trailing_slash=trailing_slash ) return scope def model( op_tens: tf_compat.Tensor, ks_group: str, additional: str = None, trailing_slash: bool = False, ) -> str: """ Create a model specific kernel sparsity scope in the tf graph. Use cases are for the specific mask, threshold, etc variables to induce sparsity along with the ops to update those vars. :param op_tens: the op tensor to create the scope for :param ks_group: the group identifier the scope should be created under :param additional: any additional scope that should be added to the end :param trailing_slash: include a trailing forward slash if True, else False :return: the proper scope """ op_name = clean_tensor_name(op_tens) scope = PruningScope._format( "{}_{}".format(op_name, PruningScope.NM_KS), ks_group ) scope = PruningScope._format( scope, additional=additional, trailing_slash=trailing_slash ) return scope def collection_name(ks_group: str, name: str) -> str: """ Create a predictable name for a given variable / op in a group for lookup / storage in a collection :param ks_group: the group identifier the name belongs under :param name: the name of the op or variable to be stored or retrieved :return: the formatted name for use in a collection """ return "nm_ks_collection_{}_{}".format(ks_group, name) def _format( current: str, additional: str = None, trailing_slash: bool = False ) -> str: scope = current if additional is not None: scope = "{}/{}".format(current, additional) if trailing_slash: scope += "/" return scope The provided code snippet includes necessary dependencies for implementing the `apply_op_vars_masks` function. Write a Python function `def apply_op_vars_masks( pruning_op_vars: List[PruningOpVars], ks_group: str, sess: tf_compat.Session )` to solve the following problem: 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 to run the assign Here is the function: def apply_op_vars_masks( pruning_op_vars: List[PruningOpVars], ks_group: str, sess: tf_compat.Session ): """ 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 to run the assign """ for op_vars in pruning_op_vars: with tf_compat.name_scope( PruningScope.model(op_vars.op, ks_group, PruningScope.OP_SAVE) ): masked_var = tf_compat.multiply(op_vars.op_input, op_vars.mask) input_var = get_tensor_var(op_vars.op_input) assign = tf_compat.assign(input_var, masked_var) sess.run(assign)
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 to run the assign
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_compat_div, ) PruningOpVars = namedtuple( "PruningOpVars", ["op", "op_input", "update", "mask", "masked"] ) def get_or_create_graph_ops_pruning( graph: tf_compat.Graph, var_names: List[str], sparsity: tf_compat.Tensor, update_ready: tf_compat.Tensor, leave_enabled: bool, is_after_end_step: tf_compat.Tensor, ks_group: str, mask_creator: PruningMaskCreator, ) -> List[PruningOpVars]: """ Creates or retrieves (if previously created) the necessary variables and operators to gradually apply sparsity to a given list of operators in a graph. Handles setting a mask on an operator to the given sparsity. Sets the mask based on pruning away the lowest absolute magnitude weights. :param graph: the tf graph to pull the operator out of for applying the pruning to :param var_names: the names or regex patterns of names of variables to prune in the graph to the given sparsity :param sparsity: the target sparsity to use for assigning the masks :param update_ready: the tensor where if true will update the mask from sparsity, if false will not update the mask :param leave_enabled: True to continue masking the weights after end_epoch, False to stop masking :param is_after_end_step: tensor that is true if the current global step is after end_epoch :param ks_group: the group identifier the scope should be created under :param mask_creator: optional object to define sparisty mask creation :return: a list of the created or retrieved named tuples each containing the assignment op, mask variable, threshold tensor, and masked tensor """ ops = tf_compat.get_collection( PruningScope.collection_name(ks_group, PruningScope.OPS) ) ops_input = tf_compat.get_collection( PruningScope.collection_name(ks_group, PruningScope.OPS_INPUT) ) mask_updates = tf_compat.get_collection( PruningScope.collection_name(ks_group, PruningScope.OP_MASK_UPDATE) ) masks = tf_compat.get_collection( PruningScope.collection_name(ks_group, PruningScope.VAR_MASK) ) maskeds = tf_compat.get_collection( PruningScope.collection_name(ks_group, PruningScope.OP_MASKED_VAR) ) if ( len(ops) < 1 or len(ops_input) < 1 or len(mask_updates) < 1 or len(masks) < 1 or len(maskeds) < 1 ): # create new pruning ops pruning_op_vars = create_graph_ops_pruning( graph, var_names, sparsity, update_ready, leave_enabled, is_after_end_step, ks_group, mask_creator, ) else: # use collection pruning ops pruning_op_vars = [] for op, op_input, mask_update, mask, masked in zip( ops, ops_input, mask_updates, masks, maskeds ): pruning_op_vars.append( PruningOpVars(op, op_input, mask_update, mask, masked) ) return pruning_op_vars def get_or_create_ks_schedule_ops( global_step: tf_compat.Tensor, begin_step: int, end_step: int, update_step_freq: int, init_sparsity: float, final_sparsity: float, exponent: float, ks_group: str, ) -> Tuple[tf_compat.Tensor, tf_compat.Tensor]: """ Creates or retrieves (if previously created) a gradual schedule for model pruning (kernel sparsity). Creates a sparsity tensor that goes from init_sparsity til final_sparsity starting at begin_step and ending at end_step. Uses the global_step to map those. Additionally creates an update_ready tensor that is True if an update to the sparsity tensor should be run, False otherwise. :param global_step: the global optimizer step for the training graph :param begin_step: the global step to begin pruning at :param end_step: the global step to end pruning at :param update_step_freq: the number of global steps between each weight update :param init_sparsity: the starting value for sparsity of a weight tensor to be enforce :param final_sparsity: the end value for sparsity for a weight tensor to be enforce :param exponent: the exponent to use for interpolating between init_sparsity and final_sparsity higher values will lead to larger sparsity steps at the beginning vs the end ie: linear (1) vs cubic (3) :param ks_group: the group identifier the scope should be created under :return: a tuple containing the signal for update_ready and the target sparsity """ update_ready = tf_compat.get_collection( PruningScope.collection_name(ks_group, PruningScope.OP_UPDATE_READY) ) sparsity = tf_compat.get_collection( PruningScope.collection_name(ks_group, PruningScope.OP_SPARSITY) ) update_ready = update_ready[0] if len(update_ready) > 0 else None sparsity = sparsity[0] if len(sparsity) > 0 else None if update_ready is None or sparsity is None: update_ready, sparsity = create_ks_schedule_ops( global_step, begin_step, end_step, update_step_freq, init_sparsity, final_sparsity, exponent, ks_group, ) # add return state to collections tf_compat.add_to_collection( PruningScope.collection_name(ks_group, PruningScope.OP_UPDATE_READY), update_ready, ) tf_compat.add_to_collection( PruningScope.collection_name(ks_group, PruningScope.OP_SPARSITY), sparsity ) return update_ready, sparsity def get_scheduled_update_op( pruning_op_vars: List[PruningOpVars], ks_group: str, ): """ Creates model pruning (kernel sparsity) ops and vars in the graph to be applied over a specific schedule. Creates them for the ops in the graph such that they follow the given schedule. :param pruning_op_vars: List of tuples of operation tensors and masks. :param ks_group: the group identifier the scope should be created under :return: the update operation to run in a session """ update_op = tf_compat.get_collection( PruningScope.collection_name(ks_group, PruningScope.OP_COND_UPDATE) ) update_op = update_op[0] if len(update_op) > 0 else None if update_op is None: update_op = tf_compat.group(*[op_var.update for op_var in pruning_op_vars]) # add return state to collections tf_compat.add_to_collection( PruningScope.collection_name(ks_group, PruningScope.OP_COND_UPDATE), update_op, ) return update_op class PruningMaskCreator(ABC): """ Base abstract class for a sparsity mask creator. Subclasses should define all methods for creating masks and their initializers """ def get_mask_initializer( self, tensor: tf_compat.Tensor, ) -> Callable[[], tf_compat.Tensor]: """ :param tensor: A tensor of a model layer's weights :return: Tensor initializer function for this sparsity mask """ raise NotImplementedError() def create_sparsity_mask( self, tensor: tf_compat.Tensor, sparsity: tf_compat.Tensor, ) -> tf_compat.Tensor: """ :param tensor: A tensor of a model layer's weights :param sparsity: the target sparsity to use for assigning the masks :return: A sparsity mask close to the set sparsity based on the values of the input tensor """ raise NotImplementedError() The provided code snippet includes necessary dependencies for implementing the `get_or_create_ks_scheduled_graph_ops` function. Write a Python function `def get_or_create_ks_scheduled_graph_ops( graph: tf_compat.Graph, global_step: tf_compat.Variable, var_names: List[str], begin_step: int, end_step: int, update_step_freq: int, init_sparsity: float, final_sparsity: float, exponent: float, leave_enabled: bool, ks_group: str, mask_creator: PruningMaskCreator, ) -> Tuple[tf_compat.Tensor, List[PruningOpVars], tf_compat.Tensor, tf_compat.Tensor]` to solve the following problem: 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 operator out of for applying the pruning to :param global_step: the global optimizer step for the training graph :param var_names: the names or regex patterns of names of variables to prune in the graph :param begin_step: the global step to begin pruning at :param end_step: the global step to end pruning at :param update_step_freq: the number of global steps between each weight update :param init_sparsity: the starting value for sparsity of a weight tensor to be enforce :param final_sparsity: the end value for sparsity for a weight tensor to be enforce :param exponent: the exponent to use for interpolating between init_sparsity and final_sparsity higher values will lead to larger sparsity steps at the beginning vs the end ie: linear (1) vs cubic (3) :param leave_enabled: True to continue masking the weights after end_epoch, False to stop masking :param ks_group: the group identifier the scope should be created under :param mask_creator: optional object to define sparisty mask creation :return: a tuple containing the update operation to run in a session, a list of the pruning ops and vars for each desired op in the graph, the tensor containing the update_ready signal for the pruning ops, the tensor containing the set sparsity for the pruning ops Here is the function: def get_or_create_ks_scheduled_graph_ops( graph: tf_compat.Graph, global_step: tf_compat.Variable, var_names: List[str], begin_step: int, end_step: int, update_step_freq: int, init_sparsity: float, final_sparsity: float, exponent: float, leave_enabled: bool, ks_group: str, mask_creator: PruningMaskCreator, ) -> Tuple[tf_compat.Tensor, List[PruningOpVars], tf_compat.Tensor, tf_compat.Tensor]: """ 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 operator out of for applying the pruning to :param global_step: the global optimizer step for the training graph :param var_names: the names or regex patterns of names of variables to prune in the graph :param begin_step: the global step to begin pruning at :param end_step: the global step to end pruning at :param update_step_freq: the number of global steps between each weight update :param init_sparsity: the starting value for sparsity of a weight tensor to be enforce :param final_sparsity: the end value for sparsity for a weight tensor to be enforce :param exponent: the exponent to use for interpolating between init_sparsity and final_sparsity higher values will lead to larger sparsity steps at the beginning vs the end ie: linear (1) vs cubic (3) :param leave_enabled: True to continue masking the weights after end_epoch, False to stop masking :param ks_group: the group identifier the scope should be created under :param mask_creator: optional object to define sparisty mask creation :return: a tuple containing the update operation to run in a session, a list of the pruning ops and vars for each desired op in the graph, the tensor containing the update_ready signal for the pruning ops, the tensor containing the set sparsity for the pruning ops """ update_ready, sparsity = get_or_create_ks_schedule_ops( global_step, begin_step, end_step, update_step_freq, init_sparsity, final_sparsity, exponent, ks_group, ) is_after_end_step = tf_compat.greater(global_step, end_step) pruning_op_vars = get_or_create_graph_ops_pruning( graph, var_names, sparsity, update_ready, leave_enabled, is_after_end_step, ks_group, mask_creator, ) update_op = get_scheduled_update_op(pruning_op_vars, ks_group) return update_op, pruning_op_vars, update_ready, sparsity
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 operator out of for applying the pruning to :param global_step: the global optimizer step for the training graph :param var_names: the names or regex patterns of names of variables to prune in the graph :param begin_step: the global step to begin pruning at :param end_step: the global step to end pruning at :param update_step_freq: the number of global steps between each weight update :param init_sparsity: the starting value for sparsity of a weight tensor to be enforce :param final_sparsity: the end value for sparsity for a weight tensor to be enforce :param exponent: the exponent to use for interpolating between init_sparsity and final_sparsity higher values will lead to larger sparsity steps at the beginning vs the end ie: linear (1) vs cubic (3) :param leave_enabled: True to continue masking the weights after end_epoch, False to stop masking :param ks_group: the group identifier the scope should be created under :param mask_creator: optional object to define sparisty mask creation :return: a tuple containing the update operation to run in a session, a list of the pruning ops and vars for each desired op in the graph, the tensor containing the update_ready signal for the pruning ops, the tensor containing the set sparsity for the pruning ops
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_compat_div, ) PruningOpVars = namedtuple( "PruningOpVars", ["op", "op_input", "update", "mask", "masked"] ) def create_constant_op_pruning( op: tf_compat.Operation, op_input: tf_compat.Tensor, is_start_step: tf_compat.Tensor, is_end_step: tf_compat.Tensor, ks_group: str, ) -> PruningOpVars: """ Creates PruningOpVars with constant mask for the given operation on start step, sets mask to be all 1s for the weight tensor where the operation input is non zero and 0 elsewhere. At the end_step we revert the mask to be all 1s and update the weight. :param op: the operation to prune to the given sparsity :param op_input: the input tensor to op to create a constant mask for :param is_start_step: True only if we are at the start step. :param is_end_step: True only if we are at the start end step. :param ks_group: the group identifier the scope should be created under :return: a named tuple containing the assignment op, mask variable, threshold tensor, and masked tensor """ initial_vars = create_op_pruning_no_update(op, op_input, ks_group) op = initial_vars.op op_var_tens = initial_vars.op_input mask = initial_vars.mask masked = initial_vars.masked is_start_or_end_step = tf_compat.logical_or(is_start_step, is_end_step) def _set_constant_mask(): # Assign mask tensor to be 1 for all nonzero values of op_var_tens otherwise 0 # On end step, revert mask to be all 1s with tf_compat.name_scope( PruningScope.model( op, ks_group, additional=PruningScope.OPS_UPDATE, trailing_slash=True, ) ): new_mask = tf_compat.cond( is_start_step, lambda: tf_compat.cast( tf_compat.not_equal(op_var_tens, 0.0), dtype=op_var_tens.dtype ), lambda: tf_compat.ones(op_var_tens.shape, dtype=op_var_tens.dtype), ) weight_var = get_tensor_var(op_var_tens) return tf_compat.group( tf_compat.assign(mask, new_mask, name=PruningScope.OP_MASK_ASSIGN), tf_compat.assign( weight_var, masked, name=PruningScope.OP_WEIGHT_UPDATE ), ) def _no_op(): with tf_compat.name_scope( PruningScope.model( op, ks_group, additional=PruningScope.OPS_UPDATE, trailing_slash=True, ) ): # return no op wrapped in group to match update type return tf_compat.group( tf_compat.constant( 0.0, dtype=op_var_tens.dtype, name=PruningScope.OP_MASK_UPDATE_NO_OP ) ) with tf_compat.name_scope( PruningScope.model( op, ks_group, additional=PruningScope.OPS_UPDATE, trailing_slash=True, ) ): mask_update = tf_compat.cond( is_start_or_end_step, _set_constant_mask, _no_op, name=PruningScope.OP_MASK_UPDATE, ) return PruningOpVars(op, op_var_tens, mask_update, mask, masked) def get_scheduled_update_op( pruning_op_vars: List[PruningOpVars], ks_group: str, ): """ Creates model pruning (kernel sparsity) ops and vars in the graph to be applied over a specific schedule. Creates them for the ops in the graph such that they follow the given schedule. :param pruning_op_vars: List of tuples of operation tensors and masks. :param ks_group: the group identifier the scope should be created under :return: the update operation to run in a session """ update_op = tf_compat.get_collection( PruningScope.collection_name(ks_group, PruningScope.OP_COND_UPDATE) ) update_op = update_op[0] if len(update_op) > 0 else None if update_op is None: update_op = tf_compat.group(*[op_var.update for op_var in pruning_op_vars]) # add return state to collections tf_compat.add_to_collection( PruningScope.collection_name(ks_group, PruningScope.OP_COND_UPDATE), update_op, ) return update_op The provided code snippet includes necessary dependencies for implementing the `create_ks_scheduled_constant_graph_ops` function. Write a Python function `def create_ks_scheduled_constant_graph_ops( graph: tf_compat.Graph, global_step: tf_compat.Variable, var_names: List[str], begin_step: int, end_step: int, ks_group: str, ) -> Tuple[tf_compat.Tensor, List[PruningOpVars]]` to solve the following problem: 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 begin_step: the global step to begin pruning at :param end_step: the global step to end pruning at :param ks_group: the group identifier the scope should be created under :return: a tuple containing the update operation to run in a session, a list of the pruning ops and vars for each desired op in the graph Here is the function: def create_ks_scheduled_constant_graph_ops( graph: tf_compat.Graph, global_step: tf_compat.Variable, var_names: List[str], begin_step: int, end_step: int, ks_group: str, ) -> Tuple[tf_compat.Tensor, List[PruningOpVars]]: """ 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 begin_step: the global step to begin pruning at :param end_step: the global step to end pruning at :param ks_group: the group identifier the scope should be created under :return: a tuple containing the update operation to run in a session, a list of the pruning ops and vars for each desired op in the graph """ pruning_op_vars = [] is_start_step = tf_compat.equal(global_step, begin_step) is_end_step = tf_compat.equal(global_step, end_step) for op, op_input in get_ops_and_inputs_by_name_or_regex(var_names, graph): op_vars = create_constant_op_pruning( op, op_input, is_start_step, is_end_step, ks_group ) pruning_op_vars.append(op_vars) update_op = get_scheduled_update_op(pruning_op_vars, ks_group) return update_op, pruning_op_vars
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 begin_step: the global step to begin pruning at :param end_step: the global step to end pruning at :param ks_group: the group identifier the scope should be created under :return: a tuple containing the update operation to run in a session, a list of the pruning ops and vars for each desired op in the graph
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 dependencies for implementing the `epoch_to_steps` function. Write a Python function `def epoch_to_steps(epoch: float, steps_per_epoch: int, min_epoch: float = 0.0) -> int` to solve the following problem: :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 Here is the function: def epoch_to_steps(epoch: float, steps_per_epoch: int, min_epoch: float = 0.0) -> int: """ :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 """ if epoch < min_epoch: epoch = min_epoch return round(steps_per_epoch * epoch)
: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: int, init_lr: float, gamma: float, name: str = "exponential_lr_schedule", ) -> tf_compat.Tensor` to solve the following problem: 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 step to end the exponential schedule on, can be set to -1 and in that event will continually update the LR :param step_size: the number of steps between each gamma update to the init_lr :param init_lr: the learning rate to start the schedule with :param gamma: the decay weight to decrease init_lr by after every step_size interval :param name: the name scope to create the graph under :return: the calculated learning rate tensor Here is the function: def step_lr_schedule( global_step: tf_compat.Tensor, start_step: int, end_step: int, step_size: int, init_lr: float, gamma: float, name: str = "exponential_lr_schedule", ) -> tf_compat.Tensor: """ 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 step to end the exponential schedule on, can be set to -1 and in that event will continually update the LR :param step_size: the number of steps between each gamma update to the init_lr :param init_lr: the learning rate to start the schedule with :param gamma: the decay weight to decrease init_lr by after every step_size interval :param name: the name scope to create the graph under :return: the calculated learning rate tensor """ with tf_compat.name_scope(name): global_step = tf_compat.cast(global_step, tf_compat.int64) max_updates = tf_compat.constant( (end_step - start_step) // step_size if end_step > 0 else -1, dtype=tf_compat.int64, name="max_updates", ) start_step = tf_compat.constant( start_step, dtype=tf_compat.int64, name="start_step" ) end_step = tf_compat.constant(end_step, dtype=tf_compat.int64, name="end_step") init_lr = tf_compat.constant(init_lr, dtype=tf_compat.float32, name="init_lr") step_size = tf_compat.constant( step_size, dtype=tf_compat.int64, name="step_size" ) gamma = tf_compat.constant(gamma, dtype=tf_compat.float32, name="gamma") before = tf_compat.less(global_step, start_step, name="before") after = tf_compat.logical_and( tf_compat.greater_equal(global_step, end_step, name="after"), tf_compat.not_equal(end_step, tf_compat.constant(-1, tf_compat.int64)), ) def _calc_lr(): steps = tf_compat.subtract(global_step, start_step) updates = tf_compat.cond( after, lambda: max_updates, lambda: tf_compat.cast( tf_compat.floor(tf_compat.divide(steps, step_size)), tf_compat.int64, ), ) mult_g = tf_compat.pow(gamma, tf_compat.cast(updates, tf_compat.float32)) return tf_compat.multiply(init_lr, mult_g) learning_rate = tf_compat.cond( before, lambda: init_lr, _calc_lr, name="learning_rate" ) return learning_rate
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 step to end the exponential schedule on, can be set to -1 and in that event will continually update the LR :param step_size: the number of steps between each gamma update to the init_lr :param init_lr: the learning rate to start the schedule with :param gamma: the decay weight to decrease init_lr by after every step_size interval :param name: the name scope to create the graph under :return: the calculated learning rate tensor
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: List[int], init_lr: float, gamma: float, name: str = "multi_step_lr_schedule", )` to solve the following problem: 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 steps to decrease the learning rate at, these are the number of steps that must pass after start_step to decrease lr :param init_lr: the learning rate to start the schedule with :param gamma: the decay weight to decrease init_lr by after every step_size interval :param name: the name scope to create the graph under :return: the calculated learning rate tensor Here is the function: def multi_step_lr_schedule( global_step: tf_compat.Tensor, start_step: int, milestone_steps: List[int], init_lr: float, gamma: float, name: str = "multi_step_lr_schedule", ): """ 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 steps to decrease the learning rate at, these are the number of steps that must pass after start_step to decrease lr :param init_lr: the learning rate to start the schedule with :param gamma: the decay weight to decrease init_lr by after every step_size interval :param name: the name scope to create the graph under :return: the calculated learning rate tensor """ with tf_compat.name_scope(name): global_step = tf_compat.cast(global_step, tf_compat.int64) milestone_steps = tf_compat.constant( [mile + start_step for mile in milestone_steps], dtype=tf_compat.int64, name="milestone_steps", ) start_step = tf_compat.constant( start_step, dtype=tf_compat.int64, name="start_step" ) init_lr = tf_compat.constant(init_lr, dtype=tf_compat.float32, name="init_lr") gamma = tf_compat.constant(gamma, dtype=tf_compat.float32, name="gamma") before = tf_compat.less(global_step, start_step, name="before") def _calc_lr(): less = tf_compat.cast( tf_compat.greater_equal(global_step, milestone_steps), tf_compat.int64 ) updates = tf_compat.reduce_sum(less) mult_g = tf_compat.pow(gamma, tf_compat.cast(updates, tf_compat.float32)) return tf_compat.multiply(init_lr, mult_g) learning_rate = tf_compat.cond( before, lambda: init_lr, _calc_lr, name="learning_rate" ) return learning_rate
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 steps to decrease the learning rate at, these are the number of steps that must pass after start_step to decrease lr :param init_lr: the learning rate to start the schedule with :param gamma: the decay weight to decrease init_lr by after every step_size interval :param name: the name scope to create the graph under :return: the calculated learning rate tensor
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.modifier import NM_RECAL, Modifier, ScheduledModifier from sparseml.tensorflow_v1.utils import tf_compat from sparsezoo.objects import File class ScheduledModifier(Modifier, BaseScheduled): """ The base scheduled update modifier implementation, all scheduled modifiers should inherit from this class. Offers convenient properties needed for scheduled update modifiers: start_epoch, end_epoch | Modifiers are expected to implement up to 3 different functions for TensorFlow: | - create_ops - inject ops into the graph before the training begins | - create_extras - create extras like learning rate controls before training | - complete_graph - finalize the graph after training has completed | | Life cycle: | - create model graph | - manager.create_ops() | - manager.create_extras() | - train graph | - manager.complete_graph() | - export graph :param start_epoch: The epoch to start the modifier at :param end_epoch: The epoch to end the modifier at :param min_start: The minimum acceptable value for start_epoch, default -1 :param min_end: The minimum acceptable value for end_epoch, default 0 :param end_comparator: integer value representing how the end_epoch should be compared to start_epoch. if == None, then end_epoch can only be set to what its initial value was. if == -1, then end_epoch can be -1, equal, or greater than start_epoch. if == 0, then end_epoch can be equal to or greater than start_epoch. if == 1, then end_epoch can only be greater than start_epoch. :param kwargs: standard key word args, used to support multi inheritance """ def __init__( self, start_epoch: float = -1.0, end_epoch: float = -1.0, min_start: float = -1.0, min_end: float = -1.0, end_comparator: Union[int, None] = 0, **kwargs, ): super().__init__( start_epoch=start_epoch, end_epoch=end_epoch, min_start=min_start, min_end=min_end, end_comparator=end_comparator, **kwargs, ) def start_end_steps( self, steps_per_epoch: int, after_optim: bool ) -> Tuple[int, int]: """ Calculate the start and end steps for this modifier given a certain amount of steps per epoch :param steps_per_epoch: the number of steps (or batches) taken per epoch :param after_optim: True if the start and end are for an operation after the optimizer update step has run, False for before :return: a tuple containing (the converted start step, the converted end step) """ start_step = ( round(self._start_epoch * steps_per_epoch) if self.start_epoch >= 0.0 else 0 ) end_step = ( round(self._end_epoch * steps_per_epoch) - 1 if self.end_epoch >= 0.0 else -1 ) if after_optim: start_step += 1 if end_step > -1: end_step += 1 return start_step, end_step def _group_modifiers(modifiers: List[ScheduledModifier]) -> List[ScheduledModifier]: group_classes = {} # type: Dict[str, Callable] group_mods = {} # type: Dict[str, List[ScheduledModifier]] grouped = [] for mod in modifiers: group = mod.get_group() if group: if group.__name__ not in group_classes: group_classes[group.__name__] = group group_mods[group.__name__] = [] group_mods[group.__name__].append(mod) else: grouped.append(mod) for group, group_const in group_classes.items(): grouped.append(group_const(group_mods[group])) return grouped
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_v1.sparsification import sparsification_info def detect_framework(item: Any) -> Framework: """ Detect the supported ML framework for a given item specifically for the tensorflow package. Supported input types are the following: - A Framework enum - A string of any case representing the name of the framework (deepsparse, onnx, keras, tensorflow, tensorflow_v1) - A supported file type within the framework such as model files: (onnx, pth, h5, pb) - An object from a supported ML framework such as a model instance If the framework cannot be determined, will return Framework.unknown :param item: The item to detect the ML framework for :type item: Any :return: The detected framework from the given item :rtype: Framework """ framework = Framework.unknown if isinstance(item, Framework): _LOGGER.debug("framework detected from Framework instance") framework = item elif isinstance(item, str) and item.lower().strip() in Framework.__members__: _LOGGER.debug("framework detected from Framework string instance") framework = Framework[item.lower().strip()] elif isinstance(item, str) and ( "tensorflow" in item.lower().strip() or "tf" in item.lower().strip() ): _LOGGER.debug("framework detected from tensorflow text") # string, check if it's a string saying onnx first framework = Framework.tensorflow_v1 elif isinstance(item, str) and ".pb" in item.lower().strip(): _LOGGER.debug("framework detected from .pb") # string, check if it's a file url or path that ends with onnx extension framework = Framework.tensorflow_v1 elif check_tensorflow_install(raise_on_error=False): if isinstance(item, tf_compat.Graph) or isinstance(item, tf_compat.Session): _LOGGER.debug("framework detected from tensorflow instance") # tensorflow native support framework = Framework.tensorflow_v1 return framework class Framework(Enum): """ Framework types known of/supported within the sparseml/deepsparse ecosystem """ unknown = "unknown" deepsparse = "deepsparse" onnx = "onnx" keras = "keras" pytorch = "pytorch" tensorflow_v1 = "tensorflow_v1" The provided code snippet includes necessary dependencies for implementing the `is_supported` function. Write a Python function `def is_supported(item: Any) -> bool` to solve the following problem: :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 Here is the function: def is_supported(item: Any) -> bool: """ :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 """ framework = detect_framework(item) return framework == Framework.tensorflow_v1
: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_v1.sparsification import sparsification_info class Framework(Enum): """ Framework types known of/supported within the sparseml/deepsparse ecosystem """ unknown = "unknown" deepsparse = "deepsparse" onnx = "onnx" keras = "keras" pytorch = "pytorch" tensorflow_v1 = "tensorflow_v1" def get_version( package_name: str, raise_on_error: bool, alternate_package_names: Optional[List[str]] = None, ) -> Optional[str]: """ :param package_name: The name of the full package, as it would be imported, to get the version for :type package_name: str :param raise_on_error: True to raise an error if package is not installed or couldn't be imported, False to return None :type raise_on_error: bool :param alternate_package_names: List of alternate names to look for the package under if package_name is not found. Useful for nightly builds. :type alternate_package_names: Optional[List[str]] :return: the version of the desired package if detected, otherwise raises an error :rtype: str """ current_version: Optional[str] = None version_err = None try: current_version = pkg_resources.get_distribution(package_name).version except Exception as err: version_err = err if version_err and alternate_package_names: next_package = alternate_package_names.pop() return get_version(next_package, raise_on_error, alternate_package_names) if version_err and raise_on_error: raise ImportError( f"error while getting current version for {package_name}: {version_err}" ) return current_version if not version_err else None def check_tensorflow_install( min_version: Optional[str] = _TENSORFLOW_MIN_VERSION, max_version: Optional[str] = _TENSORFLOW_MAX_VERSION, raise_on_error: bool = True, allow_env_ignore_flag: bool = True, ) -> bool: """ Check that the tensorflow package is installed. If raise_on_error, will raise an ImportError if it is not installed or the required version range, if set, is not installed. If not raise_on_error, will return True if installed with required version and False otherwise. :param min_version: The minimum version for tensorflow that it must be greater than or equal to, if unset will require no minimum version :type min_version: str :param max_version: The maximum version for tensorflow that it must be less than or equal to, if unset will require no maximum version. :type max_version: str :param raise_on_error: True to raise any issues such as not installed, minimum version, or maximum version as ImportError. False to return the result. :type raise_on_error: bool :param allow_env_ignore_flag: True to allow the env variable SPARSEML_IGNORE_TFV1 to ignore the tensorflow install and version checks. False to ignore the ignore flag. :type allow_env_ignore_flag: bool :return: If raise_on_error, will return False if tensorflow is not installed or the version is outside the accepted bounds and True if everything is correct. :rtype: bool """ if allow_env_ignore_flag and os.getenv("SPARSEML_IGNORE_TFV1", False): return True if tensorflow_err is not None: if raise_on_error: raise tensorflow_err return False return check_version( "tensorflow", min_version, max_version, raise_on_error, alternate_package_names=["tensorflow-gpu"], ) The provided code snippet includes necessary dependencies for implementing the `framework_info` function. Write a Python function `def framework_info() -> FrameworkInfo` to solve the following problem: 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 Here is the function: def framework_info() -> FrameworkInfo: """ 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 """ cpu_provider = FrameworkInferenceProviderInfo( name="cpu", description="Base CPU provider within TensorFlow", device="cpu", supported_sparsification=SparsificationInfo(), # TODO: fill in when available available=check_tensorflow_install(raise_on_error=False), properties={}, warnings=[], ) gpu_provider = FrameworkInferenceProviderInfo( name="cuda", description="Base GPU CUDA provider within TensorFlow", device="gpu", supported_sparsification=SparsificationInfo(), # TODO: fill in when available available=( check_tensorflow_install(raise_on_error=False) and get_version("tensorflow_gpu", raise_on_error=False) is not None and tf_compat.test.is_gpu_available() ), properties={}, warnings=[], ) return FrameworkInfo( framework=Framework.tensorflow_v1, package_versions={ "tensorflow": ( get_version(package_name="tensorflow", raise_on_error=False) or get_version(package_name="tensorflow_gpu", raise_on_error=False) ), "onnx": get_version(package_name="onnx", raise_on_error=False), "tf2onnx": get_version(package_name="tf2onnx", raise_on_error=False), "sparsezoo": get_version( package_name="sparsezoo", raise_on_error=False, alternate_package_names=["sparsezoo-nightly"], ), "sparseml": get_version( package_name="sparseml", raise_on_error=False, alternate_package_names=["sparseml-nightly"], ), }, sparsification=sparsification_info(), inference_providers=[cpu_provider, gpu_provider], properties={}, training_available=True, sparsification_available=True, exporting_onnx_available=True, inference_available=True, )
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_v1.utils import tf_compat def _dw_sep_block( name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], out_channels: int, stride: int, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): out = depthwise_conv2d_block( "depth", x_tens, training, int(x_tens.shape[3]), kernel_size=3, padding=1, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, gamma_initializer=gamma_initializer, ) out = conv2d_block( "point", out, training, out_channels, kernel_size=1, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) return out
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_v1.utils import tf_compat class MobileNetSection(object): """ Settings to describe how to put together a MobileNet architecture using user supplied configurations. :param num_blocks: the number of depthwise separable blocks to put in the section :param out_channels: the number of output channels from the section :param downsample: True to apply stride 2 for down sampling of the input, False otherwise """ def __init__(self, num_blocks: int, out_channels: int, downsample: bool): self.num_blocks = num_blocks self.out_channels = out_channels self.downsample = downsample def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): stride = 2 if self.downsample else 1 for block in range(self.num_blocks): out = _dw_sep_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) stride = 1 return out def mobilenet_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[MobileNetSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Graph constructor for MobileNet implementation. :param x_tens: 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 sec_settings: The settings for each section in the MobileNet modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): out = _input( x_tens, training, kernel_initializer, bias_initializer, gamma_initializer ) for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=[ "mobilenet", "mobilenet_100", "mobilenet-v1", "mobilenet-v1-100", "mobilenet_v1", "mobilenet_v1_100", "mobilenetv1_1.0", ], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="mobilenet_v1", sub_architecture="1.0", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/dense/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `mobilenet` function. Write a Python function `def mobilenet( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = "single", kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def mobilenet( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = "single", kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ MobileNetSection(num_blocks=1, out_channels=64, downsample=False), MobileNetSection(num_blocks=2, out_channels=128, downsample=True), MobileNetSection(num_blocks=2, out_channels=256, downsample=True), MobileNetSection(num_blocks=6, out_channels=512, downsample=True), MobileNetSection(num_blocks=2, out_channels=1024, downsample=True), ] return mobilenet_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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_v1.utils import tf_compat def _make_divisible( value: float, divisor: int, min_value: Union[int, None] = None ) -> int: if min_value is None: min_value = divisor new_value = max(min_value, int(value + divisor / 2) // divisor * divisor) if new_value < 0.9 * value: new_value += divisor return new_value
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_v1.utils import tf_compat def _input_inverted_bottleneck_block( name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], out_channels: int, exp_channels: int, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): out = conv2d_block( "expand", x_tens, training, exp_channels, kernel_size=3, padding=1, stride=2, act="relu6", kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = depthwise_conv2d_block( "spatial", out, training, exp_channels, kernel_size=3, padding="same", stride=1, act="relu6", kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = conv2d_block( "compress", out, training, out_channels, kernel_size=1, act=None, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) return out
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_v1.utils import tf_compat def _inverted_bottleneck_block( name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], out_channels: int, exp_channels: int, stride: int, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): out = conv2d_block( "expand", x_tens, training, exp_channels, kernel_size=1, act="relu6", kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = depthwise_conv2d_block( "spatial", out, training, exp_channels, kernel_size=3, stride=stride, act="relu6", kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = conv2d_block( "compress", out, training, out_channels, kernel_size=1, act=None, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) if stride == 1 and int(x_tens.shape[3]) == out_channels: out = tf_compat.add(out, x_tens) return out
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_v1.utils import tf_compat def mobilenet_v2_width( width_mult: float, inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ Standard MobileNetV2 implementation for a given width; expected input shape is (B, 224, 224, 3) :param width_mult: The width multiplier for the architecture to create. 1.0 is standard, 0.5 is half the size, 2.0 is twice the size. :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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ MobileNetV2Section( num_blocks=1, out_channels=16, exp_channels=32, downsample=False, init_section=True, width_mult=width_mult, ), MobileNetV2Section( num_blocks=2, out_channels=24, exp_ratio=6, downsample=True, init_section=False, width_mult=width_mult, ), MobileNetV2Section( num_blocks=3, out_channels=32, exp_ratio=6, downsample=True, init_section=False, width_mult=width_mult, ), MobileNetV2Section( num_blocks=4, out_channels=64, exp_ratio=6, downsample=True, init_section=False, width_mult=width_mult, ), MobileNetV2Section( num_blocks=3, out_channels=96, exp_ratio=6, downsample=False, init_section=False, width_mult=width_mult, ), MobileNetV2Section( num_blocks=3, out_channels=160, exp_ratio=6, downsample=True, init_section=False, width_mult=width_mult, ), MobileNetV2Section( num_blocks=1, out_channels=320, exp_ratio=6, downsample=False, init_section=False, width_mult=width_mult, ), ] return mobilenet_v2_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) key=[ "mobilenetv2", "mobilenet_v2", "mobilenet_v2_100", "mobilenet-v2", "mobilenet-v2-100", "mobilenetv2_1.0", ], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="mobilenet_v2", sub_architecture="1.0", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/dense/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `mobilenet_v2` function. Write a Python function `def mobilenet_v2( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def mobilenet_v2( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ return mobilenet_v2_width( 1.0, inputs, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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 _identity_modifier( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], out_channels: int, stride: int, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: out = conv2d_block( "identity", x_tens, training, out_channels, kernel_size=1, stride=stride, act=None, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) return out def _basic_block( name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], out_channels: int, stride: int, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): out = conv2d_block( "conv_bn_0", x_tens, training, out_channels, kernel_size=3, stride=stride, padding=1, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = conv2d_block( "conv_bn_1", out, training, out_channels, kernel_size=3, padding=1, act=None, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) if stride > 1 or int(x_tens.shape[3]) != out_channels: out = tf_compat.add( out, _identity_modifier( x_tens, training, out_channels, stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ), ) else: out = tf_compat.add(out, x_tens) out = activation(out, act="relu", name="act_out") return out
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 _identity_modifier( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], out_channels: int, stride: int, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: out = conv2d_block( "identity", x_tens, training, out_channels, kernel_size=1, stride=stride, act=None, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) return out def _bottleneck_block( name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], out_channels: int, proj_channels: int, stride: int, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): out = conv2d_block( "conv_bn_0", x_tens, training, proj_channels, kernel_size=1, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = conv2d_block( "conv_bn_1", out, training, proj_channels, kernel_size=3, stride=stride, padding=1, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = conv2d_block( "conv_bn_2", out, training, out_channels, kernel_size=1, act=None, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) if stride > 1 or int(x_tens.shape[3]) != out_channels: out = tf_compat.add( out, _identity_modifier( x_tens, training, out_channels, stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ), ) else: out = tf_compat.add(out, x_tens) out = activation(out, act="relu", name="act_out") return out
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 ResNetSection(object): """ Settings to describe how to put together a ResNet based architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (ie Basic or Bottleneck blocks) :param out_channels: the number of output channels from the section :param downsample: True to apply stride 2 for downsampling of the input, False otherwise :param proj_channels: The number of channels in the projection for a bottleneck block, if < 0 then uses basic """ def __init__( self, num_blocks: int, out_channels: int, downsample: bool, proj_channels: int = -1, ): self.num_blocks = num_blocks self.out_channels = out_channels self.downsample = downsample self.proj_channels = proj_channels def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): stride = 2 if self.downsample else 1 for block in range(self.num_blocks): if self.proj_channels > 0: out = _bottleneck_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, proj_channels=self.proj_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) else: out = _basic_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) stride = 1 return out def resnet_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[ResNetSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch: bool = False, ) -> tf_compat.Tensor: """ Graph constructor for ResNet implementation. :param x_tens: 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 sec_settings: The settings for each section in the ResNet modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :param simplified_arch: Whether the network is a simplified version for the Cifar10/100 dataset :return: the output tensor from the created graph """ with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): out = _input( x_tens, training, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch=simplified_arch, ) for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["resnet18", "resnet_18", "resnet-18", "resnetv1_18", "resnetv1-18"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="resnet_v1", sub_architecture="18", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/dense/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `resnet18` function. Write a Python function `def resnet18( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def resnet18( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ ResNetSection(num_blocks=2, out_channels=64, downsample=False), ResNetSection(num_blocks=2, out_channels=128, downsample=True), ResNetSection(num_blocks=2, out_channels=256, downsample=True), ResNetSection(num_blocks=2, out_channels=512, downsample=True), ] return resnet_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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 ResNetSection(object): def __init__( self, num_blocks: int, out_channels: int, downsample: bool, proj_channels: int = -1, ): def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: def resnet_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[ResNetSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch: bool = False, ) -> tf_compat.Tensor: def resnet20( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 10, class_type: str = "single", kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: with tf_compat.variable_scope("resnet20", reuse=tf_compat.AUTO_REUSE): sec_settings = [ ResNetSection(num_blocks=2, out_channels=16, downsample=False), ResNetSection(num_blocks=2, out_channels=32, downsample=True), ResNetSection(num_blocks=2, out_channels=64, downsample=True), ] net = resnet_const( inputs, training, sec_settings, num_classes, class_type=class_type, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, simplified_arch=True, ) return net
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 ResNetSection(object): """ Settings to describe how to put together a ResNet based architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (ie Basic or Bottleneck blocks) :param out_channels: the number of output channels from the section :param downsample: True to apply stride 2 for downsampling of the input, False otherwise :param proj_channels: The number of channels in the projection for a bottleneck block, if < 0 then uses basic """ def __init__( self, num_blocks: int, out_channels: int, downsample: bool, proj_channels: int = -1, ): self.num_blocks = num_blocks self.out_channels = out_channels self.downsample = downsample self.proj_channels = proj_channels def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): stride = 2 if self.downsample else 1 for block in range(self.num_blocks): if self.proj_channels > 0: out = _bottleneck_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, proj_channels=self.proj_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) else: out = _basic_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) stride = 1 return out def resnet_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[ResNetSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch: bool = False, ) -> tf_compat.Tensor: """ Graph constructor for ResNet implementation. :param x_tens: 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 sec_settings: The settings for each section in the ResNet modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :param simplified_arch: Whether the network is a simplified version for the Cifar10/100 dataset :return: the output tensor from the created graph """ with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): out = _input( x_tens, training, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch=simplified_arch, ) for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["resnet18", "resnet_18", "resnet-18", "resnetv1_18", "resnetv1-18"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="resnet_v1", sub_architecture="18", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/dense/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `resnet34` function. Write a Python function `def resnet34( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def resnet34( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ ResNetSection(num_blocks=3, out_channels=64, downsample=False), ResNetSection(num_blocks=4, out_channels=128, downsample=True), ResNetSection(num_blocks=6, out_channels=256, downsample=True), ResNetSection(num_blocks=3, out_channels=512, downsample=True), ] return resnet_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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 ResNetSection(object): """ Settings to describe how to put together a ResNet based architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (ie Basic or Bottleneck blocks) :param out_channels: the number of output channels from the section :param downsample: True to apply stride 2 for downsampling of the input, False otherwise :param proj_channels: The number of channels in the projection for a bottleneck block, if < 0 then uses basic """ def __init__( self, num_blocks: int, out_channels: int, downsample: bool, proj_channels: int = -1, ): self.num_blocks = num_blocks self.out_channels = out_channels self.downsample = downsample self.proj_channels = proj_channels def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): stride = 2 if self.downsample else 1 for block in range(self.num_blocks): if self.proj_channels > 0: out = _bottleneck_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, proj_channels=self.proj_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) else: out = _basic_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) stride = 1 return out def resnet_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[ResNetSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch: bool = False, ) -> tf_compat.Tensor: """ Graph constructor for ResNet implementation. :param x_tens: 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 sec_settings: The settings for each section in the ResNet modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :param simplified_arch: Whether the network is a simplified version for the Cifar10/100 dataset :return: the output tensor from the created graph """ with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): out = _input( x_tens, training, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch=simplified_arch, ) for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["resnet18", "resnet_18", "resnet-18", "resnetv1_18", "resnetv1-18"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="resnet_v1", sub_architecture="18", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/dense/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `resnet50` function. Write a Python function `def resnet50( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def resnet50( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ ResNetSection( num_blocks=3, out_channels=256, downsample=False, proj_channels=64, ), ResNetSection( num_blocks=4, out_channels=512, downsample=True, proj_channels=128, ), ResNetSection( num_blocks=6, out_channels=1024, downsample=True, proj_channels=256, ), ResNetSection( num_blocks=3, out_channels=2048, downsample=True, proj_channels=512, ), ] return resnet_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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 ResNetSection(object): """ Settings to describe how to put together a ResNet based architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (ie Basic or Bottleneck blocks) :param out_channels: the number of output channels from the section :param downsample: True to apply stride 2 for downsampling of the input, False otherwise :param proj_channels: The number of channels in the projection for a bottleneck block, if < 0 then uses basic """ def __init__( self, num_blocks: int, out_channels: int, downsample: bool, proj_channels: int = -1, ): self.num_blocks = num_blocks self.out_channels = out_channels self.downsample = downsample self.proj_channels = proj_channels def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): stride = 2 if self.downsample else 1 for block in range(self.num_blocks): if self.proj_channels > 0: out = _bottleneck_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, proj_channels=self.proj_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) else: out = _basic_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) stride = 1 return out def resnet_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[ResNetSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch: bool = False, ) -> tf_compat.Tensor: """ Graph constructor for ResNet implementation. :param x_tens: 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 sec_settings: The settings for each section in the ResNet modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :param simplified_arch: Whether the network is a simplified version for the Cifar10/100 dataset :return: the output tensor from the created graph """ with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): out = _input( x_tens, training, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch=simplified_arch, ) for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["resnet18", "resnet_18", "resnet-18", "resnetv1_18", "resnetv1-18"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="resnet_v1", sub_architecture="18", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/dense/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `resnet101` function. Write a Python function `def resnet101( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def resnet101( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ ResNetSection( num_blocks=3, out_channels=256, downsample=False, proj_channels=64, ), ResNetSection( num_blocks=4, out_channels=512, downsample=True, proj_channels=128, ), ResNetSection( num_blocks=23, out_channels=1024, downsample=True, proj_channels=256, ), ResNetSection( num_blocks=3, out_channels=2048, downsample=True, proj_channels=512, ), ] return resnet_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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 ResNetSection(object): """ Settings to describe how to put together a ResNet based architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (ie Basic or Bottleneck blocks) :param out_channels: the number of output channels from the section :param downsample: True to apply stride 2 for downsampling of the input, False otherwise :param proj_channels: The number of channels in the projection for a bottleneck block, if < 0 then uses basic """ def __init__( self, num_blocks: int, out_channels: int, downsample: bool, proj_channels: int = -1, ): self.num_blocks = num_blocks self.out_channels = out_channels self.downsample = downsample self.proj_channels = proj_channels def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): stride = 2 if self.downsample else 1 for block in range(self.num_blocks): if self.proj_channels > 0: out = _bottleneck_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, proj_channels=self.proj_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) else: out = _basic_block( name="block_{}".format(block), x_tens=out, training=training, out_channels=self.out_channels, stride=stride, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) stride = 1 return out def resnet_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[ResNetSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch: bool = False, ) -> tf_compat.Tensor: """ Graph constructor for ResNet implementation. :param x_tens: 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 sec_settings: The settings for each section in the ResNet modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :param simplified_arch: Whether the network is a simplified version for the Cifar10/100 dataset :return: the output tensor from the created graph """ with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): out = _input( x_tens, training, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, simplified_arch=simplified_arch, ) for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["resnet18", "resnet_18", "resnet-18", "resnetv1_18", "resnetv1-18"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="resnet_v1", sub_architecture="18", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/dense/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `resnet152` function. Write a Python function `def resnet152( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def resnet152( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ ResNetSection( num_blocks=3, out_channels=256, downsample=False, proj_channels=64, ), ResNetSection( num_blocks=8, out_channels=512, downsample=True, proj_channels=128, ), ResNetSection( num_blocks=36, out_channels=1024, downsample=True, proj_channels=256, ), ResNetSection( num_blocks=3, out_channels=2048, downsample=True, proj_channels=512, ), ] return resnet_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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(object): """ Settings to describe how to put together a VGG architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (conv [bn] relu) :param out_channels: the number of output channels from the section :param use_batchnorm: True to put batchnorm after each conv, False otherwise """ def __init__(self, num_blocks: int, out_channels: int, use_batchnorm: bool): self.num_blocks = num_blocks self.out_channels = out_channels self.use_batchnorm = use_batchnorm def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): for block in range(self.num_blocks): out = conv2d_block( name="block_{}".format(block), x_tens=out, training=training, channels=self.out_channels, kernel_size=3, include_bn=self.use_batchnorm, include_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = pool2d( name="pool", x_tens=out, type_="max", pool_size=2, strides=2, padding="valid", ) return out def vgg_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[VGGSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Graph constructor for VGG implementation. :param x_tens: The input tensor to the VGG architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param sec_settings: The settings for each section in the VGG modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ out = x_tens with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["vgg11", "vgg_11", "vgg-11"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="vgg", sub_architecture="11", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/mlp_2/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `vgg11` function. Write a Python function `def vgg11( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def vgg11( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ VGGSection(num_blocks=1, out_channels=64, use_batchnorm=False), VGGSection(num_blocks=1, out_channels=128, use_batchnorm=False), VGGSection(num_blocks=2, out_channels=256, use_batchnorm=False), VGGSection(num_blocks=2, out_channels=512, use_batchnorm=False), VGGSection(num_blocks=2, out_channels=512, use_batchnorm=False), ] return vgg_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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(object): """ Settings to describe how to put together a VGG architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (conv [bn] relu) :param out_channels: the number of output channels from the section :param use_batchnorm: True to put batchnorm after each conv, False otherwise """ def __init__(self, num_blocks: int, out_channels: int, use_batchnorm: bool): self.num_blocks = num_blocks self.out_channels = out_channels self.use_batchnorm = use_batchnorm def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): for block in range(self.num_blocks): out = conv2d_block( name="block_{}".format(block), x_tens=out, training=training, channels=self.out_channels, kernel_size=3, include_bn=self.use_batchnorm, include_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = pool2d( name="pool", x_tens=out, type_="max", pool_size=2, strides=2, padding="valid", ) return out def vgg_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[VGGSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Graph constructor for VGG implementation. :param x_tens: The input tensor to the VGG architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param sec_settings: The settings for each section in the VGG modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ out = x_tens with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["vgg11", "vgg_11", "vgg-11"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="vgg", sub_architecture="11", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/mlp_2/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `vgg11bn` function. Write a Python function `def vgg11bn( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def vgg11bn( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ VGGSection(num_blocks=1, out_channels=64, use_batchnorm=True), VGGSection(num_blocks=1, out_channels=128, use_batchnorm=True), VGGSection(num_blocks=2, out_channels=256, use_batchnorm=True), VGGSection(num_blocks=2, out_channels=512, use_batchnorm=True), VGGSection(num_blocks=2, out_channels=512, use_batchnorm=True), ] return vgg_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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(object): """ Settings to describe how to put together a VGG architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (conv [bn] relu) :param out_channels: the number of output channels from the section :param use_batchnorm: True to put batchnorm after each conv, False otherwise """ def __init__(self, num_blocks: int, out_channels: int, use_batchnorm: bool): self.num_blocks = num_blocks self.out_channels = out_channels self.use_batchnorm = use_batchnorm def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): for block in range(self.num_blocks): out = conv2d_block( name="block_{}".format(block), x_tens=out, training=training, channels=self.out_channels, kernel_size=3, include_bn=self.use_batchnorm, include_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = pool2d( name="pool", x_tens=out, type_="max", pool_size=2, strides=2, padding="valid", ) return out def vgg_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[VGGSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Graph constructor for VGG implementation. :param x_tens: The input tensor to the VGG architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param sec_settings: The settings for each section in the VGG modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ out = x_tens with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["vgg11", "vgg_11", "vgg-11"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="vgg", sub_architecture="11", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/mlp_2/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `vgg13` function. Write a Python function `def vgg13( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def vgg13( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ VGGSection(num_blocks=2, out_channels=64, use_batchnorm=False), VGGSection(num_blocks=2, out_channels=128, use_batchnorm=False), VGGSection(num_blocks=2, out_channels=256, use_batchnorm=False), VGGSection(num_blocks=2, out_channels=512, use_batchnorm=False), VGGSection(num_blocks=2, out_channels=512, use_batchnorm=False), ] return vgg_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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(object): """ Settings to describe how to put together a VGG architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (conv [bn] relu) :param out_channels: the number of output channels from the section :param use_batchnorm: True to put batchnorm after each conv, False otherwise """ def __init__(self, num_blocks: int, out_channels: int, use_batchnorm: bool): self.num_blocks = num_blocks self.out_channels = out_channels self.use_batchnorm = use_batchnorm def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): for block in range(self.num_blocks): out = conv2d_block( name="block_{}".format(block), x_tens=out, training=training, channels=self.out_channels, kernel_size=3, include_bn=self.use_batchnorm, include_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = pool2d( name="pool", x_tens=out, type_="max", pool_size=2, strides=2, padding="valid", ) return out def vgg_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[VGGSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Graph constructor for VGG implementation. :param x_tens: The input tensor to the VGG architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param sec_settings: The settings for each section in the VGG modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ out = x_tens with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["vgg11", "vgg_11", "vgg-11"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="vgg", sub_architecture="11", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/mlp_2/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `vgg13bn` function. Write a Python function `def vgg13bn( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def vgg13bn( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ VGGSection(num_blocks=2, out_channels=64, use_batchnorm=True), VGGSection(num_blocks=2, out_channels=128, use_batchnorm=True), VGGSection(num_blocks=2, out_channels=256, use_batchnorm=True), VGGSection(num_blocks=2, out_channels=512, use_batchnorm=True), VGGSection(num_blocks=2, out_channels=512, use_batchnorm=True), ] return vgg_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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(object): """ Settings to describe how to put together a VGG architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (conv [bn] relu) :param out_channels: the number of output channels from the section :param use_batchnorm: True to put batchnorm after each conv, False otherwise """ def __init__(self, num_blocks: int, out_channels: int, use_batchnorm: bool): self.num_blocks = num_blocks self.out_channels = out_channels self.use_batchnorm = use_batchnorm def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): for block in range(self.num_blocks): out = conv2d_block( name="block_{}".format(block), x_tens=out, training=training, channels=self.out_channels, kernel_size=3, include_bn=self.use_batchnorm, include_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = pool2d( name="pool", x_tens=out, type_="max", pool_size=2, strides=2, padding="valid", ) return out def vgg_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[VGGSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Graph constructor for VGG implementation. :param x_tens: The input tensor to the VGG architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param sec_settings: The settings for each section in the VGG modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ out = x_tens with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["vgg11", "vgg_11", "vgg-11"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="vgg", sub_architecture="11", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/mlp_2/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `vgg16` function. Write a Python function `def vgg16( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def vgg16( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ VGGSection(num_blocks=2, out_channels=64, use_batchnorm=False), VGGSection(num_blocks=2, out_channels=128, use_batchnorm=False), VGGSection(num_blocks=3, out_channels=256, use_batchnorm=False), VGGSection(num_blocks=3, out_channels=512, use_batchnorm=False), VGGSection(num_blocks=3, out_channels=512, use_batchnorm=False), ] return vgg_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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(object): """ Settings to describe how to put together a VGG architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (conv [bn] relu) :param out_channels: the number of output channels from the section :param use_batchnorm: True to put batchnorm after each conv, False otherwise """ def __init__(self, num_blocks: int, out_channels: int, use_batchnorm: bool): self.num_blocks = num_blocks self.out_channels = out_channels self.use_batchnorm = use_batchnorm def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): for block in range(self.num_blocks): out = conv2d_block( name="block_{}".format(block), x_tens=out, training=training, channels=self.out_channels, kernel_size=3, include_bn=self.use_batchnorm, include_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = pool2d( name="pool", x_tens=out, type_="max", pool_size=2, strides=2, padding="valid", ) return out def vgg_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[VGGSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Graph constructor for VGG implementation. :param x_tens: The input tensor to the VGG architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param sec_settings: The settings for each section in the VGG modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ out = x_tens with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["vgg11", "vgg_11", "vgg-11"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="vgg", sub_architecture="11", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/mlp_2/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `vgg16bn` function. Write a Python function `def vgg16bn( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def vgg16bn( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ VGGSection(num_blocks=2, out_channels=64, use_batchnorm=True), VGGSection(num_blocks=2, out_channels=128, use_batchnorm=True), VGGSection(num_blocks=3, out_channels=256, use_batchnorm=True), VGGSection(num_blocks=3, out_channels=512, use_batchnorm=True), VGGSection(num_blocks=3, out_channels=512, use_batchnorm=True), ] return vgg_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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(object): """ Settings to describe how to put together a VGG architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (conv [bn] relu) :param out_channels: the number of output channels from the section :param use_batchnorm: True to put batchnorm after each conv, False otherwise """ def __init__(self, num_blocks: int, out_channels: int, use_batchnorm: bool): self.num_blocks = num_blocks self.out_channels = out_channels self.use_batchnorm = use_batchnorm def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): for block in range(self.num_blocks): out = conv2d_block( name="block_{}".format(block), x_tens=out, training=training, channels=self.out_channels, kernel_size=3, include_bn=self.use_batchnorm, include_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = pool2d( name="pool", x_tens=out, type_="max", pool_size=2, strides=2, padding="valid", ) return out def vgg_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[VGGSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Graph constructor for VGG implementation. :param x_tens: The input tensor to the VGG architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param sec_settings: The settings for each section in the VGG modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ out = x_tens with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["vgg11", "vgg_11", "vgg-11"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="vgg", sub_architecture="11", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/mlp_2/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `vgg19` function. Write a Python function `def vgg19( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def vgg19( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ VGGSection(num_blocks=2, out_channels=64, use_batchnorm=False), VGGSection(num_blocks=2, out_channels=128, use_batchnorm=False), VGGSection(num_blocks=4, out_channels=256, use_batchnorm=False), VGGSection(num_blocks=4, out_channels=512, use_batchnorm=False), VGGSection(num_blocks=4, out_channels=512, use_batchnorm=False), ] return vgg_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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 [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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(object): """ Settings to describe how to put together a VGG architecture using user supplied configurations. :param num_blocks: the number of blocks to put in the section (conv [bn] relu) :param out_channels: the number of output channels from the section :param use_batchnorm: True to put batchnorm after each conv, False otherwise """ def __init__(self, num_blocks: int, out_channels: int, use_batchnorm: bool): self.num_blocks = num_blocks self.out_channels = out_channels self.use_batchnorm = use_batchnorm def create( self, name: str, x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Create the section in the current graph and scope :param name: the name for the scope to create the section under :param x_tens: 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 kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the section """ out = x_tens with tf_compat.variable_scope(name, reuse=tf_compat.AUTO_REUSE): for block in range(self.num_blocks): out = conv2d_block( name="block_{}".format(block), x_tens=out, training=training, channels=self.out_channels, kernel_size=3, include_bn=self.use_batchnorm, include_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) out = pool2d( name="pool", x_tens=out, type_="max", pool_size=2, strides=2, padding="valid", ) return out def vgg_const( x_tens: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor], sec_settings: List[VGGSection], num_classes: int, class_type: str, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) -> tf_compat.Tensor: """ Graph constructor for VGG implementation. :param x_tens: The input tensor to the VGG architecture :param training: bool or Tensor to specify if the model should be run in training or inference mode :param sec_settings: The settings for each section in the VGG modoel :param num_classes: The number of classes to classify :param class_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ out = x_tens with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): for sec_index, section in enumerate(sec_settings): out = section.create( name="section_{}".format(sec_index), x_tens=out, training=training, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, ) logits = _classifier( out, training, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, ) return logits key=["vgg11", "vgg_11", "vgg-11"], input_shape=(224, 224, 3), domain="cv", sub_domain="classification", architecture="vgg", sub_architecture="11", default_dataset="imagenet", default_desc="base", default_model_fn_creator=ClassificationEstimatorModelFn, base_name_scope=BASE_NAME_SCOPE, tl_ignore_tens=[".+/classifier/mlp_2/fc/.+"], The provided code snippet includes necessary dependencies for implementing the `vgg19bn` function. Write a Python function `def vgg19bn( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor` to solve the following problem: 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph Here is the function: def vgg19bn( inputs: tf_compat.Tensor, training: Union[bool, tf_compat.Tensor] = True, num_classes: int = 1000, class_type: str = None, kernel_initializer=tf_compat.glorot_uniform_initializer(), bias_initializer=tf_compat.zeros_initializer(), beta_initializer=tf_compat.zeros_initializer(), gamma_initializer=tf_compat.ones_initializer(), ) -> tf_compat.Tensor: """ 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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph """ sec_settings = [ VGGSection(num_blocks=2, out_channels=64, use_batchnorm=True), VGGSection(num_blocks=2, out_channels=128, use_batchnorm=True), VGGSection(num_blocks=4, out_channels=256, use_batchnorm=True), VGGSection(num_blocks=4, out_channels=512, use_batchnorm=True), VGGSection(num_blocks=4, out_channels=512, use_batchnorm=True), ] return vgg_const( inputs, training, sec_settings, num_classes, class_type, kernel_initializer, bias_initializer, beta_initializer, gamma_initializer, )
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_type: One of [single, multi, None] to support multi class training. Default single. If None, then will not add the fully connected at the end. :param kernel_initializer: Initializer to use for the conv and fully connected kernels :param bias_initializer: Initializer to use for the bias in the fully connected :param beta_initializer: Initializer to use for the batch norm beta variables :param gamma_initializer: Initializer to use for the batch norm gama variables :return: the output tensor from the created graph
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 includes necessary dependencies for implementing the `mnist_net` function. Write a Python function `def mnist_net( inputs: tf_compat.Tensor, num_classes: int = 10, act: str = None ) -> tf_compat.Tensor` to solve the following problem: 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 the created network Here is the function: def mnist_net( inputs: tf_compat.Tensor, num_classes: int = 10, act: str = None ) -> tf_compat.Tensor: """ 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 the created network """ if act not in [None, "sigmoid", "softmax"]: raise ValueError("unsupported value for act given of {}".format(act)) with tf_compat.variable_scope(BASE_NAME_SCOPE, reuse=tf_compat.AUTO_REUSE): with tf_compat.variable_scope("blocks", reuse=tf_compat.AUTO_REUSE): x_tens = conv2d( name="conv0", x_tens=inputs, in_chan=1, out_chan=16, kernel=5, stride=1, padding="SAME", act="relu", ) x_tens = conv2d( name="conv1", x_tens=x_tens, in_chan=16, out_chan=32, kernel=5, stride=2, padding="SAME", act="relu", ) x_tens = conv2d( name="conv2", x_tens=x_tens, in_chan=32, out_chan=64, kernel=5, stride=1, padding="SAME", act="relu", ) x_tens = conv2d( name="conv3", x_tens=x_tens, in_chan=64, out_chan=128, kernel=5, stride=2, padding="SAME", act="relu", ) with tf_compat.variable_scope("classifier"): x_tens = tf_compat.reduce_mean(x_tens, axis=[1, 2]) x_tens = tf_compat.reshape(x_tens, [-1, 128]) x_tens = fc(name="fc", x_tens=x_tens, in_chan=128, out_chan=num_classes) with tf_compat.variable_scope("logits"): logits = activation(x_tens, act) return logits
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 the created network
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_gan_network_fn( name: str, is_training: bool = False, ): """ Returns network_fn for a GAN sub-model :param name: The name of the network. :param is_training: `True` if the model is being used for training otherwise `False` :return network_fn: Function that will run a gan sub-model :raises ValueError: If network `name` is not recognized. """ _check_slim_availability() if name not in _gans_constructors(): raise ValueError("Name of GAN network unknown %s" % name) func = _gans_constructors()[name] def network_fn(inputs, **kwargs): if name == "dcgan_generator": kwargs["final_size"] = 16 return func(inputs, is_training=is_training, **kwargs) return network_fn def get_model_scope(model_name: str, arg_scope_vars: Dict = None): """ :param model_name: name of the model to create an arg scope for :param arg_scope_vars: :return: arg_scope_vars to be passed to the slim arg_scope """ _check_slim_availability() if arg_scope_vars is None: arg_scope_vars = {} arg_scope = nets_factory.arg_scopes_map[model_name](**arg_scope_vars) if model_name == "mobilenet_v1": arg_scope = mobilenet_v1_arg_scope(**arg_scope_vars) return arg_scope The provided code snippet includes necessary dependencies for implementing the `get_network_fn` function. Write a Python function `def get_network_fn( name: str, num_classes: int, weight_decay: float = 0.0, is_training: bool = False, arg_scope_vars: Dict = None, )` to solve the following problem: 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_decay: The l2 coefficient for the model weights. :param is_training: `True` if the model is being used for training otherwise `False` :param arg_scope_vars: arg_scope_vars to be passed to the slim arg_scope :return network_fn: A function that applies the model to a batch of images. It has the following signature: net, end_points = network_fn(images) The `images` input is a tensor of shape [batch_size, height, width, 3 or 1] with height = width = network_fn.default_image_size. (The permissibility and treatment of other sizes depends on the network_fn.) The returned `end_points` are a dictionary of intermediate activations. The returned `net` is the topmost layer, depending on `num_classes`: If `num_classes` was a non-zero integer, `net` is a logits tensor of shape [batch_size, num_classes]. If `num_classes` was 0 or `None`, `net` is a tensor with the input to the logits layer of shape [batch_size, 1, 1, num_features] or [batch_size, num_features]. Dropout has not been applied to this (even if the network's original classification does); it remains for the caller to do this or not. :raises ValueError: If network `name` is not recognized. Here is the function: def get_network_fn( name: str, num_classes: int, weight_decay: float = 0.0, is_training: bool = False, arg_scope_vars: Dict = None, ): """ 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_decay: The l2 coefficient for the model weights. :param is_training: `True` if the model is being used for training otherwise `False` :param arg_scope_vars: arg_scope_vars to be passed to the slim arg_scope :return network_fn: A function that applies the model to a batch of images. It has the following signature: net, end_points = network_fn(images) The `images` input is a tensor of shape [batch_size, height, width, 3 or 1] with height = width = network_fn.default_image_size. (The permissibility and treatment of other sizes depends on the network_fn.) The returned `end_points` are a dictionary of intermediate activations. The returned `net` is the topmost layer, depending on `num_classes`: If `num_classes` was a non-zero integer, `net` is a logits tensor of shape [batch_size, num_classes]. If `num_classes` was 0 or `None`, `net` is a tensor with the input to the logits layer of shape [batch_size, 1, 1, num_features] or [batch_size, num_features]. Dropout has not been applied to this (even if the network's original classification does); it remains for the caller to do this or not. :raises ValueError: If network `name` is not recognized. """ _check_slim_availability() if not arg_scope_vars: arg_scope_vars = {} if "gan" in name.lower(): return get_gan_network_fn(name, is_training) if name not in nets_factory.networks_map: raise ValueError("Name of network unknown %s" % name) func = nets_factory.networks_map[name] arg_scope_vars["weight_decay"] = weight_decay @functools.wraps(func) def network_fn(images, **kwargs): with slim.arg_scope(get_model_scope(name, arg_scope_vars=arg_scope_vars)): return func( images, num_classes=num_classes, is_training=is_training, **kwargs ) if hasattr(func, "default_image_size"): network_fn.default_image_size = func.default_image_size return network_fn
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_decay: The l2 coefficient for the model weights. :param is_training: `True` if the model is being used for training otherwise `False` :param arg_scope_vars: arg_scope_vars to be passed to the slim arg_scope :return network_fn: A function that applies the model to a batch of images. It has the following signature: net, end_points = network_fn(images) The `images` input is a tensor of shape [batch_size, height, width, 3 or 1] with height = width = network_fn.default_image_size. (The permissibility and treatment of other sizes depends on the network_fn.) The returned `end_points` are a dictionary of intermediate activations. The returned `net` is the topmost layer, depending on `num_classes`: If `num_classes` was a non-zero integer, `net` is a logits tensor of shape [batch_size, num_classes]. If `num_classes` was 0 or `None`, `net` is a tensor with the input to the logits layer of shape [batch_size, 1, 1, num_features] or [batch_size, num_features]. Dropout has not been applied to this (even if the network's original classification does); it remains for the caller to do this or not. :raises ValueError: If network `name` is not recognized.
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. Write a Python function `def write_simple_summary( writer: tf_compat.summary.FileWriter, tag: str, val: Any, step: int )` to solve the following problem: 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 Here is the function: def write_simple_summary( writer: tf_compat.summary.FileWriter, tag: str, val: Any, step: int ): """ 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 """ value = tf_compat.Summary.Value(tag=tag, simple_value=val) summary = tf_compat.Summary(value=[value]) writer.add_summary(summary, step)
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, path_file_count, tensors_export, ) def default_onnx_opset() -> int: return 9 if onnx.__version__ < "1.6" else 11
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 (removes read and indices at the end) """ name = var_tens if isinstance(var_tens, str) else var_tens.name name = re.sub(r"/read/_.+:[0-9]+$", "", name) # x/read/_12__cv__46:0 -> x name = re.sub(r"/read:[0-9]+$", "", name) # x/read:0 -> x name = re.sub(r":[0-9]+$", "", name) # x:0 -> x return name 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 `get_tensor_var` function. Write a Python function `def get_tensor_var(tens: tf_compat.Tensor) -> tf_compat.Variable` to solve the following problem: 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 Here is the function: def get_tensor_var(tens: tf_compat.Tensor) -> tf_compat.Variable: """ 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 """ expected_name = "{}:0".format(clean_tensor_name(tens)) for var in tf_compat.global_variables(): if expected_name == var.name: return var raise ValueError( "could not find a global variable that matched the tensor {}".format(tens) )
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: the weight for a conv operator. See @get_op_var_index for proper values for var_index. :param operation: the operation to get the input variable for :param var_index: the index to guide which input to grab from the operation :return: the tensor input that represents the variable input for the operation """ if tf_contrib_err: raise tf_contrib_err op_sgv = graph_editor.sgv(operation) var_index = get_op_var_index(var_index, op_sgv.inputs) return op_sgv.inputs[var_index] def get_prunable_ops( graph: tf_compat.Graph = None, ) -> List[Tuple[str, tf_compat.Operation]]: """ Get the prunable operations from a TensorFlow graph. :param graph: the graph to get the prunable operations from. If not supplied, then will use the default graph :return: a list containing the names and ops of the prunable operations (MatMul, Conv1D, Conv2D, Conv3D) """ if not graph: graph = tf_compat.get_default_graph() ops = [] for op in graph.get_operations(): if is_prunable_op(op): ops.append((op.name, op)) return ops def any_str_or_regex_matches_tensor_name( tensor_name: str, name_or_regex_patterns: List[str], ): """ :param tensor_name: The name of a tensor :param name_or_regex_patterns: List of full tensor names to match to the input or regex patterns to match with that should be prefixed with 're:' :return: True if any given str or regex pattern matches the given name """ clean_name = clean_tensor_name(tensor_name) for name_or_regex in name_or_regex_patterns: if name_or_regex[:3] == "re:": pattern = name_or_regex[3:] if re.match(pattern, tensor_name) or re.match(pattern, clean_name): return True else: if ( tensor_name == name_or_regex or clean_name == name_or_regex or clean_name == clean_tensor_name(name_or_regex) ): return True return False def _validate_all_params_found( name_or_regex_patterns: List[str], prunable_ops_and_inputs: List[Tuple[tf_compat.Operation, tf_compat.Tensor]], ): """ :param name_or_regex_patterns: List of full param names or regex patterns of them to check for matches in named_layers_and_params names :param prunable_ops_and_inputs: List prunable ops and inputs found in get_ops_and_inputs_by_name_or_regex :raise RuntimeError: If there is a name or regex pattern that does not have a match in named_layers_and_params """ tensor_names = [inp.name for _, inp in prunable_ops_and_inputs] for name_or_regex in name_or_regex_patterns: # Convert all name_or_regex values to regex patterns since we may want # full names to match based on tensor name extensions pattern = ( clean_tensor_name(name_or_regex) if name_or_regex[:3] != "re:" else name_or_regex[3:] ) if any(re.match(pattern, name) for name in tensor_names): continue # regex pattern matches at least one full parameter name raise RuntimeError( "All supplied parameter names or regex patterns not found." "No match for {} in found tensors {}. Supplied {}".format( name_or_regex, tensor_names, name_or_regex_patterns ) ) 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 `get_ops_and_inputs_by_name_or_regex` function. Write a Python function `def get_ops_and_inputs_by_name_or_regex( var_names: List[str], graph: tf_compat.Graph = None, ) -> List[Tuple[tf_compat.Operation, tf_compat.Tensor]]` to solve the following problem: 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 of (operation, parameter) pairs for parameters that match a regex pattern in var_names. If the wildcards '.' or '.*' are provided as regex patterns, then will match on all prunable layers and return variables using get_op_input_var Here is the function: def get_ops_and_inputs_by_name_or_regex( var_names: List[str], graph: tf_compat.Graph = None, ) -> List[Tuple[tf_compat.Operation, tf_compat.Tensor]]: """ 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 of (operation, parameter) pairs for parameters that match a regex pattern in var_names. If the wildcards '.' or '.*' are provided as regex patterns, then will match on all prunable layers and return variables using get_op_input_var """ if tf_contrib_err: raise tf_contrib_err if not graph: graph = tf_compat.get_default_graph() prunable_ops_and_inputs = [] if "re:.*" in var_names or "re:." in var_names: # wildcard cases ops = get_prunable_ops(graph) for _, op in ops: prunable_ops_and_inputs.append((op, get_op_input_var(op))) else: for var in tf_compat.global_variables(): if any_str_or_regex_matches_tensor_name(var.name, var_names): var_tens = graph.get_tensor_by_name(var.name) # get all the read ops for the var read_ops = [ read_op for read_op in graph_editor.get_consuming_ops(var_tens) if "/read" == read_op.name[-5:] ] # filter for /read ops read_tensors = { read_tensor for read_op in read_ops for read_tensor in graph_editor.sgv(read_op).outputs } # gets ops that read from read_tensors and filters any ops # that were created by mask_ks consuming_ops_with_input = [ (consuming_op, read_tensor) for read_tensor in read_tensors for consuming_op in graph_editor.get_consuming_ops(read_tensor) ] for op, inp in consuming_ops_with_input: if "_nm_ks" not in op.name: prunable_ops_and_inputs.append((op, inp)) else: nm_ks_consuming_ops_with_input = [ (consuming_op, inp) for output_tens in graph_editor.sgv(op).outputs for consuming_op in graph_editor.get_consuming_ops( output_tens ) if "_nm_ks" not in consuming_op.name ] prunable_ops_and_inputs += nm_ks_consuming_ops_with_input # Check that all var_names values have a match _validate_all_params_found(var_names, prunable_ops_and_inputs) return prunable_ops_and_inputs
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 of (operation, parameter) pairs for parameters that match a regex pattern in var_names. If the wildcards '.' or '.*' are provided as regex patterns, then will match on all prunable layers and return variables using get_op_input_var
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 the density for :param sess: the session to use for evaluating the tensor, if not supplied will use the default session :return: the density of the tensor """ if not sess: sess = tf_compat.get_default_session() val_array = sess.run(tens) num_nonzeros = numpy.count_nonzero(val_array) density = float(num_nonzeros) / float(val_array.size) return density 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 `eval_tensor_sparsity` function. Write a Python function `def eval_tensor_sparsity( tens: tf_compat.Tensor, sess: tf_compat.Session = None ) -> float` to solve the following problem: 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 Here is the function: def eval_tensor_sparsity( tens: tf_compat.Tensor, sess: tf_compat.Session = None ) -> float: """ 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 """ return 1.0 - eval_tensor_density(tens, sess)
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 function `def batch_cross_entropy_loss( logits: tf_compat.Tensor, labels: tf_compat.Tensor ) -> tf_compat.Tensor` to solve the following problem: 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 Here is the function: def batch_cross_entropy_loss( logits: tf_compat.Tensor, labels: tf_compat.Tensor ) -> tf_compat.Tensor: """ 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 """ with tf_compat.name_scope("loss/batch_cross_entropy/"): return tf_compat.reduce_mean( tf_compat.nn.softmax_cross_entropy_with_logits_v2( logits=logits, labels=labels ) )
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( logits: tf_compat.Tensor, labels: tf_compat.Tensor, index: int = 1 ) -> tf_compat.Tensor` to solve the following problem: 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 Here is the function: def accuracy( logits: tf_compat.Tensor, labels: tf_compat.Tensor, index: int = 1 ) -> tf_compat.Tensor: """ 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 """ with tf_compat.name_scope("loss/accuracy/"): return tf_compat.reduce_mean( tf_compat.cast( tf_compat.equal( tf_compat.argmax(logits, index), tf_compat.argmax(labels, index) ), tf_compat.float32, ) )
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, BenchmarkInfo, BenchmarkResult, ) from sparseml.framework.info import FrameworkInferenceProviderInfo, FrameworkInfo from sparseml.utils import clean_path, create_parent_dirs, deprecation_warning from sparseml.utils.helpers import convert_to_bool _LOGGER = logging.getLogger(__name__) def save_benchmark_results( model: Any, data: Any, batch_size: int, iterations: int, warmup_iterations: int, framework: Optional[str], provider: Optional[str] = None, device: Optional[str] = None, save_path: Optional[str] = None, framework_args: Dict[str, Any] = {}, show_progress: bool = False, ): """ Saves the benchmark results ran for specific framework. If path is provided, will save to a json file at the path. If path is not provided, will print out the info. If no framework is provided, will detect the framework based on the model. :param model: model to benchmark :param data: data to benchmark :param batch_size: batch size :param iterations: number of iterations :param warmup_iterations: number of warmup iterations :param framework: the specific framework run the benchmark in :param provider: the specific inference provider to use :param device: the specific device to use :param save_path: path to save the benchmark results :param framework_args: additional framework specific arguments to pass to the runner :param show_progress: True to show a tqdm bar when running, False otherwise """ results = execute_in_sparseml_framework( framework if framework is not None else model, "run_benchmark", model, data, batch_size=batch_size, iterations=iterations, warmup_iterations=warmup_iterations, provider=provider, device=device, framework_args=framework_args, show_progress=show_progress, ) if save_path: save_path = clean_path(save_path) create_parent_dirs(save_path) with open(save_path, "w") as file: file.write(results.json(indent=4)) _LOGGER.info(f"saved benchmark results in file at {save_path}"), else: print(results.json(indent=4)) _LOGGER.info("printed out benchmark results") def load_benchmark_info(load: str) -> BenchmarkInfo: """ Load the benchmark 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 benchmark info. :rtype: FrameworkInfo """ loaded_path = clean_path(load) if os.path.exists(loaded_path): with open(loaded_path, "r") as file: load = file.read() info = BenchmarkInfo.parse_raw(load) return info The provided code snippet includes necessary dependencies for implementing the `load_and_run_benchmark` function. Write a Python function `def load_and_run_benchmark( model: Any, data: Any, load: str, save_path: Optional[str] = None, )` to solve the following problem: 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 raw json string. :param save_path: path to save the new benchmark results Here is the function: def load_and_run_benchmark( model: Any, data: Any, load: str, save_path: Optional[str] = None, ): """ 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 raw json string. :param save_path: path to save the new benchmark results """ _LOGGER.info(f"rerunning benchmark {load}") info = load_benchmark_info(load) save_benchmark_results( info.framework if info.framework is not None else model, data, batch_size=info.config.batch_size, iterations=info.config.iterations, warmup_iterations=info.config.warmup_iterations, framework=info.framework, provider=info.config.inference_provider.name, device=info.config.device, framework_args=info.config.framework_args, save_path=save_path, )
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 raw json string. :param save_path: path to save the new benchmark results
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, BenchmarkInfo, BenchmarkResult, ) from sparseml.framework.info import FrameworkInferenceProviderInfo, FrameworkInfo from sparseml.utils import clean_path, create_parent_dirs, deprecation_warning from sparseml.utils.helpers import convert_to_bool def save_benchmark_results( model: Any, data: Any, batch_size: int, iterations: int, warmup_iterations: int, framework: Optional[str], provider: Optional[str] = None, device: Optional[str] = None, save_path: Optional[str] = None, framework_args: Dict[str, Any] = {}, show_progress: bool = False, ): """ Saves the benchmark results ran for specific framework. If path is provided, will save to a json file at the path. If path is not provided, will print out the info. If no framework is provided, will detect the framework based on the model. :param model: model to benchmark :param data: data to benchmark :param batch_size: batch size :param iterations: number of iterations :param warmup_iterations: number of warmup iterations :param framework: the specific framework run the benchmark in :param provider: the specific inference provider to use :param device: the specific device to use :param save_path: path to save the benchmark results :param framework_args: additional framework specific arguments to pass to the runner :param show_progress: True to show a tqdm bar when running, False otherwise """ results = execute_in_sparseml_framework( framework if framework is not None else model, "run_benchmark", model, data, batch_size=batch_size, iterations=iterations, warmup_iterations=warmup_iterations, provider=provider, device=device, framework_args=framework_args, show_progress=show_progress, ) if save_path: save_path = clean_path(save_path) create_parent_dirs(save_path) with open(save_path, "w") as file: file.write(results.json(indent=4)) _LOGGER.info(f"saved benchmark results in file at {save_path}"), else: print(results.json(indent=4)) _LOGGER.info("printed out benchmark results") def _parse_args(): parser = argparse.ArgumentParser( description=( "Run a benchmark for a specific model in an optionally specified framework." ) ) parser.add_argument( "--model", type=str, required=True, help=( "The model used for inference. Accepts either a path to the directory " "where the model is saved or a zoo stub." ), ) parser.add_argument( "--data", type=str, required=False, help=("The path to the directory where the data is saved."), ) parser.add_argument( "--batch-size", type=int, default=1, help=( "The batch size to use for the benchmark. If not specified, will " "be set to 1." ), ) parser.add_argument( "--iterations", type=int, default=0, help=( "The number of iteration steps to use for the benchmark. If not specified, " "will be set to 0 and go through entire dataset once." ), ) parser.add_argument( "--warmup-iterations", type=int, default=0, help=("The number of warmup iterations to use for the benchmark."), ) parser.add_argument( "--framework", type=str, default=None, help=( "The framework to use for the benchmark. If not specified, will be " "automatically detected based on model provided." ), ) parser.add_argument( "--provider", type=str, default=None, help=( "The inference provider to use for the benchmark. If not specified, will " "be automatically detected." ), ) parser.add_argument( "--device", type=str, default=None, help=( "The device to use for the benchmark. If not specified, will be " "automatically detected." ), ) parser.add_argument( "--save-path", type=str, default=None, help=( "A full file path to save the benchmark results to. " "If not supplied, will print out the benchmark results to the console." ), ) parser.add_argument( "--show-progress", type=convert_to_bool, default=True, help=("If specified, will show the progress of the benchmark."), ) return parser.parse_args() def _main(): deprecation_warning( message=f"{__file__} is scheduled for deprecation in a future version", ) args = _parse_args() save_benchmark_results( model=args.model, data=args.data, batch_size=args.batch_size, iterations=args.iterations, warmup_iterations=args.warmup_iterations, framework=args.framework, provider=args.provider, device=args.device, save_path=args.save_path, show_progress=args.show_progress, )
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 val_run The provided code snippet includes necessary dependencies for implementing the `train` function. Write a Python function `def train(**kwargs)` to solve the following problem: Hook to call into train.py in YOLOv5 fork Here is the function: def train(**kwargs): """ Hook to call into train.py in YOLOv5 fork """ if kwargs: train_run(**kwargs) else: opt = parse_train_args() train_run(**vars(opt))
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 val_run The provided code snippet includes necessary dependencies for implementing the `val` function. Write a Python function `def val(**kwargs)` to solve the following problem: Hook to call into val.py in YOLOv5 fork Here is the function: def val(**kwargs): """ Hook to call into val.py in YOLOv5 fork """ if kwargs: val_run(**kwargs) else: opt = parse_val_args() val_run(**vars(opt))
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 val_run The provided code snippet includes necessary dependencies for implementing the `export` function. Write a Python function `def export(**kwargs)` to solve the following problem: Hook to call into export.py in YOLOv5 fork Here is the function: def export(**kwargs): """ Hook to call into export.py in YOLOv5 fork """ if kwargs: export_run(**kwargs) else: opt = parse_export_args() export_run(**vars(opt))
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 necessary if os.path.isdir(onnx_file_or_parent_directory_path): parent_dir = onnx_file_or_parent_directory_path parent_directory_files = os.listdir(parent_dir) onnx_file_name = [ file_name for file_name in parent_directory_files if file_name.endswith(".onnx") ] if len(onnx_file_name) != 1: raise ValueError( f"Expected to find only one .onnx file inside the {parent_dir}. " f"However, found {len(onnx_file_name)} .onnx files" ) onnx_file_path = os.path.join(parent_dir, onnx_file_name[0]) else: onnx_file_path = onnx_file_or_parent_directory_path if not os.path.basename(onnx_file_path) == MODEL_ONNX_NAME: target_onnx_file_path = os.path.join( os.path.dirname(onnx_file_path), MODEL_ONNX_NAME ) shutil.move(onnx_file_path, target_onnx_file_path) The provided code snippet includes necessary dependencies for implementing the `save_zoo_directory` function. Write a Python function `def save_zoo_directory( output_dir: str, training_outputs_dir: str, model_file_torch: str, ) -> None` to solve the following problem: 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 training_outputs_dir: The path to the existing directory with the saved training artifacts :param model_file_torch: name of the final .pth/.pt file to be saved Here is the function: def save_zoo_directory( output_dir: str, training_outputs_dir: str, model_file_torch: str, ) -> None: """ 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 training_outputs_dir: The path to the existing directory with the saved training artifacts :param model_file_torch: name of the final .pth/.pt file to be saved """ logs_path = [ file for file in glob.glob(os.path.join(training_outputs_dir, "*")) if os.path.basename(file).startswith("events.out.") ] for root_file in ["sample_inputs.tar.gz", "sample_outputs.tar.gz"]: root_file_path = os.path.join(training_outputs_dir, root_file) if not os.path.exists(root_file_path): logging.warning( f"File {root_file_path} missing. To create this file, " "make sure that the export script has been ran with" "`--num_export_samples` argument." ) model_onnx_path = os.path.join( training_outputs_dir, "weights", model_file_torch.replace(".pt", ".onnx") ) deployment_path = os.path.join(training_outputs_dir, "deployment") for path in [model_onnx_path, deployment_path]: if not os.path.exists(path): raise ValueError( f"File {path} missing. To create this file, " "make sure that the `export` script (for exporting " "yolo model) has been evoked." ) _assert_correct_model_onnx_name(model_onnx_path) _assert_correct_model_onnx_name(deployment_path) setup_model( output_dir=output_dir, training=[os.path.join(training_outputs_dir, "weights", model_file_torch)], deployment=deployment_path, onnx_model=model_onnx_path, sample_inputs=os.path.join(training_outputs_dir, "sample_inputs.tar.gz"), sample_outputs=os.path.join(training_outputs_dir, "sample_outputs.tar.gz"), model_card=os.path.join(training_outputs_dir, "model.md"), logs=logs_path, sample_labels=None, sample_originals=None, analysis=None, benchmarks=None, eval_results=None, recipes=None, ) logging.info(f"Created `ModelDirectory` folder locally in {output_dir}")
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 training_outputs_dir: The path to the existing directory with the saved training artifacts :param model_file_torch: name of the final .pth/.pt file to be saved
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_pruning_sparsities_loss` function. Write a Python function `def default_pruning_sparsities_loss(extended: bool) -> Tuple[float, ...]` to solve the following problem: 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 Here is the function: def default_pruning_sparsities_loss(extended: bool) -> Tuple[float, ...]: """ 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 """ if not extended: return 0.0, 0.2, 0.4, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 0.99 sparsities = [float(s) / 100.0 for s in range(100)] return tuple(sparsities)
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 the `default_pruning_sparsities_perf` function. Write a Python function `def default_pruning_sparsities_perf() -> Tuple[float, ...]` to solve the following problem: :return: the sparsities to check for effects on the loss Here is the function: def default_pruning_sparsities_perf() -> Tuple[float, ...]: """ :return: the sparsities to check for effects on the loss """ return 0.0, 0.4, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 0.975, 0.99
: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.types import SparsificationTypes from sparseml.utils import RECIPE_METADATA_KEY, clean_path, create_parent_dirs def _nested_dict_to_lines( dict1: dict, yaml_str_lines: List[str], nesting_depth: int = 1 ) -> List[str]: indentation = " " if dict1 is None: return yaml_str_lines for key, value in dict1.items(): if isinstance(value, dict): # add data for the current nesting level and # move deeper to the next nesting level yaml_str_lines.append(indentation * nesting_depth + f"{key}:") yaml_str_lines = _nested_dict_to_lines( value, yaml_str_lines, nesting_depth + 1 ) else: # reached maximum nesting level. yaml_str_lines.append(indentation * nesting_depth + f"{key}: {value}") return yaml_str_lines
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.types import SparsificationTypes from sparseml.utils import RECIPE_METADATA_KEY, clean_path, create_parent_dirs class BaseModifier(BaseObject): """ Parent class meant to be used for all modifiers. Handles base implementations for properties and methods. :param kwargs: standard key word args, used to support multi inheritance """ def _convert_to_framework_modifiers(yaml_str: str, framework: str) -> str: pattern = re.compile(r"!(?P<mod_class>(?!.*\.)[a-zA-Z_][a-zA-Z^._0-9]+)") yaml_str = pattern.sub(r"!{}.\g<mod_class>".format(framework), yaml_str) return yaml_str def load_framework_list(yaml_str: str, framework: str): """ :param yaml_str: a string representation of the yaml syntax to load modifiers :param framework: the framework to load the modifiers for :return: the loaded modifiers list or dictionary of stage name to stage modifiers list if given a yaml string of a staged recipe """ def _load_stage_modifiers(stage_container): stage_modifiers = [] # type: List[BaseModifier] for name, item in stage_container.items(): if "modifiers" in name and isinstance(item, List): stage_modifiers.extend(item) elif isinstance(item, BaseModifier): stage_modifiers.append(item) elif isinstance(item, List) and any( isinstance(element, BaseModifier) for element in item ): # invalid modifier group name modifier_type = type( [mod for mod in item if isinstance(mod, BaseModifier)][0] ) raise ValueError( "Invalid modifier location. Grouped modifiers in recipes must " "be listed in lists with 'modifiers' in its name. A modifier " f"of type {modifier_type} was found in recipe list {name}" ) return stage_modifiers # evaluate recipe equations and load into yaml container object yaml_str = evaluate_recipe_yaml_str_equations(yaml_str) yaml_str = BaseModifier._convert_to_framework_modifiers(yaml_str, framework) container = yaml.safe_load(yaml_str) if isinstance(container, BaseModifier): modifiers = [container] elif isinstance(container, List): modifiers = container else: # Dict if any("modifiers" in key for key in container): # non-staged recipe, treat entire recipe as stage modifiers = _load_stage_modifiers(container) else: # staged recipe, return dict of stage_name -> modifiers modifiers = {} for stage_name, stage_item in container.items(): if not isinstance(stage_item, Dict): continue # stages must be represented as a Dict if any("modifiers" in key for key in stage_item): modifiers[stage_name] = _load_stage_modifiers(stage_item) if not modifiers: raise ValueError( "Unable to find any modifiers in given recipe. Modifiers must be " "listed as lists under yaml keys that include 'modifiers' in their " "name. Those keys and lists may also be nested under an extra key for " "staged recipes." ) return modifiers def load_framework_obj(yaml_str: str, framework: str): """ :param yaml_str: a string representation of the yaml syntax to load a modifier :param framework: the framework to load the modifier for :return: the loaded modifier object """ yaml_str = BaseModifier._convert_to_framework_modifiers(yaml_str, framework) modifier = yaml.safe_load(yaml_str) return modifier def yaml_key(clazz, framework: Union[str, None] = None): """ create a key for loading in yaml from the class and the framework :param clazz: the class representation to create the key for :param framework: the string representing the ML framework the modifier class is for. Default is None. :return: the formatted key; ex: !{framework}.{clazz.__name__} """ if framework is None: return "!{}".format(clazz.__name__) return "!{}.{}".format(framework, clazz.__name__) def comparator(one, two) -> int: """ Comparator implementation for Modifiers. Compares first on end_epoch, next on start_epoch, and finally on identifier. :param one: first modifier to compare :param two: second modifier to compare :return: int representing where one is in relation to two """ # compare first on end epoch compare = BaseModifier.comparator_ends(one, two) if compare == 0: # if ends equal, compare next on start compare = BaseModifier.comparator_starts(one, two) if compare == 0: # if still equal, compare on identifier compare = BaseModifier.comparator_identifiers(one, two) return compare def comparator_lists(one: List["BaseModifier"], two: List["BaseModifier"]) -> int: """ Comparator for list of modifiers, compares the max end, min start epochs of either lists and then the maximal identifiers of either :param one: first list of modifiers to compare :param two: second list of modifiers to compare :return: int representing where one is in relation to two """ # compare first on end epoch compare = BaseModifier.comparator_ends( max(one, key=lambda mod: mod.end_epoch), max(two, key=lambda mod: mod.end_epoch), ) if compare == 0: # if ends equal, compare next on start compare = BaseModifier.comparator_starts( min(one, key=lambda mod: mod.start_epoch), min(two, key=lambda mod: mod.start_epoch), ) if compare == 0: # if still equal, compare on identifier compare = BaseModifier.comparator_identifiers( max(one, key=lambda mod: mod.identifier()), max(two, key=lambda mod: mod.identifier()), ) return compare def comparator_ends(one, two) -> int: """ Comparator implementation for Modifiers based on end_epoch. Modifiers with ends greater than another will come out higher. :param one: first modifier to compare :param two: second modifier to compare :return: int representing where one is in relation to two """ one_end = getattr(one, "end_epoch") if hasattr(one, "end_epoch") else None two_end = getattr(two, "end_epoch") if hasattr(two, "end_epoch") else None if one_end == two_end: return 0 if one_end is None or two_end == -1: # if no end for one and two has one or two never ends, return one before two return -1 if two_end is None or one_end == -1: # if no end for two and one has one or one never ends, return one after two return 1 if one_end < two_end: return -1 return 1 def comparator_starts(one, two) -> int: """ Comparator implementation for Modifiers based on start_epoch. Modifiers with starts greater than another will come out higher. :param one: first modifier to compare :param two: second modifier to compare :return: int representing where one is in relation to two """ one_start = getattr(one, "start_epoch") if hasattr(one, "start_epoch") else None two_start = getattr(two, "start_epoch") if hasattr(two, "start_epoch") else None if one_start == two_start: return 0 if one_start is None: # if no start for one and two has one, return one before two return -1 if two_start is None: # if no start for two and one has one, return one after two return 1 if one_start > two_start: # if one starts after two, return after return 1 return -1 def comparator_identifiers(one, two) -> int: """ Comparator implementation for Modifiers based on identifier. Modifiers with ends greater than another will come out higher. :param one: first modifier to compare :param two: second modifier to compare :return: int representing where one is in relation to two """ one_id = one.identifier() two_id = two.identifier() if one_id < two_id: return -1 if one_id > two_id: return 1 return 0 def __init__(self, **kwargs): super().__init__(**kwargs) self._initialized = False self._enabled = True def __str__(self): formatted = [ " {}".format("{}: {}".format(key, val)) for key, val in self.props(only_serializable=True, format_str=True).items() ] return "{}\n{}".format( BaseModifier.yaml_key(self.__class__), "\n".join(formatted) ) def __repr__(self): return "{}({})".format( self.__class__.__name__, self.props(only_serializable=False, format_repr=True), ) def sparsification_types(self) -> List[SparsificationTypes]: """ :return: the sparsification types this modifier instance will apply """ return [] def initialized(self) -> bool: """ :return: True if the modifier has gone through the initialized life cycle, False otherwise """ return self._initialized def enabled(self) -> bool: """ :return: True if the modifier is currently enabled and making updates, False otherwise """ return self._enabled def enabled(self, value: bool): """ :param value: True to allow the modifier to make updates, False otherwise """ self._enabled = value def identifier(self, extra: Any = "") -> str: """ :param extra: any extra identifier to append to the end of the string :return: generate an identifier for the current modifier based on its class name and params """ props = self.props(only_serializable=True, format_str=True) props_list = [f"{key}:{val}" for key, val in props.items()] props_list.sort() # convert to list and sort to make deterministic hash_str = hashlib.md5(str(props_list).encode()).hexdigest() return f"{self.__class__.__name__}-{hash_str}{f'-{extra}' if extra else ''}" def props( self, only_serializable: bool, format_str: bool = False, format_repr: bool = False, ) -> Dict[str, Any]: """ Gather all the ModifierProps for the current instance into a dictionary collection. :param only_serializable: True if only props marked as serializable should be collected, False otherwise :param format_str: True to format the values properly for a str. Ex: None values are formatted to null and otherwise str is called :param format_repr: True to format the values properly for a repr. :return: the collected properties with names mapping to values """ if format_str and format_repr: raise ValueError( "only format_str or format_repr can be True, both are currently True" ) props = {} for attr in dir(self): if attr.startswith("_"): continue func = getattr(self.__class__, attr) if not isinstance(func, ModifierProp) or ( only_serializable and not func.serializable ): continue val = getattr(self, attr) no_serialize_val = func.no_serialize_val if val == no_serialize_val: continue if format_str: props[attr] = str(val) if val is not None else "null" elif format_repr: props[attr] = repr(val) else: props[attr] = val return props The provided code snippet includes necessary dependencies for implementing the `_min_modifier_epoch` function. Write a Python function `def _min_modifier_epoch(modifiers: Iterable[BaseModifier]) -> float` to solve the following problem: :return: the minimum epochs required by any of the modifiers provided Here is the function: def _min_modifier_epoch(modifiers: Iterable[BaseModifier]) -> float: """ :return: the minimum epochs required by any of the modifiers provided """ vals = [math.floor(mod.start_epoch) for mod in modifiers if mod.start_epoch > -1] return min(vals) if len(vals) > 0 else -1
: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.types import SparsificationTypes from sparseml.utils import RECIPE_METADATA_KEY, clean_path, create_parent_dirs class BaseModifier(BaseObject): """ Parent class meant to be used for all modifiers. Handles base implementations for properties and methods. :param kwargs: standard key word args, used to support multi inheritance """ def _convert_to_framework_modifiers(yaml_str: str, framework: str) -> str: pattern = re.compile(r"!(?P<mod_class>(?!.*\.)[a-zA-Z_][a-zA-Z^._0-9]+)") yaml_str = pattern.sub(r"!{}.\g<mod_class>".format(framework), yaml_str) return yaml_str def load_framework_list(yaml_str: str, framework: str): """ :param yaml_str: a string representation of the yaml syntax to load modifiers :param framework: the framework to load the modifiers for :return: the loaded modifiers list or dictionary of stage name to stage modifiers list if given a yaml string of a staged recipe """ def _load_stage_modifiers(stage_container): stage_modifiers = [] # type: List[BaseModifier] for name, item in stage_container.items(): if "modifiers" in name and isinstance(item, List): stage_modifiers.extend(item) elif isinstance(item, BaseModifier): stage_modifiers.append(item) elif isinstance(item, List) and any( isinstance(element, BaseModifier) for element in item ): # invalid modifier group name modifier_type = type( [mod for mod in item if isinstance(mod, BaseModifier)][0] ) raise ValueError( "Invalid modifier location. Grouped modifiers in recipes must " "be listed in lists with 'modifiers' in its name. A modifier " f"of type {modifier_type} was found in recipe list {name}" ) return stage_modifiers # evaluate recipe equations and load into yaml container object yaml_str = evaluate_recipe_yaml_str_equations(yaml_str) yaml_str = BaseModifier._convert_to_framework_modifiers(yaml_str, framework) container = yaml.safe_load(yaml_str) if isinstance(container, BaseModifier): modifiers = [container] elif isinstance(container, List): modifiers = container else: # Dict if any("modifiers" in key for key in container): # non-staged recipe, treat entire recipe as stage modifiers = _load_stage_modifiers(container) else: # staged recipe, return dict of stage_name -> modifiers modifiers = {} for stage_name, stage_item in container.items(): if not isinstance(stage_item, Dict): continue # stages must be represented as a Dict if any("modifiers" in key for key in stage_item): modifiers[stage_name] = _load_stage_modifiers(stage_item) if not modifiers: raise ValueError( "Unable to find any modifiers in given recipe. Modifiers must be " "listed as lists under yaml keys that include 'modifiers' in their " "name. Those keys and lists may also be nested under an extra key for " "staged recipes." ) return modifiers def load_framework_obj(yaml_str: str, framework: str): """ :param yaml_str: a string representation of the yaml syntax to load a modifier :param framework: the framework to load the modifier for :return: the loaded modifier object """ yaml_str = BaseModifier._convert_to_framework_modifiers(yaml_str, framework) modifier = yaml.safe_load(yaml_str) return modifier def yaml_key(clazz, framework: Union[str, None] = None): """ create a key for loading in yaml from the class and the framework :param clazz: the class representation to create the key for :param framework: the string representing the ML framework the modifier class is for. Default is None. :return: the formatted key; ex: !{framework}.{clazz.__name__} """ if framework is None: return "!{}".format(clazz.__name__) return "!{}.{}".format(framework, clazz.__name__) def comparator(one, two) -> int: """ Comparator implementation for Modifiers. Compares first on end_epoch, next on start_epoch, and finally on identifier. :param one: first modifier to compare :param two: second modifier to compare :return: int representing where one is in relation to two """ # compare first on end epoch compare = BaseModifier.comparator_ends(one, two) if compare == 0: # if ends equal, compare next on start compare = BaseModifier.comparator_starts(one, two) if compare == 0: # if still equal, compare on identifier compare = BaseModifier.comparator_identifiers(one, two) return compare def comparator_lists(one: List["BaseModifier"], two: List["BaseModifier"]) -> int: """ Comparator for list of modifiers, compares the max end, min start epochs of either lists and then the maximal identifiers of either :param one: first list of modifiers to compare :param two: second list of modifiers to compare :return: int representing where one is in relation to two """ # compare first on end epoch compare = BaseModifier.comparator_ends( max(one, key=lambda mod: mod.end_epoch), max(two, key=lambda mod: mod.end_epoch), ) if compare == 0: # if ends equal, compare next on start compare = BaseModifier.comparator_starts( min(one, key=lambda mod: mod.start_epoch), min(two, key=lambda mod: mod.start_epoch), ) if compare == 0: # if still equal, compare on identifier compare = BaseModifier.comparator_identifiers( max(one, key=lambda mod: mod.identifier()), max(two, key=lambda mod: mod.identifier()), ) return compare def comparator_ends(one, two) -> int: """ Comparator implementation for Modifiers based on end_epoch. Modifiers with ends greater than another will come out higher. :param one: first modifier to compare :param two: second modifier to compare :return: int representing where one is in relation to two """ one_end = getattr(one, "end_epoch") if hasattr(one, "end_epoch") else None two_end = getattr(two, "end_epoch") if hasattr(two, "end_epoch") else None if one_end == two_end: return 0 if one_end is None or two_end == -1: # if no end for one and two has one or two never ends, return one before two return -1 if two_end is None or one_end == -1: # if no end for two and one has one or one never ends, return one after two return 1 if one_end < two_end: return -1 return 1 def comparator_starts(one, two) -> int: """ Comparator implementation for Modifiers based on start_epoch. Modifiers with starts greater than another will come out higher. :param one: first modifier to compare :param two: second modifier to compare :return: int representing where one is in relation to two """ one_start = getattr(one, "start_epoch") if hasattr(one, "start_epoch") else None two_start = getattr(two, "start_epoch") if hasattr(two, "start_epoch") else None if one_start == two_start: return 0 if one_start is None: # if no start for one and two has one, return one before two return -1 if two_start is None: # if no start for two and one has one, return one after two return 1 if one_start > two_start: # if one starts after two, return after return 1 return -1 def comparator_identifiers(one, two) -> int: """ Comparator implementation for Modifiers based on identifier. Modifiers with ends greater than another will come out higher. :param one: first modifier to compare :param two: second modifier to compare :return: int representing where one is in relation to two """ one_id = one.identifier() two_id = two.identifier() if one_id < two_id: return -1 if one_id > two_id: return 1 return 0 def __init__(self, **kwargs): super().__init__(**kwargs) self._initialized = False self._enabled = True def __str__(self): formatted = [ " {}".format("{}: {}".format(key, val)) for key, val in self.props(only_serializable=True, format_str=True).items() ] return "{}\n{}".format( BaseModifier.yaml_key(self.__class__), "\n".join(formatted) ) def __repr__(self): return "{}({})".format( self.__class__.__name__, self.props(only_serializable=False, format_repr=True), ) def sparsification_types(self) -> List[SparsificationTypes]: """ :return: the sparsification types this modifier instance will apply """ return [] def initialized(self) -> bool: """ :return: True if the modifier has gone through the initialized life cycle, False otherwise """ return self._initialized def enabled(self) -> bool: """ :return: True if the modifier is currently enabled and making updates, False otherwise """ return self._enabled def enabled(self, value: bool): """ :param value: True to allow the modifier to make updates, False otherwise """ self._enabled = value def identifier(self, extra: Any = "") -> str: """ :param extra: any extra identifier to append to the end of the string :return: generate an identifier for the current modifier based on its class name and params """ props = self.props(only_serializable=True, format_str=True) props_list = [f"{key}:{val}" for key, val in props.items()] props_list.sort() # convert to list and sort to make deterministic hash_str = hashlib.md5(str(props_list).encode()).hexdigest() return f"{self.__class__.__name__}-{hash_str}{f'-{extra}' if extra else ''}" def props( self, only_serializable: bool, format_str: bool = False, format_repr: bool = False, ) -> Dict[str, Any]: """ Gather all the ModifierProps for the current instance into a dictionary collection. :param only_serializable: True if only props marked as serializable should be collected, False otherwise :param format_str: True to format the values properly for a str. Ex: None values are formatted to null and otherwise str is called :param format_repr: True to format the values properly for a repr. :return: the collected properties with names mapping to values """ if format_str and format_repr: raise ValueError( "only format_str or format_repr can be True, both are currently True" ) props = {} for attr in dir(self): if attr.startswith("_"): continue func = getattr(self.__class__, attr) if not isinstance(func, ModifierProp) or ( only_serializable and not func.serializable ): continue val = getattr(self, attr) no_serialize_val = func.no_serialize_val if val == no_serialize_val: continue if format_str: props[attr] = str(val) if val is not None else "null" elif format_repr: props[attr] = repr(val) else: props[attr] = val return props The provided code snippet includes necessary dependencies for implementing the `_max_modifier_epoch` function. Write a Python function `def _max_modifier_epoch(modifiers: Iterable[BaseModifier]) -> float` to solve the following problem: :return: the maximum number of epochs required by any of the modifiers provided Here is the function: def _max_modifier_epoch(modifiers: Iterable[BaseModifier]) -> float: """ :return: the maximum number of epochs required by any of the modifiers provided """ # save modifiers as list so it can iterated over multiple times modifiers = [mod for mod in modifiers] vals = [] vals.extend( [math.ceil(mod.start_epoch) for mod in modifiers if mod.start_epoch > -1] ) vals.extend([math.ceil(mod.end_epoch) for mod in modifiers if mod.end_epoch > -1]) return max(vals) if len(vals) > 0 else -1
: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, UnknownVariableException, restricted_eval, ) from sparsezoo import File, Model def load_recipe_yaml_str_no_classes(recipe_yaml_str: str) -> Dict[str, Any]: """ :param recipe_yaml_str: YAML string of a SparseML recipe :return: recipe loaded into YAML with all objects replaced as a dictionary of their parameters """ pattern = re.compile(r"!(?P<class_name>(?!.*\.)[a-zA-Z_][a-zA-Z^._0-9]+)") classless_yaml_str = pattern.sub(r"OBJECT.\g<class_name>:", recipe_yaml_str) return yaml.safe_load(classless_yaml_str) def _load_yaml_str_from_file(file_path: Union[str, File]) -> str: # load raw yaml string from yaml file, zoo stub, or markdown frontmatter if isinstance(file_path, File): # download and unwrap Recipe object file_path = file_path.path if not isinstance(file_path, str): raise ValueError(f"file_path must be a str, given {type(file_path)}") if file_path.startswith("zoo:"): # download from zoo stub model = Model(file_path) file_path = model.recipes.default.path # load the yaml string if "\n" in file_path or "\r" in file_path: # treat as raw yaml passed in yaml_str = file_path extension = "unknown" else: # load yaml from file_path extension = file_path.lower().split(".")[-1] if extension not in ["md", "yaml"]: raise ValueError( "Unsupported file extension for recipe. Excepted '.md' or '.yaml'. " f"Received {file_path}" ) with open(file_path, "r") as yaml_file: yaml_str = yaml_file.read() if extension == "md" or extension == "unknown": # extract YAML front matter from markdown recipe card # adapted from # https://github.com/jonbeebe/frontmatter/blob/master/frontmatter yaml_delim = r"(?:---|\+\+\+)" yaml = r"(.*?)" re_pattern = r"^\s*" + yaml_delim + yaml + yaml_delim regex = re.compile(re_pattern, re.S | re.M) result = regex.search(yaml_str) if result: yaml_str = result.group(1) elif extension == "md": # fail if we know whe should have extracted front matter out raise RuntimeError( "Could not extract YAML front matter from recipe card:" " {}".format(file_path) ) return yaml_str The provided code snippet includes necessary dependencies for implementing the `load_global_recipe_variables_from_yaml` function. Write a Python function `def load_global_recipe_variables_from_yaml( file_path: Union[str, File] ) -> Dict[str, Any]` to solve the following problem: :param file_path: path to recipe yaml or markdown or raw recipe yaml str :return: dictionary of recipe variable name to value Here is the function: def load_global_recipe_variables_from_yaml( file_path: Union[str, File] ) -> Dict[str, Any]: """ :param file_path: path to recipe yaml or markdown or raw recipe yaml str :return: dictionary of recipe variable name to value """ yaml_str = _load_yaml_str_from_file(file_path) recipe_dict_full = load_recipe_yaml_str_no_classes(yaml_str) # filter modifier containers from recipe variables recipe_variables = {} for variable_name, value in recipe_dict_full.items(): if "modifier" in variable_name: # modifier group, skip continue if isinstance(value, dict) and any("modifier" in key for key in value): # recipe stage: skip continue recipe_variables[variable_name] = value return recipe_variables
: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, UnknownVariableException, restricted_eval, ) from sparsezoo import File, Model The provided code snippet includes necessary dependencies for implementing the `parse_recipe_variables` function. Write a Python function `def parse_recipe_variables( recipe_variables: Optional[Union[Dict[str, Any], str]] = None ) -> Dict[str, Any]` to solve the following problem: 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 :return: the parsed recipe variables Here is the function: def parse_recipe_variables( recipe_variables: Optional[Union[Dict[str, Any], str]] = None ) -> Dict[str, Any]: """ 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 :return: the parsed recipe variables """ if not recipe_variables: return {} if isinstance(recipe_variables, Dict): return recipe_variables if not isinstance(recipe_variables, str): raise ValueError( f"recipe_args must be a string for parsing, given {recipe_variables}" ) # assume json first, try and parse with suppress(Exception): recipe_variables = json.loads(recipe_variables) return recipe_variables # assume csv, and standardize to format key=val orig_recipe_variables = recipe_variables recipe_vars_str = recipe_variables.replace(":", "=") recipe_variables = {} for arg_val in recipe_vars_str.split(","): vals = arg_val.split("=") if len(vals) != 2: raise ValueError( "Improper key=val given in csv for recipe variables with value " f"{arg_val} in {orig_recipe_variables}" ) key = vals[0].strip() if any(char in key for char in ["{", "!", "=", "}"]): raise ValueError( "Improper key given in csv for recipe variables with value " f"{key} in {orig_recipe_variables}" ) val = vals[1].strip() with suppress(Exception): # check if val should be a number, otherwise fall back on string val = float(val) recipe_variables[key] = val return recipe_variables
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 :return: the parsed recipe variables
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, UnknownVariableException, restricted_eval, ) from sparsezoo import File, Model def load_recipe_yaml_str_no_classes(recipe_yaml_str: str) -> Dict[str, Any]: """ :param recipe_yaml_str: YAML string of a SparseML recipe :return: recipe loaded into YAML with all objects replaced as a dictionary of their parameters """ pattern = re.compile(r"!(?P<class_name>(?!.*\.)[a-zA-Z_][a-zA-Z^._0-9]+)") classless_yaml_str = pattern.sub(r"OBJECT.\g<class_name>:", recipe_yaml_str) return yaml.safe_load(classless_yaml_str) def rewrite_recipe_yaml_string_with_classes(recipe_contianer: Any) -> str: """ :param recipe_contianer: recipe loaded as yaml with load_recipe_yaml_str_no_classes :return: recipe serialized into YAML with original class values re-added """ updated_yaml_str = yaml.dump(recipe_contianer) # convert object dicts back to object declarations and return pattern = re.compile( r"OBJECT\.(?P<class_name>(?!.*\.)[a-zA-Z_][a-zA-Z^._0-9]+):( null)?" ) return pattern.sub(r"!\g<class_name>", updated_yaml_str) def check_if_staged_recipe(container: dict) -> bool: """ Check whether container pertains to a staged recipe. Such a "staged container" fulfills two conditions: - no top level key in container contains "modifiers" in its name - a stage should map to a dict that has at least one key with "modifiers" in its name :param container: a container generated from a YAML string of SparseML recipe :return: True if stage recipe, False if normal recipe """ for k, v in container.items(): if isinstance(v, dict): if any( key for key in v.keys() if isinstance(key, str) and "modifiers" in key ): return True return False def _evaluate_staged_recipe_yaml_str_equations(container: dict) -> dict: """ Consumes a staged container and transforms it into a valid container for the manager and modifiers to consume further. :param container: a staged container generated from a staged recipe. :return: transformed container containing evaluated variables, operations and objects. """ main_container = {} for k, v in container.items(): if isinstance(v, dict): if any([key for key in v.keys() if "modifiers" in key]): continue main_container.update({k: v}) stages = {k: container[k] for k in set(container) - set(main_container)} ( main_container, global_variables, global_non_val_variables, ) = _evaluate_container_variables(main_container) for stage_name, staged_container in stages.items(): stage_container, variables, non_val_variables = _evaluate_container_variables( staged_container, main_container ) """ if same variable is both in global_variables and variables, the global_variable will get overwritten. """ _global_variables = { k: v for k, v in global_variables.items() if k not in variables.keys() } variables = {**variables, **_global_variables} _global_non_val_variables = { k: v for k, v in global_non_val_variables.items() if k not in non_val_variables.keys() } non_val_variables = {**non_val_variables, **_global_non_val_variables} for key, val in staged_container.items(): if "modifiers" not in key: continue stage_container[key] = _maybe_evaluate_yaml_object( val, variables, non_val_variables ) container[stage_name] = staged_container return container def _evaluate_container_variables( recipe_container: Dict[str, Any], global_container: Optional[Dict[str, Any]] = {} ) -> Tuple[Dict[str, Any], Dict[str, Union[int, float]]]: valid_variables = {} non_evaluatable_variables = {} prev_num_variables = -1 while prev_num_variables != len(valid_variables): prev_num_variables = len(valid_variables) for name, val in recipe_container.items(): if name in valid_variables: continue if isinstance(val, (int, float)): valid_variables[name] = val continue if not _is_evaluatable_variable(val): # only parse string values non_evaluatable_variables[name] = val continue try: val = _maybe_evaluate_recipe_equation( val, valid_variables, non_evaluatable_variables, global_container ) except UnknownVariableException: # dependant variables maybe not evaluated yet continue if isinstance(val, (int, float)): # update variable value and add to valid vars recipe_container[name] = val valid_variables[name] = val # check that all eval statements have been evaluated for name, val in recipe_container.items(): if isinstance(val, str) and is_eval_string(val): raise RuntimeError( f"Unable to evaluate expression: {val}. Check if any dependent " "variables form a cycle or are not defined" ) return recipe_container, valid_variables, non_evaluatable_variables def _maybe_evaluate_yaml_object( obj: Any, variables: Dict[str, Union[int, float]], non_eval_variables: Dict[str, Any], ) -> Any: if isinstance(obj, str): return _maybe_evaluate_recipe_equation(obj, variables, non_eval_variables) elif isinstance(obj, list): return [ _maybe_evaluate_yaml_object(val, variables, non_eval_variables) for val in obj ] elif isinstance(obj, dict): return { key: _maybe_evaluate_yaml_object(val, variables, non_eval_variables) for key, val in obj.items() } else: return obj The provided code snippet includes necessary dependencies for implementing the `evaluate_recipe_yaml_str_equations` function. Write a Python function `def evaluate_recipe_yaml_str_equations(recipe_yaml_str: str) -> str` to solve the following problem: :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 Here is the function: def evaluate_recipe_yaml_str_equations(recipe_yaml_str: str) -> str: """ :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 """ container = load_recipe_yaml_str_no_classes(recipe_yaml_str) if not isinstance(container, dict): # yaml string does not create a dict, return original string return recipe_yaml_str # check whether the recipe is a stage recipe of not if check_if_staged_recipe(container): container = _evaluate_staged_recipe_yaml_str_equations(container) else: container, variables, non_val_variables = _evaluate_container_variables( container ) # update values nested in modifier lists based on the variables for key, val in container.items(): if "modifiers" not in key: continue container[key] = _maybe_evaluate_yaml_object( val, variables, non_val_variables ) return rewrite_recipe_yaml_string_with_classes(container)
: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, UnknownVariableException, restricted_eval, ) from sparsezoo import File, Model def _maybe_parse_number(val: str) -> Union[str, float, int]: try: return int(val) except Exception: try: return float(val) except Exception: return val
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, UnknownVariableException, restricted_eval, ) from sparsezoo import File, Model The provided code snippet includes necessary dependencies for implementing the `add_framework_metadata` function. Write a Python function `def add_framework_metadata( metadata: Dict[str, Dict], **extra_metadata ) -> Dict[str, Dict]` to solve the following problem: 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_version = torch.__version__)') :return: Validated metadata with framework metadata Here is the function: def add_framework_metadata( metadata: Dict[str, Dict], **extra_metadata ) -> Dict[str, Dict]: """ 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_version = torch.__version__)') :return: Validated metadata with framework metadata """ framework_metadata = { "python_version": platform.python_version(), "sparseml_version": sparseml_version, } framework_metadata.update(extra_metadata) for stage_name, stage_value in metadata.items(): if stage_value is None: stage_metadata = {FRAMEWORK_METADATA_KEY: framework_metadata} else: if (FRAMEWORK_METADATA_KEY in stage_value.keys()) and stage_value[ FRAMEWORK_METADATA_KEY ]: shared_keys = set( stage_value[FRAMEWORK_METADATA_KEY].keys() ).intersection(set(framework_metadata.keys())) warning_if_stage = ( f"stage (stage name: {stage_name})" if stage_name != RECIPE_METADATA_KEY else "" ) warning_msg = ( f"Overwriting metadata {warning_if_stage} key(s) " f"{shared_keys} with new value(s) " f"{ {k:v for k,v in framework_metadata.items() if k in shared_keys} }" # noqa E501 ) logging.warning(warning_msg) stage_metadata = deepcopy(stage_value) stage_metadata[FRAMEWORK_METADATA_KEY] = framework_metadata metadata[stage_name] = stage_metadata return metadata
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_version = torch.__version__)') :return: Validated metadata with framework metadata
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, UnknownVariableException, restricted_eval, ) from sparsezoo import File, Model def load_recipe_yaml_str_no_classes(recipe_yaml_str: str) -> Dict[str, Any]: """ :param recipe_yaml_str: YAML string of a SparseML recipe :return: recipe loaded into YAML with all objects replaced as a dictionary of their parameters """ pattern = re.compile(r"!(?P<class_name>(?!.*\.)[a-zA-Z_][a-zA-Z^._0-9]+)") classless_yaml_str = pattern.sub(r"OBJECT.\g<class_name>:", recipe_yaml_str) return yaml.safe_load(classless_yaml_str) def check_if_staged_recipe(container: dict) -> bool: """ Check whether container pertains to a staged recipe. Such a "staged container" fulfills two conditions: - no top level key in container contains "modifiers" in its name - a stage should map to a dict that has at least one key with "modifiers" in its name :param container: a container generated from a YAML string of SparseML recipe :return: True if stage recipe, False if normal recipe """ for k, v in container.items(): if isinstance(v, dict): if any( key for key in v.keys() if isinstance(key, str) and "modifiers" in key ): return True return False def _extract_metadata_from_recipe(container): metadata = {} if RECIPE_METADATA_KEY in container.keys(): metadata = container[RECIPE_METADATA_KEY] return metadata def _extract_metadata_from_staged_recipe(container): metadata = {} stage_names = _get_recipe_stage_names(container) for stage_name in stage_names: if RECIPE_METADATA_KEY in container[stage_name].keys(): metadata[stage_name] = container[stage_name][RECIPE_METADATA_KEY] if metadata and (len(metadata) != len(stage_names)): raise ValueError( "It seems that some stages in your checkpoint recipe" "contain metadata and some do not. Either all or no stages must " f"must contain the {RECIPE_METADATA_KEY} key" ) return metadata def _get_recipe_stage_names(container): # Extracts valid stage names from a container. # Valid stage name (key) is the one which corresponds to a value, which is # a dictionary where at least one of the keys contains a string 'modifiers'. stage_names = [ stage_name for stage_name, stage_dict in container.items() if isinstance(stage_dict, dict) and any([key for key in stage_dict.keys() if "modifiers" in key]) ] return stage_names def _check_warn_dict_difference(original_dict, new_dict): if original_dict != new_dict: logging.warning( f"Attempting to overwrite the previous metadata: {original_dict} " f"with new metadata: {new_dict}. " "This may lead to different results than the original run of the recipe. " "The previous metadata will be omitted and discarded. Ignore if a " "change in metadata is expected." ) return new_dict The provided code snippet includes necessary dependencies for implementing the `validate_metadata` function. Write a Python function `def validate_metadata(metadata: dict, yaml_str: str) -> dict` to solve the following problem: 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 form. :param metadata: New metadata :param yaml_str: String representation of the recipe YAML file, (may contain previous metadata) :return: Validated metadata Here is the function: def validate_metadata(metadata: dict, yaml_str: str) -> dict: """ 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 form. :param metadata: New metadata :param yaml_str: String representation of the recipe YAML file, (may contain previous metadata) :return: Validated metadata """ container = load_recipe_yaml_str_no_classes(yaml_str) is_container_staged = check_if_staged_recipe(container) checkpoint_metadata = ( _extract_metadata_from_staged_recipe(container) if is_container_staged else _extract_metadata_from_recipe(container) ) if checkpoint_metadata: if metadata: if is_container_staged: is_metadata_staged = set(_get_recipe_stage_names(container)) == set( metadata.keys() ) for stage_name in _get_recipe_stage_names(container): if is_metadata_staged: checkpoint_metadata[stage_name] = _check_warn_dict_difference( container[stage_name][RECIPE_METADATA_KEY], metadata[stage_name], ) else: checkpoint_metadata[stage_name] = _check_warn_dict_difference( container[stage_name][RECIPE_METADATA_KEY], metadata ) else: checkpoint_metadata = _check_warn_dict_difference( container[RECIPE_METADATA_KEY], metadata ) return ( checkpoint_metadata if is_container_staged else {RECIPE_METADATA_KEY: checkpoint_metadata} ) else: if metadata: return ( { stage_name: metadata for stage_name in _get_recipe_stage_names(container) } if is_container_staged else {RECIPE_METADATA_KEY: metadata} ) else: return ( {stage_name: None for stage_name in _get_recipe_stage_names(container)} if is_container_staged else {RECIPE_METADATA_KEY: None} )
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 form. :param metadata: New metadata :param yaml_str: String representation of the recipe YAML file, (may contain previous metadata) :return: Validated metadata
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("__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 necessary dependencies for implementing the `set_logging_level` function. Write a Python function `def set_logging_level(level: int)` to solve the following problem: 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 Here is the function: def set_logging_level(level: int): """ 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 """ NM_ROOT_LOGGER.setLevel(level) for hand in NM_ROOT_LOGGER.handlers: hand.setLevel(level) MAIN_LOGGER.setLevel(level) for hand in MAIN_LOGGER.handlers: hand.setLevel(level)
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 includes necessary dependencies for implementing the `get_nm_root_logger` function. Write a Python function `def get_nm_root_logger() -> logging.Logger` to solve the following problem: :return: the logger used for the sparseml root package that all other loggers in that namespace are created from Here is the function: def get_nm_root_logger() -> logging.Logger: """ :return: the logger used for the sparseml root package that all other loggers in that namespace are created from """ return NM_ROOT_LOGGER
: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 necessary dependencies for implementing the `get_main_logger` function. Write a Python function `def get_main_logger() -> logging.Logger` to solve the following problem: :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 Here is the function: def get_main_logger() -> logging.Logger: """ :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 """ return MAIN_LOGGER
: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_path, create_parent_dirs class FrameworkInfo(BaseModel): """ Class for storing the information for an ML frameworks info and availability on the current system. Extends pydantics BaseModel class for serialization to and from json in addition to proper type checking on construction. """ framework: Framework = Field( title="framework", description="The framework the system info is for." ) package_versions: Dict[str, Optional[str]] = Field( title="package_versions", description=( "A mapping of the package and supporting packages for a given framework " "to the detected versions on the system currently. " "If the package is not detected, will be set to None." ), ) sparsification: Optional[SparsificationInfo] = Field( default=None, title="sparsification", description=( "True if inference for a model is available on the system " "for the given framework, False otherwise." ), ) inference_providers: List[FrameworkInferenceProviderInfo] = Field( default=[], title="inference_providers", description=( "True if inference for a model is available on the system " "for the given framework, False otherwise." ), ) properties: Dict[str, Any] = Field( default={}, title="properties", description="Any additional properties for the framework.", ) training_available: bool = Field( default=False, title="training_available", description=( "True if training/editing a model is available on the system " "for the given framework, False otherwise." ), ) sparsification_available: bool = Field( default=False, title="sparsification_available", description=( "True if sparsifying a model is available on the system " "for the given framework, False otherwise." ), ) exporting_onnx_available: bool = Field( default=False, title="exporting_onnx_available", description=( "True if exporting a model in the ONNX format is available on the system " "for the given framework, False otherwise." ), ) inference_available: bool = Field( default=False, title="inference_available", description=( "True if inference for a model is available on the system " "for the given framework, False otherwise." ), ) The provided code snippet includes necessary dependencies for implementing the `load_framework_info` function. Write a Python function `def load_framework_info(load: str) -> FrameworkInfo` to solve the following problem: 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 Here is the function: def load_framework_info(load: str) -> FrameworkInfo: """ 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 """ loaded_path = clean_path(load) if os.path.exists(loaded_path): with open(loaded_path, "r") as file: load = file.read() info = FrameworkInfo.parse_raw(load) return info
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_path, create_parent_dirs def save_framework_info(framework: Any, path: Optional[str] = None): """ Save the framework info for a given framework. If path is provided, will save to a json file at that path. If path is not provided, will print out the info. :param framework: The item to detect the ML framework for. See :func:`detect_framework` for more information. :type framework: Any :param path: The path, if any, to save the info to in json format. If not provided will print out the info. :type path: Optional[str] """ _LOGGER.debug( "saving framework info for framework %s to %s", framework, path if path else "sys.out", ) info = ( framework_info(framework) if not isinstance(framework, FrameworkInfo) else framework ) if path: path = clean_path(path) create_parent_dirs(path) with open(path, "w") as file: file.write(info.json()) _LOGGER.info( "saved framework info for framework %s in file at %s", framework, path ), else: print(info.json(indent=4)) _LOGGER.info("printed out framework info for framework %s", framework) def _parse_args(): parser = argparse.ArgumentParser( description=( "Compile the available setup and information for a given framework." ) ) parser.add_argument( "framework", type=str, help=( "the ML framework or path to a framework file to load the " "framework info for" ), ) parser.add_argument( "--path", type=str, default=None, help=( "A full file path to save the framework info to. " "If not supplied, will print out the framework info to the console." ), ) return parser.parse_args() def _main(): args = _parse_args() save_framework_info(args.framework, args.path)
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(name): def _exe_input(_, inp, out): if name in subset: order.append(name) return _exe_input handles = [subset[name].register_forward_hook(exe_input(name)) for name in subset] layer(an_input, **kwargs) for h in handles: h.remove() return order
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, layers=[torch.nn.qat.Linear], name=""): if type(module) in layers: pieces = name.split(".") if pieces[-1] == "module": name = ".".join(pieces[:-1]) return {name: module} res = {} for name1, child in module.named_children(): res.update( _find_layers( child, layers=layers, name=name + "." + name1 if name != "" else name1 ) ) return res
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_dataloader from llmfoundry.utils.builders import build_tokenizer from model_preprocessor import ModelPreprocessor, QuantizationModelPreprocessor from omegaconf import OmegaConf as om from sparseml.experimental.sparsegpt.layer_compressor import ( BaseCompressor, LayerCompressor, ) from sparseml.experimental.sparsegpt.quant import ( MatMulLeftInput_PV, MatMulLeftInput_QK, MatMulOutput_PV, MatMulOutput_QK, MatMulRightInput_PV, MatMulRightInput_QK, QuantizableMatMul, ) from sparseml.experimental.sparsegpt.sequential import SequentialSparseGPT class SequentialSparseGPT_MPT(SequentialSparseGPT): def compressible_layers(self): return self.model.model.transformer.blocks class MPTBottomCompressor(BaseCompressor): def compress( self, dataloader=None, nsamples: int = None, dev: str = "cuda:0", **kwargs ): args = kwargs["args"] data_seq_len = args.data_sequence_length model = self.model layers = self.model.model.transformer.blocks use_cache = model.config.use_cache model.config.use_cache = False layers = model.model.transformer.blocks model.model.transformer.wte = model.model.transformer.wte.to(dev) layers[0] = layers[0].to(dev) dtype = next(iter(model.parameters())).dtype inps = torch.zeros( (nsamples, data_seq_len, model.config.d_model), dtype=dtype, device=dev ) cache = [] class Catcher(nn.Module): def __init__(self, module): super().__init__() self.module = module def forward(self, inp, **kwargs): inps[len(cache)] = inp cache.append(kwargs["attn_bias"]) raise ValueError layers[0] = Catcher(layers[0]) i = 0 for batch in dataloader: try: tmp = {k: v.to(dev) for k, v in batch.items()} model(tmp) except ValueError: pass i += 1 if i == nsamples: break layers[0] = layers[0].module layers[0] = layers[0].cpu() model.model.transformer.wte = model.model.transformer.wte.cpu() torch.cuda.empty_cache() extras = kwargs.copy() extras.updates({"use_cache": use_cache, "outputs": inps, "attn_bias": cache}) self.model = model return model, extras class EmbeddingAndHeadWeightSeparator(ModelPreprocessor): """ Untie embedding and head weights, used for their separated quantization """ def __call__(self, dev: str = "cuda:0", **kwargs) -> Tuple[nn.Module, Dict]: from copy import deepcopy self.model.model.lm_head = torch.nn.Linear( in_features=self.model.model.transformer.wte.weight.shape[1], out_features=self.model.model.transformer.wte.weight.shape[0], bias=False, ) self.model.model.lm_head.weight = deepcopy( self.model.model.transformer.wte.weight ) self.model.model.lm_head = self.model.model.lm_head.to( self.model.model.transformer.wte.weight.device ) from typing import List, Optional, Tuple import torch.nn.functional as F from transformers.modeling_outputs import CausalLMOutputWithPast def new_untied_forward( self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]] = None, attention_mask: Optional[torch.ByteTensor] = None, prefix_mask: Optional[torch.ByteTensor] = None, sequence_id: Optional[torch.LongTensor] = None, labels: Optional[torch.LongTensor] = None, return_dict: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, use_cache: Optional[bool] = None, inputs_embeds: Optional[torch.FloatTensor] = None, ): return_dict = ( return_dict if return_dict is not None else self.config.return_dict ) use_cache = use_cache if use_cache is not None else self.config.use_cache if inputs_embeds is not None: raise NotImplementedError( "inputs_embeds has to be None (for hf/peft support)." ) outputs = self.transformer( input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache, ) # [ELDAR] this is from the original implementation # logits = self.transformer.wte( # outputs.last_hidden_state.to(self.transformer.wte.weight.device), True # ) # [ELDAR] this is our new version logits = self.lm_head( outputs.last_hidden_state.to(self.transformer.wte.weight.device) ) if self.logit_scale is not None: if self.logit_scale == 0: warnings.warn( f"Multiplying logits by self.logit_scale={self.logit_scale!r}. " "This will produce uniform (uninformative) outputs." ) logits *= self.logit_scale loss = None if labels is not None: labels = torch.roll(labels, shifts=-1) labels[:, -1] = -100 loss = F.cross_entropy( logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1) ) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) # we are overriding forward of an instance, and not a class # we should change this to a class method when we own the model implementation bound_method = new_untied_forward.__get__( self.model.model, self.model.model.__class__ ) setattr(self.model.model, "forward", bound_method) def MatMulQuantizationPreprocessor(ModelPreprocessor): def __call__(self, dev: str = "cuda:0", **kwargs) -> Tuple[nn.Module, Dict]: for name, mod in self.model.named_modules(): if hasattr(mod, "attn_fn"): print( f"Overriding attention for {name} with quantization-aware matmuls" ) attn_weights_matmul = QuantizableMatMul( MatMulLeftInput_QK, MatMulRightInput_QK, MatMulOutput_QK ) attn_output_matmul = QuantizableMatMul( MatMulLeftInput_PV, MatMulRightInput_PV, MatMulOutput_PV ) mod.attn_weights_matmul = attn_weights_matmul mod.attn_output_matmul = attn_output_matmul mod.attn_fn = mpt_get_attn_with_quantized_matmuls( mod.attn_weights_matmul, mod.attn_output_matmul ) return self.model, {} class QuantizationModelPreprocessor(ModelPreprocessor): def __init__( self, model, recipe: str, data_loader, observer_batches, model_forward, ): super().__init__(model) self.recipe = recipe if self.recipe is None: raise ValueError("Recipe must not be None") self.data_loader = data_loader self.observer_batches = observer_batches self.model_forward = model_forward def __call__(self, dev: str = "cuda:0", **kwargs) -> Tuple[nn.Module, Dict]: manager = apply_recipe(self.model, self.recipe) self.initialize_scales_from_batches(dev) self.model.apply(torch.quantization.disable_observer) return self.model, {"manager": manager} def initialize_scales_from_batches(self, dev): print("Collecting data statistics for quantization scales...") self.model.eval() with torch.no_grad(): for _ in range(int(ceil(self.observer_batches / len(self.data_loader)))): self.model_forward(self.model, self.data_loader, dev) class SequentialSparseGPT: def __init__( self, model, recipe: Optional[str] = None, model_preprocessors: Optional[List[ModelPreprocessor]] = None, bottom_compressor: Optional[LayerCompressor] = None, head_compressor: Optional[LayerCompressor] = None, args=None, ): self.model = model self.model_preprocessors = model_preprocessors self.bottom_compressor = bottom_compressor self.head_compressor = head_compressor self.recipe = recipe self.manager = None self.compressible_layers = self.compressible_layers() self.args = args def compressible_layers(self): """ Derived class could override """ try: return self.model.model.decoders.layers except Exception: raise RuntimeError( "Derived class should override to provide list of compressible layers" ) def pre_compress(self, dev: str = "cuda:0", **kwargs): model = self.model all_extras = {} for processor in self.model_preprocessors: # We assume the processors are independent, and therefore # pass in the initial kwargs into each of them model, extras = processor(dev=dev, **kwargs) all_extras.update(extras) return model, all_extras def compress(self, dev: str = "cuda:0", **kwargs): accum_kwargs = deepcopy(kwargs) if "args" not in kwargs: # Ensure that all CLI arguments are also passed down to all the steps kwargs["args"] = self.args self.model, extras = self.pre_compress(dev=dev, **kwargs) self.model = self.model.cpu() torch.cuda.empty_cache() self.manager = extras.pop("manager", self.manager) # Step 0: BottomCompressor accomplishes two things: # 1) Compress the embedding if needed # 2) Pass the calibration data through the (compressed) bottom part # of the network, capturing the output which will become the inputs # to the first decoder layer # Also return attention_mask as part of kwargs accum_kwargs.update(extras) self.model, extras = self.bottom_compressor.compress(dev=dev, **accum_kwargs) accum_kwargs.update(extras) # Step 1: Sequentially prune/quantize decoder layers inputs = None num_layers = len(self.compressible_layers) for idx, layer in enumerate(self.compressible_layers): if "outputs" not in accum_kwargs: raise RuntimeError( "The 'outputs' key is expected but not found from the " "return of the bottom compressor" ) inputs = accum_kwargs["outputs"] print(f"\n===== Compressing layer {idx}/{num_layers-1} =====") layer_compressor = LayerCompressor( self.model, layer, idx, inputs, self.manager, self.args ) # Prune/quantize using SparseGPT self.model, layer_kwargs = layer_compressor.compress( dev=dev, **accum_kwargs ) accum_kwargs.update(layer_kwargs) # Step 2: Prune/quantize head if self.head_compressor is not None: self.model, extras = self.head_compressor.compress(dev=dev, **accum_kwargs) return self.model, {} def post_compress(self, dev: str = "cuda:0", **kwargs): use_cache = kwargs["use_cache"] self.model.apply(torch.quantization.disable_observer) self.model.config.use_cache = use_cache return self.model, {} def prepare_sparsegpt(model, dataloader, args, **kwargs) -> SequentialSparseGPT: model_preprocessors = [] if args.recipe: # TODO: add check if the recipe has quantiztion modifier model_preprocessors.append(MatMulQuantizationPreprocessor(model)) model_preprocessors.append(EmbeddingAndHeadWeightSeparator(model)) model_preprocessors.append( QuantizationModelPreprocessor( model, args.recipe, dataloader, args.observer_batches ) ) bottom_compressor = MPTBottomCompressor(model) sequential_sparsegpt = SequentialSparseGPT_MPT( model, recipe=args.recipe, model_preprocessors=model_preprocessors, bottom_compressor=bottom_compressor, ) return sequential_sparsegpt
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_dataloader from llmfoundry.utils.builders import build_tokenizer from model_preprocessor import ModelPreprocessor, QuantizationModelPreprocessor from omegaconf import OmegaConf as om from sparseml.experimental.sparsegpt.layer_compressor import ( BaseCompressor, LayerCompressor, ) from sparseml.experimental.sparsegpt.quant import ( MatMulLeftInput_PV, MatMulLeftInput_QK, MatMulOutput_PV, MatMulOutput_QK, MatMulRightInput_PV, MatMulRightInput_QK, QuantizableMatMul, ) from sparseml.experimental.sparsegpt.sequential import SequentialSparseGPT def build_composer_model(model_cfg, tokenizer): warnings.filterwarnings( action="ignore", message="Torchmetrics v0.9 introduced a new argument class property", ) if model_cfg.name not in COMPOSER_MODEL_REGISTRY: raise ValueError(f"Not sure how to build model with name={model_cfg.name}") return COMPOSER_MODEL_REGISTRY[model_cfg.name](model_cfg, tokenizer) def _build_cfg(args): yaml_path = args.yaml_path args_list = args.args_list with open(yaml_path) as f: yaml_cfg = om.load(f) cli_cfg = om.from_cli(args_list) cfg = om.merge(yaml_cfg, cli_cfg) return cfg def load_model(args): cfg = _build_cfg(args) tokenizer = build_tokenizer(cfg.tokenizer) print("Initializing model...") init_context = contextlib.nullcontext() cfg.model.init_device = "cpu" with init_context: model = build_composer_model(cfg.model, tokenizer) return model, {"cfg": cfg, "tokenizer": tokenizer}
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_dataloader from llmfoundry.utils.builders import build_tokenizer from model_preprocessor import ModelPreprocessor, QuantizationModelPreprocessor from omegaconf import OmegaConf as om from sparseml.experimental.sparsegpt.layer_compressor import ( BaseCompressor, LayerCompressor, ) from sparseml.experimental.sparsegpt.quant import ( MatMulLeftInput_PV, MatMulLeftInput_QK, MatMulOutput_PV, MatMulOutput_QK, MatMulRightInput_PV, MatMulRightInput_QK, QuantizableMatMul, ) from sparseml.experimental.sparsegpt.sequential import SequentialSparseGPT def _build_cfg(args): def build_dataloader(cfg, tokenizer, device_batch_size): def load_data(args): cfg = _build_cfg(args) tokenizer = build_tokenizer(cfg.tokenizer) train_loader = build_dataloader( cfg.train_loader, tokenizer, cfg.device_train_batch_size, ) test_loader = build_dataloader( cfg.eval_loader, tokenizer, cfg.device_eval_batch_size ) return train_loader, test_loader, tokenizer
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(model, tokenizer, save_path): assert save_path, "Save path must be speficied" print(f"Saving model and artifacts to {save_path}") model.save_pretrained(save_path) tokenizer.save_pretrained(save_path) if args.recipe: recipe_path = os.path.join(save_path, "recipe.yaml") with open(recipe_path, "w") as fp: fp.write(load_recipe_yaml_str(args.recipe))
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.sparsification.obcq.obcq import one_shot from sparseml.transformers.sparsification.obcq.utils.helpers import opt_forward data_sequence_length = 2048 device = "cuda:0" def load_model(args, model_key: str = None, *gargs, **kwargs): def sequential(model, dataloader, dev, args): def load_data(args, seqlen, split=0.1): def run_experimental_obcq(experimental_args): model, _ = load_model(experimental_args) calibration_data, _, _ = load_data(experimental_args, data_sequence_length) sequential(model, calibration_data, device, experimental_args) del calibration_data return model
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.sparsification.obcq.obcq import one_shot from sparseml.transformers.sparsification.obcq.utils.helpers import llama_forward data_sequence_length = 2048 device = "cuda:0" def load_model(args, model_key: str = None, *gargs, **kwargs): model_key = _get_model_key(args) if model_key is None else model_key if model_key == "opt": from sparseml.experimental.sparsegpt.opt import load_model as _load_model elif model_key == "mpt": from sparseml.experimental.sparsegpt.mpt import load_model as _load_model elif model_key == "llama-2": from sparseml.experimental.sparsegpt.llama2 import load_model as _load_model else: raise ValueError(f"Unrecognized model key. Supported: {SUPPORTED_MODELS}") return _load_model(args, *gargs, **kwargs) def load_data(args, seqlen, split=0.1): name = args.dataset nsamples = args.nsamples model = args.model seed = args.seed if "wikitext2" in name: return get_wikitext2(nsamples, seed, seqlen, model) elif "platypus" in name: return get_openplatypus(nsamples, seed, seqlen, model, split) def sequential(model, dataloader, dev, args): sequential_sparsegpt = prepare_sparsegpt(model, dataloader, args=args, dev=dev) if args.ptq_only: sequential_sparsegpt.pre_compress(dev=dev) else: sequential_sparsegpt.compress(dataloader=dataloader, dev=dev) def run_experimental_obcq(experimental_args): model, _ = load_model(experimental_args) calibration_data, _, _ = load_data(experimental_args, data_sequence_length) sequential(model, calibration_data, device, experimental_args) del calibration_data return model
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 ( catch, execute_offloaded_module, get_openplatypus, get_wikitext2, ppl_eval_general, ) class SequentialSparseGPT_Llama2(SequentialSparseGPT): def compressible_layers(self): return self.model.model.layers class Llama2BottomCompressor(BaseCompressor): """ Llama2 specific """ def compress( self, dataloader=None, nsamples: int = None, dev: str = "cuda:0", **kwargs, ): cached_inputs = cache_attention_inputs(self.model, dataloader, dev, nsamples) outputs = cached_inputs.pop("inputs") outputs = [o[0] for o in outputs] cached_inputs.update({"outputs": outputs}) return self.model, cached_inputs def llama2_forward(model, data_loader, device, nsamples=None): # Catch attention mask cached_inputs = cache_attention_inputs(model, data_loader, device, nsamples) buffer = [b[0] for b in cached_inputs.pop("inputs")] for layer in model.model.layers: buffer = execute_offloaded_module( layer, buffer, device, cached_inputs=cached_inputs, use_cache=False, ) buffer = [b[0] for b in buffer] del cached_inputs torch.cuda.empty_cache() buffer = execute_offloaded_module( model.model.norm, buffer, device, ) logits = execute_offloaded_module( model.lm_head, buffer, device, ) return logits class QuantizationModelPreprocessor(ModelPreprocessor): def __init__( self, model, recipe: str, data_loader, observer_batches, model_forward, ): super().__init__(model) self.recipe = recipe if self.recipe is None: raise ValueError("Recipe must not be None") self.data_loader = data_loader self.observer_batches = observer_batches self.model_forward = model_forward def __call__(self, dev: str = "cuda:0", **kwargs) -> Tuple[nn.Module, Dict]: manager = apply_recipe(self.model, self.recipe) self.initialize_scales_from_batches(dev) self.model.apply(torch.quantization.disable_observer) return self.model, {"manager": manager} def initialize_scales_from_batches(self, dev): print("Collecting data statistics for quantization scales...") self.model.eval() with torch.no_grad(): for _ in range(int(ceil(self.observer_batches / len(self.data_loader)))): self.model_forward(self.model, self.data_loader, dev) class SequentialSparseGPT: def __init__( self, model, recipe: Optional[str] = None, model_preprocessors: Optional[List[ModelPreprocessor]] = None, bottom_compressor: Optional[LayerCompressor] = None, head_compressor: Optional[LayerCompressor] = None, args=None, ): self.model = model self.model_preprocessors = model_preprocessors self.bottom_compressor = bottom_compressor self.head_compressor = head_compressor self.recipe = recipe self.manager = None self.compressible_layers = self.compressible_layers() self.args = args def compressible_layers(self): """ Derived class could override """ try: return self.model.model.decoders.layers except Exception: raise RuntimeError( "Derived class should override to provide list of compressible layers" ) def pre_compress(self, dev: str = "cuda:0", **kwargs): model = self.model all_extras = {} for processor in self.model_preprocessors: # We assume the processors are independent, and therefore # pass in the initial kwargs into each of them model, extras = processor(dev=dev, **kwargs) all_extras.update(extras) return model, all_extras def compress(self, dev: str = "cuda:0", **kwargs): accum_kwargs = deepcopy(kwargs) if "args" not in kwargs: # Ensure that all CLI arguments are also passed down to all the steps kwargs["args"] = self.args self.model, extras = self.pre_compress(dev=dev, **kwargs) self.model = self.model.cpu() torch.cuda.empty_cache() self.manager = extras.pop("manager", self.manager) # Step 0: BottomCompressor accomplishes two things: # 1) Compress the embedding if needed # 2) Pass the calibration data through the (compressed) bottom part # of the network, capturing the output which will become the inputs # to the first decoder layer # Also return attention_mask as part of kwargs accum_kwargs.update(extras) self.model, extras = self.bottom_compressor.compress(dev=dev, **accum_kwargs) accum_kwargs.update(extras) # Step 1: Sequentially prune/quantize decoder layers inputs = None num_layers = len(self.compressible_layers) for idx, layer in enumerate(self.compressible_layers): if "outputs" not in accum_kwargs: raise RuntimeError( "The 'outputs' key is expected but not found from the " "return of the bottom compressor" ) inputs = accum_kwargs["outputs"] print(f"\n===== Compressing layer {idx}/{num_layers-1} =====") layer_compressor = LayerCompressor( self.model, layer, idx, inputs, self.manager, self.args ) # Prune/quantize using SparseGPT self.model, layer_kwargs = layer_compressor.compress( dev=dev, **accum_kwargs ) accum_kwargs.update(layer_kwargs) # Step 2: Prune/quantize head if self.head_compressor is not None: self.model, extras = self.head_compressor.compress(dev=dev, **accum_kwargs) return self.model, {} def post_compress(self, dev: str = "cuda:0", **kwargs): use_cache = kwargs["use_cache"] self.model.apply(torch.quantization.disable_observer) self.model.config.use_cache = use_cache return self.model, {} def prepare_sparsegpt(model, dataloader, args, dev) -> SequentialSparseGPT: model_preprocessors = [] if args.recipe: model_preprocessors.append( QuantizationModelPreprocessor( model, args.recipe, dataloader, args.observer_batches, llama2_forward, ) ) bottom_compressor = Llama2BottomCompressor(model) sequential_sparsegpt = SequentialSparseGPT_Llama2( model, recipe=args.recipe, model_preprocessors=model_preprocessors, bottom_compressor=bottom_compressor, args=args, ) return sequential_sparsegpt
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_perplexity( args, model, dataloader, dev, model_key: str = None, *gargs, **kwargs ): model_key = _get_model_key(args) if model_key is None else model_key if model_key == "opt": from sparseml.experimental.sparsegpt.opt import ppl_eval as _ppl_eval elif model_key == "llama-2": from sparseml.experimental.sparsegpt.llama2 import ppl_eval as _ppl_eval else: raise ValueError(f"Unrecognized model key. Supported: {SUPPORTED_MODELS}") return _ppl_eval(args, model, dataloader, dev, *gargs, **kwargs)
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 sparseml.experimental.sparsegpt.utils import ( catch, execute_offloaded_module, get_c4, get_ptb, get_wikitext2, ppl_eval_general, ) class SequentialSparseGPT_OPT(SequentialSparseGPT): def compressible_layers(self): return self.model.model.decoder.layers class OPTBottomCompressor(BaseCompressor): """ OPT specific """ def compress( self, dataloader=None, nsamples: int = None, dev: str = "cuda:0", **kwargs ): cached_inputs = cache_attention_inputs(self.model, dataloader, dev, nsamples) outputs = cached_inputs.pop("inputs") outputs = [o[0] for o in outputs] cached_inputs.update({"outputs": outputs}) return self.model, cached_inputs def opt_forward(model, data_loader, device, nsamples=None): # Catch attention mask cached_inputs = cache_attention_inputs(model, data_loader, device, nsamples) buffer = [b[0] for b in cached_inputs.pop("inputs")] for layer in model.model.decoder.layers: buffer = execute_offloaded_module( layer, buffer, device, cached_inputs=cached_inputs, use_cache=False, ) buffer = [b[0] for b in buffer] del cached_inputs torch.cuda.empty_cache() if model.model.decoder.final_layer_norm is not None: buffer = execute_offloaded_module( model.model.decoder.final_layer_norm, buffer, device, ) if model.model.decoder.project_out is not None: buffer = execute_offloaded_module( model.model.decoder.project_out, buffer, device, ) logits = execute_offloaded_module( model.lm_head, buffer, device, ) return logits class QuantizationModelPreprocessor(ModelPreprocessor): def __init__( self, model, recipe: str, data_loader, observer_batches, model_forward, ): super().__init__(model) self.recipe = recipe if self.recipe is None: raise ValueError("Recipe must not be None") self.data_loader = data_loader self.observer_batches = observer_batches self.model_forward = model_forward def __call__(self, dev: str = "cuda:0", **kwargs) -> Tuple[nn.Module, Dict]: manager = apply_recipe(self.model, self.recipe) self.initialize_scales_from_batches(dev) self.model.apply(torch.quantization.disable_observer) return self.model, {"manager": manager} def initialize_scales_from_batches(self, dev): print("Collecting data statistics for quantization scales...") self.model.eval() with torch.no_grad(): for _ in range(int(ceil(self.observer_batches / len(self.data_loader)))): self.model_forward(self.model, self.data_loader, dev) class SequentialSparseGPT: def __init__( self, model, recipe: Optional[str] = None, model_preprocessors: Optional[List[ModelPreprocessor]] = None, bottom_compressor: Optional[LayerCompressor] = None, head_compressor: Optional[LayerCompressor] = None, args=None, ): self.model = model self.model_preprocessors = model_preprocessors self.bottom_compressor = bottom_compressor self.head_compressor = head_compressor self.recipe = recipe self.manager = None self.compressible_layers = self.compressible_layers() self.args = args def compressible_layers(self): """ Derived class could override """ try: return self.model.model.decoders.layers except Exception: raise RuntimeError( "Derived class should override to provide list of compressible layers" ) def pre_compress(self, dev: str = "cuda:0", **kwargs): model = self.model all_extras = {} for processor in self.model_preprocessors: # We assume the processors are independent, and therefore # pass in the initial kwargs into each of them model, extras = processor(dev=dev, **kwargs) all_extras.update(extras) return model, all_extras def compress(self, dev: str = "cuda:0", **kwargs): accum_kwargs = deepcopy(kwargs) if "args" not in kwargs: # Ensure that all CLI arguments are also passed down to all the steps kwargs["args"] = self.args self.model, extras = self.pre_compress(dev=dev, **kwargs) self.model = self.model.cpu() torch.cuda.empty_cache() self.manager = extras.pop("manager", self.manager) # Step 0: BottomCompressor accomplishes two things: # 1) Compress the embedding if needed # 2) Pass the calibration data through the (compressed) bottom part # of the network, capturing the output which will become the inputs # to the first decoder layer # Also return attention_mask as part of kwargs accum_kwargs.update(extras) self.model, extras = self.bottom_compressor.compress(dev=dev, **accum_kwargs) accum_kwargs.update(extras) # Step 1: Sequentially prune/quantize decoder layers inputs = None num_layers = len(self.compressible_layers) for idx, layer in enumerate(self.compressible_layers): if "outputs" not in accum_kwargs: raise RuntimeError( "The 'outputs' key is expected but not found from the " "return of the bottom compressor" ) inputs = accum_kwargs["outputs"] print(f"\n===== Compressing layer {idx}/{num_layers-1} =====") layer_compressor = LayerCompressor( self.model, layer, idx, inputs, self.manager, self.args ) # Prune/quantize using SparseGPT self.model, layer_kwargs = layer_compressor.compress( dev=dev, **accum_kwargs ) accum_kwargs.update(layer_kwargs) # Step 2: Prune/quantize head if self.head_compressor is not None: self.model, extras = self.head_compressor.compress(dev=dev, **accum_kwargs) return self.model, {} def post_compress(self, dev: str = "cuda:0", **kwargs): use_cache = kwargs["use_cache"] self.model.apply(torch.quantization.disable_observer) self.model.config.use_cache = use_cache return self.model, {} def prepare_sparsegpt(model, dataloader, args, **kwargs) -> SequentialSparseGPT: model_preprocessors = [] if args.recipe: model_preprocessors.append( QuantizationModelPreprocessor( model, args.recipe, dataloader, args.observer_batches, opt_forward, ) ) bottom_compressor = OPTBottomCompressor(model) sequential_sparsegpt = SequentialSparseGPT_OPT( model, recipe=args.recipe, model_preprocessors=model_preprocessors, bottom_compressor=bottom_compressor, args=args, ) return sequential_sparsegpt
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 sparseml.experimental.sparsegpt.utils import ( catch, execute_offloaded_module, get_c4, get_ptb, get_wikitext2, ppl_eval_general, ) def set_seed(seed): np.random.seed(seed) torch.random.manual_seed(seed)
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: | - initialize | - initialize_loggers | - modify | - finalize :param modifiers: the modifiers to wrap """ def from_yaml( file_path: Union[str, File], add_modifiers: Optional[List[Modifier]] = None, recipe_variables: Optional[Union[Dict[str, Any], str]] = None, metadata: Optional[Dict[str, Any]] = None, ): """ Convenience function used to create the manager of multiple modifiers from a recipe file. :param file_path: the path to the recipe file to load the modifier from, or a SparseZoo model stub to load a recipe for a model stored in SparseZoo. SparseZoo stubs should be preceded by 'zoo:', and can contain an optional '?recipe_type=<type>' parameter. Can also be a SparseZoo File object. i.e. '/path/to/local/recipe.md', 'zoo:model/stub/path', 'zoo:model/stub/path?recipe_type=transfer'. Additionally, a raw yaml str is also supported in place of a file path. :param add_modifiers: additional modifiers that should be added to the returned manager alongside the ones loaded from the recipe file :param recipe_variables: additional arguments to override any root variables in the recipe with (i.e. num_epochs, init_lr) :metadata: additional (to the information provided in the recipe) data to be preserved and utilized in the future - for reproducibility and completeness. :return: ScheduledModifierManager() created from the recipe file """ recipe_variables = parse_recipe_variables(recipe_variables) yaml_str = load_recipe_yaml_str(file_path, **recipe_variables) modifiers = Modifier.load_list(yaml_str) if add_modifiers: modifiers.extend(add_modifiers) validated_metadata = validate_metadata(metadata, yaml_str) if metadata is not None: validated_metadata = add_framework_metadata( validated_metadata, torch_version=torch.__version__ ) manager = ScheduledModifierManager( modifiers=modifiers, metadata=validated_metadata ) return manager def __init__( self, modifiers: List[ScheduledModifier], metadata: Optional[Dict[str, Any]] = None, ): sparseml_analytics.send_event("python__pytorch__manager__init") super().__init__(modifiers=modifiers, metadata=metadata) self._initialize_epoch = 0 def state_dict(self) -> Dict[str, Dict]: """ :return: Dictionary to store any state variables for this manager. Includes all modifiers nested under this manager as sub keys in the dict. Only modifiers that a non empty state dict are included. """ def _modifiers_list_state_dict(modifiers): return {mod.identifier(): mod.state_dict() for mod in modifiers} if isinstance(self.modifiers, List): state_dict = _modifiers_list_state_dict(self.modifiers) else: state_dict = { stage: _modifiers_list_state_dict(modifiers) for stage, modifiers in self.modifiers } return state_dict def load_state_dict(self, state_dict: Dict[str, Dict], strict: bool = True): """ Loads the given state dict into this manager. All modifiers that match will be loaded. If any are missing or extra and strict=True, then will raise a KeyError :param state_dict: dictionary object as generated by this object's state_dict function :param strict: True to raise a KeyError for any missing or extra information in the state dict, False to ignore :raises IndexError: If any keys in the state dict do not correspond to a valid index for this manager and strict=True """ if isinstance(self.modifiers, List): modifiers_index = {mod.identifier(): mod for mod in self.modifiers} else: if strict: modifiers_stages = set(self.modifiers.keys()) state_dict_stages = set(state_dict.keys()) diff = modifiers_stages.symmetric_difference(state_dict_stages) if diff: raise IndexError( f"Found extra stages: {state_dict_stages - modifiers_stages}" f"and missing stages: {modifiers_stages - state_dict_stages}" ) modifiers_index = {} for stage_modifiers in self.modifiers.values(): modifiers_index.update( {mod.identifier(): mod for mod in stage_modifiers} ) if strict: modifier_keys = set(modifiers_index.keys()) state_dict_keys = set(state_dict.keys()) diff = modifier_keys.symmetric_difference(state_dict_keys) if diff: raise IndexError( f"Found extra keys: {state_dict_keys - modifier_keys} " f"and missing keys: {modifier_keys - state_dict_keys}" ) for key, val in state_dict.items(): if key not in modifiers_index: continue modifiers_index[key].load_state_dict(val) def apply( self, module: Module, epoch: float = math.inf, loggers: Optional[LoggerManager] = None, finalize: bool = True, **kwargs, ): """ Applies the lifecycle of each stage in the manager/recipe by calling into initialize and finalize for each modifier for each stage :param module: the PyTorch model/module to modify :param epoch: the epoch to apply the modifier at, defaults to math.inf (end) :param loggers: Optional logger manager to log the modification process to :param finalize: True to invoke finalize after initialize, False otherwise. If training after one shot, set finalize=False to keep modifiers applied. :param kwargs: Optional kwargs to support specific arguments for individual modifiers (passed to initialize and finalize). """ if not self.initialized: super().initialize(module, epoch, loggers, **kwargs) self._initialize_epoch = epoch modifier_lists = ( self._modifiers if isinstance(self._modifiers, List) else list(self._modifiers.values()) ) for modifier_list in modifier_lists: self._initialize_modifiers( modifier_list, module, epoch, loggers=loggers, **kwargs ) if finalize: self._finalize_modifiers(modifier_list, module, **kwargs) def apply_structure( self, module: Module, epoch: float = 0.0, loggers: Union[None, LoggerManager, List[BaseLogger]] = None, finalize: bool = False, **kwargs, ): """ Initialize/apply the modifier for a given model/module at the given epoch if the modifier affects the structure of the module such as quantization, layer pruning, or filter pruning. Calls into initialize(module, epoch, loggers, **kwargs) if structured. :param module: the PyTorch model/module to modify :param epoch: the epoch to apply the modifier at, defaults to 0.0 (start) :param loggers: Optional logger manager to log the modification process to :param finalize: True to invoke finalize after initialize, False otherwise. Set finalize to True and epoch to math.inf for one shot application. :param kwargs: Optional kwargs to support specific arguments for individual modifiers (passed to initialize and finalize). """ self._initialize_epoch = epoch for mod in self.iter_modifiers(): mod.apply_structure(module, epoch, loggers, finalize, **kwargs) def initialize( self, module: Module, epoch: float = 0, loggers: Union[None, LoggerManager, List[BaseLogger]] = None, **kwargs, ): """ Handles any initialization of the manager for the given model/module. epoch and steps_per_epoch can optionally be passed in to initialize the manager and module at a specific point in the training process. If loggers is not None, will additionally call initialize_loggers. :param module: the PyTorch model/module to modify :param epoch: The epoch to initialize the manager and module at. Defaults to 0 (start of the training process) :param loggers: Optional logger manager to log the modification process to :param kwargs: Optional kwargs to support specific arguments for individual modifiers. """ super().initialize(module, epoch, loggers, **kwargs) self._initialize_epoch = epoch self._initialize_modifiers( self.iter_modifiers(), module, epoch, loggers, **kwargs ) def initialize_loggers(self, loggers: Union[None, LoggerManager, List[BaseLogger]]): """ Handles initializing and setting up the loggers for the contained modifiers. :param loggers: the logger manager to setup this manager with for logging important info and milestones to """ super().initialize_loggers(loggers) for mod in self.iter_modifiers(): mod.initialize_loggers(self.loggers) def modify( self, module: Module, optimizer: Optimizer, steps_per_epoch: int, wrap_optim: Any = None, epoch: float = None, allow_parallel_module: bool = True, **kwargs, ) -> RecipeManagerStepWrapper: """ Modify the given module and optimizer for training aware algorithms such as pruning and quantization. Initialize must be called first. After training is complete, finalize should be called. :param module: The model/module to modify :param optimizer: The optimizer to modify :param steps_per_epoch: The number of optimizer steps (batches) in each epoch :param wrap_optim: Optional object to wrap instead of the optimizer. Useful for cases like amp (fp16 training) where a it should be wrapped in place of the original optimizer since it doesn't always call into the optimizer.step() function. :param epoch: Optional epoch that can be passed in to start modifying at. Defaults to the epoch that was supplied to the initialize function. :param allow_parallel_module: if False, a DataParallel or DistributedDataParallel module passed to this function will be unwrapped to its base module during recipe initialization by referencing module.module. This is useful so a recipe may reference the base module parameters instead of the wrapped distributed ones. Set to True to not unwrap the distributed module. Default is True :param kwargs: Key word arguments that are passed to the intialize call if initilaize has not been called yet :return: A wrapped optimizer object. The wrapped object makes all the original properties for the wrapped object available so it can be used without any additional code changes. """ if epoch is None: epoch = self._initialize_epoch if is_parallel_model(module) and not allow_parallel_module: if allow_parallel_module: _LOGGER.warning( "Parallel module detected by ScheduledModifierManager. Note that " "the base module parameters will be prefixed by 'module.' which " "may lead to matching issues if unaccounted for in recipe. Run " "modify() with allow_parallel_module=False to unwrap the parallel " "module during recipe initialization" ) else: _LOGGER.info("Unwrapping parallel module for recipe initialization") module = module.module # unwrap parallel module if not self.initialized: self.initialize(module, epoch, **kwargs) if wrap_optim is None: wrap_optim = optimizer return RecipeManagerStepWrapper( wrap_optim, optimizer, module, self, epoch, steps_per_epoch ) def finalize( self, module: Optional[Module] = None, reset_loggers: bool = True, **kwargs ): """ Handles any finalization of the modifier for the given model/module. Applies any remaining logic and cleans up any hooks or attachments to the model. :param module: The model/module to finalize the modifier for. Marked optional so state can still be cleaned up on delete, but generally should always be passed in. :param reset_loggers: True to remove any currently attached loggers (default), False to keep the loggers attached. :param kwargs: Optional kwargs to support specific arguments for individual modifiers. """ super().finalize(module, reset_loggers, **kwargs) self._finalize_modifiers(self.iter_modifiers(), module, reset_loggers, **kwargs) def update( self, module: Module, optimizer: Optimizer, epoch: float, steps_per_epoch: int, log_updates: bool = True, ): """ Handles updating the contained modifiers' states, module, or optimizer Only calls scheduled_update on the each modifier if modifier.update_ready() :param module: module to modify :param optimizer: optimizer to modify :param epoch: current epoch and progress within the current epoch :param steps_per_epoch: number of steps taken within each epoch (calculate batch number using this and epoch) :param log_updates: True to log the updates for each modifier to the loggers, False to skip logging """ super().update(module, optimizer, epoch, steps_per_epoch) for mod in self.iter_modifiers(): if not mod.enabled: continue if mod.update_ready(epoch, steps_per_epoch): mod.scheduled_update(module, optimizer, epoch, steps_per_epoch) if log_updates: mod.scheduled_log_update(module, optimizer, epoch, steps_per_epoch) def loss_update( self, loss: Tensor, module: Module, optimizer: Optimizer, epoch: float, steps_per_epoch: int, **kwargs, ) -> Tensor: """ Optional call that can be made on the optimizer to update the contained modifiers once loss has been calculated :param loss: The calculated loss tensor :param module: module to modify :param optimizer: optimizer to modify :param epoch: current epoch and progress within the current epoch :param steps_per_epoch: number of steps taken within each epoch (calculate batch number using this and epoch) :return: the modified loss tensor """ super().loss_update(loss, module, optimizer, epoch, steps_per_epoch, **kwargs) for mod in self.iter_modifiers(): if not mod.enabled: continue loss = mod.loss_update( loss, module, optimizer, epoch=epoch, steps_per_epoch=steps_per_epoch, **kwargs, ) return loss def optimizer_pre_step( self, module: Module, optimizer: Optimizer, epoch: float, steps_per_epoch: int ): """ Called before the optimizer step happens (after backward has been called, before optimizer.step) Calls into the contained modifiers :param module: module to modify :param optimizer: optimizer to modify :param epoch: current epoch and progress within the current epoch :param steps_per_epoch: number of steps taken within each epoch (calculate batch number using this and epoch) """ super().optimizer_pre_step(module, optimizer, epoch, steps_per_epoch) for mod in self.iter_modifiers(): if not mod.enabled: continue mod.optimizer_pre_step(module, optimizer, epoch, steps_per_epoch) def optimizer_post_step( self, module: Module, optimizer: Optimizer, epoch: float, steps_per_epoch: int ): """ Called after the optimizer step happens and weights have updated Calls into the contained modifiers :param module: module to modify :param optimizer: optimizer to modify :param epoch: current epoch and progress within the current epoch :param steps_per_epoch: number of steps taken within each epoch (calculate batch number using this and epoch) """ super().optimizer_post_step(module, optimizer, epoch, steps_per_epoch) for mod in self.iter_modifiers(): if not mod.enabled: continue mod.optimizer_post_step(module, optimizer, epoch, steps_per_epoch) def _initialize_modifiers( self, modifiers: Iterable[Modifier], module: Module, epoch: float = 0, loggers: Union[None, LoggerManager, List[BaseLogger]] = None, **kwargs, ): if isinstance(modifiers, Modifier): modifiers = [modifiers] for mod in modifiers: if mod.initialized: # check in case modifier was initialized from apply_structure continue mod.initialize(module, epoch, loggers, **kwargs) def _finalize_modifiers( self, modifiers: Iterable[Modifier], module: Optional[Module] = None, reset_loggers: bool = True, **kwargs, ): if isinstance(modifiers, Modifier): modifiers = [modifiers] for mod in modifiers: mod.finalize(module, reset_loggers, **kwargs) def apply_recipe(model, recipe): manager = ScheduledModifierManager.from_yaml(recipe) model.train() manager.apply_structure(model, epoch=0.1) model.eval() return manager
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 HFTrainingArgs from transformers.tokenization_utils_base import PaddingStrategy from sparseml.optim import parse_recipe_variables from sparseml.pytorch.opset import TORCH_DEFAULT_ONNX_OPSET from sparseml.pytorch.optim import ScheduledModifierManager from sparseml.pytorch.utils import export_onnx from sparseml.transformers import SparseAutoTokenizer from sparseml.transformers.sparsification import Trainer from sparseml.transformers.utils import SparseAutoModel from sparsezoo.utils.onnx import EXTERNAL_ONNX_DATA_NAME MODEL_ONNX_NAME = "model.onnx" TORCH_DEFAULT_ONNX_OPSET = _default_opset() def _parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Export a trained transformers model to an ONNX file" ) parser.add_argument( "--task", type=str, required=True, help="Task to create the model for. i.e. mlm, qa, glue, ner", ) parser.add_argument( "--model_path", required=True, type=str, help=( "Path to directory where model files for weights, config, and " "tokenizer are stored" ), ) parser.add_argument( "--sequence_length", type=int, default=None, help=( "Sequence length to use. Default is `config.max_position_embeddings`. " "Can be overwritten later" ), ) parser.add_argument( "--no_convert_qat", action="store_true", help=("Set flag to not perform QAT to fully quantized conversion after export"), ) parser.add_argument( "--finetuning_task", type=str, default=None, help=( "Optional finetuning task for text classification and token " "classification exports" ), ) parser.add_argument( "--onnx_file_name", type=str, default=MODEL_ONNX_NAME, help=( "Name for exported ONNX file in the model directory. " "Default and recommended value for pipeline " f"compatibility is {MODEL_ONNX_NAME}" ), ) parser.add_argument( "--num_export_samples", type=int, default=0, help="Number of samples (inputs/outputs) to export", ) parser.add_argument( "--data_args", type=str, default=None, help="Valid json loadable args used to instantiate a `DataTrainingArguments`" " instance while exporting samples", ) parser.add_argument( "--one_shot", type=str, default=None, help="local path or SparseZoo stub to a recipe that should be applied " "in a one-shot manner before exporting", ) parser.add_argument( "--trust_remote_code", action="store_true", help=("Set flag to allow custom models in HF-transformers"), ) parser.add_argument( "--opset", type=int, default=TORCH_DEFAULT_ONNX_OPSET, help=f"ONNX opset to export with, default: {TORCH_DEFAULT_ONNX_OPSET}", ) return parser.parse_args()
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 HFTrainingArgs from transformers.tokenization_utils_base import PaddingStrategy from sparseml.optim import parse_recipe_variables from sparseml.pytorch.opset import TORCH_DEFAULT_ONNX_OPSET from sparseml.pytorch.optim import ScheduledModifierManager from sparseml.pytorch.utils import export_onnx from sparseml.transformers import SparseAutoTokenizer from sparseml.transformers.sparsification import Trainer from sparseml.transformers.utils import SparseAutoModel from sparsezoo.utils.onnx import EXTERNAL_ONNX_DATA_NAME _LOGGER = logging.getLogger(__name__) def export_transformer_to_onnx( task: str, model_path: str, sequence_length: Optional[int] = None, convert_qat: bool = True, finetuning_task: Optional[str] = None, onnx_file_name: str = MODEL_ONNX_NAME, num_export_samples: int = 0, trust_remote_code: bool = False, data_args: Optional[Union[Dict[str, Any], str]] = None, one_shot: Optional[str] = None, opset: int = TORCH_DEFAULT_ONNX_OPSET, ) -> str: def create_deployment_folder( training_directory: str, onnx_file_name: str = MODEL_ONNX_NAME, deployment_files: Optional[List[str]] = None, ): TORCH_DEFAULT_ONNX_OPSET = _default_opset() def export( task: str, model_path: str, sequence_length: Optional[int], no_convert_qat: bool, finetuning_task: str, onnx_file_name: str, num_export_samples: int = 0, trust_remote_code: bool = False, data_args: Optional[str] = None, one_shot: Optional[str] = None, opset: int = TORCH_DEFAULT_ONNX_OPSET, ): if os.path.exists(model_path): # expand to absolute path to support downstream logic model_path = os.path.abspath(model_path) export_transformer_to_onnx( task=task, model_path=model_path, sequence_length=sequence_length, convert_qat=(not no_convert_qat), # False if flagged finetuning_task=finetuning_task, onnx_file_name=onnx_file_name, num_export_samples=num_export_samples, trust_remote_code=trust_remote_code, data_args=data_args, one_shot=one_shot, opset=opset, ) deployment_folder_dir = create_deployment_folder( training_directory=model_path, onnx_file_name=onnx_file_name ) _LOGGER.info( f"Created deployment folder at {deployment_folder_dir} " f"with files: {os.listdir(deployment_folder_dir)}" )
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, StageRunType from sparseml.pytorch.model_load.helpers import ( apply_recipe_structure_to_model, fallback_to_cpu, get_session_model, parse_dtype, ) from sparseml.transformers import SparseAutoTokenizer from sparseml.transformers.finetune.data.data_args import DataTrainingArguments from sparseml.transformers.finetune.model_args import ModelArguments from sparseml.transformers.finetune.runner import StageRunner from sparseml.transformers.finetune.trainer import Trainer from sparseml.transformers.finetune.training_args import TrainingArguments from sparseml.transformers.utils import SparseAutoModel, get_shared_tokenizer_src from sparseml.transformers.utils.helpers import detect_last_checkpoint def parse_args(**kwargs): """ Parses kwargs by grouping into model, data or training arg groups: * model_args in src/sparseml/transformers/finetune/model_args.py * data_args in src/sparseml/transformers/finetune/data/data_args.py * training_args in src/sparseml/transformers/finetune/training_args.py """ parser = HfArgumentParser( (ModelArguments, DataTrainingArguments, TrainingArguments) ) if not kwargs: model_args, data_args, training_args = parser.parse_args_into_dataclasses() else: model_args, data_args, training_args = parser.parse_dict(kwargs) if training_args.recipe_args is not None: if not isinstance(training_args.recipe_args, dict): arg_dict = {} for recipe_arg in training_args.recipe_args: key, value = recipe_arg.split("=") arg_dict[key] = value training_args.recipe_args = arg_dict # when set to true in FSDP mode this causes issues, the model arguments show up # as *args and **kwargs so all columns get removed training_args.remove_unused_columns = False return model_args, data_args, training_args def main( model_args: ModelArguments, data_args: DataTrainingArguments, training_args: TrainingArguments, ): """ Main entrypoint for finetuning text generation models. A model can be loaded from Hugging Face or disk, and resuming training from a checkpoint is supported. Lifecycle: - SparseAutoModel.text_generation_from_pretrained if model provided as string for model and teacher - SparseAutoTokenizer.from_pretrained() if tokenizer provided as string for tokenizer - StageRunner.populate_datasets() - Trainer() - SessionMixIn() - HFTransformersTrainer() - StageRunner.train() and/or evaluate() and/or predict() and/or oneshot() :param model_args: Arguments pertaining to which model/config/tokenizer we are going to fine-tune from :param data_args: Arguments pertaining to what data we are going to input our model for training and eval :param training_args: Arguments pertaining to training loop configuration """ # Setup logging log_level = training_args.get_process_log_level() _LOGGER.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Setup based on stage types if running stage mode if training_args.run_stages and training_args.recipe is not None: recipe_obj = Recipe.create_instance(training_args.recipe) for stage in recipe_obj.stages: run_type = stage.infer_run_type() if run_type is StageRunType.ONESHOT: training_args.do_oneshot = True elif run_type is StageRunType.TRAIN: training_args.do_train = True # Summary on each process _LOGGER.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, " f"n_gpu: {training_args.n_gpu}, " f"distributed training: {bool(training_args.local_rank != -1)}, " f"16-bits training: {training_args.fp16}" ) _LOGGER.info(f"Training/evaluation parameters {training_args}") # Detecting last checkpoint. last_checkpoint = None teacher = model_args.distill_teacher model_path = None model = model_args.model # Load tokenizer # distill TODO: support for different tokenizer for teacher? tokenizer = model_args.tokenizer if isinstance(model, str) or isinstance(model, PosixPath): (teacher, model_path, model) = intialize_model_from_path( model_args, training_args, ) if teacher is not None: teacher.eval() if isinstance(tokenizer, str) or tokenizer is None: tokenizer = initialize_tokenizer_from_path(model_args, model, teacher) # setup new SparseSession unless user requests otherwise if training_args.clear_sparse_session: session_manager.create_session() session_manager.active_session().reset() session_manager.pre_initialize_structure(model=model, framework=Framework.pytorch) # intialize session manager apply_recipe_structure_to_model(model, None, model_path) # Load datasets stage_runner = StageRunner( model_args=model_args, data_args=data_args, training_args=training_args, model=model, ) stage_runner.populate_datasets(tokenizer=tokenizer) train_dataset = stage_runner.get_dataset_split("train") eval_dataset = stage_runner.get_dataset_split("validation") calib_dataset = stage_runner.get_dataset_split("calibration") # Initialize our Trainer data_collator = DefaultDataCollator() trainer = Trainer( model_init=get_session_model, teacher=teacher, model_state_path=model_path, recipe=training_args.recipe, metadata_args=metadata_args, recipe_args=training_args.recipe_args, args=training_args, data_args=data_args, train_dataset=train_dataset or calib_dataset, eval_dataset=eval_dataset, tokenizer=tokenizer, data_collator=data_collator, ) if trainer.is_fsdp_enabled: trainer._prepare_model_for_fsdp() stage_runner.trainer = trainer # alternating Training/One-shot if training_args.run_stages: checkpoint = None if last_checkpoint is not None: checkpoint = last_checkpoint stage_runner.run_sequential_stages(checkpoint) # exit immediately return # Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint elif last_checkpoint is not None: checkpoint = last_checkpoint stage_runner.train(checkpoint) # One Shot if training_args.do_oneshot: stage_runner.one_shot() # Evaluation if training_args.do_eval: stage_runner.evaluate() # Prediction if training_args.do_predict: stage_runner.predict() The provided code snippet includes necessary dependencies for implementing the `train` function. Write a Python function `def train(**kwargs)` to solve the following problem: CLI entrypoint for running training Here is the function: def train(**kwargs): """ CLI entrypoint for running training """ model_args, data_args, training_args = parse_args(**kwargs) training_args.do_train = True main(model_args, data_args, training_args)
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, StageRunType from sparseml.pytorch.model_load.helpers import ( apply_recipe_structure_to_model, fallback_to_cpu, get_session_model, parse_dtype, ) from sparseml.transformers import SparseAutoTokenizer from sparseml.transformers.finetune.data.data_args import DataTrainingArguments from sparseml.transformers.finetune.model_args import ModelArguments from sparseml.transformers.finetune.runner import StageRunner from sparseml.transformers.finetune.trainer import Trainer from sparseml.transformers.finetune.training_args import TrainingArguments from sparseml.transformers.utils import SparseAutoModel, get_shared_tokenizer_src from sparseml.transformers.utils.helpers import detect_last_checkpoint def parse_args(**kwargs): """ Parses kwargs by grouping into model, data or training arg groups: * model_args in src/sparseml/transformers/finetune/model_args.py * data_args in src/sparseml/transformers/finetune/data/data_args.py * training_args in src/sparseml/transformers/finetune/training_args.py """ parser = HfArgumentParser( (ModelArguments, DataTrainingArguments, TrainingArguments) ) if not kwargs: model_args, data_args, training_args = parser.parse_args_into_dataclasses() else: model_args, data_args, training_args = parser.parse_dict(kwargs) if training_args.recipe_args is not None: if not isinstance(training_args.recipe_args, dict): arg_dict = {} for recipe_arg in training_args.recipe_args: key, value = recipe_arg.split("=") arg_dict[key] = value training_args.recipe_args = arg_dict # when set to true in FSDP mode this causes issues, the model arguments show up # as *args and **kwargs so all columns get removed training_args.remove_unused_columns = False return model_args, data_args, training_args def main( model_args: ModelArguments, data_args: DataTrainingArguments, training_args: TrainingArguments, ): """ Main entrypoint for finetuning text generation models. A model can be loaded from Hugging Face or disk, and resuming training from a checkpoint is supported. Lifecycle: - SparseAutoModel.text_generation_from_pretrained if model provided as string for model and teacher - SparseAutoTokenizer.from_pretrained() if tokenizer provided as string for tokenizer - StageRunner.populate_datasets() - Trainer() - SessionMixIn() - HFTransformersTrainer() - StageRunner.train() and/or evaluate() and/or predict() and/or oneshot() :param model_args: Arguments pertaining to which model/config/tokenizer we are going to fine-tune from :param data_args: Arguments pertaining to what data we are going to input our model for training and eval :param training_args: Arguments pertaining to training loop configuration """ # Setup logging log_level = training_args.get_process_log_level() _LOGGER.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Setup based on stage types if running stage mode if training_args.run_stages and training_args.recipe is not None: recipe_obj = Recipe.create_instance(training_args.recipe) for stage in recipe_obj.stages: run_type = stage.infer_run_type() if run_type is StageRunType.ONESHOT: training_args.do_oneshot = True elif run_type is StageRunType.TRAIN: training_args.do_train = True # Summary on each process _LOGGER.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, " f"n_gpu: {training_args.n_gpu}, " f"distributed training: {bool(training_args.local_rank != -1)}, " f"16-bits training: {training_args.fp16}" ) _LOGGER.info(f"Training/evaluation parameters {training_args}") # Detecting last checkpoint. last_checkpoint = None teacher = model_args.distill_teacher model_path = None model = model_args.model # Load tokenizer # distill TODO: support for different tokenizer for teacher? tokenizer = model_args.tokenizer if isinstance(model, str) or isinstance(model, PosixPath): (teacher, model_path, model) = intialize_model_from_path( model_args, training_args, ) if teacher is not None: teacher.eval() if isinstance(tokenizer, str) or tokenizer is None: tokenizer = initialize_tokenizer_from_path(model_args, model, teacher) # setup new SparseSession unless user requests otherwise if training_args.clear_sparse_session: session_manager.create_session() session_manager.active_session().reset() session_manager.pre_initialize_structure(model=model, framework=Framework.pytorch) # intialize session manager apply_recipe_structure_to_model(model, None, model_path) # Load datasets stage_runner = StageRunner( model_args=model_args, data_args=data_args, training_args=training_args, model=model, ) stage_runner.populate_datasets(tokenizer=tokenizer) train_dataset = stage_runner.get_dataset_split("train") eval_dataset = stage_runner.get_dataset_split("validation") calib_dataset = stage_runner.get_dataset_split("calibration") # Initialize our Trainer data_collator = DefaultDataCollator() trainer = Trainer( model_init=get_session_model, teacher=teacher, model_state_path=model_path, recipe=training_args.recipe, metadata_args=metadata_args, recipe_args=training_args.recipe_args, args=training_args, data_args=data_args, train_dataset=train_dataset or calib_dataset, eval_dataset=eval_dataset, tokenizer=tokenizer, data_collator=data_collator, ) if trainer.is_fsdp_enabled: trainer._prepare_model_for_fsdp() stage_runner.trainer = trainer # alternating Training/One-shot if training_args.run_stages: checkpoint = None if last_checkpoint is not None: checkpoint = last_checkpoint stage_runner.run_sequential_stages(checkpoint) # exit immediately return # Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint elif last_checkpoint is not None: checkpoint = last_checkpoint stage_runner.train(checkpoint) # One Shot if training_args.do_oneshot: stage_runner.one_shot() # Evaluation if training_args.do_eval: stage_runner.evaluate() # Prediction if training_args.do_predict: stage_runner.predict() The provided code snippet includes necessary dependencies for implementing the `eval` function. Write a Python function `def eval(**kwargs)` to solve the following problem: CLI entrypoint for running evaluation Here is the function: def eval(**kwargs): """ CLI entrypoint for running evaluation """ model_args, data_args, training_args = parse_args(**kwargs) training_args.do_eval = True main(model_args, data_args, training_args)
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, StageRunType from sparseml.pytorch.model_load.helpers import ( apply_recipe_structure_to_model, fallback_to_cpu, get_session_model, parse_dtype, ) from sparseml.transformers import SparseAutoTokenizer from sparseml.transformers.finetune.data.data_args import DataTrainingArguments from sparseml.transformers.finetune.model_args import ModelArguments from sparseml.transformers.finetune.runner import StageRunner from sparseml.transformers.finetune.trainer import Trainer from sparseml.transformers.finetune.training_args import TrainingArguments from sparseml.transformers.utils import SparseAutoModel, get_shared_tokenizer_src from sparseml.transformers.utils.helpers import detect_last_checkpoint def parse_args(**kwargs): """ Parses kwargs by grouping into model, data or training arg groups: * model_args in src/sparseml/transformers/finetune/model_args.py * data_args in src/sparseml/transformers/finetune/data/data_args.py * training_args in src/sparseml/transformers/finetune/training_args.py """ parser = HfArgumentParser( (ModelArguments, DataTrainingArguments, TrainingArguments) ) if not kwargs: model_args, data_args, training_args = parser.parse_args_into_dataclasses() else: model_args, data_args, training_args = parser.parse_dict(kwargs) if training_args.recipe_args is not None: if not isinstance(training_args.recipe_args, dict): arg_dict = {} for recipe_arg in training_args.recipe_args: key, value = recipe_arg.split("=") arg_dict[key] = value training_args.recipe_args = arg_dict # when set to true in FSDP mode this causes issues, the model arguments show up # as *args and **kwargs so all columns get removed training_args.remove_unused_columns = False return model_args, data_args, training_args def main( model_args: ModelArguments, data_args: DataTrainingArguments, training_args: TrainingArguments, ): """ Main entrypoint for finetuning text generation models. A model can be loaded from Hugging Face or disk, and resuming training from a checkpoint is supported. Lifecycle: - SparseAutoModel.text_generation_from_pretrained if model provided as string for model and teacher - SparseAutoTokenizer.from_pretrained() if tokenizer provided as string for tokenizer - StageRunner.populate_datasets() - Trainer() - SessionMixIn() - HFTransformersTrainer() - StageRunner.train() and/or evaluate() and/or predict() and/or oneshot() :param model_args: Arguments pertaining to which model/config/tokenizer we are going to fine-tune from :param data_args: Arguments pertaining to what data we are going to input our model for training and eval :param training_args: Arguments pertaining to training loop configuration """ # Setup logging log_level = training_args.get_process_log_level() _LOGGER.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Setup based on stage types if running stage mode if training_args.run_stages and training_args.recipe is not None: recipe_obj = Recipe.create_instance(training_args.recipe) for stage in recipe_obj.stages: run_type = stage.infer_run_type() if run_type is StageRunType.ONESHOT: training_args.do_oneshot = True elif run_type is StageRunType.TRAIN: training_args.do_train = True # Summary on each process _LOGGER.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, " f"n_gpu: {training_args.n_gpu}, " f"distributed training: {bool(training_args.local_rank != -1)}, " f"16-bits training: {training_args.fp16}" ) _LOGGER.info(f"Training/evaluation parameters {training_args}") # Detecting last checkpoint. last_checkpoint = None teacher = model_args.distill_teacher model_path = None model = model_args.model # Load tokenizer # distill TODO: support for different tokenizer for teacher? tokenizer = model_args.tokenizer if isinstance(model, str) or isinstance(model, PosixPath): (teacher, model_path, model) = intialize_model_from_path( model_args, training_args, ) if teacher is not None: teacher.eval() if isinstance(tokenizer, str) or tokenizer is None: tokenizer = initialize_tokenizer_from_path(model_args, model, teacher) # setup new SparseSession unless user requests otherwise if training_args.clear_sparse_session: session_manager.create_session() session_manager.active_session().reset() session_manager.pre_initialize_structure(model=model, framework=Framework.pytorch) # intialize session manager apply_recipe_structure_to_model(model, None, model_path) # Load datasets stage_runner = StageRunner( model_args=model_args, data_args=data_args, training_args=training_args, model=model, ) stage_runner.populate_datasets(tokenizer=tokenizer) train_dataset = stage_runner.get_dataset_split("train") eval_dataset = stage_runner.get_dataset_split("validation") calib_dataset = stage_runner.get_dataset_split("calibration") # Initialize our Trainer data_collator = DefaultDataCollator() trainer = Trainer( model_init=get_session_model, teacher=teacher, model_state_path=model_path, recipe=training_args.recipe, metadata_args=metadata_args, recipe_args=training_args.recipe_args, args=training_args, data_args=data_args, train_dataset=train_dataset or calib_dataset, eval_dataset=eval_dataset, tokenizer=tokenizer, data_collator=data_collator, ) if trainer.is_fsdp_enabled: trainer._prepare_model_for_fsdp() stage_runner.trainer = trainer # alternating Training/One-shot if training_args.run_stages: checkpoint = None if last_checkpoint is not None: checkpoint = last_checkpoint stage_runner.run_sequential_stages(checkpoint) # exit immediately return # Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint elif last_checkpoint is not None: checkpoint = last_checkpoint stage_runner.train(checkpoint) # One Shot if training_args.do_oneshot: stage_runner.one_shot() # Evaluation if training_args.do_eval: stage_runner.evaluate() # Prediction if training_args.do_predict: stage_runner.predict() The provided code snippet includes necessary dependencies for implementing the `oneshot` function. Write a Python function `def oneshot(**kwargs)` to solve the following problem: CLI entrypoint for running oneshot calibration Here is the function: def oneshot(**kwargs): """ CLI entrypoint for running oneshot calibration """ model_args, data_args, training_args = parse_args(**kwargs) training_args.do_oneshot = True main(model_args, data_args, training_args)
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, StageRunType from sparseml.pytorch.model_load.helpers import ( apply_recipe_structure_to_model, fallback_to_cpu, get_session_model, parse_dtype, ) from sparseml.transformers import SparseAutoTokenizer from sparseml.transformers.finetune.data.data_args import DataTrainingArguments from sparseml.transformers.finetune.model_args import ModelArguments from sparseml.transformers.finetune.runner import StageRunner from sparseml.transformers.finetune.trainer import Trainer from sparseml.transformers.finetune.training_args import TrainingArguments from sparseml.transformers.utils import SparseAutoModel, get_shared_tokenizer_src from sparseml.transformers.utils.helpers import detect_last_checkpoint def apply(**kwargs): """ CLI entrypoint for any of training, eval, predict or oneshot """ model_args, data_args, training_args = parse_args(**kwargs) training_args.run_stages = True main(model_args, data_args, training_args) def compress(**kwargs): apply(**kwargs)
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, StageRunType from sparseml.pytorch.model_load.helpers import ( apply_recipe_structure_to_model, fallback_to_cpu, get_session_model, parse_dtype, ) from sparseml.transformers import SparseAutoTokenizer from sparseml.transformers.finetune.data.data_args import DataTrainingArguments from sparseml.transformers.finetune.model_args import ModelArguments from sparseml.transformers.finetune.runner import StageRunner from sparseml.transformers.finetune.trainer import Trainer from sparseml.transformers.finetune.training_args import TrainingArguments from sparseml.transformers.utils import SparseAutoModel, get_shared_tokenizer_src from sparseml.transformers.utils.helpers import detect_last_checkpoint class DataTrainingArguments(CustomDataTrainingArguments): """ Arguments pertaining to what data we are going to input our model for training and eval Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command line """ dataset: Optional[str] = field( default=None, metadata={ "help": ( "The name of the dataset to use (via the datasets library). " "Supports input as a string or DatasetDict from HF" ) }, ) dataset_config_name: Optional[str] = field( default=None, metadata={ "help": ("The configuration name of the dataset to use"), }, ) max_seq_length: int = field( default=384, metadata={ "help": "The maximum total input sequence length after tokenization. " "Sequences longer than this will be truncated, sequences shorter will " "be padded." }, ) concatenate_data: bool = field( default=False, metadata={ "help": "Whether or not to concatenate datapoints to fill max_seq_length" }, ) raw_kwargs: Optional[Dict] = field( default=None, metadata={"help": "Additional keyboard args to pass to datasets load_data"}, ) splits: Union[None, str, List, Dict] = field( default=None, metadata={"help": "Optional percentages of each split to download"}, ) num_calibration_samples: Optional[int] = field( default=512, metadata={"help": "Number of samples to use for one-shot calibration"}, ) streaming: Optional[bool] = field( default=False, metadata={"help": "True to stream data from a cloud dataset"}, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}, ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) pad_to_max_length: bool = field( default=True, metadata={ "help": "Whether to pad all samples to `max_seq_length`. If False, " "will pad the samples dynamically when batching to the maximum length " "in the batch (which can be faster on GPU but will be slower on TPU)." }, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number " "of training examples to this value if set." }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number " "of evaluation examples to this value if set." }, ) max_predict_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of " "prediction examples to this value if set." ), }, ) class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from """ model: str = field( metadata={ "help": ( "A pretrained model or a string as a path to pretrained model, " "sparsezoo stub, or model identifier from huggingface.co/models." ) }, ) distill_teacher: Optional[str] = field( default=None, metadata={ "help": "Teacher model (a trained text generation model)", }, ) config_name: Optional[str] = field( default=None, metadata={ "help": "Pretrained config name or path if not the same as model_name" }, ) tokenizer: Optional[str] = field( default=None, metadata={ "help": "Pretrained tokenizer name or path if not the same as model_name" }, ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where to store the pretrained data from huggingface.co"}, ) use_fast_tokenizer: bool = field( default=True, metadata={"help": "Whether to use one of the fast tokenizers. Default True"}, ) model_revision: str = field( default="main", metadata={ "help": "The specific model version to use " "(can be a branch name, tag name or commit id)" }, ) use_auth_token: bool = field( default=False, metadata={ "help": "Will use token generated when running `transformers-cli login` " "(necessary to use this script with private models)" }, ) precision: str = field( default="auto", metadata={"help": "Precision to cast model weights to, default to auto"}, ) class TrainingArguments(HFTrainingArgs): """ Training arguments specific to SparseML Transformers workflow :param best_model_after_epoch (`int`, *optional*, defaults to None): The epoch after which best model will be saved; used in conjunction with `load_best_model_at_end` and `metric_for_best_model` training arguments """ best_model_after_epoch: int = field( default=None, metadata={"help": "Epoch after which best model will be saved."}, ) recipe: Optional[str] = field( default=None, metadata={ "help": ( "Path to a SparseML sparsification recipe, see " "https://github.com/neuralmagic/sparseml for more information" ), }, ) recipe_args: Optional[List[str]] = field( default=None, metadata={ "help": ( "List of recipe arguments to evaluate, of the format key1=value1 " "key2=value2" ) }, ) do_oneshot: Optional[bool] = field( default=False, metadata={"help": "Whether to run one-shot calibration"}, ) run_stages: Optional[bool] = field( default=False, metadata={"help": "Whether to trigger recipe stage by stage"} ) oneshot_device: Optional[str] = field( default="cuda:0", metadata={"help": "Device to run oneshot calibration on"}, ) clear_sparse_session: Optional[bool] = field( default=True, metadata={"help": "Whether to clear SparseSession data between runs."}, ) save_safetensors: Optional[bool] = field( default=True, metadata={ "help": "Use safetensors saving and loading for state dicts instead of " "default torch.load and torch.save." }, ) output_dir: str = field( default="./output", metadata={ "help": "The output directory where the model predictions and " "checkpoints will be written." }, ) def load_dataset(dataset_name: str, **kwargs): parser = HfArgumentParser( (ModelArguments, DataTrainingArguments, TrainingArguments) ) model_args, data_args, training_args = parser.parse_dict(kwargs) data_args["dataset_name"] = dataset_name
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, StageRunType from sparseml.pytorch.model_load.helpers import ( apply_recipe_structure_to_model, fallback_to_cpu, get_session_model, parse_dtype, ) from sparseml.transformers import SparseAutoTokenizer from sparseml.transformers.finetune.data.data_args import DataTrainingArguments from sparseml.transformers.finetune.model_args import ModelArguments from sparseml.transformers.finetune.runner import StageRunner from sparseml.transformers.finetune.trainer import Trainer from sparseml.transformers.finetune.training_args import TrainingArguments from sparseml.transformers.utils import SparseAutoModel, get_shared_tokenizer_src from sparseml.transformers.utils.helpers import detect_last_checkpoint _LOGGER: logging.Logger = logging.getLogger(__name__) def fallback_to_cpu(device: str) -> str: """ Takes in a device string and forces it to cpu if cuda is not available :param device: device id to check :return: device modified for CUDA status """ if "cuda" in device and not torch.cuda.is_available(): _LOGGER.warning( f"Requested {device} but CUDA is not available, falling back to CPU" ) return "cpu" return device def parse_dtype(dtype_arg: str) -> torch.dtype: """ :param dtype_arg: dtype string to parse :return: torch.dtype parsed from input string """ dtype = "auto" # get precision from model by default if dtype_arg == "half" or dtype_arg == "float16": dtype = torch.float16 elif dtype_arg == "bfloat16": dtype = torch.bfloat16 elif dtype_arg == "full" or dtype_arg == "float32": dtype = torch.float32 return dtype class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from """ model: str = field( metadata={ "help": ( "A pretrained model or a string as a path to pretrained model, " "sparsezoo stub, or model identifier from huggingface.co/models." ) }, ) distill_teacher: Optional[str] = field( default=None, metadata={ "help": "Teacher model (a trained text generation model)", }, ) config_name: Optional[str] = field( default=None, metadata={ "help": "Pretrained config name or path if not the same as model_name" }, ) tokenizer: Optional[str] = field( default=None, metadata={ "help": "Pretrained tokenizer name or path if not the same as model_name" }, ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where to store the pretrained data from huggingface.co"}, ) use_fast_tokenizer: bool = field( default=True, metadata={"help": "Whether to use one of the fast tokenizers. Default True"}, ) model_revision: str = field( default="main", metadata={ "help": "The specific model version to use " "(can be a branch name, tag name or commit id)" }, ) use_auth_token: bool = field( default=False, metadata={ "help": "Will use token generated when running `transformers-cli login` " "(necessary to use this script with private models)" }, ) precision: str = field( default="auto", metadata={"help": "Precision to cast model weights to, default to auto"}, ) class TrainingArguments(HFTrainingArgs): """ Training arguments specific to SparseML Transformers workflow :param best_model_after_epoch (`int`, *optional*, defaults to None): The epoch after which best model will be saved; used in conjunction with `load_best_model_at_end` and `metric_for_best_model` training arguments """ best_model_after_epoch: int = field( default=None, metadata={"help": "Epoch after which best model will be saved."}, ) recipe: Optional[str] = field( default=None, metadata={ "help": ( "Path to a SparseML sparsification recipe, see " "https://github.com/neuralmagic/sparseml for more information" ), }, ) recipe_args: Optional[List[str]] = field( default=None, metadata={ "help": ( "List of recipe arguments to evaluate, of the format key1=value1 " "key2=value2" ) }, ) do_oneshot: Optional[bool] = field( default=False, metadata={"help": "Whether to run one-shot calibration"}, ) run_stages: Optional[bool] = field( default=False, metadata={"help": "Whether to trigger recipe stage by stage"} ) oneshot_device: Optional[str] = field( default="cuda:0", metadata={"help": "Device to run oneshot calibration on"}, ) clear_sparse_session: Optional[bool] = field( default=True, metadata={"help": "Whether to clear SparseSession data between runs."}, ) save_safetensors: Optional[bool] = field( default=True, metadata={ "help": "Use safetensors saving and loading for state dicts instead of " "default torch.load and torch.save." }, ) output_dir: str = field( default="./output", metadata={ "help": "The output directory where the model predictions and " "checkpoints will be written." }, ) def detect_last_checkpoint( training_args: "TrainingArguments", # noqa 821 model_args: Optional["ModelArguments"] = None, # noqa 821 ): last_checkpoint = None if ( os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if training_args.run_stages and model_args is not None: model = ( model_args.model if hasattr(model_args, "model") else model_args.model_name_or_path ) if os.path.isdir(model): last_checkpoint = get_last_checkpoint(model_args.model_name_or_path) if last_checkpoint is None and (len(os.listdir(training_args.output_dir)) > 0): raise ValueError( f"Output directory ({training_args.output_dir}) already " "exists and is not empty. Use --overwrite_output_dir to overcome." ) elif ( last_checkpoint is not None and training_args.resume_from_checkpoint is None ): _LOGGER.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To " "avoid this behavior, change the `--output_dir` or add " "`--overwrite_output_dir` to train from scratch." ) return last_checkpoint def intialize_model_from_path( model_args: ModelArguments, training_args: TrainingArguments, ): last_checkpoint = detect_last_checkpoint(training_args, model_args=model_args) # Load pretrained model # The .from_pretrained methods guarantee that only one local process can # concurrently download model & vocab. model_path = model_args.model config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) teacher_config = ( AutoConfig.from_pretrained( model_args.distill_teacher, use_auth_token=True if model_args.use_auth_token else None, ) if model_args.distill_teacher else None ) model_path = ( last_checkpoint or model_args.model if hasattr(model_args, "model") else model_args.model_name_or_path ) # Set seed before initializing model. set_seed(training_args.seed) # Fallback to CPU if GPU requested and not available training_args.oneshot_device = fallback_to_cpu(training_args.oneshot_device) # Trainer handles device assignment for FSDP and training, don't do mapping here # if running oneshot outside of FSDP, apply user device settings device_map = None fsdp_enabled = os.environ.get("ACCELERATE_USE_FSDP", "false") == "true" if not fsdp_enabled and training_args.do_oneshot: device_map = training_args.oneshot_device _LOGGER.warning(f"Moving {model_path} to device {device_map} for One-Shot") elif not fsdp_enabled: device_map = "auto" model_kwargs = { "config": config, "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, "torch_dtype": parse_dtype(model_args.precision), "device_map": device_map, } teacher_device_map = None if fsdp_enabled else "auto" teacher_kwargs = { "config": teacher_config, "cache_dir": model_args.cache_dir, "use_auth_token": True if model_args.use_auth_token else None, "torch_dtype": parse_dtype(model_args.precision), "device_map": teacher_device_map, } # this calls from_pretrained under the hood so should be FSDP safe model = SparseAutoModel.text_generation_from_pretrained( model_name_or_path=model_path, sequence_length=None, # use model default **model_kwargs, ) teacher = ( SparseAutoModel.text_generation_from_pretrained( model_name_or_path=model_args.distill_teacher, sequence_length=None, # use model default **teacher_kwargs, ) if model_args.distill_teacher is not None else None ) return teacher, model_path, model
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, StageRunType from sparseml.pytorch.model_load.helpers import ( apply_recipe_structure_to_model, fallback_to_cpu, get_session_model, parse_dtype, ) from sparseml.transformers import SparseAutoTokenizer from sparseml.transformers.finetune.data.data_args import DataTrainingArguments from sparseml.transformers.finetune.model_args import ModelArguments from sparseml.transformers.finetune.runner import StageRunner from sparseml.transformers.finetune.trainer import Trainer from sparseml.transformers.finetune.training_args import TrainingArguments from sparseml.transformers.utils import SparseAutoModel, get_shared_tokenizer_src from sparseml.transformers.utils.helpers import detect_last_checkpoint def initialize_tokenizer_from_path(model_args, model, teacher): tokenizer_src = model_args.tokenizer tokenizer_src = tokenizer_src or get_shared_tokenizer_src(model, teacher) tokenizer = SparseAutoTokenizer.from_pretrained( tokenizer_src, cache_dir=model_args.cache_dir, use_fast=True, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) return tokenizer
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 the `make_dataset_splits` function. Write a Python function `def make_dataset_splits( tokenized_datasets: Dict[str, Any], do_train: bool = False, do_eval: bool = False, do_predict: bool = False, do_oneshot: bool = False, ) -> Dict[str, Dataset]` to solve the following problem: 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 do_oneshot: Whether to store the calibration dataset :return: Datasets to be used by the requested tasks Here is the function: def make_dataset_splits( tokenized_datasets: Dict[str, Any], do_train: bool = False, do_eval: bool = False, do_predict: bool = False, do_oneshot: bool = False, ) -> Dict[str, Dataset]: """ 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 do_oneshot: Whether to store the calibration dataset :return: Datasets to be used by the requested tasks """ # handles case where all splits are contained in a single dataset if "all" in tokenized_datasets and len(tokenized_datasets) == 1: tokenized_datasets = tokenized_datasets.get("all") if isinstance(tokenized_datasets, Dataset): tokenized_datasets = {"train": tokenized_datasets} train_split = eval_split = predict_split = calib_split = None if do_train: if "train" not in tokenized_datasets: raise ValueError("--do_train requires a train dataset") train_split = tokenized_datasets["train"] if do_eval: if "validation" not in tokenized_datasets: raise ValueError("--do_eval requires a validation dataset") eval_split = tokenized_datasets["validation"] if do_predict: if "test" not in tokenized_datasets: raise ValueError("--do_predict requires a test dataset") predict_split = tokenized_datasets["test"] if do_oneshot: calib_split = tokenized_datasets.get("calibration") if calib_split is None: if "train" not in tokenized_datasets: raise ValueError("--do_oneshot requires a calibration dataset") calib_split = tokenized_datasets["train"] split_datasets = { "train": train_split, "validation": eval_split, "test": predict_split, "calibration": calib_split, } return split_datasets
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 do_oneshot: Whether to store the calibration dataset :return: Datasets to be used by the requested tasks
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 dict keys to `train`, `val` or `test` for the given input dict if matches exist with the existing keys. Note that there can only be one matching file name. Ex. Folder(train_eval.json) -> Folder(train.json) Folder(train1.json, train2.json) -> Same :param data_files: The dict where keys will be transformed """ keys = set(data_files.keys()) def transform_dataset_key(candidate: str) -> None: for key in keys: if candidate in key: if key == candidate: return val = data_files.pop(key) data_files[candidate] = val def do_transform(candidate: str) -> bool: return sum(candidate in key for key in keys) == 1 dataset_keys = ("train", "val", "test") for dataset_key in dataset_keys: if do_transform(dataset_key): transform_dataset_key(dataset_key) return data_files The provided code snippet includes necessary dependencies for implementing the `get_custom_datasets_from_path` function. Write a Python function `def get_custom_datasets_from_path(path: str, ext: str = "json") -> Dict[str, str]` to solve the following problem: 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 subdirectory names or direct dataset names (depending on the directory structure) and the values are either file paths (if only one file exists with that name) or lists of file paths (if multiple files exist). :param path: The path to the directory containing the dataset files. :param ext: The file extension to filter files by. Default is 'json'. :return: A dictionary mapping dataset names to their file paths or lists of file paths. Example: dataset = get_custom_datasets_from_path("/path/to/dataset/directory", "json") Note: If datasets are organized in subdirectories, the function constructs the dictionary with lists of file paths. If datasets are found directly in the main directory, they are included with their respective names. Accepts: - path\ train.json test.json val.json - path\ train\ data1.json data2.json ... test\ ... val\ ... Here is the function: def get_custom_datasets_from_path(path: str, ext: str = "json") -> Dict[str, str]: """ 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 subdirectory names or direct dataset names (depending on the directory structure) and the values are either file paths (if only one file exists with that name) or lists of file paths (if multiple files exist). :param path: The path to the directory containing the dataset files. :param ext: The file extension to filter files by. Default is 'json'. :return: A dictionary mapping dataset names to their file paths or lists of file paths. Example: dataset = get_custom_datasets_from_path("/path/to/dataset/directory", "json") Note: If datasets are organized in subdirectories, the function constructs the dictionary with lists of file paths. If datasets are found directly in the main directory, they are included with their respective names. Accepts: - path\ train.json test.json val.json - path\ train\ data1.json data2.json ... test\ ... val\ ... """ data_files = {} if any(filename.endswith(ext) for filename in os.listdir(path)): # If there are files with the given extension in the path for filename in os.listdir(path): if filename.endswith(ext): name, _ = os.path.splitext(filename) data_files[name] = os.path.join(path, filename) else: # If datasets are organized in subdirectories for root, dirs, files in os.walk(path): for dir_name in dirs: dir_path = os.path.join(root, dir_name) dir_dataset = [] for filename in os.listdir(dir_path): if filename.endswith(ext): file_path = os.path.join(dir_path, filename) dir_dataset.append(file_path) if dir_dataset: data_files[dir_name] = dir_dataset return transform_dataset_keys(data_files)
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 subdirectory names or direct dataset names (depending on the directory structure) and the values are either file paths (if only one file exists with that name) or lists of file paths (if multiple files exist). :param path: The path to the directory containing the dataset files. :param ext: The file extension to filter files by. Default is 'json'. :return: A dictionary mapping dataset names to their file paths or lists of file paths. Example: dataset = get_custom_datasets_from_path("/path/to/dataset/directory", "json") Note: If datasets are organized in subdirectories, the function constructs the dictionary with lists of file paths. If datasets are found directly in the main directory, they are included with their respective names. Accepts: - path\ train.json test.json val.json - path\ train\ data1.json data2.json ... test\ ... val\ ...