forked from EvolvingLMMs-Lab/lmms-eval
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregistry_v2.py
More file actions
275 lines (222 loc) · 9.19 KB
/
registry_v2.py
File metadata and controls
275 lines (222 loc) · 9.19 KB
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
267
268
269
270
271
272
273
274
275
from __future__ import annotations
import importlib
from dataclasses import dataclass
from importlib.metadata import entry_points
from typing import Iterable, Literal
ModelType = Literal["simple", "chat"]
@dataclass(frozen=True)
class ModelManifest:
"""Declarative model registration payload for model loading.
A single manifest can expose a chat implementation, a simple implementation,
or both for the same `model_id`.
"""
model_id: str
simple_class_path: str | None = None
chat_class_path: str | None = None
aliases: tuple[str, ...] = ()
def __post_init__(self) -> None:
if self.simple_class_path is None and self.chat_class_path is None:
raise ValueError(
f"ModelManifest('{self.model_id}') requires at least one class path",
)
normalized_aliases = tuple(alias for alias in dict.fromkeys(self.aliases) if alias and alias != self.model_id)
object.__setattr__(self, "aliases", normalized_aliases)
@dataclass(frozen=True)
class ResolvedModel:
"""Resolution result for one requested model name."""
requested_name: str
model_id: str
model_type: ModelType
class_path: str
@property
def class_name(self) -> str:
return self.class_path.rsplit(".", 1)[-1]
class ModelRegistryV2:
"""Canonical model registry with aliasing and typed resolution semantics."""
def __init__(self) -> None:
self.clear()
def clear(self) -> None:
self._manifests: dict[str, ModelManifest] = {}
self._alias_to_model_id: dict[str, str] = {}
def register_manifest(
self,
manifest: ModelManifest,
*,
overwrite: bool = False,
) -> None:
"""Register a manifest and all aliases.
When `overwrite=False`, conflicting class paths for an existing model id
raise `ValueError`.
"""
merged = self._merge_manifest(self._manifests.get(manifest.model_id), manifest, overwrite=overwrite)
self._manifests[manifest.model_id] = merged
names = (merged.model_id, *merged.aliases)
for name in names:
existing = self._alias_to_model_id.get(name)
if existing and existing != merged.model_id and not overwrite:
raise ValueError(
f"Alias '{name}' already points to '{existing}', cannot remap to '{merged.model_id}'",
)
self._alias_to_model_id[name] = merged.model_id
def resolve(self, model_name: str, force_simple: bool = False) -> ResolvedModel:
"""Resolve a model name to one concrete implementation class path."""
model_id = self._require_model_id(model_name)
manifest = self._manifests[model_id]
if force_simple and manifest.simple_class_path is not None:
model_type = "simple"
class_path = manifest.simple_class_path
elif manifest.chat_class_path is not None:
model_type = "chat"
class_path = manifest.chat_class_path
else:
assert manifest.simple_class_path is not None
model_type = "simple"
class_path = manifest.simple_class_path
return ResolvedModel(
requested_name=model_name,
model_id=model_id,
model_type=model_type,
class_path=class_path,
)
def get_model_class(self, model_name: str, force_simple: bool = False):
"""Resolve, import, and validate a model class.
Validates that the loaded class is a subclass of ``lmms`` and that its
``is_simple`` flag is consistent with the resolved model type.
"""
resolved = self.resolve(model_name, force_simple=force_simple)
module_name, cls_name = resolved.class_path.rsplit(".", 1)
module = importlib.import_module(module_name)
cls = getattr(module, cls_name)
self._validate_model_class(cls, resolved)
return cls
@staticmethod
def _validate_model_class(cls: type, resolved: ResolvedModel) -> None:
from lmms_eval.api.model import lmms
if not (isinstance(cls, type) and issubclass(cls, lmms)):
raise TypeError(
f"Model class '{resolved.class_path}' is not a subclass of lmms",
)
cls_is_simple = getattr(cls, "is_simple", True)
if resolved.model_type == "chat" and cls_is_simple:
raise TypeError(
f"Model '{resolved.model_id}' resolved as chat but " f"{cls.__name__}.is_simple is True. " f"Set is_simple = False on the class.",
)
if resolved.model_type == "simple" and not cls_is_simple:
raise TypeError(
f"Model '{resolved.model_id}' resolved as simple but " f"{cls.__name__}.is_simple is False. " f"Set is_simple = True or register a chat_class_path.",
)
def load_entrypoint_manifests(
self,
group: str = "lmms_eval.models",
*,
overwrite: bool = False,
) -> None:
"""Load model manifests from Python entry points.
Supported payloads per entry point:
- `ModelManifest`
- `Iterable[ModelManifest]`
- `Callable[[], ModelManifest | Iterable[ModelManifest]]`
"""
selected = self._select_entry_points(group)
for ep in selected:
payload = ep.load()
manifests = self._coerce_payload_to_manifests(payload)
for manifest in manifests:
self.register_manifest(manifest, overwrite=overwrite)
def list_model_names(self) -> list[str]:
"""Return all known requestable model names (ids + aliases)."""
return sorted(self._alias_to_model_id)
def list_canonical_model_ids(self) -> list[str]:
"""Return canonical model ids."""
return sorted(self._manifests)
def get_manifest(self, model_name: str) -> ModelManifest:
"""Return canonical manifest for a model id or alias."""
model_id = self._require_model_id(model_name)
return self._manifests[model_id]
def _require_model_id(self, model_name: str) -> str:
model_id = self._alias_to_model_id.get(model_name)
if model_id is not None:
return model_id
available = ", ".join(self.list_model_names())
raise ValueError(
f"Model '{model_name}' not found in available models: {available}",
)
def _merge_manifest(
self,
current: ModelManifest | None,
incoming: ModelManifest,
*,
overwrite: bool,
) -> ModelManifest:
if current is None:
return incoming
simple_class_path = self._merge_class_path(
current.simple_class_path,
incoming.simple_class_path,
overwrite=overwrite,
field_name="simple_class_path",
model_id=incoming.model_id,
)
chat_class_path = self._merge_class_path(
current.chat_class_path,
incoming.chat_class_path,
overwrite=overwrite,
field_name="chat_class_path",
model_id=incoming.model_id,
)
aliases = tuple(dict.fromkeys((*current.aliases, *incoming.aliases)))
return ModelManifest(
model_id=incoming.model_id,
simple_class_path=simple_class_path,
chat_class_path=chat_class_path,
aliases=aliases,
)
def _merge_class_path(
self,
current_value: str | None,
incoming_value: str | None,
*,
overwrite: bool,
field_name: str,
model_id: str,
) -> str | None:
if incoming_value is None:
return current_value
if current_value is None:
return incoming_value
if current_value == incoming_value:
return current_value
if overwrite:
return incoming_value
raise ValueError(
f"Conflicting {field_name} for model '{model_id}': " f"'{current_value}' vs '{incoming_value}'",
)
def _coerce_payload_to_manifests(self, payload) -> list[ModelManifest]:
if callable(payload):
payload = payload()
if isinstance(payload, ModelManifest):
return [payload]
if isinstance(payload, Iterable) and not isinstance(payload, (str, bytes, dict)):
return self._coerce_manifest_iterable(payload)
raise TypeError(
"Entry point payload must be ModelManifest, iterable of ModelManifest, " "or callable returning one of those",
)
@staticmethod
def _coerce_manifest_iterable(payload: Iterable[object]) -> list[ModelManifest]:
manifests: list[ModelManifest] = []
for item in payload:
if not isinstance(item, ModelManifest):
raise TypeError(
"Entry point iterable must contain only ModelManifest objects",
)
manifests.append(item)
return manifests
def _select_entry_points(self, group: str):
eps = entry_points()
if hasattr(eps, "select"):
return list(eps.select(group=group))
if isinstance(eps, dict):
legacy_group = eps.get(group, [])
if isinstance(legacy_group, Iterable):
return list(legacy_group)
return []