|
| 1 | +# Copyright 2026 Tencent Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import importlib |
| 16 | +from typing import Any, Dict, List, Tuple |
| 17 | + |
| 18 | +import torch.nn as nn |
| 19 | + |
| 20 | +from .base.config import TokenCompressorConfig |
| 21 | +from .utils.config_utils import plan_pruning_execution |
| 22 | + |
| 23 | + |
| 24 | +class UniversalPruningAdapter: |
| 25 | + """ |
| 26 | + A metadata-driven adapter that transforms standard models into prunable models. |
| 27 | + The transformation sequence and targets are determined at initialization. |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + model: nn.Module, |
| 33 | + strategy_config: TokenCompressorConfig, |
| 34 | + raw_map_data: List[Dict[str, Any]], |
| 35 | + ): |
| 36 | + """ |
| 37 | + Args: |
| 38 | + model: The base HuggingFace model. |
| 39 | + strategy_config: User-defined compression and data requirements. |
| 40 | + raw_map_data: The ordered list of component mappings from YAML. |
| 41 | + """ |
| 42 | + self.model = model |
| 43 | + |
| 44 | + # 1. Generate the immutable execution plan at initialization |
| 45 | + self.strategy_config, self.execution_plan = plan_pruning_execution( |
| 46 | + strategy_config=strategy_config, |
| 47 | + raw_map_data=raw_map_data, |
| 48 | + model_config=getattr(model, "config", None), |
| 49 | + ) |
| 50 | + |
| 51 | + # 2. Initialize backup storage for original module pointers |
| 52 | + if not hasattr(self.model, "old_model"): |
| 53 | + self.model.old_model = {} |
| 54 | + |
| 55 | + def _get_parent_and_attr(self, path: str) -> Tuple[Any, str]: |
| 56 | + """Resolves a dot-separated string path to (parent_object, attribute_name).""" |
| 57 | + parts = path.split(".") |
| 58 | + current = self.model |
| 59 | + for part in parts[:-1]: |
| 60 | + current = getattr(current, part) |
| 61 | + return current, parts[-1] |
| 62 | + |
| 63 | + def _get_wrapper_class(self, module_path: str, class_name: str) -> Any: |
| 64 | + """ |
| 65 | + Dynamically imports the specified wrapper class. |
| 66 | + """ |
| 67 | + # Relative import logic: assumes we are inside the 'token_compressor' |
| 68 | + # package |
| 69 | + module = importlib.import_module( |
| 70 | + module_path, |
| 71 | + package="angelslim.compressor.token_compressor", |
| 72 | + ) |
| 73 | + return getattr(module, class_name) |
| 74 | + |
| 75 | + def _expand_execution_step(self, step: Dict[str, Any]) -> List[Tuple[str, int]]: |
| 76 | + """ |
| 77 | + Expands a plan step into physical module paths. |
| 78 | + Handles '[n]' by referencing the 'indices' field determined during planning. |
| 79 | + """ |
| 80 | + path_template = step["path"] |
| 81 | + if "[n]" not in path_template: |
| 82 | + return [(path_template, -1)] |
| 83 | + |
| 84 | + prefix, suffix = path_template.split("[n]") |
| 85 | + suffix = suffix.lstrip(".") |
| 86 | + container_path = prefix.rstrip(".") |
| 87 | + |
| 88 | + parent, attr = self._get_parent_and_attr(container_path) |
| 89 | + container = getattr(parent, attr) |
| 90 | + |
| 91 | + # Use planned indices; if None, default to the entire range of the |
| 92 | + # container |
| 93 | + target_indices = step.get("indices") |
| 94 | + if target_indices is None: |
| 95 | + target_indices = range(len(container)) |
| 96 | + |
| 97 | + expanded = [] |
| 98 | + for i in target_indices: |
| 99 | + full_path = f"{container_path}.{i}" |
| 100 | + if suffix: |
| 101 | + full_path += f".{suffix}" |
| 102 | + expanded.append((full_path, i)) |
| 103 | + return expanded |
| 104 | + |
| 105 | + def wrap_model(self) -> nn.Module: |
| 106 | + """ |
| 107 | + Sequentially wraps model components according to the execution_plan. |
| 108 | + """ |
| 109 | + for step in self.execution_plan: |
| 110 | + name = step["name"] |
| 111 | + wrapper_mod = step["wrapper_module"] |
| 112 | + wrapper_cls = step["wrapper_class"] |
| 113 | + |
| 114 | + WrapperClass = self._get_wrapper_class(wrapper_mod, wrapper_cls) |
| 115 | + targets = self._expand_execution_step(step) |
| 116 | + |
| 117 | + if name not in self.model.old_model: |
| 118 | + self.model.old_model[name] = {} |
| 119 | + |
| 120 | + print(f"targets: {targets}") |
| 121 | + |
| 122 | + for path, idx in targets: |
| 123 | + parent, attr_name = self._get_parent_and_attr(path) |
| 124 | + original_module = getattr(parent, attr_name) |
| 125 | + |
| 126 | + # Prevent double-wrapping |
| 127 | + if not isinstance(original_module, WrapperClass): |
| 128 | + # Store original module for safe recovery |
| 129 | + backup_key = idx if idx != -1 else "single" |
| 130 | + self.model.old_model[name][backup_key] = original_module |
| 131 | + |
| 132 | + # Instantiate and replace with the prunable wrapper |
| 133 | + new_module = WrapperClass(original_module, self.strategy_config) |
| 134 | + |
| 135 | + # Explicitly inject the layer index for collection |
| 136 | + # components |
| 137 | + if idx != -1: |
| 138 | + new_module.layer_idx = idx |
| 139 | + |
| 140 | + setattr(parent, attr_name, new_module) |
| 141 | + |
| 142 | + print(f"[UniversalAdapter] '{name}' wrapped successfully") |
| 143 | + |
| 144 | + return self.model |
| 145 | + |
| 146 | + def unwrap_model(self) -> nn.Module: |
| 147 | + """ |
| 148 | + Restores the model to its original state by iterating the plan in REVERSE order. |
| 149 | + """ |
| 150 | + if not hasattr(self.model, "old_model") or not self.model.old_model: |
| 151 | + return self.model |
| 152 | + |
| 153 | + # Order is reversed to restore nested modules from inside-out |
| 154 | + for step in reversed(self.execution_plan): |
| 155 | + name = step["name"] |
| 156 | + if name not in self.model.old_model: |
| 157 | + continue |
| 158 | + |
| 159 | + targets = self._expand_execution_step(step) |
| 160 | + backups = self.model.old_model[name] |
| 161 | + |
| 162 | + for path, idx in targets: |
| 163 | + backup_key = idx if idx != -1 else "single" |
| 164 | + if backup_key in backups: |
| 165 | + parent, attr_name = self._get_parent_and_attr(path) |
| 166 | + setattr(parent, attr_name, backups[backup_key]) |
| 167 | + |
| 168 | + print(f"[UniversalAdapter] '{name}' successfully restored.") |
| 169 | + |
| 170 | + # Cleanup metadata |
| 171 | + self.model.old_model = {} |
| 172 | + if hasattr(self.model, "_pruning_adapter"): |
| 173 | + del self.model._pruning_adapter |
| 174 | + |
| 175 | + print("[UniversalAdapter] Model fully reverted to standard architecture.") |
| 176 | + return self.model |
0 commit comments