torch-tweak 0.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- torch_tweak/__init__.py +9 -0
- torch_tweak/__version__.py +11 -0
- torch_tweak/global_context.py +73 -0
- torch_tweak/torch/__init__.py +40 -0
- torch_tweak/torch/backend/__init__.py +27 -0
- torch_tweak/torch/backend/backend.py +477 -0
- torch_tweak/torch/backend/openvino/__init__.py +8 -0
- torch_tweak/torch/backend/openvino/openvino_backend.py +269 -0
- torch_tweak/torch/backend/openvino/ov_model_converter.py +425 -0
- torch_tweak/torch/backend/torch_eager.py +165 -0
- torch_tweak/torch/backend/torch_inductor_backend.py +266 -0
- torch_tweak/torch/backend/torchao_backend.py +340 -0
- torch_tweak/torch/backend/xpu_graph_backend.py +326 -0
- torch_tweak/torch/checkpoint/__init__.py +3 -0
- torch_tweak/torch/checkpoint/checkpoint.py +55 -0
- torch_tweak/torch/checkpoint/local_torch_storage.py +67 -0
- torch_tweak/torch/checkpoint/storage.py +67 -0
- torch_tweak/torch/checkpoint/storage_tasks.py +528 -0
- torch_tweak/torch/checkpoint/torch_checkpoint.py +336 -0
- torch_tweak/torch/config.py +104 -0
- torch_tweak/torch/dataloader.py +555 -0
- torch_tweak/torch/inspecting/__init__.py +11 -0
- torch_tweak/torch/inspecting/inspecting.py +123 -0
- torch_tweak/torch/inspecting/module_info.py +188 -0
- torch_tweak/torch/inspecting/module_inspector.py +428 -0
- torch_tweak/torch/inspecting/wrapping.py +49 -0
- torch_tweak/torch/integrations/__init__.py +3 -0
- torch_tweak/torch/integrations/hugging_face.py +20 -0
- torch_tweak/torch/module/__init__.py +9 -0
- torch_tweak/torch/module/graph_spec.py +85 -0
- torch_tweak/torch/module/locator.py +435 -0
- torch_tweak/torch/module/passthrough_module.py +44 -0
- torch_tweak/torch/module/recording_module.py +159 -0
- torch_tweak/torch/module/sample_metadata.py +466 -0
- torch_tweak/torch/module/tensor_spec.py +271 -0
- torch_tweak/torch/module/tuned_module.py +142 -0
- torch_tweak/torch/module/wrapper_module.py +483 -0
- torch_tweak/torch/module_registry.py +48 -0
- torch_tweak/torch/task/__init__.py +29 -0
- torch_tweak/torch/task/correctness.py +85 -0
- torch_tweak/torch/task/find_max_batch_size.py +133 -0
- torch_tweak/torch/task/profiling/__init__.py +38 -0
- torch_tweak/torch/task/profiling/config.py +57 -0
- torch_tweak/torch/task/profiling/events.py +33 -0
- torch_tweak/torch/task/profiling/measuring_stop_strategy.py +82 -0
- torch_tweak/torch/task/profiling/measuring_strategy.py +70 -0
- torch_tweak/torch/task/profiling/metrics.py +77 -0
- torch_tweak/torch/task/profiling/profiling.py +193 -0
- torch_tweak/torch/task/profiling/profiling_stop_strategy.py +77 -0
- torch_tweak/torch/tune_strategy/__init__.py +12 -0
- torch_tweak/torch/tune_strategy/extension/__init__.py +18 -0
- torch_tweak/torch/tune_strategy/extension/find_max_batch_size_extension.py +175 -0
- torch_tweak/torch/tune_strategy/first_wins_strategy.py +105 -0
- torch_tweak/torch/tune_strategy/highest_throughput_strategy.py +236 -0
- torch_tweak/torch/tune_strategy/one_backend_strategy.py +73 -0
- torch_tweak/torch/tune_strategy/tune_strategy.py +242 -0
- torch_tweak/torch/tuning.py +221 -0
- torch_tweak/torch/utils/__init__.py +3 -0
- torch_tweak/torch/utils/device.py +48 -0
- torch_tweak/torch/utils/graph_break_detector.py +50 -0
- torch_tweak/torch/utils/memory.py +45 -0
- torch_tweak/torch/utils/module.py +175 -0
- torch_tweak/torch/utils/path_utils.py +77 -0
- torch_tweak/torch/utils/xpu.py +79 -0
- torch_tweak/utils/__init__.py +19 -0
- torch_tweak/utils/hashing.py +12 -0
- torch_tweak/utils/logging.py +471 -0
- torch_tweak/utils/permissions.py +34 -0
- torch_tweak/utils/system_monitor.py +391 -0
- torch_tweak/utils/timer.py +320 -0
- torch_tweak/utils/trace.py +61 -0
- torch_tweak-0.4.1.dist-info/METADATA +209 -0
- torch_tweak-0.4.1.dist-info/RECORD +76 -0
- torch_tweak-0.4.1.dist-info/WHEEL +4 -0
- torch_tweak-0.4.1.dist-info/licenses/LICENSE +174 -0
- torch_tweak-0.4.1.dist-info/licenses/third-party-programs.txt +198 -0
torch_tweak/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
2
|
+
# Copyright (c) 2026 Intel Corporation
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
# NOTE: This file has been modified by Intel Corporation.
|
|
5
|
+
"""Main module for torch_tweak."""
|
|
6
|
+
|
|
7
|
+
from torch_tweak.__version__ import __version__ # noqa: F401
|
|
8
|
+
|
|
9
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
2
|
+
# Copyright (c) 2026 Intel Corporation
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
# NOTE: This file has been modified by Intel Corporation.
|
|
6
|
+
from importlib.metadata import version
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
__version__ = version("torch_tweak")
|
|
10
|
+
except Exception:
|
|
11
|
+
__version__ = "0.0.0+unknown"
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
2
|
+
# Copyright (c) 2026 Intel Corporation
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
# NOTE: This file has been modified by Intel Corporation.
|
|
5
|
+
"""Global context for torch."""
|
|
6
|
+
|
|
7
|
+
BATCH_SIZE_KEY = "batch_size"
|
|
8
|
+
LIBRARY_LOGGING_KEY = "library_logging"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class GlobalContext:
|
|
12
|
+
"""Global context holding key value pairs.
|
|
13
|
+
|
|
14
|
+
Creates only one instance (singleton) and can be used as a context manager to push and pop context.
|
|
15
|
+
|
|
16
|
+
Example:
|
|
17
|
+
>>> global_context.set("bs", 1)
|
|
18
|
+
>>> with global_context:
|
|
19
|
+
... global_context.set("bs", 2)
|
|
20
|
+
... with global_context:
|
|
21
|
+
... global_context.set("bs", 3)
|
|
22
|
+
... assert global_context.get("bs") == 3
|
|
23
|
+
... assert global_context.get("bs") == 2
|
|
24
|
+
>>> assert global_context.get("bs") == 1
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self):
|
|
28
|
+
"""Initialize the global context."""
|
|
29
|
+
self._data_stack = [{}] # Stack to support nested contexts
|
|
30
|
+
|
|
31
|
+
def __enter__(self):
|
|
32
|
+
"""Enter a new context."""
|
|
33
|
+
self._data_stack.append(self._data_stack[-1].copy()) # Push a copy of the current context
|
|
34
|
+
return self
|
|
35
|
+
|
|
36
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
37
|
+
"""Exit the current context."""
|
|
38
|
+
self._data_stack.pop() # Pop the current context
|
|
39
|
+
return False
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def _current_data(self):
|
|
43
|
+
"""The current context."""
|
|
44
|
+
return self._data_stack[-1]
|
|
45
|
+
|
|
46
|
+
def set(self, key, value):
|
|
47
|
+
"""Set a key-value pair in the current context."""
|
|
48
|
+
self._current_data[key] = value
|
|
49
|
+
|
|
50
|
+
def get(self, key, default=None):
|
|
51
|
+
"""Get a value from the current context."""
|
|
52
|
+
for data in reversed(self._data_stack):
|
|
53
|
+
if key in data:
|
|
54
|
+
return data[key]
|
|
55
|
+
return default
|
|
56
|
+
|
|
57
|
+
def __getitem__(self, key):
|
|
58
|
+
"""Get a value from the current context."""
|
|
59
|
+
for data in reversed(self._data_stack):
|
|
60
|
+
if key in data:
|
|
61
|
+
return data[key]
|
|
62
|
+
raise KeyError(key)
|
|
63
|
+
|
|
64
|
+
def __setitem__(self, key, value):
|
|
65
|
+
"""Set a key-value pair in the current context."""
|
|
66
|
+
self._current_data[key] = value
|
|
67
|
+
|
|
68
|
+
def clear(self):
|
|
69
|
+
"""Clear the current context."""
|
|
70
|
+
self._data_stack = [{}]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
global_context = GlobalContext()
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
2
|
+
# Copyright (c) 2026 Intel Corporation
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
# NOTE: This file has been modified by Intel Corporation.
|
|
5
|
+
"""Torch tuning module."""
|
|
6
|
+
|
|
7
|
+
# configuring some variables before importing other modules
|
|
8
|
+
from torch_tweak.torch.config import torch_tweak_cache_dir, config # noqa: I001
|
|
9
|
+
|
|
10
|
+
from torch_tweak.torch.checkpoint.local_torch_storage import LocalTorchStorage
|
|
11
|
+
from torch_tweak.torch.dataloader import DataLoaderFactory
|
|
12
|
+
from torch_tweak.torch.inspecting import inspect, wrap
|
|
13
|
+
from torch_tweak.torch.module import Module
|
|
14
|
+
from torch_tweak.torch.tune_strategy import (
|
|
15
|
+
FirstWinsStrategy,
|
|
16
|
+
HighestThroughputStrategy,
|
|
17
|
+
OneBackendStrategy,
|
|
18
|
+
TuneStrategy,
|
|
19
|
+
)
|
|
20
|
+
from torch_tweak.torch.tuning import load, save, tune
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"torch_tweak_cache_dir",
|
|
24
|
+
"config",
|
|
25
|
+
"inspect",
|
|
26
|
+
"wrap",
|
|
27
|
+
"tune",
|
|
28
|
+
"load",
|
|
29
|
+
"save",
|
|
30
|
+
"Module",
|
|
31
|
+
"TuneStrategy",
|
|
32
|
+
"OneBackendStrategy",
|
|
33
|
+
"FirstWinsStrategy",
|
|
34
|
+
"HighestThroughputStrategy",
|
|
35
|
+
"LocalTorchStorage",
|
|
36
|
+
"DataLoaderFactory",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
if config.enable_hf_integrations:
|
|
40
|
+
import torch_tweak.torch.integrations.hugging_face # noqa: F401
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
2
|
+
# Copyright (c) 2026 Intel Corporation
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
#
|
|
5
|
+
# NOTE: This file has been modified by Intel Corporation.
|
|
6
|
+
"""Torch backend module."""
|
|
7
|
+
|
|
8
|
+
from torch_tweak.torch.backend.backend import Backend
|
|
9
|
+
from torch_tweak.torch.backend.openvino import OpenVINOBackend, OpenVINOBackendConfig
|
|
10
|
+
from torch_tweak.torch.backend.torch_eager import TorchEagerBackend, TorchEagerBackendConfig
|
|
11
|
+
from torch_tweak.torch.backend.torch_inductor_backend import TorchInductorBackend, TorchInductorBackendConfig
|
|
12
|
+
from torch_tweak.torch.backend.torchao_backend import TorchAOBackend, TorchAOBackendConfig
|
|
13
|
+
from torch_tweak.torch.backend.xpu_graph_backend import XPUGraphBackend, XPUGraphBackendConfig
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Backend",
|
|
17
|
+
"OpenVINOBackend",
|
|
18
|
+
"OpenVINOBackendConfig",
|
|
19
|
+
"TorchInductorBackend",
|
|
20
|
+
"TorchInductorBackendConfig",
|
|
21
|
+
"TorchAOBackend",
|
|
22
|
+
"TorchAOBackendConfig",
|
|
23
|
+
"TorchEagerBackend",
|
|
24
|
+
"TorchEagerBackendConfig",
|
|
25
|
+
"XPUGraphBackend",
|
|
26
|
+
"XPUGraphBackendConfig",
|
|
27
|
+
]
|
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
2
|
+
# Copyright (c) 2026 Intel Corporation
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
#
|
|
5
|
+
# NOTE: This file has been modified by Intel Corporation.
|
|
6
|
+
"""Backend interface."""
|
|
7
|
+
|
|
8
|
+
import gc
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
from abc import ABC, abstractmethod
|
|
12
|
+
from dataclasses import asdict, dataclass, fields, is_dataclass
|
|
13
|
+
from enum import Enum
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, ClassVar
|
|
16
|
+
|
|
17
|
+
import torch
|
|
18
|
+
import torch.nn as nn
|
|
19
|
+
|
|
20
|
+
from torch_tweak.torch.checkpoint.storage_tasks import is_weights_only_safe
|
|
21
|
+
from torch_tweak.torch.module.graph_spec import GraphSpec
|
|
22
|
+
from torch_tweak.torch.module.recording_module import Sample
|
|
23
|
+
from torch_tweak.utils.hashing import hash_string
|
|
24
|
+
from torch_tweak.utils.permissions import secure_file
|
|
25
|
+
from torch_tweak.utils.trace import annotate
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def samples_for_checkpoint(data: list[Sample] | None) -> list[Sample] | None:
|
|
31
|
+
"""The samples of `data` that a checkpoint can hold.
|
|
32
|
+
|
|
33
|
+
For backends that replay samples only to compile ahead of the first call. A sample holding an
|
|
34
|
+
object such as a transformers `DynamicCache` is left out, and the first call compiles instead.
|
|
35
|
+
"""
|
|
36
|
+
if data is None:
|
|
37
|
+
return None
|
|
38
|
+
safe = [sample for sample in data if is_weights_only_safe(sample)]
|
|
39
|
+
if len(safe) < len(data):
|
|
40
|
+
logger.info(
|
|
41
|
+
"%d of %d samples cannot be saved and are left out of the checkpoint.", len(data) - len(safe), len(data)
|
|
42
|
+
)
|
|
43
|
+
return safe
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class BackendState(Enum):
|
|
47
|
+
"""Enum representing the state of a backend.
|
|
48
|
+
|
|
49
|
+
Attributes:
|
|
50
|
+
INIT: The backend is initialized, there was no tuning done yet.
|
|
51
|
+
INACTIVE: The model was tuned but the backend is deactivated, you can't do inference
|
|
52
|
+
ACTIVE: The model was tuned and the backend is activated, you can do inference
|
|
53
|
+
CHECKPOINT_LOADED: The backend was loaded from a checkpoint, it is ready to be deployed
|
|
54
|
+
DEPLOYED: The model was tuned and is ready to use, you can do inference.
|
|
55
|
+
|
|
56
|
+
State transitions:
|
|
57
|
+
```mermaid
|
|
58
|
+
stateDiagram
|
|
59
|
+
[*] --> init
|
|
60
|
+
init --> active: When backend is built successfully
|
|
61
|
+
active --> inactive: When backend is deactivated
|
|
62
|
+
inactive --> active: When backend is activated again
|
|
63
|
+
checkpoint_loaded --> deployed: When backend is deployed from checkpoint
|
|
64
|
+
checkpoint_loaded --> active: When backend is activated from checkpoint
|
|
65
|
+
active --> deployed: When backend is deployed after being active
|
|
66
|
+
deployed --> [*]
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Note:
|
|
70
|
+
- Changing state to deployed should be done in `ModuleWrapper` as it does a proxy of `forward` method and reverses
|
|
71
|
+
that in order to deploy backends that compile during activation.
|
|
72
|
+
- After loading a checkpoint you can still activate the backend while debugging, but some backends
|
|
73
|
+
compile their implementation again on activation.
|
|
74
|
+
|
|
75
|
+
This abstract class has public interface methods which manage state of the backend:
|
|
76
|
+
build(): Builds backend, changes state to ACTIVE
|
|
77
|
+
activate(): Activates backend, changes state to ACTIVE
|
|
78
|
+
deactivate(): Deactivates backend, changes state to INACTIVE
|
|
79
|
+
deploy(): Deploys backend, changes state to DEPLOYED
|
|
80
|
+
|
|
81
|
+
Each method calls corresponding private method which should not change state differently - with one exception:
|
|
82
|
+
_build should set state to ACTIVE after building the backend. This is to ensure that rest of the system
|
|
83
|
+
can use the backend in ACTIVE state and prevents unnecessary backend compilation.
|
|
84
|
+
|
|
85
|
+
Each backend implementation should implement public methods:
|
|
86
|
+
to_dict(): Returns the state_dict of the backend
|
|
87
|
+
from_dict(): Creates a backend from a state_dict
|
|
88
|
+
|
|
89
|
+
and private ones:
|
|
90
|
+
_build(): Builds backend, changes state to ACTIVE
|
|
91
|
+
_activate(): Activates backend, changes state to ACTIVE
|
|
92
|
+
_deactivate(): Deactivates backend, changes state to INACTIVE
|
|
93
|
+
_deploy(): Deploys backend, changes state to DEPLOYED
|
|
94
|
+
_infer(): Runs inference with the given arguments
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
INIT = "init"
|
|
98
|
+
INACTIVE = "inactive"
|
|
99
|
+
ACTIVE = "active"
|
|
100
|
+
CHECKPOINT_LOADED = "checkpoint_loaded"
|
|
101
|
+
DEPLOYED = "deployed"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass
|
|
105
|
+
class BackendConfig:
|
|
106
|
+
"""Configuration for a backend."""
|
|
107
|
+
|
|
108
|
+
def key(self) -> str:
|
|
109
|
+
"""Returns the keys of the backend configuration."""
|
|
110
|
+
config_dict = self.to_dict()
|
|
111
|
+
config_dict = self._to_json(config_dict)
|
|
112
|
+
config_dict_str = json.dumps(config_dict)
|
|
113
|
+
key = hash_string(config_dict_str)
|
|
114
|
+
return key
|
|
115
|
+
|
|
116
|
+
def describe(self) -> str:
|
|
117
|
+
"""Describe the backend configuration. Display only changed fields."""
|
|
118
|
+
default = self.__class__()
|
|
119
|
+
changed_fields = self._get_changed_fields(self, default)
|
|
120
|
+
return ",".join(changed_fields)
|
|
121
|
+
|
|
122
|
+
def to_dict(self):
|
|
123
|
+
"""Returns the state_dict of the backend."""
|
|
124
|
+
return asdict(self)
|
|
125
|
+
|
|
126
|
+
def save_to_file(self, path: Path) -> None:
|
|
127
|
+
"""Saves the backend configuration to config.json in the given directory."""
|
|
128
|
+
config_path = path / "config.json"
|
|
129
|
+
config_dict = self._to_json(self.to_dict())
|
|
130
|
+
with open(config_path, "w", encoding="utf-8") as f:
|
|
131
|
+
json.dump(config_dict, f, indent=2)
|
|
132
|
+
secure_file(config_path)
|
|
133
|
+
|
|
134
|
+
def _to_json(self, obj: Any) -> Any:
|
|
135
|
+
"""Convert object to JSON-serializable format.
|
|
136
|
+
|
|
137
|
+
Handles the following types:
|
|
138
|
+
- JSON primitives: int, float, str, bool, None
|
|
139
|
+
- Collections: dict, list, tuple, set
|
|
140
|
+
- Dataclasses: converted to dict
|
|
141
|
+
- Enums: converted to their values
|
|
142
|
+
- Other objects: converted to string representation
|
|
143
|
+
"""
|
|
144
|
+
# Handle None explicitly
|
|
145
|
+
if obj is None:
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
# Handle dataclasses
|
|
149
|
+
if is_dataclass(obj):
|
|
150
|
+
obj = asdict(obj)
|
|
151
|
+
|
|
152
|
+
# Handle dictionaries
|
|
153
|
+
if isinstance(obj, dict):
|
|
154
|
+
return {k: self._to_json(v) for k, v in obj.items()}
|
|
155
|
+
|
|
156
|
+
# Handle sequences (list, tuple, set)
|
|
157
|
+
if isinstance(obj, list | tuple | set):
|
|
158
|
+
return [self._to_json(item) for item in obj]
|
|
159
|
+
|
|
160
|
+
# Handle Enums
|
|
161
|
+
if isinstance(obj, Enum):
|
|
162
|
+
return obj.value
|
|
163
|
+
|
|
164
|
+
# Handle JSON primitives (these are already JSON-serializable)
|
|
165
|
+
if isinstance(obj, int | float | str | bool):
|
|
166
|
+
return obj
|
|
167
|
+
|
|
168
|
+
# Handle other types by converting to string
|
|
169
|
+
return str(obj)
|
|
170
|
+
|
|
171
|
+
def _default_describe_fields(self) -> list[str]:
|
|
172
|
+
"""Returns the default fields to describe."""
|
|
173
|
+
return []
|
|
174
|
+
|
|
175
|
+
def _get_changed_fields(
|
|
176
|
+
self,
|
|
177
|
+
current,
|
|
178
|
+
other,
|
|
179
|
+
exclude: list[str] | None = None,
|
|
180
|
+
include: list[str] | None = None,
|
|
181
|
+
) -> list[str]:
|
|
182
|
+
"""Returns the changed fields of the backend configuration."""
|
|
183
|
+
if exclude is None:
|
|
184
|
+
exclude = []
|
|
185
|
+
if include is None:
|
|
186
|
+
include = self._default_describe_fields()
|
|
187
|
+
|
|
188
|
+
changed_fields = []
|
|
189
|
+
for f in fields(current):
|
|
190
|
+
if (getattr(current, f.name) != getattr(other, f.name) and f.name not in exclude) or f.name in include:
|
|
191
|
+
changed_fields.append(f"{f.name}={getattr(current, f.name)}")
|
|
192
|
+
return changed_fields
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class Backend(ABC):
|
|
196
|
+
"""Backend interface for tuning a module."""
|
|
197
|
+
|
|
198
|
+
# Supported devices types
|
|
199
|
+
_devices: ClassVar[list[str]] = ["cpu", "xpu"]
|
|
200
|
+
# Keep the original module after tuning. False offloads it to the meta device.
|
|
201
|
+
requires_original_module: ClassVar[bool] = False
|
|
202
|
+
|
|
203
|
+
def __init__(self):
|
|
204
|
+
"""Initialize the backend."""
|
|
205
|
+
self.state = BackendState.INIT
|
|
206
|
+
self._device = None
|
|
207
|
+
|
|
208
|
+
def build(
|
|
209
|
+
self,
|
|
210
|
+
module: nn.Module,
|
|
211
|
+
graph_spec: GraphSpec,
|
|
212
|
+
data: list[Sample],
|
|
213
|
+
device: torch.device,
|
|
214
|
+
cache_dir: Path,
|
|
215
|
+
) -> "Backend":
|
|
216
|
+
"""Build the model with the given arguments.
|
|
217
|
+
|
|
218
|
+
Building a backend should be idempotent i.e. do not cause side effects. A model is not necessarily pure
|
|
219
|
+
functional and can have an internal state (like kv cache for LLMs). That is why build can call a sample of
|
|
220
|
+
inputs at most once so that subsequent calls have exact same state as the first call for the given sample.
|
|
221
|
+
|
|
222
|
+
After building, the backend should be activated.
|
|
223
|
+
"""
|
|
224
|
+
if self.state == BackendState.INIT:
|
|
225
|
+
try:
|
|
226
|
+
self._assert_device(device)
|
|
227
|
+
self._set_device(device)
|
|
228
|
+
if not data:
|
|
229
|
+
raise RuntimeError(f"Backend {self.name} needs at least one sample")
|
|
230
|
+
ready_backend = self._build(module, graph_spec, data, cache_dir)
|
|
231
|
+
self.state = BackendState.ACTIVE
|
|
232
|
+
return ready_backend
|
|
233
|
+
except Exception as e:
|
|
234
|
+
self._logger.error("Failed to build backend(%s): %s", self.__class__.__name__, e, exc_info=True)
|
|
235
|
+
raise e
|
|
236
|
+
else:
|
|
237
|
+
raise RuntimeError(f"Backend {self.name} build should be called only once")
|
|
238
|
+
|
|
239
|
+
@annotate(domain="Torch Tweak")
|
|
240
|
+
def activate(self):
|
|
241
|
+
"""Activates backend.
|
|
242
|
+
|
|
243
|
+
After activating, the backend should be ready to do inference.
|
|
244
|
+
"""
|
|
245
|
+
if self.state == BackendState.INIT:
|
|
246
|
+
raise RuntimeError(f"Cannot activate backend {self.name}, backend should be built first")
|
|
247
|
+
if self.state == BackendState.DEPLOYED:
|
|
248
|
+
raise RuntimeError(f"Cannot activate backend {self.name}, backend is already deployed")
|
|
249
|
+
|
|
250
|
+
if self.state == BackendState.INACTIVE or self.state == BackendState.CHECKPOINT_LOADED:
|
|
251
|
+
self._activate()
|
|
252
|
+
self.state = BackendState.ACTIVE
|
|
253
|
+
|
|
254
|
+
def deactivate(self):
|
|
255
|
+
"""Deactivates backend.
|
|
256
|
+
|
|
257
|
+
After deactivating, the backend cannot be used to do inference.
|
|
258
|
+
"""
|
|
259
|
+
if self.state == BackendState.INIT:
|
|
260
|
+
raise RuntimeError(f"Cannot deactivate backend {self.name}, backend should be built first")
|
|
261
|
+
if self.state == BackendState.DEPLOYED:
|
|
262
|
+
raise RuntimeError(f"Cannot deactivate backend {self.name}, backend is already deployed")
|
|
263
|
+
if self.state == BackendState.CHECKPOINT_LOADED:
|
|
264
|
+
raise RuntimeError(f"Cannot deactivate backend {self.name}, backend has already been deployed")
|
|
265
|
+
|
|
266
|
+
if self.state == BackendState.ACTIVE:
|
|
267
|
+
self._deactivate()
|
|
268
|
+
self._clean_memory()
|
|
269
|
+
self.state = BackendState.INACTIVE
|
|
270
|
+
|
|
271
|
+
def deploy(self, device: torch.device | None):
|
|
272
|
+
"""Deploys the backend.
|
|
273
|
+
|
|
274
|
+
After deploying, the backend is ready to do inference. Backend cannot be deactivated anymore.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
device: The device to deploy the backend on.
|
|
278
|
+
"""
|
|
279
|
+
if self.state != BackendState.CHECKPOINT_LOADED:
|
|
280
|
+
raise RuntimeError(f"Cannot deploy backend {self.name}, backend should be loaded from a checkpoint")
|
|
281
|
+
|
|
282
|
+
self._set_device(device)
|
|
283
|
+
self._deploy()
|
|
284
|
+
self.state = BackendState.DEPLOYED
|
|
285
|
+
|
|
286
|
+
def infer(self, *args: Any, **kwargs: Any) -> Any:
|
|
287
|
+
"""Run inference with the given arguments.
|
|
288
|
+
|
|
289
|
+
Args:
|
|
290
|
+
args: Variable length argument list.
|
|
291
|
+
kwargs: Arbitrary keyword arguments.
|
|
292
|
+
|
|
293
|
+
Returns:
|
|
294
|
+
Any: The result of the inference.
|
|
295
|
+
"""
|
|
296
|
+
if self.state != BackendState.ACTIVE and self.state != BackendState.DEPLOYED:
|
|
297
|
+
raise RuntimeError(f"Cannot run inference, backend {self.name} should be activated first")
|
|
298
|
+
|
|
299
|
+
return self._infer(*args, **kwargs)
|
|
300
|
+
|
|
301
|
+
@abstractmethod
|
|
302
|
+
def key(self) -> str:
|
|
303
|
+
"""Returns the key of the backend."""
|
|
304
|
+
pass
|
|
305
|
+
|
|
306
|
+
@abstractmethod
|
|
307
|
+
def describe(self) -> str:
|
|
308
|
+
"""Returns the description of the backend."""
|
|
309
|
+
pass
|
|
310
|
+
|
|
311
|
+
@abstractmethod
|
|
312
|
+
def to_dict(self):
|
|
313
|
+
"""Returns the state_dict of the backend.
|
|
314
|
+
|
|
315
|
+
Note: if there any binary artifacts (files) which should be stored by a backend,
|
|
316
|
+
they must be passed as Python Path object. Such objects will be bundled with a checkpoint.
|
|
317
|
+
"""
|
|
318
|
+
pass
|
|
319
|
+
|
|
320
|
+
@classmethod
|
|
321
|
+
@abstractmethod
|
|
322
|
+
def from_dict(cls, state_dict: dict):
|
|
323
|
+
"""Creates a backend from a state_dict."""
|
|
324
|
+
pass
|
|
325
|
+
|
|
326
|
+
@property
|
|
327
|
+
def name(self) -> str:
|
|
328
|
+
"""Name of a backend."""
|
|
329
|
+
return self.__class__.__name__
|
|
330
|
+
|
|
331
|
+
@property
|
|
332
|
+
def device(self) -> torch.device:
|
|
333
|
+
"""The device of the backend.
|
|
334
|
+
|
|
335
|
+
Returns:
|
|
336
|
+
The device the module is using.
|
|
337
|
+
"""
|
|
338
|
+
return self._device
|
|
339
|
+
|
|
340
|
+
@property
|
|
341
|
+
def is_active(self) -> bool:
|
|
342
|
+
"""True if the backend is active."""
|
|
343
|
+
return self.state == BackendState.ACTIVE
|
|
344
|
+
|
|
345
|
+
@abstractmethod
|
|
346
|
+
def _build(self, module: nn.Module, graph_spec: GraphSpec, data: list[Sample], cache_dir: Path) -> "Backend":
|
|
347
|
+
"""Build the model with the given arguments.
|
|
348
|
+
|
|
349
|
+
After building, the backend should be activated.
|
|
350
|
+
|
|
351
|
+
Args:
|
|
352
|
+
module: The module to build the backend on.
|
|
353
|
+
name: The name of the backend.
|
|
354
|
+
graph_spec: The graph specification of the backend.
|
|
355
|
+
data: The data to build the backend on.
|
|
356
|
+
cache_dir: The cache directory to store the backend artifacts.
|
|
357
|
+
"""
|
|
358
|
+
pass
|
|
359
|
+
|
|
360
|
+
@abstractmethod
|
|
361
|
+
def _activate(self):
|
|
362
|
+
"""Activates backend.
|
|
363
|
+
|
|
364
|
+
After activating, the backend should be ready to do inference.
|
|
365
|
+
"""
|
|
366
|
+
pass
|
|
367
|
+
|
|
368
|
+
@abstractmethod
|
|
369
|
+
def _deactivate(self):
|
|
370
|
+
"""Deactivates backend.
|
|
371
|
+
|
|
372
|
+
After deactivating, the backend cannot be used to do inference.
|
|
373
|
+
"""
|
|
374
|
+
pass
|
|
375
|
+
|
|
376
|
+
@abstractmethod
|
|
377
|
+
def _deploy(self):
|
|
378
|
+
"""Deploys the backend.
|
|
379
|
+
|
|
380
|
+
After deploying, the backend is ready to do inference. Backend cannot be deactivated anymore.
|
|
381
|
+
"""
|
|
382
|
+
pass
|
|
383
|
+
|
|
384
|
+
@abstractmethod
|
|
385
|
+
def _infer(self, *args, **kwargs):
|
|
386
|
+
"""Run inference with the given arguments.
|
|
387
|
+
|
|
388
|
+
Args:
|
|
389
|
+
*args: Variable length argument list.
|
|
390
|
+
**kwargs: Arbitrary keyword arguments.
|
|
391
|
+
|
|
392
|
+
Returns:
|
|
393
|
+
Any: The result of the inference.
|
|
394
|
+
"""
|
|
395
|
+
pass
|
|
396
|
+
|
|
397
|
+
def _assert_device(self, device: torch.device):
|
|
398
|
+
"""Assert the device of the backend.
|
|
399
|
+
|
|
400
|
+
Args:
|
|
401
|
+
device: The device to assert.
|
|
402
|
+
"""
|
|
403
|
+
if device.type not in self._devices:
|
|
404
|
+
raise ValueError(f"Device {device.type} is not supported by the backend {self.name}")
|
|
405
|
+
|
|
406
|
+
def _set_device(self, device: torch.device):
|
|
407
|
+
"""Set the device of the backend.
|
|
408
|
+
|
|
409
|
+
Args:
|
|
410
|
+
device: The device to set the backend on.
|
|
411
|
+
"""
|
|
412
|
+
if device is not None:
|
|
413
|
+
self._device = device
|
|
414
|
+
|
|
415
|
+
if self._device is None:
|
|
416
|
+
raise ValueError("Device is not set. Please set the device before deploying.")
|
|
417
|
+
|
|
418
|
+
@property
|
|
419
|
+
def _logger(self) -> logging.Logger:
|
|
420
|
+
"""A logger specific to this backend implementation."""
|
|
421
|
+
return logging.getLogger(f"{self.__class__.__module__}")
|
|
422
|
+
|
|
423
|
+
def _clean_memory(self):
|
|
424
|
+
"""Clean up memory."""
|
|
425
|
+
torch._dynamo.reset()
|
|
426
|
+
torch.compiler.reset()
|
|
427
|
+
xpu = getattr(torch, "xpu", None)
|
|
428
|
+
if xpu is not None and hasattr(xpu, "empty_cache") and xpu.is_available():
|
|
429
|
+
xpu.empty_cache()
|
|
430
|
+
gc.collect()
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
class DummyBackend(Backend):
|
|
434
|
+
"""Dummy backend for testing purposes."""
|
|
435
|
+
|
|
436
|
+
_devices = ["cpu", "xpu"]
|
|
437
|
+
|
|
438
|
+
def key(self) -> str:
|
|
439
|
+
"""Returns the key of the backend."""
|
|
440
|
+
return f"{self.__class__.__name__}"
|
|
441
|
+
|
|
442
|
+
def describe(self) -> str:
|
|
443
|
+
"""Returns the description of the backend."""
|
|
444
|
+
return "Dummy backend"
|
|
445
|
+
|
|
446
|
+
def _build(self, module: nn.Module, graph_spec: GraphSpec, data: list[Sample], cache_dir: Path) -> Backend:
|
|
447
|
+
"""Build the model with the given arguments."""
|
|
448
|
+
return self
|
|
449
|
+
|
|
450
|
+
def _activate(self):
|
|
451
|
+
"""Activate the backend."""
|
|
452
|
+
print("Activating backend") # noqa: T201
|
|
453
|
+
|
|
454
|
+
def infer(self, *args, **kwargs):
|
|
455
|
+
"""Run inference with the given arguments."""
|
|
456
|
+
print("Running inference") # noqa: T201
|
|
457
|
+
|
|
458
|
+
def _deactivate(self):
|
|
459
|
+
"""Deactivate the backend."""
|
|
460
|
+
print("Deactivating backend") # noqa: T201
|
|
461
|
+
|
|
462
|
+
def _deploy(self):
|
|
463
|
+
"""Deploy the backend."""
|
|
464
|
+
print("Deploying backend") # noqa: T201
|
|
465
|
+
|
|
466
|
+
def _infer(self, *args, **kwargs):
|
|
467
|
+
"""Run inference with the given arguments."""
|
|
468
|
+
print("Running inference with args: ", args, "and kwargs: ", kwargs) # noqa: T201
|
|
469
|
+
|
|
470
|
+
def to_dict(self):
|
|
471
|
+
"""Returns the state_dict of the backend."""
|
|
472
|
+
return {}
|
|
473
|
+
|
|
474
|
+
@classmethod
|
|
475
|
+
def from_dict(cls, state_dict: dict):
|
|
476
|
+
"""Creates a backend from a state_dict."""
|
|
477
|
+
return cls()
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Copyright (c) 2026 Intel Corporation
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""OpenVINO backend components."""
|
|
4
|
+
|
|
5
|
+
from torch_tweak.torch.backend.openvino.openvino_backend import OpenVINOBackend, OpenVINOBackendConfig
|
|
6
|
+
from torch_tweak.torch.backend.openvino.ov_model_converter import OpenVINOModelConverter
|
|
7
|
+
|
|
8
|
+
__all__ = ["OpenVINOModelConverter", "OpenVINOBackend", "OpenVINOBackendConfig"]
|