diffract-core 0.2.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.
- diffract/__init__.py +52 -0
- diffract/configs/fast_speed_without_disk.ini +48 -0
- diffract/configs/hybrid.ini +74 -0
- diffract/configs/sqlite.ini +62 -0
- diffract/containers.py +405 -0
- diffract/core/__init__.py +23 -0
- diffract/core/cache/__init__.py +24 -0
- diffract/core/cache/containers.py +93 -0
- diffract/core/cache/interface.py +117 -0
- diffract/core/cache/redis_manager.py +464 -0
- diffract/core/cache/simple_manager.py +478 -0
- diffract/core/compute/__init__.py +46 -0
- diffract/core/compute/config.py +48 -0
- diffract/core/compute/containers.py +81 -0
- diffract/core/compute/decorator.py +125 -0
- diffract/core/compute/exceptions.py +31 -0
- diffract/core/compute/execution/__init__.py +14 -0
- diffract/core/compute/execution/_types.py +70 -0
- diffract/core/compute/execution/aggregation.py +74 -0
- diffract/core/compute/execution/aggregation_runner.py +362 -0
- diffract/core/compute/execution/enums.py +38 -0
- diffract/core/compute/execution/executor.py +125 -0
- diffract/core/compute/execution/parameter_runner.py +125 -0
- diffract/core/compute/execution/restrictions.py +61 -0
- diffract/core/compute/execution/strategy.py +118 -0
- diffract/core/compute/execution/utils.py +112 -0
- diffract/core/compute/extensions/__init__.py +0 -0
- diffract/core/compute/extensions/power_law.py +1051 -0
- diffract/core/compute/extensions/rmt.py +150 -0
- diffract/core/compute/extensions/utils.py +36 -0
- diffract/core/compute/field_signature.py +183 -0
- diffract/core/compute/kernels/__init__.py +48 -0
- diffract/core/compute/kernels/alignment.py +106 -0
- diffract/core/compute/kernels/heavy_tailed.py +394 -0
- diffract/core/compute/kernels/marchenko_pastur.py +99 -0
- diffract/core/compute/kernels/mat_decomposition.py +101 -0
- diffract/core/compute/kernels/mat_properties.py +53 -0
- diffract/core/compute/kernels/model_quality.py +27 -0
- diffract/core/compute/kernels/norms.py +88 -0
- diffract/core/compute/kernels/ranks.py +35 -0
- diffract/core/compute/kernels/tracy_widom.py +36 -0
- diffract/core/compute/metadata.py +67 -0
- diffract/core/compute/registry.py +485 -0
- diffract/core/constants.py +147 -0
- diffract/core/data/__init__.py +32 -0
- diffract/core/data/interface.py +304 -0
- diffract/core/data/metadata/__init__.py +15 -0
- diffract/core/data/metadata/containers.py +60 -0
- diffract/core/data/metadata/interface.py +208 -0
- diffract/core/data/metadata/sqlite_index.py +604 -0
- diffract/core/data/nn/__init__.py +43 -0
- diffract/core/data/nn/aggregates/__init__.py +35 -0
- diffract/core/data/nn/aggregates/metadata.py +96 -0
- diffract/core/data/nn/aggregates/proxy.py +57 -0
- diffract/core/data/nn/aggregates/repository.py +87 -0
- diffract/core/data/nn/aggregates/view.py +307 -0
- diffract/core/data/nn/containers.py +86 -0
- diffract/core/data/nn/extractors/__init__.py +49 -0
- diffract/core/data/nn/extractors/base.py +300 -0
- diffract/core/data/nn/extractors/factory.py +234 -0
- diffract/core/data/nn/extractors/flax.py +112 -0
- diffract/core/data/nn/extractors/handlers/__init__.py +39 -0
- diffract/core/data/nn/extractors/handlers/base.py +110 -0
- diffract/core/data/nn/extractors/handlers/flax_handlers.py +71 -0
- diffract/core/data/nn/extractors/handlers/numpy_handlers.py +63 -0
- diffract/core/data/nn/extractors/handlers/onnx_handlers.py +67 -0
- diffract/core/data/nn/extractors/handlers/tensorflow_handlers.py +82 -0
- diffract/core/data/nn/extractors/handlers/torch_handlers.py +124 -0
- diffract/core/data/nn/extractors/interface.py +56 -0
- diffract/core/data/nn/extractors/numpy.py +94 -0
- diffract/core/data/nn/extractors/onnx.py +108 -0
- diffract/core/data/nn/extractors/tensorflow.py +99 -0
- diffract/core/data/nn/extractors/torch.py +204 -0
- diffract/core/data/nn/params/__init__.py +27 -0
- diffract/core/data/nn/params/interface.py +402 -0
- diffract/core/data/nn/params/metadata.py +110 -0
- diffract/core/data/nn/params/proxy.py +93 -0
- diffract/core/data/nn/params/repository.py +45 -0
- diffract/core/data/nn/params/schema.py +82 -0
- diffract/core/data/nn/params/view.py +393 -0
- diffract/core/data/proxy.py +246 -0
- diffract/core/data/repository.py +227 -0
- diffract/core/data/utils.py +33 -0
- diffract/core/data/view.py +389 -0
- diffract/core/export/__init__.py +27 -0
- diffract/core/export/containers.py +47 -0
- diffract/core/export/exporters.py +191 -0
- diffract/core/export/formatters/__init__.py +23 -0
- diffract/core/export/formatters/base.py +68 -0
- diffract/core/export/formatters/dict_formatter.py +38 -0
- diffract/core/export/formatters/json_formatter.py +58 -0
- diffract/core/export/formatters/list_formatter.py +41 -0
- diffract/core/export/formatters/pandas_formatter.py +86 -0
- diffract/core/export/formatters/polars_formatter.py +86 -0
- diffract/core/export/formatters/registry.py +84 -0
- diffract/core/export/interface.py +105 -0
- diffract/core/parallel/__init__.py +21 -0
- diffract/core/parallel/containers.py +57 -0
- diffract/core/parallel/execution.py +91 -0
- diffract/core/parallel/runtime.py +91 -0
- diffract/core/storage/__init__.py +35 -0
- diffract/core/storage/base_manager.py +330 -0
- diffract/core/storage/containers.py +122 -0
- diffract/core/storage/hdf5_manager.py +856 -0
- diffract/core/storage/hybrid_manager.py +218 -0
- diffract/core/storage/interface.py +222 -0
- diffract/core/storage/metadata.py +89 -0
- diffract/core/storage/ram_manager.py +159 -0
- diffract/core/storage/sqlite_manager.py +1062 -0
- diffract/core/storage/zarr_manager.py +992 -0
- diffract/core/utils/__init__.py +45 -0
- diffract/core/utils/build.py +46 -0
- diffract/core/utils/exceptions.py +11 -0
- diffract/core/utils/hashing.py +90 -0
- diffract/core/utils/imports.py +292 -0
- diffract/core/utils/math.py +15 -0
- diffract/py.typed +0 -0
- diffract/session/__init__.py +24 -0
- diffract/session/errors.py +17 -0
- diffract/session/field_cache.py +216 -0
- diffract/session/namespaces/__init__.py +15 -0
- diffract/session/namespaces/compute/__init__.py +219 -0
- diffract/session/namespaces/models/__init__.py +282 -0
- diffract/session/namespaces/models/parameters/__init__.py +133 -0
- diffract/session/namespaces/models/parameters/meta_patcher.py +167 -0
- diffract/session/namespaces/results/__init__.py +378 -0
- diffract/session/namespaces/results/eraser.py +129 -0
- diffract/session/namespaces/results/injester.py +249 -0
- diffract/session/namespaces/utils/__init__.py +141 -0
- diffract/session/namespaces/utils/merger.py +295 -0
- diffract/session/namespaces/viz/__init__.py +91 -0
- diffract/session/namespaces/viz/_utils.py +14 -0
- diffract/session/namespaces/viz/box.py +207 -0
- diffract/session/namespaces/viz/grid.py +160 -0
- diffract/session/namespaces/viz/heatmap.py +164 -0
- diffract/session/namespaces/viz/scatter.py +202 -0
- diffract/session/namespaces/viz/sparkline.py +270 -0
- diffract/session/namespaces/viz/violin.py +212 -0
- diffract/session/session.py +260 -0
- diffract/session/utils.py +81 -0
- diffract/viz/__init__.py +42 -0
- diffract/viz/data/__init__.py +34 -0
- diffract/viz/data/detection.py +57 -0
- diffract/viz/data/extraction.py +117 -0
- diffract/viz/data/filtering.py +57 -0
- diffract/viz/data/ordering.py +129 -0
- diffract/viz/data/provider.py +99 -0
- diffract/viz/data/types.py +98 -0
- diffract/viz/plots/__init__.py +37 -0
- diffract/viz/plots/base/__init__.py +20 -0
- diffract/viz/plots/base/axis.py +219 -0
- diffract/viz/plots/base/coloraxis.py +133 -0
- diffract/viz/plots/base/configurator.py +18 -0
- diffract/viz/plots/base/jitter.py +368 -0
- diffract/viz/plots/base/line.py +197 -0
- diffract/viz/plots/base/marker.py +278 -0
- diffract/viz/plots/base/overlay.py +14 -0
- diffract/viz/plots/base/plot.py +110 -0
- diffract/viz/plots/base/update.py +50 -0
- diffract/viz/plots/boxplot.py +283 -0
- diffract/viz/plots/cluster.py +374 -0
- diffract/viz/plots/heatmap.py +168 -0
- diffract/viz/plots/scatter.py +233 -0
- diffract/viz/plots/sparkline.py +405 -0
- diffract/viz/plots/subplots/__init__.py +32 -0
- diffract/viz/plots/subplots/coloraxis.py +339 -0
- diffract/viz/plots/subplots/factory.py +713 -0
- diffract/viz/plots/subplots/grid.py +214 -0
- diffract/viz/plots/subplots/layout.py +370 -0
- diffract/viz/plots/subplots/spec.py +39 -0
- diffract/viz/plots/violin.py +298 -0
- diffract/viz/renderer.py +513 -0
- diffract/viz/styling/__init__.py +78 -0
- diffract/viz/styling/palettes/__init__.py +20 -0
- diffract/viz/styling/palettes/bundle.py +16 -0
- diffract/viz/styling/palettes/color.py +83 -0
- diffract/viz/styling/palettes/dashes.py +27 -0
- diffract/viz/styling/palettes/symbols.py +42 -0
- diffract/viz/styling/resolvers/__init__.py +11 -0
- diffract/viz/styling/resolvers/categorical.py +68 -0
- diffract/viz/styling/resolvers/color.py +77 -0
- diffract/viz/styling/resolvers/numeric.py +108 -0
- diffract/viz/styling/sources.py +27 -0
- diffract/viz/styling/theme/__init__.py +29 -0
- diffract/viz/styling/theme/applier.py +114 -0
- diffract/viz/styling/theme/components.py +66 -0
- diffract/viz/styling/theme/presets.py +58 -0
- diffract/viz/styling/theme/theme.py +36 -0
- diffract_core-0.2.1.dist-info/METADATA +530 -0
- diffract_core-0.2.1.dist-info/RECORD +193 -0
- diffract_core-0.2.1.dist-info/WHEEL +4 -0
- diffract_core-0.2.1.dist-info/licenses/LICENSE +201 -0
- diffract_core-0.2.1.dist-info/licenses/NOTICE +2 -0
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
"""Parameter repository and view interfaces and protocols.
|
|
2
|
+
|
|
3
|
+
This module defines the core protocols for parameter management in diffract.
|
|
4
|
+
It provides framework-agnostic contracts for two key concepts:
|
|
5
|
+
|
|
6
|
+
1. IParameterRepository: Exclusively owns and manages IStorageManager and ICacheManager
|
|
7
|
+
instances, serving as the single source of truth for persistent parameter data.
|
|
8
|
+
The repository controls the lifecycle of storage and cache resources and acts
|
|
9
|
+
as the entry point for creating parameter views.
|
|
10
|
+
|
|
11
|
+
2. IParameterView: Provides numpy-like views for batch operations on parameters,
|
|
12
|
+
supporting filtering and efficient data access. Views contain methods for data
|
|
13
|
+
operations (prefetching, field management) that work only on parameters within
|
|
14
|
+
the view, similar to numpy array slicing. Views access storage and cache through
|
|
15
|
+
the repository but do not own these resources.
|
|
16
|
+
|
|
17
|
+
The interfaces support rich filtering capabilities by parameter name,
|
|
18
|
+
type, model ID, and custom fields, as well as batch operations for
|
|
19
|
+
efficient parameter management.
|
|
20
|
+
|
|
21
|
+
Example:
|
|
22
|
+
>>> repository: IParameterRepository = get_parameter_repository()
|
|
23
|
+
>>> view: IParameterView = repository.create_view()
|
|
24
|
+
>>> dense_params = view.filter_by_ptype("DENSE")
|
|
25
|
+
>>> dense_params.prefetch_fields(fields=["weights", "gradients"])
|
|
26
|
+
>>> dense_params.erase_fields("temporary_field")
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from typing import (
|
|
32
|
+
TYPE_CHECKING,
|
|
33
|
+
Any,
|
|
34
|
+
Protocol,
|
|
35
|
+
Self,
|
|
36
|
+
TypeVar,
|
|
37
|
+
overload,
|
|
38
|
+
runtime_checkable,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
if TYPE_CHECKING:
|
|
42
|
+
import types
|
|
43
|
+
from collections.abc import Iterable, Iterator, Sequence
|
|
44
|
+
|
|
45
|
+
from diffract.core.cache.interface import ICacheManager
|
|
46
|
+
from diffract.core.data.metadata.interface import IMetadataIndex
|
|
47
|
+
from diffract.core.data.nn.params.schema import (
|
|
48
|
+
FieldName,
|
|
49
|
+
ParameterIndex,
|
|
50
|
+
ParameterType,
|
|
51
|
+
ParameterUID,
|
|
52
|
+
)
|
|
53
|
+
from diffract.core.parallel import ParallelContext
|
|
54
|
+
from diffract.core.storage.interface import IStorageManager
|
|
55
|
+
|
|
56
|
+
T = TypeVar("T")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@runtime_checkable
|
|
60
|
+
class IParameterProxy(Protocol):
|
|
61
|
+
"""Protocol for a proxy object representing a single parameter.
|
|
62
|
+
|
|
63
|
+
This protocol describes how the rest of the system interacts with a single
|
|
64
|
+
parameter (conceptually: a single "row" in storage). Importantly, the proxy
|
|
65
|
+
is a *handle* for interacting with storage-backed data; it should not be
|
|
66
|
+
interpreted as an owner of storage/cache managers.
|
|
67
|
+
|
|
68
|
+
Implementations may internally use storage/cache managers, but the public
|
|
69
|
+
interface is expressed in terms of parameter identity/metadata and field
|
|
70
|
+
operations.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def set_field(self, name: FieldName, value: Any) -> None:
|
|
74
|
+
"""Store a named field for this parameter."""
|
|
75
|
+
...
|
|
76
|
+
|
|
77
|
+
def get_field(
|
|
78
|
+
self, name: FieldName, default: T | None = None, auto_prefetch: bool = True
|
|
79
|
+
) -> Any | T:
|
|
80
|
+
"""Retrieve a named field for this parameter (cache-first)."""
|
|
81
|
+
...
|
|
82
|
+
|
|
83
|
+
def has_field(self, name: FieldName) -> bool:
|
|
84
|
+
"""Return True if the field exists (storage or cache)."""
|
|
85
|
+
...
|
|
86
|
+
|
|
87
|
+
def get_field_metadata(self, name: FieldName) -> dict[str, Any] | None:
|
|
88
|
+
"""Return storage-level metadata for the given field if available."""
|
|
89
|
+
...
|
|
90
|
+
|
|
91
|
+
def is_field_prefetched(self, name: FieldName) -> bool:
|
|
92
|
+
"""Return True if the field is cached for fast access."""
|
|
93
|
+
...
|
|
94
|
+
|
|
95
|
+
def prefetch_field(self, name: FieldName, value: Any) -> None:
|
|
96
|
+
"""Cache a field value for fast access."""
|
|
97
|
+
...
|
|
98
|
+
|
|
99
|
+
def try_prefetch_field(self, name: FieldName) -> bool:
|
|
100
|
+
"""Attempt to prefetch a field into cache; returns False if missing."""
|
|
101
|
+
...
|
|
102
|
+
|
|
103
|
+
def erase_field(self, name: FieldName) -> None:
|
|
104
|
+
"""Remove a field from storage and cache."""
|
|
105
|
+
...
|
|
106
|
+
|
|
107
|
+
def list_fields(self) -> list[FieldName]:
|
|
108
|
+
"""List all field names for this parameter."""
|
|
109
|
+
...
|
|
110
|
+
|
|
111
|
+
def __hash__(self) -> int:
|
|
112
|
+
"""Hash based on parameter identity."""
|
|
113
|
+
...
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@runtime_checkable
|
|
117
|
+
class IParameterRepository(Protocol):
|
|
118
|
+
"""Protocol for a parameter repository owning storage and cache infrastructure.
|
|
119
|
+
|
|
120
|
+
Defines the interface for parameter repositories that exclusively own and manage
|
|
121
|
+
the IStorageManager and ICacheManager instances. The repository is the single
|
|
122
|
+
source of truth for persistent parameter data and acts as the exclusive owner
|
|
123
|
+
of the underlying storage and caching infrastructure.
|
|
124
|
+
|
|
125
|
+
As the owner of storage and cache managers, the repository:
|
|
126
|
+
- Controls the lifecycle of storage and cache resources
|
|
127
|
+
- Ensures data consistency across storage and cache layers
|
|
128
|
+
- Provides access to owned managers via properties
|
|
129
|
+
- Manages repository membership (adding/removing parameters)
|
|
130
|
+
- Provides the foundation for creating parameter views
|
|
131
|
+
- Delegates data operations to views for efficient batch processing
|
|
132
|
+
|
|
133
|
+
Views created by the repository share access to the owned storage and cache
|
|
134
|
+
but do not own these resources themselves. The repository exposes its owned
|
|
135
|
+
managers through properties for introspection and advanced usage.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
@property
|
|
139
|
+
def storage_manager(self) -> IStorageManager:
|
|
140
|
+
"""Storage manager owned by this repository."""
|
|
141
|
+
...
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def metadata_index(self) -> IMetadataIndex:
|
|
145
|
+
"""Metadata index owned by this repository."""
|
|
146
|
+
...
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def cache_manager(self) -> ICacheManager | None:
|
|
150
|
+
"""Cache manager owned by this repository (optional)."""
|
|
151
|
+
...
|
|
152
|
+
|
|
153
|
+
def __enter__(self) -> Self:
|
|
154
|
+
"""Enter a batch write context (delegated to the owned storage manager)."""
|
|
155
|
+
...
|
|
156
|
+
|
|
157
|
+
def __exit__(
|
|
158
|
+
self,
|
|
159
|
+
exc_type: type[BaseException] | None,
|
|
160
|
+
exc_val: BaseException | None,
|
|
161
|
+
exc_tb: types.TracebackType | None,
|
|
162
|
+
) -> None:
|
|
163
|
+
"""Exit the batch write context and flush pending operations."""
|
|
164
|
+
...
|
|
165
|
+
|
|
166
|
+
def __len__(self) -> int:
|
|
167
|
+
"""Return the total number of parameters in the repository.
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
Number of parameters currently stored in the repository.
|
|
171
|
+
"""
|
|
172
|
+
...
|
|
173
|
+
|
|
174
|
+
def __iter__(self) -> Iterator[IParameterProxy]:
|
|
175
|
+
"""Iterate over parameters in the repository.
|
|
176
|
+
|
|
177
|
+
Note:
|
|
178
|
+
Iteration order is implementation-defined.
|
|
179
|
+
"""
|
|
180
|
+
...
|
|
181
|
+
|
|
182
|
+
def __getitem__(self, index: int) -> IParameterProxy:
|
|
183
|
+
"""Get a parameter by index.
|
|
184
|
+
|
|
185
|
+
Note:
|
|
186
|
+
Indexing is provided for quasi list-compatibility; ordering is
|
|
187
|
+
implementation-defined and may not be stable across sessions.
|
|
188
|
+
"""
|
|
189
|
+
...
|
|
190
|
+
|
|
191
|
+
def get_proxy(self, uid: ParameterUID) -> IParameterProxy:
|
|
192
|
+
"""Return a proxy for a parameter uid currently present in the repository."""
|
|
193
|
+
...
|
|
194
|
+
|
|
195
|
+
def append(self, param: IParameterProxy) -> None:
|
|
196
|
+
"""Add a single parameter to the repository (mutates membership)."""
|
|
197
|
+
...
|
|
198
|
+
|
|
199
|
+
def extend(self, params: Iterable[IParameterProxy]) -> None:
|
|
200
|
+
"""Add multiple parameters to the repository (mutates membership)."""
|
|
201
|
+
...
|
|
202
|
+
|
|
203
|
+
def remove_by_uid(self, uid: ParameterUID) -> None:
|
|
204
|
+
"""Remove a parameter from the repository by UID (mutates membership).
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
uid: Unique identifier of the parameter to remove.
|
|
208
|
+
"""
|
|
209
|
+
...
|
|
210
|
+
|
|
211
|
+
def clear(self, erase: bool = False) -> None:
|
|
212
|
+
"""Clear repository membership.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
erase: If True, also erase data from storage and cache.
|
|
216
|
+
"""
|
|
217
|
+
...
|
|
218
|
+
|
|
219
|
+
def create_view(self) -> IParameterView:
|
|
220
|
+
"""Create a parameter view for working with a subset of parameters."""
|
|
221
|
+
...
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@runtime_checkable
|
|
225
|
+
class IParameterView(Protocol):
|
|
226
|
+
"""Protocol for a parameter view with rich filtering and data access.
|
|
227
|
+
|
|
228
|
+
Defines the interface for parameter views that provide efficient batch
|
|
229
|
+
operations and data access for neural network parameters. Views support
|
|
230
|
+
rich filtering by various criteria and provide convenient access to
|
|
231
|
+
parameter data through proxies.
|
|
232
|
+
|
|
233
|
+
This protocol represents a working view of parameters that can be filtered,
|
|
234
|
+
iterated, and manipulated as a collection. It provides access to data operations
|
|
235
|
+
(prefetching, field management) for the parameters within this view only,
|
|
236
|
+
similar to numpy's array views.
|
|
237
|
+
|
|
238
|
+
This protocol is the main interface for parameter data operations. It may be
|
|
239
|
+
extended with new methods over time, but existing methods should remain
|
|
240
|
+
backwards compatible to ensure compatibility across implementations.
|
|
241
|
+
"""
|
|
242
|
+
|
|
243
|
+
def __len__(self) -> int:
|
|
244
|
+
"""Return the number of parameters in this view.
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
Number of parameters in the view.
|
|
248
|
+
"""
|
|
249
|
+
...
|
|
250
|
+
|
|
251
|
+
@overload
|
|
252
|
+
def __getitem__(self, index: ParameterIndex) -> IParameterProxy: ...
|
|
253
|
+
|
|
254
|
+
@overload
|
|
255
|
+
def __getitem__(self, index: slice) -> IParameterView: ...
|
|
256
|
+
|
|
257
|
+
@overload
|
|
258
|
+
def __getitem__(self, uid: ParameterUID) -> IParameterProxy: ...
|
|
259
|
+
|
|
260
|
+
@overload
|
|
261
|
+
def __getitem__(self, indices: Sequence[ParameterIndex]) -> IParameterView: ...
|
|
262
|
+
|
|
263
|
+
@overload
|
|
264
|
+
def __getitem__(self, uids: Sequence[ParameterUID]) -> IParameterView: ...
|
|
265
|
+
|
|
266
|
+
def __getitem__(
|
|
267
|
+
self,
|
|
268
|
+
index: ParameterIndex
|
|
269
|
+
| slice
|
|
270
|
+
| ParameterUID
|
|
271
|
+
| Sequence[ParameterIndex]
|
|
272
|
+
| Sequence[ParameterUID],
|
|
273
|
+
) -> IParameterProxy | IParameterView:
|
|
274
|
+
"""Index into the view by position(s) or uid(s).
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
index: One of:
|
|
278
|
+
- ParameterIndex: zero-based positional index, returns a proxy
|
|
279
|
+
- slice: positional slice, returns a new view
|
|
280
|
+
- ParameterUID: a single uid, returns a proxy
|
|
281
|
+
- Sequence[ParameterIndex]: positional indices, returns a new view
|
|
282
|
+
- Sequence[ParameterUID]: uids, returns a new view
|
|
283
|
+
|
|
284
|
+
Returns:
|
|
285
|
+
Either a single parameter proxy (for int/str) or a new view (for
|
|
286
|
+
slice/sequence).
|
|
287
|
+
"""
|
|
288
|
+
...
|
|
289
|
+
|
|
290
|
+
def list_uids(self) -> list[ParameterUID]:
|
|
291
|
+
"""List parameter unique identifiers in this view.
|
|
292
|
+
|
|
293
|
+
Returns:
|
|
294
|
+
List of UIDs for parameters in this view.
|
|
295
|
+
"""
|
|
296
|
+
...
|
|
297
|
+
|
|
298
|
+
def list_fields_by_uid(
|
|
299
|
+
self, *, parallel: ParallelContext | None = None
|
|
300
|
+
) -> dict[ParameterUID, list[FieldName]]:
|
|
301
|
+
"""Return a uid -> list(fields) mapping for parameters in this view."""
|
|
302
|
+
...
|
|
303
|
+
|
|
304
|
+
def prefetch_fields(
|
|
305
|
+
self,
|
|
306
|
+
*,
|
|
307
|
+
fields_by_uid: dict[ParameterUID, list[FieldName]] | None = None,
|
|
308
|
+
fields: list[FieldName] | None = None,
|
|
309
|
+
verify_prefetch: bool = False,
|
|
310
|
+
parallel: ParallelContext | None = None,
|
|
311
|
+
) -> bool:
|
|
312
|
+
"""Prefetch specified fields for parameters in this view into cache.
|
|
313
|
+
|
|
314
|
+
Args:
|
|
315
|
+
fields_by_uid: Mapping of uid -> list of fields to prefetch.
|
|
316
|
+
fields: List of fields to prefetch for all parameters in the view.
|
|
317
|
+
verify_prefetch: If True, verify cached presence after prefetch.
|
|
318
|
+
parallel: Optional per-method parallel context for prefetching.
|
|
319
|
+
|
|
320
|
+
Returns:
|
|
321
|
+
True if all requested fields were successfully prefetched.
|
|
322
|
+
"""
|
|
323
|
+
...
|
|
324
|
+
|
|
325
|
+
def erase_fields(self, *fields: FieldName) -> None:
|
|
326
|
+
"""Remove specified fields from parameters in this view.
|
|
327
|
+
|
|
328
|
+
Args:
|
|
329
|
+
*fields: Field names to remove from parameters.
|
|
330
|
+
"""
|
|
331
|
+
...
|
|
332
|
+
|
|
333
|
+
def erase_fields_with_regexp(self, *patterns: str) -> None:
|
|
334
|
+
"""Remove fields matching regex patterns from parameters in this view.
|
|
335
|
+
|
|
336
|
+
Args:
|
|
337
|
+
*patterns: Regex patterns for field names to remove.
|
|
338
|
+
"""
|
|
339
|
+
...
|
|
340
|
+
|
|
341
|
+
def filter_by_name(self, *names: str, inverse_mask: bool = False) -> IParameterView:
|
|
342
|
+
"""Filter parameters by name.
|
|
343
|
+
|
|
344
|
+
Args:
|
|
345
|
+
*names: Parameter names to filter by.
|
|
346
|
+
inverse_mask: If True, exclude matching names instead.
|
|
347
|
+
|
|
348
|
+
Returns:
|
|
349
|
+
New view containing only matching parameters.
|
|
350
|
+
"""
|
|
351
|
+
...
|
|
352
|
+
|
|
353
|
+
def filter_by_ptype(self, *ptypes: str | ParameterType) -> IParameterView:
|
|
354
|
+
"""Filter parameters by type.
|
|
355
|
+
|
|
356
|
+
Args:
|
|
357
|
+
*ptypes: Parameter types to filter by (strings or ParameterType).
|
|
358
|
+
|
|
359
|
+
Returns:
|
|
360
|
+
New view containing only matching parameters.
|
|
361
|
+
"""
|
|
362
|
+
...
|
|
363
|
+
|
|
364
|
+
def filter_by_model_id(
|
|
365
|
+
self, *model_ids: str, inverse_mask: bool = False
|
|
366
|
+
) -> IParameterView:
|
|
367
|
+
"""Filter parameters by model ID.
|
|
368
|
+
|
|
369
|
+
Args:
|
|
370
|
+
*model_ids: Model IDs to filter by.
|
|
371
|
+
inverse_mask: If True, exclude matching model IDs instead.
|
|
372
|
+
|
|
373
|
+
Returns:
|
|
374
|
+
New view containing only matching parameters.
|
|
375
|
+
"""
|
|
376
|
+
...
|
|
377
|
+
|
|
378
|
+
def filter_by_fields(
|
|
379
|
+
self,
|
|
380
|
+
*fields: str,
|
|
381
|
+
inverse_mask: bool = False,
|
|
382
|
+
parallel: ParallelContext | None = None,
|
|
383
|
+
) -> IParameterView:
|
|
384
|
+
"""Filter parameters by field presence.
|
|
385
|
+
|
|
386
|
+
Args:
|
|
387
|
+
*fields: Field names that parameters must have.
|
|
388
|
+
inverse_mask: If True, exclude parameters with these fields.
|
|
389
|
+
parallel: Optional per-method parallel context for field checks.
|
|
390
|
+
|
|
391
|
+
Returns:
|
|
392
|
+
New view containing only matching parameters.
|
|
393
|
+
"""
|
|
394
|
+
...
|
|
395
|
+
|
|
396
|
+
def clear(self, erase: bool = False) -> None:
|
|
397
|
+
"""Clear the view.
|
|
398
|
+
|
|
399
|
+
Args:
|
|
400
|
+
erase: If True, also erase data from storage and cache.
|
|
401
|
+
"""
|
|
402
|
+
...
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Parameter metadata definition.
|
|
2
|
+
|
|
3
|
+
This module provides the ParameterMetadata class which serves as an immutable
|
|
4
|
+
container for parameter descriptive information.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from diffract.core.utils.hashing import get_unique_id
|
|
14
|
+
|
|
15
|
+
from .schema import ParameterType
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, kw_only=True)
|
|
19
|
+
class ParameterMetadata:
|
|
20
|
+
"""Immutable metadata container for neural network parameters.
|
|
21
|
+
|
|
22
|
+
Contains all descriptive information about a parameter including
|
|
23
|
+
identification, classification, and additional metadata. The frozen
|
|
24
|
+
dataclass ensures immutability for safe sharing across components.
|
|
25
|
+
|
|
26
|
+
Implements IMetadata protocol for compatibility with generic data layer.
|
|
27
|
+
|
|
28
|
+
Attributes:
|
|
29
|
+
uid: Unique identifier automatically generated if not provided.
|
|
30
|
+
name: Human-readable parameter name (e.g., "conv1.weight").
|
|
31
|
+
ptype: Parameter type classification for filtering.
|
|
32
|
+
model_id: Identifier of the model this parameter belongs to.
|
|
33
|
+
other_meta: Additional metadata as key-value pairs.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
uid: str = field(default_factory=get_unique_id)
|
|
37
|
+
name: str
|
|
38
|
+
ptype: ParameterType
|
|
39
|
+
model_id: str
|
|
40
|
+
other_meta: dict[str, Any] = field(default_factory=dict)
|
|
41
|
+
|
|
42
|
+
_FORBIDDEN_CHARS = re.compile(r'[<>:"/\\|?*]')
|
|
43
|
+
|
|
44
|
+
def __post_init__(self) -> None:
|
|
45
|
+
"""Validate metadata fields contain no forbidden characters."""
|
|
46
|
+
invalid_fields: list[str] = []
|
|
47
|
+
|
|
48
|
+
for field_name, value in [
|
|
49
|
+
("uid", self.uid),
|
|
50
|
+
("name", self.name),
|
|
51
|
+
("ptype", self.ptype.name),
|
|
52
|
+
("model_id", self.model_id),
|
|
53
|
+
]:
|
|
54
|
+
if self._FORBIDDEN_CHARS.search(value):
|
|
55
|
+
invalid_fields.append(field_name)
|
|
56
|
+
|
|
57
|
+
for key in self.other_meta:
|
|
58
|
+
if not isinstance(key, str):
|
|
59
|
+
invalid_fields.append(f"other_meta[{key!r}] (non-string key)")
|
|
60
|
+
elif self._FORBIDDEN_CHARS.search(key):
|
|
61
|
+
invalid_fields.append(f"other_meta[{key!r}]")
|
|
62
|
+
|
|
63
|
+
if invalid_fields:
|
|
64
|
+
raise ValueError(
|
|
65
|
+
f"Fields contain invalid characters {self._FORBIDDEN_CHARS.pattern!r}: "
|
|
66
|
+
f"{', '.join(invalid_fields)}"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
def to_dict(self) -> dict[str, Any]:
|
|
70
|
+
"""Serialize metadata to dictionary.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
Dictionary representation suitable for storage/reconstruction.
|
|
74
|
+
"""
|
|
75
|
+
return {
|
|
76
|
+
"uid": self.uid,
|
|
77
|
+
"name": self.name,
|
|
78
|
+
"ptype": self.ptype.name, # Always serialize as string name
|
|
79
|
+
"model_id": self.model_id,
|
|
80
|
+
"other_meta": self.other_meta,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def from_dict(cls, data: dict[str, Any]) -> ParameterMetadata:
|
|
85
|
+
"""Deserialize metadata from dictionary.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
data: Dictionary with metadata fields.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
ParameterMetadata instance.
|
|
92
|
+
"""
|
|
93
|
+
ptype_value = data["ptype"]
|
|
94
|
+
if isinstance(ptype_value, str):
|
|
95
|
+
ptype = ParameterType.from_string(ptype_value)
|
|
96
|
+
elif isinstance(ptype_value, ParameterType):
|
|
97
|
+
ptype = ptype_value
|
|
98
|
+
else:
|
|
99
|
+
raise TypeError(
|
|
100
|
+
f"Invalid or unsupported 'ptype' value '{ptype_value!r}' in metadata; "
|
|
101
|
+
"expected str or ParameterType"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
return cls(
|
|
105
|
+
uid=data["uid"],
|
|
106
|
+
name=data["name"],
|
|
107
|
+
ptype=ptype,
|
|
108
|
+
model_id=data["model_id"],
|
|
109
|
+
other_meta=data.get("other_meta", {}),
|
|
110
|
+
)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Core parameter data structures and type definitions.
|
|
2
|
+
|
|
3
|
+
This module provides the fundamental data structures for representing neural
|
|
4
|
+
network parameters, including metadata management, type definitions, and
|
|
5
|
+
proxy objects for efficient data access.
|
|
6
|
+
|
|
7
|
+
Key Components:
|
|
8
|
+
- ParameterType: Extensible enum for parameter classification
|
|
9
|
+
- ParameterMetadata: Immutable metadata container for parameters
|
|
10
|
+
- ParameterDataProxy: Lazy-loading proxy for parameter data access
|
|
11
|
+
|
|
12
|
+
The ParameterDataProxy provides intelligent caching and storage management,
|
|
13
|
+
allowing efficient access to large parameter datasets without loading
|
|
14
|
+
everything into memory at once.
|
|
15
|
+
|
|
16
|
+
Example:
|
|
17
|
+
>>> metadata = ParameterMetadata(
|
|
18
|
+
... name="conv1.weight", ptype=ParameterType.DENSE, model_id="resnet50"
|
|
19
|
+
... )
|
|
20
|
+
>>> proxy = ParameterDataProxy.create_and_store(
|
|
21
|
+
... meta=metadata,
|
|
22
|
+
... weights=weight_array,
|
|
23
|
+
... repository=repository,
|
|
24
|
+
... )
|
|
25
|
+
>>> weights = proxy.get_field("weights")
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
from typing import TYPE_CHECKING
|
|
32
|
+
|
|
33
|
+
from diffract.core.constants import TABLE_PARAMETERS
|
|
34
|
+
from diffract.core.data.proxy import DataProxy
|
|
35
|
+
|
|
36
|
+
from .metadata import ParameterMetadata
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from .interface import IParameterRepository
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(kw_only=True)
|
|
43
|
+
class ParameterDataProxy(DataProxy[ParameterMetadata]):
|
|
44
|
+
"""Lazy-loading proxy for neural network parameter data.
|
|
45
|
+
|
|
46
|
+
Extends the generic DataProxy with parameter-specific functionality.
|
|
47
|
+
Provides efficient access to parameter data through intelligent caching
|
|
48
|
+
and storage management. Parameters are loaded on-demand and can be
|
|
49
|
+
prefetched for batch operations. The proxy pattern allows working with
|
|
50
|
+
large parameter datasets without memory constraints.
|
|
51
|
+
|
|
52
|
+
Example:
|
|
53
|
+
>>> # Create and store a new parameter
|
|
54
|
+
>>> proxy = ParameterDataProxy.create_and_store(
|
|
55
|
+
... meta=metadata,
|
|
56
|
+
... repository=repository,
|
|
57
|
+
... )
|
|
58
|
+
>>> # Access fields
|
|
59
|
+
>>> weights = proxy.get_field("weights")
|
|
60
|
+
>>> proxy.set_field("frob_norm", computed_value)
|
|
61
|
+
|
|
62
|
+
Attributes:
|
|
63
|
+
meta: Immutable parameter metadata.
|
|
64
|
+
_repository: Repository that owns storage/cache managers.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
meta: ParameterMetadata
|
|
68
|
+
_repository: IParameterRepository = field(repr=False)
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def get_table(cls) -> str:
|
|
72
|
+
"""Return the storage table name for parameters."""
|
|
73
|
+
return TABLE_PARAMETERS
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def create_and_store(
|
|
77
|
+
cls,
|
|
78
|
+
meta: ParameterMetadata,
|
|
79
|
+
repository: IParameterRepository,
|
|
80
|
+
) -> ParameterDataProxy:
|
|
81
|
+
"""Create parameter proxy and store metadata in index.
|
|
82
|
+
|
|
83
|
+
Factory method that creates a new parameter proxy and immediately
|
|
84
|
+
stores the metadata to the metadata index.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
meta: Parameter metadata.
|
|
88
|
+
repository: Repository owning storage, cache, and metadata managers.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
New parameter proxy with metadata stored.
|
|
92
|
+
"""
|
|
93
|
+
return super().create_and_store(meta=meta, repository=repository)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Parameter repository for managing neural network parameters.
|
|
2
|
+
|
|
3
|
+
This module provides the ParameterRepository class that extends the generic
|
|
4
|
+
DataRepository with parameter-specific functionality.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import ClassVar
|
|
10
|
+
|
|
11
|
+
from diffract.core.constants import TABLE_PARAMETERS
|
|
12
|
+
from diffract.core.data.repository import DataRepository
|
|
13
|
+
|
|
14
|
+
from .metadata import ParameterMetadata
|
|
15
|
+
from .proxy import ParameterDataProxy
|
|
16
|
+
from .view import ParameterView
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ParameterRepository(DataRepository[ParameterMetadata, ParameterDataProxy]):
|
|
20
|
+
"""Repository owning storage/cache/metadata and managing parameter membership.
|
|
21
|
+
|
|
22
|
+
Extends the generic DataRepository with parameter-specific configuration
|
|
23
|
+
for metadata class, proxy class, view class, storage table, and metadata schema.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
METADATA_CLASS = ParameterMetadata
|
|
27
|
+
PROXY_CLASS = ParameterDataProxy
|
|
28
|
+
VIEW_CLASS = ParameterView
|
|
29
|
+
TABLE = TABLE_PARAMETERS
|
|
30
|
+
|
|
31
|
+
# Schema for MetadataIndex
|
|
32
|
+
METADATA_COLUMNS: ClassVar[dict[str, type]] = {
|
|
33
|
+
"name": str,
|
|
34
|
+
"model_id": str,
|
|
35
|
+
"ptype": str,
|
|
36
|
+
}
|
|
37
|
+
METADATA_INDEXES: ClassVar[list[str]] = ["model_id", "ptype", "name"]
|
|
38
|
+
|
|
39
|
+
def create_view(self) -> ParameterView:
|
|
40
|
+
"""Create a view over all parameters in this repository.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
ParameterView containing all parameters.
|
|
44
|
+
"""
|
|
45
|
+
return ParameterView(repository=self, uids=None)
|