|
| 1 | +# Copyright (c) 2025 Intel Corporation |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +from typing import Any, Dict, List, TypedDict, TypeVar, cast |
| 13 | +from weakref import WeakKeyDictionary |
| 14 | + |
| 15 | +from torch import nn |
| 16 | + |
| 17 | +import nncf |
| 18 | +from nncf.experimental.torch2.function_hook.wrapper import get_hook_storage |
| 19 | +from nncf.experimental.torch2.function_hook.wrapper import wrap_model |
| 20 | +from nncf.torch.layer_utils import COMPRESSION_MODULES |
| 21 | +from nncf.torch.layer_utils import StatefullModuleInterface |
| 22 | + |
| 23 | +COMPRESSION_STATE_ATTR = "compression_state" |
| 24 | +TModel = TypeVar("TModel", bound=nn.Module) |
| 25 | + |
| 26 | + |
| 27 | +class S_COMMAND(TypedDict): |
| 28 | + hook_names_in_model: List[str] |
| 29 | + module_cls_name: str |
| 30 | + module_config: Dict[str, Any] |
| 31 | + |
| 32 | + |
| 33 | +def get_config(model: nn.Module) -> Dict[str, Any]: |
| 34 | + """ |
| 35 | + Returns serializable config which contains all information required to recover all additional modules placement. |
| 36 | +
|
| 37 | + :param model: The model to serialize. |
| 38 | + :return: Serializable config. |
| 39 | + """ |
| 40 | + hook_storage = get_hook_storage(model) |
| 41 | + |
| 42 | + # Find shared modules |
| 43 | + modules_map: WeakKeyDictionary[nn.Module, List[str]] = WeakKeyDictionary() |
| 44 | + for name, module in hook_storage.named_modules(remove_duplicate=False): |
| 45 | + splitted_name = name.split(".") |
| 46 | + if len(splitted_name) != 3: |
| 47 | + # Expected depths of target hook module is 3 |
| 48 | + # <3 - ModuleDicts in HookStorage, >3 - submodules of hooks |
| 49 | + continue |
| 50 | + if module not in modules_map: |
| 51 | + modules_map[module] = [] |
| 52 | + modules_map[module].append(name) |
| 53 | + |
| 54 | + # Generate serialized transformation commands |
| 55 | + serialized_transformations: List[S_COMMAND] = [] |
| 56 | + for module, names in modules_map.items(): |
| 57 | + compression_module_name = module.__class__.__name__ |
| 58 | + if compression_module_name not in COMPRESSION_MODULES.registry_dict: |
| 59 | + msg = ( |
| 60 | + f"Could not serialize compression module with name {compression_module_name}. " |
| 61 | + "Please register your module in the COMPRESSION_MODULES registry." |
| 62 | + ) |
| 63 | + raise nncf.InternalError(msg) |
| 64 | + if not isinstance(module, StatefullModuleInterface): |
| 65 | + msg = "Support only StatefullModuleInterface modules" |
| 66 | + raise nncf.InternalError(msg) |
| 67 | + |
| 68 | + serialized_transformations.append( |
| 69 | + { |
| 70 | + "hook_names_in_model": names, |
| 71 | + "module_cls_name": compression_module_name, |
| 72 | + "module_config": module.get_config(), |
| 73 | + } |
| 74 | + ) |
| 75 | + |
| 76 | + return {COMPRESSION_STATE_ATTR: serialized_transformations} |
| 77 | + |
| 78 | + |
| 79 | +def load_from_config(model: TModel, config: Dict[str, Any]) -> TModel: |
| 80 | + """ |
| 81 | + Initialize model with compressed modules from config file. |
| 82 | +
|
| 83 | + .. code-block:: python |
| 84 | +
|
| 85 | + model = MyModel() |
| 86 | + qmodel = nncf.quantize(model, ...) |
| 87 | + torch.save( |
| 88 | + { |
| 89 | + "state_dict": qmodel.state_dict(), |
| 90 | + "config": get_config(qmodel), |
| 91 | + }, |
| 92 | + "ckpt.pth", |
| 93 | + ) |
| 94 | + ... |
| 95 | + ckpt = torch.load("ckpt.pth") |
| 96 | + restored_model = load_from_config(MyModel(), ckpt["config"]) |
| 97 | + restored_model.load_state_dict(ckpt["state_dict"]) |
| 98 | +
|
| 99 | + :param model: The original uncompressed model. |
| 100 | + :param config: The configuration dictionary containing the compressed model information. |
| 101 | + :return: The compressed model. |
| 102 | + """ |
| 103 | + wrapped_model = wrap_model(model) |
| 104 | + hook_storage = get_hook_storage(wrapped_model) |
| 105 | + transformation_commands = cast(List[S_COMMAND], config[COMPRESSION_STATE_ATTR]) |
| 106 | + for command in transformation_commands: |
| 107 | + module_cls = COMPRESSION_MODULES.get(command["module_cls_name"]) |
| 108 | + module = module_cls.from_config(command["module_config"]) |
| 109 | + for target_name in command["hook_names_in_model"]: |
| 110 | + hook_type, hook_key, hook_id = target_name.split(".") |
| 111 | + storage_dict = getattr(hook_storage, hook_type) |
| 112 | + if hook_key not in storage_dict: |
| 113 | + storage_dict[hook_key] = nn.ModuleDict() |
| 114 | + if hook_id in storage_dict[hook_key]: |
| 115 | + msg = f"{hook_id=} for {hook_type}.{hook_key} already registered" |
| 116 | + raise nncf.InternalError(msg) |
| 117 | + storage_dict[hook_key][hook_id] = module |
| 118 | + return wrapped_model |
0 commit comments