code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def load_diffusion_weights_state_dict( model: nn.Module | DiffusionModelStruct, config: DiffusionQuantConfig, state_dict: dict[str, torch.Tensor], branch_state_dict: dict[str, dict[str, torch.Tensor]] | None = None, ) -> None: """Load the state dict of the weights of a diffusion model. Args: ...
Load the state dict of the weights of a diffusion model. Args: model (`nn.Module` or `DiffusionModelStruct`): The diffusion model to load the weights. config (`DiffusionQuantConfig`): The quantization configuration. state_dict (`dict[str, torch.Tensor]`): ...
load_diffusion_weights_state_dict
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/weight.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/weight.py
Apache-2.0
def generate_calib_dirname(self) -> str: """Generate the name for quantization calibration. Returns: str: The name. """ name = "" if self.static: name += ".static" if self.enabled_gptq: name += ".gptq" if self.enabled_low_rank:...
Generate the name for quantization calibration. Returns: str: The name.
generate_calib_dirname
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/quantizer/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/quantizer/config.py
Apache-2.0
def generate_dirnames( self, *, prefix: str = "", shape: torch.Size | tuple[int, ...] = (1024, 1024, 16, 16), default_dtype: torch.dtype = torch.float16, **kwargs, ) -> list[str]: """Get the directory names of the quantization configuration. Args: ...
Get the directory names of the quantization configuration. Args: prefix (`str`, *optional*, defaults to `""`): The prefix for the directory names. shape (`torch.Size` or `tuple[int, ...]`, *optional*, defaults to `(1024, 1024, 16, 16)`): The shape of the ...
generate_dirnames
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/quantizer/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/quantizer/config.py
Apache-2.0
def for_unsigned(self) -> "DiffusionActivationQuantizerConfig": """get the quantizer configuration for unsigned activations. Returns: `DiffusionActivationQuantizerConfig`: The quantizer configuration for unsigned activations. """ if isinstance(self.dtype, Qua...
get the quantizer configuration for unsigned activations. Returns: `DiffusionActivationQuantizerConfig`: The quantizer configuration for unsigned activations.
for_unsigned
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/quantizer/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/quantizer/config.py
Apache-2.0
def generate_calib_dirname(self) -> str: """Generate the name for quantization calibration. Returns: `str`: The name. """ name = "" if self.enabled_wgts: calib_name = self.wgts.generate_calib_dirname() if calib_name: ...
Generate the name for quantization calibration. Returns: `str`: The name.
generate_calib_dirname
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/quantizer/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/quantizer/config.py
Apache-2.0
def calibrate_dynamic_range( self, modules: tp.Sequence[nn.Module], activations: TensorsCache, weights: tp.Sequence[nn.Parameter] = None, eval_inputs: TensorsCache | None = None, eval_module: nn.Module | None = None, eval_kwargs: dict[str, tp.Any] | None = None, ...
Calibrate the dynamic range. Args: modules (`Sequence[nn.Module]`): The modules to calibrate. activations (`TensorsCache`): The inputs cache if the tensor type is not outputs, or the outputs cache if the tensor type is outputs. weights (`Seque...
calibrate_dynamic_range
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/quantizer/quantizer.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/quantizer/quantizer.py
Apache-2.0
def calibrate_dynamic_range( self, module: nn.Module, inputs: TensorsCache, weight: nn.Parameter | None = None, eval_inputs: TensorsCache | None = None, eval_module: nn.Module | None = None, eval_kwargs: dict[str, tp.Any] | None = None, orig_inputs: Tensor...
Calibrate the dynamic range. Args: module (`nn.Module`): The module to calibrate. inputs (`TensorsCache`): The inputs cache. weight (`nn.Parameter` or `None`, *optional*, defaults to `None`): The weight parameter to calibrate. ...
calibrate_dynamic_range
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/quantizer/quantizer.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/quantizer/quantizer.py
Apache-2.0
def calibrate_low_rank( self, input_quantizer: "DiffusionActivationQuantizer", modules: tp.Sequence[nn.Module], inputs: TensorsCache, weights: tp.Sequence[nn.Parameter] = None, eval_inputs: TensorsCache | None = None, eval_module: nn.Module | None = None, ...
Calibrate the quantization low-rank branch.
calibrate_low_rank
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/quantizer/quantizer.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/quantizer/quantizer.py
Apache-2.0
def get_parser(cls) -> ConfigParser: """Get a parser for evaluating a large language model. Returns: `ConfigParser`: A parser for evaluating a large language model. """ parser = ConfigParser("Evaluate a large language model") parser.add_config(cls) return par...
Get a parser for evaluating a large language model. Returns: `ConfigParser`: A parser for evaluating a large language model.
get_parser
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/config.py
Apache-2.0
def ptq( # noqa: C901 model: PreTrainedModel | LlmModelStruct, /, tokenizer: PreTrainedTokenizer, config: LlmQuantConfig, cache: LlmCacheConfig | None = None, load_dirpath: str = "", save_dirpath: str = "", copy_on_save: bool = False, save_model: bool = False, ) -> PreTrainedModel: ...
Post-training quantization of a large language model. Args: model (`PreTrainedModel` or `LlmStruct`): The large language model. tokenizer (`PreTrainedTokenizer`): The large language model tokenizer. config (`LlmQuantConfig`): The large language model post...
ptq
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/ptq.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/ptq.py
Apache-2.0
def main(config: LlmPtqRunConfig, logging_level: int = tools.logging.DEBUG) -> None: # noqa: C901 """Post-training quantization and evaluation of a large language model. Args: config (`LlmPtqConfig`): The large language model post-training quantization configuration. logging_level ...
Post-training quantization and evaluation of a large language model. Args: config (`LlmPtqConfig`): The large language model post-training quantization configuration. logging_level (`int`, *optional*, defaults to `logging.DEBUG`): The logging level.
main
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/ptq.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/ptq.py
Apache-2.0
def evaluate( self, model: PreTrainedModel, /, tokenizer: PreTrainedTokenizer, model_name: str, eos_token_ids: tp.Sequence[int] = (), output_dirpath: str = "", ) -> dict[str, dict[int, dict[str, dict[tp.Any, dict[str, tp.Any]]]]]: """Evaluate the model...
Evaluate the model. Args: model (`PreTrainedModel`): The model. tokenizer (`PreTrainedTokenizer`): The tokenizer. model_name (`str`): The name of the model. eos_token_ids (`Sequence[int]`, *optional*, defaults to `(...
evaluate
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/eval/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/eval/config.py
Apache-2.0
def evaluate( self, tasks: list[str], max_length: int | None = None, **kwargs ) -> dict[str, dict[str, dict[str, float]]]: """Evaluate the model on the given tasks. Args: tasks (`list[str]`): List of tasks to evaluate on. max_length (`int`, optional, defaults to `Non...
Evaluate the model on the given tasks. Args: tasks (`list[str]`): List of tasks to evaluate on. max_length (`int`, optional, defaults to `None`): Maximum length for the model. Returns: dict[str, dict[str, dict[str, float]]]: Evaluation results `{"results": {"task": ...
evaluate
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/eval/custom.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/eval/custom.py
Apache-2.0
def _eval_ppl_with_gptq_evaluator( model: PreTrainedModel, /, tokenizer: PreTrainedTokenizer, task: str, seq_length: int = 2048, max_num_samples: int = -1, ) -> float: """Evaluate the perplexity of a model on a task using GPTQ style evaluation. Args: model (`PreTrainedModel`): ...
Evaluate the perplexity of a model on a task using GPTQ style evaluation. Args: model (`PreTrainedModel`): The model. tokenizer (`PreTrainedTokenizer`): The tokenizer. task (`str`): The task name. seq_length (`int`, *optional*, defaults to `2048`)...
_eval_ppl_with_gptq_evaluator
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/eval/custom.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/eval/custom.py
Apache-2.0
def filter_tasks(self, tasks: list[str]) -> list[str]: """Filter the tasks to only include supported tasks.""" if "longbench-e" in tasks: return ["longbench-e"] if "longbench" in tasks: return sorted(self.task2maxlen.keys(), key=lambda x: self.task2maxlen[x]) retu...
Filter the tasks to only include supported tasks.
filter_tasks
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/eval/longbench/eval.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/eval/longbench/eval.py
Apache-2.0
def evaluate(self, tasks: list[str], max_length: int, **kwargs) -> dict[str, dict[str, dict[str, float]]]: """Evaluate the model on the given tasks.""" ... tools.logging.Formatter.indent_inc() longbench_e = False if "longbench-e" in tasks: assert len(tasks) == 1, "Lon...
Evaluate the model on the given tasks.
evaluate
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/eval/longbench/eval.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/eval/longbench/eval.py
Apache-2.0
def build_chat(self, prompt): """Build chat prompt for chat models.""" if "llama-2" in self.model_name: prompt = f"[INST]{prompt}[/INST]" return prompt
Build chat prompt for chat models.
build_chat
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/eval/longbench/eval.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/eval/longbench/eval.py
Apache-2.0
def build(self) -> tuple[PreTrainedModel, PreTrainedTokenizer]: """Build model and tokenizer. Args: dtype (`torch.dtype`, *optional*, defaults to `None`): Data type of the model. Returns: `tuple[PreTrainedModel, PreTrainedTokenizer]`: Mod...
Build model and tokenizer. Args: dtype (`torch.dtype`, *optional*, defaults to `None`): Data type of the model. Returns: `tuple[PreTrainedModel, PreTrainedTokenizer]`: Model and tokenizer.
build
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/model/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/model/config.py
Apache-2.0
def register_model_factory( cls, names: str | tuple[str, ...], /, factory: tp.Callable[[str, torch.dtype], tuple[PreTrainedModel, PreTrainedTokenizer]], *, overwrite: bool = False, ) -> None: """Register a model factory. Args: names (`str`...
Register a model factory. Args: names (`str` or `tuple[str, ...]`): Names of the model. factory (`Callable[[str, torch.dtype], tuple[PreTrainedModel, PreTrainedTokenizer]]`): Factory function. overwrite (`bool`, *optional*, defaults to `False`...
register_model_factory
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/model/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/model/config.py
Apache-2.0
def update_rotary_cos_sin( cos: torch.Tensor, sin: torch.Tensor, position_ids: torch.LongTensor | None, unsqueeze_dim: int = 1 ) -> tuple[torch.Tensor, torch.Tensor]: """Update the cos and sin tensors with new position_ids. Args: cos (``torch.Tensor``): Cosine tensor. sin (``tor...
Update the cos and sin tensors with new position_ids. Args: cos (``torch.Tensor``): Cosine tensor. sin (``torch.Tensor``): Sine tensor. position_ids (``torch.LongTensor | None``): Position ids. unsqueeze_dim (``int``, *optional*, defaults to ``1``...
update_rotary_cos_sin
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/nn/patch.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/nn/patch.py
Apache-2.0
def forward( self, states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1 ) -> torch.Tensor: """Apply rotary embedding to states. Args: states (torch.Tensor): States. cos (torch.Tensor): Cosine tensor. sin (torch.Tensor): Sine ...
Apply rotary embedding to states. Args: states (torch.Tensor): States. cos (torch.Tensor): Cosine tensor. sin (torch.Tensor): Sine tensor. unsqueeze_dim (int, optional): The dimension along which to unsqueeze cos and sin. Defaults to ``1``. ...
forward
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/nn/patch.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/nn/patch.py
Apache-2.0
def apply_rotary_pos_emb( self, q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, position_ids: torch.LongTensor = None, unsqueeze_dim: int = 1, ) -> tuple[torch.Tensor, torch.Tensor]: """Apply Rotary Position Embedding to the query and key tensors. Args: ...
Apply Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine...
apply_rotary_pos_emb
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/nn/patch.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/nn/patch.py
Apache-2.0
def get_iter_layer_activations_args( self, **kwargs ) -> tuple[list[nn.Module], list[LlmTransformerBlockStruct], list[bool], list[bool]]: """ Get the arguments for iterating over the layers and their activations. Args: skip_pre_modules (`bool`): Whether t...
Get the arguments for iterating over the layers and their activations. Args: skip_pre_modules (`bool`): Whether to skip the pre-modules skip_post_modules (`bool`): Whether to skip the post-modules Returns: `tuple[list[nn.Modu...
get_iter_layer_activations_args
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/nn/struct.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/nn/struct.py
Apache-2.0
def _default_construct( model: nn.Module, /, parent: tp.Optional[BaseModuleStruct] = None, fname: str = "", rname: str = "", rkey: str = "", idx: int = 0, **kwargs, ) -> "LlmModelStruct": """Build the Large Language Model Structure.""" ...
Build the Large Language Model Structure.
_default_construct
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/nn/struct.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/nn/struct.py
Apache-2.0
def quantize_llm_layer_activations( # noqa: C901 layer: LlmTransformerBlockStruct, config: LlmQuantConfig, quantizer_state_dict: dict[str, tp.Any], layer_cache: dict[str, IOTensorsCache] | None = None, layer_kwargs: dict[str, tp.Any] | None = None, orig_state_dict: dict[str, torch.Tensor] | Non...
Calibrate the activation quantization ranges of modules in a layer. Args: layer (`LlmTransformerBlockStruct`): Layer. config (`LlmQuantConfig`): Quantization configuration. quantizer_state_dict (`dict[str, Any]`): Activation quantizer state dict. ...
quantize_llm_layer_activations
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/activation.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/activation.py
Apache-2.0
def quantize_llm_activations( model: nn.Module | LlmModelStruct, config: LlmQuantConfig, tokenizer: PreTrainedTokenizer | None = None, quantizer_state_dict: dict[str, tp.Any] | None = None, orig_state_dict: dict[str, torch.Tensor] | None = None, ) -> dict[str, tp.Any]: """Quantize the large foun...
Quantize the large foundation model activations. Args: model (`nn.Module` or `LlmStruct`): Model to be quantized. config (`LlmQuantConfig`): Quantization configuration. tokenizer (`PreTrainedTokenizer`, *optional*, defaults to `None`): Tokenizer. ...
quantize_llm_activations
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/activation.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/activation.py
Apache-2.0
def generate_default_dirname(self) -> str: # noqa: C901 """Generate directory name for a large language model quantization configuration.""" w_names = x_names = {"qkv_proj": "qkv", "out_proj": "out", "up_proj": "fc1", "down_proj": "fc2"} y_names = {"attn_q": "q", "attn_k": "k", "attn_v": "v"} ...
Generate directory name for a large language model quantization configuration.
generate_default_dirname
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/config.py
Apache-2.0
def generate_dirnames(self, *, prefix: str = "", **kwargs) -> list[str]: """Get the names of the configuration fields.""" name = f"{self.data}.{self.num_samples}x{self.seq_length}.[{self.min_seq_length}-{self.max_seq_length}]" return [f"{prefix}.{name}" if prefix else name]
Get the names of the configuration fields.
generate_dirnames
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/dataset.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/dataset.py
Apache-2.0
def build_dataset(self, tokenizer: PreTrainedTokenizer) -> "LlmCalibDataset": """Build calibration dataset. Args: tokenizer (`PreTrainedTokenizer`): Tokenizer for encoding text. Returns: `LlmCalibDataset`: Calibration dataset. """...
Build calibration dataset. Args: tokenizer (`PreTrainedTokenizer`): Tokenizer for encoding text. Returns: `LlmCalibDataset`: Calibration dataset.
build_dataset
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/dataset.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/dataset.py
Apache-2.0
def __init__(self, config: LlmCalibDataLoaderConfig, tokenizer: PreTrainedTokenizer) -> None: """Initialize large language model calibration cache loader. Args: config (`LlmCalibDataLoaderConfig`): Configuration for loading calibration dataset. tokenizer (`PreTra...
Initialize large language model calibration cache loader. Args: config (`LlmCalibDataLoaderConfig`): Configuration for loading calibration dataset. tokenizer (`PreTrainedTokenizer`): Tokenizer for encoding text.
__init__
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/dataset.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/dataset.py
Apache-2.0
def _init_cache(self, name: str, module: nn.Module) -> IOTensorsCache: """Initialize cache. Args: name (`str`): Module name. module (`nn.Module`): Module. Returns: `IOTensorsCache`: Input and output tensors cac...
Initialize cache. Args: name (`str`): Module name. module (`nn.Module`): Module. Returns: `IOTensorsCache`: Input and output tensors cache.
_init_cache
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/dataset.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/dataset.py
Apache-2.0
def iter_samples(self) -> tp.Generator[ModuleForwardInput, None, None]: """Iterate over model input samples. Args: tokenizer (`nn.Module`): Tokenizer for encoding text. Yields: `ModuleForwardInput`: Module forward input. """ ...
Iterate over model input samples. Args: tokenizer (`nn.Module`): Tokenizer for encoding text. Yields: `ModuleForwardInput`: Module forward input.
iter_samples
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/dataset.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/dataset.py
Apache-2.0
def iter_layer_activations( # noqa: C901 self, model: nn.Module | LlmModelStruct, *args, action: CacheAction | None = None, needs_inputs_fn: tp.Callable[[str, nn.Module], bool] | bool | None = True, needs_outputs_fn: tp.Callable[[str, nn.Module], bool] | bool | None = No...
Iterate over model activations for each layer. Args: model (`nn.Module`): Model. action (`CacheAction`, *optional*, defaults to `None`): Action for caching activations. If ``None``, ``ConcatCacheAction("cpu")`` is used. needs_inputs_fn (`Calla...
iter_layer_activations
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/dataset.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/dataset.py
Apache-2.0
def _extend_params_( params: list[tuple[nn.Parameter, int]], modules: list[nn.Linear | nn.Embedding, nn.LayerNorm], out_channels_dim: int | None = None, in_channels_dim: int | None = None, ) -> list[tuple[nn.Parameter, int]]: """Extend the parameters to be reordered.""" if out_channels_dim is no...
Extend the parameters to be reordered.
_extend_params_
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/reorder.py
Apache-2.0
def reorder_llm_layer( # noqa: C901 layer: LlmTransformerBlockStruct, config: LlmQuantConfig, reorder_cache: dict[str, torch.Tensor], residual_calibrator: ChannelOrderCalibrator | None = None, layer_cache: dict[str, IOTensorsCache] | None = None, layer_kwargs: dict[str, tp.Any] | None = None, )...
Calibrate the channel order in a layer. Args: layer (`LlmTransformerBlockStruct`): Large language model layer to be reordered. config (`LlmQuantConfig`): Quantization config. reorder_cache (`dict[str, torch.Tensor]`): Reorder indexes cache. residu...
reorder_llm_layer
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/reorder.py
Apache-2.0
def reorder_llm( # noqa: C901 model: nn.Module | LlmModelStruct, config: LlmQuantConfig, tokenizer: PreTrainedTokenizer | None = None, reorder_cache: dict[str, torch.Tensor] | None = None, ) -> dict[str, torch.Tensor]: """Quantize the large foundation model weights. Args: model (`nn.Mo...
Quantize the large foundation model weights. Args: model (`nn.Module` or `LlmStruct`): Model to be reordered. config (`LlmQuantConfig`): Quantization config. tokenizer (`PreTrainedTokenizer` or `None`, *optional*, defaults to `None`): Tokenizer. r...
reorder_llm
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/reorder.py
Apache-2.0
def rotate_llm( # noqa: C901 model: PreTrainedModel | LlmModelStruct, /, config: QuantRotationConfig, rotation: torch.Tensor | None = None, ) -> torch.Tensor: """Rotate the weights of the large language model. Args: model (`PreTrainedModel` or `LlmStruct`): Model to be rota...
Rotate the weights of the large language model. Args: model (`PreTrainedModel` or `LlmStruct`): Model to be rotated. config (`QuantRotationConfig`): Rotation configuration. rotation (`torch.Tensor` or `None`, *optional*, defaults to `None`): Rotation matr...
rotate_llm
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/rotate.py
Apache-2.0
def smooth_llm_layer( # noqa: C901 layer: LlmTransformerBlockStruct, config: LlmQuantConfig, smooth_cache: dict[str, torch.Tensor], layer_cache: dict[str, IOTensorsCache] | None = None, layer_kwargs: dict[str, tp.Any] | None = None, ) -> None: """Smooth a large language model layer. Args: ...
Smooth a large language model layer. Args: layer (`LlmTransformerBlockStruct`): Large language model layer to smooth. config (`LlmQuantConfig`): Quantization configuration. smooth_cache (`dict[str, torch.Tensor]`): Smoothing scale caches. layer_ca...
smooth_llm_layer
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/smooth.py
Apache-2.0
def smooth_llm( model: nn.Module | LlmModelStruct, /, config: LlmQuantConfig, tokenizer: PreTrainedTokenizer | None = None, smooth_cache: dict[str, torch.Tensor] | None = None, ) -> dict[str, torch.Tensor]: """Smooth the large language model. Args: model (`nn.Module` or `LlmStruct`)...
Smooth the large language model. Args: model (`nn.Module` or `LlmStruct`): Model to be smoothed. config (`LlmQuantConfig`): Quantization configuration. tokenizer (`PreTrainedTokenizer`, *optional*, defaults to `None`): Tokenizer. smooth_cache (`di...
smooth_llm
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/smooth.py
Apache-2.0
def get_needs_inputs_fn(model: LlmModelStruct, config: LlmModuleQuantizerConfig) -> tp.Callable[[str, nn.Module], bool]: """Get function that checks if the module needs to cache the inputs. Args: model (`LlmStruct`): Model struct. config (`LlmModuleQuantizerConfig`): Mod...
Get function that checks if the module needs to cache the inputs. Args: model (`LlmStruct`): Model struct. config (`LlmModuleQuantizerConfig`): Module quantization config. Returns: `Callable[[str, nn.Module], bool]`: Function to check if the module n...
get_needs_inputs_fn
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/utils.py
Apache-2.0
def get_needs_outputs_fn( model: LlmModelStruct, config: LlmModuleQuantizerConfig ) -> tp.Callable[[str, nn.Module], bool]: """Get function that checks if the module needs to cache the outputs. Args: model (`LlmStruct`): Model struct. config (`LlmModuleQuantizerConfig`): ...
Get function that checks if the module needs to cache the outputs. Args: model (`LlmStruct`): Model struct. config (`LlmModuleQuantizerConfig`): Module quantization config. Returns: `Callable[[str, nn.Module], bool]`: Function to check if the module ...
get_needs_outputs_fn
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/utils.py
Apache-2.0
def quantize_llm_layer_weights( # noqa: C901 layer: LlmTransformerBlockStruct, config: LlmQuantConfig, quantizer_state_dict: dict[str, tp.Any], layer_cache: dict[str, IOTensorsCache] | None = None, layer_kwargs: dict[str, tp.Any] | None = None, return_with_scale_state_dict: bool = False, ) -> d...
Calibrate the weight quantization ranges of modules in a layer. Args: layer (`LlmTransformerBlockStruct`): Layer. config (`LlmQuantConfig`): Quantization config. quantizer_state_dict (`dict[str, Any]`): Weight quantizer. layer_cache (`dict[str, IO...
quantize_llm_layer_weights
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/weight.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/weight.py
Apache-2.0
def quantize_llm_weights( model: nn.Module | LlmModelStruct, config: LlmQuantConfig, tokenizer: PreTrainedTokenizer | None = None, quantizer_state_dict: dict[str, tp.Any] | None = None, return_with_scale_state_dict: bool = False, ) -> tuple[dict[str, tp.Any], dict[str, torch.Tensor | float | None]]:...
Quantize the large language model weights. Args: model (`nn.Module` or `LlmStruct`): Model to be quantized. config (`LlmQuantConfig`): Quantization configuration. tokenizer (`PreTrainedTokenizer`, *optional*, defaults to `None`): Tokenizer. quanti...
quantize_llm_weights
python
mit-han-lab/deepcompressor
deepcompressor/app/llm/quant/weight.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/llm/quant/weight.py
Apache-2.0
def load_state_dict_in_safetensors( path: str, device: str | torch.device = "cpu", filter_prefix: str = "" ) -> dict[str, torch.Tensor]: """Load state dict in SafeTensors. Args: path (`str`): file path. device (`str` | `torch.device`, optional, defaults to `"cpu"`): ...
Load state dict in SafeTensors. Args: path (`str`): file path. device (`str` | `torch.device`, optional, defaults to `"cpu"`): device. filter_prefix (`str`, optional, defaults to `""`): filter prefix. Returns: `dict`: loaded SafeT...
load_state_dict_in_safetensors
python
mit-han-lab/deepcompressor
deepcompressor/backend/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/utils.py
Apache-2.0
def pack_lowrank_weight(self, weight: torch.Tensor, down: bool) -> torch.Tensor: """Pack Low-Rank Weight. Args: weight (`torch.Tensor`): low-rank weight tensor. down (`bool`): whether the weight is for down projection in low-rank branch. "...
Pack Low-Rank Weight. Args: weight (`torch.Tensor`): low-rank weight tensor. down (`bool`): whether the weight is for down projection in low-rank branch.
pack_lowrank_weight
python
mit-han-lab/deepcompressor
deepcompressor/backend/nunchaku/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/nunchaku/utils.py
Apache-2.0
def unpack_lowrank_weight(self, weight: torch.Tensor, down: bool) -> torch.Tensor: """Unpack Low-Rank Weight. Args: weight (`torch.Tensor`): low-rank weight tensor. down (`bool`): whether the weight is for down projection in low-rank branch. ...
Unpack Low-Rank Weight. Args: weight (`torch.Tensor`): low-rank weight tensor. down (`bool`): whether the weight is for down projection in low-rank branch.
unpack_lowrank_weight
python
mit-han-lab/deepcompressor
deepcompressor/backend/nunchaku/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/nunchaku/utils.py
Apache-2.0
def convert_to_qserve_w4x8y16_linear_state_dict( param_name: str, weight: torch.Tensor, scale: torch.Tensor, zero: torch.Tensor, subscale: torch.Tensor | None = None, zero_pre_scaled: bool = False, ) -> dict[str, torch.Tensor]: """Convert a weight tensor to QServe W4-X8-Y16 linear state dict...
Convert a weight tensor to QServe W4-X8-Y16 linear state dictionary. Args: param_name (`str`): parameter name. weight (`torch.Tensor`): weight tensor to be converted. scale (`torch.Tensor`): scale tensor for the weight tensor. zero (`torch.Tensor`...
convert_to_qserve_w4x8y16_linear_state_dict
python
mit-han-lab/deepcompressor
deepcompressor/backend/qserve/convert.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/qserve/convert.py
Apache-2.0
def convert_to_qserve_w8x8y16_linear_state_dict( param_name: str, weight: torch.Tensor, scale: torch.Tensor ) -> dict[str, torch.Tensor]: """Convert a weight tensor to QServe W8-X8-Y16 linear state dictionary. Args: param_name (`str`): parameter name. weight (`torch.Tensor`): ...
Convert a weight tensor to QServe W8-X8-Y16 linear state dictionary. Args: param_name (`str`): parameter name. weight (`torch.Tensor`): weight tensor to be converted. scale (`torch.Tensor`): scale tensor for the weight tensor. Returns: `dict[...
convert_to_qserve_w8x8y16_linear_state_dict
python
mit-han-lab/deepcompressor
deepcompressor/backend/qserve/convert.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/qserve/convert.py
Apache-2.0
def convert_to_qserve_w4x8y16_linear_weight( weight: torch.Tensor, scale: torch.Tensor, zero: torch.Tensor, subscale: torch.Tensor | None = None, zero_pre_scaled: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor | None]: """Convert a weight tensor to QServe W4-X8-Y...
Convert a weight tensor to QServe W4-X8-Y16 linear weight format. Args: weight (`torch.Tensor`): weight tensor to be converted. scale (`torch.Tensor`): scale tensor for the weight tensor. zero (`torch.Tensor`): zero point tensor for the weight tensor. ...
convert_to_qserve_w4x8y16_linear_weight
python
mit-han-lab/deepcompressor
deepcompressor/backend/qserve/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/qserve/utils.py
Apache-2.0
def convert_to_qserve_w8x8y16_linear_weight( weight: torch.Tensor, scale: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: """Convert a weight tensor to QServe W8-X8-Y16 linear weight format. Args: weight (`torch.Tensor`): weight tensor to be converted. scale (`torch.Tensor`...
Convert a weight tensor to QServe W8-X8-Y16 linear weight format. Args: weight (`torch.Tensor`): weight tensor to be converted. scale (`torch.Tensor`): scale tensor for the weight tensor. Returns: `tuple[torch.Tensor, torch.Tensor]`: packed quantized...
convert_to_qserve_w8x8y16_linear_weight
python
mit-han-lab/deepcompressor
deepcompressor/backend/qserve/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/qserve/utils.py
Apache-2.0
def convert_to_tinychat_w4x16y16_linear_state_dict( param_name: str, weight: torch.Tensor, scale: torch.Tensor, zero: torch.Tensor, zero_pre_scaled: bool = False, ) -> dict[str, torch.Tensor]: """Convert a weight tensor to TinyChat W4-X16-Y16 linear state dictionary. Args: param_nam...
Convert a weight tensor to TinyChat W4-X16-Y16 linear state dictionary. Args: param_name (`str`): parameter name. weight (`torch.Tensor`): weight tensor to be converted. scale (`torch.Tensor`): scale tensor for the weight tensor. zero (`torch.Tens...
convert_to_tinychat_w4x16y16_linear_state_dict
python
mit-han-lab/deepcompressor
deepcompressor/backend/tinychat/convert.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/tinychat/convert.py
Apache-2.0
def from_linear( linear: nn.Linear, group_size: int, init_only: bool = False, weight: torch.Tensor | None = None, scale: torch.Tensor | None = None, zero: torch.Tensor | None = None, zero_pre_scaled: bool = False, ) -> "W4Linear": """Convert a linear l...
Convert a linear layer to a TinyChat 4-bit weight-only quantized linear layer. Args: linear (`nn.Linear`): linear layer to be converted. group_size (`int`): quantization group size. init_only (`bool`, *optional*, defaults to `False`): ...
from_linear
python
mit-han-lab/deepcompressor
deepcompressor/backend/tinychat/linear.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/tinychat/linear.py
Apache-2.0
def ceil_num_groups(in_features: int, group_size: int, weight_bits: int = 4) -> int: """Calculate the ceiling number of quantization groups. Args: in_features (`int`): input channel size. group_size (`int`): quantization group size. weight_bits (`int`, *optional*...
Calculate the ceiling number of quantization groups. Args: in_features (`int`): input channel size. group_size (`int`): quantization group size. weight_bits (`int`, *optional*, defaults to `4`): quantized weight bits. Returns: `int`: ...
ceil_num_groups
python
mit-han-lab/deepcompressor
deepcompressor/backend/tinychat/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/tinychat/utils.py
Apache-2.0
def convert_to_tinychat_w4x16y16_linear_weight( weight: torch.Tensor, scale: torch.Tensor, zero: torch.Tensor, zero_pre_scaled: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Convert a weight tensor to TinyChat W4-X16-Y16 linear weight format. Args: weight (`torc...
Convert a weight tensor to TinyChat W4-X16-Y16 linear weight format. Args: weight (`torch.Tensor`): weight tensor to be converted. scale (`torch.Tensor`): scale tensor for the weight tensor. zero (`torch.Tensor`): zero point tensor for the weight tensor. ...
convert_to_tinychat_w4x16y16_linear_weight
python
mit-han-lab/deepcompressor
deepcompressor/backend/tinychat/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/backend/tinychat/utils.py
Apache-2.0
def __init__( self, config: QuantLowRankCalibConfig, w_quantizer: Quantizer, x_quantizer: Quantizer | None, develop_dtype: torch.dtype = torch.float32, ) -> None: """Initialize the calibrator. Args: config (`QuantLowRankCalibConfig`): ...
Initialize the calibrator. Args: config (`QuantLowRankCalibConfig`): The configuration of the quantization low-rank branch calibrator. w_quantizer (`Quantizer`): The quantizer for weights. x_quantizer (`Quantizer` or `None`): T...
__init__
python
mit-han-lab/deepcompressor
deepcompressor/calib/lowrank.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/lowrank.py
Apache-2.0
def _reset(self, x_wgts: list[torch.Tensor | nn.Parameter], **kwargs) -> None: # noqa: C901 """Reset the calibrator. Args: x_wgts (`list[torch.Tensor | nn.Parameter]`): The weights in x-w computation. """ self.best_branch: LowRankBranch = None self.b...
Reset the calibrator. Args: x_wgts (`list[torch.Tensor | nn.Parameter]`): The weights in x-w computation.
_reset
python
mit-han-lab/deepcompressor
deepcompressor/calib/lowrank.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/lowrank.py
Apache-2.0
def _ask(self) -> LowRankBranch: """Ask for the next candidate. Returns: `LowRankBranch`: The next candidate. """ branch = LowRankBranch( self.w.shape[1], self.w.shape[0], rank=self.config.rank, weight=self.w - ...
Ask for the next candidate. Returns: `LowRankBranch`: The next candidate.
_ask
python
mit-han-lab/deepcompressor
deepcompressor/calib/lowrank.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/lowrank.py
Apache-2.0
def _tell(self, error: list[torch.Tensor]) -> None: # noqa: C901 """Tell the error of the last candidate and update the best candidate. Args: errors (list[torch.Tensor]): The error of the last candidate. """ if len(error) > 1: error = [sum(error)] error ...
Tell the error of the last candidate and update the best candidate. Args: errors (list[torch.Tensor]): The error of the last candidate.
_tell
python
mit-han-lab/deepcompressor
deepcompressor/calib/lowrank.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/lowrank.py
Apache-2.0
def abs_max( tensors: tp.Iterable[torch.Tensor] | torch.Tensor, num_channels: int, group_shape: tp.Sequence[int], device: torch.device | str = None, dtype: torch.dtype = torch.float32, ) -> torch.Tensor: """Get the absolute maximum of the tensors, where `R[i] = AbsMax...
Get the absolute maximum of the tensors, where `R[i] = AbsMax(T[i, :])`.
abs_max
python
mit-han-lab/deepcompressor
deepcompressor/calib/metric.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/metric.py
Apache-2.0
def abs_mean( tensors: tp.Iterable[torch.Tensor] | torch.Tensor, num_channels: int, group_shape: tp.Sequence[int], device: torch.device | str = None, dtype: torch.dtype = torch.float32, ) -> torch.Tensor: """Get the absolute mean of the tensors, where `R[i] = AbsMean(...
Get the absolute mean of the tensors, where `R[i] = AbsMean(T[i, :])`.
abs_mean
python
mit-han-lab/deepcompressor
deepcompressor/calib/metric.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/metric.py
Apache-2.0
def abs_normalize_mean( tensors: tp.Iterable[torch.Tensor] | torch.Tensor, num_channels: int, group_shape: tp.Sequence[int], device: torch.device | str = None, dtype: torch.dtype = torch.float32, ) -> torch.Tensor: """Get the absolute group normalized mean of the tens...
Get the absolute group normalized mean of the tensors, where `R[i] = Mean(U[i, :])` and `U[i,j] = Abs(T[i, j]) / AbsMax(T[:, j]))`.
abs_normalize_mean
python
mit-han-lab/deepcompressor
deepcompressor/calib/metric.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/metric.py
Apache-2.0
def root_mean_square( tensors: tp.Iterable[torch.Tensor] | torch.Tensor, num_channels: int, group_shape: tp.Sequence[int], device: torch.device | str = None, dtype: torch.dtype = torch.float32, ) -> torch.Tensor: """Get the root mean square of the tensors, where `R[i]...
Get the root mean square of the tensors, where `R[i] = Root(Mean(T[i, :]^2))`.
root_mean_square
python
mit-han-lab/deepcompressor
deepcompressor/calib/metric.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/metric.py
Apache-2.0
def __init__( self, tensor_type: TensorType, config: DynamicRangeCalibConfig, static: bool, quantizer: Quantizer, pre_scale: torch.Tensor | None = None, ) -> None: """Initialize the calibrator. Args: tensor_type (`TensorType`): ...
Initialize the calibrator. Args: tensor_type (`TensorType`): The tensor type. config (`DynamicRangeCalibConfig`): The dynamic range calibration configuration. static (`bool`): Whether the dynamic range is static, i.e., whether ...
__init__
python
mit-han-lab/deepcompressor
deepcompressor/calib/range.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/range.py
Apache-2.0
def _reset( # noqa: C901 self, x_wgts: list[torch.Tensor | nn.Parameter], x_acts: TensorsCache | None, y_acts: TensorsCache | None, **kwargs, ) -> None: """Reset the calibrator. Args: x_wgts (`list[torch.Tensor | nn.Parameter]`): ...
Reset the calibrator. Args: x_wgts (`list[torch.Tensor | nn.Parameter]`): The weights in x-w computation. x_acts (`TensorsCache` or `None`): The x activations in x-w computation. y_acts (`TensorsCache` or `None`): The y activat...
_reset
python
mit-han-lab/deepcompressor
deepcompressor/calib/range.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/range.py
Apache-2.0
def get_best(self) -> DynamicRange: """Get the best candidate. Returns: `DynamicRange`: The best candidate. """ if self.static: return DynamicRange(min=self.best_range.min, max=self.best_range.max) elif self.is_clamp_based(): r...
Get the best candidate. Returns: `DynamicRange`: The best candidate.
get_best
python
mit-han-lab/deepcompressor
deepcompressor/calib/range.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/range.py
Apache-2.0
def _ask(self) -> DynamicRange: """Ask for the next candidate. Returns: `DynamicRange`: The next candidate. """ ratio = self.ratios[self.iter][self.candidate_id] if self.is_clamp_based(): return self.base_range.scale( ratio...
Ask for the next candidate. Returns: `DynamicRange`: The next candidate.
_ask
python
mit-han-lab/deepcompressor
deepcompressor/calib/range.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/range.py
Apache-2.0
def _tell(self, error: list[torch.Tensor]) -> None: # noqa: C901 """Tell the error of the last candidate and update the best candidate. Args: errors (`list[torch.Tensor]`): The error of the last candidate. """ assert len(error) == 1, "The error should only h...
Tell the error of the last candidate and update the best candidate. Args: errors (`list[torch.Tensor]`): The error of the last candidate.
_tell
python
mit-han-lab/deepcompressor
deepcompressor/calib/range.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/range.py
Apache-2.0
def calibrate_dynamic_range( tensor_type: TensorType, config: DynamicRangeCalibConfig | None, static: bool, quantizer: Quantizer, modules: tp.Sequence[nn.Module], activations: TensorsCache, weights: tp.Sequence[nn.Parameter] | None = None, eval_inputs: TensorsCache | None = None, eva...
Calibrate the dynamic range. Args: tensor_type (`TensorType`): The tensor type. config (`DynamicRangeCalibConfig`): The quantization dynamic range calibration configuration. static (`bool`): Whether the dynamic range is static. quantizer (`Quantiz...
calibrate_dynamic_range
python
mit-han-lab/deepcompressor
deepcompressor/calib/range.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/range.py
Apache-2.0
def process(self, tensor: torch.Tensor) -> torch.Tensor: """Process the tensor. Args: tensor (torch.Tensor): The tensor to process. Returns: torch.Tensor: The processed tensor. """ self.index = self.index.to(device=tensor.device) return tensor.in...
Process the tensor. Args: tensor (torch.Tensor): The tensor to process. Returns: torch.Tensor: The processed tensor.
process
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def get_channel_index_from_rank( rank: torch.Tensor, num_channels: int, num_groups: int, index_mode: ChannelOrderCalibConfig.ChannelIndex, ) -> torch.Tensor: """Get the index from the rank. Args: rank (`torch.Tensor`): The rank of the channels. num_channels (`int`): ...
Get the index from the rank. Args: rank (`torch.Tensor`): The rank of the channels. num_channels (`int`): The number of channels. num_groups (`int`): The number of groups. index_mode (`ChannelOrderCalibConfig.ChannelIndex`): The index ...
get_channel_index_from_rank
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def get_channel_metric( inputs: TensorsCache, weights: tp.Sequence[torch.Tensor], metric_mode: ChannelOrderCalibConfig.ChannelMetric, num_channels: int, num_heads: int = 1, device: torch.device | str | None = None, dtype: torch.dtype = torch.float32, ) -> torch.Tensor: """Get the metric ...
Get the metric value of the channels. Args: inputs (`TensorsCache`): The input activations. weights (`Sequence[torch.Tensor]`): The weight tensors. metric_mode (`ChannelOrderCalibConfig.ChannelMetric`): The channel metric mode. num_channels (`int`...
get_channel_metric
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def update_channel_metric( metric: torch.Tensor | None, inputs: TensorsCache, weights: tp.Sequence[torch.Tensor], metric_mode: ChannelOrderCalibConfig.ChannelMetric, num_channels: int, num_heads: int = 1, device: torch.device | str = None, dtype: torch.dtype = torch.float32, ) -> torch.T...
Update the metric value of the channels. Args: metric (`torch.Tensor` or `None`): The metric value of the channels. inputs (`TensorsCache`): The input activations. weights (`Sequence[torch.Tensor]`): The weight tensors. metric_mode (`ChannelOrderC...
update_channel_metric
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def init_channel_index_from_metric( metric: torch.Tensor, /, metric_mode: ChannelOrderCalibConfig.ChannelMetric, index_mode: ChannelOrderCalibConfig.ChannelIndex, group_size: int, num_heads: int = 1, num_head_repeats: int = 1, ) -> torch.Tensor: """Get the index of the channels. Arg...
Get the index of the channels. Args: metric (`torch.Tensor`): The metric value of the channels. metric_mode (`ChannelOrderCalibConfig.ChannelMetric`): The channel metric mode. index_mode (`ChannelOrderCalibConfig.ChannelIndex`): The index mode. gr...
init_channel_index_from_metric
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def __init__( self, config: ChannelOrderCalibConfig, weight_quantizer: Quantizer | None, input_quantizer: Quantizer | None, num_heads: int = 1, num_head_repeats: int = 1, develop_dtype: torch.dtype = torch.float32, ) -> None: """Initialize the calibrat...
Initialize the calibrator. Args: config (`ChannelOrderCalibConfig`): The channel order calibration configuration. weight_quantizer (`Quantizer` or `None`): The quantizer for the weights. input_quantizer (`Quantizer` or `None`): ...
__init__
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def update_channel_metrics(self, weights: list[torch.Tensor | nn.Parameter], inputs: TensorsCache) -> None: """Update the metrics of the channels. Args: weights (list[torch.Tensor | nn.Parameter]): The weight tensors. inputs (TensorsCache): The input activations. """ ...
Update the metrics of the channels. Args: weights (list[torch.Tensor | nn.Parameter]): The weight tensors. inputs (TensorsCache): The input activations.
update_channel_metrics
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def _reset(self, x_wgts: list[torch.Tensor | nn.Parameter], x_acts: TensorsCache, **kwargs) -> None: """Reset the calibrator. Args: x_wgts (list[list[torch.Tensor | nn.Parameter]]): Weight tensors. x_acts (TensorsCache): Input activations. """ if self.channel_ind...
Reset the calibrator. Args: x_wgts (list[list[torch.Tensor | nn.Parameter]]): Weight tensors. x_acts (TensorsCache): Input activations.
_reset
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def _ask(self) -> torch.Tensor: """Ask for the next candidate. Returns: torch.Tensor: The next candidate. """ channel_index = self.channel_indexes[self.candidate_id] channel_index_inverse = None if channel_index is not None: channel_index_inverse ...
Ask for the next candidate. Returns: torch.Tensor: The next candidate.
_ask
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def _tell(self, errors: list[tuple[torch.Tensor, ...]]) -> None: # noqa: C901 """Tell the error of the last candidate and update the best candidate. Args: errors (list[tuple[torch.Tensor, ...]]): The error of the last candidate. """ errors = [tuple(math.root_(e.to(torch.flo...
Tell the error of the last candidate and update the best candidate. Args: errors (list[tuple[torch.Tensor, ...]]): The error of the last candidate.
_tell
python
mit-han-lab/deepcompressor
deepcompressor/calib/reorder.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/reorder.py
Apache-2.0
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: """Apply RMSNorm normalization to hidden states.""" input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_stat...
Apply RMSNorm normalization to hidden states.
forward
python
mit-han-lab/deepcompressor
deepcompressor/calib/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/rotate.py
Apache-2.0
def rotate_in_channels(weight: nn.Parameter, /, *, rotation: torch.Tensor) -> None: """Rotate the input channels of a weight matrix.""" shape, dtype = weight.shape, weight.dtype weight.data = ( torch.matmul(weight.data.view(-1, rotation.shape[0]).to(dtype=torch.float64), rotation.to(weight.device)) ...
Rotate the input channels of a weight matrix.
rotate_in_channels
python
mit-han-lab/deepcompressor
deepcompressor/calib/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/rotate.py
Apache-2.0
def rotate_out_channels(weight: nn.Parameter, /, *, rotation: torch.Tensor, bias: nn.Parameter | None = None) -> None: """Rotate the output channels of a weight matrix.""" shape, dtype = weight.shape, weight.dtype out_channels, head_channels = shape[0], rotation.shape[0] num_heads = out_channels // head...
Rotate the output channels of a weight matrix.
rotate_out_channels
python
mit-han-lab/deepcompressor
deepcompressor/calib/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/rotate.py
Apache-2.0
def hadamard_in_channels( modules: tp.Iterable[nn.Module], packager: BaseInputPackager = None, dtype: torch.dtype | None = None, device: torch.device | str | None = None, ): """Apply Hadamard quantization to the input channels of the modules.""" for module in modules: if isinstance(modul...
Apply Hadamard quantization to the input channels of the modules.
hadamard_in_channels
python
mit-han-lab/deepcompressor
deepcompressor/calib/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/rotate.py
Apache-2.0
def get_rotation_matrix(num_channels: int, random: bool = True, compatible: bool = True) -> torch.Tensor: """Get a random rotation matrix for the given number of channels.""" if random: return random_hadamard_matrix(num_channels) else: rhs, lhs, k = HadamardMatrix.get(num_channels, scale=Fal...
Get a random rotation matrix for the given number of channels.
get_rotation_matrix
python
mit-han-lab/deepcompressor
deepcompressor/calib/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/rotate.py
Apache-2.0
def transform_rms_norm_and_linear(norm: nn.LayerNorm | RMSNorm, next_modules: tp.Iterable[nn.Linear]) -> None: """Fuse the weight multiplication of rms norm into the next adjacent linear modules. Args: norm (`nn.LayerNorm` or `RMSNorm`): normalization module. next_modules (`Iterable...
Fuse the weight multiplication of rms norm into the next adjacent linear modules. Args: norm (`nn.LayerNorm` or `RMSNorm`): normalization module. next_modules (`Iterable[nn.Linear]`): modules after the normalization module.
transform_rms_norm_and_linear
python
mit-han-lab/deepcompressor
deepcompressor/calib/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/rotate.py
Apache-2.0
def transform_layer_norm_to_rms_norm( parent: nn.Module, norm_name: str, prev_modules: tp.Iterable[nn.Linear], prev_out_channels_dims: int | tp.Iterable[int] = 0, ) -> None: """Transform LayerNorm to RMSNorm. Args: parent (`nn.Module`): Parent module that contains the normal...
Transform LayerNorm to RMSNorm. Args: parent (`nn.Module`): Parent module that contains the normalization module. norm_name (`str`): Name of the normalization module in `parent`. prev_modules (`Iterable[nn.Linear]`): Previous adjacent linear modules. ...
transform_layer_norm_to_rms_norm
python
mit-han-lab/deepcompressor
deepcompressor/calib/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/rotate.py
Apache-2.0
def transform_norm_and_linear( parent: nn.Module, norm_name: str, next_modules: tp.Iterable[nn.Linear], prev_modules: tp.Iterable[nn.Linear] | None = None, prev_out_channels_dims: int | tp.Iterable[int] = 0, ): """Transform the normalization module and the next adjacent linear modules. Args...
Transform the normalization module and the next adjacent linear modules. Args: parent (nn.Module): Parent module. norm_name (str): Name of the normalization module. next_modules (tp.Iterable[nn.Linear]): Next adjacent linear modules. prev_modules (tp.Iterable[nn.Linear]): Previous a...
transform_norm_and_linear
python
mit-han-lab/deepcompressor
deepcompressor/calib/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/rotate.py
Apache-2.0
def __init__( self, tensor_type: TensorType, config: _CONFIG, w_quantizer: Quantizer | None, x_quantizer: Quantizer | None, y_quantizer: Quantizer | None, develop_dtype: torch.dtype, ) -> None: """Initialize the search-based calibrator. Args: ...
Initialize the search-based calibrator. Args: tensor_type (`TensorType`): The tensor type. config (`_CONFIG`): The calibration configuration. w_quantizer (`Quantizer` or `None`): The w quantizer for x-w computation. ...
__init__
python
mit-han-lab/deepcompressor
deepcompressor/calib/search.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/search.py
Apache-2.0
def tell(self, error: list[torch.Tensor]) -> None: """Tell the error of the last candidate and update the best candidate. Args: error (`list[torch.Tensor]`): The error of the last candidate. """ self._tell(error) self.candidate_id += 1 if self...
Tell the error of the last candidate and update the best candidate. Args: error (`list[torch.Tensor]`): The error of the last candidate.
tell
python
mit-han-lab/deepcompressor
deepcompressor/calib/search.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/search.py
Apache-2.0
def calibrate( self, x_wgts: list[nn.Parameter] | None = None, y_wgts: list[nn.Parameter] | None = None, x_acts: TensorsCache | None = None, y_acts: TensorsCache | None = None, x_mods: list[nn.Module] | None = None, y_mods: list[nn.Module] | None = None, e...
Calibrate the quantization parameters. Args: x_wgts (`list[nn.Parameter]` or `None`, *optional*, defaults to `None`): The weights in x-w computation, or weights that generates x for y-x computation. y_wgts (`list[nn.Parameter]` or `None`, *optional*, defaults to `None`):...
calibrate
python
mit-han-lab/deepcompressor
deepcompressor/calib/search.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/search.py
Apache-2.0
def process(self, tensor: torch.Tensor) -> torch.Tensor: """Process the tensor. Args: tensor (`torch.Tensor`): The tensor to smooth. Returns: `torch.Tensor`: The smoothed tensor. """ device, dtype = tensor.device, tensor.d...
Process the tensor. Args: tensor (`torch.Tensor`): The tensor to smooth. Returns: `torch.Tensor`: The smoothed tensor.
process
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def get_smooth_span( tensors: tp.Sequence[torch.Tensor], /, *, group_shape: tp.Sequence[int], span_mode: SmoothSpanMode, device: torch.device | str | None = None, dtype: torch.dtype = torch.float32, ) -> torch.Tensor: """Calculate the value span of tensors for calculating smoothing scale...
Calculate the value span of tensors for calculating smoothing scale. Args: tensors (`Sequence[torch.Tensor]`): Tensors to calculate the span. group_shape (`Sequence[int]`): Quantization group shape. span_mode (`SmoothSpanMode`): The quantization smoothing...
get_smooth_span
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def get_smooth_scale(*, alpha_base: torch.Tensor, beta_base: torch.Tensor, alpha: float, beta: float) -> torch.Tensor: """Calculate the smoothing scale for quantization. Scale = alpha_base^alpha / beta_base^beta. Args: alpha_base (`torch.Tensor`): Base span for alpha. beta_base (`to...
Calculate the smoothing scale for quantization. Scale = alpha_base^alpha / beta_base^beta. Args: alpha_base (`torch.Tensor`): Base span for alpha. beta_base (`torch.Tensor`): Base span for beta. alpha (`float`): Alpha. beta (`float`): ...
get_smooth_scale
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def __init__( self, tensor_type: TensorType, config: SmoothCalibConfig, w_quantizer: Quantizer | None, x_quantizer: Quantizer | None, y_quantizer: Quantizer | None, num_heads: int = 1, num_head_repeats: int = 1, with_rope: bool = False, dev...
Initialize the calibrator. Args: tensor_type (`TensorType`): The type of tensor to quantize. Choices are ``Weights`` and ``Outputs``. config (`SmoothCalibConfig`): The quantization smoothing calibration configuration. w_quantizer (`Quantizer` ...
__init__
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def _reset( # noqa: C901 self, *, x_wgts: list[torch.Tensor | nn.Parameter], x_acts: TensorsCache, y_wgts: list[torch.Tensor | nn.Parameter] = None, y_acts: TensorsCache | None = None, **kwargs, ) -> None: """Reset the calibrator. Args: ...
Reset the calibrator. Args: x_wgts (`list[torch.Tensor | nn.Parameter]`): The weights in x-w computation, or weights that generates x for y-x computation. x_acts (`TensorsCache`): The x activations. It should be x for x-w or y-x computation. y...
_reset
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def _split_candidate_id(self, candidate_id: int) -> tuple[int, int]: """Split the candidate id into alpha_beta id and span_pair id. Args: candidate_id (`int`): The candidate id. Returns: `tuple[int, int]`: The alpha_beta id and span_mode ...
Split the candidate id into alpha_beta id and span_pair id. Args: candidate_id (`int`): The candidate id. Returns: `tuple[int, int]`: The alpha_beta id and span_mode id.
_split_candidate_id
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def _ask(self) -> torch.Tensor: """Ask for the next candidate. Returns: `torch.Tensor`: The next candidate. """ alpha_beta_id, span_pair_id = self._split_candidate_id(self.candidate_id) alpha, beta = self.alpha_beta_pairs[alpha_beta_id] a_span...
Ask for the next candidate. Returns: `torch.Tensor`: The next candidate.
_ask
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def __init__( self, config: SmoothCalibConfig, weight_quantizer: Quantizer | None, input_quantizer: Quantizer | None, num_heads: int = 1, num_head_repeats: int = 1, develop_dtype: torch.dtype = torch.float32, ) -> None: """Initialize the calibrator. ...
Initialize the calibrator. Args: config (`SmoothCalibConfig`): The quantization smoothing calibration configuration. weight_quantizer (`Quantizer` or `None`): The weight quantizer. input_quantizer (`Quantizer` or `None`): The i...
__init__
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def __init__( self, config: SmoothCalibConfig, query_quantizer: Quantizer | None, key_quantizer: Quantizer | None, num_heads: int = 1, num_head_repeats: int = 1, with_rope: bool = True, develop_dtype: torch.dtype = torch.float32, ) -> None: """...
Initialize the calibrator. Args: config (`SmoothCalibConfig`): The quantization smoothing calibration configuration. query_quantizer (`Quantizer` or `None`): The query quantizer. key_quantizer (`Quantizer` or `None`): The key q...
__init__
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def calibrate( self, q_proj_weight: nn.Parameter, k_proj_weight: nn.Parameter, queries: TensorsCache, keys: TensorsCache, query_module: nn.Module, key_module: nn.Module, eval_module: nn.Module | None = None, eval_inputs: TensorsCache | None = None,...
Calibrate the quantization for attention. Args: q_proj_weight (`nn.Parameter`): The query projection weight. k_proj_weight (`nn.Parameter`): The key projection weight. queries (`TensorsCache`): The query activations. ...
calibrate
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0
def smooth_upscale_param(param: nn.Parameter, scale: torch.Tensor, channels_dim: int = 1) -> None: """In-place smooth the parameter by upscaling. Args: param (`nn.Parameter`): The parameter to smooth. scale (`torch.Tensor`): The scale to upscale. channels_dim (`i...
In-place smooth the parameter by upscaling. Args: param (`nn.Parameter`): The parameter to smooth. scale (`torch.Tensor`): The scale to upscale. channels_dim (`int`, *optional*, defaults to `1`): The dimension of channels.
smooth_upscale_param
python
mit-han-lab/deepcompressor
deepcompressor/calib/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/calib/smooth.py
Apache-2.0