-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathconfig.py
266 lines (217 loc) · 8.96 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD 3-Clause license found in the
# LICENSE file in the root directory of this source tree.
import abc
import dataclasses
import enum
import importlib
import json
from typing import Any, ClassVar, Dict
import torch
class AOBaseConfig(abc.ABC):
"""
If a workflow config inherits from this then `quantize_` knows
how to a apply it to a model. For example::
# user facing code
class WorkflowFooConfig(AOBaseConfig): ...
# configuration for workflow `Foo` is defined here
bar = 'baz'
# non user facing code
@register_quantize_module_handler(WorkflowFooConfig)
def _transform(
mod: torch.nn.Module,
config: WorkflowFooConfig,
) -> torch.nn.Module:
# the transform is implemented here, usually a tensor sublass
# weight swap or a module swap
...
# then, the user calls `quantize_` with a config, and `_transform` is called
# under the hood by `quantize_.
"""
# Base Version of a config
VERSION: ClassVar[int] = 1
class VersionMismatchError(Exception):
"""Raised when trying to deserialize a config with a different version"""
def __init__(self, type_path, stored_version, current_version):
self.type_path = type_path
self.stored_version = stored_version
self.current_version = current_version
message = (
f"Version mismatch for {type_path}: "
f"stored version {stored_version} != current version {current_version}"
)
super().__init__(message)
class ConfigJSONEncoder(json.JSONEncoder):
"""Custom JSON encoder for AOBaseConfig objects"""
def default(self, o):
# Handle AOBaseConfig subclasses first (most specific case)
if isinstance(o, AOBaseConfig):
data_dict = {}
# Process each attribute to handle nested objects
for k, v in o.__dict__.items():
if not k.startswith("_") and k != "VERSION":
# Recursively encode each value (important for nested objects)
data_dict[k] = self.encode_value(v)
return {
# Only store the class name, not the full module path
"_type": o.__class__.__name__,
"_version": getattr(o.__class__, "VERSION", 1),
"_data": data_dict,
}
# Handle NamedTuple types
if hasattr(o, "_fields") and hasattr(
o, "_asdict"
): # Check for NamedTuple characteristics
asdict_data = o._asdict()
# Process each field to handle nested objects
processed_data = {k: self.encode_value(v) for k, v in asdict_data.items()}
return {
"_type": o.__class__.__name__,
"_version": getattr(o.__class__, "VERSION", 1),
"_data": processed_data,
}
# Handle dataclasses
if dataclasses.is_dataclass(o) and not isinstance(o, type):
data_dict = {}
# Process each field to handle nested objects
for f in dataclasses.fields(o):
if f.name != "VERSION":
data_dict[f.name] = self.encode_value(getattr(o, f.name))
return {
# Only store the class name for dataclasses too
"_type": o.__class__.__name__,
"_version": getattr(o.__class__, "VERSION", 1),
"_data": data_dict,
}
# Handle torch.dtype
if hasattr(o, "__module__") and o.__module__ == "torch" and isinstance(o, type):
return {"_type": "torch.dtype", "_data": str(o).split(".")[-1]}
# Handle Layout objects
if hasattr(o, "__class__") and "Layout" in o.__class__.__name__:
return {
"_type": o.__class__.__name__,
"_data": {
k: self.encode_value(v)
for k, v in o.__dict__.items()
if not k.startswith("_")
},
}
# Handle enum values
if isinstance(o, enum.Enum):
# Store the full path for enums to ensure uniqueness
return {"_type": f"{o.__class__.__name__}", "_data": o.name}
if isinstance(o, torch.dtype):
return {"_type": "torch.dtype", "_data": str(o).split(".")[-1]}
# For lists and dictionaries, recursively process their items
if isinstance(o, list):
return [self.encode_value(item) for item in o]
if isinstance(o, dict):
return {k: self.encode_value(v) for k, v in o.items()}
# Default case - let the parent class handle it
return super().default(o)
def encode_value(self, value):
"""Helper method to recursively encode a value"""
# Try to use default for custom type
try:
# This will handle all our special cases and raise TypeError
# if it can't handle the type
result = self.default(value)
return result
except TypeError:
pass
# Default case - return as is
# (This will be processed by standard JSON encoder later)
return value
def config_to_dict(config: AOBaseConfig) -> Dict[str, Any]:
"""
Convert an AOBaseConfig instance to a dictionary suitable for serialization.
Args:
config: An instance of AOBaseConfig subclass
Returns:
Dict representation of the config
"""
if not isinstance(config, AOBaseConfig):
raise TypeError(f"Expected AOBaseConfig instance, got {type(config)}")
# Use the existing JSON encoder but return the dict directly
return json.loads(json.dumps(config, cls=ConfigJSONEncoder))
ALLOWED_AO_MODULES = {
"torchao.quantization",
"torchao.sparsity.sparse_api",
"torchao.prototype.quantization",
"torchao.dtypes",
}
def config_from_dict(data: Dict[str, Any]) -> AOBaseConfig:
"""
Create an AOBaseConfig subclass instance from a dictionary.
Args:
data: Dictionary containing serialized config data
Returns:
An instance of the appropriate AOBaseConfig subclass
Raises:
VersionMismatchError: If the stored version doesn't match the class version
ValueError: If deserialization fails for other reasons
"""
if not isinstance(data, dict):
raise TypeError(f"Expected dictionary, got {type(data)}")
if "_type" not in data or "_data" not in data:
raise ValueError("Input dictionary missing required '_type' or '_data' fields")
type_path = data["_type"]
stored_version = data.get("_version", 1)
obj_data = data["_data"]
# Handle torch.dtype
if type_path == "torch.dtype":
import torch
return getattr(torch, obj_data)
# Try to find the class in any of the allowed modules
cls = None
for module_path in ALLOWED_AO_MODULES:
try:
module = importlib.import_module(module_path)
cls = getattr(module, type_path)
break # Found the class, exit the loop
except (ImportError, AttributeError):
continue # Try the next module
# If we couldn't find the class in any allowed module, raise an error
if cls is None:
allowed_modules_str = ", ".join(ALLOWED_AO_MODULES)
raise ValueError(
f"Failed to find class {type_path} in any of the allowed modules: {allowed_modules_str}"
)
# Check version - require exact match
current_version = getattr(cls, "VERSION", 1)
if stored_version != current_version:
raise VersionMismatchError(type_path, stored_version, current_version)
# Handle the case where obj_data is not a dictionary
if not isinstance(obj_data, dict):
if issubclass(cls, enum.Enum):
# For enums, convert string to enum value
return getattr(cls, obj_data)
else:
# For other primitive types, create an instance with the value
try:
return cls(obj_data)
except:
return obj_data
# Process nested structures for dictionary obj_data
processed_data = {}
for key, value in obj_data.items():
if isinstance(value, dict) and "_type" in value and "_data" in value:
# Recursively handle nested configs
processed_data[key] = config_from_dict(value)
elif isinstance(value, list):
# Handle lists of possible configs
processed_data[key] = [
config_from_dict(item)
if isinstance(item, dict) and "_type" in item and "_data" in item
else item
for item in value
]
else:
processed_data[key] = value
# Create and return the instance
try:
return cls(**processed_data)
except Exception as e:
raise ValueError(f"Failed to create instance of {cls.__name__}: {e}")