id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
21,400 | import logging
from typing import Any, Dict, Generator, List, Optional, Set, Tuple
import numpy
from onnx import ModelProto, numpy_helper
from sparseml.onnx.utils import DataLoader, DeepSparseAnalyzeModelRunner, ONNXGraph
from sparseml.optim import default_pruning_sparsities_perf
from sparseml.sparsification import Ana... | null |
21,401 | from collections import OrderedDict
from typing import List, Optional, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, numpy_helper
from sparseml.onnx.utils import ONNXGraph, get_node_attributes
from sparseml.sparsification import LayerInfo
from sparseml.sparsification import ModelInfo as BaseMod... | null |
21,402 | from collections import OrderedDict
from typing import List, Optional, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, numpy_helper
from sparseml.onnx.utils import ONNXGraph, get_node_attributes
from sparseml.sparsification import LayerInfo
from sparseml.sparsification import ModelInfo as BaseMod... | null |
21,403 | from collections import OrderedDict
from typing import List, Optional, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, numpy_helper
from sparseml.onnx.utils import ONNXGraph, get_node_attributes
from sparseml.sparsification import LayerInfo
from sparseml.sparsification import ModelInfo as BaseMod... | null |
21,404 | import logging
from sparseml.sparsification import SparsificationInfo
_LOGGER = logging.getLogger(__name__)
The provided code snippet includes necessary dependencies for implementing the `sparsification_info` function. Write a Python function `def sparsification_info() -> SparsificationInfo` to solve the following pro... | Load the available setup for sparsifying model within onnx. :return: The sparsification info for the onnx framework :rtype: SparsificationInfo |
21,405 | import logging
import os
from collections import OrderedDict
from typing import Any, Dict, Iterable, Optional, Tuple, Union
import onnx
from onnx import ModelProto
from sparseml.base import Framework
from sparseml.benchmark import BatchBenchmarkResult, BenchmarkInfo, BenchmarkRunner
from sparseml.framework import Frame... | null |
21,406 | import logging
import os
from collections import OrderedDict
from typing import Any, Dict, Iterable, Optional, Tuple, Union
import onnx
from onnx import ModelProto
from sparseml.base import Framework
from sparseml.benchmark import BatchBenchmarkResult, BenchmarkInfo, BenchmarkRunner
from sparseml.framework import Frame... | Creates a iteratable data loader for the given data. Acceptable types for data are: - a folder path containing numpy files - a list of file paths - a SparseML DataLoader - a SparseZoo DataLoader - an iterable - None type, in which case model must be passed :param data: data to use for benchmarking :param model: model t... |
21,407 | import logging
import os
from collections import OrderedDict
from typing import Any, Dict, Iterable, Optional, Tuple, Union
import onnx
from onnx import ModelProto
from sparseml.base import Framework
from sparseml.benchmark import BatchBenchmarkResult, BenchmarkInfo, BenchmarkRunner
from sparseml.framework import Frame... | Run a benchmark for the given 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 inf... |
21,408 | import logging
import numbers
import time
from typing import Any, Generator, List, NamedTuple, Tuple, Union
import numpy
from onnx import ModelProto
from tqdm import auto
from sparseml.onnx.utils import (
DataLoader,
DeepSparseAnalyzeModelRunner,
DeepSparseModelRunner,
ORTModelRunner,
extract_node_i... | Approximate the pruning sensitivity of a Neural Network's layer based on the params and metadata for a given layer :param input_shape: the input shape to the layer :param output_shape: the output shape from the layer :param params: the number of params in the layer :param apply_shape_change_mult: True to adjust the sen... |
21,409 | import logging
import numbers
import time
from typing import Any, Generator, List, NamedTuple, Tuple, Union
import numpy
from onnx import ModelProto
from tqdm import auto
from sparseml.onnx.utils import (
DataLoader,
DeepSparseAnalyzeModelRunner,
DeepSparseModelRunner,
ORTModelRunner,
extract_node_i... | Approximated kernel sparsity (pruning) loss analysis for a given model. Returns the results for each prunable param (conv, linear) in the model. :param model: the loaded model or a file path to the onnx model to calculate the sparse sensitivity analysis for :param sparsity_levels: the sparsity levels to calculate the l... |
21,410 | import logging
import numbers
import time
from typing import Any, Generator, List, NamedTuple, Tuple, Union
import numpy
from onnx import ModelProto
from tqdm import auto
from sparseml.onnx.utils import (
DataLoader,
DeepSparseAnalyzeModelRunner,
DeepSparseModelRunner,
ORTModelRunner,
extract_node_i... | Run a one shot sensitivity analysis for kernel sparsity. It does not retrain,. Moves layer by layer to calculate the sensitivity analysis for each and resets the previously run layers. The loss is calculated by taking the kl_divergence of pruned values from the baseline. :param model: the loaded model or a file path to... |
21,411 | import logging
import numbers
import time
from typing import Any, Generator, List, NamedTuple, Tuple, Union
import numpy
from onnx import ModelProto
from tqdm import auto
from sparseml.onnx.utils import (
DataLoader,
DeepSparseAnalyzeModelRunner,
DeepSparseModelRunner,
ORTModelRunner,
extract_node_i... | Run a one shot sensitivity analysis for kernel sparsity. Runs a baseline and then sets the sparsity for each layer to a given range of values as defined in sparsity_levels to measure their performance for pruning. :param model: the loaded model or a file path to the onnx model to calculate the sparse sensitivity analys... |
21,412 | from typing import Dict, List, Set, Union
import onnx
from sparseml.onnx.utils import ONNXGraph, get_node_attributes
_PRUNABLE_OP_TYPES = ["Conv", "Gemm", "MatMul"]
def _get_node_dependency_names(
graph: ONNXGraph, node: onnx.NodeProto, structure_type: str
) -> Set[str]:
# returns a list of parameters whose sho... | :param model: model to generate pruning groups and dependencies for :param structure_type: valid options are 'filter' and 'channel'. Generates dependency map for corresponding pruning scheme. Default is 'filter' :return: dictionary of parameter names that should be grouped during structured pruning to a list of paramet... |
21,413 | from typing import Iterable, List, Union
import onnx
from tqdm.auto import tqdm
from sparseml.onnx.optim.quantization.calibration import CalibrationSession
from sparseml.onnx.optim.quantization.quantize import QuantizationMode, quantize
from sparseml.onnx.utils import DataLoader, quantize_resnet_identity_add_inputs
fro... | Wrapper function for calibrating and quantizing an Onnx model :param onnx_file: File path to saved Onnx model to calibrate and quantize :param data_loader: Iterable of lists of model inputs or filepath to directory of numpy arrays. If the model has multiple inputs and an .npz file is provided, the function will try to ... |
21,414 | import numpy as np
import onnx
import onnx.numpy_helper
from onnx import onnx_pb as onnx_proto
from onnx import shape_inference
The provided code snippet includes necessary dependencies for implementing the `quantize_data` function. Write a Python function `def quantize_data(data, quantize_range, qType)` to solve the ... | :parameter data: data to quantize :parameter quantize_range: list of data to weight pack. :parameter qType: data type to quantize to. Supported types UINT8 and INT8 :return: minimum, maximum, zero point, scale, and quantized weights To pack weights, we compute a linear transformation - when data type == uint8 mode, fro... |
21,415 | import numpy as np
import onnx
import onnx.numpy_helper
from onnx import onnx_pb as onnx_proto
from onnx import shape_inference
The provided code snippet includes necessary dependencies for implementing the `_attribute_to_kwarg` function. Write a Python function `def _attribute_to_kwarg(attribute)` to solve the follow... | Convert attribute to kwarg format for use with onnx.helper.make_node. :parameter attribute: attribute in AttributeProto format. :return: attribute in {key: value} format. |
21,416 | import numpy as np
import onnx
import onnx.numpy_helper
from onnx import onnx_pb as onnx_proto
from onnx import shape_inference
The provided code snippet includes necessary dependencies for implementing the `_get_mul_node` function. Write a Python function `def _get_mul_node(inputs, output, name)` to solve the followi... | Helper function to create a Mul node. parameter inputs: list of input names. parameter output: output name. parameter name: name of the node. return: Mul node in NodeProto format. |
21,417 | import numpy as np
import onnx
import onnx.numpy_helper
from onnx import onnx_pb as onnx_proto
from onnx import shape_inference
def _find_by_name(item_name, item_list):
"""
Helper function to find item by name in a list.
parameter item_name: name of the item.
parameter item_list: list of items.
... | Helper function to check if a node exists in a graph or new set of nodes created during quantization. parameter node_name: name of the node. parameter graph: GraphProto. parameter new_nodes_list: list of nodes added during quantization. return: NodeProto if found. None otherwise. |
21,418 | import numpy as np
import onnx
import onnx.numpy_helper
from onnx import onnx_pb as onnx_proto
from onnx import shape_inference
def _find_by_name(item_name, item_list):
"""
Helper function to find item by name in a list.
parameter item_name: name of the item.
parameter item_list: list of items.
... | Helper function to add an initializer if it is not present in the graph. parameter graph: GraphProto. parameter name: Initializer's name. parameter value: Initializer's value. parameter shape: Initializer's shape. parameter type: Initializer's type. |
21,419 | import numpy as np
import onnx
import onnx.numpy_helper
from onnx import onnx_pb as onnx_proto
from onnx import shape_inference
The provided code snippet includes necessary dependencies for implementing the `_get_qrange_for_qType` function. Write a Python function `def _get_qrange_for_qType(qType)` to solve the follow... | Helper function to get the quantization range for a type. parameter qType: quantization type. return: quantization range. |
21,420 | import numpy as np
import onnx
import onnx.numpy_helper
from onnx import onnx_pb as onnx_proto
from onnx import shape_inference
The provided code snippet includes necessary dependencies for implementing the `_find_nodes_using_initializer` function. Write a Python function `def _find_nodes_using_initializer(graph, init... | Helper function to find all nodes with an initializer as a input. parameter graph: GraphProto. parameter initializer: Initializer in TensorProto format. return: List of nodes. |
21,421 | import logging
from typing import Any
from sparseml.base import Framework, get_version
from sparseml.framework import FrameworkInferenceProviderInfo, FrameworkInfo
from sparseml.onnx.base import check_onnx_install, check_onnxruntime_install
from sparseml.onnx.sparsification import sparsification_info
from sparseml.spar... | :param item: The item to detect the support for :type item: Any :return: True if the item is supported by onnx/onnxruntime, False otherwise :rtype: bool |
21,422 | import logging
from typing import Any
from sparseml.base import Framework, get_version
from sparseml.framework import FrameworkInferenceProviderInfo, FrameworkInfo
from sparseml.onnx.base import check_onnx_install, check_onnxruntime_install
from sparseml.onnx.sparsification import sparsification_info
from sparseml.spar... | Detect the information for the onnx/onnxruntime 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 onnx/onnxruntime :rtype: FrameworkInfo |
21,423 | from copy import deepcopy
from typing import Union
import numpy
from onnx import ModelProto, TensorProto, numpy_helper
def _check_sparse_tensor_import():
if sparse_tensor_import_error:
# ONNX >= 1.6.0 required
raise sparse_tensor_import_error
def create_sparse_tensor(
array: Union[numpy.ndarray,... | :param model: ONNX model with initializers to convert to sparse :param sparsity_threshold: the minimum sparsity of a tensor to be converted to sparse representation. Default is 0.6 :param inplace: True to do model conversion in place. Default is True :return: the given model with initializers above the sparsity thresho... |
21,424 | from copy import deepcopy
from typing import Union
import numpy
from onnx import ModelProto, TensorProto, numpy_helper
def _check_sparse_tensor_import():
if sparse_tensor_import_error:
# ONNX >= 1.6.0 required
raise sparse_tensor_import_error
def sparse_tensor_to_dense(sparse_tensor: SparseTensorPro... | :param model: ONNX model with sparse initializers to convert to dense representation :param inplace: True to do model conversion in place. Default is True :return: The given model with all sparse initializers converted to dense initializers |
21,425 | import logging
import os
import re
import tempfile
import time
from abc import ABC, abstractmethod
from collections import OrderedDict
from copy import deepcopy
from typing import Any, Callable, Dict, List, Tuple, Union
import numpy
import psutil
from onnx import ModelProto
from tqdm import auto
from sparseml.onnx.base... | null |
21,426 | import logging
import os
import re
import tempfile
import time
from abc import ABC, abstractmethod
from collections import OrderedDict
from copy import deepcopy
from typing import Any, Callable, Dict, List, Tuple, Union
import numpy
import psutil
from onnx import ModelProto
from tqdm import auto
from sparseml.onnx.base... | :return: the maximum number of physical cores detected on the system |
21,427 | import logging
import os
import re
import tempfile
import time
from abc import ABC, abstractmethod
from collections import OrderedDict
from copy import deepcopy
from typing import Any, Callable, Dict, List, Tuple, Union
import numpy
import psutil
from onnx import ModelProto
from tqdm import auto
from sparseml.onnx.base... | Correct the node ids returned from the deepsparse.analyze_model api. In some cases, it will return the ids for folded nodes due to ONNXRuntime folding. This finds the corrected node ids from those folded nodes. Additionally, ops that did not have an id are changed from the returned string <none> to proper None python t... |
21,428 | import logging
import os
import re
import tempfile
import time
from abc import ABC, abstractmethod
from collections import OrderedDict
from copy import deepcopy
from typing import Any, Callable, Dict, List, Tuple, Union
import numpy
import psutil
from onnx import ModelProto
from tqdm import auto
from sparseml.onnx.base... | Splits analysis layer results from grouped canonical names by individual nodes. Stores the original grouped canonical name in the 'meta_canonical_name' field. Will split on any canonical_name that includes ','. :param nm_result: the result from the deepsparse.model_debug_analysis api |
21,429 | import numpy
from scipy.stats import entropy
The provided code snippet includes necessary dependencies for implementing the `kl_divergence` function. Write a Python function `def kl_divergence( predicted: numpy.ndarray, expected: numpy.ndarray, zero_point: float = 0.0, min_value: float = 1.0, ) -> floa... | Calculate the kl_divergence (entropy) between two input arrays. Shifts all values such that the zero_point is at one. If a value is lower, then sets it equal to 1. :param predicted: the first array to compare with :param expected: the second array to compare with :param zero_point: the zero point that should be used to... |
21,430 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | Extract the NumPy dtype of an ONNX tensor. Returns None if there is not a direct mapping from the ONNX data type to a NumPy dtype. :param tensor: the tensor to get the dtype of :return: a NumPy dtype for the tensor if available otherwise None |
21,431 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | Extracts the shape information for each node as a NodeShape object. :param model: the loaded onnx.ModelProto to extract node shape information from :return: a mapping of node id to a NodeShape object |
21,432 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | :param node: Node to get the attribute value of :param attr: Attribute name to match in the node :return: The value of the attribute if the attribute found in the node and is a float type. Otherwise returns None |
21,433 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | Retrieve the sparsities for each Conv or Gemm op in an ONNX graph for the associated weight inputs. :param model: ONNX model to use :return: a tuple containing the overall sparsity measurement for the model, each conv or gemm node found in the model |
21,434 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | Get the input to the model from an ONNX model :param model: the loaded model or a file path to the ONNX model to get the model inputs for :return: the input to the model |
21,435 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | Get the output from an ONNX model :param model: the loaded model or a file path to the ONNX model to get the model outputs for :return: the output from the model |
21,436 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | Get the kernel shape from a dictionary of a model's attributes :param attributes: a dictionary of a model's attributes :return: the kernel shape if attribute contains either the kernel or kernel_shape field, otherwise None |
21,437 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | Calculate flops based on operation type and shape of certain attributes. If any fields necessary in operation are set to None, will return None :param op_type: Operation type of flop calculation :param input_shape: List of input shapes of operation :param output_shape: List of output shapes of operation :param weight_s... |
21,438 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | :param tensor: ONNX tensor to get the shape of :return: shape of the tensor as a list |
21,439 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | :param tensor: ONNX tensor to get the shape of a dimension of :param dim: dimension index of the tensor to get the shape of :return: shape of the tensor at the given dimension |
21,440 | import logging
from collections import OrderedDict
from copy import deepcopy
from functools import reduce
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from onnx.helper import get_attribute_value, make_empty_tensor... | Set the shape of the first input of the given model to the given shape. If given a file, the file will be overwritten :param model: ONNX model or model path to overrwrite :param shape: shape as list of integers to override with. must match existing dimensions |
21,441 | from typing import Tuple, Union
import numpy as np
import onnx
from sparseml.onnx.utils.graph_editor import (
ONNXGraph,
remove_node_and_params_from_graph,
swap_node_output,
update_model_param,
)
from sparseml.onnx.utils.helpers import (
BatchNormParams,
NodeParam,
conv_node_params,
get_... | When a batch norm op is the only child operator of a conv op, this function will fold the batch norm into the conv and return the processed graph :param onnx_file: file path to ONNX model to process or in-memory ModelProto to be modified in-place :return: A loaded ONNX model with BatchNormalization ops folded into Conv... |
21,442 | from typing import Tuple, Union
import numpy as np
import onnx
from sparseml.onnx.utils.graph_editor import (
ONNXGraph,
remove_node_and_params_from_graph,
swap_node_output,
update_model_param,
)
from sparseml.onnx.utils.helpers import (
BatchNormParams,
NodeParam,
conv_node_params,
get_... | To avoid storing the identity value of a ResNet block in fp32, this optimization will pass the identity value through the same quantize operation as the ResNet block and add a de-quantize operation for the identity before the add. Function will match to any add operation whose inputs are the output of a relu or add op ... |
21,443 | from typing import Tuple, Union
import numpy as np
import onnx
from sparseml.onnx.utils.graph_editor import (
ONNXGraph,
remove_node_and_params_from_graph,
swap_node_output,
update_model_param,
)
from sparseml.onnx.utils.helpers import (
BatchNormParams,
NodeParam,
conv_node_params,
get_... | null |
21,444 | from collections import defaultdict
from typing import Iterable, List, Optional, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from toposort import toposort_flatten
from sparseml.onnx.utils.helpers import get_node_params
def _override_tensor_batch_dim(model, tensor, ba... | Rewrites any positive batch dimensions in the model inputs or outputs to the given batch_size :param model: Model to modify :param batch_size: Batch size to enforce :return: the given model with inputs and outputs set to batch_size if the batch dimensions are not -1. |
21,445 | from collections import defaultdict
from typing import Iterable, List, Optional, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from toposort import toposort_flatten
from sparseml.onnx.utils.helpers import get_node_params
def update_model_param(
model: ModelProto,
... | Prune a model in-place with one shot pruning (no retraining) according to magnitude pruning. Does so in an unstructured way currently :param model: the model to apply pruning to :param nodes: the nodes within the model to prune to the desired sparsities :param sparsity: the sparsity level to prune all nodes to if a flo... |
21,446 | from collections import defaultdict
from typing import Iterable, List, Optional, Union
import numpy
import onnx
from onnx import ModelProto, NodeProto, TensorProto, numpy_helper
from toposort import toposort_flatten
from sparseml.onnx.utils.helpers import get_node_params
def update_model_param(
model: ModelProto,
... | Iteratively prune a model in-place with one shot pruning (no retraining) according to magnitude pruning. Does so in an unstructured way currently :param model: the model to apply pruning to :param nodes: the nodes within the model to prune to the desired sparsities :param sparsity: the sparsity level to prune all nodes... |
21,447 | import logging
from typing import Any, Dict, Iterable, List, Optional, Tuple
import numpy as np
import torch
from tqdm import tqdm
from sparseml.core.model.base import ModifiableModel
from sparseml.core.state import State
from sparseml.modifiers.pruning.wanda.base import WandaPruningModifier
from sparseml.modifiers.pru... | null |
21,448 | import math
import re
from dataclasses import dataclass
from typing import Any, Callable, Dict
from sparseml.core import Event, State
class PruningCreateSettings:
start: float
end: float
update: float
init_sparsity: float
final_sparsity: float
args: Dict[str, Any]
SchedulerCalculationType = Call... | null |
21,449 | import math
import re
from dataclasses import dataclass
from typing import Any, Callable, Dict
from sparseml.core import Event, State
class PruningCreateSettings:
start: float
end: float
update: float
init_sparsity: float
final_sparsity: float
args: Dict[str, Any]
SchedulerCalculationType = Call... | null |
21,450 | import math
import re
from dataclasses import dataclass
from typing import Any, Callable, Dict
from sparseml.core import Event, State
class PruningCreateSettings:
start: float
end: float
update: float
init_sparsity: float
final_sparsity: float
args: Dict[str, Any]
SchedulerCalculationType = Call... | null |
21,451 | import math
import re
from dataclasses import dataclass
from typing import Any, Callable, Dict
from sparseml.core import Event, State
class PruningCreateSettings:
SchedulerCalculationType = Callable[[Event, State], float]
def polynomial_scheduler(settings: PruningCreateSettings) -> SchedulerCalculationType:
args =... | null |
21,452 | import math
import re
from dataclasses import dataclass
from typing import Any, Callable, Dict
from sparseml.core import Event, State
class PruningCreateSettings:
SchedulerCalculationType = Callable[[Event, State], float]
def multi_step_scheduler(settings: PruningCreateSettings) -> SchedulerCalculationType:
args =... | null |
21,453 | from dataclasses import dataclass
from typing import Dict
import torch
from pydantic import BaseModel
from torch.nn import Module, Parameter
from torch.utils.hooks import RemovableHandle
from sparseml.core import ModelParameterizedLayer
The provided code snippet includes necessary dependencies for implementing the `pa... | Name to use for mask buffer on a sparse layer |
21,454 | from dataclasses import dataclass
from typing import Dict
import torch
from pydantic import BaseModel
from torch.nn import Module, Parameter
from torch.utils.hooks import RemovableHandle
from sparseml.core import ModelParameterizedLayer
try:
import torch
_PARSED_TORCH_VERSION = version.parse(torch.__version__... | null |
21,455 | import re
from dataclasses import dataclass
from typing import Callable, Optional
import torch
from torch import Tensor
from torch.nn.parameter import Parameter
class PruningMaskCreatorArgs:
try:
import torch
_PARSED_TORCH_VERSION = version.parse(torch.__version__)
if _PARSED_TORCH_VERSION.major >= 2:
... | null |
21,456 | import re
from dataclasses import dataclass
from typing import Callable, Optional
import torch
from torch import Tensor
from torch.nn.parameter import Parameter
class PruningMaskCreatorArgs:
parameter: Parameter
sparsity: float
scores: Tensor
prev_mask: Optional[Tensor] = None
try:
import torch
... | null |
21,457 | import re
from dataclasses import dataclass
from typing import Callable, Optional
import torch
from torch import Tensor
from torch.nn.parameter import Parameter
class PruningMaskCreatorArgs:
parameter: Parameter
sparsity: float
scores: Tensor
prev_mask: Optional[Tensor] = None
try:
import torch
... | null |
21,458 | import re
from dataclasses import dataclass
from typing import Callable, Optional
import torch
from torch import Tensor
from torch.nn.parameter import Parameter
class PruningMaskCreatorArgs:
parameter: Parameter
sparsity: float
scores: Tensor
prev_mask: Optional[Tensor] = None
try:
import torch
... | null |
21,459 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def identity_transform(name: str, **kwargs):... | null |
21,460 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_apply(
val: TensorOrCollect... | null |
21,461 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_apply(
val: TensorOrCollect... | null |
21,462 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_apply(
val: TensorOrCollect... | null |
21,463 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_combine(
val_one: TensorOrC... | null |
21,464 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_combine(
val_one: TensorOrC... | null |
21,465 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_combine(
val_one: TensorOrC... | null |
21,466 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_combine(
val_one: TensorOrC... | null |
21,467 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_combine(
val_one: TensorOrC... | null |
21,468 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_combine(
val_one: TensorOrC... | null |
21,469 | import re
from typing import Callable, Dict, Sequence, Tuple, Union
import torch
import torch.nn.functional as TF
from torch import Tensor
from torch.nn import Module
from sparseml.core import State
TensorOrCollectionType = Union[Tensor, Sequence[Tensor], Dict[str, Tensor]]
def recursive_combine(
val_one: TensorOrC... | null |
21,470 | import logging
import operator
from collections import defaultdict
from math import ceil
from typing import List, Optional
import torch
from torch.nn.modules.sparse import Embedding
_LOGGER = logging.getLogger(__name__)
def ppl_eval_general(
eval_logits, model, dataloader, dev, nsamples=None, max_samples_per_itera... | null |
21,471 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.intrinsic as nni
from packaging import version
from torch import quantization as torch_quantization
from torch.nn import BatchNorm2d, Conv2d, Embedding, Mo... | Wrap any BatchNormalization modules that are not fused with convolutions with BNWrapper to enable freezing/unfreezing of BN statistics :param module: module to potentially wrap the submodules of |
21,472 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.intrinsic as nni
from packaging import version
from torch import quantization as torch_quantization
from torch.nn import BatchNorm2d, Conv2d, Embedding, Mo... | if any submodule of the given module has the attribute wrap_qat == True, then it will be replaced by a QATWrapper of it created by QATWrapper.from_module. Other named kwargs to the QATWrapper constructor must be contained in a dictionary under an attributed named `qat_wrapper_kwargs` :param module: module to potentiall... |
21,473 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.intrinsic as nni
from packaging import version
from torch import quantization as torch_quantization
from torch.nn import BatchNorm2d, Conv2d, Embedding, Mo... | Wraps all Conv and Linear submodule with a qconfig with a QuantWrapper :param module: the module to modify :param name: name of the module to modify; default to None :param parent_module: parent module containing the module to modify; default to None :param layer_class_names: list of module class names to be added to t... |
21,474 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.intrinsic as nni
from packaging import version
from torch import quantization as torch_quantization
from torch.nn import BatchNorm2d, Conv2d, Embedding, Mo... | Disables fake quantization of activations for all submodules of the given module with class name layer_class_names :param module: module to remove activation fake quantization for certain layers :param layer_class_names: list of layer class names that should be affected. e.x. ["Linear"] |
21,475 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.intrinsic as nni
from packaging import version
from torch import quantization as torch_quantization
from torch.nn import BatchNorm2d, Conv2d, Embedding, Mo... | null |
21,476 | from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.intrinsic as nni
from packaging import version
from torch import quantization as torch_quantization
from torch.nn import BatchNorm2d, Conv2d, Embedding, Mo... | Performs fusion of Conv2d, BatchNorm2d, and ReLU layers found in the given module. To be fused, these layers must appear sequentially in module.named_modules() and be in the same submodule. Fuses either Conv2d -> BatchNorm2d, Conv2d -> ReLU, or Conv2d -> BatchNorm2d -> ReLU blocks If this function does not fuse the mod... |
21,477 | from typing import Dict, List, Optional
import torch
from packaging import version
from torch.nn import Identity, Module
from sparseml.modifiers.quantization.utils.constants import (
FUSED_MODULE_NAMES,
NON_QUANTIZABLE_MODULE_NAMES,
)
from sparseml.modifiers.quantization.utils.fake_quant_wrapper import FakeQuan... | Sets an appropriate `quantization_scheme` to targeted quantizable submodules :param model: module to attach QuantizationSchemes to :param scheme: default scheme to add to a target module unless overwritten by another scheme :param scheme_overrides: dictionary of module type names or submodule names mapped to a quantiza... |
21,478 | from typing import Dict, List, Optional
import torch
from packaging import version
from torch.nn import Identity, Module
from sparseml.modifiers.quantization.utils.constants import (
FUSED_MODULE_NAMES,
NON_QUANTIZABLE_MODULE_NAMES,
)
from sparseml.modifiers.quantization.utils.fake_quant_wrapper import FakeQuan... | Converts submodules with set quantization_schemes into quantization aware modules with FakeQuantize modules in the model :param module: module to convert to QAT mode |
21,479 | from typing import Dict, List, Optional
import torch
from packaging import version
from torch.nn import Identity, Module
from sparseml.modifiers.quantization.utils.constants import (
FUSED_MODULE_NAMES,
NON_QUANTIZABLE_MODULE_NAMES,
)
from sparseml.modifiers.quantization.utils.fake_quant_wrapper import FakeQuan... | :raises: RuntimeError if the installed torch version does not include support for quantization aware training |
21,480 | from copy import deepcopy
from functools import partial
from typing import Any, Dict, Optional, Union
import torch
from packaging import version
from pydantic import BaseModel, Field, validator
from torch.nn import Identity
from sparseml.modifiers.quantization.utils.fake_quant_wrapper import FakeQuantizeWrapper
class Q... | null |
21,481 | from copy import deepcopy
from functools import partial
from typing import Any, Dict, Optional, Union
import torch
from packaging import version
from pydantic import BaseModel, Field, validator
from torch.nn import Identity
from sparseml.modifiers.quantization.utils.fake_quant_wrapper import FakeQuantizeWrapper
def _p... | null |
21,482 | import logging
from typing import Any, Dict, Optional
import torch
from torch.nn import Module
from sparseml.core import Event, EventType, State
from sparseml.modifiers.quantization.base import QuantizationModifier
from sparseml.modifiers.quantization.utils.helpers import (
configure_module_bn_wrappers,
freeze_... | null |
21,483 | from itertools import cycle
from typing import Callable, Dict, Optional
import torch
from torch.nn import Module
from torch.utils.data import DataLoader
from tqdm import tqdm
from sparseml.pytorch.utils import tensors_module_forward, tensors_to_device
def apply_pad_mask_to_batch(batch: Dict[str, torch.Tensor]) -> Dict[... | Helper function used by one-shot modifiers, runs calibration data through a model to update modifier statistics and trigger hooks :param model: PyTorch model to run :param calibration_dataloader: data to use for calibration :param num_calibration_steps: number of items in calibration_dataloader to process, None or a ne... |
21,484 | from pathlib import Path
import click
def export():
from yolact.export import main as run_export
run_export() | null |
21,485 | from pathlib import Path
import click
def train():
from yolact.train import main as run_train
run_train() | null |
21,486 | from pathlib import Path
import click
def val():
from yolact.eval import main as run_val
run_val() | null |
21,487 | from pathlib import Path
import click
The provided code snippet includes necessary dependencies for implementing the `download` function. Write a Python function `def download(test: bool = False)` to solve the following problem:
A command line callable to download training/test coco dataset for yolact
Here is the fun... | A command line callable to download training/test coco dataset for yolact |
21,488 | import json
from abc import ABC, abstractmethod
from collections import OrderedDict
from copy import deepcopy
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Union
import numpy
from pydantic import BaseModel, Field, root_validator
from sparseml.utils import clean_path, create_parent_dirs
class ... | null |
21,489 | import json
from abc import ABC, abstractmethod
from collections import OrderedDict
from copy import deepcopy
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Union
import numpy
from pydantic import BaseModel, Field, root_validator
from sparseml.utils import clean_path, create_parent_dirs
class ... | null |
21,490 | import logging
from typing import Any, Dict, List, Optional, Type
from sparseml import Framework, execute_in_sparseml_framework
from sparseml.base import detect_frameworks
from sparseml.sparsification.analyzer import Analyzer
from sparseml.sparsification.recipe_builder import PruningRecipeBuilder
from sparseml.sparsifi... | :param model: loaded framework model or model file path of a model to create a recipe for :param save_path: optional path to save the created recipe to :param analyzer_kwargs: keyword arguments to be passed to the available() and run() functions of analyzer objects :param skip_analyzer_types: list of Analyzer class typ... |
21,491 | import textwrap
from copy import deepcopy
from typing import Any, Dict, List, Optional, Type, Union
import yaml
from sparseml.optim import BaseModifier, ModifierProp
from sparseml.sparsification.model_info import ModelInfo
from sparseml.sparsification.modifier_epoch import EpochRangeModifier
from sparseml.sparsificatio... | :param val: value to get yaml str value of :return: direct str cast of val if it is an int, float, or bool, otherwise the stripped output of yaml.dump |
21,492 | import argparse
import logging
import os
from enum import Enum
from typing import Any, List, Optional
from pydantic import BaseModel, Field
from sparseml.base import execute_in_sparseml_framework
from sparseml.utils import clean_path, create_parent_dirs
class SparsificationInfo(BaseModel):
"""
Class for storing... | Load the sparsification 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 sparsification info. :rtype: Sparsificat... |
21,493 | import argparse
import logging
import os
from enum import Enum
from typing import Any, List, Optional
from pydantic import BaseModel, Field
from sparseml.base import execute_in_sparseml_framework
from sparseml.utils import clean_path, create_parent_dirs
def save_sparsification_info(framework: Any, path: Optional[str] =... | null |
21,494 | from typing import Tuple, Union
from sparseml.tensorflow_v1.utils import tf_compat
def symmetric_pad2d(
x_tens: tf_compat.Tensor, pad: Union[str, int, Tuple[int, int]], data_format: str
):
"""
Create a symmetric pad op in the current graph and scope.
To do this, pad must be an integer or tuple of intege... | Create a pool op with the given name in the current graph and scope. Supported are [max, avg, global_avg] :param name: the name to given to the pooling op in the graph :param x_tens: the input tensor to apply pooling to :param type_: the type of pooling to apply, one of [max, avg, global_avg] :param pool_size: the size... |
21,495 | from typing import Tuple, Union
from sparseml.tensorflow_v1.utils import tf_compat
BN_MOMENTUM = 0.9
BN_EPSILON = 1e-5
def activation(x_tens: tf_compat.Tensor, act: Union[None, str], name: str = "act"):
"""
Create an activation operation in the current graph and scope.
:param x_tens: the tensor to apply the... | Create a convolution op and supporting ops (batch norm, activation, etc) in the current graph and scope. :param name: The name to group all ops under in the graph :param x_tens: The input tensor to apply a convolution and supporting ops to :param training: A bool or tensor to indicate if the net is being run in trainin... |
21,496 | from typing import Tuple, Union
from sparseml.tensorflow_v1.utils import tf_compat
BN_MOMENTUM = 0.9
BN_EPSILON = 1e-5
def activation(x_tens: tf_compat.Tensor, act: Union[None, str], name: str = "act"):
"""
Create an activation operation in the current graph and scope.
:param x_tens: the tensor to apply the... | Create a depthwise convolution op and supporting ops (batch norm, activation, etc) in the current graph and scope. :param name: The name to group all ops under in the graph :param x_tens: The input tensor to apply a convolution and supporting ops to :param training: A bool or tensor to indicate if the net is being run ... |
21,497 | from typing import Tuple, Union
from sparseml.tensorflow_v1.utils import tf_compat
BN_MOMENTUM = 0.9
BN_EPSILON = 1e-5
def activation(x_tens: tf_compat.Tensor, act: Union[None, str], name: str = "act"):
"""
Create an activation operation in the current graph and scope.
:param x_tens: the tensor to apply the... | Create a dense or fully connected op and supporting ops (batch norm, activation, etc) in the current graph and scope. :param name: The name to group all ops under in the graph :param x_tens: The input tensor to apply a fully connected and supporting ops to :param training: A bool or tensor to indicate if the net is bei... |
21,498 | from typing import Tuple, Union
from sparseml.tensorflow_v1.utils import tf_compat
def activation(x_tens: tf_compat.Tensor, act: Union[None, str], name: str = "act"):
"""
Create an activation operation in the current graph and scope.
:param x_tens: the tensor to apply the op to
:param act: the activatio... | Create a fully connected layer with the proper ops and variables. :param name: the name scope to create the layer under :param x_tens: the tensor to apply the layer to :param in_chan: the number of input channels :param out_chan: the number of output channels :param act: an activation type to add into the layer, suppor... |
21,499 | import functools
import os
from typing import Optional
from sparseml.base import check_version
_TENSORFLOW_MIN_VERSION = "1.8.0"
_TENSORFLOW_MAX_VERSION = "1.16.0"
def check_tensorflow_install(
min_version: Optional[str] = _TENSORFLOW_MIN_VERSION,
max_version: Optional[str] = _TENSORFLOW_MAX_VERSION,
raise_... | Decorator function to require use of tensorflow. Will check that tensorflow 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_tensorflow_install` for more info. :param min_version: The minimum version for tensorflow t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.