code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def smooth_downscale_param(param: nn.Parameter, scale: torch.Tensor, channels_dim: int = 0) -> None:
"""In-place smooth the parameter by downscaling.
Args:
param (`nn.Parameter`):
The parameter to smooth.
scale (`torch.Tensor`):
The scale to downscale.
channels_d... | In-place smooth the parameter by downscaling.
Args:
param (`nn.Parameter`):
The parameter to smooth.
scale (`torch.Tensor`):
The scale to downscale.
channels_dim (`int`, *optional*, defaults to `0`):
The dimension of channels.
| smooth_downscale_param | python | mit-han-lab/deepcompressor | deepcompressor/calib/smooth.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py | Apache-2.0 |
def convert_smooth_upscale_to_downscale(
scale: torch.Tensor, num_heads: int = 1, num_head_repeats: int = 1
) -> torch.Tensor:
"""Convert the upscale smooth scale to downscale smooth scale.
Args:
scale (`torch.Tensor`):
The upscale smooth scale.
num_heads (`int`, *optional*, def... | Convert the upscale smooth scale to downscale smooth scale.
Args:
scale (`torch.Tensor`):
The upscale smooth scale.
num_heads (`int`, *optional*, defaults to `1`):
The number of heads.
num_head_repeats (`int`, *optional*, defaults to `1`):
The number of h... | convert_smooth_upscale_to_downscale | python | mit-han-lab/deepcompressor | deepcompressor/calib/smooth.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py | Apache-2.0 |
def smooth_linear_modules(
prevs: nn.Module | tp.Sequence[nn.Module] | None,
modules: tp.Sequence[nn.Linear] | nn.Linear,
*,
scale: torch.Tensor | None,
config: SmoothCalibConfig | None = None,
weight_quantizer: Quantizer | None = None,
input_quantizer: Quantizer | None = None,
weights: ... | Smooth two consecutive modules.
Args:
prevs (`nn.Module` or `list[nn.Module]`):
The first module(s).
modules (`nn.Linear` or `list[nn.Linear]`):
The second module(s).
scale (`torch.Tensor` or `None`, *optional*, defaults to `None`):
The smooth quantizatio... | smooth_linear_modules | python | mit-han-lab/deepcompressor | deepcompressor/calib/smooth.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py | Apache-2.0 |
def smooth_attention(
*,
q_proj: nn.Linear,
k_proj: nn.Linear,
scale: torch.Tensor | None,
config: SmoothCalibConfig | None = None,
query_quantizer: Quantizer | None = None,
key_quantizer: Quantizer | None = None,
queries: TensorsCache | None = None,
keys: TensorsCache | None = None,... | Smooth attention.
Args:
q_proj (`nn.Linear`):
The query projection module.
k_proj (`nn.Linear`):
The key projection module.
scale (`torch.Tensor` or `None`, *optional*, defaults to `None`):
The smooth quantization scale.
config (`SmoothCalibConfig... | smooth_attention | python | mit-han-lab/deepcompressor | deepcompressor/calib/smooth.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py | Apache-2.0 |
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]:
"""Generate the directory names of the configuration.
Returns:
list[str]: The directory names.
"""
names = super().generate_dirnames(**kwargs)
name = f"i{num2str(self.num_iters)}.r{num2str(self.... | Generate the directory names of the configuration.
Returns:
list[str]: The directory names.
| generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/lowrank.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/lowrank.py | Apache-2.0 |
def get_linear_ratios(self) -> list[float]:
"""Get the ratios for linear range search.
Returns:
`list[float]`:
The dynamic range ratio candidates for linear range search.
"""
num_grids, max_shrink, max_expand = self.num_grids, self.max_shrink, self.max_expand... | Get the ratios for linear range search.
Returns:
`list[float]`:
The dynamic range ratio candidates for linear range search.
| get_linear_ratios | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/range.py | Apache-2.0 |
def get_ratios(self) -> list[list[float]]:
"""Get the ratios for linear range search.
Returns:
`list[list[float]]`:
The dynamic range ratio candidates for linear range search.
"""
if self.strategy == SearchBasedCalibStrategy.Manual:
return [[self.... | Get the ratios for linear range search.
Returns:
`list[list[float]]`:
The dynamic range ratio candidates for linear range search.
| get_ratios | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/range.py | Apache-2.0 |
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]:
"""Generate the directory names of the configuration.
Args:
prefix (`str`, *optional*, default=`""`):
The prefix of the directory.
Returns:
`list[str]`:
The director... | Generate the directory names of the configuration.
Args:
prefix (`str`, *optional*, default=`""`):
The prefix of the directory.
Returns:
`list[str]`:
The directory names.
| generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/range.py | Apache-2.0 |
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]:
"""Get the directory names of the rotation quantization configuration.
Returns:
list[str]: The directory names of the rotation quantization configuration.
"""
name = self.name
if self.transforms... | Get the directory names of the rotation quantization configuration.
Returns:
list[str]: The directory names of the rotation quantization configuration.
| generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/rotation.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/rotation.py | Apache-2.0 |
def update_get_arguments(
cls: type["QuantRotationConfig"],
*,
overwrites: dict[str, tp.Callable[[omniconfig.Arguments], None] | None] | None = None,
defaults: dict[str, tp.Any] | None = None,
) -> tuple[dict[str, tp.Callable[[omniconfig.Arguments], None] | None], dict[str, tp.Any]]:... | Get the arguments for the rotation quantization configuration. | update_get_arguments | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/rotation.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/rotation.py | Apache-2.0 |
def update_from_dict(
cls: type["QuantRotationConfig"], *, parsed_args: dict[str, tp.Any], overwrites: dict[str, tp.Any]
) -> tuple[dict[str, tp.Any], dict[str, tp.Any]]:
"""Create a rotation quantization configuration from the parsed arguments."""
parsed_args.setdefault("transforms", []).ex... | Create a rotation quantization configuration from the parsed arguments. | update_from_dict | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/rotation.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/rotation.py | Apache-2.0 |
def get_alpha_beta_pairs(self) -> list[tuple[float, float]]: # noqa: C901
"""Get the alpha and beta pairs for smooth quantization.
Returns:
`list[tuple[float, float]]`:
The alpha and beta pair candidates.
"""
if self.strategy == SearchBasedCalibStrategy.Manu... | Get the alpha and beta pairs for smooth quantization.
Returns:
`list[tuple[float, float]]`:
The alpha and beta pair candidates.
| get_alpha_beta_pairs | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/smooth.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/smooth.py | Apache-2.0 |
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]:
"""Get the directory names of the smooth quantization configuration.
Args:
prefix (`str`, *optional*, default=`""`):
The prefix of the directory.
Returns:
`list[str]`:
... | Get the directory names of the smooth quantization configuration.
Args:
prefix (`str`, *optional*, default=`""`):
The prefix of the directory.
Returns:
`list[str]`:
The directory names of the configuration.
| generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/smooth.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/smooth.py | Apache-2.0 |
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]:
"""Get the names of the smooth quantization configuration.
Args:
prefix (`str`, *optional*, default=`""`):
The prefix of the directory.
Returns:
`list[str]`:
The nam... | Get the names of the smooth quantization configuration.
Args:
prefix (`str`, *optional*, default=`""`):
The prefix of the directory.
Returns:
`list[str]`:
The names of the smooth quantization configuration
| generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/calib/config/smooth.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/config/smooth.py | Apache-2.0 |
def to(self, device: torch.device | str) -> "ModuleForwardInput":
"""Move input to device.
Args:
device (`torch.device` or `str`):
Device.
Returns:
`ModuleForwardInput`:
Module forward input.
"""
return ModuleForwardInput(... | Move input to device.
Args:
device (`torch.device` or `str`):
Device.
Returns:
`ModuleForwardInput`:
Module forward input.
| to | python | mit-han-lab/deepcompressor | deepcompressor/data/cache.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/cache.py | Apache-2.0 |
def update(self, x: dict[str | int, tp.Any] | None = None) -> "ModuleForwardInput":
"""Return a new ModuleForwardInput with updated values.
Args:
x (`dict[str | int, tp.Any]` or `None`, *optional*, defaults to `None`):
Values to update.
Returns:
`ModuleF... | Return a new ModuleForwardInput with updated values.
Args:
x (`dict[str | int, tp.Any]` or `None`, *optional*, defaults to `None`):
Values to update.
Returns:
`ModuleForwardInput`:
Module forward input.
| update | python | mit-han-lab/deepcompressor | deepcompressor/data/cache.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/cache.py | Apache-2.0 |
def get_standardized_data(self, reshape: bool = False) -> list[torch.Tensor]:
"""Get standardized data, i.e., flatten dimensions before `channels_dim`.
Args:
reshape (`bool`, *optional*, defaults to `False`):
Whether to apply reshape function.
Returns:
`... | Get standardized data, i.e., flatten dimensions before `channels_dim`.
Args:
reshape (`bool`, *optional*, defaults to `False`):
Whether to apply reshape function.
Returns:
`list[torch.Tensor]`:
Standardized data.
| get_standardized_data | python | mit-han-lab/deepcompressor | deepcompressor/data/cache.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/cache.py | Apache-2.0 |
def repartition(self, max_batch_size: int, max_size: int, standardize: bool, reshape: bool) -> "TensorCache":
"""Relocate data based on the maximum batch size and size.
Args:
max_batch_size (`int`):
Maximum batch size.
max_size (`int`):
Maximum si... | Relocate data based on the maximum batch size and size.
Args:
max_batch_size (`int`):
Maximum batch size.
max_size (`int`):
Maximum size.
standardize (`bool`):
Whether to standardize data, i.e., flatten dimensions before `chann... | repartition | python | mit-han-lab/deepcompressor | deepcompressor/data/cache.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/cache.py | Apache-2.0 |
def extract(self, index: int, kwargs: dict[str, tp.Any]) -> ModuleForwardInput:
"""Extract data for binding to module forward.
Args:
index (`int`):
Index.
kwargs (`dict[str, tp.Any]`):
Keyword arguments.
Returns:
`ModuleForwar... | Extract data for binding to module forward.
Args:
index (`int`):
Index.
kwargs (`dict[str, tp.Any]`):
Keyword arguments.
Returns:
`ModuleForwardInput`:
Module forward input.
| extract | python | mit-han-lab/deepcompressor | deepcompressor/data/cache.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/cache.py | Apache-2.0 |
def round(self, tensor: torch.Tensor) -> torch.Tensor:
"""Round the tensor to the nearest value in the codebook.
Args:
tensor (`torch.Tensor`):
A tensor to round.
Returns:
`torch.Tensor`:
A rounded tensor.
"""
dtype = tens... | Round the tensor to the nearest value in the codebook.
Args:
tensor (`torch.Tensor`):
A tensor to round.
Returns:
`torch.Tensor`:
A rounded tensor.
| round | python | mit-han-lab/deepcompressor | deepcompressor/data/codebook.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/codebook.py | Apache-2.0 |
def to(self, *, device: torch.device | None = None, dtype: torch.dtype | None = None) -> "Codebook":
"""Move the codebook to the specified device and dtype.
Args:
device (`torch.device`):
Device to move the codebook.
dtype (`torch.dtype`):
Dtype t... | Move the codebook to the specified device and dtype.
Args:
device (`torch.device`):
Device to move the codebook.
dtype (`torch.dtype`):
Dtype to move the codebook.
Returns:
`Codebook`:
A codebook.
| to | python | mit-han-lab/deepcompressor | deepcompressor/data/codebook.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/codebook.py | Apache-2.0 |
def construct(
maps: list[tuple[float, int]],
*,
bits: int,
device: torch.device | str = "cpu",
dtype: torch.dtype = torch.float32,
) -> "Codebook":
"""Create a map of values to a code of `code_bits` bits.
Args:
maps (`list[tuple[float, int]]`):
... | Create a map of values to a code of `code_bits` bits.
Args:
maps (`list[tuple[float, int]]`):
A list of tuples of (value, binary code).
bits (`int`):
Number of bits for the binary code.
device (`torch.device` or str, *optional*, defaults to `"... | construct | python | mit-han-lab/deepcompressor | deepcompressor/data/codebook.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/codebook.py | Apache-2.0 |
def build_for_float_point(
*,
total_bits: int,
exponent_bits: int,
signed: bool = True,
has_subnormal: bool = True,
has_inf: bool = False,
has_nan: bool = False,
device: torch.device | str = "cpu",
dtype: torch.dtype = torch.float32,
) -> "Code... | Create a map of floating point values to a code of `code_bits` bits.
Args:
total_bits (`int`):
Number of bits for the floating point value.
exponent_bits (`int`):
Number of bits for the exponent.
signed (`bool`, *optional*, defaults to `True`)... | build_for_float_point | python | mit-han-lab/deepcompressor | deepcompressor/data/codebook.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/codebook.py | Apache-2.0 |
def build_for_integer(
*,
total_bits: int,
signed: bool = True,
magnitude: bool = False,
device: torch.device | str = "cpu",
dtype: torch.dtype = torch.float32,
) -> "Codebook":
"""Create a map of integer values to a code of `code_bits` bits.
Args:
... | Create a map of integer values to a code of `code_bits` bits.
Args:
total_bits (`int`):
Number of bits for the integer value.
signed (`bool`, *optional*, defaults to `True`):
Whether to use signed code.
magnitude (`bool`, *optional*, defaults ... | build_for_integer | python | mit-han-lab/deepcompressor | deepcompressor/data/codebook.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/codebook.py | Apache-2.0 |
def __init__(
self,
total_bits: int,
*,
signed: bool = True,
exponent_bits: int = 0,
has_subnormal: bool = True,
has_nan: bool = False,
has_inf: bool = False,
magnitude: bool = False,
codebook: Codebook | None = None,
codebook_name:... | Initialize the quantization data type.
Args:
total_bits (`int`):
Total number of bits. Must be greater than 0.
signed (`bool`, *optional*, defaults to `True`):
Whether the data type is signed.
exponent_bits (`int`, *optional*, defaults to `0`)... | __init__ | python | mit-han-lab/deepcompressor | deepcompressor/data/dtype.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/dtype.py | Apache-2.0 |
def get_codebook(self, *, device: torch.device | str = "cpu", dtype: torch.dtype = torch.float32) -> Codebook:
"""Get a get_codebook of `code_bits` bits for the quantization.
Args:
device (`torch.device` or `str`, *optional*, defaults to `"cpu"`):
Device to create the codebo... | Get a get_codebook of `code_bits` bits for the quantization.
Args:
device (`torch.device` or `str`, *optional*, defaults to `"cpu"`):
Device to create the codebook on.
dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
Data type to create the... | get_codebook | python | mit-han-lab/deepcompressor | deepcompressor/data/dtype.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/dtype.py | Apache-2.0 |
def round(self, tensor: torch.Tensor) -> torch.Tensor:
"""Round the tensor to the nearest quantized value.
Args:
tensor (`torch.Tensor`):
Tensor to round.
Returns:
`torch.Tensor`:
Rounded tensor.
"""
if self.is_integer:
... | Round the tensor to the nearest quantized value.
Args:
tensor (`torch.Tensor`):
Tensor to round.
Returns:
`torch.Tensor`:
Rounded tensor.
| round | python | mit-han-lab/deepcompressor | deepcompressor/data/dtype.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/dtype.py | Apache-2.0 |
def log2(self) -> "LogQuantRange":
"""Return the log-scale of the current quantization range."""
log2_abs_min = int(math.log2(min(abs(self.min or 0), abs(self.max or 0))))
return LogQuantRange(
min=None,
max=None if self.max is None else log2_abs_min,
) | Return the log-scale of the current quantization range. | log2 | python | mit-han-lab/deepcompressor | deepcompressor/data/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/range.py | Apache-2.0 |
def intersect(self, quant_dtype: QuantDataType, *, has_zero_point: bool) -> "QuantRange":
"""Return the intersection of the current quantization range and the given data type.
Args:
quant_dtype (`QuantDataType`):
The quantization data type.
has_zero_point (`bool`... | Return the intersection of the current quantization range and the given data type.
Args:
quant_dtype (`QuantDataType`):
The quantization data type.
has_zero_point (`bool`):
Whether the quantization range has zero-point.
Returns:
`Quan... | intersect | python | mit-han-lab/deepcompressor | deepcompressor/data/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/range.py | Apache-2.0 |
def construct(
dtype: QuantDataType, *, has_zero_point: bool, quant_range: tp.Optional["QuantRange"] = None
) -> "QuantRange":
"""Return the intersection of the given quantization range and the given data type.
Args:
dtype (`QuantDataType`):
The quantization data... | Return the intersection of the given quantization range and the given data type.
Args:
dtype (`QuantDataType`):
The quantization data type.
has_zero_point (`bool`):
Whether the quantization range has zero-point.
quant_range (`QuantRange` or `N... | construct | python | mit-han-lab/deepcompressor | deepcompressor/data/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/range.py | Apache-2.0 |
def intersect_log2(self, quant_dtype: QuantDataType) -> "LogQuantRange":
"""Return the intersection of the current quantization range and the given data type in log2 space.
Args:
quant_dtype (`QuantDataType`):
The quantization data type.
Returns:
`LogQua... | Return the intersection of the current quantization range and the given data type in log2 space.
Args:
quant_dtype (`QuantDataType`):
The quantization data type.
Returns:
`LogQuantRange`:
The intersection of the current quantization range and the... | intersect_log2 | python | mit-han-lab/deepcompressor | deepcompressor/data/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/range.py | Apache-2.0 |
def construct(
dtype: QuantDataType, quant_range: tp.Optional[tp.Union["LogQuantRange", QuantRange]] = None
) -> "LogQuantRange":
"""Return the intersection of the given quantization range and the given data type in log2 space.
Args:
dtype (`QuantDataType`):
The ... | Return the intersection of the given quantization range and the given data type in log2 space.
Args:
dtype (`QuantDataType`):
The quantization data type.
quant_range (`LogQuantRange` or `QuantRange` or `None`, *optional*, defaults to `None`):
The extra qu... | construct | python | mit-han-lab/deepcompressor | deepcompressor/data/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/range.py | Apache-2.0 |
def construct(
outer_dtype: QuantDataType,
inner_dtype: QuantDataType,
zero_domain: ZeroPointDomain | None,
inner_quant_range: QuantRange | None = None,
) -> QuantRange:
"""Return the protective quantization range.
Args:
outer_dtype (`QuantDataType`):
... | Return the protective quantization range.
Args:
outer_dtype (`QuantDataType`):
The data type of the outer level in the quantization hierarchy.
inner_dtype (`QuantDataType`):
The data type of the inner level in the quantization hierarchy.
zero_... | construct | python | mit-han-lab/deepcompressor | deepcompressor/data/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/range.py | Apache-2.0 |
def intersect(self, range_bound: RangeBound | None) -> "DynamicRange":
"""Return the intersection of the current dynamic range and the given range bound.
Args:
range_bound (`RangeBound` or `None`):
The range bound.
Returns:
`DynamicRange`:
... | Return the intersection of the current dynamic range and the given range bound.
Args:
range_bound (`RangeBound` or `None`):
The range bound.
Returns:
`DynamicRange`:
The intersection of the current dynamic range and the given range bound.
... | intersect | python | mit-han-lab/deepcompressor | deepcompressor/data/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/range.py | Apache-2.0 |
def measure( # noqa: C901
self,
tensors: torch.Tensor | list[torch.Tensor],
/,
*,
zero_domain: ZeroPointDomain | None,
is_float_point: bool,
) -> "DynamicRange":
"""Return a dynamic range of the given tensor.
Args:
tensors (`torch.Tensor`... | Return a dynamic range of the given tensor.
Args:
tensors (`torch.Tensor` or `list[torch.Tensor]`):
The tensor in the shape of (#g0, gs0, #g1, gs1, ..., #gn, gsn).
zero_domain (`ZeroPointDomain` or `None`):
The zero-point domain.
is_float_poin... | measure | python | mit-han-lab/deepcompressor | deepcompressor/data/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/range.py | Apache-2.0 |
def scale(
self, ratio: float | torch.Tensor, zero_domain: ZeroPointDomain | None, is_float_point: bool
) -> "DynamicRange":
"""Return new dynamic range by scaling the current range.
Args:
ratio (`float` or `torch.Tensor`):
The scaling ratio.
zero_dom... | Return new dynamic range by scaling the current range.
Args:
ratio (`float` or `torch.Tensor`):
The scaling ratio.
zero_domain (`ZeroPointDomain` or `None`):
The zero-point domain.
is_float_point (`bool`):
Whether the data type... | scale | python | mit-han-lab/deepcompressor | deepcompressor/data/range.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/range.py | Apache-2.0 |
def _join_scale_tensor(global_scale: torch.Tensor | None, local_scale: torch.Tensor) -> torch.Tensor:
"""Multiply the local scale tensor by the global scale tensor.
Args:
global_scale (`torch.Tensor` or `None`):
Global scale tensor.
local_scale (`torch.Tensor`):
Local sc... | Multiply the local scale tensor by the global scale tensor.
Args:
global_scale (`torch.Tensor` or `None`):
Global scale tensor.
local_scale (`torch.Tensor`):
Local scale tensor.
Returns:
`torch.Tensor`:
The compounded scale tensor.
| _join_scale_tensor | python | mit-han-lab/deepcompressor | deepcompressor/data/scale.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/scale.py | Apache-2.0 |
def infer_dtype_bits(dtype: torch.dtype | QuantDataType) -> int:
"""Get the number of bits of a torch.dtype or QuantDataType.
Args:
dtype (`torch.dtype` or `QuantDataType`):
The dtype to get the number of bits of.
Returns:
`int`:
The number of bits.
"""
if i... | Get the number of bits of a torch.dtype or QuantDataType.
Args:
dtype (`torch.dtype` or `QuantDataType`):
The dtype to get the number of bits of.
Returns:
`int`:
The number of bits.
| infer_dtype_bits | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/dtype.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/dtype.py | Apache-2.0 |
def infer_dtype_name(dtype: torch.dtype | QuantDataType) -> str:
"""Get the string representation of a torch.dtype or QuantDataType.
Args:
dtype (`torch.dtype` | `QuantDataType`):
The dtype to get the string representation of.
Returns:
`str`:
The string representati... | Get the string representation of a torch.dtype or QuantDataType.
Args:
dtype (`torch.dtype` | `QuantDataType`):
The dtype to get the string representation of.
Returns:
`str`:
The string representation.
| infer_dtype_name | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/dtype.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/dtype.py | Apache-2.0 |
def __init__(
self, kernel_size: tuple[int, ...], padding: tuple[int, ...], stride: tuple[int, ...], dilation: tuple[int, ...]
) -> None:
"""Initialize the reshape function.
Args:
kernel_size (`tuple[int, ...]`):
Kernel size.
padding (`tuple[int, ...]... | Initialize the reshape function.
Args:
kernel_size (`tuple[int, ...]`):
Kernel size.
padding (`tuple[int, ...]`):
Padding.
stride (`tuple[int, ...]`):
Stride.
dilation (`tuple[int, ...]`):
Dilation.
... | __init__ | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/reshape.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/reshape.py | Apache-2.0 |
def __call__(self, x: torch.Tensor, /, ic_last: bool = True) -> torch.Tensor:
"""Reshape input tensor to the desired 2D shape used for GEMM.
Args:
x (`torch.Tensor`):
Input tensor.
ic_last (`bool`, *optional*, defaults to `True`):
Whether input ch... | Reshape input tensor to the desired 2D shape used for GEMM.
Args:
x (`torch.Tensor`):
Input tensor.
ic_last (`bool`, *optional*, defaults to `True`):
Whether input channel is the last dimension.
Returns:
`torch.Tensor`:
... | __call__ | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/reshape.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/reshape.py | Apache-2.0 |
def __call__(self, x: torch.Tensor, /, ic_last: bool = True) -> torch.Tensor:
"""Reshape output tensor to the desired shape.
Args:
x (`torch.Tensor`):
Input tensor.
ic_last (`bool`, *optional*, defaults to `True`):
Whether input channel is the las... | Reshape output tensor to the desired shape.
Args:
x (`torch.Tensor`):
Input tensor.
ic_last (`bool`, *optional*, defaults to `True`):
Whether input channel is the last dimension.
Returns:
`torch.Tensor`:
Reshaped tenso... | __call__ | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/reshape.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/reshape.py | Apache-2.0 |
def infer_scale_dtypes(
scale_dtypes: tp.Sequence[torch.dtype | QuantDataType | None], default_dtype: torch.dtype | QuantDataType
) -> list[torch.dtype | QuantDataType]:
"""Get the scale dtypes for the given tensor dtype.
Args:
scale_dtypes (`Sequence[torch.dtype | QuantDataType | None]`):
... | Get the scale dtypes for the given tensor dtype.
Args:
scale_dtypes (`Sequence[torch.dtype | QuantDataType | None]`):
The scale dtypes.
default_dtype (`torch.dtype`):
The default scale dtype.
Returns:
`list[torch.dtype | QuantDataType]`:
The scale dt... | infer_scale_dtypes | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/scale.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/scale.py | Apache-2.0 |
def infer_exponent_scale_level(scale_dtypes: tp.Sequence[torch.dtype | QuantDataType]) -> int:
"""Get the exponent scaling level.
Args:
scale_dtypes (`Sequence[torch.dtype | QuantDataType]`):
The scale data types.
Returns:
`int`: The exponent scaling level.
"""
for leve... | Get the exponent scaling level.
Args:
scale_dtypes (`Sequence[torch.dtype | QuantDataType]`):
The scale data types.
Returns:
`int`: The exponent scaling level.
| infer_exponent_scale_level | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/scale.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/scale.py | Apache-2.0 |
def infer_group_shape_name(group_shape: tp.Sequence[int]) -> str:
"""Get the name of the group shape.
Args:
group_shape (`Sequence[int]`):
The group shape.
Returns:
`str`:
The name of the group shape.
"""
if all(gs <= 0 for gs in group_shape[2:]):
if... | Get the name of the group shape.
Args:
group_shape (`Sequence[int]`):
The group shape.
Returns:
`str`:
The name of the group shape.
| infer_group_shape_name | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/shape.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/shape.py | Apache-2.0 |
def format_group_configs(
*,
group_shapes: tp.Sequence[tp.Sequence[int]],
scale_dtypes: tp.Sequence[torch.dtype | QuantDataType | None] | torch.dtype | QuantDataType | None,
) -> tuple[tuple[tuple[int, ...], ...], tuple[torch.dtype | QuantDataType | None, ...]]:
"""Format the group shape and scale dtype... | Format the group shape and scale dtype.
Args:
group_shapes (`Sequence[tp.Sequence[int]]`):
The group shapes.
scale_dtypes (`Sequence[torch.dtype | QuantDataType | None]` or `torch.dtype` or `QuantDataType` or `None`):
The scale dtypes.
Returns:
`tuple[tuple[tupl... | format_group_configs | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/shape.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/shape.py | Apache-2.0 |
def infer_group_shapes(group_shapes: tuple[tuple[int, ...], ...], shape: torch.Size) -> list[torch.Size]:
"""Infer the group shapes using group shape config on the given tensor shape.
Args:
group_shapes (`tuple[tuple[int, ...], ...]`):
The group shapes.
shape (`torch.Size`):
... | Infer the group shapes using group shape config on the given tensor shape.
Args:
group_shapes (`tuple[tuple[int, ...], ...]`):
The group shapes.
shape (`torch.Size`):
The shape of the tensor.
Returns:
`list[torch.Size]`:
The inferred group shapes.
... | infer_group_shapes | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/shape.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/shape.py | Apache-2.0 |
def infer_view_shape(
tensor_shape: torch.Size,
/,
group_shape: tp.Sequence[int],
skip_first_dim: bool = False,
) -> torch.Size:
"""Infer the view shape from the tensor shape and the group shape.
Args:
tensor_shape (`torch.Size`):
The tensor shape.
group_shape (`Sequ... | Infer the view shape from the tensor shape and the group shape.
Args:
tensor_shape (`torch.Size`):
The tensor shape.
group_shape (`Sequence[int]`):
The group shape.
skip_first_dim (`bool`, *optional*, defaults to `False`):
Whether to skip the first dimens... | infer_view_shape | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/shape.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/shape.py | Apache-2.0 |
def infer_scale_view_shapes(
group_shapes: tp.Sequence[tp.Sequence[int]] | tp.Sequence[torch.Size], shape: torch.Size
) -> list[torch.Size]:
"""Infer the view shapes of quantization scale for the given tensor shape.
Args:
group_shapes (`Sequence[tp.Sequence[int]]` or `list[torch.Size]`):
... | Infer the view shapes of quantization scale for the given tensor shape.
Args:
group_shapes (`Sequence[tp.Sequence[int]]` or `list[torch.Size]`):
The group shapes.
shape (`torch.Size`):
The shape of the tensor to be quantized.
Returns:
`list[torch.Size]`:
... | infer_scale_view_shapes | python | mit-han-lab/deepcompressor | deepcompressor/data/utils/shape.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/data/utils/shape.py | Apache-2.0 |
def __init__(
self, name: str, module: nn.Module, action: "CacheAction", cache: TensorsCache, info_mode: bool, is_output: bool
):
"""Initialize the hook.
Args:
name (``str``):
Module name.
module (``nn.Module``):
Module.
ac... | Initialize the hook.
Args:
name (``str``):
Module name.
module (``nn.Module``):
Module.
action (``CacheAction``):
Cache action.
cache (``TensorsCache``):
Cache.
info_mode (``bool``):
... | __init__ | python | mit-han-lab/deepcompressor | deepcompressor/dataset/action.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/action.py | Apache-2.0 |
def apply(
self,
name: str,
module: nn.Module,
tensors: dict[int | str, torch.Tensor],
cache: TensorsCache,
) -> None:
"""Cache activations.
Args:
name (`str`):
Module name.
module (`nn.Module`):
Module.... | Cache activations.
Args:
name (`str`):
Module name.
module (`nn.Module`):
Module.
tensors (`dict[int or str, torch.Tensor]`):
Tensors to cache.
cache (`TensorsCache`):
Cache.
| apply | python | mit-han-lab/deepcompressor | deepcompressor/dataset/action.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/action.py | Apache-2.0 |
def info(
self,
name: str,
module: nn.Module,
tensors: dict[int | str, torch.Tensor],
cache: TensorsCache,
) -> None:
"""Update cache information.
Args:
name (`str`):
Module name.
module (`nn.Module`):
M... | Update cache information.
Args:
name (`str`):
Module name.
module (`nn.Module`):
Module.
tensors (`dict[int or str, torch.Tensor]`):
Tensors to cache.
cache (`TensorsCache`):
Cache.
| info | python | mit-han-lab/deepcompressor | deepcompressor/dataset/action.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/action.py | Apache-2.0 |
def register(
self,
name: str,
module: nn.Module,
cache: IOTensorsCache,
info_mode: bool,
needs_inputs: bool,
needs_outputs: bool,
) -> list[Hook]:
"""Register hooks for caching activations.
Args:
name (`str`):
Modu... | Register hooks for caching activations.
Args:
name (`str`):
Module name.
module (`nn.Module`):
Module.
cache (`IOTensorsCache`):
Cache.
info_mode (`bool`):
Whether to update cache information.
... | register | python | mit-han-lab/deepcompressor | deepcompressor/dataset/action.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/action.py | Apache-2.0 |
def apply(
self,
name: str,
module: nn.Module,
tensors: dict[int | str, torch.Tensor],
cache: TensorsCache,
) -> None:
"""Concatenate cached activations along the sample dimension.
Args:
name (`str`):
Module name.
modul... | Concatenate cached activations along the sample dimension.
Args:
name (`str`):
Module name.
module (`nn.Module`):
Module.
tensors (`dict[int or str, torch.Tensor]`):
Tensors to cache.
cache (`TensorsCache`):
... | apply | python | mit-han-lab/deepcompressor | deepcompressor/dataset/action.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/action.py | Apache-2.0 |
def __init__(self, dataset: torch.utils.data.Dataset, batch_size: int):
"""Initialize the dataset.
Args:
dataset (`torch.utils.data.Dataset`):
Calibration dataset.
batch_size (`int`):
Batch size.
"""
self.dataset = dataset
... | Initialize the dataset.
Args:
dataset (`torch.utils.data.Dataset`):
Calibration dataset.
batch_size (`int`):
Batch size.
| __init__ | python | mit-han-lab/deepcompressor | deepcompressor/dataset/cache.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/cache.py | Apache-2.0 |
def _init_cache(self, name: str, module: nn.Module) -> IOTensorsCache:
"""Initialize activation cache.
Args:
name (`str`):
Module name.
module (`nn.Module`):
Module.
Returns:
`IOTensorsCache`:
Tensors cache for... | Initialize activation cache.
Args:
name (`str`):
Module name.
module (`nn.Module`):
Module.
Returns:
`IOTensorsCache`:
Tensors cache for inputs and outputs.
| _init_cache | python | mit-han-lab/deepcompressor | deepcompressor/dataset/cache.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/cache.py | Apache-2.0 |
def _iter_layer_activations( # noqa: C901
self,
model: nn.Module,
*args,
action: CacheAction,
layers: tp.Sequence[nn.Module] | None = None,
needs_inputs_fn: tp.Callable[[str, nn.Module], bool] | bool | None = True,
needs_outputs_fn: tp.Callable[[str, nn.Module], ... | Iterate over model activations in layers.
Args:
model (`nn.Module`):
Model.
action (`CacheAction`):
Action for caching activations.
layers (`Sequence[nn.Module]` or `None`, *optional*, defaults to `None`):
Layers to cache activ... | _iter_layer_activations | python | mit-han-lab/deepcompressor | deepcompressor/dataset/cache.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/cache.py | Apache-2.0 |
def iter_layer_activations( # noqa: C901
self,
model: nn.Module,
*args,
action: CacheAction,
needs_inputs_fn: tp.Callable[[str, nn.Module], bool] | bool | None = True,
needs_outputs_fn: tp.Callable[[str, nn.Module], bool] | bool | None = None,
**kwargs,
) -> ... | Iterate over model activations in layers.
Args:
model (`nn.Module`):
Model.
action (`CacheAction`):
Action for caching activations.
needs_inputs_fn (`Callable[[str, nn.Module], bool]` or `bool` or `None`, *optional*, defaults to `True`):
... | iter_layer_activations | python | mit-han-lab/deepcompressor | deepcompressor/dataset/cache.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/cache.py | Apache-2.0 |
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]:
"""Get the names of the configuration fields.
Args:
prefix (`str`, *optional*):
Prefix for the names.
Returns:
`list[str]`:
Names of the configuration.
"""
... | Get the names of the configuration fields.
Args:
prefix (`str`, *optional*):
Prefix for the names.
Returns:
`list[str]`:
Names of the configuration.
| generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/dataset/config.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/dataset/config.py | Apache-2.0 |
def as_hook(
self,
input_packager: BaseInputPackager | None = None,
output_packager: BaseOutputPackager | None = None,
) -> AccumBranchHook:
"""Wrap the module as a branch hook.
Args:
input_packager (`BaseInputPackager` or `None`, *optional*, defaults to `None`):... | Wrap the module as a branch hook.
Args:
input_packager (`BaseInputPackager` or `None`, *optional*, defaults to `None`):
Input packager.
output_packager (`BaseOutputPackager` or `None`, *optional*, defaults to `None`):
Output packager.
Returns:
... | as_hook | python | mit-han-lab/deepcompressor | deepcompressor/nn/patch/lowrank.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/nn/patch/lowrank.py | Apache-2.0 |
def register_factory(
cls,
module_types: type[nn.Module] | tuple[type[nn.Module], ...],
/,
factory: tp.Callable[[nn.Module, tp.Optional["BaseModuleStruct"], str, str, str, int], tp.Self],
*,
overwrite: bool = False,
) -> None:
"""Register a factory that constr... | Register a factory that constructs a module struct from a module.
Args:
module_types (`type[nn.Module]` or `tuple[type[nn.Module], ...]`):
The module type(s).
factory (`Callable[[nn.Module, BaseModuleStruct, str, str, str, int], BaseModuleStruct]`):
The f... | register_factory | python | mit-han-lab/deepcompressor | deepcompressor/nn/struct/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/nn/struct/base.py | Apache-2.0 |
def construct(
cls,
module: nn.Module,
/,
parent: tp.Optional["BaseModuleStruct"] = None,
fname: str = "",
rname: str = "",
rkey: str = "",
idx: int = 0,
**kwargs,
) -> tp.Self:
"""Construct a module struct from a module.
Args:... | Construct a module struct from a module.
Args:
module (`nn.Module`):
The module instance.
parent (`BaseModuleStruct` or `None`, *optional*, defaults to `None):
The parent module struct that contains this module struct.
rname (`str`, *optional*... | construct | python | mit-han-lab/deepcompressor | deepcompressor/nn/struct/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/nn/struct/base.py | Apache-2.0 |
def quantize(
self,
tensor: torch.Tensor,
/,
*,
return_with_dequant: bool = True,
return_with_quant: bool = False,
kernel: (
BaseKeyEnableQuantKernelConfig | BaseQuantKernelConfig | BaseQuantKernel | None | _MISSING_TYPE
) = MISSING,
ch... | Quantize a tensor.
Args:
tensor (`torch.Tensor`):
The tensor to quantize.
return_with_dequant (`bool`, *optional*, defaults to `True`):
Whether to return the dequantized tensor.
return_with_quant (`bool`, *optional*, defaults to `False`):
... | quantize | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/processor.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/processor.py | Apache-2.0 |
def update(
self,
tensor_shape: torch.Size,
default_dtype: torch.dtype | _MISSING_TYPE = MISSING,
quant_range: QuantRange | None | _MISSING_TYPE = MISSING,
range_bound: RangeBound | None | _MISSING_TYPE = MISSING,
) -> QuantInfo | None:
"""Update the quantization info... | Update the quantization information.
Args:
tensor_shape (`torch.Size`):
The shape of the tensor.
default_dtype (`torch.dtype` or `None` or `_MISSING_TYPE`, *optional*, defaults to `MISSING`):
The default scale dtype.
quant_range (`QuantRange` ... | update | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/processor.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/processor.py | Apache-2.0 |
def state_dict(self, device: torch.device | str = "cpu") -> dict[str, tp.Any]:
"""Get the state dictionary of the quantizer.
Args:
device (`torch.device` or `str`, *optional*, defaults to `"cpu"`):
The device to store the state dictionary.
Returns:
`dict... | Get the state dictionary of the quantizer.
Args:
device (`torch.device` or `str`, *optional*, defaults to `"cpu"`):
The device to store the state dictionary.
Returns:
`dict[str, Any]`:
The state dictionary.
| state_dict | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/processor.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/processor.py | Apache-2.0 |
def load_state_dict(self, state_dict: dict[str, tp.Any], device: torch.device | str = "cpu"):
"""Load the state dictionary.
Args:
state_dict (`dict[str, Any]`):
The state dictionary.
device (`torch.device` or `str`, *optional*, defaults to `"cpu"`):
... | Load the state dictionary.
Args:
state_dict (`dict[str, Any]`):
The state dictionary.
device (`torch.device` or `str`, *optional*, defaults to `"cpu"`):
The device to load the state dictionary.
| load_state_dict | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/processor.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/processor.py | Apache-2.0 |
def generate_dirnames(
self,
*,
prefix: str = "",
shape: torch.Size | tuple[int, ...] = (4096, 4096),
default_dtype: torch.dtype = torch.float16,
**kwargs,
) -> list[str]:
"""Generate the directory names of the quantization configuration.
Args:
... | Generate the directory names of the quantization configuration.
Args:
prefix (`str`, *optional*, defaults to `""`):
The prefix for the directory names.
shape (`torch.Size` or `tuple[int, ...]`, *optional*, defaults to `(4096, 4096)`):
The shape of the ten... | generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/config/base.py | Apache-2.0 |
def _get_effective_bits(
self, *, shape: torch.Size | tuple[int, ...] = (4096, 4096), default_dtype: torch.dtype = torch.float16
) -> float:
"""Get the effective bits of the quantization.
Args:
shape (`torch.Size` or `tuple[int, ...]`, *optional*, defaults to `(4096, 4096)`):
... | Get the effective bits of the quantization.
Args:
shape (`torch.Size` or `tuple[int, ...]`, *optional*, defaults to `(4096, 4096)`):
The shape of the tensor to be quantized.
dtype (torch.dtype, *optional*, defaults to `torch.float16`):
The dtype of the te... | _get_effective_bits | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/config/base.py | Apache-2.0 |
def _get_dtype_name(self, default_dtype: torch.dtype = torch.float16) -> str:
"""Get the name of the quantization data type.
Args:
default_dtype (`torch.dtype`, *optional*, defaults to `torch.float16`):
The default_dtype dtype of the input tensor.
Returns:
... | Get the name of the quantization data type.
Args:
default_dtype (`torch.dtype`, *optional*, defaults to `torch.float16`):
The default_dtype dtype of the input tensor.
Returns:
`str`:
The name of the quantization data type.
| _get_dtype_name | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/config/base.py | Apache-2.0 |
def _get_group_shapes_name(self, default_dtype: torch.dtype = torch.float16) -> str:
"""Get the name of the group shapes.
Args:
default_dtype (`torch.dtype`, *optional*, defaults to `torch.float16`):
The default_dtype dtype of the input tensor.
Returns:
... | Get the name of the group shapes.
Args:
default_dtype (`torch.dtype`, *optional*, defaults to `torch.float16`):
The default_dtype dtype of the input tensor.
Returns:
str: The name of the group shapes.
| _get_group_shapes_name | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/config/base.py | Apache-2.0 |
def generate_dirnames(
self,
*,
prefix: str = "",
shape: torch.Size | tuple[int, ...] = (4096, 4096),
default_dtype: torch.dtype = torch.float16,
**kwargs,
) -> list[str]:
"""Generate the directory names of the quantization configuration.
Args:
... | Generate the directory names of the quantization configuration.
Args:
prefix (`str`, *optional*, defaults to `""`):
The prefix for the directory names.
shape (`torch.Size` or `tuple[int, ...]`, *optional*, defaults to `(4096, 4096)`):
The shape of the ten... | generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/config/base.py | Apache-2.0 |
def decompose(self) -> DecomposedQuantizerConfig:
"""Decompose the configuration to a list of simple configurations."""
if self.dtype is None:
return DecomposedQuantizerConfig(steps=())
elif len(self.intermediate_dtypes) == 0:
return DecomposedQuantizerConfig(steps=(self,... | Decompose the configuration to a list of simple configurations. | decompose | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/config/base.py | Apache-2.0 |
def quantize(
self,
tensor: torch.Tensor,
*,
view_shape: torch.Size,
quant_dtype: QuantDataType,
zero_domain: ZeroPointDomain | None,
scale: torch.Tensor,
zero: torch.Tensor,
quant_range: QuantRange | None = None,
**kwargs,
) -> torch.T... | Quantize the tensor.
Args:
tensor (`torch.Tensor`):
The tensor to quantize.
view_shape (`torch.Size`):
The view shape when quantizing the tensor.
quant_dtype (`QuantDataType`):
The quantization data type.
zero_domai... | quantize | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/config/kernel.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/config/kernel.py | Apache-2.0 |
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]:
"""Generate the directory names of the configuration.
Args:
prefix (`str`, *optional*, defaults to `""`):
The prefix for the directory names.
Returns:
`list[str]`:
T... | Generate the directory names of the configuration.
Args:
prefix (`str`, *optional*, defaults to `""`):
The prefix for the directory names.
Returns:
`list[str]`:
The directory names.
| generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/config/kernel.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/config/kernel.py | Apache-2.0 |
def quantize(
self,
tensor: torch.Tensor,
*,
kernel: BaseQuantKernel | BaseQuantKernelConfig | None = None,
channels_dim: int | None = None,
# scale-based quantization arguments
scale: torch.Tensor | tp.Sequence[torch.Tensor] | None = None,
zero: torch.Ten... | Quantize a floating point tensor.
Args:
tensor (`torch.Tensor`):
The floating-point tensor to be quantized.
kernel (`QuantKernel` or `QuantKernelConfig` or `None`, *optional*, defaults to `None`):
The quantization kernel or its configuration.
... | quantize | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/impl/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/impl/base.py | Apache-2.0 |
def _quantize( # noqa: C901
self,
tensor: torch.Tensor,
*,
kernel: BaseQuantKernel | BaseQuantKernelConfig | None = None,
# scale-based quantization arguments
scale: torch.Tensor | tp.Sequence[torch.Tensor | None] | None = None,
zero: torch.Tensor | None = None,
... | Quantize a floating point tensor.
Args:
tensor (`torch.Tensor`):
The floating-point tensor to be quantized.
kernel (`QuantKernel` or `QuantKernelConfig` or `None`, *optional*, defaults to `None`):
The quantization kernel or its configuration.
... | _quantize | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/impl/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/impl/base.py | Apache-2.0 |
def update(
self,
tensor_shape: torch.Size,
default_dtype: torch.dtype | None,
quant_range: QuantRange | None,
range_bound: RangeBound | None,
) -> QuantInfo | None:
"""Update the quantization information.
Args:
tensor_shape (`torch.Size`):
... | Update the quantization information.
Args:
tensor_shape (`torch.Size`):
The shape of the tensor.
default_dtype (`torch.dtype` or `None`):
The default data type of the scale.
quant_range (`QuantRange` or `None`):
The quantizatio... | update | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/impl/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/impl/base.py | Apache-2.0 |
def is_outdated(
self,
config: DecomposedQuantizerConfig,
tensor_shape: torch.Size,
default_dtype: torch.dtype,
quant_range: QuantRange | None = None,
range_bound: RangeBound | None = None,
) -> bool:
"""Check if the current quantization information is outdate... | Check if the current quantization information is outdated. | is_outdated | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/impl/info.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/impl/info.py | Apache-2.0 |
def quantize_scale(
s: torch.Tensor,
/,
*,
quant_dtypes: tp.Sequence[QuantDataType],
quant_spans: tp.Sequence[float],
view_shapes: tp.Sequence[torch.Size],
) -> QuantScale:
"""Quantize the scale tensor.
Args:
s (`torch.Tensor`):
The scale tensor.
quant_dtypes... | Quantize the scale tensor.
Args:
s (`torch.Tensor`):
The scale tensor.
quant_dtypes (`Sequence[QuantDataType]`):
The quantization dtypes of the scale tensor.
quant_spans (`Sequence[float]`):
The quantization spans of the scale tensor.
view_shapes ... | quantize_scale | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/impl/scale.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/impl/scale.py | Apache-2.0 |
def quantize(
self,
*,
# scale-based quantization related arguments
scale: torch.Tensor | None = None,
zero: torch.Tensor | None = None,
# range-based quantization related arguments
tensor: torch.Tensor | None = None,
dynamic_range: DynamicRange | None = N... | Get the quantization scale and zero point of the tensor to be quantized.
Args:
scale (`torch.Tensor` or `None`, *optional*, defaults to `None`):
The scale tensor.
zero (`torch.Tensor` or `None`, *optional*, defaults to `None`):
The zero point tensor.
... | quantize | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/impl/scale.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/impl/scale.py | Apache-2.0 |
def quantize(
self,
tensor: torch.Tensor,
*,
view_shape: torch.Size,
quant_dtype: QuantDataType,
zero_domain: ZeroPointDomain | None,
scale: torch.Tensor,
zero: torch.Tensor,
inputs: TensorCache,
quant_range: QuantRange | None = None,
... | Quantize the tensor.
Args:
tensor (`torch.Tensor`):
The tensor to quantize.
view_shape (`torch.Size`):
The view shape when quantizing the tensor.
quant_dtype (`QuantDataType`):
The quantization data type.
zero_domai... | quantize | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/kernel/gptq.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/kernel/gptq.py | Apache-2.0 |
def gptq_quantize( # noqa: C901
tensor: torch.Tensor,
*,
view_shape: torch.Size,
quant_dtype: QuantDataType,
zero_domain: ZeroPointDomain | None,
scale: torch.Tensor,
zero: torch.Tensor,
gptq_config: QuantGptqConfig,
inputs: TensorCache,
quant_range: QuantRange | None = None,
... | Quantize the tensor using the GPTQ quantization kernel.
Args:
tensor (`torch.Tensor`):
The tensor to quantize.
view_shape (`torch.Size`):
The view shape when quantizing the tensor.
quant_dtype (`QuantDataType`):
The quantization data type.
zero_do... | gptq_quantize | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/kernel/gptq.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/kernel/gptq.py | Apache-2.0 |
def quantize(
self,
tensor: torch.Tensor,
*,
view_shape: torch.Size,
quant_dtype: QuantDataType,
zero_domain: ZeroPointDomain | None,
scale: torch.Tensor,
zero: torch.Tensor,
quant_range: QuantRange | None = None,
round_delta: torch.Tensor ... | Quantize the tensor.
Args:
tensor (`torch.Tensor`):
The tensor to quantize.
view_shape (`torch.Size`):
The view shape when quantizing the tensor.
quant_dtype (`QuantDataType`):
The quantization data type.
zero_domai... | quantize | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/kernel/rtn.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/kernel/rtn.py | Apache-2.0 |
def rtn_quantize(
tensor: torch.Tensor,
*,
view_shape: torch.Size,
quant_dtype: QuantDataType,
zero_domain: ZeroPointDomain | None,
scale: torch.Tensor,
zero: torch.Tensor,
quant_range: QuantRange | None = None,
round_delta: torch.Tensor | None = None,
) -> torch.Tensor:
"""Quant... | Quantize the tensor using the RTN quantization kernel.
Args:
tensor (`torch.Tensor`):
The tensor to quantize.
view_shape (`torch.Size`):
The view shape when quantizing the tensor.
quant_dtype (`QuantDataType`):
The quantization data type.
zero_dom... | rtn_quantize | python | mit-han-lab/deepcompressor | deepcompressor/quantizer/kernel/rtn.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/quantizer/kernel/rtn.py | Apache-2.0 |
def join_name(prefix: str, name: str, sep: str = ".", relative: bool = True) -> str:
"""Join a prefix and a name with a separator.
Args:
prefix (`str`): Prefix.
name (`str`): Name.
sep (`str`, *optional*, defaults to `.`): Separator.
relative (`bool`, *optional*, defaults to `Tr... | Join a prefix and a name with a separator.
Args:
prefix (`str`): Prefix.
name (`str`): Name.
sep (`str`, *optional*, defaults to `.`): Separator.
relative (`bool`, *optional*, defaults to `True`):
Whether to resolve relative name.
Returns:
`str`: Joined name... | join_name | python | mit-han-lab/deepcompressor | deepcompressor/utils/common.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/common.py | Apache-2.0 |
def join_names(*names: str, sep: str = ".", relative: bool = True) -> str:
"""Join multiple names with a separator.
Args:
names (`str`): Names.
sep (`str`, *optional*, defaults to `.`): Separator.
relative (`bool`, *optional*, defaults to `True`):
Whether to resolve relative... | Join multiple names with a separator.
Args:
names (`str`): Names.
sep (`str`, *optional*, defaults to `.`): Separator.
relative (`bool`, *optional*, defaults to `True`):
Whether to resolve relative name.
Returns:
`str`: Joined name.
| join_names | python | mit-han-lab/deepcompressor | deepcompressor/utils/common.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/common.py | Apache-2.0 |
def num2str(num: int | float) -> str:
"""Convert a number to a string.
Args:
num (`int` or `float`): Number to convert.
Returns:
str: Converted string.
"""
s = str(num).replace("-", "n")
us = s.split(".")
if len(us) == 1 or int(us[1]) == 0:
return us[0]
else:
... | Convert a number to a string.
Args:
num (`int` or `float`): Number to convert.
Returns:
str: Converted string.
| num2str | python | mit-han-lab/deepcompressor | deepcompressor/utils/common.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/common.py | Apache-2.0 |
def split_sequence(lst: tp.Sequence[tp.Any], splits: tp.Sequence[int]) -> list[list[tp.Any]]:
"""Split a sequence into multiple sequences.
Args:
lst (`Sequence`):
Sequence to split.
splits (`Sequence`):
Split indices.
Returns:
`list[list]`:
Split... | Split a sequence into multiple sequences.
Args:
lst (`Sequence`):
Sequence to split.
splits (`Sequence`):
Split indices.
Returns:
`list[list]`:
Splitted sequences.
| split_sequence | python | mit-han-lab/deepcompressor | deepcompressor/utils/common.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/common.py | Apache-2.0 |
def tree_map(func: tp.Callable[[tp.Any], tp.Any], tree: tp.Any) -> tp.Any:
"""Apply a function to tree-structured data."""
if isinstance(tree, dict):
return {k: tree_map(func, v) for k, v in tree.items()}
elif isinstance(tree, (list, tuple)):
return type(tree)(tree_map(func, v) for v in tree... | Apply a function to tree-structured data. | tree_map | python | mit-han-lab/deepcompressor | deepcompressor/utils/common.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/common.py | Apache-2.0 |
def tree_copy_with_ref(
tree: tp.Any, /, ref: tp.Any, copy_func: tp.Callable[[tp.Any, tp.Any], tp.Any] | None = None
) -> tp.Any:
"""Copy tree-structured data with reference."""
if isinstance(tree, dict):
return {k: tree_copy_with_ref(v, ref[k]) for k, v in tree.items()}
elif isinstance(tree, (l... | Copy tree-structured data with reference. | tree_copy_with_ref | python | mit-han-lab/deepcompressor | deepcompressor/utils/common.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/common.py | Apache-2.0 |
def tree_split(tree: tp.Any) -> list[tp.Any]:
"""Split tree-structured data into a list of data samples."""
def get_batch_size(tree: tp.Any) -> int | None:
if isinstance(tree, dict):
for v in tree.values():
b = get_batch_size(v)
if b is not None:
... | Split tree-structured data into a list of data samples. | tree_split | python | mit-han-lab/deepcompressor | deepcompressor/utils/common.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/common.py | Apache-2.0 |
def tree_collate(batch: list[tp.Any] | tuple[tp.Any, ...]) -> tp.Any:
"""Collate function for tree-structured data."""
if isinstance(batch[0], dict):
return {k: tree_collate([d[k] for d in batch]) for k in batch[0]}
elif isinstance(batch[0], (list, tuple)):
return [tree_collate(samples) for ... | Collate function for tree-structured data. | tree_collate | python | mit-han-lab/deepcompressor | deepcompressor/utils/common.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/common.py | Apache-2.0 |
def get_fields(class_or_instance, *, init_vars: bool = False, class_vars: bool = False) -> tuple[Field, ...]:
"""Get the fields of the dataclass.
Args:
class_or_instance:
The dataclass type or instance.
init_vars (`bool`, *optional*, defaults to `False`):
Whether to incl... | Get the fields of the dataclass.
Args:
class_or_instance:
The dataclass type or instance.
init_vars (`bool`, *optional*, defaults to `False`):
Whether to include the init vars.
class_vars (`bool`, *optional*, defaults to `False`):
Whether to include the c... | get_fields | python | mit-han-lab/deepcompressor | deepcompressor/utils/dataclass.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/dataclass.py | Apache-2.0 |
def copy_func(f: types.FunctionType, globals: dict[str, typing.Any] | None = None):
"""Copied from https://stackoverflow.com/a/13503277/2988730 (@unutbu)
and https://github.com/spcl/QuaRot/blob/main/fake_quant/monkeypatch.py.
Copy a function.
Args:
f (`types.FunctionType`):
Functio... | Copied from https://stackoverflow.com/a/13503277/2988730 (@unutbu)
and https://github.com/spcl/QuaRot/blob/main/fake_quant/monkeypatch.py.
Copy a function.
Args:
f (`types.FunctionType`):
Function to be copied.
globals (`dict[str, typing.Any]` or `None`, *optional*, defaults to... | copy_func | python | mit-han-lab/deepcompressor | deepcompressor/utils/patch.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/patch.py | Apache-2.0 |
def get_module_parents_map(
module: nn.Module, name: str = "", parents_map: dict[nn.Module, list[tuple[str, nn.Module, str]]] | None = None
) -> dict[nn.Module, list[tuple[str, nn.Module, str]]]:
"""Get module parents map.
Args:
module (`nn.Module`):
Module.
name (`str`, *option... | Get module parents map.
Args:
module (`nn.Module`):
Module.
name (`str`, *optional*, defaults to `""`):
Name.
parents_map (`dict[nn.Module, list[tuple[str, nn.Module, str]]]`, *optional*, defaults to `None`):
Parents map.
Returns:
`dict[nn.Mo... | get_module_parents_map | python | mit-han-lab/deepcompressor | deepcompressor/utils/patch.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/patch.py | Apache-2.0 |
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]:
"""Generate the directory names of the configuration.
Args:
prefix (`str`, *optional*, defaults to `""`):
The prefix of the directory names.
Returns:
`list[str]`:
Th... | Generate the directory names of the configuration.
Args:
prefix (`str`, *optional*, defaults to `""`):
The prefix of the directory names.
Returns:
`list[str]`:
The directory names of the configuration.
| generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/utils/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/config/base.py | Apache-2.0 |
def update_get_arguments(
cls: type["SkipBasedConfig"],
*,
overwrites: dict[str, tp.Callable[[omniconfig.Arguments], None] | None] | None = None,
defaults: dict[str, tp.Any] | None = None,
) -> tuple[dict[str, tp.Callable[[omniconfig.Arguments], None] | None], dict[str, tp.Any]]:
... | Get the arguments for the quantization configuration. | update_get_arguments | python | mit-han-lab/deepcompressor | deepcompressor/utils/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/config/base.py | Apache-2.0 |
def update_from_dict(
cls: type["SkipBasedConfig"], *, parsed_args: dict[str, tp.Any], overwrites: dict[str, tp.Any]
) -> tuple[dict[str, tp.Any], dict[str, tp.Any]]:
"""Update the arguments settings for the quantization configuration."""
update_from_dict = getattr(super(), "update_from_dic... | Update the arguments settings for the quantization configuration. | update_from_dict | python | mit-han-lab/deepcompressor | deepcompressor/utils/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/config/base.py | Apache-2.0 |
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]:
"""Generate the directory names of the configuration.
Args:
prefix (`str`, *optional*, defaults to `""`):
The prefix of the directory names.
Returns:
`list[str]`:
Th... | Generate the directory names of the configuration.
Args:
prefix (`str`, *optional*, defaults to `""`):
The prefix of the directory names.
Returns:
`list[str]`:
The directory names. The last directory name is the modules to include.
| generate_dirnames | python | mit-han-lab/deepcompressor | deepcompressor/utils/config/base.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/config/base.py | Apache-2.0 |
def is_locked_by_others(self) -> bool:
"""Check if the running directory is locked by others."""
running_job_dirname = self.running_job_dirname
for dirname in os.listdir(self.running_dirpath):
if dirname.endswith(".RUNNING") and dirname != running_job_dirname:
return ... | Check if the running directory is locked by others. | is_locked_by_others | python | mit-han-lab/deepcompressor | deepcompressor/utils/config/output.py | https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/utils/config/output.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.