diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ce381ad32e498cd629590b6859082b63d92cb88 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/_mappings.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/_mappings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c6040583d6c127f165d457594a1a46f657aadd0 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/_mappings.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/__pycache__/nearly_diagonal_sparsifier.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/__pycache__/nearly_diagonal_sparsifier.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..187b9d9de606a448c89c39e96e54372fa731c1a4 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/__pycache__/nearly_diagonal_sparsifier.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__init__.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..04323f68b5d7ed53e5900c3a912ccd03208cc6bb --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__init__.py @@ -0,0 +1,185 @@ +# flake8: noqa: F403 + +from .fake_quantize import * # noqa: F403 +from .fuse_modules import fuse_modules # noqa: F403 +from .fuse_modules import fuse_modules_qat # noqa: F403 +from .fuser_method_mappings import * # noqa: F403 +from .observer import * # noqa: F403 +from .qconfig import * # noqa: F403 +from .qconfig_mapping import * # noqa: F403 +from .quant_type import * # noqa: F403 +from .quantization_mappings import * # type: ignore[no-redef] +from .quantize import * # noqa: F403 +from .quantize_jit import * # noqa: F403 +from .stubs import * # noqa: F403 +from .pt2e.eval_utils import _move_exported_model_to_eval as move_exported_model_to_eval +from .pt2e.generate_numeric_debug_handle import generate_numeric_debug_handle # noqa: F401 +from typing import Union, List, Callable, Tuple, Optional +from torch import Tensor +import torch + +ObserverOrFakeQuantize = Union[ObserverBase, FakeQuantizeBase] +ObserverOrFakeQuantize.__module__ = "torch.ao.quantization" + +__all__ = [ + "DeQuantStub", + "FakeQuantize", + "FakeQuantizeBase", + "FixedQParamsFakeQuantize", + "FixedQParamsObserver", + "FusedMovingAvgObsFakeQuantize", + "HistogramObserver", + "MatchAllNode", + "MinMaxObserver", + "MovingAverageMinMaxObserver", + "MovingAveragePerChannelMinMaxObserver", + "NoopObserver", + "ObserverBase", + "ObserverOrFakeQuantize", + "Pattern", + "PerChannelMinMaxObserver", + "PlaceholderObserver", + "QConfig", + "QConfigAny", + "QConfigDynamic", + "QConfigMapping", + "QuantStub", + "QuantType", + "QuantWrapper", + "RecordingObserver", + "ReuseInputObserver", + "UniformQuantizationObserverBase", + "add_quant_dequant", + "convert", + "convert_dynamic_jit", + "convert_jit", + "default_affine_fixed_qparams_fake_quant", + "default_affine_fixed_qparams_observer", + "default_debug_observer", + "default_dynamic_fake_quant", + "default_dynamic_quant_observer", + "default_embedding_fake_quant", + "default_embedding_fake_quant_4bit", + "default_eval_fn", + "default_fake_quant", + "default_fixed_qparams_range_0to1_fake_quant", + "default_fixed_qparams_range_0to1_observer", + "default_fixed_qparams_range_neg1to1_fake_quant", + "default_fixed_qparams_range_neg1to1_observer", + "default_float_qparams_observer", + "default_float_qparams_observer_4bit", + "default_fused_act_fake_quant", + "default_fused_per_channel_wt_fake_quant", + "default_fused_wt_fake_quant", + "default_histogram_fake_quant", + "default_histogram_observer", + "default_observer", + "default_per_channel_weight_fake_quant", + "default_per_channel_weight_observer", + "default_placeholder_observer", + "default_reuse_input_observer", + "default_symmetric_fixed_qparams_fake_quant", + "default_symmetric_fixed_qparams_observer", + "default_weight_fake_quant", + "default_weight_observer", + "disable_fake_quant", + "disable_observer", + "enable_fake_quant", + "enable_observer", + "fuse_conv_bn", + "fuse_conv_bn_jit", + "fuse_conv_bn_relu", + "fuse_convtranspose_bn", + "fuse_linear_bn", + "fuse_modules", + "fuse_modules_qat", + "fused_per_channel_wt_fake_quant_range_neg_127_to_127", + "fused_wt_fake_quant_range_neg_127_to_127", + "get_combined_dict", + "get_default_compare_output_module_list", + "get_default_custom_config_dict", + "get_default_dynamic_quant_module_mappings", + "get_default_dynamic_sparse_quant_module_mappings", + "get_default_float_to_quantized_operator_mappings", + "get_default_qat_module_mappings", + "get_default_qat_qconfig", + "get_default_qat_qconfig_dict", + "get_default_qat_qconfig_mapping", + "get_default_qconfig", + "get_default_qconfig_dict", + "get_default_qconfig_mapping", + "get_default_qconfig_propagation_list", + "get_default_static_quant_module_mappings", + "get_default_static_quant_reference_module_mappings", + "get_default_static_sparse_quant_module_mappings", + "get_dynamic_quant_module_class", + "get_embedding_qat_module_mappings", + "get_embedding_static_quant_module_mappings", + "get_fuser_method", + "get_fuser_method_new", + "get_observer_state_dict", + "get_quantized_operator", + "get_static_quant_module_class", + "load_observer_state_dict", + "move_exported_model_to_eval", + "no_observer_set", + "per_channel_weight_observer_range_neg_127_to_127", + "prepare", + "prepare_dynamic_jit", + "prepare_jit", + "prepare_qat", + "propagate_qconfig_", + "qconfig_equals", + "quantize", + "quantize_dynamic", + "quantize_dynamic_jit", + "quantize_jit", + "quantize_qat", + "script_qconfig", + "script_qconfig_dict", + "swap_module", + "weight_observer_range_neg_127_to_127", + "generate_numeric_debug_handle", +] + +def default_eval_fn(model, calib_data): + r"""Define the default evaluation function. + + Default evaluation function takes a torch.utils.data.Dataset or a list of + input Tensors and run the model on the dataset + """ + for data, target in calib_data: + model(data) + +class _DerivedObserverOrFakeQuantize(ObserverBase): + r"""This observer is used to describe an observer whose quantization parameters + are derived from other observers + """ + + def __init__( + self, + dtype: torch.dtype, + obs_or_fqs: List[ObserverOrFakeQuantize], + derive_qparams_fn: Callable[[List[ObserverOrFakeQuantize]], Tuple[Tensor, Tensor]], + quant_min: Optional[int]=None, + quant_max: Optional[int]=None, + qscheme: Optional[torch.qscheme]=None, + ch_axis: Optional[int] = None + ): + super().__init__(dtype) + self.obs_or_fqs = obs_or_fqs + self.derive_qparams_fn = derive_qparams_fn + self.quant_min = quant_min + self.quant_max = quant_max + self.qscheme = qscheme + self.ch_axis = ch_axis + + from .utils import is_per_channel + if is_per_channel(self.qscheme): + assert self.ch_axis is not None, "Must provide a valid ch_axis if qscheme is per channel" + + def forward(self, x: Tensor) -> Tensor: + return x + + def calculate_qparams(self): + return self.derive_qparams_fn(self.obs_or_fqs) diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/_correct_bias.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/_correct_bias.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6a283af69972925b1013175638c70c639b3094c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/_correct_bias.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fake_quantize.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fake_quantize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f8facb90ccb652508ff918acfb2255cfc0ea4b8 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fake_quantize.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fuse_modules.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fuse_modules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6562c48785502211c0dd273d9e99e4541b9d3ea3 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fuse_modules.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quant_type.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quant_type.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9e7322a4fb8e799d2d1f585f6602ae4228f42cb Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quant_type.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantization_mappings.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantization_mappings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5aede05e45342b71c0094178eecb3d3a87c21a96 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantization_mappings.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebebadceac0844b9e836f930a49fd1d5d3772367 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize_pt2e.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize_pt2e.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd16a47912504d5d340476a80a41390e2535ff1c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize_pt2e.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/stubs.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/stubs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa1e46771527f9a74423b2038c28a96fb6130226 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/stubs.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/_correct_bias.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/_correct_bias.py new file mode 100644 index 0000000000000000000000000000000000000000..83cc81bb6b002c5df4110f52c0b6cb9a8e04e3c5 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/_correct_bias.py @@ -0,0 +1,144 @@ +import torch +import torch.nn as nn +import torch.ao.nn.quantized as nnq + +import torch.ao.quantization +import torch.ao.ns._numeric_suite as ns + +__all__ = [ + "get_module", + "parent_child_names", + "get_param", + "MeanShadowLogger", + "bias_correction", +] + +_supported_modules = {nn.Linear, nn.Conv2d} +_supported_modules_quantized = {nnq.Linear, nnq.Conv2d} + +def get_module(model, name): + """Given name of submodule, this function grabs the submodule from given model.""" + return dict(model.named_modules())[name] + +def parent_child_names(name): + """Split full name of submodule into parent submodule's full name and submodule's name.""" + split_name = name.rsplit('.', 1) + if len(split_name) == 1: + return '', split_name[0] + else: + return split_name[0], split_name[1] + +def get_param(module, attr): + """Get the parameter given a module and attribute. + + Sometimes the weights/bias attribute gives you the raw tensor, but sometimes + gives a function that will give you the raw tensor, this function takes care of that logic + """ + param = getattr(module, attr, None) + if callable(param): + return param() + else: + return param + +class MeanShadowLogger(ns.Logger): + """Mean Logger for a Shadow module. + + A logger for a Shadow module whose purpose is to record the rolling mean + of the data passed to the floating point and quantized models + """ + + def __init__(self): + """Set up initial values for float and quantized stats, count, float sum, and quant sum.""" + super().__init__() + self.stats["float"] = None + self.stats["quantized"] = None + self.count = 0 + self.float_sum = None + self.quant_sum = None + + def forward(self, x, y): + """Compute the average of quantized and floating-point data from modules. + + The inputs x,y are output data from the quantized and floating-point modules. + x is for the quantized module, y is for the floating point module + """ + if x.is_quantized: + x = x.dequantize() + + self.count += 1 + if self.stats["quantized"] is None: + self.stats["quantized"] = x + self.quant_sum = x + else: + self.quant_sum += x + self.stats["quantized"] = self.quant_sum / self.count + + if self.stats["float"] is None: + self.stats["float"] = y + self.float_sum = y + else: + self.float_sum += y + self.stats["float"] = self.float_sum / self.count + + def clear(self): + self.stats["float"] = None + self.stats["quantized"] = None + self.count = 0 + self.float_sum = None + self.quant_sum = None + +def bias_correction(float_model, quantized_model, img_data, target_modules=_supported_modules_quantized, neval_batches=None): + """Perform bias correction on a module. + + Using numeric suite shadow module, the expected output of the floating point and quantized modules + is recorded. Using that data the bias of supported modules is shifted to compensate for the drift caused + by quantization + Paper reference: https://arxiv.org/pdf/1906.04721.pdf (Section 4.2) + + Args: + float_model: a trained model that serves as a reference to what bias correction should aim for + quantized_model: quantized form of float_model that bias correction is to applied to + img_data: calibration data to estimate the expected output (used to find quantization error) + target_modules: specifies what submodules in quantized_model need bias correction (can be extended to + unquantized submodules) + neval_batches: a cap to the number of batches you want to be used for estimating the expected output + """ + ns.prepare_model_with_stubs(float_model, quantized_model, _supported_modules, MeanShadowLogger) + + uncorrected_modules = {} + for name, submodule in quantized_model.named_modules(): + if type(submodule) in target_modules: + uncorrected_modules[name] = submodule + + for uncorrected_module in uncorrected_modules: + quantized_submodule = get_module(quantized_model, uncorrected_module) + bias = get_param(quantized_submodule, 'bias') + if bias is not None: + + count = 0 + for data in img_data: + quantized_model(data[0]) + count += 1 + if count == neval_batches: + break + ob_dict = ns.get_logger_dict(quantized_model) + parent_name, _ = parent_child_names(uncorrected_module) + + float_data = ob_dict[parent_name + '.stats']['float'] + quant_data = ob_dict[parent_name + '.stats']['quantized'] + + # math for expected_error + quantization_error = quant_data - float_data + dims = list(range(quantization_error.dim())) + # Note: we don't want to take the mean over the output channel dimension + dims.remove(1) + expected_error = torch.mean(quantization_error, dims) + + updated_bias = bias.data - expected_error + + bias.data = updated_bias + + # Resets the data contained in the loggers + for name, submodule in quantized_model.named_modules(): + if isinstance(submodule, MeanShadowLogger): + submodule.clear() diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/_equalize.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/_equalize.py new file mode 100644 index 0000000000000000000000000000000000000000..7d39dbcf1ca861fc6ae8b19ed3684ec6ec72a0f2 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/_equalize.py @@ -0,0 +1,182 @@ +import torch +import copy +from typing import Dict, Any + +__all__ = [ + "set_module_weight", + "set_module_bias", + "get_module_weight", + "get_module_bias", + "max_over_ndim", + "min_over_ndim", + "channel_range", + "cross_layer_equalization", + "equalize", + "converged", +] + +_supported_types = {torch.nn.Conv2d, torch.nn.Linear} +_supported_intrinsic_types = {torch.ao.nn.intrinsic.ConvReLU2d, torch.ao.nn.intrinsic.LinearReLU} +_all_supported_types = _supported_types.union(_supported_intrinsic_types) + +def set_module_weight(module, weight) -> None: + if type(module) in _supported_types: + module.weight = torch.nn.Parameter(weight) + else: + module[0].weight = torch.nn.Parameter(weight) + +def set_module_bias(module, bias) -> None: + if type(module) in _supported_types: + module.bias = torch.nn.Parameter(bias) + else: + module[0].bias = torch.nn.Parameter(bias) + +def get_module_weight(module): + if type(module) in _supported_types: + return module.weight + else: + return module[0].weight + +def get_module_bias(module): + if type(module) in _supported_types: + return module.bias + else: + return module[0].bias + +def max_over_ndim(input, axis_list, keepdim=False): + """Apply 'torch.max' over the given axes.""" + axis_list.sort(reverse=True) + for axis in axis_list: + input, _ = input.max(axis, keepdim) + return input + +def min_over_ndim(input, axis_list, keepdim=False): + """Apply 'torch.min' over the given axes.""" + axis_list.sort(reverse=True) + for axis in axis_list: + input, _ = input.min(axis, keepdim) + return input + +def channel_range(input, axis=0): + """Find the range of weights associated with a specific channel.""" + size_of_tensor_dim = input.ndim + axis_list = list(range(size_of_tensor_dim)) + axis_list.remove(axis) + + mins = min_over_ndim(input, axis_list) + maxs = max_over_ndim(input, axis_list) + + assert mins.size(0) == input.size(axis), "Dimensions of resultant channel range does not match size of requested axis" + return maxs - mins + +def cross_layer_equalization(module1, module2, output_axis=0, input_axis=1): + """Scale the range of Tensor1.output to equal Tensor2.input. + + Given two adjacent tensors', the weights are scaled such that + the ranges of the first tensors' output channel are equal to the + ranges of the second tensors' input channel + """ + if type(module1) not in _all_supported_types or type(module2) not in _all_supported_types: + raise ValueError("module type not supported:", type(module1), " ", type(module2)) + + weight1 = get_module_weight(module1) + weight2 = get_module_weight(module2) + + if weight1.size(output_axis) != weight2.size(input_axis): + raise TypeError("Number of output channels of first arg do not match \ + number input channels of second arg") + + bias = get_module_bias(module1) + + weight1_range = channel_range(weight1, output_axis) + weight2_range = channel_range(weight2, input_axis) + + # producing scaling factors to applied + weight2_range += 1e-9 + scaling_factors = torch.sqrt(weight1_range / weight2_range) + inverse_scaling_factors = torch.reciprocal(scaling_factors) + + bias = bias * inverse_scaling_factors + + # formatting the scaling (1D) tensors to be applied on the given argument tensors + # pads axis to (1D) tensors to then be broadcasted + size1 = [1] * weight1.ndim + size1[output_axis] = weight1.size(output_axis) + size2 = [1] * weight2.ndim + size2[input_axis] = weight2.size(input_axis) + + scaling_factors = torch.reshape(scaling_factors, size2) + inverse_scaling_factors = torch.reshape(inverse_scaling_factors, size1) + + weight1 = weight1 * inverse_scaling_factors + weight2 = weight2 * scaling_factors + + set_module_weight(module1, weight1) + set_module_bias(module1, bias) + set_module_weight(module2, weight2) + +def equalize(model, paired_modules_list, threshold=1e-4, inplace=True): + """Equalize modules until convergence is achieved. + + Given a list of adjacent modules within a model, equalization will + be applied between each pair, this will repeated until convergence is achieved + + Keeps a copy of the changing modules from the previous iteration, if the copies + are not that different than the current modules (determined by converged_test), + then the modules have converged enough that further equalizing is not necessary + + Implementation of this referced section 4.1 of this paper https://arxiv.org/pdf/1906.04721.pdf + + Args: + model: a model (nn.module) that equalization is to be applied on + paired_modules_list: a list of lists where each sublist is a pair of two + submodules found in the model, for each pair the two submodules generally + have to be adjacent in the model to get expected/reasonable results + threshold: a number used by the converged function to determine what degree + similarity between models is necessary for them to be called equivalent + inplace: determines if function is inplace or not + """ + if not inplace: + model = copy.deepcopy(model) + + name_to_module : Dict[str, torch.nn.Module] = {} + previous_name_to_module: Dict[str, Any] = {} + name_set = {name for pair in paired_modules_list for name in pair} + + for name, module in model.named_modules(): + if name in name_set: + name_to_module[name] = module + previous_name_to_module[name] = None + while not converged(name_to_module, previous_name_to_module, threshold): + for pair in paired_modules_list: + previous_name_to_module[pair[0]] = copy.deepcopy(name_to_module[pair[0]]) + previous_name_to_module[pair[1]] = copy.deepcopy(name_to_module[pair[1]]) + + cross_layer_equalization(name_to_module[pair[0]], name_to_module[pair[1]]) + + return model + +def converged(curr_modules, prev_modules, threshold=1e-4): + """Test whether modules are converged to a specified threshold. + + Tests for the summed norm of the differences between each set of modules + being less than the given threshold + + Takes two dictionaries mapping names to modules, the set of names for each dictionary + should be the same, looping over the set of names, for each name take the difference + between the associated modules in each dictionary + + """ + if curr_modules.keys() != prev_modules.keys(): + raise ValueError("The keys to the given mappings must have the same set of names of modules") + + summed_norms = torch.tensor(0.) + if None in prev_modules.values(): + return False + for name in curr_modules.keys(): + curr_weight = get_module_weight(curr_modules[name]) + prev_weight = get_module_weight(prev_modules[name]) + + difference = curr_weight.sub(prev_weight) + summed_norms += torch.norm(difference) + return bool(summed_norms < threshold) diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/_learnable_fake_quantize.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/_learnable_fake_quantize.py new file mode 100644 index 0000000000000000000000000000000000000000..6827ae35533cd1a7ea651256b599c916efb0b8a0 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/_learnable_fake_quantize.py @@ -0,0 +1,164 @@ +import torch +from torch.nn.parameter import Parameter +from typing import List + +__all__: List[str] = [] + +class _LearnableFakeQuantize(torch.ao.quantization.FakeQuantizeBase): + r"""Generalized extension of the FakeQuantize module in fake_quantize.py. + + This is an extension of the FakeQuantize module in fake_quantize.py, which + supports more generalized lower-bit quantization and support learning of the scale + and zero point parameters through backpropagation. For literature references, + please see the class _LearnableFakeQuantizePerTensorOp. + + In addition to the attributes in the original FakeQuantize module, the _LearnableFakeQuantize + module also includes the following attributes to support quantization parameter learning. + + * :attr:`channel_len` defines the length of the channel when initializing scale and zero point + for the per channel case. + + * :attr:`use_grad_scaling` defines the flag for whether the gradients for scale and zero point are + normalized by the constant, which is proportional to the square root of the number of + elements in the tensor. The related literature justifying the use of this particular constant + can be found here: https://openreview.net/pdf?id=rkgO66VKDS. + + * :attr:`fake_quant_enabled` defines the flag for enabling fake quantization on the output. + + * :attr:`static_enabled` defines the flag for using observer's static estimation for + scale and zero point. + + * :attr:`learning_enabled` defines the flag for enabling backpropagation for scale and zero point. + """ + def __init__(self, observer, quant_min=0, quant_max=255, scale=1., zero_point=0., channel_len=-1, + use_grad_scaling=False, **observer_kwargs): + super().__init__() + assert quant_min < quant_max, 'quant_min must be strictly less than quant_max.' + self.quant_min = quant_min + self.quant_max = quant_max + # also pass quant_min and quant_max to observer + observer_kwargs["quant_min"] = quant_min + observer_kwargs["quant_max"] = quant_max + self.use_grad_scaling = use_grad_scaling + if channel_len == -1: + self.scale = Parameter(torch.tensor([scale])) + self.zero_point = Parameter(torch.tensor([zero_point])) + else: + assert isinstance(channel_len, int) and channel_len > 0, "Channel size must be a positive integer." + self.scale = Parameter(torch.tensor([scale] * channel_len)) + self.zero_point = Parameter(torch.tensor([zero_point] * channel_len)) + + self.activation_post_process = observer(**observer_kwargs) + assert torch.iinfo(self.activation_post_process.dtype).min <= quant_min, \ + 'quant_min out of bound' + assert quant_max <= torch.iinfo(self.activation_post_process.dtype).max, \ + 'quant_max out of bound' + self.dtype = self.activation_post_process.dtype + self.qscheme = self.activation_post_process.qscheme + self.ch_axis = self.activation_post_process.ch_axis \ + if hasattr(self.activation_post_process, 'ch_axis') else -1 + self.register_buffer('fake_quant_enabled', torch.tensor([1], dtype=torch.uint8)) + self.register_buffer('static_enabled', torch.tensor([1], dtype=torch.uint8)) + self.register_buffer('learning_enabled', torch.tensor([0], dtype=torch.uint8)) + + bitrange = torch.tensor(quant_max - quant_min + 1).double() + self.bitwidth = int(torch.log2(bitrange).item()) + self.register_buffer('eps', torch.tensor([torch.finfo(torch.float32).eps])) + + @torch.jit.export + def enable_param_learning(self): + r"""Enable parameter learning over static observer estimates. + + Enables learning of quantization parameters and + disables static observer estimates. Forward path returns fake quantized X. + """ + self.toggle_qparam_learning(enabled=True) \ + .toggle_fake_quant(enabled=True) \ + .toggle_observer_update(enabled=False) + return self + + @torch.jit.export + def enable_static_estimate(self): + """Enable static estimates of quantization parameters. + + Enables static observer estimates and disables learning of + quantization parameters. Forward path returns fake quantized X. + """ + self.toggle_qparam_learning(enabled=False) \ + .toggle_fake_quant(enabled=True) \ + .toggle_observer_update(enabled=True) + + @torch.jit.export + def enable_static_observation(self): + """Enable accumulation of data without updating quantization parameters. + + Enables static observer accumulating data from input but doesn't + update the quantization parameters. Forward path returns the original X. + """ + self.toggle_qparam_learning(enabled=False) \ + .toggle_fake_quant(enabled=False) \ + .toggle_observer_update(enabled=True) + + @torch.jit.export + def toggle_observer_update(self, enabled=True): + self.static_enabled[0] = int(enabled) # type: ignore[operator] + return self + + @torch.jit.export + def enable_observer(self, enabled=True): + self.toggle_observer_update(enabled) + + @torch.jit.export + def toggle_qparam_learning(self, enabled=True): + self.learning_enabled[0] = int(enabled) # type: ignore[operator] + self.scale.requires_grad = enabled + self.zero_point.requires_grad = enabled + return self + + @torch.jit.export + def toggle_fake_quant(self, enabled=True): + self.fake_quant_enabled[0] = int(enabled) + return self + + @torch.jit.export + def observe_quant_params(self): + print(f'_LearnableFakeQuantize Scale: {self.scale.detach()}') + print(f'_LearnableFakeQuantize Zero Point: {self.zero_point.detach()}') + + @torch.jit.export + def calculate_qparams(self): + self.scale.data.clamp_(min=self.eps.item()) # type: ignore[operator] + scale = self.scale.detach() + zero_point = self.zero_point.detach().round().clamp(self.quant_min, self.quant_max).long() + return scale, zero_point + + def forward(self, X): + if self.static_enabled[0] == 1: # type: ignore[index] + self.activation_post_process(X.detach()) + _scale, _zero_point = self.activation_post_process.calculate_qparams() + _scale = _scale.to(self.scale.device) + _zero_point = _zero_point.to(self.zero_point.device) + self.scale.data.copy_(_scale) + self.zero_point.data.copy_(_zero_point) + else: + self.scale.data.clamp_(min=self.eps.item()) # type: ignore[operator] + + if self.fake_quant_enabled[0] == 1: + if self.qscheme in (torch.per_channel_symmetric, torch.per_tensor_symmetric): + self.zero_point.data.zero_() + + if self.use_grad_scaling: + grad_factor = 1.0 / (X.numel() * self.quant_max) ** 0.5 + else: + grad_factor = 1.0 + if self.qscheme in ( + torch.per_channel_symmetric, torch.per_channel_affine): + X = torch._fake_quantize_learnable_per_channel_affine( + X, self.scale, self.zero_point, self.ch_axis, + self.quant_min, self.quant_max, grad_factor) + else: + X = torch._fake_quantize_learnable_per_tensor_affine( + X, self.scale, self.zero_point, + self.quant_min, self.quant_max, grad_factor) + + return X diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/fake_quantize.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/fake_quantize.py new file mode 100644 index 0000000000000000000000000000000000000000..d616afa557dff8a0ebc4a703b9c20dcb7f9ac8c8 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/fake_quantize.py @@ -0,0 +1,546 @@ +"""Implements modules used to perform fake quantization.""" + +import torch +from torch.nn import Module +from torch.ao.quantization.observer import ( + MovingAverageMinMaxObserver, + HistogramObserver, + MovingAveragePerChannelMinMaxObserver, + FixedQParamsObserver, + default_fixed_qparams_range_0to1_observer, + default_fixed_qparams_range_neg1to1_observer, + _with_args, +) +import re +from abc import ABC, abstractmethod +from typing import Any, Tuple + +__all__ = [ + "FakeQuantizeBase", + "FakeQuantize", + "FixedQParamsFakeQuantize", + "FusedMovingAvgObsFakeQuantize", + "disable_fake_quant", + "disable_observer", + "enable_fake_quant", + "enable_observer", + "default_fake_quant", + "default_weight_fake_quant", + "default_dynamic_fake_quant", + "default_fixed_qparams_range_neg1to1_fake_quant", + "default_fixed_qparams_range_0to1_fake_quant", + "default_symmetric_fixed_qparams_fake_quant", + "default_affine_fixed_qparams_fake_quant", + "default_per_channel_weight_fake_quant", + "default_embedding_fake_quant", + "default_embedding_fake_quant_4bit", + "default_histogram_fake_quant", + "default_fused_act_fake_quant", + "default_fused_wt_fake_quant", + "default_fused_per_channel_wt_fake_quant", + "fused_wt_fake_quant_range_neg_127_to_127", + "fused_per_channel_wt_fake_quant_range_neg_127_to_127", +] + +def _is_per_channel(qscheme: 'torch.qscheme') -> bool: + return qscheme in [torch.per_channel_symmetric, torch.per_channel_affine, torch.per_channel_affine_float_qparams] + +def _is_per_tensor(qscheme: 'torch.qscheme') -> bool: + return qscheme in [torch.per_tensor_symmetric, torch.per_tensor_affine] + +def _is_symmetric_quant(qscheme: 'torch.qscheme') -> bool: + return qscheme in [torch.per_tensor_symmetric, torch.per_channel_symmetric] + +def _is_float_qparams(qscheme: 'torch.qscheme') -> bool: + return qscheme in [torch.per_channel_affine_float_qparams, ] + +class FakeQuantizeBase(ABC, Module): + r"""Base fake quantize module. + + Base fake quantize module + Any fake quantize implementation should derive from this class. + + Concrete fake quantize module should follow the same API. In forward, they will update + the statistics of the observed Tensor and fake quantize the input. They should also provide a + `calculate_qparams` function that computes the quantization parameters given + the collected statistics. + + """ + + fake_quant_enabled: torch.Tensor + observer_enabled: torch.Tensor + + def __init__(self): + """Set fake_quant_enabled and observer_enabled.""" + super().__init__() + # fake_quant_enabled and observer_enabled are buffers to support their + # replication in DDP. Data type is uint8 because NCCL does not support + # bool tensors. + self.register_buffer('fake_quant_enabled', torch.tensor([1], dtype=torch.uint8)) + self.register_buffer('observer_enabled', torch.tensor([1], dtype=torch.uint8)) + + @abstractmethod + def forward(self, x): + pass + + @abstractmethod + def calculate_qparams(self, **kwargs): + pass + + @torch.jit.export + def enable_fake_quant(self, enabled: bool = True) -> None: + self.fake_quant_enabled[0] = 1 if enabled else 0 + + @torch.jit.export + def disable_fake_quant(self): + self.enable_fake_quant(False) + + @torch.jit.export + def enable_observer(self, enabled: bool = True) -> None: + self.observer_enabled[0] = 1 if enabled else 0 + + @torch.jit.export + def disable_observer(self): + self.enable_observer(False) + + @classmethod + def with_args(cls, **kwargs): + fake_quant_constructor = _with_args(cls, **kwargs) + # need to assign the correct module to fake_quantize + # constructors to satisfy public v private requirements + fake_quant_constructor.__module__ = "torch.ao.quantization.fake_quantize" + return fake_quant_constructor + +class FakeQuantize(FakeQuantizeBase): + r"""Simulate the quantize and dequantize operations in training time. + + The output of this module is given by:: + + x_out = ( + clamp(round(x/scale + zero_point), quant_min, quant_max) - zero_point + ) * scale + + * :attr:`is_dynamic` indicates whether the fake quantie is a placeholder for dynamic quantization + operators (choose_qparams -> q -> dq) or static quantization operators (q -> dq) + + * :attr:`scale` defines the scale factor used for quantization. + + * :attr:`zero_point` specifies the quantized value to which 0 in floating point maps to + + * :attr:`fake_quant_enabled` controls the application of fake quantization on tensors, note that + statistics can still be updated. + + * :attr:`observer_enabled` controls statistics collection on tensors + + * :attr:`dtype` specifies the quantized dtype that is being emulated with fake-quantization, + allowable values are torch.qint8 and torch.quint8. + + Args: + + observer (module): Module for observing statistics on input tensors and calculating scale + and zero-point. + observer_kwargs (optional): Arguments for the observer module + + Attributes: + activation_post_process (Module): User provided module that collects statistics on the input tensor and + provides a method to calculate scale and zero-point. + + """ + + scale: torch.Tensor + zero_point: torch.Tensor + + def __init__(self, observer=MovingAverageMinMaxObserver, quant_min=None, quant_max=None, is_dynamic=False, **observer_kwargs): + super().__init__() + # Populate quant_min/quant_max to observer_kwargs if valid + if quant_min is not None and quant_max is not None: + assert quant_min <= quant_max, \ + 'quant_min must be less than or equal to quant_max' + dtype = observer_kwargs.get("dtype", torch.quint8) + if hasattr(observer, "p"): + # In case observer is _PartialWrapper, dtype can be stored in + # observer.p.keywords["dtype"] + dtype = getattr(getattr(observer, "p", {}), "keywords", {}).get( + "dtype", dtype + ) + assert torch.iinfo(dtype).min <= quant_min, 'quant_min out of bound' + assert quant_max <= torch.iinfo(dtype).max, 'quant_max out of bound' + observer_kwargs.update({"quant_min": quant_min, "quant_max": quant_max}) + observer_kwargs["is_dynamic"] = is_dynamic + self.activation_post_process = observer(**observer_kwargs) + # TODO: keeping self.quant_min/max for BC; remove after a couple releases + # Users should use self.activation_post_process.quant_min + self.quant_min = self.activation_post_process.quant_min + self.quant_max = self.activation_post_process.quant_max + self.is_dynamic = self.activation_post_process.is_dynamic + if _is_float_qparams(self.activation_post_process.qscheme): + zero_point_dtype = torch.float + else: + zero_point_dtype = torch.int + self.register_buffer('scale', torch.tensor([1.0], dtype=torch.float)) + self.register_buffer('zero_point', torch.tensor([0], dtype=zero_point_dtype)) + self.dtype = self.activation_post_process.dtype + self.qscheme = self.activation_post_process.qscheme + self.ch_axis = self.activation_post_process.ch_axis \ + if hasattr(self.activation_post_process, 'ch_axis') else -1 + assert _is_per_channel(self.qscheme) or \ + _is_per_tensor(self.qscheme), \ + 'Only per channel and per tensor quantization are supported in fake quantize' + \ + ' got qscheme: ' + str(self.qscheme) + self.is_per_channel = _is_per_channel(self.qscheme) + + @torch.jit.export + def calculate_qparams(self): + return self.activation_post_process.calculate_qparams() + + def forward(self, X): + if self.observer_enabled[0] == 1: + self.activation_post_process(X.detach()) + _scale, _zero_point = self.calculate_qparams() + _scale, _zero_point = _scale.to(self.scale.device), _zero_point.to(self.zero_point.device) + if self.scale.shape != _scale.shape: + self.scale.resize_(_scale.shape) + self.zero_point.resize_(_zero_point.shape) + self.scale.copy_(_scale) + self.zero_point.copy_(_zero_point) + + if self.fake_quant_enabled[0] == 1: + if self.is_per_channel: + X = torch.fake_quantize_per_channel_affine( + X, self.scale, self.zero_point, + self.ch_axis, self.activation_post_process.quant_min, self.activation_post_process.quant_max) + else: + X = torch.fake_quantize_per_tensor_affine( + X, self.scale, self.zero_point, + self.activation_post_process.quant_min, self.activation_post_process.quant_max) + return X + + @torch.jit.export + def extra_repr(self): + return 'fake_quant_enabled={}, observer_enabled={}, ' \ + 'quant_min={}, quant_max={}, dtype={}, qscheme={}, ch_axis={}, ' \ + 'scale={}, zero_point={}'.format( + self.fake_quant_enabled, self.observer_enabled, + self.activation_post_process.quant_min, self.activation_post_process.quant_max, + self.dtype, self.qscheme, self.ch_axis, self.scale, self.zero_point) + + def _save_to_state_dict(self, destination, prefix, keep_vars): + # We cannot currently register scalar values as buffers, so need to manually + # specify serialization here. + super()._save_to_state_dict(destination, prefix, keep_vars) + destination[prefix + 'scale'] = self.scale + destination[prefix + 'zero_point'] = self.zero_point + + def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, + missing_keys, unexpected_keys, error_msgs): + # Removing this function throws an error that the size of the loaded tensor does not match the original size + # i.e., These buffers start out with numel 0 and become numel 1 once they have their first forward pass. + local_state = ['scale', 'zero_point'] + for name in local_state: + key = prefix + name + if key in state_dict: + val = state_dict[key] + # Custom handling to allow loading scale and zero_point + # of size N into uninitialized buffers of size 0. The + # buffers are resized here, and the values are copied in + # the default state_dict loading code of the parent. + if name == 'scale': + self.scale.resize_(val.shape) + else: + assert name == 'zero_point' + self.zero_point.resize_(val.shape) + # For torchscript module we need to update the attributes here since we do not + # call the `_load_from_state_dict` function defined module.py + if torch.jit.is_scripting(): + if name == 'scale': + self.scale.copy_(val) + else: + assert name == 'zero_point' + self.zero_point.copy_(val) + elif strict: + missing_keys.append(key) + super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, + missing_keys, unexpected_keys, error_msgs) + + +class FixedQParamsFakeQuantize(FakeQuantize): + """Simulate quantize and dequantize in training time. + + Simulate quantize and dequantize with fixed quantization + parameters in training time. Only per tensor quantization + is supported. + """ + + # TODO: rename observer to observer_ctr + def __init__(self, observer): + super().__init__(observer=observer) + assert type(self.activation_post_process) == FixedQParamsObserver,\ + f"{self.__class__.__name__}'s observer must be a {FixedQParamsObserver.__name__}" + self._observer_ctr = observer + self.scale = self.activation_post_process.scale + self.zero_point = self.activation_post_process.zero_point + assert _is_per_tensor(self.qscheme), 'Only per tensor quantization is supported' + \ + ' FixedQParamsFakeQuantize module, got qscheme:' + str(self.qscheme) + + @torch.jit.export + def calculate_qparams(self): + return self.scale, self.zero_point + + @torch.jit.export + def extra_repr(self): + """Define a string representation of the object's attributes.""" + return 'fake_quant_enabled={}, observer_enabled={}, scale={}, zero_point={}, ' \ + 'dtype={}, quant_min={}, quant_max={}, qscheme={}'.format( + self.fake_quant_enabled, self.observer_enabled, + self.scale, self.zero_point, self.dtype, + self.activation_post_process.quant_min, self.activation_post_process.quant_max, self.qscheme) + + +class FusedMovingAvgObsFakeQuantize(FakeQuantize): + r"""Define a fused module to observe the tensor. + + Fused module that is used to observe the input tensor (compute min/max), compute + scale/zero_point and fake_quantize the tensor. + This module uses calculation similar MovingAverageMinMaxObserver for the inputs, + to compute the min/max values in order to compute the scale/zero_point. + The qscheme input in the observer is used to differentiate between symmetric/affine + quantization scheme. + + The output of this module is given by + x_out = (clamp(round(x/scale + zero_point), quant_min, quant_max)-zero_point)*scale + + Similar to :class:`~torch.ao.quantization.FakeQuantize`, and accepts the same attributes as the + base class. + + """ + + def __init__( + self, + observer: Any = MovingAverageMinMaxObserver, + quant_min: int = 0, + quant_max: int = 255, + **observer_kwargs: Any + ) -> None: + super().__init__(observer, quant_min, quant_max, **observer_kwargs) + assert isinstance(self.activation_post_process, (MovingAverageMinMaxObserver, MovingAveragePerChannelMinMaxObserver)),\ + "Fused observer+fake_quant module only works with MovingAverageMinMaxObserver" + self.register_buffer("fake_quant_enabled", torch.tensor([1], dtype=torch.long)) + self.register_buffer("observer_enabled", torch.tensor([1], dtype=torch.long)) + self.is_symmetric_quant = _is_symmetric_quant(self.activation_post_process.qscheme) + + @torch.jit.export + def calculate_qparams(self) -> Tuple[torch.Tensor, torch.Tensor]: + return self.activation_post_process.calculate_qparams() + + @torch.jit.export + def extra_repr(self) -> str: + return ( + "fake_quant_enabled={}, observer_enabled={}, scale={}, zero_point={}, " + "dtype={}, quant_min={}, quant_max={}, qscheme={}, reduce_range={}".format( + self.fake_quant_enabled, + self.observer_enabled, + self.scale, + self.zero_point, + self.dtype, + self.activation_post_process.quant_min, + self.activation_post_process.quant_max, + self.qscheme, + self.activation_post_process.reduce_range, + ) + ) + + def forward(self, X: torch.Tensor) -> torch.Tensor: + return torch.fused_moving_avg_obs_fake_quant( + X, + self.observer_enabled, + self.fake_quant_enabled, + self.activation_post_process.min_val, + self.activation_post_process.max_val, + self.scale, + self.zero_point, + self.activation_post_process.averaging_constant, + self.activation_post_process.quant_min, + self.activation_post_process.quant_max, + self.ch_axis, + self.is_per_channel, + self.is_symmetric_quant, + ) + +default_fake_quant = FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, quant_min=0, quant_max=255, + dtype=torch.quint8, qscheme=torch.per_tensor_affine, reduce_range=True) +""" +Default fake_quant for activations. +""" + +default_weight_fake_quant = FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, quant_min=-128, quant_max=127, + dtype=torch.qint8, qscheme=torch.per_tensor_symmetric, reduce_range=False) +""" +Default fake_quant for weights. +Observer is memoryless since averaging_constant is 1. +""" + +default_dynamic_fake_quant = FakeQuantize.with_args( + observer=MovingAverageMinMaxObserver, quant_min=0, quant_max=255, is_dynamic=True, + dtype=torch.quint8, averaging_constant=1) +""" +Default dynamic fake_quant for activations. +""" + +default_fixed_qparams_range_neg1to1_fake_quant = ( + FixedQParamsFakeQuantize.with_args(observer=default_fixed_qparams_range_neg1to1_observer) +) +default_fixed_qparams_range_0to1_fake_quant = ( + FixedQParamsFakeQuantize.with_args(observer=default_fixed_qparams_range_0to1_observer) +) +# TODO: the following 2 variables are kept for backwards compatibility; remove after a few releases +default_symmetric_fixed_qparams_fake_quant = default_fixed_qparams_range_neg1to1_fake_quant +default_affine_fixed_qparams_fake_quant = default_fixed_qparams_range_0to1_fake_quant + +default_per_channel_weight_fake_quant = FakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver, + quant_min=-128, + quant_max=127, + dtype=torch.qint8, + qscheme=torch.per_channel_symmetric, + reduce_range=False, + ch_axis=0) +""" +Default fake_quant for per-channel weights. +Observer is memoryless since averaging_constant is 1. +""" +default_embedding_fake_quant = FakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver, + qscheme=torch.per_channel_affine_float_qparams, + dtype=torch.quint8, + quant_min=0, + quant_max=255, + ch_axis=0, + averaging_constant=1) +""" +Default fake_quant for embeddings. +Observer is memoryless since averaging_constant is 1. +""" + +default_embedding_fake_quant_4bit = FakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver, + qscheme=torch.per_channel_affine_float_qparams, + ch_axis=0, + dtype=torch.quint4x2, + averaging_constant=1) + +default_histogram_fake_quant = FakeQuantize.with_args(observer=HistogramObserver, + quant_min=0, + quant_max=255, + dtype=torch.quint8, + qscheme=torch.per_tensor_affine, + reduce_range=True) +""" +Fake_quant for activations using a histogram.. +""" + + +default_fused_act_fake_quant = FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + dtype=torch.quint8,) + +""" +Fused version of `default_fake_quant`, with improved performance. +""" + + +default_fused_wt_fake_quant = FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=-128, + quant_max=127, + dtype=torch.qint8, + qscheme=torch.per_tensor_symmetric) +""" +Fused version of `default_weight_fake_quant`, with improved performance. +""" + +default_fused_per_channel_wt_fake_quant = FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver, + quant_min=-128, + quant_max=127, + dtype=torch.qint8, + qscheme=torch.per_channel_symmetric) +""" +Fused version of `default_per_channel_weight_fake_quant`, with improved performance. +""" + +fused_wt_fake_quant_range_neg_127_to_127 = FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=-127, + quant_max=127, + dtype=torch.qint8, + qscheme=torch.per_tensor_symmetric, + eps=2 ** -12) +""" +Fused version of `default_weight_fake_quant`, with the 8-bit values restricted to [-127, +127], excluding -128. +""" + +fused_per_channel_wt_fake_quant_range_neg_127_to_127 = \ + FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver, + quant_min=-127, + quant_max=127, + dtype=torch.qint8, + qscheme=torch.per_channel_symmetric, + eps=2 ** -12) + +""" +Fused version of `default_per_channel_weight_fake_quant`, with the 8-bit values restricted to [-127, +127], excluding -128. +""" + + +def _is_fake_quant_script_module(mod): + """Return true if given mod is an instance of FakeQuantize script module.""" + if isinstance(mod, torch.jit.RecursiveScriptModule): + # qualified name looks like '__torch__.torch.ao.quantization.fake_quantize.___torch_mangle_2.FakeQuantize' + suffix = mod._c.qualified_name.split('.', 1)[1] + name = re.sub(r'\.___torch_mangle_\d+', '', suffix) + return name == 'torch.ao.quantization.fake_quantize.FakeQuantize' or \ + name == 'torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize' + return False + +def disable_fake_quant(mod): + """Disable fake quantization for the module. + + Disable fake quantization for this module, if applicable. Example usage:: + + # model is any PyTorch model + model.apply(torch.ao.quantization.disable_fake_quant) + + """ + if isinstance(mod, FakeQuantizeBase) or _is_fake_quant_script_module(mod): + mod.disable_fake_quant() + +def enable_fake_quant(mod): + """Enable fake quantization for the module. + + Enable fake quantization for this module, if applicable. Example usage:: + + # model is any PyTorch model + model.apply(torch.ao.quantization.enable_fake_quant) + + """ + if isinstance(mod, FakeQuantizeBase) or _is_fake_quant_script_module(mod): + mod.enable_fake_quant() + +def disable_observer(mod): + """Disable observation for this module. + + Disable observation for this module, if applicable. Example usage:: + + # model is any PyTorch model + model.apply(torch.ao.quantization.disable_observer) + + """ + if isinstance(mod, FakeQuantizeBase) or _is_fake_quant_script_module(mod): + mod.disable_observer() + +def enable_observer(mod): + """Enable observation for this module. + + Enable observation for this module, if applicable. Example usage:: + + # model is any PyTorch model + model.apply(torch.ao.quantization.enable_observer) + + """ + if isinstance(mod, FakeQuantizeBase) or _is_fake_quant_script_module(mod): + mod.enable_observer() diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuse_modules.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuse_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..2caa0a2b7f2d484b0e948afd8af8ea6d854b9868 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuse_modules.py @@ -0,0 +1,175 @@ +import copy + +import torch.nn as nn + +from torch.ao.quantization.fuser_method_mappings import get_fuser_method +# for backward compatibility +from torch.ao.quantization.fuser_method_mappings import fuse_conv_bn # noqa: F401 +from torch.ao.quantization.fuser_method_mappings import fuse_conv_bn_relu # noqa: F401 +from torch.nn.utils.parametrize import type_before_parametrizations + +from typing import List, Optional + +__all__ = [ + "fuse_known_modules", + "fuse_modules", + "fuse_modules_qat", +] + +# Generalization of getattr +def _get_module(model, submodule_key): + tokens = submodule_key.split('.') + cur_mod = model + for s in tokens: + cur_mod = getattr(cur_mod, s) + return cur_mod + +# Generalization of setattr +def _set_module(model, submodule_key, module): + tokens = submodule_key.split('.') + sub_tokens = tokens[:-1] + cur_mod = model + for s in sub_tokens: + cur_mod = getattr(cur_mod, s) + + setattr(cur_mod, tokens[-1], module) + +def fuse_known_modules(mod_list, is_qat, additional_fuser_method_mapping=None): + r"""Return a list of known fuse modules. + + Returns a list of modules that fuses the operations specified + in the input module list. + + Fuses only the following sequence of modules: + conv, bn + conv, bn, relu + conv, relu + linear, bn + linear, relu + For these sequences, the first element in the output module list performs + the fused operation. The rest of the elements are set to nn.Identity() + """ + types = tuple(type_before_parametrizations(m) for m in mod_list) + fuser_method = get_fuser_method(types, additional_fuser_method_mapping) + if fuser_method is None: + raise NotImplementedError(f"Cannot fuse modules: {types}") + new_mod : List[Optional[nn.Module]] = [None] * len(mod_list) + fused = fuser_method(is_qat, *mod_list) + # NOTE: forward hooks not processed in the two following for loops will be lost after the fusion + # Move pre forward hooks of the base module to resulting fused module + for pre_hook_fn in mod_list[0]._forward_pre_hooks.values(): + fused.register_forward_pre_hook(pre_hook_fn) + mod_list[0]._forward_pre_hooks.clear() + # Move post forward hooks of the last module to resulting fused module + for hook_fn in mod_list[-1]._forward_hooks.values(): + fused.register_forward_hook(hook_fn) + mod_list[-1]._forward_hooks.clear() + new_mod[0] = fused + + for i in range(1, len(mod_list)): + identity = nn.Identity() + identity.training = mod_list[0].training + new_mod[i] = identity + + return new_mod + +def _fuse_modules_helper(model, modules_to_fuse, is_qat, fuser_func=fuse_known_modules, fuse_custom_config_dict=None): + if fuse_custom_config_dict is None: + fuse_custom_config_dict = {} + additional_fuser_method_mapping = fuse_custom_config_dict.get("additional_fuser_method_mapping", {}) + mod_list = [] + for item in modules_to_fuse: + mod_list.append(_get_module(model, item)) + + # Fuse list of modules + new_mod_list = fuser_func(mod_list, is_qat, additional_fuser_method_mapping) + + # Replace original module list with fused module list + for i, item in enumerate(modules_to_fuse): + _set_module(model, item, new_mod_list[i]) + +def _fuse_modules(model, modules_to_fuse, is_qat, inplace=False, fuser_func=fuse_known_modules, fuse_custom_config_dict=None): + if not inplace: + model = copy.deepcopy(model) + + if all(isinstance(module_element, str) for module_element in modules_to_fuse): + # Handle case of modules_to_fuse being a list + _fuse_modules_helper(model, modules_to_fuse, is_qat, fuser_func, fuse_custom_config_dict) + else: + # Handle case of modules_to_fuse being a list of lists + for module_list in modules_to_fuse: + _fuse_modules_helper(model, module_list, is_qat, fuser_func, fuse_custom_config_dict) + return model + +def fuse_modules(model, modules_to_fuse, inplace=False, fuser_func=fuse_known_modules, fuse_custom_config_dict=None): + r"""Fuse a list of modules into a single module. + + Fuses only the following sequence of modules: + conv, bn + conv, bn, relu + conv, relu + linear, relu + bn, relu + All other sequences are left unchanged. + For these sequences, replaces the first item in the list + with the fused module, replacing the rest of the modules + with identity. + + Args: + model: Model containing the modules to be fused + modules_to_fuse: list of list of module names to fuse. Can also be a list + of strings if there is only a single list of modules to fuse. + inplace: bool specifying if fusion happens in place on the model, by default + a new model is returned + fuser_func: Function that takes in a list of modules and outputs a list of fused modules + of the same length. For example, + fuser_func([convModule, BNModule]) returns the list [ConvBNModule, nn.Identity()] + Defaults to torch.ao.quantization.fuse_known_modules + `fuse_custom_config_dict`: custom configuration for fusion + + .. code-block:: python + + # Example of fuse_custom_config_dict + fuse_custom_config_dict = { + # Additional fuser_method mapping + "additional_fuser_method_mapping": { + (torch.nn.Conv2d, torch.nn.BatchNorm2d): fuse_conv_bn + }, + } + + Returns: + model with fused modules. A new copy is created if inplace=True. + + Examples:: + + >>> # xdoctest: +SKIP + >>> m = M().eval() + >>> # m is a module containing the sub-modules below + >>> modules_to_fuse = [ ['conv1', 'bn1', 'relu1'], ['submodule.conv', 'submodule.relu']] + >>> fused_m = torch.ao.quantization.fuse_modules(m, modules_to_fuse) + >>> output = fused_m(input) + + >>> m = M().eval() + >>> # Alternately provide a single list of modules to fuse + >>> modules_to_fuse = ['conv1', 'bn1', 'relu1'] + >>> fused_m = torch.ao.quantization.fuse_modules(m, modules_to_fuse) + >>> output = fused_m(input) + + """ + return _fuse_modules( + model, + modules_to_fuse, + is_qat=False, + inplace=inplace, + fuser_func=fuser_func, + fuse_custom_config_dict=fuse_custom_config_dict) + +def fuse_modules_qat(model, modules_to_fuse, inplace=False, fuser_func=fuse_known_modules, fuse_custom_config_dict=None): + """QAT version for `fuse_modules`.""" + return _fuse_modules( + model, + modules_to_fuse, + is_qat=True, + inplace=inplace, + fuser_func=fuser_func, + fuse_custom_config_dict=fuse_custom_config_dict) diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuser_method_mappings.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuser_method_mappings.py new file mode 100644 index 0000000000000000000000000000000000000000..7381c0571415daabc5e1c68f77ca35ace94587ba --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuser_method_mappings.py @@ -0,0 +1,259 @@ +import torch.nn as nn +import torch.ao.nn.intrinsic as nni + +from typing import Any, Union, Callable, List, Tuple, Dict, Optional, Type +from torch.ao.quantization.utils import Pattern, get_combined_dict, MatchAllNode +import itertools + +__all__ = [ + "fuse_conv_bn", + "fuse_conv_bn_relu", + "fuse_linear_bn", + "fuse_convtranspose_bn", + "get_fuser_method", + "get_fuser_method_new", +] + +def fuse_conv_bn(is_qat, conv, bn): + r"""Return the fused the conv and bn modules. + Given the conv and bn modules, fuses them and returns the fused module + + Args: + is_qat: a flag for whether we are using quantization aware training fusion + or post training quantization fusion + conv: Module instance of type conv2d/conv3d + bn: Spatial BN instance that needs to be fused with the conv + + Examples:: + + >>> m1 = nn.Conv2d(10, 20, 3) + >>> b1 = nn.BatchNorm2d(20) + >>> # xdoctest: +SKIP + >>> m2 = fuse_conv_bn(m1, b1) + """ + assert(conv.training == bn.training),\ + "Conv and BN both must be in the same mode (train or eval)." + + fused_module_class_map = { + nn.Conv1d: nni.ConvBn1d, + nn.Conv2d: nni.ConvBn2d, + nn.Conv3d: nni.ConvBn3d, + } + + if is_qat: + assert bn.num_features == conv.out_channels, 'Output channel of Conv2d must match num_features of BatchNorm2d' + assert bn.affine, 'Only support fusing BatchNorm2d with affine set to True' + assert bn.track_running_stats, 'Only support fusing BatchNorm2d with tracking_running_stats set to True' + fused_module_class = fused_module_class_map.get((type(conv)), None) + if fused_module_class is not None: + return fused_module_class(conv, bn) + else: + raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn)}") + else: + return nn.utils.fuse_conv_bn_eval(conv, bn) + +def fuse_conv_bn_relu(is_qat, conv, bn, relu): + r"""Return the fused conv and bv modules. + + Given the conv and bn modules, fuses them and returns the fused module + + Args: + is_qat: a flag for whether we are using quantization aware training fusion + or post training quantization fusion + conv: Module instance of type conv2d/conv3d + bn: Spatial BN instance that needs to be fused with the conv + + Examples:: + + >>> m1 = nn.Conv2d(10, 20, 3) + >>> b1 = nn.BatchNorm2d(20) + >>> r1 = nn.ReLU(inplace=False) + >>> # xdoctest: +SKIP + >>> m2 = fuse_conv_bn_relu(m1, b1, r1) + """ + assert(conv.training == bn.training == relu.training),\ + "Conv and BN both must be in the same mode (train or eval)." + fused_module : Optional[Type[nn.Sequential]] = None + if is_qat: + map_to_fused_module_train = { + nn.Conv1d: nni.ConvBnReLU1d, + nn.Conv2d: nni.ConvBnReLU2d, + nn.Conv3d: nni.ConvBnReLU3d, + } + assert bn.num_features == conv.out_channels, 'Output channel of Conv must match num_features of BatchNorm' + assert bn.affine, 'Only support fusing BatchNorm with affine set to True' + assert bn.track_running_stats, 'Only support fusing BatchNorm with tracking_running_stats set to True' + fused_module = map_to_fused_module_train.get(type(conv), None) + if fused_module is not None: + return fused_module(conv, bn, relu) + else: + raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, relu)}") + else: + map_to_fused_module_eval = { + nn.Conv1d: nni.ConvReLU1d, + nn.Conv2d: nni.ConvReLU2d, + nn.Conv3d: nni.ConvReLU3d, + } + fused_module = map_to_fused_module_eval.get(type(conv), None) + if fused_module is not None: + fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn) + return fused_module(fused_conv, relu) + else: + raise NotImplementedError(f"Cannot fuse eval modules: {(conv, bn, relu)}") + +def fuse_linear_bn(is_qat, linear, bn): + r"""Return the fused linear and bn modules. + Given the linear and bn modules, fuses them and returns the fused module + + Args: + is_qat: a flag for whether we are using quantization aware training fusion + or post training quantization fusion + linear: Module instance of type Linear + bn: BatchNorm1d instance that needs to be fused with the linear layer + + Examples:: + + >>> m1 = nn.Linear(20, 10) + >>> b1 = nn.BatchNorm1d(10) + >>> # xdoctest: +SKIP + >>> m2 = fuse_linear_bn(m1, b1) + """ + assert(linear.training == bn.training),\ + "Linear and BN both must be in the same mode (train or eval)." + + if is_qat: + assert bn.num_features == linear.out_features,\ + "Output features of Linear must match num_features of BatchNorm1d" + assert bn.affine, "Only support fusing BatchNorm1d with affine set to True" + assert bn.track_running_stats,\ + "Only support fusing BatchNorm1d with tracking_running_stats set to True" + return nni.LinearBn1d(linear, bn) + else: + return nn.utils.fusion.fuse_linear_bn_eval(linear, bn) + +def fuse_convtranspose_bn(is_qat, convt, bn): + r"""Return the fused ConvTranspose and bn modules. + Given ConvTranspose and bn modules, fuses them and returns the fused module + + Args: + convt: Module instance of type ConvTransposeNd + bn: BatchNormNd instance that needs to be fused with the linear layer. + batch norm N should match the ConvTranspose N + + Examples:: + + >>> m1 = nn.ConvTranspose2d(10, 20, 3) + >>> b1 = nn.BatchNorm2d(20) + >>> # xdoctest: +SKIP + >>> m2 = fuse_convtranspose_bn(m1, b1) + """ + assert(convt.training == bn.training),\ + "ConvTranspose and BN both must be in the same mode (train or eval)." + + if is_qat: + raise Exception("Fusing ConvTranspose+BatchNorm not yet supported in QAT.") + else: + return nn.utils.fusion.fuse_conv_bn_eval(convt, bn, transpose=True) + +def _sequential_wrapper2(sequential): + """Return a sequential wrapped that for is_qat and two modules. + Given a sequential class for two modules, return a function that takes + is_qat, and then two modules as argument, that ignores the is_qat flag + and always returns the sequential that combines the two input modules + """ + def fuser_method(is_qat, m1, m2): + return sequential(m1, m2) + return fuser_method + +_DEFAULT_OP_LIST_TO_FUSER_METHOD: Dict[Tuple, Union[nn.Sequential, Callable]] = { + (nn.Conv1d, nn.BatchNorm1d): fuse_conv_bn, + (nn.Conv1d, nn.BatchNorm1d, nn.ReLU): fuse_conv_bn_relu, + (nn.Conv2d, nn.BatchNorm2d): fuse_conv_bn, + (nn.Conv2d, nn.BatchNorm2d, nn.ReLU): fuse_conv_bn_relu, + (nn.Conv3d, nn.BatchNorm3d): fuse_conv_bn, + (nn.Conv3d, nn.BatchNorm3d, nn.ReLU): fuse_conv_bn_relu, + (nn.Conv1d, nn.ReLU): _sequential_wrapper2(nni.ConvReLU1d), + (nn.Conv2d, nn.ReLU): _sequential_wrapper2(nni.ConvReLU2d), + (nn.Conv3d, nn.ReLU): _sequential_wrapper2(nni.ConvReLU3d), + (nn.Linear, nn.BatchNorm1d): fuse_linear_bn, + (nn.Linear, nn.ReLU): _sequential_wrapper2(nni.LinearReLU), + (nn.BatchNorm2d, nn.ReLU): _sequential_wrapper2(nni.BNReLU2d), + (nn.BatchNorm3d, nn.ReLU): _sequential_wrapper2(nni.BNReLU3d), + (nn.ConvTranspose1d, nn.BatchNorm1d): fuse_convtranspose_bn, + (nn.ConvTranspose2d, nn.BatchNorm2d): fuse_convtranspose_bn, + (nn.ConvTranspose3d, nn.BatchNorm3d): fuse_convtranspose_bn, +} + +def get_fuser_method(op_list, additional_fuser_method_mapping=None): + """Get fuser method for the given list of module types. + + Get fuser method for the given list of module types, + return None if fuser method does not exist + """ + if additional_fuser_method_mapping is None: + additional_fuser_method_mapping = {} + all_mappings = get_combined_dict(_DEFAULT_OP_LIST_TO_FUSER_METHOD, + additional_fuser_method_mapping) + fuser_method = all_mappings.get(op_list, None) + assert fuser_method is not None, f"did not find fuser method for: {op_list} " + return fuser_method + +def _reverse2(f): + def reversed(is_qat, x, y): + return f(is_qat, y, x) + return reversed + +def _reverse3(f): + def reversed(is_qat, x, w): + y, z = w + return f(is_qat, z, y, x) + return reversed + +def _get_valid_patterns(op_pattern): + """Return a list of valid patterns generated from the op_pattern. + + Returns a list of valid patterns generated from the op_pattern, + since MatchAllNode can match all types of nodes, + e.g. pattern (torch.nn.Conv2d, torch.add) should also be able to match keys like + (MatchAllNode, torch.add) and (torch.nn.Conv2d, MatchAllNode) + + Example Input: + (torch.add, (torch.nn.ReLU, torch.nn.Conv2d)) + + Example Output: + [(torch.add, (torch.nn.ReLU, torch.nn.Conv2d)), + (torch.add, (torch.nn.ReLU, MatchAllNode)), + (torch.add, (MatchAllNode, torch.nn.Conv2d)), + (torch.add, (MatchAllNode, MatchAllNode)), + (MatchAllNode, (torch.nn.ReLU, torch.nn.Conv2d)), + (MatchAllNode, (torch.nn.ReLU, MatchAllNode)), + (MatchAllNode, (MatchAllNode, torch.nn.Conv2d)), + (MatchAllNode, (MatchAllNode, MatchAllNode)), + ] + """ + result: List[Any] + if isinstance(op_pattern, (tuple, list)): + sub_combs = [] + for sub_pattern in op_pattern: + sub_combs.append(_get_valid_patterns(sub_pattern)) + result = list(itertools.product(*sub_combs)) + else: + result = [op_pattern, MatchAllNode] + return result + +def get_fuser_method_new( + op_pattern: Pattern, + fuser_method_mapping: Dict[Pattern, Union[nn.Sequential, Callable]]): + """Get fuser method. + + This will be made default after we deprecate the get_fuser_method + Would like to implement this first and have a separate PR for deprecation + """ + op_patterns = _get_valid_patterns(op_pattern) + fuser_method = None + for op_pattern in op_patterns: + fuser_method = fuser_method_mapping.get(op_pattern, None) + if fuser_method is not None: + break + assert fuser_method is not None, f"did not find fuser method for: {op_pattern} " + return fuser_method diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/observer.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/observer.py new file mode 100644 index 0000000000000000000000000000000000000000..ea7bc03c44f22f3e1850c9f9ccebf80d672f97a9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/observer.py @@ -0,0 +1,1679 @@ +""" +This module implements observers which are used to collect statistics about +the values observed during calibration (PTQ) or training (QAT). +""" + +import re +import warnings +from abc import ABCMeta, abstractmethod +from collections import OrderedDict +from functools import partial +from typing import Any, List, Tuple, Optional, Dict + +import torch +import torch.nn as nn +from torch.ao.quantization.utils import ( + check_min_max_valid, calculate_qmin_qmax, is_per_tensor, is_per_channel, validate_qmin_qmax) + +__all__ = [ + "default_affine_fixed_qparams_observer", + "default_debug_observer", + "default_dynamic_quant_observer", + "default_fixed_qparams_range_0to1_observer", + "default_fixed_qparams_range_neg1to1_observer", + "default_float_qparams_observer", + "default_float_qparams_observer_4bit", + "default_histogram_observer", + "default_observer", + "default_per_channel_weight_observer", + "default_placeholder_observer", + "default_reuse_input_observer", + "default_symmetric_fixed_qparams_observer", + "default_weight_observer", + "get_observer_state_dict", + "load_observer_state_dict", + "per_channel_weight_observer_range_neg_127_to_127", + "weight_observer_range_neg_127_to_127", + "FixedQParamsObserver", + "HistogramObserver", + "MinMaxObserver", + "MovingAverageMinMaxObserver", + "MovingAveragePerChannelMinMaxObserver", + "NoopObserver", + "ObserverBase", + "PerChannelMinMaxObserver", + "PlaceholderObserver", + "RecordingObserver", + "ReuseInputObserver", + "UniformQuantizationObserverBase", +] + + +class _PartialWrapper: + def __init__(self, p): + self.p = p + self.callable_args = {} + + def __call__(self, *args, **keywords): + # call each arg in callable_args and add them partial, then run with keywords + # skip if arg_name in keywords so its possible to overwrite + for arg_name in self.callable_args: + if arg_name not in keywords: + keywords = {**keywords, arg_name: self.callable_args[arg_name]()} + return self.p(*args, **keywords) + + def __repr__(self): + return self.p.__repr__() + self.callable_args.__repr__() + + def with_args(self, **kwargs): + return _with_args(self, **kwargs) + + def with_callable_args(self, **kwargs): + result = _PartialWrapper(p=self.p) + result.callable_args = {**self.callable_args, **kwargs} + return result + + +def _with_args(cls_or_self, **kwargs): + r"""Wrapper that allows creation of class factories. + + This can be useful when there is a need to create classes with the same + constructor arguments, but different instances. Can be used in conjunction with + _callable_args + + Example:: + + >>> # xdoctest: +SKIP("Undefined vars") + >>> Foo.with_args = classmethod(_with_args) + >>> foo_builder = Foo.with_args(a=3, b=4).with_args(answer=42) + >>> foo_instance1 = foo_builder() + >>> foo_instance2 = foo_builder() + >>> id(foo_instance1) == id(foo_instance2) + False + """ + r = _PartialWrapper(partial(cls_or_self, **kwargs)) + return r + +def _with_callable_args(cls_or_self, **kwargs): + r"""Wrapper that allows creation of class factories args that need to be + called at construction time. + + This can be useful when there is a need to create classes with the same + constructor arguments, but different instances and those arguments should only + be calculated at construction time. Can be used in conjunction with _with_args + + Example:: + + >>> # xdoctest: +SKIP("Undefined vars") + >>> Foo.with_callable_args = classmethod(_with_callable_args) + >>> Foo.with_args = classmethod(_with_args) + >>> foo_builder = Foo.with_callable_args(cur_time=get_time_func).with_args(name="dan") + >>> foo_instance1 = foo_builder() + >>> # wait 50 + >>> foo_instance2 = foo_builder() + >>> id(foo_instance1.creation_time) == id(foo_instance2.creation_time) + False + """ + r = _PartialWrapper(partial(cls_or_self)) + return r.with_callable_args(**kwargs) + + +ABC: Any = ABCMeta("ABC", (object,), {}) # compatible with Python 2 *and* 3: + + +class ObserverBase(ABC, nn.Module): + r"""Base observer Module. + Any observer implementation should derive from this class. + + Concrete observers should follow the same API. In forward, they will update + the statistics of the observed Tensor. And they should provide a + `calculate_qparams` function that computes the quantization parameters given + the collected statistics. + + Args: + dtype: dtype argument to the `quantize` node needed to implement the + reference model spec. + is_dynamic: indicator for whether the observer is a placeholder for dynamic quantization + or static quantization + """ + + def __init__(self, dtype, is_dynamic=False): + super().__init__() + self.dtype = dtype + self.is_dynamic = is_dynamic + + @abstractmethod + def forward(self, x): + pass + + @abstractmethod + def calculate_qparams(self, **kwargs): + pass + + with_args = classmethod(_with_args) + with_callable_args = classmethod(_with_callable_args) + + +class UniformQuantizationObserverBase(ObserverBase): + r"""Common base for all observers using uniform quantization to calculate + scale and zero_point. + + Args: + dtype: dtype argument to the `quantize` node needed to implement the + reference model spec. + qscheme: Quantization scheme to be used. + reduce_range: Reduces the range of the quantized data type by 1 bit. + This is sometimes required to avoid instruction overflow. + quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup. + quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup. + eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`. + + .. warning:: + + :attr:`dtype` can only take ``torch.qint8`` or ``torch.quint8``. + or `torch.int8` or `torch.uint8` + + .. warning:: + + :attr:`qscheme` can only take one of the following options: + + - ``torch.per_tensor_affine`` + - ``torch.per_tensor_symmetric`` + - ``torch.per_channel_affine`` + - ``torch.per_channel_symmetric`` + """ + + # Note: the version is shared by all observer types + # + # Version 1/None + # self + # + # Version 2 (base class only, does not include child class buffers) + # self + # |--- eps : Tensor + # + # Version 3 + # for HistogramObserver only, changed the shape of uninitialized + # min_val and max_val buffers from torch.Size([0]) to torch.Size([]) + # for PerChannelObservers, changed the name of the buffers from min_vals + # to min_val and from max_vals to max_val. + _version = 3 + + eps: torch.Tensor + + def __init__( + self, + dtype=torch.quint8, + qscheme=torch.per_tensor_affine, + reduce_range=False, + quant_min=None, + quant_max=None, + factory_kwargs=None, + eps=torch.finfo(torch.float32).eps, + is_dynamic=False, + **kwargs, + ) -> None: + factory_kwargs = torch.nn.factory_kwargs(factory_kwargs) + super().__init__(dtype=dtype, is_dynamic=is_dynamic, **kwargs) + self.qscheme = qscheme + if reduce_range: + warnings.warn( + "Please use quant_min and quant_max to specify the range for observers. \ + reduce_range will be deprecated in a future release of PyTorch." + ) + self.reduce_range = reduce_range + self.register_buffer( + "eps", torch.tensor([eps], **factory_kwargs) + ) + assert self.qscheme in ( + torch.per_tensor_affine, + torch.per_tensor_symmetric, + torch.per_channel_affine, + torch.per_channel_symmetric, + torch.per_channel_affine_float_qparams, + ), "Default Observer only works for per_tensor_affine, \ + per_tensor_symmetric, per_channel_affine, \ + per_channel_symmetric and per_channel_float_qparams quantization scheme" + + _ALLOWED_DTYPES = ( + torch.qint8, + torch.quint8, + torch.quint4x2, + torch.qint32, + torch.int8, + torch.uint8, + torch.int16, + torch.int32, + ) + + assert self.dtype in _ALLOWED_DTYPES, f"Default Observer only works for {_ALLOWED_DTYPES} data type" + self.has_customized_qrange = (quant_min is not None) and (quant_max is not None) + if self.has_customized_qrange: + validate_qmin_qmax(quant_min, quant_max) + self.quant_min, self.quant_max = \ + calculate_qmin_qmax(quant_min, quant_max, self.has_customized_qrange, self.dtype, self.reduce_range) + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + + version = local_metadata.get("version", None) + + if version is None or version == 1: + # eps was moved to a buffer in version 2 + eps = torch.tensor([torch.finfo(torch.float32).eps]) + state_dict[prefix + "eps"] = eps + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + @torch.jit.export + def _validate_qmin_qmax(self, quant_min: int, quant_max: int) -> None: + r"""Validates that the user-specified quantization range is properly initialized + and within the given bound supported by the observer dtype. + + To accommodate lower-bit quantization with respect to the existing torch.qint8 and + torch.quint8 datatypes, the user can choose to use dynamic quantization range by passing + in a tuple of initial qmin and qmax values. One use case is these customized qmin and qmax + values are used to calculate static estimates of the scale and zero point for aggressive lower-bit + fake quantization. These estimates are compared against parameters learned through backpropagation. + The related literatures for scale and zero point via backpropagation are as follows: + + Learned Step Size Quantization: https://openreview.net/pdf?id=rkgO66VKDS + Trained Quantization Thresholds: https://arxiv.org/pdf/1903.08066.pdf + """ + # The variable names are prefixed with "initial" because their values (qmin and qmax) might be adjusted + # based on whether quantization range is reduced and the datatype (signed/unsigned) used by the observer. + assert ( + quant_min <= 0 <= quant_max + ), "Used-specified quantization range must include 0." + assert ( + quant_min < quant_max + ), "qmin must be strictly less than qmax for user-specified quantization range." + + @torch.jit.export + def _calculate_qparams( + self, min_val: torch.Tensor, max_val: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + r"""Calculates the quantization parameters, given min and max + value tensors. Works for both per tensor and per channel cases + + Args: + min_val: Minimum values per channel + max_val: Maximum values per channel + + Returns: + scales: Scales tensor of shape (#channels,) + zero_points: Zero points tensor of shape (#channels,) + """ + # Functionally equivalent to 'determine_qparams' in utils.py. Observers must be torchscriptable however and qscheme + # as far as I can tell is not allowed to passed as a parameter in torchscript functions. This makes refactoring observer + # to use this utility a massive pain and very gross. For now Im opting just to duplicate as this code + # seems unlikey to change (last update over 1 year ago) and when torchscript is fully deprecated we can refactor. + # TODO(jakeszwe, jerryzh168) + if not check_min_max_valid(min_val, max_val): + return torch.tensor([1.0], device=min_val.device.type), torch.tensor([0], device=min_val.device.type) + + quant_min, quant_max = self.quant_min, self.quant_max + min_val_neg = torch.min(min_val, torch.zeros_like(min_val)) + max_val_pos = torch.max(max_val, torch.zeros_like(max_val)) + + device = min_val_neg.device + scale = torch.ones(min_val_neg.size(), dtype=torch.float32, device=device) + zero_point = torch.zeros(min_val_neg.size(), dtype=torch.int64, device=device) + + if ( + self.qscheme == torch.per_tensor_symmetric + or self.qscheme == torch.per_channel_symmetric + ): + max_val_pos = torch.max(-min_val_neg, max_val_pos) + scale = max_val_pos / (float(quant_max - quant_min) / 2) + scale = torch.max(scale, self.eps) + if self.dtype in [torch.quint8, torch.uint8]: + if self.has_customized_qrange: + # When customized quantization range is used, down-rounded midpoint of the range is chosen. + zero_point = zero_point.new_full( + zero_point.size(), (quant_min + quant_max) // 2 + ) + else: + zero_point = zero_point.new_full(zero_point.size(), 128) + elif self.qscheme == torch.per_channel_affine_float_qparams: + scale = (max_val - min_val) / float(quant_max - quant_min) + scale = torch.where(scale > self.eps, scale, torch.ones_like(scale)) + # We use the quantize function + # xq = Round(Xf * inv_scale + zero_point), + # setting zero_point to (-1 * min *inv_scale) we get + # Xq = Round((Xf - min) * inv_scale) + zero_point = -1 * min_val / scale + else: + scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min) + scale = torch.max(scale, self.eps) + zero_point = quant_min - torch.round(min_val_neg / scale).to(torch.int) + zero_point = torch.clamp(zero_point, quant_min, quant_max) + + # For scalar values, cast them to Tensors of size 1 to keep the shape + # consistent with default values in FakeQuantize. + if len(scale.shape) == 0: + # TODO: switch to scale.item() after adding JIT support + scale = torch.tensor([float(scale)], dtype=scale.dtype, device=device) + if len(zero_point.shape) == 0: + # TODO: switch to zero_point.item() after adding JIT support + zero_point = torch.tensor( + [int(zero_point)], dtype=zero_point.dtype, device=device + ) + if self.qscheme == torch.per_channel_affine_float_qparams: + zero_point = torch.tensor( + [float(zero_point)], dtype=zero_point.dtype, device=device + ) + + return scale, zero_point + + @torch.jit.export + def reset_min_max_vals(self): + raise NotImplementedError("Cannot reset min/max values in the given observer.") + + +# Originally, this class was called `_ObserverBase`. Keeping the old name around +# for backwards compatibility. +# TODO(after v1.13): delete this +_ObserverBase = UniformQuantizationObserverBase + + +class MinMaxObserver(UniformQuantizationObserverBase): + r"""Observer module for computing the quantization parameters based on the + running min and max values. + + This observer uses the tensor min/max statistics to compute the quantization + parameters. The module records the running minimum and maximum of incoming + tensors, and uses this statistic to compute the quantization parameters. + + Args: + dtype: dtype argument to the `quantize` node needed to implement the + reference model spec. + qscheme: Quantization scheme to be used + reduce_range: Reduces the range of the quantized data type by 1 bit + quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup. + quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup. + eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`. + + Given running min/max as :math:`x_\text{min}` and :math:`x_\text{max}`, + scale :math:`s` and zero point :math:`z` are computed as: + + The running minimum/maximum :math:`x_\text{min/max}` is computed as: + + .. math:: + + \begin{array}{ll} + x_\text{min} &= \begin{cases} + \min(X) & \text{if~}x_\text{min} = \text{None} \\ + \min\left(x_\text{min}, \min(X)\right) & \text{otherwise} + \end{cases}\\ + x_\text{max} &= \begin{cases} + \max(X) & \text{if~}x_\text{max} = \text{None} \\ + \max\left(x_\text{max}, \max(X)\right) & \text{otherwise} + \end{cases}\\ + \end{array} + + where :math:`X` is the observed tensor. + + The scale :math:`s` and zero point :math:`z` are then computed as: + + .. math:: + + \begin{aligned} + \text{if Symmetric:}&\\ + &s = 2 \max(|x_\text{min}|, x_\text{max}) / + \left( Q_\text{max} - Q_\text{min} \right) \\ + &z = \begin{cases} + 0 & \text{if dtype is qint8} \\ + 128 & \text{otherwise} + \end{cases}\\ + \text{Otherwise:}&\\ + &s = \left( x_\text{max} - x_\text{min} \right ) / + \left( Q_\text{max} - Q_\text{min} \right ) \\ + &z = Q_\text{min} - \text{round}(x_\text{min} / s) + \end{aligned} + + where :math:`Q_\text{min}` and :math:`Q_\text{max}` are the minimum and + maximum of the quantized data type. + + .. warning:: :attr:`dtype` can only take ``torch.qint8`` or ``torch.quint8``. + + .. note:: If the running minimum equals to the running maximum, the scale + and zero_point are set to 1.0 and 0. + """ + min_val: torch.Tensor + max_val: torch.Tensor + + def __init__( + self, + dtype=torch.quint8, + qscheme=torch.per_tensor_affine, + reduce_range=False, + quant_min=None, + quant_max=None, + factory_kwargs=None, + eps=torch.finfo(torch.float32).eps, + is_dynamic=False, + **kwargs, + ) -> None: + if not is_per_tensor(qscheme): + raise NotImplementedError( + "MinMaxObserver's qscheme only support torch.per_tensor_symmetric \ + and torch.per_tensor_affine." + ) + # TODO: MinMaxObserver by itself doesn't support dynamic quantization, but + # if it's inherited by MovingAverageObserver, and averaging_constant is 1, it + # supports dynamic quantization, we may need to better error checking here + + # For x86 quantized kernels, we need to ensure that the vpmaddubsw + # instruction does not overflow. We allow for a reduce_range argument to + # observers that reduces the quantized range to (0,127) or (-64, 63). + # For more details see aten/src/ATen/native/quantized/cpu/qconv.cpp + # This is not an optimal choice for non x86 backends as it loses a bit + # of precision for activations. + super().__init__( + dtype=dtype, + qscheme=qscheme, + reduce_range=reduce_range, + quant_min=quant_min, + quant_max=quant_max, + factory_kwargs=factory_kwargs, + eps=eps, + is_dynamic=is_dynamic, + **kwargs, + ) + factory_kwargs = torch.nn.factory_kwargs(factory_kwargs) + self.register_buffer("min_val", torch.tensor(float("inf"), **factory_kwargs)) + self.register_buffer("max_val", torch.tensor(float("-inf"), **factory_kwargs)) + if ( + self.qscheme == torch.per_tensor_symmetric + and self.reduce_range + and self.dtype == torch.quint8 + ): + raise NotImplementedError( + "Cannot reduce range for symmetric \ + quantization for quint8" + ) + + def forward(self, x_orig): + r"""Records the running minimum and maximum of ``x``.""" + if x_orig.numel() == 0: + return x_orig + x = x_orig.detach() # avoid keeping autograd tape + x = x.to(self.min_val.dtype) + min_val_cur, max_val_cur = torch.aminmax(x) + min_val = torch.min(min_val_cur, self.min_val) + max_val = torch.max(max_val_cur, self.max_val) + self.min_val.copy_(min_val) + self.max_val.copy_(max_val) + return x_orig + + @torch.jit.export + def calculate_qparams(self): + r"""Calculates the quantization parameters.""" + return self._calculate_qparams(self.min_val, self.max_val) + + @torch.jit.export + def extra_repr(self): + return f"min_val={self.min_val}, max_val={self.max_val}" + + @torch.jit.export + def reset_min_max_vals(self): + """Resets the min/max values.""" + self.min_val.copy_(torch.tensor(float("inf"))) + self.max_val.copy_(torch.tensor(float("-inf"))) + +class MovingAverageMinMaxObserver(MinMaxObserver): + r"""Observer module for computing the quantization parameters based on the + moving average of the min and max values. + + This observer computes the quantization parameters based on the moving + averages of minimums and maximums of the incoming tensors. The module + records the average minimum and maximum of incoming tensors, and uses this + statistic to compute the quantization parameters. + + Args: + averaging_constant: Averaging constant for min/max. + dtype: dtype argument to the `quantize` node needed to implement the + reference model spec. + qscheme: Quantization scheme to be used + reduce_range: Reduces the range of the quantized data type by 1 bit + quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup. + quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup. + eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`. + + The moving average min/max is computed as follows + + .. math:: + + \begin{array}{ll} + x_\text{min} = \begin{cases} + \min(X) & \text{if~}x_\text{min} = \text{None} \\ + (1 - c) x_\text{min} + c \min(X) & \text{otherwise} + \end{cases}\\ + x_\text{max} = \begin{cases} + \max(X) & \text{if~}x_\text{max} = \text{None} \\ + (1 - c) x_\text{max} + c \max(X) & \text{otherwise} + \end{cases}\\ + \end{array} + + where :math:`x_\text{min/max}` is the running average min/max, :math:`X` is + is the incoming tensor, and :math:`c` is the ``averaging_constant``. + + The scale and zero point are then computed as in + :class:`~torch.ao.quantization.observer.MinMaxObserver`. + + .. note:: Only works with ``torch.per_tensor_affine`` quantization scheme. + + .. note:: If the running minimum equals to the running maximum, the scale + and zero_point are set to 1.0 and 0. + """ + + def __init__( + self, + averaging_constant=0.01, + dtype=torch.quint8, + qscheme=torch.per_tensor_affine, + reduce_range=False, + quant_min=None, + quant_max=None, + eps=torch.finfo(torch.float32).eps, + is_dynamic=False, + **kwargs + ) -> None: + if not is_per_tensor(qscheme): + raise NotImplementedError( + f"MovingAverageMinMaxObserver's qscheme only support \ + torch.per_tensor_symmetric and torch.per_tensor_affine. \ + but got: {qscheme}" + ) + self.averaging_constant = averaging_constant + if is_dynamic and self.averaging_constant != 1: + raise NotImplementedError( + "MovingAverageMinMaxObserver doesn't support dynamic quantization for " + f"averaging constant of {self.averaging_constant}" + ) + super().__init__( + dtype=dtype, + qscheme=qscheme, + reduce_range=reduce_range, + quant_min=quant_min, + quant_max=quant_max, + eps=eps, + is_dynamic=is_dynamic, + **kwargs + ) + + def forward(self, x_orig): + if x_orig.numel() == 0: + return x_orig + x = x_orig.detach() # avoid keeping autograd tape + x = x.to(self.min_val.dtype) + min_val = self.min_val + max_val = self.max_val + if min_val == float("inf") and max_val == float("-inf"): + min_val, max_val = torch.aminmax(x) + else: + min_val_cur, max_val_cur = torch.aminmax(x) + min_val = min_val + self.averaging_constant * (min_val_cur - min_val) + max_val = max_val + self.averaging_constant * (max_val_cur - max_val) + self.min_val.copy_(min_val) + self.max_val.copy_(max_val) + return x_orig + + +class PerChannelMinMaxObserver(UniformQuantizationObserverBase): + r"""Observer module for computing the quantization parameters based on the + running per channel min and max values. + + This observer uses the tensor min/max statistics to compute the per channel + quantization parameters. The module records the running minimum and maximum + of incoming tensors, and uses this statistic to compute the quantization + parameters. + + Args: + ch_axis: Channel axis + dtype: dtype argument to the `quantize` node needed to implement the + reference model spec. + qscheme: Quantization scheme to be used + reduce_range: Reduces the range of the quantized data type by 1 bit + quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup. + quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup. + eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`. + + The quantization parameters are computed the same way as in + :class:`~torch.ao.quantization.observer.MinMaxObserver`, with the difference + that the running min/max values are stored per channel. + Scales and zero points are thus computed per channel as well. + + .. note:: If the running minimum equals to the running maximum, the scales + and zero_points are set to 1.0 and 0. + """ + min_val: torch.Tensor + max_val: torch.Tensor + + def __init__( + self, + ch_axis=0, + dtype=torch.quint8, + qscheme=torch.per_channel_affine, + reduce_range=False, + quant_min=None, + quant_max=None, + factory_kwargs=None, + eps=torch.finfo(torch.float32).eps, + is_dynamic=False, + **kwargs, + ) -> None: + if not is_per_channel(qscheme): + raise NotImplementedError( + "PerChannelMinMaxObserver's qscheme only support \ + torch.per_channel_symmetric, torch.per_channel_affine and torch.per_channel_affine_float_qparams." + ) + if is_dynamic: + raise NotImplementedError( + "PerChannelMinMaxObserver doesn't support dynamic quantization" + ) + super().__init__( + dtype=dtype, + qscheme=qscheme, + reduce_range=reduce_range, + quant_min=quant_min, + quant_max=quant_max, + factory_kwargs=factory_kwargs, + eps=eps, + is_dynamic=is_dynamic, + **kwargs, + ) + factory_kwargs = torch.nn.factory_kwargs(factory_kwargs) + self.ch_axis = ch_axis + self.register_buffer("min_val", torch.tensor([], **factory_kwargs)) + self.register_buffer("max_val", torch.tensor([], **factory_kwargs)) + if ( + self.qscheme == torch.per_channel_symmetric + and self.reduce_range + and self.dtype == torch.quint8 + ): + raise NotImplementedError( + "Cannot reduce range for symmetric quantization for quint8" + ) + + def forward(self, x_orig): + return self._forward(x_orig) + + def _forward(self, x_orig): + if x_orig.numel() == 0: + return x_orig + x = x_orig.detach() # avoid keeping autograd tape + min_val = self.min_val + max_val = self.max_val + x_dim = x.size() + + new_axis_list = [i for i in range(len(x_dim))] # noqa: C416 + new_axis_list[self.ch_axis] = 0 + new_axis_list[0] = self.ch_axis + y = x.permute(new_axis_list) + # Need to match dtype of min/max because the updates to buffers + # are done in place and types need to match for comparisons + y = y.to(self.min_val.dtype) + y = torch.flatten(y, start_dim=1) + if min_val.numel() == 0 or max_val.numel() == 0: + min_val, max_val = torch.aminmax(y, dim=1) + else: + min_val_cur, max_val_cur = torch.aminmax(y, dim=1) + min_val = torch.min(min_val_cur, min_val) + max_val = torch.max(max_val_cur, max_val) + self.min_val.resize_(min_val.shape) + self.max_val.resize_(max_val.shape) + self.min_val.copy_(min_val) + self.max_val.copy_(max_val) + return x_orig + + @torch.jit.export + def calculate_qparams(self): + return self._calculate_qparams(self.min_val, self.max_val) + + def extra_repr(self): + return f"min_val={self.min_val}, max_val={self.max_val}" + + def _load_from_state_dict( + self, + state_dict: Dict[str, Any], + prefix: str, + local_metadata: Dict[str, torch.Tensor], + strict: bool, + missing_keys: List[str], + unexpected_keys: List[str], + error_msgs: List[str], + ): + version = local_metadata.get("version", None) + if version is None or version < 3: + local_state = ["min_vals", "max_vals"] + expected_min_name = "min_vals" + expected_max_name = "max_vals" + else: + local_state = ["min_val", "max_val"] + expected_min_name = "min_val" + expected_max_name = "max_val" + for name in local_state: + key = prefix + name + if key in state_dict: + val = state_dict[key] + # Custom handling to allow loading min_val or max_val + # of size N into uninitialized buffers of size 0. The + # buffers are resized here, and the values are copied in + # the default state_dict loading code of the parent. + if name == expected_min_name: + self.min_val.resize_(val.shape) + elif name == expected_max_name: + self.max_val.resize_(val.shape) + else: + warnings.warn(f"Observer load_from_state_dict got unexpected name {name}") + # For torchscript module we need to update the attributes here since we do not + # call the `_load_from_state_dict` function defined module.py + if torch.jit.is_scripting(): + if name == expected_min_name: + self.min_val.copy_(val) + elif name == expected_max_name: + self.max_val.copy_(val) + else: + warnings.warn(f"Observer load_from_state_dict got unexpected name {name}") + elif strict: + missing_keys.append(key) + + if not torch.jit.is_scripting(): + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + False, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def _load_from_state_dict_script( + self, + state_dict: Dict[str, Any], + prefix: str, + local_metadata: Dict[str, torch.Tensor], + strict: bool, + missing_keys: List[str], + unexpected_keys: List[str], + error_msgs: List[str], + ): + + self._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + @torch.jit.export + def reset_min_max_vals(self): + """Resets the min/max values.""" + # This used to be torch.ones but that does not work because + # JIT compiler can optimize it via common subexpression elimination + # in which case both min_val and max_val point to the same tensor. + self.min_val = torch.rand(0, ) + self.max_val = torch.rand(0, ) + + +class MovingAveragePerChannelMinMaxObserver(PerChannelMinMaxObserver): + r"""Observer module for computing the quantization parameters based on the + running per channel min and max values. + + This observer uses the tensor min/max statistics to compute the per channel + quantization parameters. The module records the running minimum and maximum + of incoming tensors, and uses this statistic to compute the quantization + parameters. + + Args: + averaging_constant: Averaging constant for min/max. + ch_axis: Channel axis + dtype: Quantized data type + qscheme: Quantization scheme to be used + reduce_range: Reduces the range of the quantized data type by 1 bit + quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup. + quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup. + eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`. + + The quantization parameters are computed the same way as in + :class:`~torch.ao.quantization.observer.MovingAverageMinMaxObserver`, with the + difference that the running min/max values are stored per channel. + Scales and zero points are thus computed per channel as well. + + .. note:: If the running minimum equals to the running maximum, the scales + and zero_points are set to 1.0 and 0. + """ + + def __init__( + self, + averaging_constant=0.01, + ch_axis=0, + dtype=torch.quint8, + qscheme=torch.per_channel_affine, + reduce_range=False, + quant_min=None, + quant_max=None, + eps=torch.finfo(torch.float32).eps, + is_dynamic=False, + **kwargs + ) -> None: + if not is_per_channel(qscheme): + raise NotImplementedError( + "MovingAveragePerChannelMinMaxObserver's qscheme only support \ + torch.per_channel_symmetric, torch.per_channel_affine and torch.per_channel_affine_float_qparams." + ) + if is_dynamic: + raise NotImplementedError( + "MovingAveragePerChannelMinMaxObserver doesn't support dynamic quantization" + ) + super().__init__( + ch_axis=ch_axis, + dtype=dtype, + qscheme=qscheme, + reduce_range=reduce_range, + quant_min=quant_min, + quant_max=quant_max, + eps=eps, + is_dynamic=is_dynamic, + **kwargs + ) + self.averaging_constant = averaging_constant + + def forward(self, x_orig): + if x_orig.numel() == 0: + return x_orig + x = x_orig.detach() # avoid keeping autograd tape + x = x.to(self.min_val.dtype) + min_val = self.min_val + max_val = self.max_val + x_dim = x.size() + + new_axis_list = [i for i in range(len(x_dim))] # noqa: C416 + new_axis_list[self.ch_axis] = 0 + new_axis_list[0] = self.ch_axis + y = x.permute(new_axis_list) + y = torch.flatten(y, start_dim=1) + if min_val.numel() == 0 or max_val.numel() == 0: + min_val, max_val = torch.aminmax(y, dim=1) + else: + min_val_cur, max_val_cur = torch.aminmax(y, dim=1) + min_val = min_val + self.averaging_constant * (min_val_cur - min_val) + max_val = max_val + self.averaging_constant * (max_val_cur - max_val) + self.min_val.resize_(min_val.shape) + self.max_val.resize_(max_val.shape) + self.min_val.copy_(min_val) + self.max_val.copy_(max_val) + return x_orig + + +class HistogramObserver(UniformQuantizationObserverBase): + r""" + The module records the running histogram of tensor values along with + min/max values. ``calculate_qparams`` will calculate scale and zero_point. + + Args: + bins: Number of bins to use for the histogram + upsample_rate: Factor by which the histograms are upsampled, this is + used to interpolate histograms with varying ranges across observations + dtype: dtype argument to the `quantize` node needed to implement the + reference model spec + qscheme: Quantization scheme to be used + reduce_range: Reduces the range of the quantized data type by 1 bit + eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`. + + The scale and zero point are computed as follows: + + 1. Create the histogram of the incoming inputs. + The histogram is computed continuously, and the ranges per bin change + with every new tensor observed. + 2. Search the distribution in the histogram for optimal min/max values. + The search for the min/max values ensures the minimization of the + quantization error with respect to the floating point model. + 3. Compute the scale and zero point the same way as in the + :class:`~torch.ao.quantization.MinMaxObserver` + """ + histogram: torch.Tensor + min_val: torch.Tensor + max_val: torch.Tensor + + def __init__( + self, + bins: int = 2048, + upsample_rate: int = 128, + dtype: torch.dtype = torch.quint8, + qscheme=torch.per_tensor_affine, + reduce_range=False, + quant_min=None, + quant_max=None, + factory_kwargs=None, + eps=torch.finfo(torch.float32).eps, + is_dynamic=False, + **kwargs, + ) -> None: + if not is_per_tensor(qscheme): + raise NotImplementedError( + "HistogramObserver's qscheme only support torch.per_tensor_symmetric \ + and torch.per_tensor_affine." + ) + if is_dynamic: + raise NotImplementedError( + "HistogramObserver doesn't support dynamic quantization" + ) + # bins: The number of bins used for histogram calculation. + super().__init__( + dtype=dtype, + qscheme=qscheme, + reduce_range=reduce_range, + quant_min=quant_min, + quant_max=quant_max, + factory_kwargs=factory_kwargs, + eps=eps, + is_dynamic=is_dynamic, + **kwargs + ) + factory_kwargs = torch.nn.factory_kwargs(factory_kwargs) + self.bins = bins + self.register_buffer("histogram", torch.zeros(self.bins, **factory_kwargs)) + self.register_buffer("min_val", torch.tensor(float("inf"), **factory_kwargs)) + self.register_buffer("max_val", torch.tensor(float("-inf"), **factory_kwargs)) + self.dst_nbins = 2 ** torch.iinfo(self.dtype).bits + self.upsample_rate = upsample_rate + + def _get_norm( + self, delta_begin: torch.Tensor, delta_end: torch.Tensor, density: torch.Tensor + ) -> torch.Tensor: + r""" + Compute the norm of the values uniformaly distributed between + delta_begin and delta_end. + Currently only L2 norm is supported. + + norm = density * (integral_{begin, end} x^2) + = density * (end^3 - begin^3) / 3 + """ + norm = ( + delta_end * delta_end * delta_end - delta_begin * delta_begin * delta_begin + ) / 3 + return density * norm + + def _compute_quantization_error(self, next_start_bin: int, next_end_bin: int): + r""" + Compute the quantization error if we use start_bin to end_bin as the + min and max to do the quantization. + """ + bin_width = (self.max_val.item() - self.min_val.item()) / self.bins + + dst_bin_width = bin_width * (next_end_bin - next_start_bin + 1) / self.dst_nbins + if dst_bin_width == 0.0: + return 0.0 + + src_bin = torch.arange(self.bins, device=self.histogram.device) + # distances from the beginning of first dst_bin to the beginning and + # end of src_bin + src_bin_begin = (src_bin - next_start_bin) * bin_width + src_bin_end = src_bin_begin + bin_width + + # which dst_bins the beginning and end of src_bin belong to? + dst_bin_of_begin = torch.clamp( + torch.div(src_bin_begin, dst_bin_width, rounding_mode='floor'), 0, self.dst_nbins - 1 + ) + dst_bin_of_begin_center = (dst_bin_of_begin + 0.5) * dst_bin_width + + dst_bin_of_end = torch.clamp( + torch.div(src_bin_end, dst_bin_width, rounding_mode='floor'), 0, self.dst_nbins - 1 + ) + density = self.histogram / bin_width + + norm = torch.zeros(self.bins, device=self.histogram.device) + + delta_begin = src_bin_begin - dst_bin_of_begin_center + delta_end = dst_bin_width / 2 + norm += self._get_norm(delta_begin, + torch.ones(self.bins, device=self.histogram.device) * delta_end, + density) + + norm += (dst_bin_of_end - dst_bin_of_begin - 1) * self._get_norm( + torch.tensor(-dst_bin_width / 2), torch.tensor(dst_bin_width / 2), density + ) + + dst_bin_of_end_center = dst_bin_of_end * dst_bin_width + dst_bin_width / 2 + + delta_begin = -dst_bin_width / 2 + delta_end = src_bin_end - dst_bin_of_end_center + norm += self._get_norm(torch.tensor(delta_begin), delta_end, density) + + return norm.sum().item() + + def _non_linear_param_search(self) -> Tuple[torch.Tensor, torch.Tensor]: + r"""Non-linear parameter search. + + An approximation for L2 error minimization for selecting min/max. + By selecting new min/max, we filter out outliers in input distribution. + This follows the implementation of NormMinimization::NonlinearQuantizationParamsSearch in + caffe2/quantization/server/norm_minimization.cc + """ + assert self.histogram.size()[0] == self.bins, "bins mismatch" + bin_width = (self.max_val - self.min_val) / self.bins + + # cumulative sum + total = torch.sum(self.histogram).item() + cSum = torch.cumsum(self.histogram, dim=0) + + stepsize = 1e-5 # granularity + alpha = 0.0 # lower bound + beta = 1.0 # upper bound + start_bin = 0 + end_bin = self.bins - 1 + norm_min = float("inf") + + while alpha < beta: + # Find the next step + next_alpha = alpha + stepsize + next_beta = beta - stepsize + + # find the left and right bins between the quantile bounds + l = start_bin + r = end_bin + while l < end_bin and cSum[l] < next_alpha * total: + l = l + 1 + while r > start_bin and cSum[r] > next_beta * total: + r = r - 1 + + # decide the next move + next_start_bin = start_bin + next_end_bin = end_bin + if (l - start_bin) > (end_bin - r): + # move the start bin + next_start_bin = l + alpha = next_alpha + else: + # move the end bin + next_end_bin = r + beta = next_beta + + if next_start_bin == start_bin and next_end_bin == end_bin: + continue + + # calculate the quantization error using next_start_bin and next_end_bin + norm = self._compute_quantization_error(next_start_bin, next_end_bin) + + if norm > norm_min: + break + norm_min = norm + start_bin = next_start_bin + end_bin = next_end_bin + + new_min = self.min_val + bin_width * start_bin + new_max = self.min_val + bin_width * (end_bin + 1) + return new_min, new_max + + def _adjust_min_max( + self, combined_min: torch.Tensor, combined_max: torch.Tensor, upsample_rate: int + ) -> Tuple[torch.Tensor, torch.Tensor, int, int]: + # We ensure that: + # (combined_max - combined_min)/(downsample_rate*Nbins) = (max - min)/(upsample_rate*Nbins) + # This allows us to have a common grid of resolution s, where we can align + # the input histogram + # start_idx maps min_val to the histogram bin index. + + # Compute the width of histogram bins is a straightforward solution, where + # hist_bin_width = (self.max_val - self.min_val) / (self.bins * upsample_rate) + # Underflow happens if the numerator is close to the smallest positive subnormal number of FP32 + # Therefore, we avoid such division operation. + downsample_rate = int( + torch.ceil( + (combined_max - combined_min) * upsample_rate / (self.max_val - self.min_val) + ).item() + ) + e = downsample_rate * (self.max_val - self.min_val) / upsample_rate - (combined_max - combined_min) + start_idx = int( + torch.round((self.min_val - combined_min) * self.bins * upsample_rate / (self.max_val - self.min_val)).item() + ) + combined_max = combined_max + e + combined_min = combined_min + return combined_min, combined_max, downsample_rate, start_idx + + def _combine_histograms( + self, + orig_hist: torch.Tensor, + new_hist: torch.Tensor, + upsample_rate: int, + downsample_rate: int, + start_idx: int, + Nbins: int, + ) -> torch.Tensor: + # First up-sample the histogram with new data by a factor of L + # This creates an approximate probability density thats piecewise constant + upsampled_histogram = new_hist.repeat_interleave(upsample_rate) + # Now insert the upsampled histogram into the output + # histogram, which is initialized with zeros. + # The offset at which the histogram is introduced is determined + # by the start index as the output histogram can cover a wider range + histogram_with_output_range = torch.zeros( + (Nbins * downsample_rate), device=orig_hist.device + ) + histogram_with_output_range[ + start_idx : Nbins * upsample_rate + start_idx + ] = upsampled_histogram + # Compute integral histogram, double precision is needed to ensure + # that there are no overflows + integral_histogram = torch.cumsum( + histogram_with_output_range, 0, dtype=torch.double + )[downsample_rate - 1 :: downsample_rate] + # Finally perform interpolation + shifted_integral_histogram = torch.zeros((Nbins), device=orig_hist.device) + shifted_integral_histogram[1:Nbins] = integral_histogram[0:-1] + interpolated_histogram = ( + integral_histogram - shifted_integral_histogram + ) / upsample_rate + orig_hist = orig_hist + interpolated_histogram.to(torch.float) + return orig_hist + + def forward(self, x_orig: torch.Tensor) -> torch.Tensor: + if x_orig.numel() == 0: + return x_orig + x = x_orig.detach() + min_val = self.min_val + max_val = self.max_val + same_values = min_val.item() == max_val.item() + is_uninitialized = min_val == float("inf") and max_val == float("-inf") + if is_uninitialized or same_values: + min_val, max_val = torch.aminmax(x) + self.min_val.resize_(min_val.shape) + self.min_val.copy_(min_val) + self.max_val.resize_(max_val.shape) + self.max_val.copy_(max_val) + assert ( + min_val.numel() == 1 and max_val.numel() == 1 + ), "histogram min/max values must be scalar." + torch.histc( + x, self.bins, min=min_val, max=max_val, out=self.histogram # type: ignore[arg-type] + ) + else: + new_min, new_max = torch.aminmax(x) + combined_min = torch.min(new_min, min_val) + combined_max = torch.max(new_max, max_val) + # combine the existing histogram and new histogram into 1 histogram + # We do this by first upsampling the histogram to a dense grid + # and then downsampling the histogram efficiently + ( + combined_min, + combined_max, + downsample_rate, + start_idx, + ) = self._adjust_min_max(combined_min, combined_max, self.upsample_rate) + assert ( + combined_min.numel() == 1 and combined_max.numel() == 1 + ), "histogram min/max values must be scalar." + + # TODO: For some reason, this is required for it to pass torchscript test + # combined_min and combined_max should already have requires_grad set to False + combined_min, combined_max = combined_min.detach(), combined_max.detach() + + combined_histogram = torch.histc( + x, self.bins, min=combined_min, max=combined_max # type: ignore[arg-type] + ) + if combined_min == min_val and combined_max == max_val: + combined_histogram += self.histogram + else: + combined_histogram = self._combine_histograms( + combined_histogram, + self.histogram, + self.upsample_rate, + downsample_rate, + start_idx, + self.bins, + ) + + self.histogram.detach_().resize_(combined_histogram.shape) + self.histogram.copy_(combined_histogram) + self.min_val.detach_().resize_(combined_min.shape) + self.min_val.copy_(combined_min) + self.max_val.detach_().resize_(combined_max.shape) + self.max_val.copy_(combined_max) + return x_orig + + @torch.jit.export + def calculate_qparams(self): + is_uninitialized = self.min_val == float("inf") and self.max_val == float( + "-inf" + ) + if is_uninitialized: + warnings.warn( + "must run observer before calling calculate_qparams.\ + Returning default scale and zero point " + ) + return torch.tensor([1.0], device=self.min_val.device.type), torch.tensor([0], device=self.min_val.device.type) + assert self.bins == len(self.histogram), ( + "The number of bins in histogram should be equal to the number of bins " + "supplied while making this observer" + ) + + new_min, new_max = self._non_linear_param_search() + + return self._calculate_qparams(new_min, new_max) + + def _save_to_state_dict(self, destination, prefix, keep_vars): + super()._save_to_state_dict(destination, prefix, keep_vars) + destination[prefix + "min_val"] = self.min_val + destination[prefix + "max_val"] = self.max_val + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 3: + # if min_val and max_val are not initialized, update their shape + # to account for the differences between v2 and v3 + min_val_name, max_val_name = prefix + "min_val", prefix + "max_val" + if min_val_name in state_dict: + if state_dict[min_val_name].shape == torch.Size([0]): + state_dict[min_val_name] = torch.tensor(float("inf")) + if max_val_name in state_dict: + if state_dict[max_val_name].shape == torch.Size([0]): + state_dict[max_val_name] = torch.tensor(float("-inf")) + + local_state = ["min_val", "max_val"] + for name in local_state: + key = prefix + name + if key in state_dict: + val = state_dict[key] + setattr(self, name, val) + elif strict: + missing_keys.append(key) + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def extra_repr(self): + return f"min_val={self.min_val}, max_val={self.max_val}" + + +class FixedQParamsObserver(ObserverBase): + r""" + Observer that simulates quantize and dequantize with fixed + quantization parameters in training time. Only per tensor + quantization is supported. + + Args: + `scale` (float): fixed scale for the observer + `zero_point` (int): fixed zero point for the observer + `dtype`, `qscheme`, `quant_min`, `quant_max` + """ + + scale: torch.Tensor + zero_point: torch.Tensor + + def __init__( + self, + scale, + zero_point, + dtype=torch.quint8, + qscheme=torch.per_tensor_affine, + quant_min=0, + quant_max=255, + is_dynamic=False, + **kwargs, + ): + if is_dynamic: + raise NotImplementedError( + "FixedQParamsObserver doesn't support dynamic quantization" + ) + super().__init__(dtype=dtype, is_dynamic=is_dynamic, **kwargs) + self.quant_min = quant_min + self.quant_max = quant_max + self.register_buffer('scale', torch.tensor([scale], dtype=torch.float)) + self.register_buffer('zero_point', torch.tensor([zero_point], dtype=torch.int)) + self.dtype = dtype + self.qscheme = qscheme + + def forward(self, X): + return X + + @torch.jit.export + def calculate_qparams(self): + return self.scale, self.zero_point + + +class PlaceholderObserver(ObserverBase): + r""" + Observer that doesn't do anything and just passes its configuration to the + quantized module's ``.from_float()``. + + Can be used for quantization to float16 which doesn't require determining + ranges. + + Args: + dtype: dtype argument to the `quantize` node needed to implement the + reference model spec. + quant_min: minimum value in quantized domain (TODO: align behavior with other observers) + quant_max: maximum value in quantized domain + custom_op_name: (temporary) specify this observer for an operator that doesn't require any observation + (Can be used in Graph Mode Passes for special case ops). + compute_dtype (deprecated): if set, marks the future quantize function to use + dynamic quantization instead of static quantization. + This field is deprecated, use `is_dynamic=True` instead. + is_dynamic: if True, the `quantize` function in the reference model + representation taking stats from this observer instance will + use dynamic quantization. + """ + + def __init__( + self, dtype=torch.float32, custom_op_name="", compute_dtype=None, + quant_min=None, quant_max=None, qscheme=None, eps=None, + is_dynamic=False, + ) -> None: + super().__init__(dtype=dtype, is_dynamic=is_dynamic) + if qscheme is None: + qscheme = torch.per_tensor_affine + if eps is None: + eps = torch.finfo(torch.float32).eps + + # dtype of input of the target operator, e.g. for dynamic quantization + # ops, the dtype will be float32 + self.dtype = dtype + self.qscheme = qscheme + self.quant_min = quant_min + self.quant_max = quant_max + self.eps = eps + self.custom_op = custom_op_name + # used for configuration of computation type for dynamic quantization + if compute_dtype: + is_dynamic = True + warnings.warn( + "Please use `is_dynamic` instead of `compute_dtype`. \ + `compute_dtype` will be deprecated in a future release \ + of PyTorch." + ) + + def forward(self, x): + return x + + @torch.jit.export + def extra_repr(self): + return f"dtype={self.dtype}, is_dynamic={self.is_dynamic}" + + @torch.jit.export + def calculate_qparams(self): + raise Exception( + "calculate_qparams should not be called for PlaceholderObserver" + ) + + +class RecordingObserver(ObserverBase): + r""" + The module is mainly for debug and records the tensor values during runtime. + + Args: + dtype: Quantized data type + qscheme: Quantization scheme to be used + reduce_range: Reduces the range of the quantized data type by 1 bit + """ + __annotations__ = {"tensor_val": List[Optional[torch.Tensor]]} + + def __init__(self, dtype=torch.quint8): + super().__init__(dtype=dtype, is_dynamic=False) # type: ignore[call-arg] + self.tensor_val = [] + + def forward(self, x): + self.tensor_val.append(x.clone()) + return x + + @torch.jit.export + def calculate_qparams(self): + raise Exception("calculate_qparams should not be called for RecordingObserver") + + @torch.jit.export + def get_tensor_value(self): + return self.tensor_val + + +class NoopObserver(ObserverBase): + r""" + Observer that doesn't do anything and just passes its configuration to the + quantized module's ``.from_float()``. + + Primarily used for quantization to float16 which doesn't require determining + ranges. + + Args: + dtype: Quantized data type + custom_op_name: (temporary) specify this observer for an operator that doesn't require any observation + (Can be used in Graph Mode Passes for special case ops). + """ + + def __init__(self, dtype=torch.float16, custom_op_name="") -> None: + super().__init__(dtype=dtype, is_dynamic=False) + self.dtype = dtype + self.custom_op = custom_op_name + + def forward(self, x): + return x + + @torch.jit.export + def calculate_qparams(self): + raise Exception("calculate_qparams should not be called for NoopObserver") + +class ReuseInputObserver(ObserverBase): + r""" This observer is used when we want to reuse the observer from the operator + that produces the input Tensor, typically used for operators like reshape, e.g. + ``` + x0 = ... + x1 = x0.reshape() + ``` + if we configure x0 to be observed by some observer, let's say MinMaxObserver, + and reshape is configured with ReuseInputObserver, we'll reuse the observer instance + for x0 for x1 (output of reshape). If x0 is not observed, we also won't observe x1. + + Note: this is only enabled in FX Graph Mode Quantization + """ + def __init__(self): + super().__init__(torch.quint8, is_dynamic=False) + + def forward(self, x): + return x + + @torch.jit.export + def calculate_qparams(self): + raise Exception("calculate_qparams should not be called for ReuseInputObserver") + +def _is_observer_script_module(mod, obs_type_name): + """Returns true if given mod is an instance of Observer script module.""" + if isinstance(mod, torch.jit.RecursiveScriptModule): + # qualified name looks like '__torch__.torch.ao.quantization.observer.___torch_mangle_2.MinMaxObserver' + suffix = mod._c.qualified_name.split(".", 1)[1] + name = re.sub(r"\.___torch_mangle_\d+", "", suffix) + return obs_type_name in name + return False + + +def _is_activation_post_process(module): + return ( + isinstance(module, (torch.ao.quantization.ObserverBase, + torch.ao.quantization.FakeQuantizeBase)) or _is_observer_script_module(module, "quantization.observer") + ) + + +def _is_per_channel_script_obs_instance(module): + if isinstance(module, torch.jit.RecursiveScriptModule): + return _is_observer_script_module( + module, "quantization.observer.PerChannelMinMaxObserver" + ) or _is_observer_script_module( + module, "quantization.observer.MovingAveragePerChannelMinMaxObserver" + ) + return False + + +def get_observer_state_dict(mod): + r""" + Returns the state dict corresponding to the observer stats. + Traverse the model state_dict and extract out the stats. + """ + od = OrderedDict() + if isinstance(mod, torch.jit.RecursiveScriptModule): + for k, v in mod.state_dict().items(): + if "observer" in k: + od[k] = v + else: + # path for GraphModule and nn.Module (eager mode) + for k, v in mod.state_dict().items(): + if "activation_post_process" in k: + od[k] = v + od._metadata = mod.state_dict()._metadata # type: ignore[attr-defined] + return od + + +def load_observer_state_dict(mod, obs_dict): + r""" + Given input model and a state_dict containing model observer stats, + load the stats back into the model. The observer state_dict can be saved + using torch.ao.quantization.get_observer_state_dict + """ + missing_keys: List[str] = [] + unexpected_keys: List[str] = [] + for name, module in mod.named_modules(): + prefix = name + "." + if _is_activation_post_process(module): + if _is_per_channel_script_obs_instance(module): + # For per-channel observers we need to call a custom load_from_state_dict to resize the tensor. + # However this is not called when the module is scripted and we end up calling the default one in module.py + module._load_from_state_dict_script( + obs_dict, prefix, {}, True, missing_keys, unexpected_keys, [] + ) + else: + module._load_from_state_dict( + obs_dict, prefix, {}, False, missing_keys, unexpected_keys, [] + ) + for k in missing_keys: + if "observer" in k or "activation_post_process" in k: + raise Exception(f"Missing keys for observer {k} in state_dict") + for k in unexpected_keys: + if "observer" in k or "activation_post_process" in k: + raise Exception(f"Unexpected keys for observer {k} in state_dict") + + +# Restrict activations to be in the range (0,127) +default_observer = MinMaxObserver.with_args(quant_min=0, quant_max=127) +""" +Default observer for static quantization, usually used for debugging. +""" + +default_placeholder_observer = PlaceholderObserver +""" +Default placeholder observer, usually used for quantization to torch.float16. +""" + +default_debug_observer = RecordingObserver +""" +Default debug-only observer. +""" + +default_weight_observer = MinMaxObserver.with_args( + dtype=torch.qint8, qscheme=torch.per_tensor_symmetric +) +""" +Default weight observer. +""" + +weight_observer_range_neg_127_to_127 = MinMaxObserver.with_args( + dtype=torch.qint8, qscheme=torch.per_tensor_symmetric, + quant_min=-127, quant_max=127, eps=2 ** -12) +""" +Symmetric weight observer with the 8-bit values restricted to [-127, +127], excluding -128. +""" + +default_histogram_observer = HistogramObserver.with_args(quant_min=0, quant_max=127) +""" +Default histogram observer, usually used for PTQ. +""" + +default_per_channel_weight_observer = PerChannelMinMaxObserver.with_args( + dtype=torch.qint8, qscheme=torch.per_channel_symmetric +) +""" +Default per-channel weight observer, usually used on backends where per-channel +weight quantization is supported, such as `fbgemm`. +""" + +per_channel_weight_observer_range_neg_127_to_127 = PerChannelMinMaxObserver.with_args( + dtype=torch.qint8, qscheme=torch.per_channel_symmetric, + quant_min=-127, quant_max=127, eps=2 ** -12) +""" +Per-channel, symmetric weight observer with the 8-bit values restricted to [-127, +127], excluding -128. +""" + +default_dynamic_quant_observer = PlaceholderObserver.with_args( + dtype=torch.quint8, quant_min=0, quant_max=255, is_dynamic=True, +) +""" +Default observer for dynamic quantization. +""" + +default_float_qparams_observer = PerChannelMinMaxObserver.with_args( + dtype=torch.quint8, qscheme=torch.per_channel_affine_float_qparams, ch_axis=0 +) +""" +Default observer for a floating point zero-point. +""" + +default_float_qparams_observer_4bit = PerChannelMinMaxObserver.with_args( + dtype=torch.quint4x2, qscheme=torch.per_channel_affine_float_qparams, ch_axis=0 +) +""" +Default observer for a floating point zero-point and 4 bit activations. +""" + +# TODO(future PR): remove these defaults and enforce activation functions +# to explicitly specify their output range +default_fixed_qparams_range_neg1to1_observer = FixedQParamsObserver.with_args( + scale=2.0 / 256.0, zero_point=128, dtype=torch.quint8, quant_min=0, quant_max=255) +default_fixed_qparams_range_0to1_observer = FixedQParamsObserver.with_args( + scale=1.0 / 256.0, zero_point=0, dtype=torch.quint8, quant_min=0, quant_max=255) +# TODO: the following 2 variables are kept for backwards compatibility; remove after a few releases +default_symmetric_fixed_qparams_observer = default_fixed_qparams_range_neg1to1_observer +default_affine_fixed_qparams_observer = default_fixed_qparams_range_0to1_observer + +""" +Default observers for fixed qparams operations. +""" + +default_reuse_input_observer = ReuseInputObserver +""" +Default observer for operators like reshape that reuses the observer of input to +the operator +""" diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__init__.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f87ae9dd11fd9cd231158fcaa2717ce50de8849 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/duplicate_dq_pass.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/duplicate_dq_pass.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f8b38fff4736d00684b651e7b5a0425565f8153 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/duplicate_dq_pass.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/eval_utils.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/eval_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47c3547b5e4a86b536ee8e18772acdb98f67bd25 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/eval_utils.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/prepare.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/prepare.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68a01252dd1a0878c37720dd79f1295b45cacb19 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/prepare.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/utils.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01b451d66c86eed5d3cccc9251f928dccf40d1c9 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/utils.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/eval_utils.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/eval_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7699e61ed6d5a0bef6e0f6becd6bb0519c19f50d --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/eval_utils.py @@ -0,0 +1,112 @@ +import torch +import torch.nn.functional as F + + +def _replace_dropout_for_eval(m: torch.fx.GraphModule): + """ + Replace the aten training dropout pattern with a noop, intended for eval. + + For models with dropout torch ops (nn.Dropout, F.dropout), calling model.eval() + effectively turns these dropout ops into noops. For exported models, however, + this is not done automatically, since the aten dropout patterns previously generated + for training remain in the graph. Here we rewrite these dropout patterns with noops + to avoid incorrectly applying further dropout during eval. + + See https://github.com/pytorch/pytorch/issues/103681. + """ + # Avoid circular dependencies + from .utils import get_aten_graph_module + + # Needed to ensure subgraph matches are self-contained + m.graph.eliminate_dead_code() + m.recompile() + + for inplace in [False, True]: + + def dropout_train(x): + return F.dropout(x, p=0.5, training=True, inplace=inplace) + + def dropout_eval(x): + return F.dropout(x, p=0.5, training=False, inplace=inplace) + + example_inputs = (torch.randn(1),) + match_pattern = get_aten_graph_module(dropout_train, example_inputs) + replacement_pattern = get_aten_graph_module(dropout_eval, example_inputs) + + from torch.fx.subgraph_rewriter import replace_pattern_with_filters + + replace_pattern_with_filters( + m, + match_pattern, + replacement_pattern, + match_filters=[], + ignore_literals=True, + ) + m.recompile() + + +def _replace_batchnorm_for_eval(m: torch.fx.GraphModule): + # TODO(Leslie): This function still fails to support custom momentum and eps value. + # Enable this support in future updates. + + # Avoid circular dependencies + from .utils import get_aten_graph_module + + # Needed to ensure subgraph matches are self-contained + m.graph.eliminate_dead_code() + m.recompile() + + def bn_train( + x: torch.Tensor, + bn_weight: torch.Tensor, + bn_bias: torch.Tensor, + bn_running_mean: torch.Tensor, + bn_running_var: torch.Tensor, + ): + return F.batch_norm( + x, bn_running_mean, bn_running_var, bn_weight, bn_bias, training=True + ) + + def bn_eval( + x: torch.Tensor, + bn_weight: torch.Tensor, + bn_bias: torch.Tensor, + bn_running_mean: torch.Tensor, + bn_running_var: torch.Tensor, + ): + return F.batch_norm( + x, bn_running_mean, bn_running_var, bn_weight, bn_bias, training=False + ) + + example_inputs = ( + torch.randn(1, 1, 3, 3), # x + torch.randn(1), # bn_weight + torch.randn(1), # bn_bias + torch.randn(1), # bn_running_mean + torch.randn(1), # bn_running_var + ) + match_pattern = get_aten_graph_module(bn_train, example_inputs) + replacement_pattern = get_aten_graph_module(bn_eval, example_inputs) + from torch.fx.subgraph_rewriter import replace_pattern_with_filters + + replace_pattern_with_filters( + m, + match_pattern, + replacement_pattern, + match_filters=[], + ignore_literals=True, + ) + m.recompile() + + +# TODO: also support move_exported_model_to_train +def _move_exported_model_to_eval(model: torch.fx.GraphModule): + """ + Move an exported GraphModule to eval mode. + + This is equivalent to model.eval() but only for certain special ops like dropout, batchnorm. + QAT users should call this before performing inference on the model. + """ + _replace_dropout_for_eval(model) + _replace_batchnorm_for_eval(model) + return model diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/generate_numeric_debug_handle.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/generate_numeric_debug_handle.py new file mode 100644 index 0000000000000000000000000000000000000000..a6ca1f71b7d20c3d230f0ccd20924d2c3ef02d7a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/generate_numeric_debug_handle.py @@ -0,0 +1,17 @@ +from torch.fx import GraphModule, Node + +__all__ = ["generate_numeric_debug_handle"] + + +def generate_numeric_debug_handle(graph_module: GraphModule) -> None: + unique_id = 0 + for node in graph_module.graph.nodes: + if node.op == "call_function": + node.meta["numeric_debug_handle"] = {} + for arg in node.args: + if isinstance(arg, Node): + node.meta["numeric_debug_handle"][arg] = unique_id + unique_id += 1 + + node.meta["numeric_debug_handle"]["output"] = unique_id + unique_id += 1 diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/graph_utils.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/graph_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2390bafed286814a6e86c640a2862ebfcfa69278 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/graph_utils.py @@ -0,0 +1,109 @@ +import itertools +from typing import Any, List, OrderedDict, Set, Optional, Callable +import operator +from torch.fx import Node + +import torch + +from torch.fx.passes.utils.source_matcher_utils import ( + check_subgraphs_connected, + get_source_partitions, + SourcePartition, +) + +__all__ = [ + "find_sequential_partitions", + "get_equivalent_types", + "update_equivalent_types_dict", +] + +_EQUIVALENT_TYPES: List[Set] = [ + {torch.nn.Conv1d, torch.nn.functional.conv1d}, + {torch.nn.Conv2d, torch.nn.functional.conv2d}, + {torch.nn.AdaptiveAvgPool2d, torch.nn.functional.adaptive_avg_pool2d}, + {torch.nn.ReLU, torch.nn.functional.relu, torch.nn.functional.relu_}, + {torch.nn.BatchNorm2d, torch.nn.functional.batch_norm}, + {torch.nn.Hardtanh, torch.nn.functional.hardtanh, torch.nn.functional.hardtanh_}, + {torch.add, operator.add, operator.iadd, "add", "add_"}, + {torch.mul, operator.mul, operator.imul, "mul", "mul_"}, +] + + +def _create_equivalent_types_dict(): + _DICT = {} + for values in _EQUIVALENT_TYPES: + for v in values: + _DICT[v] = list(values) + return _DICT + + +_EQUIVALENT_TYPES_DICT = _create_equivalent_types_dict() + +def get_equivalent_types() -> List[Set]: + return _EQUIVALENT_TYPES + +def update_equivalent_types_dict(customized_equivalent_types=None): + """Help function for user who wants to customize the _EQUIVALENT_TYPES and _EQUIVALENT_TYPES_DICT. + When customized_equivalent_types passes in, + re-generate _EQUIVALENT_TYPES and _EQUIVALENT_TYPES_DICT. + """ + if customized_equivalent_types is None: + raise ValueError("customized_equivalent_types should not be None") + global _EQUIVALENT_TYPES + global _EQUIVALENT_TYPES_DICT + _EQUIVALENT_TYPES = customized_equivalent_types + _EQUIVALENT_TYPES_DICT = _create_equivalent_types_dict() + +def _partitions_sequential(partitions: List[SourcePartition]): + prev_partition = None + for partition in partitions: + if prev_partition is not None and not check_subgraphs_connected( + prev_partition, partition + ): + return False + prev_partition = partition + return True + + +def _get_matching_types(partition_type): + matching_types = [partition_type] + if partition_type in _EQUIVALENT_TYPES_DICT: + matching_types.extend(_EQUIVALENT_TYPES_DICT[partition_type]) + return matching_types + + +def _valid_type_sequence(partition_types: List[Any]): + partition_types_set = set() # type: ignore[var-annotated] + for partition_type in partition_types: + matching_types = _get_matching_types(partition_type) + matching_types_set = set(matching_types) + if len(partition_types_set & matching_types_set) > 0: + return False + partition_types_set |= matching_types_set + return True + + +def find_sequential_partitions( + gm: torch.fx.GraphModule, + partition_types: List[Any], + include_functional_equivalent=True, + filter_fn: Optional[Callable[[Node], bool]] = None, +): + if not _valid_type_sequence(partition_types): + raise ValueError( + f"Invalid partition types: {partition_types}. Each type in the sequence must be unique" + ) + + typed_partitions: OrderedDict[Any, List[SourcePartition]] = OrderedDict() + for partition_type in partition_types: + types_to_match = _get_matching_types(partition_type) + partitions = get_source_partitions(gm.graph, types_to_match, filter_fn) + typed_partitions[partition_type] = list(itertools.chain(*partitions.values())) + + typed_partitions_list = list(typed_partitions.values()) + fusion_candidates = itertools.product(*typed_partitions_list) + fused_partitions = [] + for candidate in fusion_candidates: + if _partitions_sequential(candidate): # type: ignore[arg-type] + fused_partitions.append(candidate) + return fused_partitions diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/prepare.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..ed7816d93c6b7bc78f0dc436b89bd348c80b60b0 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/prepare.py @@ -0,0 +1,476 @@ +import torch +from torch._subclasses import FakeTensor +from torch.ao.quantization.fx.prepare import ( + _insert_obs_or_fq, + _save_state, + _is_activation_post_process_node, + _create_obs_or_fq_from_qspec, +) +from torch.fx import ( + GraphModule, + Graph, + Node, +) +from torch.fx.node import Argument + +from torch.ao.quantization import QConfigMapping +from torch.ao.quantization.qconfig import QConfigAny +from torch.ao.quantization.fx.custom_config import PrepareCustomConfig +from typing import Dict, Tuple, Union, Any, Optional +from torch.ao.quantization.quantizer import ( + EdgeOrNode, + SharedQuantizationSpec, + QuantizationSpecBase, +) +from torch.ao.quantization import ObserverOrFakeQuantize + +# TODO: make pt2e folder private? +__all__ = [ + "prepare", +] + + +def _find_root_edge_or_node(edge_or_node: EdgeOrNode, shared_with_map: Dict[EdgeOrNode, EdgeOrNode]) -> EdgeOrNode: + """Find the root node for the sharing tree + Args: + edge_or_node: edge/node that we want to find the root + shared_with_map: each edge/node points to the parent, the root node will points to itself + + Returns: + root edge/node + """ + parent = shared_with_map[edge_or_node] + if parent == edge_or_node: + return edge_or_node + root = _find_root_edge_or_node(parent, shared_with_map) + # path compression + shared_with_map[edge_or_node] = root + return root + +def _union(parent: EdgeOrNode, child: EdgeOrNode, shared_with_map: Dict[EdgeOrNode, EdgeOrNode]) -> None: + """Merge the subtree for `child` with `parent`, the order is important here + """ + root_parent = _find_root_edge_or_node(parent, shared_with_map) + root_child = _find_root_edge_or_node(child, shared_with_map) + # union the two trees by pointing the root of child to root of parent + shared_with_map[root_child] = root_parent + +def _update_shared_with(child: EdgeOrNode, qspec: QuantizationSpecBase, shared_with_map: Dict[EdgeOrNode, EdgeOrNode]): + """Update the `shared_with_map` based on the qspec, this applies the `SharedQuantizationSpec` + configuration and established the relationship between `edge_or_node` with the edge/node that it + is pointing to, we'll use this information in the end to get the group id + """ + if isinstance(qspec, SharedQuantizationSpec): + parent = qspec.edge_or_node + # we point from edge_or_node to the node that it is sharing_with, e.g. + # qspec for a = SharedQuantizationSpec(b) means `a` points to `b` + _union(parent, child, shared_with_map) + +def _unwrap_shared_qspec( + qspec: QuantizationSpecBase, + edge_or_node_to_qspec: Dict[EdgeOrNode, QuantizationSpecBase], + shared_with_map: Dict[EdgeOrNode, EdgeOrNode] +) -> QuantizationSpecBase: + """Unwraps qspec to get the final root qspec (non SharedQuantizationSpec) + if qspec is SharedQuantizationSpec + (1). tries to find the root edge or node for the node that the qspec points to + (2). recursively find the root qspec based on the qspec for the root node + """ + if isinstance(qspec, SharedQuantizationSpec): + sharing_with = qspec.edge_or_node + root = _find_root_edge_or_node(sharing_with, shared_with_map) + qspec = edge_or_node_to_qspec[root] + return _unwrap_shared_qspec(qspec, edge_or_node_to_qspec, shared_with_map) + return qspec + +def _has_same_dtype(qspec_a: QuantizationSpecBase, qspec_b: QuantizationSpecBase): + return ( + hasattr(qspec_a, "dtype") and + hasattr(qspec_b, "dtype") and + qspec_a.dtype == qspec_b.dtype + ) + +def _has_same_is_dynamic(qspec_a: QuantizationSpecBase, qspec_b: QuantizationSpecBase): + return ( + hasattr(qspec_a, "is_dynamic") and + hasattr(qspec_b, "is_dynamic") and + qspec_a.is_dynamic == qspec_b.is_dynamic + ) + +def _get_edge_or_node_to_qspec(model: torch.fx.GraphModule) -> Dict[EdgeOrNode, QuantizationSpecBase]: + """Get a map from EdgeOrNode to quantization spec based on annotations on the nodes + """ + edge_or_node_to_qspec: Dict[EdgeOrNode, QuantizationSpecBase] = {} + for n in model.graph.nodes: + if hasattr(n, "meta") and "quantization_annotation" in n.meta: + qa = n.meta["quantization_annotation"] + for input_to_n, qspec in qa.input_qspec_map.items(): + input_edge = (input_to_n, n) + edge_or_node_to_qspec[input_edge] = qspec + if qa.output_qspec is not None: + output_node = n + qspec = qa.output_qspec + edge_or_node_to_qspec[output_node] = qspec + return edge_or_node_to_qspec + +def _union_input_edge_with(input_edge, input_edge_root_qspec, edge_or_node, edge_or_node_to_qspec, shared_with_map): + """Union input edge with another edge or node, used in implicit sharing to point the current input + edge to other user edges of the producer node, or the output of producer node since these are + referring to the same Tensor + """ + root_qspec = None + if edge_or_node in edge_or_node_to_qspec: + qspec = edge_or_node_to_qspec[edge_or_node] + root_qspec = _unwrap_shared_qspec(qspec, edge_or_node_to_qspec, shared_with_map) + # TODO: add assertions for types of root qspecs + if ( + root_qspec is not None and + _has_same_dtype(root_qspec, input_edge_root_qspec) and + _has_same_is_dynamic(root_qspec, input_edge_root_qspec) + ): + # the input arg to the node should reuse the existing output observer for arg + # since dtype is the same (we may want to extend this to be a more strict check + # in the future) + # so we point from `input_edge` to `arg` (output of the argument) + _union(edge_or_node, input_edge, shared_with_map) + + +def _get_edge_or_node_to_group_id(edge_or_node_to_qspec: Dict[EdgeOrNode, QuantizationSpecBase]) -> Dict[EdgeOrNode, int]: + """Map from edge/node to the group ID, generated from quantization annotations, + edge/node with the same group ID should use the same observer/fake_quant instance + + This is applying SharedQuantizationSpec configuration and map each edge/node to a group + There is another implicit sharing that's built in the quantization, when we have the following: + * op1 -> op2 + * output of op1: int8_qspec + * (op1 -> op2) input edge: int8_qspec + we'll assume sharing between the output of op1 and input of (op1 -> op2) since these are the same Tensor. + + Figuring out the correct group ID for all edge/node is a standard union find problem: + https://www.geeksforgeeks.org/introduction-to-disjoint-set-data-structure-or-union-find-algorithm/ + + Args: + edge_or_node_to_qspec: Dictionary from edge_or_node to the qspec, derived from annotations + Returns: + edge_or_node_to_group_id: Dictionary from edge_or_node to group_id (int), all edge or node that + belongs to the same group should have the same id + + Example: + op2 -> cat1 -> cat2 + op1 / / + op3 + edge_or_node_to_qspec: { + op1: int8_qspec, + op2: int8_qspec, + (op1, cat1): int8_qspc, + (op2, cat1): SharedQuantizationSpec((op1, cat1)), + cat1: SharedQuantizationSpec((op1, cat1)), + (op3, cat2): int8_qspec, + (cat1, cat2): SharedQuantizationSpec((op3, cat2)), + cat2: SharedQuantizationSpec((op3, cat2)), + } + + edge_or_node_to_group_id = _get_edge_or_node_to_group_id(edge_or_node_to_qspec) + edge_or_node_to_group_id: { + op1: 1, + op2: 1, + (op1, cat1): 1, + (op2, cat1): 1, + cat1: 1, + (op3, cat2): 1, + (cat1, cat2): 1, + cat2: 1, + } + # everything are in the same group because (cat1) and (cat1, cat2) are implicitly shared, which + # connects the two sharing group around cat1 and cat2 op due to transitive sharing + """ + # means the observer of key should be shared with observer with value, by default it will + # be shared with itself + shared_with_map: Dict[EdgeOrNode, EdgeOrNode] = {k: k for k in edge_or_node_to_qspec.keys()} + for edge_or_node, qspec in edge_or_node_to_qspec.items(): + if isinstance(edge_or_node, torch.fx.Node): + output_node = edge_or_node + _update_shared_with(output_node, qspec, shared_with_map) + else: + input_edge = edge_or_node + input_edge_root_qspec = _unwrap_shared_qspec(qspec, edge_or_node_to_qspec, shared_with_map) + + assert isinstance(input_edge, tuple) + arg, n = input_edge + if n.meta["quantization_annotation"].allow_implicit_sharing: + # NOTE: the order is important here, we first share with other users and then share with previous + # output because the reverse order could cause circular dependency + # e.g node1 -> node2 + # \ -> node3 + # when processing (node1, node2), if we first point (node1, node2) to node1 + # Step 1. shared_map = {(node1, node2): node1} + # Step 2. after that, we point the (node1, node2) to its other user (node1, node3) , + # which means shared_map = {(node1, node2): node1, node1: (node1, node3)} + # because we will point the root of (node1, node2) (in this case node1) to the root of (node1, node3) + # Step 3. and when we process (node1, node3), it can try to point to node1 as well, then we'll + # have a circular dependency + # the following order works around this issue, but this does not allow arbitrary configuration + # of sharing so it might break in a different case in the future, when it breaks + # quantizer writer can check the notes here to debug the issue + + # sharing with other users of the producer node + # (arg, user) + for user in arg.users: + if user is n: + continue + arg_to_user_edge = (arg, user) + _union_input_edge_with( + input_edge, + input_edge_root_qspec, + arg_to_user_edge, + edge_or_node_to_qspec, + shared_with_map + ) + + # sharing with output of producer node + _union_input_edge_with(input_edge, input_edge_root_qspec, arg, edge_or_node_to_qspec, shared_with_map) + + _update_shared_with(input_edge, qspec, shared_with_map) + + # now that we get the sharing relations between all edges and nodes, we can assingn group ids + cur_group_id = 0 + edge_or_node_to_group_id: Dict[EdgeOrNode, int] = {} + for edge_or_node in shared_with_map.keys(): + root = _find_root_edge_or_node(edge_or_node, shared_with_map) + if root not in edge_or_node_to_group_id: + edge_or_node_to_group_id[root] = cur_group_id + cur_group_id += 1 + edge_or_node_to_group_id[edge_or_node] = edge_or_node_to_group_id[root] + + return edge_or_node_to_group_id + +def _get_obs_or_fq_map( + edge_or_node_to_group_id: Dict[EdgeOrNode, int], + edge_or_node_to_qspec: Dict[EdgeOrNode, QuantizationSpecBase], + is_qat: bool +) -> Dict[EdgeOrNode, ObserverOrFakeQuantize]: + """Generates the EdgeOrNode to observer/fake_quant instances + Makes sure that for EdgeOrNode that has the same group_id should have the same observer or fake quant + instances + """ + obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize] = {} + group_id_to_obs_or_fq: Dict[int, ObserverOrFakeQuantize] = {} + for edge_or_node, qspec in edge_or_node_to_qspec.items(): + group_id = edge_or_node_to_group_id[edge_or_node] + if group_id not in group_id_to_obs_or_fq: + # TODO: maybe edge_or_node_to_qspec should be edge_or_node_to_root_qspec, this will simplify + # the implementation for _create_obs_or_fq_from_qspec + group_id_to_obs_or_fq[group_id] = _create_obs_or_fq_from_qspec(qspec, obs_or_fq_map, is_qat) + obs_or_fq_map[edge_or_node] = group_id_to_obs_or_fq[group_id] + return obs_or_fq_map + +def _maybe_insert_input_observer_for_arg_or_kwarg( + node: Union[Node, Any], + arg: Argument, + qconfig: QConfigAny, + model: torch.nn.Module, + named_modules: Dict[str, torch.nn.Module], + obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize], + is_qat: bool, +) -> Argument: + """ + Given a `node` and an `arg`, inserts an input observer between + `node` and `arg` if necessary. + """ + # for ops such as torch.cat([x0, x1]), + # traverse through the list + if isinstance(arg, (list, tuple)): + new_arg_to_return = [] + for inner_arg in arg: + new_inner_arg = _maybe_insert_input_observer_for_arg_or_kwarg( + node, inner_arg, qconfig, model, named_modules, obs_or_fq_map, is_qat, + ) + new_arg_to_return.append(new_inner_arg) + return type(arg)(new_arg_to_return) + + if not isinstance(arg, Node): + return arg + assert isinstance(arg, Node) + # default (no observer) + new_arg = arg + + # find the original `arg` node to the current node, skipping inserted observer/fake_quant nodes + original_arg = arg + while _is_activation_post_process_node(original_arg, named_modules): + original_arg = original_arg.args[0] # type: ignore[assignment] + assert isinstance(original_arg, Node), f"expect original argument to be a Node, but got: {type(original_arg)}" + + input_edge = (original_arg, node) + if input_edge not in obs_or_fq_map: + return new_arg + # input_edge needs to be observed + input_edge_obs_or_fq = obs_or_fq_map[input_edge] + if input_edge_obs_or_fq is None: + return new_arg + + arg_as_output_obs_or_fq = obs_or_fq_map.get(original_arg, None) + # the arg is observed as the output and is using the same instance as the input_edge + # we'll reuse the inserted observer/fake_quant + if arg_as_output_obs_or_fq is not None and id(arg_as_output_obs_or_fq) == id(input_edge_obs_or_fq): + return new_arg + + # otherwise, we'll insert a new observer/fake_quant node + + existing_obs_node = None + # skip inserting new observers if the same observer instance is inserted before for another user + # Example: + # conv1 -> obs1 -> existing_obs -> conv2 + # \ -> conv3 + # + # instead of inserting new observers we will have: + # conv1 -> obs1 -> existing_obs -> conv2 + # \ -> conv3 + for maybe_obs_node in arg.users.keys(): + if not _is_activation_post_process_node(maybe_obs_node, named_modules): + continue + maybe_obs_mod = named_modules[maybe_obs_node.target] # type: ignore[index] + if id(maybe_obs_mod) == id(input_edge_obs_or_fq): + return maybe_obs_node + + new_arg = _insert_obs_or_fq(arg, input_edge_obs_or_fq, model, named_modules, model.graph) + return new_arg + +def _maybe_insert_input_observers_for_node( + node: Node, + qconfig: QConfigAny, + model: torch.nn.Module, + named_modules: Dict[str, torch.nn.Module], + obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize], + is_qat: bool, +) -> None: + """ + If needed, inserts observers to the input args and kwargs of `node`. + Note: modifies `node` inplace. + + For example, if cur_node needs an observer after prev_node, we change from + + prev_node -> cur_node + + To + + prev_node -> obs -> cur_node + + """ + # Look through every input arg. If that arg's target dtype does not + # match the current node's target dtype, insert an observer. + new_args = [] + for arg in node.args: + new_arg = _maybe_insert_input_observer_for_arg_or_kwarg( + node, arg, qconfig, model, named_modules, obs_or_fq_map, is_qat, + ) + new_args.append(new_arg) + + # Clone has a memory_format kwarg and zeros_like has a pin_memory kwarg + # that persist in exported graph. This is just a work around for these. + assert ( + node.target == torch.ops.aten.clone.default or + node.target == torch.ops.aten.zeros_like.default or + len(node.kwargs) == 0 + ), " expecting kwargs for aten op IR to be empty" + + # assign the new args to the node, inplace + node.args = tuple(new_args) + +def _maybe_insert_output_observer_for_node( + node: Node, + model: torch.nn.Module, + named_modules: Dict[str, torch.nn.Module], + graph: Graph, + obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize], + is_qat: bool, +) -> Optional[Node]: + if node in obs_or_fq_map: + output_act_obs_or_fq = obs_or_fq_map[node] + return _insert_obs_or_fq(node, output_act_obs_or_fq, model, named_modules, graph) + return None + +def _maybe_insert_input_and_output_observers_for_node( + node: Node, + model: torch.fx.GraphModule, + obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize], + is_qat: bool, +): + this_node_quantization_annotation = node.meta["quantization_annotation"] if "quantization_annotation" in node.meta else None + if this_node_quantization_annotation is None: + return + + named_modules = dict(model.named_modules(remove_duplicate=False)) + _maybe_insert_input_observers_for_node( + node, + None, # qconfig + model, + named_modules, + obs_or_fq_map, + is_qat, + ) + + output_is_a_tensor = "val" in node.meta and isinstance(node.meta["val"], FakeTensor) + if not output_is_a_tensor: + return + + # this returns the new observer node if it was needed + maybe_output_obs_node = _maybe_insert_output_observer_for_node( + node, model, named_modules, model.graph, obs_or_fq_map, is_qat) + + if maybe_output_obs_node is None: + return + # Update users of original node to use the output observer + # instead. For example, change + # + # next_node + # / + # cur_node -> obs + # + # to + # + # next_node + # / + # cur_node -> obs + # + # We need to save orig users before updating uses because + # the list of users will change as we update uses + orig_users = list(node.users.keys()) + for user_node in orig_users: + if user_node is maybe_output_obs_node: + continue + user_node.replace_input_with(node, maybe_output_obs_node) + +def prepare( + model: GraphModule, + node_name_to_scope: Dict[str, Tuple[str, type]], + is_qat: bool, +) -> GraphModule: + # Since we are mutating the graph as we go, we iterate over the original + # nodes before observer insertion, instead of model.graph.nodes. + nodes_before_observation = list(model.graph.nodes) + + # At the high level we construct a map from EdgeOrNode to a observer_or_fake_quant instance + # all edge/nodes that belongs to the same group will use the same instance + # and when we insert observers we'll just query this map to get the correct observer_or_fake_quant + # instance + edge_or_node_to_qspec = _get_edge_or_node_to_qspec(model) + edge_or_node_to_group_id = _get_edge_or_node_to_group_id(edge_or_node_to_qspec) + obs_or_fq_map = _get_obs_or_fq_map(edge_or_node_to_group_id, edge_or_node_to_qspec, is_qat) + + for node in nodes_before_observation: + # TODO: simplify logic for inserting observers + _maybe_insert_input_and_output_observers_for_node(node, model, obs_or_fq_map, is_qat) + + model = GraphModule(model, model.graph) + + _save_state( + model, + {}, # node_name_to_qconfig + node_name_to_scope, + PrepareCustomConfig(), + {}, # equalization_node_name_to_qconfig + QConfigMapping(), + is_qat, + set() # observed_node_names + ) + return model diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__init__.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ddac64c04fa4bbc6a781540cbce9c6416ba0b52 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__init__.py @@ -0,0 +1,5 @@ +from .rewrite import reference_representation_rewrite + +__all__ = [ + "reference_representation_rewrite", +] diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__pycache__/rewrite.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__pycache__/rewrite.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33b9986290631341bf036ca8f5b4ff8ab36c7b30 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__pycache__/rewrite.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8353d6172990b5be63f27dfb798605095f425e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig.py @@ -0,0 +1,560 @@ +from collections import namedtuple +from typing import Optional, Any, Union, Type + +import torch +import torch.nn as nn +from torch.ao.quantization.fake_quantize import ( + FakeQuantize, + FakeQuantizeBase, + default_fake_quant, + default_dynamic_fake_quant, + default_per_channel_weight_fake_quant, + default_weight_fake_quant, + default_fused_act_fake_quant, + default_fused_wt_fake_quant, + FusedMovingAvgObsFakeQuantize, + default_fused_per_channel_wt_fake_quant, + default_embedding_fake_quant, + default_embedding_fake_quant_4bit, + fused_wt_fake_quant_range_neg_127_to_127, + fused_per_channel_wt_fake_quant_range_neg_127_to_127, +) + +from .observer import ( + _PartialWrapper, + MinMaxObserver, + HistogramObserver, + MovingAverageMinMaxObserver, + NoopObserver, + PlaceholderObserver, + ReuseInputObserver, + default_debug_observer, + default_dynamic_quant_observer, + default_float_qparams_observer, + default_float_qparams_observer_4bit, + default_observer, + default_per_channel_weight_observer, + default_placeholder_observer, + default_weight_observer, + weight_observer_range_neg_127_to_127, + per_channel_weight_observer_range_neg_127_to_127, + default_reuse_input_observer, + ObserverBase, +) +import warnings +import copy + +__all__ = [ + "QConfig", + # TODO: deprecated, remove + "QConfigDynamic", + "default_qconfig", + "default_debug_qconfig", + "default_per_channel_qconfig", + "default_dynamic_qconfig", + "float16_dynamic_qconfig", + "float16_static_qconfig", + "per_channel_dynamic_qconfig", + "float_qparams_weight_only_qconfig", + "float_qparams_weight_only_qconfig_4bit", + "default_quint8_weight_qconfig", + "default_qat_qconfig", + "default_dynamic_qat_qconfig", + "default_weight_only_qconfig", + "default_activation_only_qconfig", + "default_qat_qconfig_v2", + "default_reuse_input_qconfig", + "default_symmetric_qnnpack_qconfig", + "default_per_channel_symmetric_qnnpack_qconfig", + "default_symmetric_qnnpack_qat_qconfig", + "default_per_channel_symmetric_qnnpack_qat_qconfig", + "default_embedding_qat_qconfig", + "default_embedding_qat_qconfig_4bit", + "get_default_qconfig", + "get_default_qat_qconfig", + "get_default_qconfig_dict", + "get_default_qat_qconfig_dict", + "QConfigAny", + "qconfig_equals", + +] + +class QConfig(namedtuple('QConfig', ['activation', 'weight'])): + """ + Describes how to quantize a layer or a part of the network by providing + settings (observer classes) for activations and weights respectively. + + + Note that QConfig needs to contain observer **classes** (like MinMaxObserver) or a callable that returns + instances on invocation, not the concrete observer instances themselves. + Quantization preparation function will instantiate observers multiple times for each of the layers. + + + Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args` + method (that behaves like functools.partial):: + + my_qconfig = QConfig( + activation=MinMaxObserver.with_args(dtype=torch.qint8), + weight=default_observer.with_args(dtype=torch.qint8)) + + """ + def __new__(cls, activation, weight): + # catch common mistakes + if isinstance(activation, nn.Module) or isinstance(weight, nn.Module): + raise ValueError("QConfig received observer instance, please pass observer class instead. " + + "Use MyObserver.with_args(x=1) to override arguments to constructor if needed") + return super().__new__(cls, activation, weight) + + +class QConfigDynamic(namedtuple('QConfigDynamic', ['activation', 'weight'])): + """ + Describes how to dynamically quantize a layer or a part of the network by providing + settings (observer classes) for weights. + + It's like QConfig, but for dynamic quantization. + + Note that QConfigDynamic needs to contain observer **classes** (like MinMaxObserver) or a callable that returns + instances on invocation, not the concrete observer instances themselves. + Quantization function will instantiate observers multiple times for each of the layers. + + Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args` + method (that behaves like functools.partial):: + + my_qconfig = QConfigDynamic(weight=default_observer.with_args(dtype=torch.qint8)) + """ + def __new__(cls, activation=torch.nn.Identity, weight=torch.nn.Identity): + # catch common mistakes + if isinstance(weight, nn.Module): + raise ValueError("QConfigDynamic received observer instance, please pass observer class instead. " + + "Use MyObserver.with_args(x=1) to override arguments to constructor if needed") + warnings.warn("QConfigDynamic is going to be deprecated in PyTorch 1.12, please use QConfig instead") + return super().__new__(cls, activation, weight) + + +default_qconfig = QConfig(activation=default_observer, + weight=default_weight_observer) +""" +Default qconfig configuration. +""" + +default_debug_qconfig = QConfig(weight=default_weight_observer, + activation=default_debug_observer) +""" +Default qconfig configuration for debugging. +""" + +default_per_channel_qconfig = QConfig(activation=default_observer, + weight=default_per_channel_weight_observer) +""" +Default qconfig configuration for per channel weight quantization. +""" + +default_dynamic_qconfig = QConfig(activation=default_dynamic_quant_observer, + weight=default_weight_observer) +""" +Default dynamic qconfig. +""" + +float16_dynamic_qconfig = QConfig(activation=PlaceholderObserver.with_args(dtype=torch.float16, is_dynamic=True), + weight=PlaceholderObserver.with_args(dtype=torch.float16)) +""" +Dynamic qconfig with weights quantized to `torch.float16`. +""" + +float16_static_qconfig = QConfig(activation=PlaceholderObserver.with_args(dtype=torch.float16), + weight=PlaceholderObserver.with_args(dtype=torch.float16)) +""" +Dynamic qconfig with both activations and weights quantized to `torch.float16`. +""" + +per_channel_dynamic_qconfig = QConfig(activation=default_dynamic_quant_observer, + weight=default_per_channel_weight_observer) +""" +Dynamic qconfig with weights quantized per channel. +""" + +float_qparams_weight_only_qconfig = QConfig( + activation=default_placeholder_observer, + weight=default_float_qparams_observer) +""" +Dynamic qconfig with weights quantized with a floating point zero_point. +""" + +float_qparams_weight_only_qconfig_4bit = QConfig( + activation=default_placeholder_observer, + weight=default_float_qparams_observer_4bit) + +default_qat_qconfig = QConfig(activation=default_fake_quant, + weight=default_weight_fake_quant) +""" +Default qconfig for QAT. +""" + +default_dynamic_qat_qconfig = QConfig(activation=default_dynamic_fake_quant, + weight=default_weight_fake_quant) +""" +Default qconfig for dynamic QAT. +""" + +default_weight_only_qconfig = QConfig(activation=torch.nn.Identity, + weight=default_weight_fake_quant) +""" +Default qconfig for quantizing weights only. +""" + +default_activation_only_qconfig = QConfig(activation=default_fake_quant, + weight=torch.nn.Identity) +""" +Default qconfig for quantizing activations only. +""" + +# QAT config that uses a fused observer + fake quant modules for optimized training performance. +# to modify the activation/weight observers, the default entries in fake_quantize.py can be modified. +default_qat_qconfig_v2 = QConfig(activation=default_fused_act_fake_quant, weight=default_fused_wt_fake_quant) +""" +Fused version of `default_qat_config`, has performance benefits. +""" + +default_reuse_input_qconfig = QConfig(activation=default_reuse_input_observer, + weight=NoopObserver) +""" +Default qconfig for operators that reuse the observers from input Tensor, e.g. reshape +""" + +def get_default_qconfig(backend='x86', version=0): + """ + Returns the default PTQ qconfig for the specified backend. + + Args: + * `backend` (str): a string representing the target backend. Currently supports + `x86` (default), `fbgemm`, `qnnpack` and `onednn`. + + Return: + qconfig + """ + supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"] + if backend not in supported_backends: + raise AssertionError( + "backend: " + str(backend) + + f" not supported. backend must be one of {supported_backends}" + ) + + if version == 0: + if backend == 'fbgemm': + qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=True), + weight=default_per_channel_weight_observer) + elif backend == 'qnnpack': + # TODO: make this compatible with xnnpack constraints + qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=False), + weight=default_weight_observer) + elif backend == 'onednn': + if not torch.cpu._is_cpu_support_vnni(): + warnings.warn( + "Default qconfig of oneDNN backend with reduce_range of false may have accuracy issues " + "on CPU without Vector Neural Network Instruction support.") + qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=False), + weight=default_per_channel_weight_observer) + elif backend == 'x86': + qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=True), + weight=default_per_channel_weight_observer) + else: + # won't reach + qconfig = default_qconfig + else: + raise AssertionError("Version number: " + str(version) + + " in get_default_qconfig is not supported. Version number must be 0") + + return qconfig + +""" +Default, symmetric PTQ qconfig for the specified backend. And a per_channel +variant of the same. + +Symmetric here applies to signed weights with zero point = 0, and additional +value restrictions. The activations are also signed 8-bit integers with this +qconfig. + + * Once this change is merged [as of 3/17/22], with backend or qengine = + 'qnnpack', some quantized operators with this symmetric qconfig may use + operators from xnnpack library. + + ** Support to use xnnpack ops with `qnnpack` backed for asymmetric + qconfig (returned by get_default_qconfig()) is not available yet. + + * This qconfig uses signed activations and weights. Weights have added + restrictions such as zero point is forced to be 0, making the weights + symmetric, hence the name. And the 8-bit quantized values are + restricting to to [-127, +127], excluding -128. + + * xnnpack has a requantization scale value restriction, 0x1p-32 <= + requantization_scale < 256.0 where, `requantization_scale = (input_scale + * kernel_scale) / (output_scale)`. Using this eps (w/ assumed max value + of 256) is to prevent requantization_scale to go below xnnpack lower + threshold. +""" +default_symmetric_qnnpack_qconfig = QConfig(activation=HistogramObserver.with_args(dtype=torch.qint8, + reduce_range=False, + eps=2 ** -12), + weight=weight_observer_range_neg_127_to_127) + +default_per_channel_symmetric_qnnpack_qconfig = QConfig(activation=HistogramObserver.with_args(dtype=torch.qint8, + reduce_range=False, + eps=2 ** -12), + weight=per_channel_weight_observer_range_neg_127_to_127) + +default_embedding_qat_qconfig = QConfig(activation=NoopObserver.with_args(dtype=torch.float32), + weight=default_embedding_fake_quant) + +default_embedding_qat_qconfig_4bit = QConfig(activation=NoopObserver.with_args(dtype=torch.float32), + weight=default_embedding_fake_quant_4bit) + +default_quint8_weight_qconfig = QConfig(activation=HistogramObserver, weight=MinMaxObserver) + +def get_default_qat_qconfig(backend='x86', version=1): + """ + Returns the default QAT qconfig for the specified backend. + + Args: + * `backend` (str): a string representing the target backend. Currently supports + `x86` (default), `fbgemm`, `qnnpack` and `onednn`. + * `version`: version, for backwards compatibility. Can be `None` or `1`. + + Return: + qconfig + """ + supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"] + if backend not in supported_backends: + raise AssertionError( + "backend: " + str(backend) + + f" not supported. backend must be one of {supported_backends}" + ) + + # Histogram observer is too slow for quantization aware training + if version == 0: + if backend == 'fbgemm': + qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True), + weight=default_per_channel_weight_fake_quant) + elif backend == 'qnnpack': + qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=False), + weight=default_weight_fake_quant) + elif backend == 'onednn': + qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255), + weight=default_per_channel_weight_fake_quant) + elif backend == 'x86': + qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True), + weight=default_per_channel_weight_fake_quant) + else: + qconfig = default_qat_qconfig + # Use the fused observe + fake_quant modules for doing QAT. + elif version == 1: + if backend == 'fbgemm': + qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True), + weight=default_fused_per_channel_wt_fake_quant) + elif backend == 'qnnpack': + # TODO: make this compatible with xnnpack constraints + qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=False), + weight=default_fused_wt_fake_quant) + elif backend == 'onednn': + qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255), + weight=default_fused_per_channel_wt_fake_quant) + elif backend == 'x86': + qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True), + weight=default_fused_per_channel_wt_fake_quant) + else: + qconfig = default_qat_qconfig_v2 + else: + raise AssertionError("Version number: " + str(version) + + "in get_default_qat_qconfig is not supported. Version number must be 0 or 1") + + return qconfig + +""" +Default symmetric QAT qconfig for qnnpack. And its per channel weight variant. +""" +default_symmetric_qnnpack_qat_qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=-128, + quant_max=127, + dtype=torch.qint8, + reduce_range=False, + eps=2 ** -12), + weight=fused_wt_fake_quant_range_neg_127_to_127) + +default_per_channel_symmetric_qnnpack_qat_qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=-128, + quant_max=127, + dtype=torch.qint8, + reduce_range=False, + eps=2 ** -12), + weight=fused_per_channel_wt_fake_quant_range_neg_127_to_127) + +_default_fp32_placeholder_qconfig = QConfig( + activation=PlaceholderObserver.with_args(dtype=torch.float32), + weight=PlaceholderObserver.with_args(dtype=torch.float32) +) + +_default_quint8_placeholder_qconfig = QConfig( + activation=PlaceholderObserver.with_args(dtype=torch.quint8), + # operators using this qconfig doesn't have weights + weight=None, +) + +def get_default_qconfig_dict(backend='x86', version=0): + warnings.warn( + "torch.ao.quantization.get_default_qconfig_dict is deprecated and will be removed in " + "a future version. Please use torch.ao.quantization.get_default_qconfig_mapping instead.") + return torch.ao.quantization.get_default_qconfig_mapping(backend, version).to_dict() + +def get_default_qat_qconfig_dict(backend='x86', version=1): + warnings.warn( + "torch.ao.quantization.get_default_qat_qconfig_dict is deprecated and will be removed in " + "a future version. Please use torch.ao.quantization.get_default_qat_qconfig_mapping instead.") + return torch.ao.quantization.get_default_qat_qconfig_mapping(backend, version).to_dict() + +def _assert_valid_qconfig(qconfig: Optional[QConfig], + mod: torch.nn.Module) -> None: + """ + Verifies that this `qconfig` is valid. + """ + if qconfig is None: + return + is_conv_transpose_mod = ( + isinstance(mod, (torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d))) + if is_conv_transpose_mod: + if qconfig.weight is None: + # for now, we assume that any qconfig for ConvTranspose without a weight is valid + return + example_observer = qconfig.weight() + is_per_channel = ( + isinstance(example_observer, (torch.ao.quantization.PerChannelMinMaxObserver, + torch.ao.quantization.MovingAveragePerChannelMinMaxObserver)) + ) + assert not is_per_channel, \ + 'Per channel weight observer is not supported yet for ConvTranspose{n}d.' + +QConfigAny = Optional[QConfig] +QConfigAny.__module__ = "torch.ao.quantization.qconfig" + +def _add_module_to_qconfig_obs_ctr( + qconfig: QConfigAny, + module: Optional[nn.Module]) -> Any: + r"""This is a helper function for use in quantization prepare that updates a qconfig so that + the constructors stored in the qconfig will create observers on the same device that + 'module' is on. This is intended to be used when the qconfigs are propagated to each + module in order to avoid potential device alignment issues. + + Args: + qconfig: QConfig with obs constructors stored in activation and weight + module: module which the qconfig is related to + + Return: + qconfig: configured so that obs constructors set to construct on the same device as module + """ + + if module is None or qconfig is None or qconfig._fields != ('activation', 'weight'): + return qconfig + + def get_factory_kwargs_based_on_module_device(): + assert isinstance(module, torch.nn.Module) + devices = {p.device for p in module.parameters()} | \ + {p.device for p in module.buffers()} + device = next(iter(devices)) if len(devices) > 0 else None + return None if device is None else {'device': device} + + def configure_constructor_to_put_obs_on_module_device(original_constructor): + try: + # check if constructor can accept factory_kwargs + check = original_constructor.with_args(factory_kwargs=None) + check() + return original_constructor.with_callable_args(factory_kwargs=get_factory_kwargs_based_on_module_device) + except AttributeError: # qconfig doesn't have activation or weight + return original_constructor + except TypeError: # the class doesn't accept factory_kwargs argument + return original_constructor + + activation = configure_constructor_to_put_obs_on_module_device(qconfig.activation) + weight = configure_constructor_to_put_obs_on_module_device(qconfig.weight) + + return QConfig(activation, weight) + +_ObserverOrFakeQuantizeConstructor = Union[_PartialWrapper, Type[ObserverBase], Type[FakeQuantizeBase]] + +def _obs_or_fq_ctr_equals(obs_or_fq1: _ObserverOrFakeQuantizeConstructor, obs_or_fq2: _ObserverOrFakeQuantizeConstructor): + if isinstance(obs_or_fq1, _PartialWrapper) and isinstance(obs_or_fq2, _PartialWrapper): + return _partial_wrapper_equals(obs_or_fq1, obs_or_fq2) + return obs_or_fq1 == obs_or_fq2 + +def _partial_wrapper_equals(obs_or_fq1: _PartialWrapper, obs_or_fq2: _PartialWrapper): + """ + Return whether the two partial wrappers are equal, + """ + # functools.partial has no __eq__ operator defined so '==' defaults to 'is' + obs_or_fq1_keywords = copy.copy(obs_or_fq1.p.keywords) + obs_or_fq2_keywords = copy.copy(obs_or_fq2.p.keywords) + keywords_equal = True + # compare observer constructor with _obs_or_fq_ctr_equals since direct compare would fail + if "observer" in obs_or_fq1_keywords and "observer" in obs_or_fq2_keywords: + keywords_equal = keywords_equal and _obs_or_fq_ctr_equals(obs_or_fq1_keywords["observer"], obs_or_fq2_keywords["observer"]) + obs_or_fq1_keywords.pop("observer") + obs_or_fq2_keywords.pop("observer") + keywords_equal = keywords_equal and obs_or_fq1_keywords == obs_or_fq2_keywords + return obs_or_fq1.p.func == obs_or_fq2.p.func and obs_or_fq1.p.args == obs_or_fq2.p.args and keywords_equal + +def qconfig_equals(q1: QConfigAny, q2: QConfigAny): + """ + Returns `True` if `q1` equals `q2`, and `False` otherwise. + """ + if q1 is None or q2 is None: + return q1 == q2 + else: + assert q1 is not None and q2 is not None + try: + # Qconfig weight and activation can be either a partial wrapper, + # or an observer class. Special handling is required (above) for + # comparing partial wrappers. + activation_same = _obs_or_fq_ctr_equals(q1.activation, q2.activation) + weight_same = _obs_or_fq_ctr_equals(q1.weight, q2.weight) + return activation_same and weight_same + except AttributeError: + return q1 == q2 + +def _activation_is_memoryless(qconfig: QConfig): + """ + Return whether the observer for activations defined in the given QConfig is memoryless. + This means a MovingAverage observer with averaging constant equal to 1. + """ + def _is_memoryless(observer): + return hasattr(observer, "averaging_constant") and observer.averaging_constant == 1 + act = qconfig.activation() + if isinstance(act, FakeQuantizeBase) and hasattr(act, "activation_post_process"): + return _is_memoryless(act.activation_post_process) + else: + return _is_memoryless(act) + +def _is_reuse_input_qconfig(qconfig: Optional[QConfig]): + return qconfig is not None and \ + isinstance(qconfig.activation(), ReuseInputObserver) and \ + isinstance(qconfig.weight(), NoopObserver) diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig_mapping.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf4b41c724a80455d5a39447550c4c98d6614fa --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig_mapping.py @@ -0,0 +1,350 @@ +from __future__ import annotations +from collections import OrderedDict +from typing import Any, Callable, Dict, Tuple, Union, List + +import torch + +from .fake_quantize import ( + default_weight_fake_quant, + FixedQParamsFakeQuantize, +) +from .observer import ( + _PartialWrapper, + default_fixed_qparams_range_0to1_observer, + default_fixed_qparams_range_neg1to1_observer, + default_placeholder_observer, + default_weight_observer, +) +from .qconfig import ( + default_reuse_input_qconfig, + default_symmetric_qnnpack_qconfig, + default_symmetric_qnnpack_qat_qconfig, + get_default_qconfig, + get_default_qat_qconfig, + QConfig, + QConfigAny, + default_quint8_weight_qconfig +) + + +__all__ = [ + "get_default_qconfig_mapping", + "get_default_qat_qconfig_mapping", + "QConfigMapping", +] + + +# TODO: replace all usages with these constants +_GLOBAL_DICT_KEY = "" +_OBJECT_TYPE_DICT_KEY = "object_type" +_MODULE_NAME_REGEX_DICT_KEY = "module_name_regex" +_MODULE_NAME_DICT_KEY = "module_name" +_MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY = "module_name_object_type_order" + +# TODO: derive this map from the BackendConfig +_FIXED_QPARAMS_OP_TO_OBSERVER: Dict[Union[Callable, str], _PartialWrapper] = { + torch.nn.Hardsigmoid: default_fixed_qparams_range_0to1_observer, + torch.nn.functional.hardsigmoid: default_fixed_qparams_range_0to1_observer, + "hardsigmoid": default_fixed_qparams_range_0to1_observer, + "hardsigmoid_": default_fixed_qparams_range_0to1_observer, + torch.nn.Sigmoid: default_fixed_qparams_range_0to1_observer, + torch.sigmoid: default_fixed_qparams_range_0to1_observer, + "sigmoid": default_fixed_qparams_range_0to1_observer, + "sigmoid_": default_fixed_qparams_range_0to1_observer, + torch.nn.Softmax: default_fixed_qparams_range_0to1_observer, + torch.nn.Tanh: default_fixed_qparams_range_neg1to1_observer, + torch.tanh: default_fixed_qparams_range_neg1to1_observer, + "tanh": default_fixed_qparams_range_neg1to1_observer, + "tanh_": default_fixed_qparams_range_neg1to1_observer, +} + + +def _get_default_qconfig_mapping(is_qat: bool, backend: str, version: int) -> QConfigMapping: + """ + Return the default QConfigMapping for the given quantization type and backend. + """ + if is_qat: + qconfig = get_default_qat_qconfig(backend, version) + else: + qconfig = get_default_qconfig(backend, version) + default_weight = default_weight_fake_quant if is_qat else default_weight_observer + + # default_per_channel_weight_observer is not currently compatible with fbgemm backend + # so we have to modify the weight observer to default_weight_observer or another + # per tensor supported observer. + # see https://github.com/pytorch/pytorch/issues/47535 + if backend in ("fbgemm", "x86"): + qconfig_transpose = QConfig(activation=qconfig.activation, weight=default_weight) + else: + qconfig_transpose = qconfig + + # currently layernorm only supports float weights + # we have to add this because otherwise there will be a extra quantize-dequantize pair + qconfig_layernorm = QConfig(activation=qconfig.activation, weight=default_placeholder_observer) + + qconfig_mapping = QConfigMapping() \ + .set_global(qconfig) \ + .set_object_type("reshape", default_reuse_input_qconfig) \ + .set_object_type(torch.nn.ConvTranspose1d, qconfig_transpose) \ + .set_object_type(torch.nn.ConvTranspose2d, qconfig_transpose) \ + .set_object_type(torch.nn.ConvTranspose3d, qconfig_transpose) \ + .set_object_type(torch.nn.functional.conv_transpose1d, qconfig_transpose) \ + .set_object_type(torch.nn.functional.conv_transpose2d, qconfig_transpose) \ + .set_object_type(torch.nn.functional.conv_transpose3d, qconfig_transpose) \ + .set_object_type(torch.nn.functional.layer_norm, qconfig_layernorm) \ + .set_object_type(torch.nn.LayerNorm, qconfig_layernorm) \ + .set_object_type(torch.nn.PReLU, default_quint8_weight_qconfig) \ + + # Use special observers for ops with fixed qparams + fixed_qparams_observer_to_qconfig: Dict[Any, QConfigAny] = {} + for fixed_qparams_op, observer in _FIXED_QPARAMS_OP_TO_OBSERVER.items(): + if observer in fixed_qparams_observer_to_qconfig: + fixed_qparams_qconfig = fixed_qparams_observer_to_qconfig[observer] + else: + if is_qat: + activation = FixedQParamsFakeQuantize.with_args(observer=observer) + else: + activation = observer + fixed_qparams_qconfig = QConfig(activation=activation, weight=default_weight) + fixed_qparams_observer_to_qconfig[observer] = fixed_qparams_qconfig + qconfig_mapping.set_object_type(fixed_qparams_op, fixed_qparams_qconfig) + + # TODO Currently it's required that separate ops in a fused op/module have the same qconfig. + # Need to be able to support fusion of ops with different qconfigs + + return qconfig_mapping + +def get_default_qconfig_mapping(backend="x86", version=0) -> QConfigMapping: + """ + Return the default QConfigMapping for post training quantization. + + Args: + * ``backend`` (str) : the quantization backend for the default qconfig mapping, should be + one of ["x86" (default), "fbgemm", "qnnpack", "onednn"] + * ``version`` (int) : the version for the default qconfig mapping + """ + # TODO: add assert for backend choices + return _get_default_qconfig_mapping(False, backend, version) + +def get_default_qat_qconfig_mapping(backend="x86", version=1) -> QConfigMapping: + """ + Return the default QConfigMapping for quantization aware training. + + Args: + * ``backend`` (str) : the quantization backend for the default qconfig mapping, should be + one of ["x86" (default), "fbgemm", "qnnpack", "onednn"] + * ``version`` (int) : the version for the default qconfig mapping + """ + return _get_default_qconfig_mapping(True, backend, version) + +def _get_symmetric_qnnpack_qconfig_mapping() -> QConfigMapping: + """ + Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qconfig` + as the default QConfig. + """ + default_qconfig = default_symmetric_qnnpack_qconfig + return _get_default_qconfig_mapping_with_default_qconfig(False, "qnnpack", default_qconfig) + +def _get_symmetric_qnnpack_qat_qconfig_mapping() -> QConfigMapping: + """ + Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qat_qconfig` + as the default QConfig. + """ + default_qconfig = default_symmetric_qnnpack_qat_qconfig + return _get_default_qconfig_mapping_with_default_qconfig(True, "qnnpack", default_qconfig) + +def _get_default_qconfig_mapping_with_default_qconfig( + is_qat: bool, + backend: str, + default_qconfig: QConfig, +) -> QConfigMapping: + """ + Return a QConfigMapping that uses the provided qconfig as the default QConfig. + """ + if is_qat: + qconfig_mapping = get_default_qat_qconfig_mapping(backend) + else: + qconfig_mapping = get_default_qconfig_mapping(backend) + qconfig_mapping.set_global(default_qconfig) + for pattern in qconfig_mapping.object_type_qconfigs.keys(): + if pattern not in _FIXED_QPARAMS_OP_TO_OBSERVER: + qconfig_mapping.set_object_type(pattern, default_qconfig) + return qconfig_mapping + +_QCONFIG_STYLE_ORDER: List[str] = [ + "global_qconfig", + "object_type_qconfigs", + "module_name_regex_qconfigs", + "module_name_qconfigs", + "module_name_object_type_order_qconfigs", +] + +class QConfigMapping: + """ + Mapping from model ops to :class:`torch.ao.quantization.QConfig` s. + + The user can specify QConfigs using the following methods (in increasing match priority): + + ``set_global`` : sets the global (default) QConfig + + ``set_object_type`` : sets the QConfig for a given module type, function, or method name + + ``set_module_name_regex`` : sets the QConfig for modules matching the given regex string + + ``set_module_name`` : sets the QConfig for modules matching the given module name + + ``set_module_name_object_type_order`` : sets the QConfig for modules matching a combination + of the given module name, object type, and the index at which the module appears + + Example usage:: + + qconfig_mapping = QConfigMapping() + .set_global(global_qconfig) + .set_object_type(torch.nn.Linear, qconfig1) + .set_object_type(torch.nn.ReLU, qconfig1) + .set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1) + .set_module_name_regex("foo.*", qconfig2) + .set_module_name("module1", qconfig1) + .set_module_name("module2", qconfig2) + .set_module_name_object_type_order("foo.bar", torch.nn.functional.linear, 0, qconfig3) + + """ + + def __init__(self): + # In increasing match priority: + self.global_qconfig: QConfigAny = None + self.object_type_qconfigs: OrderedDict[Union[Callable, str], QConfigAny] = OrderedDict() + self.module_name_regex_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict() + self.module_name_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict() + self.module_name_object_type_order_qconfigs: OrderedDict[Tuple[str, Callable, int], QConfigAny] =\ + OrderedDict() + + def set_global(self, global_qconfig: QConfigAny) -> QConfigMapping: + """ + Set the global (default) QConfig. + """ + self.global_qconfig = global_qconfig + return self + + def set_object_type(self, object_type: Union[Callable, str], qconfig: QConfigAny) -> QConfigMapping: + """ + Set the QConfig for a given module type, function, or method name. + If the QConfig for an existing object type was already set, the new QConfig will override the old one. + """ + self.object_type_qconfigs[object_type] = qconfig + return self + + def set_module_name_regex(self, module_name_regex: str, qconfig: QConfigAny) -> QConfigMapping: + """ + Set the QConfig for modules matching the given regex string. + + Regexes will be matched in the order in which they are registered through this method. + Thus, the caller should register more specific patterns first, e.g.:: + + qconfig_mapping = QConfigMapping() + .set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1) + .set_module_name_regex("foo.*bar.*", qconfig2) + .set_module_name_regex("foo.*", qconfig3) + + In this example, "foo.bar.conv0" would match qconfig1, "foo.bar.linear" would match qconfig2, + and "foo.baz.relu" would match qconfig3. + + If the QConfig for an existing module name regex was already set, the new QConfig will override the + old one while preserving the order in which the regexes were originally registered. + """ + self.module_name_regex_qconfigs[module_name_regex] = qconfig + return self + + def set_module_name(self, module_name: str, qconfig: QConfigAny) -> QConfigMapping: + """ + Set the QConfig for modules matching the given module name. + If the QConfig for an existing module name was already set, the new QConfig will override the old one. + """ + self.module_name_qconfigs[module_name] = qconfig + return self + + def set_module_name_object_type_order( + self, + module_name: str, + object_type: Callable, + index: int, + qconfig: QConfigAny) -> QConfigMapping: + """ + Set the QConfig for modules matching a combination of the given module name, object type, + and the index at which the module appears. + + If the QConfig for an existing (module name, object type, index) was already set, the new QConfig + will override the old one. + """ + self.module_name_object_type_order_qconfigs[(module_name, object_type, index)] = qconfig + return self + + def __repr__(self) -> str: + output = self.__class__.__name__ + " (" + for style_name in _QCONFIG_STYLE_ORDER: + output += f"\n {style_name}" + qconfigs = getattr(self, style_name) + if isinstance(qconfigs, OrderedDict) and len(qconfigs) > 0: + for key, qconfig in qconfigs.items(): + output += f"\n {key}: {qconfig}" + else: + output += f"\n {qconfigs}" + return output + "\n)" + + # TODO: remove this + def to_dict(self) -> Dict[str, Any]: + """ + Convert this ``QConfigMapping`` to a dictionary with the following keys: + + "" (for global QConfig) + + "object_type" + + "module_name_regex" + + "module_name" + + "module_name_object_type_order" + + The values of this dictionary are lists of tuples. + """ + return { + _GLOBAL_DICT_KEY: self.global_qconfig, + _OBJECT_TYPE_DICT_KEY: list(self.object_type_qconfigs.items()), + _MODULE_NAME_REGEX_DICT_KEY: list(self.module_name_regex_qconfigs.items()), + _MODULE_NAME_DICT_KEY: list(self.module_name_qconfigs.items()), + _MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY: [ + (*k, v) for k, v in self.module_name_object_type_order_qconfigs.items() + ], + } + + # TODO: remove this + @classmethod + def from_dict(cls, qconfig_dict: Dict[str, Any]) -> QConfigMapping: + """ + Create a ``QConfigMapping`` from a dictionary with the following keys (all optional): + + "" (for global QConfig) + + "object_type" + + "module_name_regex" + + "module_name" + + "module_name_object_type_order" + + The values of this dictionary are expected to be lists of tuples. + """ + conf = cls() + if _GLOBAL_DICT_KEY in qconfig_dict: + conf.set_global(qconfig_dict[_GLOBAL_DICT_KEY]) + for object_type, qconfig in qconfig_dict.get(_OBJECT_TYPE_DICT_KEY, []): + conf.set_object_type(object_type, qconfig) + for module_name_regex, qconfig in qconfig_dict.get(_MODULE_NAME_REGEX_DICT_KEY, []): + conf.set_module_name_regex(module_name_regex, qconfig) + for module_name, qconfig in qconfig_dict.get(_MODULE_NAME_DICT_KEY, []): + conf.set_module_name(module_name, qconfig) + for module_name, object_type, index, qconfig in qconfig_dict.get(_MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY, []): + conf.set_module_name_object_type_order(module_name, object_type, index, qconfig) + return conf diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quant_type.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quant_type.py new file mode 100644 index 0000000000000000000000000000000000000000..1448a6270e2ba9ba49b13a9d4878180f56a5bba7 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quant_type.py @@ -0,0 +1,30 @@ +import enum + +__all__ = [ + "QuantType", +] + +# Quantization type (dynamic quantization, static quantization). +# Should match the c++ enum in quantization_type.h +class QuantType(enum.IntEnum): + DYNAMIC = 0 + STATIC = 1 + QAT = 2 + WEIGHT_ONLY = 3 + +_quant_type_to_str = { + QuantType.STATIC: "static", + QuantType.DYNAMIC: "dynamic", + QuantType.QAT: "qat", + QuantType.WEIGHT_ONLY: "weight_only", +} + +# TODO: make this private +def _get_quant_type_to_str(quant_type: QuantType) -> str: + return _quant_type_to_str[quant_type] + +def _quant_type_from_str(name: str) -> QuantType: + for quant_type, s in _quant_type_to_str.items(): + if name == s: + return quant_type + raise ValueError(f"Unknown QuantType name '{name}'") diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantization_mappings.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantization_mappings.py new file mode 100644 index 0000000000000000000000000000000000000000..179cddca27427bae08139b5b777207cdd31650e8 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantization_mappings.py @@ -0,0 +1,348 @@ +import copy + +import torch +from torch import nn + +import torch.nn.functional as F +import torch.ao.nn.intrinsic as nni +import torch.ao.nn.intrinsic.quantized as nniq +import torch.ao.nn.intrinsic.quantized.dynamic as nniqd +import torch.ao.nn.intrinsic.qat as nniqat +import torch.ao.nn.quantized as nnq +import torch.ao.nn.quantized.reference as nnqr +import torch.ao.nn.quantized.dynamic as nnqd +import torch.ao.nn.qat as nnqat +import torch.ao.nn.qat.dynamic as nnqatd + +from typing import Optional, Union, Dict, Set, Callable, Any + +# Because `torch.ao.nn` uses lazy imports, we need to make +# sure we import the contents explicitly here. +import torch.ao.nn.sparse +import torch.ao.nn as ao_nn +from torch.ao.quantization.stubs import QuantStub, DeQuantStub +from torch.ao.quantization.fake_quantize import ( + default_fixed_qparams_range_0to1_fake_quant, + default_fixed_qparams_range_neg1to1_fake_quant, +) +from torch.ao.quantization.utils import get_combined_dict +from torch.nn.utils.parametrize import type_before_parametrizations + +__all__ = [ + "DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS", + "DEFAULT_STATIC_QUANT_MODULE_MAPPINGS", + "DEFAULT_QAT_MODULE_MAPPINGS", + "DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS", + "DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS", + "DEFAULT_MODULE_TO_ACT_POST_PROCESS", + "DEFAULT_STATIC_SPARSE_QUANT_MODULE_MAPPINGS", + "DEFAULT_DYNAMIC_SPARSE_QUANT_MODULE_MAPPINGS", + "no_observer_set", + "get_default_static_quant_module_mappings", + "get_default_static_quant_reference_module_mappings", + "get_embedding_static_quant_module_mappings", + "get_default_static_sparse_quant_module_mappings", + "get_static_quant_module_class", + "get_dynamic_quant_module_class", + "get_default_qat_module_mappings", + "get_embedding_qat_module_mappings", + "get_default_dynamic_quant_module_mappings", + "get_default_dynamic_sparse_quant_module_mappings", + "get_default_qconfig_propagation_list", + "get_default_compare_output_module_list", + "get_default_float_to_quantized_operator_mappings", + "get_quantized_operator", +] + +# Default map for swapping float module to reference quantized modules +DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = { + QuantStub: nnq.Quantize, + DeQuantStub: nnq.DeQuantize, + nn.Linear: nnqr.Linear, + nn.Conv1d: nnqr.Conv1d, + nn.Conv2d: nnqr.Conv2d, + nn.Conv3d: nnqr.Conv3d, + nn.ConvTranspose1d: nnqr.ConvTranspose1d, + nn.ConvTranspose2d: nnqr.ConvTranspose2d, + nn.ConvTranspose3d: nnqr.ConvTranspose3d, + nn.Embedding: nnqr.Embedding, + nn.EmbeddingBag: nnqr.EmbeddingBag, + nn.GRUCell: nnqr.GRUCell, + nn.LSTMCell: nnqr.LSTMCell, + nn.RNNCell: nnqr.RNNCell, + nn.LSTM: nnqr.LSTM, +} + +# Default map for swapping float module to quantized ones +DEFAULT_STATIC_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = { + QuantStub: nnq.Quantize, + DeQuantStub: nnq.DeQuantize, + nn.BatchNorm2d: nnq.BatchNorm2d, + nn.BatchNorm3d: nnq.BatchNorm3d, + nn.Dropout: nnq.Dropout, + nn.Conv1d: nnq.Conv1d, + nn.Conv2d: nnq.Conv2d, + nn.Conv3d: nnq.Conv3d, + nn.ConvTranspose1d: nnq.ConvTranspose1d, + nn.ConvTranspose2d: nnq.ConvTranspose2d, + nn.ConvTranspose3d: nnq.ConvTranspose3d, + nn.ELU: nnq.ELU, + nn.Embedding: nnq.Embedding, + nn.EmbeddingBag: nnq.EmbeddingBag, + nn.GroupNorm: nnq.GroupNorm, + nn.Hardswish: nnq.Hardswish, + nn.InstanceNorm1d: nnq.InstanceNorm1d, + nn.InstanceNorm2d: nnq.InstanceNorm2d, + nn.InstanceNorm3d: nnq.InstanceNorm3d, + nn.LayerNorm: nnq.LayerNorm, + nn.LeakyReLU: nnq.LeakyReLU, + nn.modules.linear.NonDynamicallyQuantizableLinear: nnq.Linear, + nn.Linear: nnq.Linear, + nn.ReLU6: nnq.ReLU6, + nn.Dropout: nnq.Dropout, + nn.PReLU: nnq.PReLU, + # Wrapper Modules: + nnq.FloatFunctional: nnq.QFunctional, + # Intrinsic modules: + nni.BNReLU2d: nniq.BNReLU2d, + nni.BNReLU3d: nniq.BNReLU3d, + nni.ConvReLU1d: nniq.ConvReLU1d, + nni.ConvReLU2d: nniq.ConvReLU2d, + nni.ConvReLU3d: nniq.ConvReLU3d, + nni.ConvAdd2d: nniq.ConvAdd2d, + nni.ConvAddReLU2d: nniq.ConvAddReLU2d, + nni.LinearReLU: nniq.LinearReLU, + nni.LinearLeakyReLU: nniq.LinearLeakyReLU, + nni.LinearTanh: nniq.LinearTanh, + nniqat.ConvBn1d: nnq.Conv1d, + nniqat.ConvBn2d: nnq.Conv2d, + nniqat.ConvBn3d: nnq.Conv3d, + nniqat.ConvBnReLU1d: nniq.ConvReLU1d, + nniqat.ConvBnReLU2d: nniq.ConvReLU2d, + nniqat.ConvBnReLU3d: nniq.ConvReLU3d, + nniqat.ConvReLU2d: nniq.ConvReLU2d, + nniqat.ConvReLU3d: nniq.ConvReLU3d, + nniqat.LinearReLU: nniq.LinearReLU, + nniqat.LinearBn1d: nnq.Linear, + # QAT modules: + nnqat.Linear: nnq.Linear, + nnqat.Conv2d: nnq.Conv2d, + nnqat.Conv3d: nnq.Conv3d, +} + +# Default map for swapping float module to qat modules +DEFAULT_QAT_MODULE_MAPPINGS : Dict[Callable, Any] = { + nn.Conv2d: nnqat.Conv2d, + nn.Conv3d: nnqat.Conv3d, + nn.Linear: nnqat.Linear, + nn.modules.linear.NonDynamicallyQuantizableLinear: nnqat.Linear, + # Intrinsic modules: + nni.ConvBn1d: nniqat.ConvBn1d, + nni.ConvBn2d: nniqat.ConvBn2d, + nni.ConvBn3d: nniqat.ConvBn3d, + nni.ConvBnReLU1d: nniqat.ConvBnReLU1d, + nni.ConvBnReLU2d: nniqat.ConvBnReLU2d, + nni.ConvBnReLU3d: nniqat.ConvBnReLU3d, + nni.ConvReLU2d: nniqat.ConvReLU2d, + nni.ConvReLU3d: nniqat.ConvReLU3d, + nni.LinearReLU: nniqat.LinearReLU, + nni.LinearBn1d: nniqat.LinearBn1d, +} + +# Default map for swapping dynamic modules +DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = { + nn.GRUCell: nnqd.GRUCell, + nn.Linear: nnqd.Linear, + nnqatd.Linear: nnqd.Linear, + nn.modules.linear.NonDynamicallyQuantizableLinear: nnqd.Linear, + nn.LSTM: nnqd.LSTM, + nn.GRU: nnqd.GRU, + nn.LSTMCell: nnqd.LSTMCell, + nn.RNNCell: nnqd.RNNCell, + nni.LinearReLU: nniqd.LinearReLU, + nn.EmbeddingBag: nnq.EmbeddingBag, + nn.Embedding: nnq.Embedding, + # Don't want to enable these by default because the numerical + # accuracy is poor compared to other dynamic ops + # nn.Conv1d: nnqd.Conv1d, + # nn.Conv2d: nnqd.Conv2d, + # nn.Conv3d: nnqd.Conv3d, + # nn.ConvTranspose1d: nnqd.ConvTranspose1d, + # nn.ConvTranspose2d: nnqd.ConvTranspose2d, + # nn.ConvTranspose3d: nnqd.ConvTranspose3d, +} + +# Allowlist for propagating the qconfig +_INCLUDE_QCONFIG_PROPAGATE_LIST : Set[Callable] = { + nn.Sequential, +} + +# Default mapping from floating point function or torch ops to quantized ops +# TODO: merge with default static mapping +DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS : Dict[Union[Callable, str], Callable] = { + F.elu: torch.ops.quantized.elu, + F.hardswish: torch.ops.quantized.hardswish, + F.instance_norm: torch.ops.quantized.instance_norm, + F.layer_norm: torch.ops.quantized.layer_norm, + F.leaky_relu: torch.ops.quantized.leaky_relu, + F.dropout: torch.ops.quantized.dropout, +} + +# mapping from module to output activation post process class +DEFAULT_MODULE_TO_ACT_POST_PROCESS : Dict[Callable, Callable] = { + nn.Hardsigmoid: default_fixed_qparams_range_0to1_fake_quant, + nn.Sigmoid: default_fixed_qparams_range_0to1_fake_quant, + nn.Softmax: default_fixed_qparams_range_0to1_fake_quant, + nn.Tanh: default_fixed_qparams_range_neg1to1_fake_quant, +} + +# Default map for swapping float module to static sparse quantized ones +DEFAULT_STATIC_SPARSE_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = { + nn.Linear: ao_nn.sparse.quantized.Linear +} + +# Default map for swapping float module to dynamic sparse quantized ones +DEFAULT_DYNAMIC_SPARSE_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = { + nn.Linear: ao_nn.sparse.quantized.dynamic.Linear +} + +def no_observer_set() -> Set[Any]: + r"""These modules cannot have observers inserted by default.""" + no_observers = { + nn.quantizable.LSTM, + nn.quantizable.MultiheadAttention + } + return no_observers + +def get_default_static_quant_module_mappings() -> Dict[Callable, Any]: + ''' Get module mapping for post training static quantization + ''' + return copy.deepcopy(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS) + +def get_default_static_quant_reference_module_mappings() -> Dict[Callable, Any]: + ''' Get reference module mapping for post training static quantization + ''' + return copy.deepcopy(DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS) + +def get_embedding_static_quant_module_mappings() -> Dict[Callable, Any]: + ''' Get module mapping, including mapping for embedding QAT + ''' + mapping = copy.deepcopy(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS) + mapping[nnqat.EmbeddingBag] = nnq.EmbeddingBag + mapping[nnqat.Embedding] = nnq.Embedding + return mapping + +def get_default_static_sparse_quant_module_mappings() -> Dict[Callable, Any]: + ''' Get module mapping for post training static sparse quantization + ''' + return copy.deepcopy(DEFAULT_STATIC_SPARSE_QUANT_MODULE_MAPPINGS) + +def get_static_quant_module_class( + float_module_class: Callable, + additional_static_quant_mapping: Optional[Dict[Callable, Any]] = None, + is_reference: bool = False) -> Any: + r"""n Get the statically quantized module class corresponding to + the floating point module class + """ + if additional_static_quant_mapping is None: + additional_static_quant_mapping = {} + all_mappings = get_combined_dict( + DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS if is_reference + else DEFAULT_STATIC_QUANT_MODULE_MAPPINGS, additional_static_quant_mapping) + static_quant_module_class = all_mappings.get(float_module_class, None) + assert static_quant_module_class is not None, \ + f"Floating point module class {str(float_module_class)}" + \ + " does not have a corresponding quantized module class" + return copy.deepcopy(static_quant_module_class) + +def get_dynamic_quant_module_class( + float_module_class: Callable, + additional_dynamic_quant_mapping: Optional[Dict[Callable, Any]] = None) -> Any: + r"""n Get the dynamically quantized module class corresponding to + the floating point module class + """ + if additional_dynamic_quant_mapping is None: + additional_dynamic_quant_mapping = {} + all_mappings = get_combined_dict(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS, additional_dynamic_quant_mapping) + dynamic_quant_module_class = all_mappings.get(float_module_class, None) + assert dynamic_quant_module_class is not None, \ + f"Floating point module class {str(float_module_class)}" + \ + " does not have a corresponding quantized module class" + return copy.deepcopy(dynamic_quant_module_class) + +def get_default_qat_module_mappings() -> Dict[Callable, Any]: + ''' Get default module mapping for quantization aware training + ''' + return copy.deepcopy(DEFAULT_QAT_MODULE_MAPPINGS) + +def get_embedding_qat_module_mappings() -> Dict[Callable, Any]: + ''' Get module mapping for quantization aware training + This is includes default values in addition to + enabling qat for embeddings. + ''' + mapping = copy.deepcopy(DEFAULT_QAT_MODULE_MAPPINGS) + mapping[nn.EmbeddingBag] = nnqat.EmbeddingBag + mapping[nn.Embedding] = nnqat.Embedding + return mapping + +def get_default_dynamic_quant_module_mappings() -> Dict[Callable, Any]: + ''' Get module mapping for post training dynamic quantization + ''' + return DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS + +def get_default_dynamic_sparse_quant_module_mappings() -> Dict[Callable, Any]: + ''' Get module mapping for post training dynamic sparse quantization + ''' + return DEFAULT_DYNAMIC_SPARSE_QUANT_MODULE_MAPPINGS + +def get_default_qconfig_propagation_list() -> Set[Callable]: + ''' Get the default list of module types that we'll attach qconfig + attribute to in prepare + ''' + QCONFIG_PROPAGATE_MODULE_CLASS_LIST = ( + set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.keys()) | + set(DEFAULT_QAT_MODULE_MAPPINGS.keys()) | + set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.keys()) | + _INCLUDE_QCONFIG_PROPAGATE_LIST + ) + return copy.deepcopy(QCONFIG_PROPAGATE_MODULE_CLASS_LIST) + +def get_default_compare_output_module_list() -> Set[Callable]: + ''' Get list of module class types that we will record output + in numeric suite + ''' + NUMERIC_SUITE_COMPARE_MODEL_OUTPUT_MODULE_LIST = ( + set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.values()) + | set(DEFAULT_QAT_MODULE_MAPPINGS.values()) + | set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.values()) + | set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.keys()) + | set(DEFAULT_QAT_MODULE_MAPPINGS.keys()) + | set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.keys()) + | _INCLUDE_QCONFIG_PROPAGATE_LIST + ) + return copy.deepcopy(NUMERIC_SUITE_COMPARE_MODEL_OUTPUT_MODULE_LIST) + +def get_default_float_to_quantized_operator_mappings( +) -> Dict[Union[Callable, str], Callable]: + return copy.deepcopy(DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS) + +# TODO: merge with get_static_quant_module_class +def get_quantized_operator(float_op: Union[Callable, str]) -> Callable: + ''' Get the quantized operator corresponding to the float operator + ''' + quantized_op = DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS.get(float_op, None) + assert quantized_op is not None, \ + f'Operator {str(float_op)} does not have corresponding quantized op' + return quantized_op + +def _get_special_act_post_process(module: torch.nn.Module) -> Optional[Callable]: + r""" Get the special activation post process for `module`, this has + higher priority than the activation post process in `qconfig` + e.g. + input: torch.nn.Sigmoid + output: default_affine_fixed_qparam_fake_quant + """ + return DEFAULT_MODULE_TO_ACT_POST_PROCESS.get(type_before_parametrizations(module), None) + +def _has_special_act_post_process(module: torch.nn.Module) -> bool: + return module.training and type(module) in DEFAULT_MODULE_TO_ACT_POST_PROCESS diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize.py new file mode 100644 index 0000000000000000000000000000000000000000..794cb142220dfb424cb58b06b736ed02cd14dad2 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize.py @@ -0,0 +1,664 @@ +import copy +import itertools +import warnings + +import torch +import torch.nn as nn +import torch.ao.nn.quantized as nnq +from torch.ao.nn.intrinsic import _FusedModule + +from torch.ao.quantization.quantization_mappings import ( + get_default_dynamic_quant_module_mappings, + get_default_static_quant_module_mappings, + get_default_static_quant_reference_module_mappings, + get_default_qat_module_mappings, + get_default_qconfig_propagation_list, + no_observer_set, + _has_special_act_post_process, + _get_special_act_post_process, +) +from .utils import get_qparam_dict, has_no_children_ignoring_parametrizations +from torch.ao.quantization.stubs import DeQuantStub, QuantWrapper +from torch.ao.quantization.qconfig import ( + _add_module_to_qconfig_obs_ctr, + default_dynamic_qconfig, + float16_dynamic_qconfig, + float_qparams_weight_only_qconfig, + float_qparams_weight_only_qconfig_4bit, + _activation_is_memoryless) +from torch.nn.utils.parametrize import type_before_parametrizations +from torch.ao.quantization.observer import _is_activation_post_process + +# TODO remove this once BC is no longer required to avoid a SEV +from torch.ao.quantization.observer import ( # noqa: F401 + _is_activation_post_process as is_activation_post_process +) + +__all__ = [ + "get_default_custom_config_dict", + "propagate_qconfig_", + "add_quant_dequant", + "prepare", + "quantize", + "quantize_dynamic", + "prepare_qat", + "quantize_qat", + "convert", + "swap_module", +] + +_DEFAULT_CUSTOM_CONFIG_DICT = { + 'float_to_observed_custom_module_class': { + nn.LSTM: nn.quantizable.LSTM, + nn.MultiheadAttention: nn.quantizable.MultiheadAttention, + }, + 'observed_to_quantized_custom_module_class': { + nn.quantizable.LSTM: nn.quantized.LSTM, + nn.quantizable.MultiheadAttention: nn.quantized.MultiheadAttention, + } +} + +def get_default_custom_config_dict(): + r"""Defines the default custom config dict. + """ + return _DEFAULT_CUSTOM_CONFIG_DICT + +def _propagate_qconfig_helper(module, qconfig_dict, + qconfig_parent=None, prefix='', prepare_custom_config_dict=None): + r"""This is a helper function for `propagate_qconfig_` + + Args: + module: input module + qconfig_dict: dictionary that maps from name of submodule to quantization + configuration + qconfig_parent: quantization config of parent module, we will fallback to + this config when there is no specified config for current + module + prefix: corresponding prefix of the current module, used as key in + qconfig_dict + prepare_custom_config_dict: dictionary for custom handling of modules + see docs for :func:`~torch.ao.quantization.prepare_fx` + + Return: + None, module is modified inplace with qconfig attached + """ + + module_qconfig = qconfig_dict.get(type_before_parametrizations(module), qconfig_parent) + module_qconfig = qconfig_dict.get(prefix, module_qconfig) + module_qconfig = getattr(module, 'qconfig', module_qconfig) + + torch.ao.quantization.qconfig._assert_valid_qconfig(module_qconfig, module) + + qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(module_qconfig, module) + module.qconfig = qconfig_with_device_check + + for name, child in module.named_children(): + module_prefix = prefix + '.' + name if prefix else name + # do no not propagate qconfig to child if child is non traceable + if prepare_custom_config_dict is None or not ( + name in prepare_custom_config_dict.get("non_traceable_module_name", []) + or type(child) in prepare_custom_config_dict.get("non_traceable_module_class", []) + ): + _propagate_qconfig_helper( + child, qconfig_dict, qconfig_with_device_check, module_prefix + ) + +def propagate_qconfig_(module, qconfig_dict=None, prepare_custom_config_dict=None): + r"""Propagate qconfig through the module hierarchy and assign `qconfig` + attribute on each leaf module + + Args: + module: input module + qconfig_dict: dictionary that maps from name or type of submodule to + quantization configuration, qconfig applies to all submodules of a + given module unless qconfig for the submodules are specified (when + the submodule already has qconfig attribute) + prepare_custom_config_dict: dictionary for custom handling of modules + see docs for :func:`~torch.ao.quantization.prepare_fx` + + Return: + None, module is modified inplace with qconfig attached + """ + if qconfig_dict is None: + qconfig_dict = {} + if prepare_custom_config_dict is None: + prepare_custom_config_dict = {} + _propagate_qconfig_helper(module, qconfig_dict, prepare_custom_config_dict=prepare_custom_config_dict) + +def _observer_forward_hook(self, input, output): + r"""Forward hook that calls observer on the output + """ + return self.activation_post_process(output) + +def _observer_forward_pre_hook(self, input): + r"""Forward pre hook that calls observer on the output + """ + return self.activation_post_process(input[0]) + +def _register_activation_post_process_hook(module, pre_hook=False): + assert hasattr(module, 'activation_post_process'), \ + 'Expect activation_post_process attribute already attached to the module' + if pre_hook: + handle = module.register_forward_pre_hook( + _observer_forward_pre_hook, prepend=True + ) + else: + handle = module.register_forward_hook( + _observer_forward_hook, prepend=True + ) + + +def _add_observer_(module, qconfig_propagation_list=None, non_leaf_module_list=None, device=None, custom_module_class_mapping=None): + r"""Add observer for the leaf child of the module. + + This function insert observer module to all leaf child module that + has a valid qconfig attribute. + + Args: + module: input module with qconfig attributes for all the leaf modules that we want to quantize + qconfig_propagation_list: a list of quantizable modules that will have observers added to them + if they are leaf nodes + device: parent device, if any + non_leaf_module_list: list of non-leaf modules we want to add observer + + Return: + None, module is modified inplace with added observer modules and forward_hooks + """ + if qconfig_propagation_list is None: + qconfig_propagation_list = get_default_qconfig_propagation_list() + + if custom_module_class_mapping is None: + custom_module_class_mapping = {} + + # respect device affinity when adding observers + if device is None: + devices = _get_unique_devices_(module) + assert len(devices) <= 1, ( + f"_add_observer_ only works with cpu or single-device CUDA modules, but got devices {devices}" + ) + device = next(iter(devices)) if len(devices) > 0 else None + + def get_activation_post_process(qconfig, device, special_act_post_process=None): + activation = qconfig.activation() if special_act_post_process is None else special_act_post_process() + if device is not None: + activation.to(device) + return activation + + def needs_observation(m): + return hasattr(m, 'qconfig') and m.qconfig is not None + + def insert_activation_post_process(m, special_act_post_process=None): + """ Adds an activation post process module and register + a pre or post hook that calls the module + """ + # We don't insert observer/fake_quantize for DeQuantStub + if needs_observation(m) and not isinstance(m, DeQuantStub): + # observer and hook will be gone after we swap the module + m.add_module('activation_post_process', get_activation_post_process( + m.qconfig, device, special_act_post_process)) + # Register observer as the first entry in the hook list + # All post forward hooks are preserved and will be executed after the observer before convert + _register_activation_post_process_hook(m, pre_hook=_activation_is_memoryless(m.qconfig)) + + for name, child in module.named_children(): + # TODO remove Dropout special after codebase stable + if type_before_parametrizations(child) in [nn.Dropout]: + continue + elif issubclass(type_before_parametrizations(child), (nnq.FloatFunctional, nnq.QFunctional)): + if needs_observation(child): + assert hasattr(child, "activation_post_process"), ( + f"functional class {type_before_parametrizations(child)} has no pre-defined `activation_post_process`" + ) + child.activation_post_process = get_activation_post_process(child.qconfig, device) + elif isinstance(child, _FusedModule): + # activation_post_process are now added directly to nn.Sequential/_FusedModule + if needs_observation(child): + insert_activation_post_process(child) + elif non_leaf_module_list is not None and type_before_parametrizations(child) in non_leaf_module_list: + if needs_observation(child): + insert_activation_post_process(child) + elif _has_special_act_post_process(child): + special_act_post_process = _get_special_act_post_process(child) + insert_activation_post_process(child, special_act_post_process) + elif needs_observation(child) and type_before_parametrizations(child) in custom_module_class_mapping: + observed_child = custom_module_class_mapping[type_before_parametrizations(child)].from_float(child) + setattr(module, name, observed_child) + # TODO: These are the modules that cannot be observed + # Once there are more, we should move them to a separate list + if custom_module_class_mapping[type_before_parametrizations(child)] not in no_observer_set(): + insert_activation_post_process(observed_child) + else: + _add_observer_(child, qconfig_propagation_list, non_leaf_module_list, device, custom_module_class_mapping) + + # Insert observers only for leaf nodes, note that this observer is for + # the output of the module, for input QuantStub will observe them + if has_no_children_ignoring_parametrizations(module) and not isinstance(module, torch.nn.Sequential) \ + and type_before_parametrizations(module) in qconfig_propagation_list: + insert_activation_post_process(module) + +def _get_unique_devices_(module): + return {p.device for p in module.parameters()} | \ + {p.device for p in module.buffers()} + +def add_quant_dequant(module): + r"""Wrap the leaf child module in QuantWrapper if it has a valid qconfig + Note that this function will modify the children of module inplace and it + can return a new module which wraps the input module as well. + + Args: + module: input module with qconfig attributes for all the leaf modules + that we want to quantize + + Return: + Either the inplace modified module with submodules wrapped in + `QuantWrapper` based on qconfig or a new `QuantWrapper` module which + wraps the input module, the latter case only happens when the input + module is a leaf module and we want to quantize it. + """ + if has_no_children_ignoring_parametrizations(module) and hasattr(module, 'qconfig') and module.qconfig: + return QuantWrapper(module) + + for name, child in module.named_children(): + module._modules[name] = add_quant_dequant(child) + return module + +def prepare(model, inplace=False, allow_list=None, + observer_non_leaf_module_list=None, + prepare_custom_config_dict=None): + r"""Prepares a copy of the model for quantization calibration or quantization-aware training. + + Quantization configuration should be assigned preemptively + to individual submodules in `.qconfig` attribute. + + The model will be attached with observer or fake quant modules, and qconfig + will be propagated. + + Args: + `model`: input model to be modified in-place + `inplace`: carry out model transformations in-place, the original module is mutated + `allow_list`: list of quantizable modules + `observer_non_leaf_module_list`: list of non-leaf modules we want to add observer + `prepare_custom_config_dict`: customization configuration dictionary for prepare function + + .. code-block:: python + + # Example of prepare_custom_config_dict: + prepare_custom_config_dict = { + # user will manually define the corresponding observed + # module class which has a from_float class method that converts + # float custom module to observed custom module + "float_to_observed_custom_module_class": { + CustomModule: ObservedCustomModule + } + } + + """ + torch._C._log_api_usage_once("quantization_api.quantize.prepare") + if prepare_custom_config_dict is None: + prepare_custom_config_dict = get_default_custom_config_dict() + custom_module_class_mapping = prepare_custom_config_dict.get("float_to_observed_custom_module_class", {}) + + if not inplace: + model = copy.deepcopy(model) + + # TODO: remove allow_list + qconfig_propagation_list = allow_list + if allow_list is None: + qconfig_propagation_list = get_default_qconfig_propagation_list() + propagate_qconfig_(model, qconfig_dict=None) + + # sanity check common API misusage + if not any(hasattr(m, 'qconfig') and m.qconfig for m in model.modules()): + warnings.warn("None of the submodule got qconfig applied. Make sure you " + "passed correct configuration through `qconfig_dict` or " + "by assigning the `.qconfig` attribute directly on submodules") + + _add_observer_( + model, qconfig_propagation_list, observer_non_leaf_module_list, + custom_module_class_mapping=custom_module_class_mapping) + return model + +def _remove_activation_post_process(module): + # TODO: maybe we should change activation_post_process to _activation_post_process + # to prevent it from being used by user + if hasattr(module, 'activation_post_process') and \ + _is_activation_post_process(module.activation_post_process): + delattr(module, 'activation_post_process') + + # remove activation_post_process pre and post hooks + def remove_hooks(pre_hook=False): + hook_map = module._forward_pre_hooks if pre_hook else module._forward_hooks + observer_hook = _observer_forward_pre_hook if pre_hook else _observer_forward_hook + handle_ids_to_remove = set() + for handle_id, hook_fn in hook_map.items(): + if hook_fn is observer_hook: + handle_ids_to_remove.add(handle_id) + for handle_id in handle_ids_to_remove: + hook_map.pop(handle_id) + + remove_hooks(pre_hook=True) + remove_hooks(pre_hook=False) + +# TODO: rename to something more general +def _remove_qconfig(module): + r"""Clean up the qconfig left in the module so that new qconfig can be + propagated. + + Args: + module: module to be cleaned up + """ + for child in module.children(): + _remove_qconfig(child) + + if hasattr(module, "qconfig"): + del module.qconfig + + _remove_activation_post_process(module) + +def quantize(model, run_fn, run_args, mapping=None, inplace=False): + r"""Quantize the input float model with post training static quantization. + + First it will prepare the model for calibration, then it calls + `run_fn` which will run the calibration step, after that we will + convert the model to a quantized model. + + Args: + model: input float model + run_fn: a calibration function for calibrating the prepared model + run_args: positional arguments for `run_fn` + inplace: carry out model transformations in-place, the original module is mutated + mapping: correspondence between original module types and quantized counterparts + + Return: + Quantized model. + """ + torch._C._log_api_usage_once("quantization_api.quantize.quantize") + if mapping is None: + mapping = get_default_static_quant_module_mappings() + if not inplace: + model = copy.deepcopy(model) + model.eval() + prepare(model, inplace=True) + run_fn(model, *run_args) + convert(model, mapping, inplace=True) + return model + +def quantize_dynamic(model, qconfig_spec=None, dtype=torch.qint8, + mapping=None, inplace=False): + r"""Converts a float model to dynamic (i.e. weights-only) quantized model. + + Replaces specified modules with dynamic weight-only quantized versions and output the quantized model. + + For simplest usage provide `dtype` argument that can be float16 or qint8. Weight-only quantization + by default is performed for layers with large weights size - i.e. Linear and RNN variants. + + Fine grained control is possible with `qconfig` and `mapping` that act similarly to `quantize()`. + If `qconfig` is provided, the `dtype` argument is ignored. + + Args: + model: input model + qconfig_spec: Either: + + - A dictionary that maps from name or type of submodule to quantization + configuration, qconfig applies to all submodules of a given + module unless qconfig for the submodules are specified (when the + submodule already has qconfig attribute). Entries in the dictionary + need to be QConfig instances. + + - A set of types and/or submodule names to apply dynamic quantization to, + in which case the `dtype` argument is used to specify the bit-width + + inplace: carry out model transformations in-place, the original module is mutated + mapping: maps type of a submodule to a type of corresponding dynamically quantized version + with which the submodule needs to be replaced + + """ + torch._C._log_api_usage_once("quantization_api.quantize.quantize_dynamic") + if qconfig_spec is None: + if dtype == torch.qint8: + qconfig_spec = { + nn.Linear : default_dynamic_qconfig, + nn.LSTM : default_dynamic_qconfig, + nn.GRU : default_dynamic_qconfig, + nn.LSTMCell : default_dynamic_qconfig, + nn.RNNCell : default_dynamic_qconfig, + nn.GRUCell : default_dynamic_qconfig, + } + elif dtype == torch.float16: + qconfig_spec = { + nn.Linear : float16_dynamic_qconfig, + nn.LSTM : float16_dynamic_qconfig, + nn.GRU : float16_dynamic_qconfig, + nn.LSTMCell : float16_dynamic_qconfig, + nn.RNNCell : float16_dynamic_qconfig, + nn.GRUCell : float16_dynamic_qconfig, + } + elif dtype == torch.quint8: + qconfig_spec = { + nn.EmbeddingBag : float_qparams_weight_only_qconfig, + nn.Embedding : float_qparams_weight_only_qconfig, + } + elif dtype == torch.quint4x2: + qconfig_spec = { + nn.EmbeddingBag : float_qparams_weight_only_qconfig_4bit, + } + else: + raise ValueError( + f"Don't know how to quantize with default settings for {dtype}. Provide full qconfig please") + elif isinstance(qconfig_spec, set): + if dtype is torch.qint8: + default_qconfig = default_dynamic_qconfig + elif dtype is torch.float16: + default_qconfig = float16_dynamic_qconfig + elif dtype is torch.quint8: + default_qconfig = float_qparams_weight_only_qconfig + elif dtype is torch.quint4x2: + default_qconfig = float_qparams_weight_only_qconfig_4bit + else: + raise RuntimeError('Unknown dtype specified for quantize_dynamic: ', str(dtype)) + qconfig_spec = dict(zip(qconfig_spec, itertools.repeat(default_qconfig))) + + if mapping is None: + mapping = get_default_dynamic_quant_module_mappings() + + if not inplace: + model = copy.deepcopy(model) + model.eval() + propagate_qconfig_(model, qconfig_spec) + convert(model, mapping, inplace=True) + return model + +def prepare_qat(model, mapping=None, inplace=False): + r""" + Prepares a copy of the model for quantization calibration or + quantization-aware training and converts it to quantized version. + + Quantization configuration should be assigned preemptively + to individual submodules in `.qconfig` attribute. + + Args: + model: input model to be modified in-place + mapping: dictionary that maps float modules to quantized modules to be + replaced. + inplace: carry out model transformations in-place, the original module + is mutated + """ + torch._C._log_api_usage_once("quantization_api.quantize.prepare_qat") + assert model.training, "prepare_qat only works on models in training mode" + if mapping is None: + mapping = get_default_qat_module_mappings() + + if not inplace: + model = copy.deepcopy(model) + + propagate_qconfig_(model, qconfig_dict=None) + convert(model, mapping=mapping, inplace=True, remove_qconfig=False) + prepare(model, observer_non_leaf_module_list=set(mapping.values()), inplace=True) + return model + +def quantize_qat(model, run_fn, run_args, inplace=False): + r"""Do quantization aware training and output a quantized model + + Args: + model: input model + run_fn: a function for evaluating the prepared model, can be a + function that simply runs the prepared model or a training + loop + run_args: positional arguments for `run_fn` + + Return: + Quantized model. + """ + torch._C._log_api_usage_once("quantization_api.quantize.quantize_qat") + if not inplace: + model = copy.deepcopy(model) + model.train() + prepare_qat(model, inplace=True) + run_fn(model, *run_args) + convert(model, inplace=True) + return model + +def convert( + module, mapping=None, inplace=False, remove_qconfig=True, + is_reference=False, convert_custom_config_dict=None): + r"""Converts submodules in input module to a different module according to `mapping` + by calling `from_float` method on the target module class. And remove qconfig at the + end if remove_qconfig is set to True. + + Args: + `module`: prepared and calibrated module + `mapping`: a dictionary that maps from source module type to target + module type, can be overwritten to allow swapping user defined + Modules + `inplace`: carry out model transformations in-place, the original module + is mutated + `convert_custom_config_dict`: custom configuration dictionary for convert function + + .. code-block:: python + + # Example of convert_custom_config_dict: + convert_custom_config_dict = { + # user will manually define the corresponding quantized + # module class which has a from_observed class method that converts + # observed custom module to quantized custom module + "observed_to_quantized_custom_module_class": { + ObservedCustomModule: QuantizedCustomModule + } + } + + """ + torch._C._log_api_usage_once("quantization_api.quantize.convert") + if not inplace: + module = copy.deepcopy(module) + _convert( + module, mapping, inplace=True, is_reference=is_reference, + convert_custom_config_dict=convert_custom_config_dict) + if remove_qconfig: + _remove_qconfig(module) + return module + +def _convert( + module, mapping=None, inplace=False, + is_reference=False, convert_custom_config_dict=None): + r"""Converts submodules in input module to a different module according to `mapping` + by calling `from_float` method on the target module class + + Args: + module: input module + mapping: a dictionary that maps from source module type to target + module type, can be overwritten to allow swapping user defined + Modules + inplace: carry out model transformations in-place, the original module + is mutated + is_reference: a flag to enable quantized reference module + + """ + if mapping is None: + mapping = get_default_static_quant_reference_module_mappings() if is_reference \ + else get_default_static_quant_module_mappings() + if convert_custom_config_dict is None: + convert_custom_config_dict = get_default_custom_config_dict() + custom_module_class_mapping = convert_custom_config_dict.get("observed_to_quantized_custom_module_class", {}) + + if not inplace: + module = copy.deepcopy(module) + reassign = {} + for name, mod in module.named_children(): + # both fused modules and observed custom modules are + # swapped as one unit + if not isinstance(mod, _FusedModule) and \ + type_before_parametrizations(mod) not in custom_module_class_mapping: + _convert(mod, mapping, True, # inplace + is_reference, convert_custom_config_dict) + reassign[name] = swap_module(mod, mapping, custom_module_class_mapping) + + for key, value in reassign.items(): + module._modules[key] = value + + return module + +def swap_module(mod, mapping, custom_module_class_mapping): + r"""Swaps the module if it has a quantized counterpart and it has an + `observer` attached. + + Args: + mod: input module + mapping: a dictionary that maps from nn module to nnq module + + Return: + The corresponding quantized module of `mod` + """ + new_mod = mod + if hasattr(mod, 'qconfig') and mod.qconfig is not None: + swapped = False + if type_before_parametrizations(mod) in custom_module_class_mapping: + new_mod = custom_module_class_mapping[type_before_parametrizations(mod)].from_observed(mod) + swapped = True + elif type_before_parametrizations(mod) in mapping: + qmod = mapping[type_before_parametrizations(mod)] + if hasattr(qmod, '_IS_REFERENCE') and qmod._IS_REFERENCE: + assert mod.qconfig is not None + weight_post_process = mod.qconfig.weight() + weight_post_process(mod.weight) + weight_qparams = get_qparam_dict(weight_post_process) + new_mod = qmod.from_float(mod, weight_qparams) + else: + new_mod = qmod.from_float(mod) + swapped = True + + if swapped: + # Preserve module's pre forward hooks. They'll be called on quantized input + for pre_hook_fn in mod._forward_pre_hooks.values(): + new_mod.register_forward_pre_hook(pre_hook_fn) + # Preserve module's post forward hooks except _observer_forward_hook + # After convert they'll work with quantized output + for hook_fn in mod._forward_hooks.values(): + if hook_fn is not _observer_forward_hook: + new_mod.register_forward_hook(hook_fn) + + # respect device affinity when swapping modules + devices = _get_unique_devices_(mod) + assert len(devices) <= 1, ( + f"swap_module only works with cpu or single-device CUDA modules, but got devices {devices}" + ) + device = next(iter(devices)) if len(devices) > 0 else None + if device: + new_mod.to(device) + return new_mod + +def _get_observer_dict(mod, target_dict, prefix=""): + r"""Traverse the modules and save all observers into dict. + This is mainly used for quantization accuracy debug + Args: + mod: the top module we want to save all observers + prefix: the prefix for the current module + target_dict: the dictionary used to save all the observers + """ + def get_prefix(prefix): + return prefix if prefix == "" else prefix + '.' + + if hasattr(mod, 'activation_post_process'): + target_dict[get_prefix(prefix) + 'activation_post_process'] = mod.activation_post_process + for name, child in mod.named_children(): + module_prefix = get_prefix(prefix) + name if prefix else name + _get_observer_dict(child, target_dict, module_prefix) diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_fx.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_fx.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a3db87552aeccc5763c5a3cc6449547d5afb53 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_fx.py @@ -0,0 +1,726 @@ +from typing import Any, Dict, Optional, Tuple, Union +import warnings + +import torch +import copy +from torch.fx import GraphModule +from torch.fx.graph_module import _USER_PRESERVED_ATTRIBUTES_KEY +from .fx.tracer import QuantizationTracer +from .fx.tracer import ( # noqa: F401 + Scope, + ScopeContextManager +) +from .fx.fuse import fuse # noqa: F401 +from .fx.prepare import prepare # noqa: F401 +from .fx.convert import convert +from .backend_config import ( # noqa: F401 + BackendConfig, + get_tensorrt_backend_config, +) +from .fx.graph_module import ObservedGraphModule # noqa: F401 +from .fx.custom_config import ( + ConvertCustomConfig, + FuseCustomConfig, + PrepareCustomConfig, +) +from .fx.utils import get_custom_module_class_keys # noqa: F401 +from .fx.utils import get_skipped_module_name_and_classes +from .qconfig_mapping import QConfigMapping + +def attach_preserved_attrs_to_model( + model: Union[GraphModule, torch.nn.Module], + preserved_attrs: Dict[str, Any], +) -> None: + """ Store preserved attributes to the model.meta so that it can be preserved during deepcopy + """ + model.meta[_USER_PRESERVED_ATTRIBUTES_KEY] = copy.copy(preserved_attrs) # type: ignore[operator, index, assignment] + # set the preserved attributes in the model so that user can call + # model.attr as they do before calling fx graph mode quantization + for attr_name, attr in model.meta[_USER_PRESERVED_ATTRIBUTES_KEY].items(): # type: ignore[index, union-attr] + setattr(model, attr_name, attr) + +def _check_is_graph_module(model: torch.nn.Module) -> None: + if not isinstance(model, GraphModule): + raise ValueError( + "input model must be a GraphModule, " + + "Got type:" + + str(type(model)) + + " Please make " + + "sure to follow the tutorials." + ) + +def _attach_meta_to_node_if_not_exist(model: GraphModule) -> None: + """ Attach meta field to all nodes of the graph if it does not exist, + meta field is a field stores some meta information about the node, such + as dtype and shape information for output of the node, this only exists + if the program is captured by make_fx (used in quantize_pt2e flow), if + the program is captured by torch.fx symbolic tracing, this field may not exist, + so we add it here to avoid checking this all over the places + """ + for node in model.graph.nodes: + if not hasattr(node, "meta"): + node.meta = {} + +def _swap_ff_with_fxff(model: torch.nn.Module) -> None: + r""" Swap FloatFunctional with FXFloatFunctional + """ + modules_to_swap = [] + for name, module in model.named_children(): + if isinstance(module, torch.ao.nn.quantized.FloatFunctional): + modules_to_swap.append(name) + else: + _swap_ff_with_fxff(module) + + for name in modules_to_swap: + del model._modules[name] + model._modules[name] = torch.ao.nn.quantized.FXFloatFunctional() + + +def _fuse_fx( + model: GraphModule, + is_qat: bool, + fuse_custom_config: Union[FuseCustomConfig, Dict[str, Any], None] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, +) -> GraphModule: + r""" Internal helper function to fuse modules in preparation for quantization + + Args: + model: GraphModule object from symbolic tracing (torch.fx.symbolic_trace) + """ + _check_is_graph_module(model) + return fuse( + model, is_qat, fuse_custom_config, backend_config) # type: ignore[operator] + +def _prepare_fx( + model: torch.nn.Module, + qconfig_mapping: Union[QConfigMapping, Dict[str, Any]], + is_qat: bool, + example_inputs: Tuple[Any, ...], + prepare_custom_config: Union[PrepareCustomConfig, Dict[str, Any], None] = None, + _equalization_config: Optional[Union[QConfigMapping, Dict[str, Any]]] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, + is_standalone_module: bool = False, +) -> GraphModule: + r""" Internal helper function for prepare_fx + Args: + `model`, `qconfig_mapping`, `prepare_custom_config`, `_equalization_config`: + see docs for :func:`~torch.ao.quantization.prepare_fx` + `is_standalone_module`: a boolean flag indicates whether we are + quantizing a standalone module or not, a standalone module + is a submodule of the parent module that is not inlined in the +forward graph of the parent module, + the way we quantize standalone module is described in: + :func:`~torch.ao.quantization._prepare_standalone_module_fx` + """ + if prepare_custom_config is None: + prepare_custom_config = PrepareCustomConfig() + if _equalization_config is None: + _equalization_config = QConfigMapping() + + if isinstance(prepare_custom_config, Dict): + warnings.warn( + "Passing a prepare_custom_config_dict to prepare is deprecated and will not be supported " + "in a future version. Please pass in a PrepareCustomConfig instead.") + prepare_custom_config = PrepareCustomConfig.from_dict(prepare_custom_config) + + # swap FloatFunctional with FXFloatFunctional + _swap_ff_with_fxff(model) + + skipped_module_names, skipped_module_classes = \ + get_skipped_module_name_and_classes(prepare_custom_config, is_standalone_module) + preserved_attr_names = prepare_custom_config.preserved_attributes + preserved_attrs = {attr: getattr(model, attr) for attr in preserved_attr_names if hasattr(model, attr)} + # symbolically trace the model + tracer = QuantizationTracer(skipped_module_names, skipped_module_classes) # type: ignore[arg-type] + graph_module = GraphModule(model, tracer.trace(model)) + _attach_meta_to_node_if_not_exist(graph_module) + + fuse_custom_config = FuseCustomConfig().set_preserved_attributes(prepare_custom_config.preserved_attributes) + graph_module = _fuse_fx( + graph_module, + is_qat, + fuse_custom_config, + backend_config) + prepared = prepare( + graph_module, + qconfig_mapping, + is_qat, + tracer.node_name_to_scope, + example_inputs=example_inputs, + prepare_custom_config=prepare_custom_config, + _equalization_config=_equalization_config, + backend_config=backend_config, + is_standalone_module=is_standalone_module, + ) # type: ignore[operator] + + attach_preserved_attrs_to_model(prepared, preserved_attrs) + return prepared + + +def _prepare_standalone_module_fx( + model: torch.nn.Module, + qconfig_mapping: Union[QConfigMapping, Dict[str, Any]], + is_qat: bool, + example_inputs: Tuple[Any, ...], + prepare_custom_config: Union[PrepareCustomConfig, Dict[str, Any], None] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, +) -> GraphModule: + r""" [Internal use only] Prepare a standalone module, so that it can be used when quantizing the + parent module. + standalone_module means it a submodule that is not inlined in parent module, + and will be quantized separately as one unit. + + How the standalone module is observed is specified by `input_quantized_idxs` and + `output_quantized_idxs` in the prepare_custom_config for the standalone module + + Returns: + + * model(GraphModule): prepared standalone module. It has these attributes in + model.meta: + + * `standalone_module_input_quantized_idxs(List[Int])`: a list of + indexes for the graph input that is expected to be quantized, + same as input_quantized_idxs configuration provided + for the standalone module + * `standalone_module_output_quantized_idxs(List[Int])`: a list of + indexs for the graph output that is quantized + same as input_quantized_idxs configuration provided + for the standalone module + + """ + return _prepare_fx( + model, + qconfig_mapping, + is_qat, + example_inputs, + prepare_custom_config, + backend_config=backend_config, + is_standalone_module=True, + ) + + +def fuse_fx( + model: torch.nn.Module, + fuse_custom_config: Union[FuseCustomConfig, Dict[str, Any], None] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, +) -> GraphModule: + r""" Fuse modules like conv+bn, conv+bn+relu etc, model must be in eval mode. + Fusion rules are defined in torch.ao.quantization.fx.fusion_pattern.py + + Args: + + * `model` (torch.nn.Module): a torch.nn.Module model + * `fuse_custom_config` (FuseCustomConfig): custom configurations for fuse_fx. + See :class:`~torch.ao.quantization.fx.custom_config.FuseCustomConfig` for more details + Example:: + + from torch.ao.quantization import fuse_fx + m = Model().eval() + m = fuse_fx(m) + + """ + if fuse_custom_config is None: + fuse_custom_config = FuseCustomConfig() + + if isinstance(fuse_custom_config, Dict): + warnings.warn( + "Passing a fuse_custom_config_dict to fuse is deprecated and will not be supported " + "in a future version. Please pass in a FuseCustomConfig instead.") + fuse_custom_config = FuseCustomConfig.from_dict(fuse_custom_config) + + torch._C._log_api_usage_once("quantization_api.quantize_fx.fuse_fx") + preserved_attr_names = fuse_custom_config.preserved_attributes + preserved_attrs = {attr: getattr(model, attr) for attr in preserved_attr_names if hasattr(model, attr)} + + graph_module = torch.fx.symbolic_trace(model) + _attach_meta_to_node_if_not_exist(graph_module) + graph_module = _fuse_fx(graph_module, False, fuse_custom_config, backend_config) + + attach_preserved_attrs_to_model(graph_module, preserved_attrs) + return graph_module + +def prepare_fx( + model: torch.nn.Module, + qconfig_mapping: Union[QConfigMapping, Dict[str, Any]], + example_inputs: Tuple[Any, ...], + prepare_custom_config: Union[PrepareCustomConfig, Dict[str, Any], None] = None, + _equalization_config: Optional[Union[QConfigMapping, Dict[str, Any]]] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, +) -> GraphModule: + r""" Prepare a model for post training quantization + + Args: + * `model` (torch.nn.Module): torch.nn.Module model + + * `qconfig_mapping` (QConfigMapping): QConfigMapping object to configure how a model is + quantized, see :class:`~torch.ao.quantization.qconfig_mapping.QConfigMapping` + for more details + + * `example_inputs` (Tuple[Any, ...]): Example inputs for forward function of the model, + Tuple of positional args (keyword args can be passed as positional args as well) + + * `prepare_custom_config` (PrepareCustomConfig): customization configuration for quantization tool. + See :class:`~torch.ao.quantization.fx.custom_config.PrepareCustomConfig` for more details + + * `_equalization_config`: config for specifying how to perform equalization on the model + + * `backend_config` (BackendConfig): config that specifies how operators are quantized + in a backend, this includes how the operators are observed, + supported fusion patterns, how quantize/dequantize ops are + inserted, supported dtypes etc. See :class:`~torch.ao.quantization.backend_config.BackendConfig` for more details + + Return: + A GraphModule with observer (configured by qconfig_mapping), ready for calibration + + Example:: + + import torch + from torch.ao.quantization import get_default_qconfig_mapping + from torch.ao.quantization.quantize_fx import prepare_fx + + class Submodule(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(5, 5) + def forward(self, x): + x = self.linear(x) + return x + + class M(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(5, 5) + self.sub = Submodule() + + def forward(self, x): + x = self.linear(x) + x = self.sub(x) + x + return x + + # initialize a floating point model + float_model = M().eval() + + # define calibration function + def calibrate(model, data_loader): + model.eval() + with torch.no_grad(): + for image, target in data_loader: + model(image) + + # qconfig is the configuration for how we insert observers for a particular + # operator + # qconfig = get_default_qconfig("fbgemm") + # Example of customizing qconfig: + # qconfig = torch.ao.quantization.QConfig( + # activation=MinMaxObserver.with_args(dtype=torch.qint8), + # weight=MinMaxObserver.with_args(dtype=torch.qint8)) + # `activation` and `weight` are constructors of observer module + + # qconfig_mapping is a collection of quantization configurations, user can + # set the qconfig for each operator (torch op calls, functional calls, module calls) + # in the model through qconfig_mapping + # the following call will get the qconfig_mapping that works best for models + # that target "fbgemm" backend + qconfig_mapping = get_default_qconfig_mapping("fbgemm") + + # We can customize qconfig_mapping in different ways. + # e.g. set the global qconfig, which means we will use the same qconfig for + # all operators in the model, this can be overwritten by other settings + # qconfig_mapping = QConfigMapping().set_global(qconfig) + # e.g. quantize the linear submodule with a specific qconfig + # qconfig_mapping = QConfigMapping().set_module_name("linear", qconfig) + # e.g. quantize all nn.Linear modules with a specific qconfig + # qconfig_mapping = QConfigMapping().set_object_type(torch.nn.Linear, qconfig) + # for a more complete list, please see the docstring for :class:`torch.ao.quantization.QConfigMapping` + # argument + + # example_inputs is a tuple of inputs, that is used to infer the type of the + # outputs in the model + # currently it's not used, but please make sure model(*example_inputs) runs + example_inputs = (torch.randn(1, 3, 224, 224),) + + # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack + # e.g. backend_config = get_default_backend_config("fbgemm") + # `prepare_fx` inserts observers in the model based on qconfig_mapping and + # backend_config. If the configuration for an operator in qconfig_mapping + # is supported in the backend_config (meaning it's supported by the target + # hardware), we'll insert observer modules according to the qconfig_mapping + # otherwise the configuration in qconfig_mapping will be ignored + # + # Example: + # in qconfig_mapping, user sets linear module to be quantized with quint8 for + # activation and qint8 for weight: + # qconfig = torch.ao.quantization.QConfig( + # observer=MinMaxObserver.with_args(dtype=torch.quint8), + # weight=MinMaxObserver.with-args(dtype=torch.qint8)) + # Note: current qconfig api does not support setting output observer, but + # we may extend this to support these more fine grained control in the + # future + # + # qconfig_mapping = QConfigMapping().set_object_type(torch.nn.Linear, qconfig) + # in backend config, linear module also supports in this configuration: + # weighted_int8_dtype_config = DTypeConfig( + # input_dtype=torch.quint8, + # output_dtype=torch.quint8, + # weight_dtype=torch.qint8, + # bias_type=torch.float) + + # linear_pattern_config = BackendPatternConfig(torch.nn.Linear) \ + # .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \ + # .add_dtype_config(weighted_int8_dtype_config) \ + # ... + + # backend_config = BackendConfig().set_backend_pattern_config(linear_pattern_config) + # `prepare_fx` will check that the setting requested by suer in qconfig_mapping + # is supported by the backend_config and insert observers and fake quant modules + # in the model + prepared_model = prepare_fx(float_model, qconfig_mapping, example_inputs) + # Run calibration + calibrate(prepared_model, sample_inference_data) + """ + torch._C._log_api_usage_once("quantization_api.quantize_fx.prepare_fx") + return _prepare_fx( + model, + qconfig_mapping, + False, # is_qat + example_inputs, + prepare_custom_config, + _equalization_config, + backend_config, + ) + + +def prepare_qat_fx( + model: torch.nn.Module, + qconfig_mapping: Union[QConfigMapping, Dict[str, Any]], + example_inputs: Tuple[Any, ...], + prepare_custom_config: Union[PrepareCustomConfig, Dict[str, Any], None] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, +) -> GraphModule: + r""" Prepare a model for quantization aware training + + Args: + * `model` (torch.nn.Module): torch.nn.Module model + * `qconfig_mapping` (QConfigMapping): see :func:`~torch.ao.quantization.prepare_fx` + * `example_inputs` (Tuple[Any, ...]): see :func:`~torch.ao.quantization.prepare_fx` + * `prepare_custom_config` (PrepareCustomConfig): see :func:`~torch.ao.quantization.prepare_fx` + * `backend_config` (BackendConfig): see :func:`~torch.ao.quantization.prepare_fx` + + Return: + A GraphModule with fake quant modules (configured by qconfig_mapping and backend_config), ready for + quantization aware training + + Example:: + + import torch + from torch.ao.quantization import get_default_qat_qconfig_mapping + from torch.ao.quantization.quantize_fx import prepare_qat_fx + + class Submodule(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(5, 5) + def forward(self, x): + x = self.linear(x) + return x + + class M(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(5, 5) + self.sub = Submodule() + + def forward(self, x): + x = self.linear(x) + x = self.sub(x) + x + return x + + # initialize a floating point model + float_model = M().train() + # (optional, but preferred) load the weights from pretrained model + # float_model.load_weights(...) + + # define the training loop for quantization aware training + def train_loop(model, train_data): + model.train() + for image, target in data_loader: + ... + + # qconfig is the configuration for how we insert observers for a particular + # operator + # qconfig = get_default_qconfig("fbgemm") + # Example of customizing qconfig: + # qconfig = torch.ao.quantization.QConfig( + # activation=FakeQuantize.with_args(observer=MinMaxObserver.with_args(dtype=torch.qint8)), + # weight=FakeQuantize.with_args(observer=MinMaxObserver.with_args(dtype=torch.qint8))) + # `activation` and `weight` are constructors of observer module + + # qconfig_mapping is a collection of quantization configurations, user can + # set the qconfig for each operator (torch op calls, functional calls, module calls) + # in the model through qconfig_mapping + # the following call will get the qconfig_mapping that works best for models + # that target "fbgemm" backend + qconfig_mapping = get_default_qat_qconfig("fbgemm") + + # We can customize qconfig_mapping in different ways, please take a look at + # the docstring for :func:`~torch.ao.quantization.prepare_fx` for different ways + # to configure this + + # example_inputs is a tuple of inputs, that is used to infer the type of the + # outputs in the model + # currently it's not used, but please make sure model(*example_inputs) runs + example_inputs = (torch.randn(1, 3, 224, 224),) + + # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack + # e.g. backend_config = get_default_backend_config("fbgemm") + # `prepare_qat_fx` inserts observers in the model based on qconfig_mapping and + # backend_config, if the configuration for an operator in qconfig_mapping + # is supported in the backend_config (meaning it's supported by the target + # hardware), we'll insert fake_quantize modules according to the qconfig_mapping + # otherwise the configuration in qconfig_mapping will be ignored + # see :func:`~torch.ao.quantization.prepare_fx` for a detailed explanation of + # how qconfig_mapping interacts with backend_config + prepared_model = prepare_qat_fx(float_model, qconfig_mapping, example_inputs) + # Run training + train_loop(prepared_model, train_loop) + + """ + torch._C._log_api_usage_once("quantization_api.quantize_fx.prepare_qat_fx") + return _prepare_fx( + model, + qconfig_mapping, + True, # is_qat + example_inputs, + prepare_custom_config, + backend_config=backend_config, + ) + + +def _convert_fx( + graph_module: GraphModule, + is_reference: bool, + convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None, + is_standalone_module: bool = False, + _remove_qconfig: bool = True, + qconfig_mapping: Union[QConfigMapping, Dict[str, Any], None] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, + is_decomposed: bool = False, +) -> GraphModule: + """ `is_standalone_module`: see docs in :func:`~torch.ao.quantization.prepare_standalone_module_fx` + """ + if convert_custom_config is None: + convert_custom_config = ConvertCustomConfig() + + if isinstance(convert_custom_config, Dict): + warnings.warn( + "Passing a convert_custom_config_dict to convert is deprecated and will not be supported " + "in a future version. Please pass in a ConvertCustomConfig instead.") + convert_custom_config = ConvertCustomConfig.from_dict(convert_custom_config) + + _check_is_graph_module(graph_module) + preserved_attr_names = convert_custom_config.preserved_attributes + preserved_attrs = {attr: getattr(graph_module, attr) for attr in preserved_attr_names if hasattr(graph_module, attr)} + + quantized = convert( + graph_module, + is_reference, + convert_custom_config, + is_standalone_module, + _remove_qconfig_flag=_remove_qconfig, + qconfig_mapping=qconfig_mapping, + backend_config=backend_config, + is_decomposed=is_decomposed, + ) + + attach_preserved_attrs_to_model(quantized, preserved_attrs) + return quantized + + +def convert_fx( + graph_module: GraphModule, + convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None, + _remove_qconfig: bool = True, + qconfig_mapping: Union[QConfigMapping, Dict[str, Any], None] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, +) -> GraphModule: + r""" Convert a calibrated or trained model to a quantized model + + Args: + * `graph_module` (torch.fx.GraphModule): A prepared and calibrated/trained model (GraphModule) + + * `convert_custom_config` (ConvertCustomConfig): custom configurations for convert function. + See :class:`~torch.ao.quantization.fx.custom_config.ConvertCustomConfig` for more details + + * `_remove_qconfig` (bool): Option to remove the qconfig attributes in the model after convert. + + * `qconfig_mapping` (QConfigMapping): config for specifying how to convert a model for quantization. + + The keys must include the ones in the qconfig_mapping passed to `prepare_fx` or `prepare_qat_fx`, + with the same values or `None`. Additional keys can be specified with values set to `None`. + + For each entry whose value is set to None, we skip quantizing that entry in the model:: + + qconfig_mapping = QConfigMapping + .set_global(qconfig_from_prepare) + .set_object_type(torch.nn.functional.add, None) # skip quantizing torch.nn.functional.add + .set_object_type(torch.nn.functional.linear, qconfig_from_prepare) + .set_module_name("foo.bar", None) # skip quantizing module "foo.bar" + + * `backend_config` (BackendConfig): A configuration for the backend which describes how + operators should be quantized in the backend, this includes quantization + mode support (static/dynamic/weight_only), dtype support (quint8/qint8 etc.), + observer placement for each operators and fused operators. + See :class:`~torch.ao.quantization.backend_config.BackendConfig` for more details + + Return: + A quantized model (torch.nn.Module) + + Example:: + + # prepared_model: the model after prepare_fx/prepare_qat_fx and calibration/training + # convert_fx converts a calibrated/trained model to a quantized model for the + # target hardware, this includes converting the model first to a reference + # quantized model, and then lower the reference quantized model to a backend + # Currently, the supported backends are fbgemm (onednn), qnnpack (xnnpack) and + # they share the same set of quantized operators, so we are using the same + # lowering procedure + # + # backend_config defines the corresponding reference quantized module for + # the weighted modules in the model, e.g. nn.Linear + # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack + # e.g. backend_config = get_default_backend_config("fbgemm") + quantized_model = convert_fx(prepared_model) + + """ + torch._C._log_api_usage_once("quantization_api.quantize_fx.convert_fx") + return _convert_fx( + graph_module, + is_reference=False, + convert_custom_config=convert_custom_config, + _remove_qconfig=_remove_qconfig, + qconfig_mapping=qconfig_mapping, + backend_config=backend_config, + ) + + +def convert_to_reference_fx( + graph_module: GraphModule, + convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None, + _remove_qconfig: bool = True, + qconfig_mapping: Union[QConfigMapping, Dict[str, Any], None] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, +) -> GraphModule: + r""" Convert a calibrated or trained model to a reference quantized model, + see https://github.com/pytorch/rfcs/blob/master/RFC-0019-Extending-PyTorch-Quantization-to-Custom-Backends.md for more details, + reference quantized model is a standard representation of a quantized model provided + by FX Graph Mode Quantization, it can be further lowered to run on the target + hardware, like accelerators + + Args: + * `graph_module` (GraphModule): A prepared and calibrated/trained model (GraphModule) + + * `convert_custom_config` (ConvertCustomConfig): custom configurations for convert function. + See :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details. + + * `_remove_qconfig` (bool): Option to remove the qconfig attributes in the model after convert. + + * `qconfig_mapping` (QConfigMapping): config for specifying how to convert a model for quantization. + See :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details. + + * `backend_config` (BackendConfig): A configuration for the backend which describes how + operators should be quantized in the backend. See + :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details. + + Return: + A reference quantized model (GraphModule) + + Example:: + + # prepared_model: the model after prepare_fx/prepare_qat_fx and calibration/training + # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack + # e.g. backend_config = get_default_backend_config("fbgemm") + reference_quantized_model = convert_to_reference_fx(prepared_model) + + """ + torch._C._log_api_usage_once("quantization_api.quantize_fx.convert_to_reference_fx") + return _convert_fx( + graph_module, + is_reference=True, + convert_custom_config=convert_custom_config, + _remove_qconfig=_remove_qconfig, + qconfig_mapping=qconfig_mapping, + backend_config=backend_config, + ) + +def _convert_to_reference_decomposed_fx( + graph_module: GraphModule, + convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None, + qconfig_mapping: Union[QConfigMapping, Dict[str, Any], None] = None, + backend_config: Union[BackendConfig, Dict[str, Any], None] = None, +) -> GraphModule: + r""" Convert a calibrated or trained model to a reference quantized model, with + decomposed representation for quantized Tensor + see https://github.com/pytorch/rfcs/blob/master/RFC-0019-Extending-PyTorch-Quantization-to-Custom-Backends.md for more details, + reference quantized model is a standard representation of a quantized model provided + by FX Graph Mode Quantization, it can be further lowered to run on the target + hardware, like accelerators + + Note: this is not public API + + Args: + * `graph_module` (GraphModule): A prepared and calibrated/trained model (GraphModule) + + * `convert_custom_config` (ConvertCustomConfig): custom configurations for convert function. + See :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details. + + * `_remove_qconfig` (bool): Option to remove the qconfig attributes in the model after convert. + + * `qconfig_mapping` (QConfigMapping): config for specifying how to convert a model for quantization. + See :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details. + + * `backend_config` (BackendConfig): A configuration for the backend which describes how + operators should be quantized in the backend. See + :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details. + + Return: + A reference quantized model (GraphModule) with operators working with decomposed quantized Tensor + + Example:: + + # prepared_model: the model after prepare_fx/prepare_qat_fx and calibration/training + # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack + # e.g. backend_config = get_default_backend_config("fbgemm") + reference_quantized_model = _convert_to_reference_decomposed_fx(prepared_model) + + """ + torch._C._log_api_usage_once("quantization_api.quantize_fx._convert_to_reference_decomposed_fx") + return _convert_fx( + graph_module, + is_reference=True, + convert_custom_config=convert_custom_config, + _remove_qconfig=False, + qconfig_mapping=qconfig_mapping, + backend_config=backend_config, + is_decomposed=True, + ) + + +def _convert_standalone_module_fx( + graph_module: GraphModule, + is_reference: bool = False, + convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None, +) -> GraphModule: + r""" [Internal use only] Convert a model produced by :func:`~torch.ao.quantization.prepare_standalone_module_fx` + and convert it to a quantized model + + Returns a quantized standalone module, whether input/output is quantized is + specified by prepare_custom_config, with + input_quantized_idxs, output_quantized_idxs, please + see docs for prepare_fx for details + """ + return _convert_fx( + graph_module, + is_reference, + convert_custom_config, + is_standalone_module=True, + ) diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_jit.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_jit.py new file mode 100644 index 0000000000000000000000000000000000000000..632fc1db2327235fc66a2dc1d49b76c0316b5be1 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_jit.py @@ -0,0 +1,335 @@ + +import torch +from torch.ao.quantization.qconfig import QConfig +from torch.ao.quantization.quant_type import QuantType +from torch.jit._recursive import wrap_cpp_module + +__all__ = [ + "script_qconfig", + "script_qconfig_dict", + "fuse_conv_bn_jit", + "prepare_jit", + "prepare_dynamic_jit", + "convert_jit", + "convert_dynamic_jit", + "quantize_jit", + "quantize_dynamic_jit", +] + +def _check_is_script_module(model): + if not isinstance(model, torch.jit.ScriptModule): + raise ValueError('input must be a script module, got: ' + str(type(model))) + +def _check_forward_method(model): + if not model._c._has_method('forward'): + raise ValueError('input script module does not have forward method') + +def script_qconfig(qconfig): + r"""Instantiate the activation and weight observer modules and script + them, these observer module instances will be deepcopied during + prepare_jit step. + """ + return QConfig( + activation=torch.jit.script(qconfig.activation())._c, + weight=torch.jit.script(qconfig.weight())._c) + +def script_qconfig_dict(qconfig_dict): + r"""Helper function used by `prepare_jit`. + Apply `script_qconfig` for all entries in `qconfig_dict` that is + not None. + """ + return {k: script_qconfig(v) if v else None for k, v in qconfig_dict.items()} + +def fuse_conv_bn_jit(model, inplace=False): + r""" Fuse conv - bn module + Works for eval model only. + + Args: + model: TorchScript model from scripting or tracing + """ + torch._C._log_api_usage_once("quantization_api.quantize_jit.fuse_conv_bn_jit") + model_c = model._c + model_c = torch._C._jit_pass_fold_convbn(model_c) + if inplace: + model._reconstruct(model_c) + else: + model = wrap_cpp_module(model_c) + return model + +def _prepare_jit(model, qconfig_dict, inplace=False, quant_type=QuantType.STATIC): + _check_is_script_module(model) + _check_forward_method(model) + if not all(isinstance(x, str) for x in qconfig_dict.keys()): + raise ValueError('qconfig_dict should only contain names(str) as keys.') + scripted_qconfig_dict = script_qconfig_dict(qconfig_dict) + model = fuse_conv_bn_jit(model, inplace) + model_c = torch._C._jit_pass_insert_observers(model._c, + 'forward', + scripted_qconfig_dict, + inplace, + quant_type) + if inplace: + model._reconstruct(model_c) + else: + model = wrap_cpp_module(model_c) + return model + +def _prepare_ondevice_jit(model, qconfig_dict, method_name='forward', inplace=False, quant_type=QuantType.STATIC): + _check_is_script_module(model) + if not all(isinstance(x, str) for x in qconfig_dict.keys()): + raise ValueError('qconfig_dict should only contain names(str) as keys.') + scripted_qconfig_dict = script_qconfig_dict(qconfig_dict) + method_graph = model._c._get_method(method_name).graph + torch._C._jit_pass_inline(method_graph) + model = fuse_conv_bn_jit(model, inplace) + model_c = torch._C._jit_pass_insert_observer_method_for_ondevice_ptq(model._c, + method_name, + scripted_qconfig_dict, + inplace, + quant_type) + if inplace: + model._reconstruct(model_c) + else: + model = wrap_cpp_module(model_c) + return model + +def prepare_jit(model, qconfig_dict, inplace=False): + torch._C._log_api_usage_once("quantization_api.quantize_jit.prepare_jit") + return _prepare_jit(model, qconfig_dict, inplace, quant_type=QuantType.STATIC) + +def prepare_dynamic_jit(model, qconfig_dict, inplace=False): + torch._C._log_api_usage_once("quantization_api.quantize_jit.prepare_dynamic_jit") + return _prepare_jit(model, qconfig_dict, inplace, quant_type=QuantType.DYNAMIC) + + +def _prepare_ondevice_dynamic_jit(model, qconfig_dict, method_name='forward', inplace=False): + return _prepare_ondevice_jit(model, qconfig_dict, method_name, inplace, quant_type=QuantType.DYNAMIC) + +def _convert_jit(model, inplace=False, debug=False, quant_type=QuantType.STATIC, + preserved_attrs=None): + _check_is_script_module(model) + model.eval() + model_c = model._c + model_c = torch._C._jit_pass_insert_quant_dequant(model_c, 'forward', inplace, debug, quant_type) + if not debug: + is_xpu = all(p.device.type == 'xpu' for p in model.parameters()) + if not is_xpu: + # Moving model parameters to CPU since quantized operators + # are only supported on CPU and XPU right now + model.cpu() + if preserved_attrs is None: + preserved_attrs = [] + model_c = torch._C._jit_pass_quant_finalize(model_c, quant_type, preserved_attrs) + if inplace: + model._reconstruct(model_c) + else: + model = wrap_cpp_module(model_c) + torch._C._jit_pass_constant_propagation(model.graph) + torch._C._jit_pass_dce(model.graph) + return model + + +def _convert_ondevice_jit(model, method_name, inplace=False, debug=False, quant_type=QuantType.STATIC): + _check_is_script_module(model) + assert quant_type == QuantType.DYNAMIC, "This API, while should work for static quant, is only tested for dynamic quant." + assert not method_name.startswith("observe_"), "Pass in valid method to be quantized, e.g. forward" + observe_method_name = "observe_" + method_name + quantize_method_name = "quantize_" + method_name + model_c = model._c + model_c = torch._C._jit_pass_insert_quant_dequant_for_ondevice_ptq( + model._c, observe_method_name, inplace, debug, QuantType.DYNAMIC) + model_c = torch._C._jit_pass_quant_finalize_for_ondevice_ptq(model_c, QuantType.DYNAMIC, quantize_method_name) + if inplace: + model._reconstruct(model_c) + else: + model = wrap_cpp_module(model_c) + return model + +def convert_jit(model, inplace=False, debug=False, preserved_attrs=None): + torch._C._log_api_usage_once("quantization_api.quantize_jit.convert_jit") + return _convert_jit(model, inplace, debug, quant_type=QuantType.STATIC, preserved_attrs=preserved_attrs) + +def convert_dynamic_jit(model, inplace=False, debug=False, preserved_attrs=None): + torch._C._log_api_usage_once("quantization_api.quantize_jit.convert_dynamic_jit") + return _convert_jit(model, inplace, debug, quant_type=QuantType.DYNAMIC, preserved_attrs=preserved_attrs) + + +def _convert_ondevice_dynamic_jit(model, method_name, inplace=False, debug=False): + return _convert_ondevice_jit(model, method_name, inplace, debug, quant_type=QuantType.DYNAMIC) + + +def _quantize_ondevice_dynamic_jit_impl(model, qconfig_dict, method_name, inplace=False): + model = _prepare_ondevice_dynamic_jit(model, qconfig_dict, method_name, inplace) + model = _convert_ondevice_dynamic_jit(model, method_name, inplace) + return model + +def _quantize_jit(model, qconfig_dict, run_fn=None, run_args=None, inplace=False, debug=False, quant_type=QuantType.STATIC): + # Always do inplace convert because the Tensor is already + # copied in prepare_jit when inplace is False + if quant_type == QuantType.DYNAMIC: + model = prepare_dynamic_jit(model, qconfig_dict, inplace) + model = convert_dynamic_jit(model, True, debug) + else: + assert run_fn, "Must provide calibration function for post training static quantization" + assert run_args, "Must provide calibration dataset for post training static quantization" + model = prepare_jit(model, qconfig_dict, inplace) + run_fn(model, *run_args) + model = convert_jit(model, True, debug) + + torch._C._jit_pass_constant_propagation(model.graph) + torch._C._jit_pass_dce(model.graph) + return model + +def quantize_jit(model, qconfig_dict, run_fn, run_args, inplace=False, debug=False): + r"""Quantize the input float TorchScript model with + post training static quantization. + + First it will prepare the model for calibration, then it calls + `run_fn` which will run the calibration step, after that we will + convert the model to a quantized model. + + Args: + `model`: input float TorchScript model + `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and + qconfig for that module as value, empty key means the qconfig will be applied + to whole model unless it's overwritten by more specific configurations, the + qconfig for each module is either found in the dictionary or fallback to + the qconfig of parent module. + + Right now qconfig_dict is the only way to configure how the model is quantized, + and it is done in the granularity of module, that is, we only support one type + of qconfig for each torch.nn.Module, and the qconfig for sub module will + override the qconfig for parent module, empty string means global configuration. + `run_fn`: a calibration function for calibrating the prepared model + `run_args`: positional arguments for `run_fn` + `inplace`: carry out model transformations in-place, the original module is + mutated + `debug`: flag for producing a debug friendly model (preserve weight attribute) + + Return: + Quantized TorchSciprt model. + + Example: + ```python + import torch + from torch.ao.quantization import get_default_qconfig + from torch.ao.quantization import quantize_jit + + ts_model = torch.jit.script(float_model.eval()) # or torch.jit.trace(float_model, input) + qconfig = get_default_qconfig('fbgemm') + def calibrate(model, data_loader): + model.eval() + with torch.no_grad(): + for image, target in data_loader: + model(image) + + quantized_model = quantize_jit( + ts_model, + {'': qconfig}, + calibrate, + [data_loader_test]) + ``` + """ + torch._C._log_api_usage_once("quantization_api.quantize_jit.quantize_jit") + return _quantize_jit(model, qconfig_dict, run_fn, run_args, inplace, debug, quant_type=QuantType.STATIC) + +def quantize_dynamic_jit(model, qconfig_dict, inplace=False, debug=False): + r"""Quantize the input float TorchScript model with + post training dynamic quantization. + Currently only qint8 quantization of torch.nn.Linear is supported. + + Args: + `model`: input float TorchScript model + `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and + qconfig for that module as value, please see detailed + descriptions in :func:`~torch.ao.quantization.quantize_jit` + `inplace`: carry out model transformations in-place, the original module is + mutated + `debug`: flag for producing a debug friendly model (preserve weight attribute) + + Return: + Quantized TorchSciprt model. + + Example: + ```python + import torch + from torch.ao.quantization import per_channel_dynamic_qconfig + from torch.ao.quantization import quantize_dynamic_jit + + ts_model = torch.jit.script(float_model.eval()) # or torch.jit.trace(float_model, input) + qconfig = get_default_qconfig('fbgemm') + def calibrate(model, data_loader): + model.eval() + with torch.no_grad(): + for image, target in data_loader: + model(image) + + quantized_model = quantize_dynamic_jit( + ts_model, + {'': qconfig}, + calibrate, + [data_loader_test]) + ``` + """ + torch._C._log_api_usage_once("quantization_api.quantize_jit.quantize_dynamic_jit") + return _quantize_jit(model, qconfig_dict, inplace=inplace, debug=debug, quant_type=QuantType.DYNAMIC) + + +def _quantize_ondevice_dynamic_jit(model, qconfig_dict, method_name='forward', inplace=False): + r"""Prepares the input float TorchScript model with + *on-device* post training dynamic quantization. + Currently only qint8 quantization of torch.nn.Linear is supported. + + Args: + `model`: input float TorchScript model + `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and + qconfig for that module as value, please see detailed + `method_name`: Name of the method within the model, to be prepared for quantization + descriptions in :func:`~torch.ao.quantization.quantize_jit` + `inplace`: carry out model transformations in-place, the original module is + mutated + + Return: + TorchScript model that is ready for on device quantization. + This means that the returned + model has: + - Method is inlined. + - Model has observer modules inserted in the model. + - Model has packed params inserted in the model. However they are empty as in they dont + contain valid quantized weights. + - observe_ is added that observe the values to be quantized. + - reset_observers_ to reset observers. + - quantize_ is added to the model. + - This method extract scale, zero points. + - Quantizes observed weights. + - Creates packed params from it and update the attribute of the model with the new values + for the packed params. + - Reset the original fp32 weights with empty tensor using SetAttr. + - quantized_ is added to the model. + - This method uses quantized weights and quantized linear ops instead of fp32 op. + - This method should be used for inference post PTQ. + - Note that all method's signatures should be the same as method_name. + + Later on device: + - Run reset_observers_ + - Run observe_ + - Run quantize_ + - Now model can be saved and loaded later. + - Run model with quantized_ + + Example: + ```python + import torch + from torch.ao.quantization import per_channel_dynamic_qconfig + from torch.ao.quantization.quantize_jit import _quantize_ondevice_dynamic_jit + + ts_model = torch.jit.script(float_model.eval()) # or torch.jit.trace(float_model, input) + qconfig = get_default_qconfig('fbgemm') + quant_ready_model = _quantize_ondevice_dynamic_jit( + ts_model, + {'': qconfig}, + 'forward', + True) + ``` + """ + return _quantize_ondevice_dynamic_jit_impl(model, qconfig_dict, method_name, inplace=inplace) diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_pt2e.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_pt2e.py new file mode 100644 index 0000000000000000000000000000000000000000..b1b9666fd61bf323318646ab8b6c62897e52d5d9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_pt2e.py @@ -0,0 +1,249 @@ +import torch +from torch.fx import GraphModule +from torch.fx import Node + +from .pt2e.prepare import prepare +from .pt2e.qat_utils import ( + _fuse_conv_bn_qat, + _fold_conv_bn_qat, +) +from .pt2e.utils import ( + _get_node_name_to_scope, + _fuse_conv_bn_, + _disallow_eval_train, +) +from .pt2e.representation import reference_representation_rewrite +from .quantize_fx import _convert_to_reference_decomposed_fx +from torch.ao.quantization.quantizer import ( # noqa: F401 + Quantizer, + QuantizationSpecBase, + QuantizationSpec, + FixedQParamsQuantizationSpec, + SharedQuantizationSpec, + DerivedQuantizationSpec, + QuantizationAnnotation, +) +from torch.fx.passes.infra.pass_manager import PassManager +from torch.ao.quantization.pt2e.duplicate_dq_pass import DuplicateDQPass +from torch.ao.quantization.pt2e.port_metadata_pass import PortNodeMetaForQDQ +from torch._inductor.constant_folding import constant_fold + +__all__ = [ + "prepare_pt2e", + "prepare_qat_pt2e", + "convert_pt2e", +] + + +def prepare_pt2e( + model: GraphModule, + quantizer: Quantizer, +) -> GraphModule: + """Prepare a model for post training quantization + + Args: + * `model` (torch.fx.GraphModule): a model captured by `torch.export` API + in the short term we are using `torch._export.capture_pre_autograd_graph`, + in the long term we'll migrate to some `torch.export` API + * `quantizer`: A backend specific quantizer that conveys how user want the + model to be quantized. Tutorial for how to write a quantizer can be found here: + https://pytorch.org/tutorials/prototype/pt2e_quantizer.html + + Return: + A GraphModule with observer (based on quantizer annotation), ready for calibration + + Example:: + + import torch + from torch.ao.quantization.quantize_pt2e import prepare_pt2e + from torch._export import capture_pre_autograd_graph + from torch.ao.quantization.quantizer import ( + XNNPACKQuantizer, + get_symmetric_quantization_config, + ) + + class M(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(5, 10) + + def forward(self, x): + return self.linear(x) + + # initialize a floating point model + float_model = M().eval() + + # define calibration function + def calibrate(model, data_loader): + model.eval() + with torch.no_grad(): + for image, target in data_loader: + model(image) + + # Step 1. program capture + # NOTE: this API will be updated to torch.export API in the future, but the captured + # result shoud mostly stay the same + m = capture_pre_autograd_graph(m, *example_inputs) + # we get a model with aten ops + + # Step 2. quantization + # backend developer will write their own Quantizer and expose methods to allow + # users to express how they + # want the model to be quantized + quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config()) + m = prepare_pt2e(m, quantizer) + + # run calibration + # calibrate(m, sample_inference_data) + """ + torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_pt2e") + original_graph_meta = model.meta + node_name_to_scope = _get_node_name_to_scope(model) + # TODO: check qconfig_mapping to make sure conv and bn are both configured + # to be quantized before fusion + # TODO: (maybe) rewrite this with subgraph_rewriter + _fuse_conv_bn_(model) + quantizer.transform_for_annotation(model) + quantizer.annotate(model) + quantizer.validate(model) + model = prepare(model, node_name_to_scope, is_qat=False) + model.meta.update(original_graph_meta) + model = _disallow_eval_train(model) + return model + +def prepare_qat_pt2e( + model: GraphModule, + quantizer: Quantizer, +) -> GraphModule: + """Prepare a model for quantization aware training + + Args: + * `model` (torch.fx.GraphModule): see :func:`~torch.ao.quantization.quantize_pt2e.prepare_pt2e` + * `quantizer`: see :func:`~torch.ao.quantization.quantize_pt2e.prepare_pt2e` + + Return: + A GraphModule with fake quant modules (based on quantizer annotation), ready for + quantization aware training + + Example:: + import torch + from torch.ao.quantization.quantize_pt2e import prepare_qat_pt2e + from torch._export import capture_pre_autograd_graph + from torch.ao.quantization.quantizer import ( + XNNPACKQuantizer, + get_symmetric_quantization_config, + ) + + class M(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(5, 10) + + def forward(self, x): + return self.linear(x) + + # initialize a floating point model + float_model = M().eval() + + # define the training loop for quantization aware training + def train_loop(model, train_data): + model.train() + for image, target in data_loader: + ... + + # Step 1. program capture + # NOTE: this API will be updated to torch.export API in the future, but the captured + # result shoud mostly stay the same + m = capture_pre_autograd_graph(m, *example_inputs) + # we get a model with aten ops + + # Step 2. quantization + # backend developer will write their own Quantizer and expose methods to allow + # users to express how they + # want the model to be quantized + quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config()) + m = prepare_qat_pt2e(m, quantizer) + + # run quantization aware training + train_loop(prepared_model, train_loop) + + """ + torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_qat_pt2e") + original_graph_meta = model.meta + node_name_to_scope = _get_node_name_to_scope(model) + quantizer.transform_for_annotation(model) + quantizer.annotate(model) + quantizer.validate(model) + # Perform fusion after annotate to avoid quantizing ops in the new + # subgraph that don't need to be quantized + # TODO: only fuse if conv and bn are both configured to be quantized + _fuse_conv_bn_qat(model) + model = prepare(model, node_name_to_scope, is_qat=True) + model.meta.update(original_graph_meta) + model = _disallow_eval_train(model) + return model + +_QUANT_OPS = [ + torch.ops.quantized_decomposed.quantize_per_tensor.default, + torch.ops.quantized_decomposed.quantize_per_tensor.tensor, + torch.ops.quantized_decomposed.quantize_per_channel.default, +] +def _quant_node_constraint(n: Node) -> bool: + """If there is any pure ops between get_attr and quantize op they will be const propagated + e.g. get_attr(weight) -> transpose -> quantize -> dequantize* + (Note: dequantize op is not going to be constant propagated) + + This filter is added because we don't want to constant fold the things that are not + related to quantization + """ + return n.op == "call_function" and n.target in _QUANT_OPS + +def convert_pt2e( + model: GraphModule, + use_reference_representation: bool = False, + fold_quantize: bool = False, +) -> GraphModule: + """Convert a calibrated/trained model to a quantized model + + Args: + * `model` (torch.fx.GraphModule): calibrated/trained model + * `use_reference_representation` (bool): boolean flag to indicate whether to produce referece representation or not + * `fold_quantize` (bool): boolean flag to indicate whether fold the quantize op or not + + Note: please set `fold_quantize` to True whenever you can, we'll deprecate this flag and + make True the default option in the future, to make sure the change doesn't break BC for you, it's + better to set the flag to True now. + + Returns: + quantized model, either in q/dq representation or reference representation + + Example:: + + # prepared_model: the model produced by `prepare_pt2e`/`prepare_qat_pt2e` and calibration/training + # `convert_pt2e` produces a quantized model that represents quantized computation with + # quantize dequantize ops and fp32 ops by default. + # Please refer to + # https://pytorch.org/tutorials/prototype/pt2e_quant_ptq_static.html#convert-the-calibrated-model-to-a-quantized-model + # for detailed explanation of output quantized model + quantized_model = convert_pt2e(prepared_model) + + """ # flake8: noqa + torch._C._log_api_usage_once("quantization_api.quantize_pt2e.convert_pt2e") + original_graph_meta = model.meta + model = _convert_to_reference_decomposed_fx(model) + model = _fold_conv_bn_qat(model) + pm = PassManager([DuplicateDQPass()]) + + model = pm(model).graph_module + pm = PassManager([PortNodeMetaForQDQ()]) + model = pm(model).graph_module + + if fold_quantize: + constant_fold(model, _quant_node_constraint) + + if use_reference_representation: + model = reference_representation_rewrite(model) + + model.meta.update(original_graph_meta) + model = _disallow_eval_train(model) + return model diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/stubs.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/stubs.py new file mode 100644 index 0000000000000000000000000000000000000000..10a63fb8f0ee43dc3f2367a2f6b0f56164ff4715 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/stubs.py @@ -0,0 +1,64 @@ + +from torch import nn + +class QuantStub(nn.Module): + r"""Quantize stub module, before calibration, this is same as an observer, + it will be swapped as `nnq.Quantize` in `convert`. + + Args: + qconfig: quantization configuration for the tensor, + if qconfig is not provided, we will get qconfig from parent modules + """ + def __init__(self, qconfig=None): + super().__init__() + if qconfig: + self.qconfig = qconfig + + def forward(self, x): + return x + + +class DeQuantStub(nn.Module): + r"""Dequantize stub module, before calibration, this is same as identity, + this will be swapped as `nnq.DeQuantize` in `convert`. + + Args: + qconfig: quantization configuration for the tensor, + if qconfig is not provided, we will get qconfig from parent modules + """ + def __init__(self, qconfig=None): + super().__init__() + if qconfig: + self.qconfig = qconfig + + def forward(self, x): + return x + + +class QuantWrapper(nn.Module): + r"""A wrapper class that wraps the input module, adds QuantStub and + DeQuantStub and surround the call to module with call to quant and dequant + modules. + + This is used by the `quantization` utility functions to add the quant and + dequant modules, before `convert` function `QuantStub` will just be observer, + it observes the input tensor, after `convert`, `QuantStub` + will be swapped to `nnq.Quantize` which does actual quantization. Similarly + for `DeQuantStub`. + """ + quant: QuantStub + dequant: DeQuantStub + module: nn.Module + + def __init__(self, module): + super().__init__() + qconfig = getattr(module, "qconfig", None) + self.add_module('quant', QuantStub(qconfig)) + self.add_module('dequant', DeQuantStub(qconfig)) + self.add_module('module', module) + self.train(module.training) + + def forward(self, X): + X = self.quant(X) + X = self.module(X) + return self.dequant(X) diff --git a/videollama2/lib/python3.10/site-packages/torch/ao/quantization/utils.py b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..49b1b81c3689bbee6adcccd7dfd868f967706aab --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/ao/quantization/utils.py @@ -0,0 +1,703 @@ +""" +Utils shared by different modes of quantization (eager/graph) +""" +import functools +import warnings +from collections import OrderedDict +from inspect import getfullargspec, signature +from typing import Any, Callable, Dict, Optional, Tuple, Union + +import torch +from torch.ao.quantization.quant_type import QuantType +from torch.fx import Node +from torch.nn.utils.parametrize import is_parametrized + +NodePattern = Union[Tuple[Node, Node], Tuple[Node, Tuple[Node, Node]], Any] +NodePattern.__module__ = "torch.ao.quantization.utils" + +# This is the Quantizer class instance from torch/quantization/fx/quantize.py. +# Define separately to prevent circular imports. +# TODO(future PR): improve this. +# make this public once fixed (can't be public as is because setting the module directly +# doesn't work) +QuantizerCls = Any + +# Type for fusion patterns, it can be more complicated than the following actually, +# see pattern.md for docs +# TODO: not sure if typing supports recursive data types +Pattern = Union[ + Callable, Tuple[Callable, Callable], Tuple[Callable, Tuple[Callable, Callable]], Any +] +Pattern.__module__ = "torch.ao.quantization.utils" + +# TODO: maybe rename this to MatchInputNode +class MatchAllNode: + """ A node pattern that matches all nodes, used in defining + fusion patterns in FX Graph Mode Quantization + """ + pass + +module_type_list = { + torch.nn.ReLU, + torch.nn.ReLU6, + torch.nn.AdaptiveAvgPool1d, + torch.nn.AdaptiveAvgPool2d, + torch.nn.AdaptiveAvgPool3d, + torch.nn.AvgPool1d, + torch.nn.AvgPool2d, + torch.nn.AvgPool3d, + torch.nn.MaxPool1d, + torch.nn.MaxPool2d, + torch.nn.MaxPool3d, + torch.nn.Identity, + torch.nn.Hardsigmoid, + torch.nn.Sigmoid, + torch.nn.Tanh, +} +func_list = { + torch.nn.functional.adaptive_avg_pool1d, + torch.nn.functional.adaptive_avg_pool2d, + torch.nn.functional.adaptive_avg_pool3d, + torch.nn.functional.elu, + torch.nn.functional.hardswish, + torch.nn.functional.instance_norm, + torch.nn.functional.layer_norm, + torch.nn.functional.leaky_relu, + torch.nn.functional.silu, + torch.nn.functional.mish, + torch.nn.functional.dropout, + torch.nn.functional.max_pool1d, + torch.nn.functional.max_pool2d, + torch.nn.functional.max_pool3d, + torch.nn.functional.relu, + torch.nn.functional.hardtanh, + torch.nn.functional.hardtanh_, + torch.nn.functional.hardsigmoid, + torch.nn.functional.sigmoid, + torch.transpose, + torch.repeat_interleave, + torch.sigmoid, + torch.squeeze, + torch.stack, + torch.sum, + torch.tanh, + torch.unsqueeze, + torch.cat, +} +method_list = { + torch.mean, + 'relu', + 'relu_', + 'contiguous', + 'detach', + 'detach_', + 'hardsigmoid', + 'hardsigmoid_', + 'permute', + 'repeat', + 'repeat_interleave', + 'reshape', + 'resize_', + 'shape', + 'sigmoid', + 'sigmoid_', + 'size', + 'squeeze', + 'squeeze_', + 'tanh', + 'tanh_', + 'transpose', + 'unsqueeze', + 'unsqueeze_', + 'view', +} + +# TODO: not used now, remove +def check_node(node, modules): + # TODO: reuse is_fixed_qparam_node after we move this function to _lower_to_native_backend.py + is_call_function = node.op == "call_function" and node.target in func_list + is_call_method = node.op == "call_method" and node.target in method_list + is_call_module = node.op == "call_module" and type(modules[str(node.target)]) in module_type_list + return is_call_function, is_call_method, is_call_module + +def get_combined_dict(default_dict, additional_dict): + d = default_dict.copy() + d.update(additional_dict) + return d + +def is_per_tensor(qscheme): + return qscheme == torch.per_tensor_affine or \ + qscheme == torch.per_tensor_symmetric + +def is_per_channel(qscheme): + return qscheme in [torch.per_channel_affine, + torch.per_channel_affine_float_qparams, + torch.per_channel_symmetric] + +def getattr_from_fqn(obj: Any, fqn: str) -> Any: + """ + Given an obj and a fqn such as "foo.bar.baz", returns gm.foo.bar.baz. + """ + return functools.reduce(getattr, fqn.split("."), obj) + +def to_underlying_dtype(qdtype): + DTYPE_MAPPING = { + torch.quint8: torch.uint8, + torch.qint8: torch.int8, + torch.qint32: torch.int32, + torch.quint4x2: torch.uint8, + torch.quint2x4: torch.uint8, + torch.uint8: torch.uint8, + torch.int8: torch.int8, + torch.int16: torch.int16, + torch.int32: torch.int32, + } + assert qdtype in DTYPE_MAPPING, "Unsupported dtype: " + qdtype + return DTYPE_MAPPING[qdtype] + +def get_qparam_dict(observer_or_fake_quant): + from torch.ao.quantization.observer import PlaceholderObserver + + qscheme = getattr(observer_or_fake_quant, "qscheme", None) + dtype = observer_or_fake_quant.dtype + qparams = {"qscheme": qscheme, "dtype": dtype} + + if not qscheme or isinstance(observer_or_fake_quant, PlaceholderObserver): + return {"qscheme": None, "dtype": dtype} + + if is_per_tensor(qscheme): + qscheme = torch.per_tensor_affine + elif is_per_channel(qscheme): + # change symmetric to affine since we do not have symmetric + # quantized Tensor + if qscheme == torch.per_channel_symmetric: + qscheme = torch.per_channel_affine + qparams["axis"] = observer_or_fake_quant.ch_axis + else: + raise RuntimeError(f"Unrecognized qscheme: {qscheme}") + # update qscheme, since we don't have symmetric quant qscheme + # in quantized Tensor + qparams["qscheme"] = qscheme + + scale, zero_point = observer_or_fake_quant.calculate_qparams() + qparams["scale"] = scale + qparams["zero_point"] = zero_point + + if hasattr(observer_or_fake_quant, "quant_min"): + qparams["quant_min"] = observer_or_fake_quant.quant_min + if hasattr(observer_or_fake_quant, "quant_max"): + qparams["quant_max"] = observer_or_fake_quant.quant_max + + return qparams + + +def get_swapped_custom_module_class(custom_module, custom_module_class_mapping, qconfig): + """ Get the observed/quantized custom module class that we need + to swap `custom_module` to + Input: + custom_module: input, can be an instance of either a float or observed custom module + custom_module_class_mapping: the float to observed or observed to quantized custom module class mapping + qconfig: qconfig configured for the custom module + + Output: + corresponding observed/quantized custom module class for input custom module instance + """ + quant_type = get_quant_type(qconfig) + class_mapping = custom_module_class_mapping.get(quant_type, {}) + assert type(custom_module) in class_mapping, "did not find corresponding observed " \ + f"module class for {type(custom_module)} in mapping: {class_mapping}" + return class_mapping[type(custom_module)] + +def activation_dtype(qconfig): + assert qconfig is not None + activation = qconfig.activation() + return activation.dtype + +def weight_dtype(qconfig): + assert qconfig is not None + weight = qconfig.weight() + return weight.dtype + +def activation_is_statically_quantized(qconfig): + """ Given a qconfig, decide if the activation needs to be + quantized or not, this includes quantizing to quint8, qint8 and qint32 and float16 + """ + return ( + activation_dtype(qconfig) in [ + torch.quint8, + torch.qint8, + torch.qint32, + torch.float16, + torch.uint8, + torch.int8, + torch.int16, + torch.int32 + ] + and (not activation_is_dynamically_quantized(qconfig)) + ) + +def activation_is_dynamically_quantized(qconfig): + """ Given a qconfig, decide if the activation needs to be + dynamically quantized or not, this includes dynamically quantizing to + quint8, qint8 and float16 + """ + activation_dtype, _, activation_is_dynamic = \ + get_qconfig_dtypes(qconfig) + return activation_is_dynamic + +def activation_is_int8_quantized(qconfig): + """ Given a qconfig, decide if the activation needs to be + quantized to int8 or not, this includes quantizing to quint8, qint8 + """ + return activation_dtype(qconfig) in [torch.quint8, torch.qint8, torch.uint8, torch.int8] + +def activation_is_int32_quantized(qconfig): + """ Given a qconfig, decide if the activation needs to be + quantized to int32 or not + """ + return activation_dtype(qconfig) in [torch.qint32, torch.int32] + +def weight_is_quantized(qconfig): + """ Given a qconfig, decide if the weight needs to be + quantized or not + """ + return weight_dtype(qconfig) in [ + torch.quint8, + torch.qint8, + torch.float16, + torch.quint4x2, + torch.uint8, + torch.int8, + torch.int16, + torch.int32 + ] + +def weight_is_statically_quantized(qconfig): + """ Given a qconfig, decide if the weight needs to be statically + quantized or not + """ + return weight_dtype(qconfig) in [torch.quint8, torch.qint8, torch.uint8, torch.int8] + +def op_is_int8_dynamically_quantized(qconfig) -> bool: + """ Given a qconfig, returns True if this op is using int8 dynamic + quantization + """ + activation_dtype, weight_dtype, activation_is_dynamic = \ + get_qconfig_dtypes(qconfig) + return ( + activation_dtype in [torch.quint8, torch.uint8] and + # for now, the lines below assume fbgemm or qnnpack + weight_dtype in [torch.qint8, torch.int8] and + activation_is_dynamic + ) + +def get_qconfig_dtypes(qconfig): + r""" returns the qconfig tuple for qconfig: + (activation_dtype, weight_dtype, activation_is_dynamic) + """ + assert qconfig is not None + activation = qconfig.activation() + weight = qconfig.weight() + act_is_dynamic = getattr(activation, "is_dynamic", False) + return (activation.dtype, weight.dtype, act_is_dynamic) + +def get_quant_type(qconfig): + assert qconfig is not None + activation = qconfig.activation() + weight = qconfig.weight() + static_dtypes = [torch.quint8, torch.qint8, torch.quint4x2, torch.qint32, torch.uint8, torch.int8, torch.int16, torch.int32] + if weight.dtype in static_dtypes: + if hasattr(activation, 'is_dynamic') and activation.is_dynamic: + return QuantType.DYNAMIC + elif activation.dtype in static_dtypes: + return QuantType.STATIC + else: + return QuantType.WEIGHT_ONLY + + if weight.dtype == torch.float16: + if hasattr(activation, 'is_dynamic') and activation.is_dynamic: + return QuantType.DYNAMIC + elif activation.dtype == torch.float16: + return QuantType.STATIC + + raise Exception(f"Unrecognized dtype combination in get_quant_type: activation({activation.dtype})," + f"weight({weight.dtype})") + +def check_min_max_valid(min_val: torch.Tensor, max_val: torch.Tensor) -> bool: + """ Checks if the given minimum and maximum values are valid, meaning that + they exist and the min value is less than the max value. + """ + if min_val.numel() == 0 or max_val.numel() == 0: + warnings.warn( + "must run observer before calling calculate_qparams. " + + "Returning default values." + ) + return False + + if min_val.dim() == 0 or max_val.dim() == 0: + if min_val == float("inf") and max_val == float("-inf"): + warnings.warn( + "must run observer before calling calculate_qparams. " + + "Returning default values." + ) + + return False + + assert min_val <= max_val, f"min {min_val} should be less than max {max_val}" + else: + assert torch.all( + min_val <= max_val + ), f"min {min_val} should be less than max {max_val}" + + return True + + +def calculate_qmin_qmax(quant_min: int, quant_max: int, has_customized_qrange: bool, dtype: torch.dtype, + reduce_range: bool) -> Tuple[int, int]: + r"""Calculates actual qmin and qmax based on the quantization range, + observer datatype and if range is reduced. + """ + # TODO(jerryzh): Figure out why custom quant_min/quant_max are still adjusted. + if has_customized_qrange: + # This initialization here is to be resolve TorchScript compilation issues and allow + # using of refinement to decouple initial_qmin and initial_qmax from quantization range. + # The actual values of initial_qmin and initial_qmax will be reset below. + if dtype in [torch.qint32, torch.int32]: + initial_quant_min, initial_quant_max = 0, 2**32 - 1 + else: + initial_quant_min, initial_quant_max = 0, 255 + # The following assignment of self.qmin and self.qmax to the local variables and the if check refine the + # attribute from Optional valid integers for use, based on TorchScript's requirements. + custom_quant_min, custom_quant_max = quant_min, quant_max + if custom_quant_min is not None and custom_quant_max is not None: + initial_quant_min, initial_quant_max = ( + custom_quant_min, + custom_quant_max, + ) + + qrange_len = initial_quant_max - initial_quant_min + 1 + if dtype in [torch.qint8, torch.int8]: + assert ( + 0 < qrange_len <= 256 + ), "quantization range should be positive and not exceed the maximum bit range (=256)." + elif dtype in [torch.qint32, torch.int32]: + assert ( + 0 < qrange_len <= 2**32 + ), "quantization range should be positive and not exceed the maximum bit range (=4294967296)." + if reduce_range: + quant_min, quant_max = quant_min // 2, quant_max // 2 + else: + # Fallback onto default 8-bit qmin and qmax calculation if dynamic range is not used. + if dtype in [torch.qint8, torch.int8]: + if reduce_range: + quant_min, quant_max = -64, 63 + else: + quant_min, quant_max = -128, 127 + elif dtype in [torch.quint8, torch.uint8]: + if reduce_range: + quant_min, quant_max = 0, 127 + else: + quant_min, quant_max = 0, 255 + elif dtype in [torch.qint32, torch.int32]: + quant_min, quant_max = -1 * (2 ** 31), (2 ** 31) - 1 + else: + quant_min, quant_max = 0, 15 + return quant_min, quant_max + + +def _parent_name(target): + """ + Turn 'foo.bar' into ['foo', 'bar'] + """ + r = target.rsplit('.', 1) + if len(r) == 1: + return '', r[0] + else: + return r[0], r[1] + +def has_no_children_ignoring_parametrizations(module): + """ + Checks if module._modules is empty or + if module is a parametrization, checks that module._modules only has + the 'parametrizations' module + """ + if len(module._modules) == 0: + return True + elif is_parametrized(module): + return len(module._modules) == 1 and 'parametrizations' in module._modules + else: + return False + +def _get_path_of_module(root: torch.nn.Module, submodule: torch.nn.Module) -> Optional[str]: + """ Get the path (fully qualified name) of a submodule + + Example:: + + >> class M(torch.nn.Module): + def __init__(self): + self.linear = torch.nn.Linear(5, 5) + def forward(self, x): + return self.linear(x) + + >> m = M() + >> l = m.linear + >> _get_path_of_module(m, l) + "linear" + """ + for n, p in root.named_modules(): + if submodule is p: + return n + return None + +def _get_signature_locals(f: Callable, loc: Dict[str, Any]) -> Dict[str, Any]: + """ Get local keyword arguments + + Example:: + + >> def f(self, a, b=9): + pass + >> loc = {"a": 6, "c": 7} + >> _get_signature_locals(f, loc) + {"a": 6} + """ + return {k: v for k, v in loc.items() if k in signature(f).parameters} + +def _get_default_kwargs(f: Callable) -> "OrderedDict[str, Any]": + """ Get all default keyword arguments from function signature + + Example:: + + >> def f(self, a, b=9): + pass + >> _get_default_kwargs(f) + {"b": 9} + """ + kwargs = {} + for name, param in signature(f).parameters.items(): + if param.default is not param.empty: + kwargs[name] = param.default + elif param.kind is param.VAR_POSITIONAL: + kwargs[name] = () + elif param.kind is param.VAR_KEYWORD: + kwargs[name] = {} + return OrderedDict(kwargs) + +def _normalize_kwargs(func: Callable, loc: Dict[str, Any]) -> "OrderedDict[str, Any]": + """ Given a function and local function arguments, normalize the keyword + arguments by filling in default arguments from function signature + + Example:: + + >> def f(self, key1=3, key2=3): + pass + >> loc = {"key2": 6} + >> _normalize_kwargs(f, loc) + {"key1": 3, "key2": 6} + """ + default_kwargs = _get_default_kwargs(func) + local_kwargs = _get_signature_locals(func, loc) + normalized_kwargs = default_kwargs.copy() + for attr, val in local_kwargs.items(): + if attr in normalized_kwargs: + # override the default keyword arguments + normalized_kwargs[attr] = val + return normalized_kwargs + +def validate_qmin_qmax(quant_min: int, quant_max: int) -> None: + r"""Validates that the user-specified quantization range is properly initialized + and within the given bound supported by the observer dtype. + + To accommodate lower-bit quantization with respect to the existing torch.qint8 and + torch.quint8 datatypes, the user can choose to use dynamic quantization range by passing + in a tuple of initial qmin and qmax values. One use case is these customized qmin and qmax + values are used to calculate static estimates of the scale and zero point for aggressive lower-bit + fake quantization. These estimates are compared against parameters learned through backpropagation. + The related literatures for scale and zero point via backpropagation are as follows: + + Learned Step Size Quantization: https://openreview.net/pdf?id=rkgO66VKDS + Trained Quantization Thresholds: https://arxiv.org/pdf/1903.08066.pdf + """ + # The variable names are prefixed with "initial" because their values (qmin and qmax) might be adjusted + # based on whether quantization range is reduced and the datatype (signed/unsigned) used by the observer. + assert ( + quant_min <= 0 <= quant_max + ), "Used-specified quantization range must include 0." + assert ( + quant_min < quant_max + ), "qmin must be strictly less than qmax for user-specified quantization range." + + +# Functionally equivalent to '_calculate_qparams' in observer.py. Observers must be torchscriptable however and qscheme +# as far as I can tell is not allowed to passed as a parameter in torchscript functions. This makes refactoring observer +# to use this utility a massive pain and very gross. For now Im opting just to duplicate as this code seems unlikey to change +# (last update over 1 year ago) and when torchscript is fully deprecated we can refactor. TODO(jakeszwe, jerryzh168) +def determine_qparams( + min_val: torch.Tensor, max_val: torch.Tensor, quant_min: int, quant_max: int, + dtype: torch.dtype, eps: torch.Tensor, has_customized_qrange: bool, + qscheme: torch.qscheme = torch.per_tensor_affine) -> Tuple[torch.Tensor, torch.Tensor]: + r"""Calculates the quantization parameters, given min and max + value tensors. Works for both per tensor and per channel cases + + Args: + min_val: Minimum values per channel + max_val: Maximum values per channel + + Returns: + scales: Scales tensor of shape (#channels,) + zero_points: Zero points tensor of shape (#channels,) + """ + if not check_min_max_valid(min_val, max_val): + return torch.tensor([1.0], device=min_val.device.type), torch.tensor([0], device=min_val.device.type) + + min_val_neg = torch.min(min_val, torch.zeros_like(min_val)) + max_val_pos = torch.max(max_val, torch.zeros_like(max_val)) + + device = min_val_neg.device + scale = torch.ones(min_val_neg.size(), dtype=torch.double, device=device) + zero_point = torch.zeros(min_val_neg.size(), dtype=torch.int64, device=device) + + if ( + qscheme == torch.per_tensor_symmetric + or qscheme == torch.per_channel_symmetric + ): + max_val_pos = torch.max(-min_val_neg, max_val_pos) + scale = max_val_pos / (float(quant_max - quant_min) / 2) + scale = torch.max(scale, eps) + if dtype in [torch.uint8, torch.quint8]: + if has_customized_qrange: + # When customized quantization range is used, down-rounded midpoint of the range is chosen. + zero_point = zero_point.new_full( + zero_point.size(), (quant_min + quant_max) // 2 + ) + else: + zero_point = zero_point.new_full(zero_point.size(), 128) + elif qscheme == torch.per_channel_affine_float_qparams: + scale = (max_val - min_val) / float(quant_max - quant_min) + scale = torch.where(scale > eps, scale, torch.ones_like(scale)) + # We use the quantize function + # xq = Round(Xf * inv_scale + zero_point), + # setting zero_point to (-1 * min *inv_scale) we get + # Xq = Round((Xf - min) * inv_scale) + zero_point = -1 * min_val / scale + else: + scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min) + scale = torch.max(scale, eps) + zero_point = quant_min - torch.round(min_val_neg / scale).to(torch.int) + zero_point = torch.clamp(zero_point, quant_min, quant_max) + + # For scalar values, cast them to Tensors of size 1 to keep the shape + # consistent with default values in FakeQuantize. + if len(scale.shape) == 0: + # TODO: switch to scale.item() after adding JIT support + scale = torch.tensor([float(scale)], dtype=scale.dtype, device=device) + if len(zero_point.shape) == 0: + # TODO: switch to zero_point.item() after adding JIT support + zero_point = torch.tensor( + [int(zero_point)], dtype=zero_point.dtype, device=device + ) + if qscheme == torch.per_channel_affine_float_qparams: + zero_point = torch.tensor( + [float(zero_point)], dtype=zero_point.dtype, device=device + ) + + return scale.to(torch.double), zero_point.to(torch.int64) + +def _get_num_pos_args(f: Callable) -> int: + """ Get number of positional args for a function + + Example:: + + >> def f(self, key1=3, key2=3): + pass + >> _get_num_pos_args(f) + 3 + """ + return len(getfullargspec(f).args) + +def get_fqn_to_example_inputs( + model: torch.nn.Module, + example_inputs: Tuple[Any, ...] +) -> Dict[str, Tuple[Any, ...]]: + """ Given a model and its example inputs, return a dictionary from + fully qualified name of submodules to example_inputs for that submodule, + e.g. {"linear1": (tensor1,), "linear2": (tensor2,), "sub": (tensor3,), + "sub.linear1": (tensor4,), ...} + + Used to make quantizing submodules easier now that FX Graph Mode Quantization requires + example inputs. + + Also works for keyword arguments with default values, we would flatten keyword + arguments as positional arguments and fill in the missing keyword args with default + values, e.g. if we have a forward function: + def forward(self, x, key1=3, key2=3): + ... + + and we call it with self.submodule(x, key2=6) + we'll get example_inputs: (x, 3, 6) + + user can also override `key1` with positional arguments as well: + for self.submodule(x, 5, key2=6) + we'll get: (x, 5, 6) + + variable positional arguments and variable positional keyword arguments in forward + function are not supported currently, so please make sure no submodules is using + them. + """ + root = model + fqn_to_example_inputs = {} + + def _patched_module_call(self, *args, **kwargs): + submodule_example_inputs = list(args).copy() + normalized_kwargs = _normalize_kwargs(self.forward, kwargs) + # minus 1 to skipping counting `self` + num_args = _get_num_pos_args(self.forward) - 1 + num_to_pop = num_args - len(submodule_example_inputs) + while num_to_pop and normalized_kwargs: + normalized_kwargs.popitem(last=False) + num_to_pop -= 1 + submodule_example_inputs.extend(normalized_kwargs.values()) + submodule_example_inputs_tuple = tuple(submodule_example_inputs) + fqn = _get_path_of_module(root, self) + if fqn is not None: + fqn_to_example_inputs[fqn] = submodule_example_inputs_tuple + return orig_module_call(self, *args, **kwargs) + + orig_module_call = torch.nn.Module.__call__ + torch.nn.Module.__call__ = _patched_module_call # type: ignore[method-assign] + try: + model(*example_inputs) + finally: + # restore the module call even if there is an exception + torch.nn.Module.__call__ = orig_module_call # type: ignore[method-assign] + return fqn_to_example_inputs + +__all__ = [ + "NodePattern", + "Pattern", + "MatchAllNode", + "check_node", + "get_combined_dict", + "is_per_tensor", + "is_per_channel", + "getattr_from_fqn", + "get_qparam_dict", + "get_swapped_custom_module_class", + "activation_dtype", + "weight_dtype", + "activation_is_statically_quantized", + "activation_is_dynamically_quantized", + "activation_is_int8_quantized", + "activation_is_int32_quantized", + "weight_is_quantized", + "weight_is_statically_quantized", + "op_is_int8_dynamically_quantized", + "get_qconfig_dtypes", + "get_quant_type", + "check_min_max_valid", + "calculate_qmin_qmax", + "has_no_children_ignoring_parametrizations", + "get_fqn_to_example_inputs", + "to_underlying_dtype", + "determine_qparams", + "validate_qmin_qmax", +] diff --git a/vllm/lib/python3.10/site-packages/textual/css/__init__.py b/vllm/lib/python3.10/site-packages/textual/css/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/textual/css/errors.py b/vllm/lib/python3.10/site-packages/textual/css/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..0920fdf8b7631fcb2f0f33aa6453c33796dbaed6 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/textual/css/errors.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from rich.console import Console, ConsoleOptions, RenderResult + +from textual.css._help_renderables import HelpText +from textual.css.tokenizer import Token, TokenError + + +class DeclarationError(Exception): + def __init__(self, name: str, token: Token, message: str | HelpText) -> None: + self.name = name + self.token = token + self.message = message + super().__init__(str(message)) + + +class StyleTypeError(TypeError): + pass + + +class UnresolvedVariableError(TokenError): + pass + + +class StyleValueError(ValueError): + """Raised when the value of a style property is not valid + + Attributes: + help_text: Optional HelpText to be rendered when this + error is raised. + """ + + def __init__(self, *args: object, help_text: HelpText | None = None): + super().__init__(*args) + self.help_text: HelpText | None = help_text + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + from rich.traceback import Traceback + + yield Traceback.from_exception(type(self), self, self.__traceback__) + if self.help_text is not None: + yield "" + yield self.help_text + yield "" + + +class StylesheetError(Exception): + pass diff --git a/vllm/lib/python3.10/site-packages/textual/css/parse.py b/vllm/lib/python3.10/site-packages/textual/css/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..d0365c825f40acadadaf309a49b9fe468fdf110c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/textual/css/parse.py @@ -0,0 +1,466 @@ +from __future__ import annotations + +import dataclasses +from functools import lru_cache +from typing import Iterable, Iterator, NoReturn + +from textual.css._help_renderables import HelpText +from textual.css._styles_builder import DeclarationError, StylesBuilder +from textual.css.errors import UnresolvedVariableError +from textual.css.model import ( + CombinatorType, + Declaration, + RuleSet, + Selector, + SelectorSet, + SelectorType, +) +from textual.css.styles import Styles +from textual.css.tokenize import Token, tokenize, tokenize_declarations, tokenize_values +from textual.css.tokenizer import EOFError, ReferencedBy +from textual.css.types import CSSLocation, Specificity3 +from textual.suggestions import get_suggestion + +SELECTOR_MAP: dict[str, tuple[SelectorType, Specificity3]] = { + "selector": (SelectorType.TYPE, (0, 0, 1)), + "selector_start": (SelectorType.TYPE, (0, 0, 1)), + "selector_class": (SelectorType.CLASS, (0, 1, 0)), + "selector_start_class": (SelectorType.CLASS, (0, 1, 0)), + "selector_id": (SelectorType.ID, (1, 0, 0)), + "selector_start_id": (SelectorType.ID, (1, 0, 0)), + "selector_universal": (SelectorType.UNIVERSAL, (0, 0, 0)), + "selector_start_universal": (SelectorType.UNIVERSAL, (0, 0, 0)), + "nested": (SelectorType.NESTED, (0, 0, 0)), +} + + +def _add_specificity( + specificity1: Specificity3, specificity2: Specificity3 +) -> Specificity3: + """Add specificity tuples together. + + Args: + specificity1: Specificity triple. + specificity2: Specificity triple. + + Returns: + Combined specificity. + """ + + a1, b1, c1 = specificity1 + a2, b2, c2 = specificity2 + return (a1 + a2, b1 + b2, c1 + c2) + + +@lru_cache(maxsize=1024) +def parse_selectors(css_selectors: str) -> tuple[SelectorSet, ...]: + if not css_selectors.strip(): + return () + tokens = iter(tokenize(css_selectors, ("", ""))) + + get_selector = SELECTOR_MAP.get + combinator: CombinatorType | None = CombinatorType.DESCENDENT + selectors: list[Selector] = [] + rule_selectors: list[list[Selector]] = [] + + while True: + try: + token = next(tokens, None) + except EOFError: + break + if token is None: + break + token_name = token.name + + if token_name == "pseudo_class": + selectors[-1]._add_pseudo_class(token.value.lstrip(":")) + elif token_name == "whitespace": + if combinator is None or combinator == CombinatorType.SAME: + combinator = CombinatorType.DESCENDENT + elif token_name == "new_selector": + rule_selectors.append(selectors[:]) + selectors.clear() + combinator = None + elif token_name == "declaration_set_start": + break + elif token_name == "combinator_child": + combinator = CombinatorType.CHILD + else: + _selector, specificity = get_selector( + token_name, (SelectorType.TYPE, (0, 0, 0)) + ) + selectors.append( + Selector( + name=token.value.lstrip(".#"), + combinator=combinator or CombinatorType.DESCENDENT, + type=_selector, + specificity=specificity, + ) + ) + combinator = CombinatorType.SAME + if selectors: + rule_selectors.append(selectors[:]) + + selector_set = tuple(SelectorSet.from_selectors(rule_selectors)) + return selector_set + + +def parse_rule_set( + scope: str, + tokens: Iterator[Token], + token: Token, + is_default_rules: bool = False, + tie_breaker: int = 0, +) -> Iterable[RuleSet]: + get_selector = SELECTOR_MAP.get + combinator: CombinatorType | None = CombinatorType.DESCENDENT + selectors: list[Selector] = [] + rule_selectors: list[list[Selector]] = [] + styles_builder = StylesBuilder() + + while True: + if token.name == "pseudo_class": + selectors[-1]._add_pseudo_class(token.value.lstrip(":")) + elif token.name == "whitespace": + if combinator is None or combinator == CombinatorType.SAME: + combinator = CombinatorType.DESCENDENT + elif token.name == "new_selector": + rule_selectors.append(selectors[:]) + selectors.clear() + combinator = None + elif token.name == "declaration_set_start": + break + elif token.name == "combinator_child": + combinator = CombinatorType.CHILD + else: + _selector, specificity = get_selector( + token.name, (SelectorType.TYPE, (0, 0, 0)) + ) + selectors.append( + Selector( + name=token.value.lstrip(".#"), + combinator=combinator or CombinatorType.DESCENDENT, + type=_selector, + specificity=specificity, + ) + ) + combinator = CombinatorType.SAME + + token = next(tokens) + + if selectors: + if scope and selectors[0].name != scope: + scope_selector, scope_specificity = get_selector( + scope, (SelectorType.TYPE, (0, 0, 0)) + ) + selectors.insert( + 0, + Selector( + name=scope, + combinator=CombinatorType.DESCENDENT, + type=scope_selector, + specificity=scope_specificity, + ), + ) + rule_selectors.append(selectors[:]) + + declaration = Declaration(token, "") + errors: list[tuple[Token, str | HelpText]] = [] + nested_rules: list[RuleSet] = [] + + while True: + token = next(tokens) + token_name = token.name + if token_name in ("whitespace", "declaration_end"): + continue + if token_name in { + "selector_start_id", + "selector_start_class", + "selector_start_universal", + "selector_start", + "nested", + }: + recursive_parse: list[RuleSet] = list( + parse_rule_set( + "", + tokens, + token, + is_default_rules=is_default_rules, + tie_breaker=tie_breaker, + ) + ) + + def combine_selectors( + selectors1: list[Selector], selectors2: list[Selector] + ) -> list[Selector]: + """Combine lists of selectors together, processing any nesting. + + Args: + selectors1: List of selectors. + selectors2: Second list of selectors. + + Returns: + Combined selectors. + """ + if selectors2 and selectors2[0].type == SelectorType.NESTED: + final_selector = selectors1[-1] + nested_selector = selectors2[0] + merged_selector = dataclasses.replace( + final_selector, + pseudo_classes=( + final_selector.pseudo_classes + | nested_selector.pseudo_classes + ), + specificity=_add_specificity( + final_selector.specificity, nested_selector.specificity + ), + ) + return [*selectors1[:-1], merged_selector, *selectors2[1:]] + else: + return selectors1 + selectors2 + + for rule_selector in rule_selectors: + for rule_set in recursive_parse: + nested_rule_set = RuleSet( + [ + SelectorSet( + combine_selectors( + rule_selector, recursive_selectors.selectors + ) + )._total_specificity() + for recursive_selectors in rule_set.selector_set + ], + rule_set.styles, + rule_set.errors, + rule_set.is_default_rules, + rule_set.tie_breaker + tie_breaker, + ) + nested_rules.append(nested_rule_set) + continue + if token_name == "declaration_name": + try: + styles_builder.add_declaration(declaration) + except DeclarationError as error: + errors.append((error.token, error.message)) + declaration = Declaration(token, "") + declaration.name = token.value.rstrip(":") + elif token_name == "declaration_set_end": + break + else: + declaration.tokens.append(token) + + try: + styles_builder.add_declaration(declaration) + except DeclarationError as error: + errors.append((error.token, error.message)) + + rule_set = RuleSet( + list(SelectorSet.from_selectors(rule_selectors)), + styles_builder.styles, + errors, + is_default_rules=is_default_rules, + tie_breaker=tie_breaker, + ) + + rule_set._post_parse() + yield rule_set + + for nested_rule_set in nested_rules: + nested_rule_set._post_parse() + yield nested_rule_set + + +def parse_declarations(css: str, read_from: CSSLocation) -> Styles: + """Parse declarations and return a Styles object. + + Args: + css: String containing CSS. + read_from: The location where the CSS was read from. + + Returns: + A styles object. + """ + + tokens = iter(tokenize_declarations(css, read_from)) + styles_builder = StylesBuilder() + + declaration: Declaration | None = None + errors: list[tuple[Token, str | HelpText]] = [] + while True: + token = next(tokens, None) + if token is None: + break + token_name = token.name + if token_name in ("whitespace", "declaration_end", "eof"): + continue + if token_name == "declaration_name": + if declaration: + try: + styles_builder.add_declaration(declaration) + except DeclarationError as error: + errors.append((error.token, error.message)) + raise + declaration = Declaration(token, "") + declaration.name = token.value.rstrip(":") + elif token_name == "declaration_set_end": + break + else: + if declaration: + declaration.tokens.append(token) + + if declaration: + try: + styles_builder.add_declaration(declaration) + except DeclarationError as error: + errors.append((error.token, error.message)) + raise + + return styles_builder.styles + + +def _unresolved(variable_name: str, variables: Iterable[str], token: Token) -> NoReturn: + """Raise a TokenError regarding an unresolved variable. + + Args: + variable_name: A variable name. + variables: Possible choices used to generate suggestion. + token: The Token. + + Raises: + UnresolvedVariableError: Always raises a TokenError. + """ + message = f"reference to undefined variable '${variable_name}'" + suggested_variable = get_suggestion(variable_name, list(variables)) + if suggested_variable: + message += f"; did you mean '${suggested_variable}'?" + + raise UnresolvedVariableError( + token.read_from, + token.code, + token.start, + message, + end=token.end, + ) + + +def substitute_references( + tokens: Iterable[Token], css_variables: dict[str, list[Token]] | None = None +) -> Iterable[Token]: + """Replace variable references with values by substituting variable reference + tokens with the tokens representing their values. + + Args: + tokens: Iterator of Tokens which may contain tokens + with the name "variable_ref". + + Returns: + Yields Tokens such that any variable references (tokens where + token.name == "variable_ref") have been replaced with the tokens representing + the value. In other words, an Iterable of Tokens similar to the original input, + but with variables resolved. Substituted tokens will have their referenced_by + attribute populated with information about where the tokens are being substituted to. + """ + variables: dict[str, list[Token]] = css_variables.copy() if css_variables else {} + iter_tokens = iter(tokens) + + while True: + token = next(iter_tokens, None) + if token is None: + break + if token.name == "variable_name": + variable_name = token.value[1:-1] # Trim the $ and the :, i.e. "$x:" -> "x" + variable_tokens = variables.setdefault(variable_name, []) + yield token + + while True: + token = next(iter_tokens, None) + if token is not None and token.name == "whitespace": + yield token + else: + break + + # Store the tokens for any variable definitions, and substitute + # any variable references we encounter with them. + while True: + if not token: + break + elif token.name == "whitespace": + variable_tokens.append(token) + yield token + elif token.name == "variable_value_end": + yield token + break + # For variables referring to other variables + elif token.name == "variable_ref": + ref_name = token.value[1:] + if ref_name in variables: + reference_tokens = variables[ref_name] + variable_tokens.extend(reference_tokens) + ref_location = token.location + ref_length = len(token.value) + for _token in reference_tokens: + yield _token.with_reference( + ReferencedBy( + ref_name, ref_location, ref_length, token.code + ) + ) + else: + _unresolved(ref_name, variables.keys(), token) + else: + variable_tokens.append(token) + yield token + token = next(iter_tokens, None) + elif token.name == "variable_ref": + variable_name = token.value[1:] # Trim the $, so $x -> x + if variable_name in variables: + variable_tokens = variables[variable_name] + ref_location = token.location + ref_length = len(token.value) + ref_code = token.code + for _token in variable_tokens: + yield _token.with_reference( + ReferencedBy(variable_name, ref_location, ref_length, ref_code) + ) + else: + _unresolved(variable_name, variables.keys(), token) + else: + yield token + + +def parse( + scope: str, + css: str, + read_from: CSSLocation, + variables: dict[str, str] | None = None, + variable_tokens: dict[str, list[Token]] | None = None, + is_default_rules: bool = False, + tie_breaker: int = 0, +) -> Iterable[RuleSet]: + """Parse CSS by tokenizing it, performing variable substitution, + and generating rule sets from it. + + Args: + scope: CSS type name. + css: The input CSS. + read_from: The source location of the CSS. + variables: Substitution variables to substitute tokens for. + is_default_rules: True if the rules we're extracting are + default (i.e. in Widget.DEFAULT_CSS) rules. False if they're from user defined CSS. + """ + reference_tokens = tokenize_values(variables) if variables is not None else {} + if variable_tokens: + reference_tokens.update(variable_tokens) + + tokens = iter(substitute_references(tokenize(css, read_from), variable_tokens)) + while True: + token = next(tokens, None) + if token is None: + break + if token.name.startswith("selector_start"): + yield from parse_rule_set( + scope, + tokens, + token, + is_default_rules=is_default_rules, + tie_breaker=tie_breaker, + ) diff --git a/vllm/lib/python3.10/site-packages/textual/css/styles.py b/vllm/lib/python3.10/site-packages/textual/css/styles.py new file mode 100644 index 0000000000000000000000000000000000000000..0a08b42dd3e30286ea2cd058a173c88880cf09fa --- /dev/null +++ b/vllm/lib/python3.10/site-packages/textual/css/styles.py @@ -0,0 +1,1423 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from functools import partial +from operator import attrgetter +from typing import TYPE_CHECKING, Any, Callable, Iterable, Literal, cast + +import rich.repr +from rich.style import Style +from typing_extensions import TypedDict + +from textual._animator import DEFAULT_EASING, Animatable, BoundAnimator, EasingFunction +from textual._types import AnimationLevel, CallbackType +from textual.color import Color +from textual.css._style_properties import ( + AlignProperty, + BooleanProperty, + BorderProperty, + BoxProperty, + ColorProperty, + DockProperty, + FractionalProperty, + HatchProperty, + IntegerProperty, + KeylineProperty, + LayoutProperty, + NameListProperty, + NameProperty, + OffsetProperty, + OverflowProperty, + ScalarListProperty, + ScalarProperty, + ScrollbarColorProperty, + SpacingProperty, + SplitProperty, + StringEnumProperty, + StyleFlagsProperty, + TransitionsProperty, +) +from textual.css.constants import ( + VALID_ALIGN_HORIZONTAL, + VALID_ALIGN_VERTICAL, + VALID_BOX_SIZING, + VALID_CONSTRAIN, + VALID_DISPLAY, + VALID_OVERFLOW, + VALID_OVERLAY, + VALID_POSITION, + VALID_SCROLLBAR_GUTTER, + VALID_TEXT_ALIGN, + VALID_VISIBILITY, +) +from textual.css.scalar import Scalar, ScalarOffset, Unit +from textual.css.scalar_animation import ScalarAnimation +from textual.css.transition import Transition +from textual.css.types import ( + AlignHorizontal, + AlignVertical, + BoxSizing, + Constrain, + Display, + Overflow, + Overlay, + ScrollbarGutter, + Specificity3, + Specificity6, + TextAlign, + Visibility, +) +from textual.geometry import Offset, Spacing + +if TYPE_CHECKING: + from textual.css.types import CSSLocation + from textual.dom import DOMNode + from textual.layout import Layout + + +class RulesMap(TypedDict, total=False): + """A typed dict for CSS rules. + + Any key may be absent, indicating that rule has not been set. + + Does not define composite rules, that is a rule that is made of a combination of other rules. + """ + + display: Display + visibility: Visibility + layout: "Layout" + + auto_color: bool + color: Color + background: Color + text_style: Style + + background_tint: Color + + opacity: float + text_opacity: float + + padding: Spacing + margin: Spacing + offset: ScalarOffset + position: str + + border_top: tuple[str, Color] + border_right: tuple[str, Color] + border_bottom: tuple[str, Color] + border_left: tuple[str, Color] + + border_title_align: AlignHorizontal + border_subtitle_align: AlignHorizontal + + outline_top: tuple[str, Color] + outline_right: tuple[str, Color] + outline_bottom: tuple[str, Color] + outline_left: tuple[str, Color] + + keyline: tuple[str, Color] + + box_sizing: BoxSizing + width: Scalar + height: Scalar + min_width: Scalar + min_height: Scalar + max_width: Scalar + max_height: Scalar + + dock: str + split: str + + overflow_x: Overflow + overflow_y: Overflow + + layers: tuple[str, ...] + layer: str + + transitions: dict[str, Transition] + + tint: Color + + scrollbar_color: Color + scrollbar_color_hover: Color + scrollbar_color_active: Color + + scrollbar_corner_color: Color + + scrollbar_background: Color + scrollbar_background_hover: Color + scrollbar_background_active: Color + + scrollbar_gutter: ScrollbarGutter + + scrollbar_size_vertical: int + scrollbar_size_horizontal: int + + align_horizontal: AlignHorizontal + align_vertical: AlignVertical + + content_align_horizontal: AlignHorizontal + content_align_vertical: AlignVertical + + grid_size_rows: int + grid_size_columns: int + grid_gutter_horizontal: int + grid_gutter_vertical: int + grid_rows: tuple[Scalar, ...] + grid_columns: tuple[Scalar, ...] + + row_span: int + column_span: int + + text_align: TextAlign + + link_color: Color + auto_link_color: bool + link_background: Color + link_style: Style + + link_color_hover: Color + auto_link_color_hover: bool + link_background_hover: Color + link_style_hover: Style + + auto_border_title_color: bool + border_title_color: Color + border_title_background: Color + border_title_style: Style + + auto_border_subtitle_color: bool + border_subtitle_color: Color + border_subtitle_background: Color + border_subtitle_style: Style + + hatch: tuple[str, Color] | Literal["none"] + + overlay: Overlay + constrain_x: Constrain + constrain_y: Constrain + + +RULE_NAMES = list(RulesMap.__annotations__.keys()) +RULE_NAMES_SET = frozenset(RULE_NAMES) +_rule_getter = attrgetter(*RULE_NAMES) + + +class StylesBase: + """A common base class for Styles and RenderStyles""" + + ANIMATABLE = { + "offset", + "padding", + "margin", + "width", + "height", + "min_width", + "min_height", + "max_width", + "max_height", + "auto_color", + "color", + "background", + "background_tint", + "opacity", + "position", + "text_opacity", + "tint", + "scrollbar_color", + "scrollbar_color_hover", + "scrollbar_color_active", + "scrollbar_background", + "scrollbar_background_hover", + "scrollbar_background_active", + "link_color", + "link_background", + "link_color_hover", + "link_background_hover", + } + + node: DOMNode | None = None + + display = StringEnumProperty(VALID_DISPLAY, "block", layout=True) + """Set the display of the widget, defining how it's rendered. + + Valid values are "block" or "none". + + "none" will hide and allow other widgets to fill the space that this widget would occupy. + + Set to None to clear any value that was set at runtime. + + Raises: + StyleValueError: If an invalid display is specified. + """ + + visibility = StringEnumProperty(VALID_VISIBILITY, "visible", layout=True) + """Set the visibility of the widget. + + Valid values are "visible" or "hidden". + + "hidden" will hide the widget, but reserve the space for this widget. + If you want to hide the widget and allow another widget to fill the space, + set the display attribute to "none" instead. + + Set to None to clear any value that was set at runtime. + + Raises: + StyleValueError: If an invalid visibility is specified. + """ + + layout = LayoutProperty() + """Set the layout of the widget, defining how it's children are laid out. + + Valid values are "grid", "horizontal", and "vertical" or None to clear any layout + that was set at runtime. + + Raises: + MissingLayout: If an invalid layout is specified. + """ + + auto_color = BooleanProperty(default=False) + """Enable automatic picking of best contrasting color.""" + color = ColorProperty(Color(255, 255, 255)) + """Set the foreground (text) color of the widget. + Supports `Color` objects but also strings e.g. "red" or "#ff0000". + You can also specify an opacity after a color e.g. "blue 10%" + """ + background = ColorProperty(Color(0, 0, 0, 0)) + """Set the background color of the widget. + Supports `Color` objects but also strings e.g. "red" or "#ff0000" + You can also specify an opacity after a color e.g. "blue 10%" + """ + background_tint = ColorProperty(Color(0, 0, 0, 0)) + """Set a color to tint (blend) with the background. + Supports `Color` objects but also strings e.g. "red" or "#ff0000" + You can also specify an opacity after a color e.g. "blue 10%" + """ + text_style = StyleFlagsProperty() + """Set the text style of the widget using Rich StyleFlags. + e.g. `"bold underline"` or `"b u strikethrough"`. + """ + opacity = FractionalProperty(children=True) + """Set the opacity of the widget, defining how it blends with the parent.""" + text_opacity = FractionalProperty() + """Set the opacity of the content within the widget against the widget's background.""" + padding = SpacingProperty() + """Set the padding (spacing between border and content) of the widget.""" + margin = SpacingProperty() + """Set the margin (spacing outside the border) of the widget.""" + offset = OffsetProperty() + """Set the offset of the widget relative to where it would have been otherwise.""" + position = StringEnumProperty(VALID_POSITION, "relative") + """If `relative` offset is applied to widgets current position, if `absolute` it is applied to (0, 0).""" + + border = BorderProperty(layout=True) + """Set the border of the widget e.g. ("rounded", "green") or "none".""" + + border_top = BoxProperty(Color(0, 255, 0)) + """Set the top border of the widget e.g. ("rounded", "green") or "none".""" + border_right = BoxProperty(Color(0, 255, 0)) + """Set the right border of the widget e.g. ("rounded", "green") or "none".""" + border_bottom = BoxProperty(Color(0, 255, 0)) + """Set the bottom border of the widget e.g. ("rounded", "green") or "none".""" + border_left = BoxProperty(Color(0, 255, 0)) + """Set the left border of the widget e.g. ("rounded", "green") or "none".""" + + border_title_align = StringEnumProperty(VALID_ALIGN_HORIZONTAL, "left") + """The alignment of the border title text.""" + border_subtitle_align = StringEnumProperty(VALID_ALIGN_HORIZONTAL, "right") + """The alignment of the border subtitle text.""" + + outline = BorderProperty(layout=False) + """Set the outline of the widget e.g. ("rounded", "green") or "none". + The outline is drawn *on top* of the widget, rather than around it like border. + """ + outline_top = BoxProperty(Color(0, 255, 0)) + """Set the top outline of the widget e.g. ("rounded", "green") or "none".""" + outline_right = BoxProperty(Color(0, 255, 0)) + """Set the right outline of the widget e.g. ("rounded", "green") or "none".""" + outline_bottom = BoxProperty(Color(0, 255, 0)) + """Set the bottom outline of the widget e.g. ("rounded", "green") or "none".""" + outline_left = BoxProperty(Color(0, 255, 0)) + """Set the left outline of the widget e.g. ("rounded", "green") or "none".""" + + keyline = KeylineProperty() + """Keyline parameters.""" + + box_sizing = StringEnumProperty(VALID_BOX_SIZING, "border-box", layout=True) + """Box sizing method ("border-box" or "conetnt-box")""" + width = ScalarProperty(percent_unit=Unit.WIDTH) + """Set the width of the widget.""" + height = ScalarProperty(percent_unit=Unit.HEIGHT) + """Set the height of the widget.""" + min_width = ScalarProperty(percent_unit=Unit.WIDTH, allow_auto=False) + """Set the minimum width of the widget.""" + min_height = ScalarProperty(percent_unit=Unit.HEIGHT, allow_auto=False) + """Set the minimum height of the widget.""" + max_width = ScalarProperty(percent_unit=Unit.WIDTH, allow_auto=False) + """Set the maximum width of the widget.""" + max_height = ScalarProperty(percent_unit=Unit.HEIGHT, allow_auto=False) + """Set the maximum height of the widget.""" + dock = DockProperty() + """Set which edge of the parent to dock this widget to e.g. "top", "left", "right", "bottom", "none". + """ + split = SplitProperty() + + overflow_x = OverflowProperty(VALID_OVERFLOW, "hidden") + """Control what happens when the content extends horizontally beyond the widget's width. + + Valid values are "scroll", "hidden", or "auto". + """ + + overflow_y = OverflowProperty(VALID_OVERFLOW, "hidden") + """Control what happens when the content extends vertically beyond the widget's height. + + Valid values are "scroll", "hidden", or "auto". + """ + + layer = NameProperty() + layers = NameListProperty() + transitions = TransitionsProperty() + + tint = ColorProperty("transparent") + """Set the tint of the widget. This allows you apply a opaque color above the widget. + + You can specify an opacity after a color e.g. "blue 10%" + """ + scrollbar_color = ScrollbarColorProperty("ansi_bright_magenta") + """Set the color of the handle of the scrollbar.""" + scrollbar_color_hover = ScrollbarColorProperty("ansi_yellow") + """Set the color of the handle of the scrollbar when hovered.""" + scrollbar_color_active = ScrollbarColorProperty("ansi_bright_yellow") + """Set the color of the handle of the scrollbar when active (being dragged).""" + scrollbar_corner_color = ScrollbarColorProperty("#666666") + """Set the color of the space between the horizontal and vertical scrollbars.""" + scrollbar_background = ScrollbarColorProperty("#555555") + """Set the background color of the scrollbar (the track that the handle sits on).""" + scrollbar_background_hover = ScrollbarColorProperty("#444444") + """Set the background color of the scrollbar when hovered.""" + scrollbar_background_active = ScrollbarColorProperty("black") + """Set the background color of the scrollbar when active (being dragged).""" + + scrollbar_gutter = StringEnumProperty( + VALID_SCROLLBAR_GUTTER, "auto", layout=True, refresh_children=True + ) + """Set to "stable" to reserve space for the scrollbar even when it's not visible. + This can prevent content from shifting when a scrollbar appears. + """ + + scrollbar_size_vertical = IntegerProperty(default=2, layout=True) + """Set the width of the vertical scrollbar (measured in cells).""" + scrollbar_size_horizontal = IntegerProperty(default=1, layout=True) + """Set the height of the horizontal scrollbar (measured in cells).""" + + align_horizontal = StringEnumProperty( + VALID_ALIGN_HORIZONTAL, "left", layout=True, refresh_children=True + ) + align_vertical = StringEnumProperty( + VALID_ALIGN_VERTICAL, "top", layout=True, refresh_children=True + ) + align = AlignProperty() + + content_align_horizontal = StringEnumProperty(VALID_ALIGN_HORIZONTAL, "left") + content_align_vertical = StringEnumProperty(VALID_ALIGN_VERTICAL, "top") + content_align = AlignProperty() + + grid_rows = ScalarListProperty(percent_unit=Unit.HEIGHT, refresh_children=True) + grid_columns = ScalarListProperty(percent_unit=Unit.WIDTH, refresh_children=True) + + grid_size_columns = IntegerProperty(default=1, layout=True, refresh_children=True) + grid_size_rows = IntegerProperty(default=0, layout=True, refresh_children=True) + grid_gutter_horizontal = IntegerProperty( + default=0, layout=True, refresh_children=True + ) + grid_gutter_vertical = IntegerProperty( + default=0, layout=True, refresh_children=True + ) + + row_span = IntegerProperty(default=1, layout=True) + column_span = IntegerProperty(default=1, layout=True) + + text_align = StringEnumProperty(VALID_TEXT_ALIGN, "start") + + link_color = ColorProperty("transparent") + auto_link_color = BooleanProperty(False) + link_background = ColorProperty("transparent") + link_style = StyleFlagsProperty() + + link_color_hover = ColorProperty("transparent") + auto_link_color_hover = BooleanProperty(False) + link_background_hover = ColorProperty("transparent") + link_style_hover = StyleFlagsProperty() + + auto_border_title_color = BooleanProperty(default=False) + border_title_color = ColorProperty(Color(255, 255, 255, 0)) + border_title_background = ColorProperty(Color(0, 0, 0, 0)) + border_title_style = StyleFlagsProperty() + + auto_border_subtitle_color = BooleanProperty(default=False) + border_subtitle_color = ColorProperty(Color(255, 255, 255, 0)) + border_subtitle_background = ColorProperty(Color(0, 0, 0, 0)) + border_subtitle_style = StyleFlagsProperty() + + hatch = HatchProperty() + """Add a hatched background effect e.g. ("right", "yellow") or "none" to use no hatch. + """ + + overlay = StringEnumProperty( + VALID_OVERLAY, "none", layout=True, refresh_parent=True + ) + constrain_x: StringEnumProperty[Constrain] = StringEnumProperty( + VALID_CONSTRAIN, "none" + ) + constrain_y: StringEnumProperty[Constrain] = StringEnumProperty( + VALID_CONSTRAIN, "none" + ) + + def __textual_animation__( + self, + attribute: str, + start_value: object, + value: object, + start_time: float, + duration: float | None, + speed: float | None, + easing: EasingFunction, + on_complete: CallbackType | None = None, + level: AnimationLevel = "full", + ) -> ScalarAnimation | None: + if self.node is None: + return None + + # Check we are animating a Scalar or Scalar offset + if isinstance(start_value, (Scalar, ScalarOffset)): + # If destination is a number, we can convert that to a scalar + if isinstance(value, (int, float)): + value = Scalar(value, Unit.CELLS, Unit.CELLS) + + # We can only animate to Scalar + if not isinstance(value, (Scalar, ScalarOffset)): + return None + + from textual.widget import Widget + + assert isinstance(self.node, Widget) + return ScalarAnimation( + self.node, + self, + start_time, + attribute, + value, + duration=duration, + speed=speed, + easing=easing, + on_complete=( + partial(self.node.app.call_later, on_complete) + if on_complete is not None + else None + ), + level=level, + ) + return None + + def __eq__(self, styles: object) -> bool: + """Check that Styles contains the same rules.""" + if not isinstance(styles, StylesBase): + return NotImplemented + return self.get_rules() == styles.get_rules() + + @property + def gutter(self) -> Spacing: + """Get space around widget. + + Returns: + Space around widget content. + """ + return self.padding + self.border.spacing + + @property + def auto_dimensions(self) -> bool: + """Check if width or height are set to 'auto'.""" + has_rule = self.has_rule + return (has_rule("width") and self.width.is_auto) or ( # type: ignore + has_rule("height") and self.height.is_auto # type: ignore + ) + + @property + def is_relative_width(self) -> bool: + """Does the node have a relative width?""" + width = self.width + return width is not None and width.unit in (Unit.FRACTION, Unit.PERCENT) + + @property + def is_relative_height(self) -> bool: + """Does the node have a relative width?""" + height = self.height + return height is not None and height.unit in (Unit.FRACTION, Unit.PERCENT) + + @property + def is_auto_width(self) -> bool: + """Does the node have automatic width?""" + width = self.width + return width is not None and width.unit == Unit.AUTO + + @property + def is_auto_height(self) -> bool: + """Does the node have automatic height?""" + height = self.height + return height is not None and height.unit == Unit.AUTO + + @property + def is_docked(self) -> bool: + """Is the node docked?""" + dock = self.dock + return dock != "none" + + @property + def is_split(self) -> bool: + """Is the node split?""" + split = self.split + return split != "none" + + def has_rule(self, rule_name: str) -> bool: + """Check if a rule is set on this Styles object. + + Args: + rule_name: Rule name. + + Returns: + ``True`` if the rules is present, otherwise ``False``. + """ + raise NotImplementedError() + + def clear_rule(self, rule_name: str) -> bool: + """Removes the rule from the Styles object, as if it had never been set. + + Args: + rule_name: Rule name. + + Returns: + ``True`` if a rule was cleared, or ``False`` if the rule is already not set. + """ + raise NotImplementedError() + + def get_rules(self) -> RulesMap: + """Get the rules in a mapping. + + Returns: + A TypedDict of the rules. + """ + raise NotImplementedError() + + def set_rule(self, rule_name: str, value: object | None) -> bool: + """Set a rule. + + Args: + rule_name: Rule name. + value: New rule value. + + Returns: + ``True`` if the rule changed, otherwise ``False``. + """ + raise NotImplementedError() + + def get_rule(self, rule_name: str, default: object = None) -> object: + """Get an individual rule. + + Args: + rule_name: Name of rule. + default: Default if rule does not exists. + + Returns: + Rule value or default. + """ + raise NotImplementedError() + + def refresh( + self, + *, + layout: bool = False, + children: bool = False, + parent: bool = False, + repaint: bool = True, + ) -> None: + """Mark the styles as requiring a refresh. + + Args: + layout: Also require a layout. + children: Also refresh children. + parent: Also refresh the parent. + repaint: Repaint the widgets. + """ + + def reset(self) -> None: + """Reset the rules to initial state.""" + + def merge(self, other: StylesBase) -> None: + """Merge values from another Styles. + + Args: + other: A Styles object. + """ + + def merge_rules(self, rules: RulesMap) -> None: + """Merge rules in to Styles. + + Args: + rules: A mapping of rules. + """ + + def get_render_rules(self) -> RulesMap: + """Get rules map with defaults.""" + # Get a dictionary of rules, going through the properties + rules = dict(zip(RULE_NAMES, _rule_getter(self))) + return cast(RulesMap, rules) + + @classmethod + def is_animatable(cls, rule: str) -> bool: + """Check if a given rule may be animated. + + Args: + rule: Name of the rule. + + Returns: + ``True`` if the rule may be animated, otherwise ``False``. + """ + return rule in cls.ANIMATABLE + + @classmethod + def parse( + cls, css: str, read_from: CSSLocation, *, node: DOMNode | None = None + ) -> Styles: + """Parse CSS and return a Styles object. + + Args: + css: Textual CSS. + read_from: Location where the CSS was read from. + node: Node to associate with the Styles. + + Returns: + A Styles instance containing result of parsing CSS. + """ + from textual.css.parse import parse_declarations + + styles = parse_declarations(css, read_from) + styles.node = node + return styles + + def _get_transition(self, key: str) -> Transition | None: + """Get a transition. + + Args: + key: Transition key. + + Returns: + Transition object or None it no transition exists. + """ + if key in self.ANIMATABLE: + return self.transitions.get(key, None) + else: + return None + + def _align_width(self, width: int, parent_width: int) -> int: + """Align the width dimension. + + Args: + width: Width of the content. + parent_width: Width of the parent container. + + Returns: + An offset to add to the X coordinate. + """ + offset_x = 0 + align_horizontal = self.align_horizontal + if align_horizontal != "left": + if align_horizontal == "center": + offset_x = (parent_width - width) // 2 + else: + offset_x = parent_width - width + + return offset_x + + def _align_height(self, height: int, parent_height: int) -> int: + """Align the height dimensions + + Args: + height: Height of the content. + parent_height: Height of the parent container. + + Returns: + An offset to add to the Y coordinate. + """ + offset_y = 0 + align_vertical = self.align_vertical + if align_vertical != "top": + if align_vertical == "middle": + offset_y = (parent_height - height) // 2 + else: + offset_y = parent_height - height + return offset_y + + def _align_size(self, child: tuple[int, int], parent: tuple[int, int]) -> Offset: + """Align a size according to alignment rules. + + Args: + child: The size of the child (width, height) + parent: The size of the parent (width, height) + + Returns: + Offset required to align the child. + """ + width, height = child + parent_width, parent_height = parent + return Offset( + self._align_width(width, parent_width), + self._align_height(height, parent_height), + ) + + @property + def partial_rich_style(self) -> Style: + """Get the style properties associated with this node only (not including parents in the DOM). + + Returns: + Rich Style object. + """ + style = Style( + color=( + self.color.rich_color + if self.has_rule("color") and self.color.a > 0 + else None + ), + bgcolor=( + self.background.rich_color + if self.has_rule("background") and self.background.a > 0 + else None + ), + ) + style += self.text_style + return style + + +@rich.repr.auto +@dataclass +class Styles(StylesBase): + node: DOMNode | None = None + _rules: RulesMap = field(default_factory=RulesMap) + _updates: int = 0 + + important: set[str] = field(default_factory=set) + + def __post_init__(self) -> None: + self.get_rule: Callable[[str, object], object] = self._rules.get # type: ignore[assignment] + self.has_rule: Callable[[str], bool] = self._rules.__contains__ # type: ignore[assignment] + + def copy(self) -> Styles: + """Get a copy of this Styles object.""" + return Styles( + node=self.node, + _rules=self.get_rules(), + important=self.important, + ) + + def clear_rule(self, rule_name: str) -> bool: + """Removes the rule from the Styles object, as if it had never been set. + + Args: + rule_name: Rule name. + + Returns: + ``True`` if a rule was cleared, or ``False`` if it was already not set. + """ + changed = self._rules.pop(rule_name, None) is not None # type: ignore + if changed: + self._updates += 1 + return changed + + def get_rules(self) -> RulesMap: + return self._rules.copy() + + def set_rule(self, rule: str, value: object | None) -> bool: + """Set a rule. + + Args: + rule: Rule name. + value: New rule value. + + Returns: + ``True`` if the rule changed, otherwise ``False``. + """ + if value is None: + changed = self._rules.pop(rule, None) is not None # type: ignore + if changed: + self._updates += 1 + return changed + current = self._rules.get(rule) + self._rules[rule] = value # type: ignore + changed = current != value + if changed: + self._updates += 1 + return changed + + def refresh( + self, + *, + layout: bool = False, + children: bool = False, + parent: bool = False, + repaint=True, + ) -> None: + node = self.node + if node is None or not node._is_mounted: + return + if parent and node._parent is not None: + node._parent.refresh(repaint=repaint) + node.refresh(layout=layout) + if children: + for child in node.walk_children(with_self=False, reverse=True): + child.refresh(layout=layout, repaint=repaint) + + def reset(self) -> None: + """Reset the rules to initial state.""" + self._updates += 1 + self._rules.clear() # type: ignore + + def merge(self, other: StylesBase) -> None: + """Merge values from another Styles. + + Args: + other: A Styles object. + """ + self._updates += 1 + self._rules.update(other.get_rules()) + + def merge_rules(self, rules: RulesMap) -> None: + self._updates += 1 + self._rules.update(rules) + + def extract_rules( + self, + specificity: Specificity3, + is_default_rules: bool = False, + tie_breaker: int = 0, + ) -> list[tuple[str, Specificity6, Any]]: + """Extract rules from Styles object, and apply !important css specificity as + well as higher specificity of user CSS vs widget CSS. + + Args: + specificity: A node specificity. + is_default_rules: True if the rules we're extracting are + default (i.e. in Widget.DEFAULT_CSS) rules. False if they're from user defined CSS. + + Returns: + A list containing a tuple of , . + """ + is_important = self.important.__contains__ + default_rules = 0 if is_default_rules else 1 + rules: list[tuple[str, Specificity6, Any]] = [ + ( + rule_name, + ( + default_rules, + 1 if is_important(rule_name) else 0, + *specificity, + tie_breaker, + ), + rule_value, + ) + for rule_name, rule_value in self._rules.items() + ] + + return rules + + def __rich_repr__(self) -> rich.repr.Result: + has_rule = self.has_rule + for name in RULE_NAMES: + if has_rule(name): + yield name, getattr(self, name) + if self.important: + yield "important", self.important + + def _get_border_css_lines( + self, rules: RulesMap, name: str + ) -> Iterable[tuple[str, str]]: + """Get pairs of strings containing , for border css declarations. + + Args: + rules: A rules map. + name: Name of rules (border or outline) + + Returns: + An iterable of CSS declarations. + """ + + has_rule = rules.__contains__ + get_rule = rules.__getitem__ + + has_top = has_rule(f"{name}_top") + has_right = has_rule(f"{name}_right") + has_bottom = has_rule(f"{name}_bottom") + has_left = has_rule(f"{name}_left") + if not any((has_top, has_right, has_bottom, has_left)): + # No border related rules + return + + if all((has_top, has_right, has_bottom, has_left)): + # All rules are set + # See if we can set them with a single border: declaration + top = get_rule(f"{name}_top") + right = get_rule(f"{name}_right") + bottom = get_rule(f"{name}_bottom") + left = get_rule(f"{name}_left") + + if top == right and right == bottom and bottom == left: + border_type, border_color = rules[f"{name}_top"] # type: ignore + yield name, f"{border_type} {border_color.hex}" + return + + # Check for edges + if has_top: + border_type, border_color = rules[f"{name}_top"] # type: ignore + yield f"{name}-top", f"{border_type} {border_color.hex}" + + if has_right: + border_type, border_color = rules[f"{name}_right"] # type: ignore + yield f"{name}-right", f"{border_type} {border_color.hex}" + + if has_bottom: + border_type, border_color = rules[f"{name}_bottom"] # type: ignore + yield f"{name}-bottom", f"{border_type} {border_color.hex}" + + if has_left: + border_type, border_color = rules[f"{name}_left"] # type: ignore + yield f"{name}-left", f"{border_type} {border_color.hex}" + + @property + def css_lines(self) -> list[str]: + lines: list[str] = [] + append = lines.append + + def append_declaration(name: str, value: str) -> None: + if name in self.important: + append(f"{name}: {value} !important;") + else: + append(f"{name}: {value};") + + rules = self.get_rules() + get_rule = rules.get + + if "display" in rules: + append_declaration("display", rules["display"]) + if "visibility" in rules: + append_declaration("visibility", rules["visibility"]) + if "padding" in rules: + append_declaration("padding", rules["padding"].css) + if "margin" in rules: + append_declaration("margin", rules["margin"].css) + + for name, rule in self._get_border_css_lines(rules, "border"): + append_declaration(name, rule) + + for name, rule in self._get_border_css_lines(rules, "outline"): + append_declaration(name, rule) + + if "offset" in rules: + x, y = self.offset + append_declaration("offset", f"{x} {y}") + if "position" in rules: + append_declaration("position", self.position) + if "dock" in rules: + append_declaration("dock", rules["dock"]) + if "split" in rules: + append_declaration("split", rules["split"]) + if "layers" in rules: + append_declaration("layers", " ".join(self.layers)) + if "layer" in rules: + append_declaration("layer", self.layer) + if "layout" in rules: + assert self.layout is not None + append_declaration("layout", self.layout.name) + + if "color" in rules: + append_declaration("color", self.color.hex) + if "background" in rules: + append_declaration("background", self.background.hex) + if "background_tint" in rules: + append_declaration("background-tint", self.background_tint.hex) + if "text_style" in rules: + append_declaration("text-style", str(get_rule("text_style"))) + if "tint" in rules: + append_declaration("tint", self.tint.css) + + if "overflow_x" in rules: + append_declaration("overflow-x", self.overflow_x) + if "overflow_y" in rules: + append_declaration("overflow-y", self.overflow_y) + + if "scrollbar_color" in rules: + append_declaration("scrollbar-color", self.scrollbar_color.css) + if "scrollbar_color_hover" in rules: + append_declaration("scrollbar-color-hover", self.scrollbar_color_hover.css) + if "scrollbar_color_active" in rules: + append_declaration( + "scrollbar-color-active", self.scrollbar_color_active.css + ) + + if "scrollbar_corner_color" in rules: + append_declaration( + "scrollbar-corner-color", self.scrollbar_corner_color.css + ) + + if "scrollbar_background" in rules: + append_declaration("scrollbar-background", self.scrollbar_background.css) + if "scrollbar_background_hover" in rules: + append_declaration( + "scrollbar-background-hover", self.scrollbar_background_hover.css + ) + if "scrollbar_background_active" in rules: + append_declaration( + "scrollbar-background-active", self.scrollbar_background_active.css + ) + + if "scrollbar_gutter" in rules: + append_declaration("scrollbar-gutter", self.scrollbar_gutter) + if "scrollbar_size" in rules: + append_declaration( + "scrollbar-size", + f"{self.scrollbar_size_horizontal} {self.scrollbar_size_vertical}", + ) + else: + if "scrollbar_size_horizontal" in rules: + append_declaration( + "scrollbar-size-horizontal", str(self.scrollbar_size_horizontal) + ) + if "scrollbar_size_vertical" in rules: + append_declaration( + "scrollbar-size-vertical", str(self.scrollbar_size_vertical) + ) + + if "box_sizing" in rules: + append_declaration("box-sizing", self.box_sizing) + if "width" in rules: + append_declaration("width", str(self.width)) + if "height" in rules: + append_declaration("height", str(self.height)) + if "min_width" in rules: + append_declaration("min-width", str(self.min_width)) + if "min_height" in rules: + append_declaration("min-height", str(self.min_height)) + if "max_width" in rules: + append_declaration("max-width", str(self.min_width)) + if "max_height" in rules: + append_declaration("max-height", str(self.min_height)) + if "transitions" in rules: + append_declaration( + "transition", + ", ".join( + f"{name} {transition}" + for name, transition in self.transitions.items() + ), + ) + + if "align_horizontal" in rules and "align_vertical" in rules: + append_declaration( + "align", f"{self.align_horizontal} {self.align_vertical}" + ) + elif "align_horizontal" in rules: + append_declaration("align-horizontal", self.align_horizontal) + elif "align_vertical" in rules: + append_declaration("align-vertical", self.align_vertical) + + if "content_align_horizontal" in rules and "content_align_vertical" in rules: + append_declaration( + "content-align", + f"{self.content_align_horizontal} {self.content_align_vertical}", + ) + elif "content_align_horizontal" in rules: + append_declaration( + "content-align-horizontal", self.content_align_horizontal + ) + elif "content_align_vertical" in rules: + append_declaration("content-align-vertical", self.content_align_vertical) + + if "text_align" in rules: + append_declaration("text-align", self.text_align) + + if "border_title_align" in rules: + append_declaration("border-title-align", self.border_title_align) + if "border_subtitle_align" in rules: + append_declaration("border-subtitle-align", self.border_subtitle_align) + + if "opacity" in rules: + append_declaration("opacity", str(self.opacity)) + if "text_opacity" in rules: + append_declaration("text-opacity", str(self.text_opacity)) + + if "grid_columns" in rules: + append_declaration( + "grid-columns", + " ".join(str(scalar) for scalar in self.grid_columns or ()), + ) + if "grid_rows" in rules: + append_declaration( + "grid-rows", + " ".join(str(scalar) for scalar in self.grid_rows or ()), + ) + if "grid_size_columns" in rules: + append_declaration("grid-size-columns", str(self.grid_size_columns)) + if "grid_size_rows" in rules: + append_declaration("grid-size-rows", str(self.grid_size_rows)) + + if "grid_gutter_horizontal" in rules: + append_declaration( + "grid-gutter-horizontal", str(self.grid_gutter_horizontal) + ) + if "grid_gutter_vertical" in rules: + append_declaration("grid-gutter-vertical", str(self.grid_gutter_vertical)) + + if "row_span" in rules: + append_declaration("row-span", str(self.row_span)) + if "column_span" in rules: + append_declaration("column-span", str(self.column_span)) + + if "link_color" in rules: + append_declaration("link-color", self.link_color.css) + if "link_background" in rules: + append_declaration("link-background", self.link_background.css) + if "link_style" in rules: + append_declaration("link-style", str(self.link_style)) + + if "link_color_hover" in rules: + append_declaration("link-color-hover", self.link_color_hover.css) + if "link_background_hover" in rules: + append_declaration("link-background-hover", self.link_background_hover.css) + if "link_style_hover" in rules: + append_declaration("link-style-hover", str(self.link_style_hover)) + + if "border_title_color" in rules: + append_declaration("title-color", self.border_title_color.css) + if "border_title_background" in rules: + append_declaration("title-background", self.border_title_background.css) + if "border_title_style" in rules: + append_declaration("title-text-style", str(self.border_title_style)) + + if "border_subtitle_color" in rules: + append_declaration("subtitle-color", self.border_subtitle_color.css) + if "border_subtitle_background" in rules: + append_declaration( + "subtitle-background", self.border_subtitle_background.css + ) + if "border_subtitle_text_style" in rules: + append_declaration("subtitle-text-style", str(self.border_subtitle_style)) + if "overlay" in rules: + append_declaration("overlay", str(self.overlay)) + if "constrain_x" in rules and "constrain_y" in rules: + if self.constrain_x == self.constrain_y: + append_declaration("constrain", self.constrain_x) + else: + append_declaration( + "constrain", f"{self.constrain_x} {self.constrain_y}" + ) + elif "constrain_x" in rules: + append_declaration("constrain-x", self.constrain_x) + elif "constrain_y" in rules: + append_declaration("constrain-y", self.constrain_y) + + if "keyline" in rules: + keyline_type, keyline_color = self.keyline + if keyline_type != "none": + append_declaration("keyline", f"{keyline_type}, {keyline_color.css}") + if "hatch" in rules: + hatch_character, hatch_color = self.hatch + append_declaration("hatch", f'"{hatch_character}" {hatch_color.css}') + lines.sort() + return lines + + @property + def css(self) -> str: + return "\n".join(self.css_lines) + + +@rich.repr.auto +class RenderStyles(StylesBase): + """Presents a combined view of two Styles object: a base Styles and inline Styles.""" + + def __init__(self, node: DOMNode, base: Styles, inline_styles: Styles) -> None: + self.node = node + self._base_styles = base + self._inline_styles = inline_styles + self._animate: BoundAnimator | None = None + self._updates: int = 0 + self._rich_style: tuple[int, Style] | None = None + self._gutter: tuple[int, Spacing] | None = None + + def __eq__(self, other: object) -> bool: + if isinstance(other, RenderStyles): + return ( + self._base_styles._rules == other._base_styles._rules + and self._inline_styles._rules == other._inline_styles._rules + ) + return NotImplemented + + @property + def _cache_key(self) -> int: + """A cache key, that changes when any style is changed. + + Returns: + An opaque integer. + """ + return self._updates + self._base_styles._updates + self._inline_styles._updates + + @property + def base(self) -> Styles: + """Quick access to base (css) style.""" + return self._base_styles + + @property + def inline(self) -> Styles: + """Quick access to the inline styles.""" + return self._inline_styles + + @property + def rich_style(self) -> Style: + """Get a Rich style for this Styles object.""" + assert self.node is not None + return self.node.rich_style + + @property + def gutter(self) -> Spacing: + """Get space around widget. + + Returns: + Space around widget content. + """ + # This is (surprisingly) a bit of a bottleneck + if self._gutter is not None: + cache_key, gutter = self._gutter + if cache_key == self._cache_key: + return gutter + gutter = self.padding + self.border.spacing + self._gutter = (self._cache_key, gutter) + return gutter + + def animate( + self, + attribute: str, + value: str | float | Animatable, + *, + final_value: object = ..., + duration: float | None = None, + speed: float | None = None, + delay: float = 0.0, + easing: EasingFunction | str = DEFAULT_EASING, + on_complete: CallbackType | None = None, + level: AnimationLevel = "full", + ) -> None: + """Animate an attribute. + + Args: + attribute: Name of the attribute to animate. + value: The value to animate to. + final_value: The final value of the animation. Defaults to `value` if not set. + duration: The duration (in seconds) of the animation. + speed: The speed of the animation. + delay: A delay (in seconds) before the animation starts. + easing: An easing method. + on_complete: A callable to invoke when the animation is finished. + level: Minimum level required for the animation to take place (inclusive). + """ + if self._animate is None: + assert self.node is not None + self._animate = self.node.app.animator.bind(self) + assert self._animate is not None + self._animate( + attribute, + value, + final_value=final_value, + duration=duration, + speed=speed, + delay=delay, + easing=easing, + on_complete=on_complete, + level=level, + ) + + def __rich_repr__(self) -> rich.repr.Result: + yield self.node + for rule_name in RULE_NAMES: + if self.has_rule(rule_name): + yield rule_name, getattr(self, rule_name) + + def refresh( + self, + *, + layout: bool = False, + children: bool = False, + parent: bool = False, + repaint: bool = True, + ) -> None: + self._inline_styles.refresh( + layout=layout, children=children, parent=parent, repaint=repaint + ) + + def merge(self, other: StylesBase) -> None: + """Merge values from another Styles. + + Args: + other: A Styles object. + """ + self._inline_styles.merge(other) + + def merge_rules(self, rules: RulesMap) -> None: + self._inline_styles.merge_rules(rules) + self._updates += 1 + + def reset(self) -> None: + """Reset the rules to initial state.""" + self._inline_styles.reset() + self._updates += 1 + + def has_rule(self, rule_name: str) -> bool: + """Check if a rule has been set.""" + return self._inline_styles.has_rule(rule_name) or self._base_styles.has_rule( + rule_name + ) + + def has_any_rules(self, *rule_names: str) -> bool: + """Check if any of the supplied rules have been set. + + Args: + rule_names: Number of rules. + + Returns: + `True` if any of the supplied rules have been set, `False` if none have. + """ + inline_has_rule = self._inline_styles.has_rule + base_has_rule = self._base_styles.has_rule + return any(inline_has_rule(name) or base_has_rule(name) for name in rule_names) + + def set_rule(self, rule_name: str, value: object | None) -> bool: + self._updates += 1 + return self._inline_styles.set_rule(rule_name, value) + + def get_rule(self, rule_name: str, default: object = None) -> object: + if self._inline_styles.has_rule(rule_name): + return self._inline_styles.get_rule(rule_name, default) + return self._base_styles.get_rule(rule_name, default) + + def clear_rule(self, rule_name: str) -> bool: + """Clear a rule (from inline).""" + self._updates += 1 + return self._inline_styles.clear_rule(rule_name) + + def get_rules(self) -> RulesMap: + """Get rules as a dictionary""" + rules = {**self._base_styles._rules, **self._inline_styles._rules} + return cast(RulesMap, rules) + + @property + def css(self) -> str: + """Get the CSS for the combined styles.""" + styles = Styles() + styles.merge(self._base_styles) + styles.merge(self._inline_styles) + combined_css = styles.css + return combined_css diff --git a/vllm/lib/python3.10/site-packages/textual/css/tokenize.py b/vllm/lib/python3.10/site-packages/textual/css/tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb8347158b2cdce7a9824c1837a50c7591c6d81 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/textual/css/tokenize.py @@ -0,0 +1,266 @@ +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Iterable + +from textual.css.tokenizer import Expect, Token, Tokenizer + +if TYPE_CHECKING: + from textual.css.types import CSSLocation + +PERCENT = r"-?\d+\.?\d*%" +DECIMAL = r"-?\d+\.?\d*" +COMMA = r"\s*,\s*" +OPEN_BRACE = r"\(\s*" +CLOSE_BRACE = r"\s*\)" + +HEX_COLOR = r"\#[0-9a-fA-F]{8}|\#[0-9a-fA-F]{6}|\#[0-9a-fA-F]{4}|\#[0-9a-fA-F]{3}" +RGB_COLOR = rf"rgb{OPEN_BRACE}{DECIMAL}{COMMA}{DECIMAL}{COMMA}{DECIMAL}{CLOSE_BRACE}|rgba{OPEN_BRACE}{DECIMAL}{COMMA}{DECIMAL}{COMMA}{DECIMAL}{COMMA}{DECIMAL}{CLOSE_BRACE}" +HSL_COLOR = rf"hsl{OPEN_BRACE}{DECIMAL}{COMMA}{PERCENT}{COMMA}{PERCENT}{CLOSE_BRACE}|hsla{OPEN_BRACE}{DECIMAL}{COMMA}{PERCENT}{COMMA}{PERCENT}{COMMA}{DECIMAL}{CLOSE_BRACE}" + +COMMENT_LINE = r"\# .*$" +COMMENT_START = r"\/\*" +SCALAR = rf"{DECIMAL}(?:fr|%|w|h|vw|vh)" +DURATION = r"\d+\.?\d*(?:ms|s)" +NUMBER = r"\-?\d+\.?\d*" +COLOR = rf"{HEX_COLOR}|{RGB_COLOR}|{HSL_COLOR}" +KEY_VALUE = r"[a-zA-Z_-][a-zA-Z0-9_-]*=[0-9a-zA-Z_\-\/]+" +TOKEN = "[a-zA-Z_][a-zA-Z0-9_-]*" +STRING = r"\".*?\"" +VARIABLE_REF = r"\$[a-zA-Z0-9_\-]+" + +IDENTIFIER = r"[a-zA-Z_\-][a-zA-Z0-9_\-]*" +SELECTOR_TYPE_NAME = r"[A-Z_][a-zA-Z0-9_]*" +"""Selectors representing Widget type names should start with upper case or '_'. + +The fact that a selector starts with an upper case letter or '_' is relevant in the +context of nested CSS to help determine whether xxx:yyy is a declaration + value or a +selector + pseudo-class.""" +DECLARATION_NAME = r"[a-z][a-zA-Z0-9_\-]*" +"""Declaration of TCSS rules start with lowercase. + +The fact that a declaration starts with a lower case letter is relevant in the context +of nested CSS to help determine whether xxx:yyy is a declaration + value or a selector ++ pseudo-class. +""" + +# Values permitted in variable and rule declarations. +DECLARATION_VALUES = { + "scalar": SCALAR, + "duration": DURATION, + "number": NUMBER, + "color": COLOR, + "key_value": KEY_VALUE, + "token": TOKEN, + "string": STRING, + "variable_ref": VARIABLE_REF, +} + +# The tokenizers "expectation" while at the root/highest level of scope +# in the CSS file. At this level we might expect to see selectors, comments, +# variable definitions etc. +expect_root_scope = Expect( + "selector or end of file", + whitespace=r"\s+", + comment_start=COMMENT_START, + comment_line=COMMENT_LINE, + selector_start_id=r"\#" + IDENTIFIER, + selector_start_class=r"\." + IDENTIFIER, + selector_start_universal=r"\*", + selector_start=SELECTOR_TYPE_NAME, + variable_name=rf"{VARIABLE_REF}:", + declaration_set_end=r"\}", +).expect_eof(True) + +expect_root_nested = Expect( + "selector or end of file", + whitespace=r"\s+", + comment_start=COMMENT_START, + comment_line=COMMENT_LINE, + declaration_name=DECLARATION_NAME + r"\:", + selector_start_id=r"\#" + IDENTIFIER, + selector_start_class=r"\." + IDENTIFIER, + selector_start_universal=r"\*", + selector_start=SELECTOR_TYPE_NAME, + variable_name=rf"{VARIABLE_REF}:", + declaration_set_end=r"\}", + nested=r"\&", +) + +# After a variable declaration e.g. "$warning-text: TOKENS;" +# for tokenizing variable value ------^~~~~~~^ +expect_variable_name_continue = Expect( + "variable value", + variable_value_end=r"\n|;", + whitespace=r"\s+", + comment_start=COMMENT_START, + comment_line=COMMENT_LINE, + **DECLARATION_VALUES, +).expect_eof(True) + +expect_comment_end = Expect( + "comment end", + comment_end=re.escape("*/"), +) + +# After we come across a selector in CSS e.g. ".my-class", we may +# find other selectors, pseudo-classes... e.g. ".my-class :hover" +expect_selector_continue = Expect( + "selector or {", + whitespace=r"\s+", + comment_start=COMMENT_START, + comment_line=COMMENT_LINE, + pseudo_class=r"\:[a-zA-Z_-]+", + selector_id=r"\#" + IDENTIFIER, + selector_class=r"\." + IDENTIFIER, + selector_universal=r"\*", + selector=SELECTOR_TYPE_NAME, + combinator_child=">", + new_selector=r",", + declaration_set_start=r"\{", + declaration_set_end=r"\}", + nested=r"\&", +).expect_eof(True) + +# A rule declaration e.g. "text: red;" +# ^---^ +expect_declaration = Expect( + "rule or selector", + nested=r"\&", + whitespace=r"\s+", + comment_start=COMMENT_START, + comment_line=COMMENT_LINE, + declaration_name=DECLARATION_NAME + r"\:", + declaration_set_end=r"\}", + # + selector_start_id=r"\#" + IDENTIFIER, + selector_start_class=r"\." + IDENTIFIER, + selector_start_universal=r"\*", + selector_start=SELECTOR_TYPE_NAME, +) + +expect_declaration_solo = Expect( + "rule declaration", + whitespace=r"\s+", + comment_start=COMMENT_START, + comment_line=COMMENT_LINE, + declaration_name=DECLARATION_NAME + r"\:", + declaration_set_end=r"\}", +).expect_eof(True) + +# The value(s)/content from a rule declaration e.g. "text: red;" +# ^---^ +expect_declaration_content = Expect( + "rule value or end of declaration", + declaration_end=r";", + whitespace=r"\s+", + comment_start=COMMENT_START, + comment_line=COMMENT_LINE, + **DECLARATION_VALUES, + important=r"\!important", + comma=",", + declaration_set_end=r"\}", +) + +expect_declaration_content_solo = Expect( + "rule value or end of declaration", + declaration_end=r";", + whitespace=r"\s+", + comment_start=COMMENT_START, + comment_line=COMMENT_LINE, + **DECLARATION_VALUES, + important=r"\!important", + comma=",", + declaration_set_end=r"\}", +).expect_eof(True) + + +class TokenizerState: + """State machine for the tokenizer. + + Attributes: + EXPECT: The initial expectation of the tokenizer. Since we start tokenizing + at the root scope, we might expect to see either a variable or selector, for example. + STATE_MAP: Maps token names to Expects, defines the sets of valid tokens + that we'd expect to see next, given the current token. For example, if + we've just processed a variable declaration name, we next expect to see + the value of that variable. + """ + + EXPECT = expect_root_scope + STATE_MAP = { + "variable_name": expect_variable_name_continue, + "variable_value_end": expect_root_scope, + "selector_start": expect_selector_continue, + "selector_start_id": expect_selector_continue, + "selector_start_class": expect_selector_continue, + "selector_start_universal": expect_selector_continue, + "selector_id": expect_selector_continue, + "selector_class": expect_selector_continue, + "selector_universal": expect_selector_continue, + "declaration_set_start": expect_declaration, + "declaration_name": expect_declaration_content, + "declaration_end": expect_declaration, + "declaration_set_end": expect_root_nested, + "nested": expect_selector_continue, + } + + def __call__(self, code: str, read_from: CSSLocation) -> Iterable[Token]: + tokenizer = Tokenizer(code, read_from=read_from) + expect = self.EXPECT + get_token = tokenizer.get_token + get_state = self.STATE_MAP.get + nest_level = 0 + while True: + token = get_token(expect) + name = token.name + if name == "comment_line": + continue + elif name == "comment_start": + tokenizer.skip_to(expect_comment_end) + continue + elif name == "eof": + break + elif name == "declaration_set_start": + nest_level += 1 + elif name == "declaration_set_end": + nest_level -= 1 + expect = expect_declaration if nest_level else expect_root_scope + yield token + continue + expect = get_state(name, expect) + yield token + + +class DeclarationTokenizerState(TokenizerState): + EXPECT = expect_declaration_solo + STATE_MAP = { + "declaration_name": expect_declaration_content, + "declaration_end": expect_declaration_solo, + } + + +class ValueTokenizerState(TokenizerState): + EXPECT = expect_declaration_content_solo + + +tokenize = TokenizerState() +tokenize_declarations = DeclarationTokenizerState() +tokenize_value = ValueTokenizerState() + + +def tokenize_values(values: dict[str, str]) -> dict[str, list[Token]]: + """Tokenizes the values in a dict of strings. + + Args: + values: A mapping of CSS variable name on to a value, to be + added to the CSS context. + + Returns: + A mapping of name on to a list of tokens, + """ + value_tokens = { + name: list(tokenize_value(value, ("__name__", ""))) + for name, value in values.items() + } + return value_tokens diff --git a/vllm/lib/python3.10/site-packages/textual/css/tokenizer.py b/vllm/lib/python3.10/site-packages/textual/css/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..42c29cb9e6b1b4e5b2ac0ef06c96dc4a8cbbeb25 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/textual/css/tokenizer.py @@ -0,0 +1,342 @@ +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, NamedTuple + +import rich.repr +from rich.console import Group, RenderableType +from rich.highlighter import ReprHighlighter +from rich.padding import Padding +from rich.panel import Panel +from rich.text import Text + +from textual.css._error_tools import friendly_list +from textual.css.constants import VALID_PSEUDO_CLASSES +from textual.suggestions import get_suggestion + +if TYPE_CHECKING: + from textual.css.types import CSSLocation + + +class TokenError(Exception): + """Error raised when the CSS cannot be tokenized (syntax error).""" + + def __init__( + self, + read_from: CSSLocation, + code: str, + start: tuple[int, int], + message: str, + end: tuple[int, int] | None = None, + ) -> None: + """ + Args: + read_from: The location where the CSS was read from. + code: The code being parsed. + start: Line and column number of the error (1-indexed). + message: A message associated with the error. + end: End location of token (1-indexed), or None if not known. + """ + + self.read_from = read_from + self.code = code + self.start = start + self.end = end or start + super().__init__(message) + + def _get_snippet(self) -> Panel: + """Get a short snippet of code around a given line number. + + Returns: + A renderable. + """ + from rich.syntax import Syntax + + line_no = self.start[0] + # TODO: Highlight column number + syntax = Syntax( + self.code, + lexer="scss", + theme="ansi_light", + line_numbers=True, + indent_guides=True, + line_range=(max(0, line_no - 2), line_no + 2), + highlight_lines={line_no}, + ) + syntax.stylize_range( + "reverse bold", + (self.start[0], self.start[1] - 1), + (self.end[0], self.end[1] - 1), + ) + return Panel(syntax, border_style="red") + + def __rich__(self) -> RenderableType: + highlighter = ReprHighlighter() + errors: list[RenderableType] = [] + + message = str(self) + errors.append(Text(" Error in stylesheet:", style="bold red")) + + line_no, col_no = self.start + + path, widget_variable = self.read_from + if widget_variable: + css_location = f" {path}, {widget_variable}:{line_no}:{col_no}" + else: + css_location = f" {path}:{line_no}:{col_no}" + errors.append(highlighter(css_location)) + errors.append(self._get_snippet()) + + final_message = "\n".join( + f"• {message_part.strip()}" for message_part in message.split(";") + ) + errors.append( + Padding( + highlighter( + Text(final_message, "red"), + ), + pad=(0, 1), + ) + ) + + return Group(*errors) + + +class EOFError(TokenError): + """Indicates that the CSS ended prematurely.""" + + +@rich.repr.auto +class Expect: + """Object that describes the format of tokens.""" + + def __init__(self, description: str, **tokens: str) -> None: + """Create Expect object. + + Args: + description: Description of this class of tokens, used in errors. + """ + self.description = f"Expected {description}" + self.names = list(tokens.keys()) + self.regexes = list(tokens.values()) + self._regex = re.compile( + "(" + + "|".join(f"(?P<{name}>{regex})" for name, regex in tokens.items()) + + ")" + ) + self.match = self._regex.match + self.search = self._regex.search + self._expect_eof = False + + def expect_eof(self, eof: bool) -> Expect: + self._expect_eof = eof + return self + + def __rich_repr__(self) -> rich.repr.Result: + yield from zip(self.names, self.regexes) + + +class ReferencedBy(NamedTuple): + name: str + location: tuple[int, int] + length: int + code: str + + +@rich.repr.auto(angular=True) +class Token(NamedTuple): + name: str + value: str + read_from: CSSLocation + code: str + location: tuple[int, int] + """Token starting location, 0-indexed.""" + referenced_by: ReferencedBy | None = None + + @property + def start(self) -> tuple[int, int]: + """Start line and column (1-indexed).""" + line, offset = self.location + return (line + 1, offset + 1) + + @property + def end(self) -> tuple[int, int]: + """End line and column (1-indexed).""" + line, offset = self.location + return (line + 1, offset + len(self.value) + 1) + + def with_reference(self, by: ReferencedBy | None) -> "Token": + """Return a copy of the Token, with reference information attached. + This is used for variable substitution, where a variable reference + can refer to tokens which were defined elsewhere. With the additional + ReferencedBy data attached, we can track where the token we are referring + to is used. + """ + return Token( + name=self.name, + value=self.value, + read_from=self.read_from, + code=self.code, + location=self.location, + referenced_by=by, + ) + + def __str__(self) -> str: + return self.value + + def __rich_repr__(self) -> rich.repr.Result: + yield "name", self.name + yield "value", self.value + yield ( + "read_from", + self.read_from[0] if not self.read_from[1] else self.read_from, + ) + yield "code", self.code if len(self.code) < 40 else self.code[:40] + "..." + yield "location", self.location + yield "referenced_by", self.referenced_by, None + + +class Tokenizer: + """Tokenizes Textual CSS.""" + + def __init__(self, text: str, read_from: CSSLocation = ("", "")) -> None: + """Initialize the tokenizer. + + Args: + text: String containing CSS. + read_from: Information regarding where the CSS was read from. + """ + self.read_from = read_from + self.code = text + self.lines = text.splitlines(keepends=True) + self.line_no = 0 + self.col_no = 0 + + def get_token(self, expect: Expect) -> Token: + """Get the next token. + + Args: + expect: Expect object which describes which tokens may be read. + + Raises: + EOFError: If there is an unexpected end of file. + TokenError: If there is an error with the token. + + Returns: + A new Token. + """ + + line_no = self.line_no + col_no = self.col_no + if line_no >= len(self.lines): + if expect._expect_eof: + return Token( + "eof", + "", + self.read_from, + self.code, + (line_no, col_no), + None, + ) + else: + raise EOFError( + self.read_from, + self.code, + (line_no + 1, col_no + 1), + "Unexpected end of file; did you forget a '}' ?", + ) + line = self.lines[line_no] + match = expect.match(line, col_no) + if match is None: + error_line = line[col_no:].rstrip() + error_message = ( + f"{expect.description} (found {error_line.split(';')[0]!r})." + ) + if not error_line.endswith(";"): + error_message += "; Did you forget a semicolon at the end of a line?" + raise TokenError( + self.read_from, self.code, (line_no + 1, col_no + 1), error_message + ) + iter_groups = iter(match.groups()) + + next(iter_groups) + + for name, value in zip(expect.names, iter_groups): + if value is not None: + break + else: + # For MyPy's benefit + raise AssertionError("can't reach here") + + token = Token( + name, + value, + self.read_from, + self.code, + (line_no, col_no), + referenced_by=None, + ) + + if ( + token.name == "pseudo_class" + and token.value.strip(":") not in VALID_PSEUDO_CLASSES + ): + pseudo_class = token.value.strip(":") + suggestion = get_suggestion(pseudo_class, list(VALID_PSEUDO_CLASSES)) + all_valid = f"must be one of {friendly_list(VALID_PSEUDO_CLASSES)}" + if suggestion: + raise TokenError( + self.read_from, + self.code, + (line_no + 1, col_no + 1), + f"unknown pseudo-class {pseudo_class!r}; did you mean {suggestion!r}?; {all_valid}", + ) + else: + raise TokenError( + self.read_from, + self.code, + (line_no + 1, col_no + 1), + f"unknown pseudo-class {pseudo_class!r}; {all_valid}", + ) + + col_no += len(value) + if col_no >= len(line): + line_no += 1 + col_no = 0 + self.line_no = line_no + self.col_no = col_no + return token + + def skip_to(self, expect: Expect) -> Token: + """Skip tokens. + + Args: + expect: Expect object describing the expected token. + + Raises: + EOFError: If end of file is reached. + + Returns: + A new token. + """ + line_no = self.line_no + col_no = self.col_no + + while True: + if line_no >= len(self.lines): + raise EOFError( + self.read_from, + self.code, + (line_no, col_no), + "Unexpected end of file; did you forget a '}' ?", + ) + line = self.lines[line_no] + match = expect.search(line, col_no) + + if match is None: + line_no += 1 + col_no = 0 + else: + self.line_no = line_no + self.col_no = match.span(0)[0] + return self.get_token(expect) diff --git a/vllm/lib/python3.10/site-packages/textual/css/types.py b/vllm/lib/python3.10/site-packages/textual/css/types.py new file mode 100644 index 0000000000000000000000000000000000000000..a8f6b1f7998fc0aa9746e4e9f16f95766d5faba4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/textual/css/types.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import Tuple + +from typing_extensions import Literal + +from textual.color import Color + +DockEdge = Literal["none", "top", "right", "bottom", "left"] +EdgeType = Literal[ + "", + "ascii", + "none", + "hidden", + "blank", + "round", + "solid", + "thick", + "double", + "dashed", + "heavy", + "inner", + "outer", + "hkey", + "vkey", + "tall", + "tab", + "panel", + "wide", +] +Visibility = Literal["visible", "hidden", "initial", "inherit"] +Display = Literal["block", "none"] +AlignHorizontal = Literal["left", "center", "right"] +AlignVertical = Literal["top", "middle", "bottom"] +ScrollbarGutter = Literal["auto", "stable"] +BoxSizing = Literal["border-box", "content-box"] +Overflow = Literal["scroll", "hidden", "auto"] +EdgeStyle = Tuple[EdgeType, Color] +TextAlign = Literal["left", "start", "center", "right", "end", "justify"] +Constrain = Literal["none", "inflect", "inside"] +Overlay = Literal["none", "screen"] +Position = Literal["relative", "absolute"] + +Specificity3 = Tuple[int, int, int] +Specificity6 = Tuple[int, int, int, int, int, int] + +CSSLocation = Tuple[str, str] +"""Represents the definition location of a piece of CSS code. + +The first element of the tuple is the file path from where the CSS was read. +If the CSS was read from a Python source file, the second element contains the class +variable from where the CSS was read (e.g., "Widget.DEFAULT_CSS"), otherwise it's an +empty string. +""" diff --git a/vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f04a67709043f0f5076715b379e6f959ae3eb00a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/background_screen.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/background_screen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91f2f25968e8f51be6d869c4916e42c5a7ea9a56 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/background_screen.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/blank.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/blank.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccdb26a9b2cd159e9ac0e973cf3c2537242dfd31 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/blank.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/renderables/sparkline.py b/vllm/lib/python3.10/site-packages/textual/renderables/sparkline.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c15608d448018d39d2d27da29286dc5bc655e6 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/textual/renderables/sparkline.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +import statistics +from fractions import Fraction +from typing import Callable, Generic, Iterable, Sequence, TypeVar + +from rich.color import Color +from rich.console import Console, ConsoleOptions, RenderResult +from rich.measure import Measurement +from rich.segment import Segment +from rich.style import Style + +from textual.renderables._blend_colors import blend_colors + +T = TypeVar("T", int, float) + +SummaryFunction = Callable[[Sequence[T]], float] + + +class Sparkline(Generic[T]): + """A sparkline representing a series of data. + + Args: + data: The sequence of data to render. + width: The width of the sparkline/the number of buckets to partition the data into. + min_color: The color of values equal to the min value in data. + max_color: The color of values equal to the max value in data. + summary_function: Function that will be applied to each bucket. + """ + + BARS = "▁▂▃▄▅▆▇█" + + def __init__( + self, + data: Sequence[T], + *, + width: int | None, + min_color: Color = Color.from_rgb(0, 255, 0), + max_color: Color = Color.from_rgb(255, 0, 0), + summary_function: SummaryFunction[T] = max, + ) -> None: + self.data: Sequence[T] = data + self.width = width + self.min_color = Style.from_color(min_color) + self.max_color = Style.from_color(max_color) + self.summary_function: SummaryFunction[T] = summary_function + + @classmethod + def _buckets(cls, data: list[T], num_buckets: int) -> Iterable[Sequence[T]]: + """Partition ``data`` into ``num_buckets`` buckets. For example, the data + [1, 2, 3, 4] partitioned into 2 buckets is [[1, 2], [3, 4]]. + + Args: + data: The data to partition. + num_buckets: The number of buckets to partition the data into. + """ + bucket_step = Fraction(len(data), num_buckets) + for bucket_no in range(num_buckets): + start = int(bucket_step * bucket_no) + end = int(bucket_step * (bucket_no + 1)) + partition = data[start:end] + if partition: + yield partition + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + width = self.width or options.max_width + len_data = len(self.data) + if len_data == 0: + yield Segment("▁" * width, self.min_color) + return + if len_data == 1: + yield Segment("█" * width, self.max_color) + return + + minimum, maximum = min(self.data), max(self.data) + extent = maximum - minimum or 1 + + buckets = tuple(self._buckets(list(self.data), num_buckets=width)) + + bucket_index = 0.0 + bars_rendered = 0 + step = len(buckets) / width + summary_function = self.summary_function + min_color, max_color = self.min_color.color, self.max_color.color + assert min_color is not None + assert max_color is not None + while bars_rendered < width: + partition = buckets[int(bucket_index)] + partition_summary = summary_function(partition) + height_ratio = (partition_summary - minimum) / extent + bar_index = int(height_ratio * (len(self.BARS) - 1)) + bar_color = blend_colors(min_color, max_color, height_ratio) + bars_rendered += 1 + bucket_index += step + yield Segment(self.BARS[bar_index], Style.from_color(bar_color)) + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> Measurement: + return Measurement(self.width or options.max_width, 1) + + +if __name__ == "__main__": + console = Console() + + def last(l: Sequence[T]) -> T: + return l[-1] + + funcs: Sequence[SummaryFunction[int]] = ( + min, + max, + last, + statistics.median, + statistics.mean, + ) + nums = [10, 2, 30, 60, 45, 20, 7, 8, 9, 10, 50, 13, 10, 6, 5, 4, 3, 7, 20] + console.print(f"data = {nums}\n") + for f in funcs: + console.print( + f"{f.__name__}:\t", + Sparkline(nums, width=12, summary_function=f), + end="", + ) + console.print("\n") diff --git a/vllm/lib/python3.10/site-packages/textual/renderables/styled.py b/vllm/lib/python3.10/site-packages/textual/renderables/styled.py new file mode 100644 index 0000000000000000000000000000000000000000..40ae6af372483705c57db2ff0ee9e52a40d078ef --- /dev/null +++ b/vllm/lib/python3.10/site-packages/textual/renderables/styled.py @@ -0,0 +1,50 @@ +from typing import TYPE_CHECKING + +from rich.measure import Measurement +from rich.segment import Segment + +if TYPE_CHECKING: + from rich.console import Console, ConsoleOptions, RenderableType, RenderResult + from rich.style import StyleType + + +class Styled: + """A renderable which allows you to apply a style before and after another renderable. + This can be used to layer styles on top of each other, like a style sandwich. This is used, + for example, in the DataTable to layer default CSS styles + user renderables (e.g. Text objects + stored in the cells of the table) + CSS component styles on top of each other.""" + + def __init__( + self, + renderable: "RenderableType", + pre_style: "StyleType", + post_style: "StyleType", + ) -> None: + """Construct a Styled. + + Args: + renderable (RenderableType): Any renderable. + pre_style (StyleType): A style to apply across the entire renderable. + Will be applied before the styles from the renderable itself. + post_style (StyleType): A style to apply across the entire renderable. + Will be applied after the styles from the renderable itself. + """ + self.renderable = renderable + self.pre_style = pre_style + self.post_style = post_style + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + pre_style = console.get_style(self.pre_style) + post_style = console.get_style(self.post_style) + rendered_segments = console.render(self.renderable, options) + segments = Segment.apply_style( + rendered_segments, style=pre_style, post_style=post_style + ) + return segments + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> Measurement: + return Measurement.get(console, options, self.renderable) diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75581c41d0fa7967de429294097ebea33fa14a95 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_button.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_button.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6f92f1fa79fcfb26e7da281610e1ac8bc8eb155 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_button.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_checkbox.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_checkbox.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21d654d2f65e5052b7d0b54e1c9c31117cd09d77 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_checkbox.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_digits.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_digits.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..502fe74ffd08df1d591c1c4e2cfea1c41020e23b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_digits.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_footer.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_footer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c019e537238b203e7fab706b92305508d417f32d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_footer.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_help_panel.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_help_panel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd35cd631a6401c885d5af8fccffa8576f317c9a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_help_panel.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_key_panel.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_key_panel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1a144ff4048f5fa7e42258061e4417f28e0b926 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_key_panel.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_label.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_label.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8d85c042471ca946d31e54c15b2a97f55653285 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_label.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_link.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_link.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1c1418661539a90cdb9b2a8508d0c379ac54ba5 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_link.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_log.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_log.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c472b356e2db9e839d46ccd473606de61eaf5854 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_log.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_progress_bar.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_progress_bar.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..365c421c25ef7102a0843ce29ac3324fa58d0674 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_progress_bar.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_sparkline.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_sparkline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0cf9cd3699503cea95ab774d05c445a96c1364d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_sparkline.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_tab_pane.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_tab_pane.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc30082926ed01e5a497e36a5b488eca6727318a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_tab_pane.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_tabs.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_tabs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..591429c7e8b20b66f4f60dc1bf66387dfcca32bf Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_tabs.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_text_area.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_text_area.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..482abf03fa3494fe56e035aac29112beccd68255 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/_text_area.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/button.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/button.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1772f441851aab2ff8c0b41aabe894aad36681e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/button.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/data_table.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/data_table.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d42b9b9c7e745625c27b8373f1c4d5e3c207071 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/data_table.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/input.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/input.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfb3693df95b033f45e55fdad0a88aa919eb3cac Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/input.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/select.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/select.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90e9296c89fbaea2b7ba4b7ad76bc179c0d2e755 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/select.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/selection_list.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/selection_list.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d9525ba0e74d399594b27b6b1559e9b507bd595 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/selection_list.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/text_area.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/text_area.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00a1fd55ca811bb41d1c3d2ca94039345aeb22c7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/text_area.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/tree.cpython-310.pyc b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/tree.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00381ae3afa33f872fa9238ee332a88cdee24863 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/textual/widgets/__pycache__/tree.cpython-310.pyc differ