torch-einops-kit 0.1.7__tar.gz → 0.1.9__tar.gz

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.
Files changed (42) hide show
  1. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/PKG-INFO +20 -15
  2. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/pyproject.toml +6 -9
  3. torch_einops_kit-0.1.9/setup.cfg +4 -0
  4. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/__init__.py +5 -4
  5. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/_cat_and_stack.py +2 -1
  6. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/_helpers.py +7 -6
  7. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/_masking.py +2 -1
  8. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/_padding.py +4 -2
  9. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/_slicing.py +4 -1
  10. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/_theTypes.py +30 -8
  11. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/device.py +4 -2
  12. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/einops.py +2 -1
  13. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/nn.py +59 -3
  14. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/save_load.py +13 -12
  15. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/scaleValues.py +6 -3
  16. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/utils.py +8 -4
  17. torch_einops_kit-0.1.9/src/torch_einops_kit.egg-info/PKG-INFO +487 -0
  18. torch_einops_kit-0.1.9/src/torch_einops_kit.egg-info/SOURCES.txt +40 -0
  19. torch_einops_kit-0.1.9/src/torch_einops_kit.egg-info/dependency_links.txt +1 -0
  20. torch_einops_kit-0.1.9/src/torch_einops_kit.egg-info/requires.txt +12 -0
  21. torch_einops_kit-0.1.9/src/torch_einops_kit.egg-info/top_level.txt +1 -0
  22. torch_einops_kit-0.1.9/tests/test_cat_stack.py +80 -0
  23. torch_einops_kit-0.1.9/tests/test_device.py +44 -0
  24. torch_einops_kit-0.1.9/tests/test_device_extended.py +151 -0
  25. torch_einops_kit-0.1.9/tests/test_dimensions.py +280 -0
  26. torch_einops_kit-0.1.9/tests/test_einops.py +85 -0
  27. torch_einops_kit-0.1.9/tests/test_helpers.py +197 -0
  28. torch_einops_kit-0.1.9/tests/test_masking.py +252 -0
  29. torch_einops_kit-0.1.9/tests/test_nn.py +102 -0
  30. torch_einops_kit-0.1.9/tests/test_nn_extended.py +166 -0
  31. torch_einops_kit-0.1.9/tests/test_padding.py +443 -0
  32. torch_einops_kit-0.1.9/tests/test_save_load.py +158 -0
  33. torch_einops_kit-0.1.9/tests/test_save_load_extended.py +471 -0
  34. torch_einops_kit-0.1.9/tests/test_scaleValues.py +181 -0
  35. torch_einops_kit-0.1.9/tests/test_slicing.py +145 -0
  36. torch_einops_kit-0.1.9/tests/test_utils.py +341 -0
  37. torch_einops_kit-0.1.9/tests/test_utils_extended.py +61 -0
  38. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/LICENSE +0 -0
  39. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/LICENSE-WANG +0 -0
  40. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/README.md +0 -0
  41. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/_dimensions.py +0 -0
  42. {torch_einops_kit-0.1.7 → torch_einops_kit-0.1.9}/src/torch_einops_kit/py.typed +0 -0
@@ -1,13 +1,17 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: torch-einops-kit
3
- Version: 0.1.7
3
+ Version: 0.1.9
4
4
  Summary: Typed tensor-shaping, masking, padding, device-routing, and checkpoint utilities for PyTorch and `einops`. A superset of `lucidrains/torch-einops-utils` with similar utilities from other lucidrains packages. Adds strict typing, extensive tests, and comprehensive docstrings.
5
- Keywords: artificial intelligence,einops,machine learning,pytorch,torch
6
- Author: Hunter Hogan
7
5
  Author-email: Hunter Hogan <HunterHogan@pm.me>
6
+ Maintainer-email: Hunter Hogan <HunterHogan@pm.me>
8
7
  License-Expression: CC-BY-NC-4.0
9
- License-File: LICENSE
10
- License-File: LICENSE-WANG
8
+ Project-URL: Context7, https://context7.com/hunterhogan/torch_einops_kit
9
+ Project-URL: Donate, https://www.patreon.com/integrated
10
+ Project-URL: Download, https://pypi.org/project/torch_einops_kit
11
+ Project-URL: Homepage, https://github.com/hunterhogan/torch_einops_kit
12
+ Project-URL: Issues, https://github.com/hunterhogan/torch_einops_kit/issues
13
+ Project-URL: Repository, https://github.com/hunterhogan/torch_einops_kit.git
14
+ Keywords: artificial intelligence,einops,machine learning,pytorch,torch
11
15
  Classifier: Development Status :: 4 - Beta
12
16
  Classifier: Environment :: Console
13
17
  Classifier: Environment :: GPU :: NVIDIA CUDA
@@ -20,20 +24,21 @@ Classifier: Programming Language :: Python :: 3.14
20
24
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
25
  Classifier: Topic :: Utilities
22
26
  Classifier: Typing :: Typed
27
+ Requires-Python: >=3.10
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ License-File: LICENSE-WANG
23
31
  Requires-Dist: einops>=0.8.2
24
32
  Requires-Dist: huntermakespy>=0.7.0
25
33
  Requires-Dist: torch>=2.0.0
26
34
  Requires-Dist: typing-extensions>=4.0.0
27
- Maintainer: Hunter Hogan
28
- Maintainer-email: Hunter Hogan <HunterHogan@pm.me>
29
- Requires-Python: >=3.10
30
- Project-URL: Context7, https://context7.com/hunterhogan/torch_einops_kit
31
- Project-URL: Donate, https://www.patreon.com/integrated
32
- Project-URL: Download, https://pypi.org/project/torch_einops_kit
33
- Project-URL: Homepage, https://github.com/hunterhogan/torch_einops_kit
34
- Project-URL: Issues, https://github.com/hunterhogan/torch_einops_kit/issues
35
- Project-URL: Repository, https://github.com/hunterhogan/torch_einops_kit.git
36
- Description-Content-Type: text/markdown
35
+ Provides-Extra: development
36
+ Requires-Dist: pytest-cov; extra == "development"
37
+ Provides-Extra: testing
38
+ Requires-Dist: more-itertools; extra == "testing"
39
+ Requires-Dist: numpy>=2.0.0; extra == "testing"
40
+ Requires-Dist: pytest; extra == "testing"
41
+ Dynamic: license-file
37
42
 
38
43
  # torch_einops_kit
39
44
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "torch-einops-kit"
3
- version = "0.1.7"
3
+ version = "0.1.9"
4
4
  description = "Typed tensor-shaping, masking, padding, device-routing, and checkpoint utilities for PyTorch and `einops`. A superset of `lucidrains/torch-einops-utils` with similar utilities from other lucidrains packages. Adds strict typing, extensive tests, and comprehensive docstrings."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -44,13 +44,13 @@ Homepage = "https://github.com/hunterhogan/torch_einops_kit"
44
44
  Issues = "https://github.com/hunterhogan/torch_einops_kit/issues"
45
45
  Repository = "https://github.com/hunterhogan/torch_einops_kit.git"
46
46
 
47
- [dependency-groups]
48
- dev = ["pytest-cov"]
47
+ [project.optional-dependencies]
48
+ development = ["pytest-cov"]
49
49
  testing = ["more-itertools", "numpy>=2.0.0", "pytest"]
50
50
 
51
51
  [build-system]
52
- requires = ["uv_build>=0.11.8,<0.12.0"]
53
- build-backend = "uv_build"
52
+ requires = ["setuptools"]
53
+ build-backend = "setuptools.build_meta"
54
54
 
55
55
  [tool.coverage]
56
56
  report = { ignore_errors = false }
@@ -59,13 +59,10 @@ run = { branch = true, data_file = "tests/coverage/.coverage", omit = [
59
59
  ], source = ["."] }
60
60
 
61
61
  [tool.pytest]
62
- addopts = ["--color=auto"]
62
+ addopts = ["--color=yes"]
63
63
  log_auto_indent = "On"
64
64
  testpaths = ["tests"]
65
65
 
66
66
  [tool.updateCitation]
67
67
  filenameCitationDOTcff = "CITATION.cff"
68
68
  pathFilenameCitationSSOT = "citations/CITATION.cff"
69
-
70
- [tool.uv]
71
- default-groups = ["dev", "testing"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -126,10 +126,11 @@ scaleValues
126
126
  from __future__ import annotations
127
127
 
128
128
  from torch_einops_kit._theTypes import (
129
- ConfigArgsKwargs as ConfigArgsKwargs, DehydratedCheckpoint as DehydratedCheckpoint, DehydratedTorchNNModule as DehydratedTorchNNModule,
130
- DimAndValue as DimAndValue, IdentityCallable as IdentityCallable, InversePackListTensors as InversePackListTensors,
131
- InversePackTensor as InversePackTensor, PSpec as PSpec, RVar as RVar, StrPath as StrPath, SupportsIntIndex as SupportsIntIndex,
132
- T_co as T_co, TorchNNModule as TorchNNModule, TVar as TVar)
129
+ ConfigArgsKwargs as ConfigArgsKwargs, CountParametersPartial as CountParametersPartial, DehydratedCheckpoint as DehydratedCheckpoint,
130
+ DehydratedTorchNNModule as DehydratedTorchNNModule, DimAndValue as DimAndValue, IdentityCallable as IdentityCallable,
131
+ InversePackListTensors as InversePackListTensors, InversePackTensor as InversePackTensor, PSpec as PSpec, RVar as RVar, StrPath as StrPath,
132
+ SupportsIntIndex as SupportsIntIndex, T_co as T_co, TorchNNModule as TorchNNModule, TVar as TVar, 形num_parameters as 形num_parameters,
133
+ 木 as 木)
133
134
 
134
135
  # isort: split
135
136
  from torch_einops_kit._helpers import (
@@ -1,11 +1,12 @@
1
1
  from __future__ import annotations
2
2
 
3
- from torch import broadcast_tensors, cat, stack, Tensor # pyright: ignore[reportUnknownVariableType]
3
+ from torch import broadcast_tensors, cat, stack # pyright: ignore[reportUnknownVariableType]
4
4
  from torch_einops_kit import safe
5
5
  from typing import cast, TYPE_CHECKING
6
6
 
7
7
  if TYPE_CHECKING:
8
8
  from collections.abc import Sequence
9
+ from torch import Tensor
9
10
 
10
11
  def broadcast_cat(tensors: Sequence[Tensor], dim: int = -1) -> Tensor:
11
12
  """Broadcast tensor groups before concatenation.
@@ -1,12 +1,13 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from functools import wraps
4
- from typing import Concatenate, overload, TYPE_CHECKING, TypeGuard
4
+ from typing import overload, TYPE_CHECKING
5
5
 
6
6
  if TYPE_CHECKING:
7
7
  from collections.abc import Callable, Iterable, Sequence
8
8
  from torch import Tensor
9
9
  from torch_einops_kit import IdentityCallable, PSpec, RVar, SupportsIntIndex, T_co, TVar
10
+ from typing import Concatenate, TypeGuard
10
11
 
11
12
  def compact(arr: Iterable[T_co | None]) -> list[T_co]:
12
13
  """Filter `None` values from `arr` and return the remaining elements as a `list`.
@@ -198,15 +199,15 @@ def map_values(fn: Callable[[TVar], TVar], v: TVar) -> TVar:
198
199
 
199
200
  Parameters
200
201
  ----------
201
- fn : Callable[[TVar], TVar]
202
+ fn : Callable[[T_co | dict[Any, T_co]], T_co]
202
203
  The function to apply to each leaf value. `fn` receives each non-container value and must
203
204
  return a value of the same type.
204
- v : TVar
205
+ v : T_co | list[T_co] | tuple[T_co, ...] | dict[Any, T_co]
205
206
  The value to transform. May be a `list`, `tuple`, `dict`, or any leaf value.
206
207
 
207
208
  Returns
208
209
  -------
209
- transformed : TVar
210
+ transformed : T_co
210
211
  The input structure with all leaf values replaced by the results of `fn`.
211
212
 
212
213
  See Also
@@ -223,10 +224,10 @@ def map_values(fn: Callable[[TVar], TVar], v: TVar) -> TVar:
223
224
  [3] tests.test_helpers.test_map_values_transforms_structure
224
225
  """
225
226
  if isinstance(v, (list, tuple)):
226
- return type(v)(map_values(fn, el) for el in v) # pyright: ignore[reportUnknownVariableType, reportUnknownArgumentType]
227
+ return type(v)(map_values(fn, el) for el in v) # pyright: ignore[reportUnknownVariableType, reportUnknownArgumentType] # ty:ignore[invalid-argument-type]
227
228
 
228
229
  if isinstance(v, dict):
229
- v = {key: map_values(fn, val) for key, val in v.items()} # pyright: ignore[reportAssignmentType, reportUnknownArgumentType, reportUnknownVariableType] # ty:ignore[invalid-assignment]
230
+ v = {key: map_values(fn, val) for key, val in v.items()} # pyright: ignore[reportAssignmentType, reportUnknownArgumentType, reportUnknownVariableType] # ty:ignore[invalid-assignment, invalid-argument-type]
230
231
 
231
232
  return fn(v)
232
233
 
@@ -2,7 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  from einops import rearrange
4
4
  from functools import reduce
5
- from torch import arange, Tensor
5
+ from torch import arange
6
6
  from torch_einops_kit import exists, safe, shift_left, shift_right
7
7
  from torch_einops_kit.scaleValues import reverse_cumsum
8
8
  from typing import TYPE_CHECKING
@@ -10,6 +10,7 @@ import torch
10
10
 
11
11
  if TYPE_CHECKING:
12
12
  from collections.abc import Callable, Sequence
13
+ from torch import Tensor
13
14
  from torch.types import Number
14
15
 
15
16
  def and_masks(masks: Sequence[Tensor | None]) -> Tensor | None:
@@ -1,15 +1,17 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from hunterMakesPy import decreasing, zeroIndexed
4
- from torch import cat, stack, Tensor, tensor
4
+ from torch import cat, stack, tensor
5
5
  from torch_einops_kit import DimAndValue, first
6
- from typing import Literal, overload, TYPE_CHECKING
6
+ from typing import overload, TYPE_CHECKING
7
7
  from typing_extensions import Unpack
8
8
  import torch
9
9
  import torch.nn.functional as F
10
10
 
11
11
  if TYPE_CHECKING:
12
12
  from collections.abc import Callable, Sequence
13
+ from torch import Tensor
14
+ from typing import Literal
13
15
 
14
16
  def pad_at_dim(t: Tensor, pad: tuple[int, int], *, dim: int = -1, value: float = 0.0) -> Tensor:
15
17
  """Pad `t` along `dim`, inserting `value` at each end by the amounts in `pad`.
@@ -1,9 +1,12 @@
1
1
  from __future__ import annotations
2
2
 
3
- from torch import Tensor
4
3
  from torch_einops_kit import exists
4
+ from typing import TYPE_CHECKING
5
5
  import torch
6
6
 
7
+ if TYPE_CHECKING:
8
+ from torch import Tensor
9
+
7
10
  def shape_with_replace(t: Tensor, replace_dict: dict[int, int] | None = None) -> torch.Size:
8
11
  """Return the shape of a tensor with selected dimension sizes replaced by new values.
9
12
 
@@ -1,12 +1,16 @@
1
- # ruff: noqa: E224
1
+ # ruff: noqa: PLC2701
2
2
  from __future__ import annotations
3
3
 
4
+ from abc import abstractmethod
4
5
  from os import PathLike
6
+ from torch import nn
5
7
  from torch.nn import Module
6
- from typing import Any, Literal, overload, ParamSpec, Protocol, TYPE_CHECKING, TypeAlias, TypedDict, TypeVar
8
+ from torch.utils._pytree import PyTree
9
+ from typing import Any, overload, ParamSpec, Protocol, TYPE_CHECKING, TypedDict, TypeVar
7
10
 
8
11
  if TYPE_CHECKING:
9
12
  from torch import Tensor
13
+ from typing import Literal, TypeAlias
10
14
 
11
15
  ConfigArgsKwargs: TypeAlias = tuple[tuple[Any, ...], dict[Any, Any]]
12
16
  """Represent the positional arguments and keyword arguments of a decorated constructor.
@@ -35,7 +39,7 @@ References
35
39
 
36
40
  [4] torch_einops_kit.save_load.rehydrate_config
37
41
  """
38
- PSpec = ParamSpec("PSpec")
42
+ PSpec = ParamSpec("PSpec")
39
43
  """Capture the full parameter specification of a callable for higher-order type signatures.
40
44
 
41
45
  `PSpec` is a `ParamSpec` [1] that preserves the complete parameter signature of a callable through
@@ -58,7 +62,7 @@ References
58
62
 
59
63
  [4] torch_einops_kit.maybe
60
64
  """
61
- RVar = TypeVar("RVar")
65
+ RVar = TypeVar("RVar")
62
66
  """Represent a generic return type in higher-order callable signatures.
63
67
 
64
68
  `RVar` is an unconstrained `TypeVar` [1] used to annotate the return type of an inner callable in
@@ -78,7 +82,7 @@ References
78
82
 
79
83
  [3] torch_einops_kit.TVar
80
84
  """
81
- StrPath: TypeAlias = str | PathLike[str]
85
+ StrPath: TypeAlias = str | PathLike[str]
82
86
  """Accept either a `str` or a `PathLike[str]` filesystem path value.
83
87
 
84
88
  `StrPath` is a `TypeAlias` for `str | PathLike[str]` [1], intentionally copying the definition of
@@ -97,7 +101,7 @@ References
97
101
  https://docs.python.org/3/library/pathlib.html#pathlib.Path
98
102
  [4] torch_einops_kit.save_load.save_load
99
103
  """
100
- T_co = TypeVar("T_co", covariant=True)
104
+ T_co = TypeVar("T_co", covariant=True)
101
105
  """Represent a covariant element type in read-only container protocols.
102
106
 
103
107
  `T_co` is a covariant `TypeVar` [1] used in container protocols and functions that produce but do not
@@ -118,7 +122,7 @@ References
118
122
 
119
123
  [3] torch_einops_kit.compact
120
124
  """
121
- TorchNNModule = TypeVar("TorchNNModule", bound=Module)
125
+ TorchNNModule = TypeVar("TorchNNModule", bound=Module)
122
126
  """Represent a concrete `torch.nn.Module` subclass in decorator and method signatures.
123
127
 
124
128
  `TorchNNModule` is a `TypeVar` [1] bound to `torch.nn.Module` [2] that lets static analyzers track
@@ -143,7 +147,7 @@ References
143
147
 
144
148
  [4] torch_einops_kit.device.move_inputs_to_module_device
145
149
  """
146
- TVar = TypeVar("TVar")
150
+ TVar = TypeVar("TVar")
147
151
  """Represent an unconstrained generic type for identity-preserving operations.
148
152
 
149
153
  `TVar` is an unconstrained `TypeVar` [1] used to annotate functions and protocols that accept a value
@@ -176,6 +180,7 @@ References
176
180
 
177
181
  [7] torch_einops_kit.first
178
182
  """
183
+ 木 = TypeVar('木', bound=PyTree)
179
184
 
180
185
  class DehydratedCheckpoint(TypedDict):
181
186
  """Represent the checkpoint dictionary written and read by the `save_load` decorator.
@@ -429,3 +434,20 @@ class SupportsIntIndex(Protocol[T_co]):
429
434
  [2] torch_einops_kit.first
430
435
  """
431
436
  def __getitem__(self, index: int, /) -> T_co: ...
437
+
438
+ class IHave_num_parameters(nn.Module):
439
+ @property
440
+ @abstractmethod
441
+ def num_parameters(self) -> int: ...
442
+
443
+ 形num_parameters = TypeVar("形num_parameters", bound=IHave_num_parameters)
444
+
445
+ class CountParametersPartial(Protocol):
446
+ @overload
447
+ def __call__(self, model_or_class: type[形num_parameters]) -> type[形num_parameters]: ...
448
+ @overload
449
+ def __call__(self, model_or_class: type[TorchNNModule]) -> type[TorchNNModule]: ...
450
+ @overload
451
+ def __call__(self, model_or_class: 形num_parameters) -> int: ...
452
+ @overload
453
+ def __call__(self, model_or_class: TorchNNModule) -> int: ...
@@ -22,14 +22,16 @@ from __future__ import annotations
22
22
 
23
23
  from functools import wraps
24
24
  from itertools import chain
25
- from torch_einops_kit import exists, PSpec, TorchNNModule, tree_map_tensor, TVar
26
- from typing import Concatenate, TYPE_CHECKING
25
+ from torch_einops_kit import exists, tree_map_tensor
26
+ from typing import TYPE_CHECKING
27
27
 
28
28
  if TYPE_CHECKING:
29
29
  from collections.abc import Callable
30
30
  from torch import device, Tensor
31
31
  from torch.nn import Module
32
32
  from torch.types import Device
33
+ from torch_einops_kit import PSpec, TorchNNModule, TVar
34
+ from typing import Concatenate
33
35
 
34
36
  def module_device(m: Module) -> device | None:
35
37
  """Infer the `torch.device` of a `torch.nn.Module` instance from its first `torch.nn.Parameter` or registered `torch.Tensor` buffer.
@@ -25,12 +25,13 @@ References
25
25
  from __future__ import annotations
26
26
 
27
27
  from einops import pack, unpack
28
- from torch import is_tensor, Tensor
28
+ from torch import is_tensor
29
29
  from torch_einops_kit import default, first
30
30
  from typing import overload, TYPE_CHECKING
31
31
 
32
32
  if TYPE_CHECKING:
33
33
  from collections.abc import Sequence
34
+ from torch import Tensor
34
35
  from torch_einops_kit import InversePackListTensors, InversePackTensor
35
36
 
36
37
  def pack_one(t: Tensor, pattern: str) -> tuple[Tensor, Sequence[tuple[int, ...] | list[int]]]:
@@ -1,3 +1,4 @@
1
+ # ruff: noqa: D101, D102
1
2
  """Construct `nn.Sequential` instances and adapt callables to the `nn.Module` interface.
2
3
 
3
4
  Contents
@@ -15,12 +16,56 @@ Classes
15
16
 
16
17
  from __future__ import annotations
17
18
 
19
+ from functools import partial
20
+ from operator import methodcaller
18
21
  from torch import nn
19
- from torch_einops_kit import compact, identity, PSpec, RVar
20
- from typing import Generic, TYPE_CHECKING
22
+ from torch_einops_kit import compact, exists, identity, PSpec, RVar, tree_flatten_with_inverse, TVar, 木
23
+ from typing import Generic, overload, TYPE_CHECKING
21
24
 
22
25
  if TYPE_CHECKING:
23
- from collections.abc import Callable
26
+ from collections.abc import Callable, Iterator
27
+ from torch_einops_kit import CountParametersPartial, TorchNNModule, 形num_parameters
28
+ from typing import Concatenate
29
+
30
+ @overload
31
+ def count_parameters(model_or_class: type[形num_parameters], *, requires_grad: bool | None = None) -> type[形num_parameters]: ...
32
+ @overload
33
+ def count_parameters(model_or_class: type[TorchNNModule], *, requires_grad: bool | None = None) -> type[TorchNNModule]: ...
34
+ @overload
35
+ def count_parameters(model_or_class: None = None, *, requires_grad: bool | None = None) -> CountParametersPartial: ...
36
+ @overload
37
+ def count_parameters(model_or_class: TorchNNModule, *, requires_grad: bool | None = None) -> int: ...
38
+ def count_parameters(
39
+ model_or_class: type[形num_parameters | TorchNNModule] | TorchNNModule | None = None
40
+ , *
41
+ , requires_grad: bool | None = None
42
+ ) -> type[TorchNNModule | 形num_parameters] | int | CountParametersPartial:
43
+ """IDK.
44
+
45
+ There's only so much I can do without changing the API.
46
+
47
+ Returns
48
+ -------
49
+ count : int
50
+ Number of parameters in `model_or_class` that satisfy `requires_grad`, or the number of parameters in `model_or_class` if `requires_grad` is `None`.
51
+ """
52
+ def doCount(model: TorchNNModule) -> int:
53
+ countMe: Iterator[nn.Parameter] = model.parameters()
54
+ if exists(requires_grad):
55
+ countMe = filter(lambda p: p.requires_grad == requires_grad, countMe)
56
+ return sum(map(methodcaller('numel'), countMe))
57
+
58
+ def addProperty(model: type[形num_parameters | TorchNNModule]) -> type[形num_parameters | TorchNNModule]:
59
+ setattr(model, 'num_parameters', property(doCount)) # noqa: B010
60
+ return model
61
+
62
+ if isinstance(model_or_class, type) and issubclass(model_or_class, nn.Module):
63
+ return addProperty(model_or_class)
64
+
65
+ if not exists(model_or_class):
66
+ return partial(count_parameters, requires_grad=requires_grad)
67
+
68
+ return doCount(model_or_class)
24
69
 
25
70
  def Sequential(*modules: nn.Module | None) -> nn.Sequential:
26
71
  """Construct an `nn.Sequential` instance from `modules`, ignoring each value that is `None`.
@@ -151,6 +196,17 @@ class Lambda(nn.Module, Generic[PSpec, RVar]):
151
196
  """
152
197
  return self.fn(*args, **kwargs)
153
198
 
199
+ class Residual(nn.Module, Generic[TVar, PSpec, 木]):
200
+ def __init__(self, fn: Callable[Concatenate[TVar, PSpec], 木]) -> None:
201
+ super().__init__()
202
+ self.fn: Callable[Concatenate[TVar, PSpec], 木] = fn
203
+
204
+ def forward(self, x: TVar, *args: PSpec.args, **kwargs: PSpec.kwargs) -> 木:
205
+ out: 木 = self.fn(x, *args, **kwargs)
206
+
207
+ (first, *rest), inverse = tree_flatten_with_inverse(out)
208
+ return inverse((first + x, *rest))
209
+
154
210
  """
155
211
  Some of the logic in this module may be protected by the following.
156
212
 
@@ -22,15 +22,16 @@ from __future__ import annotations
22
22
  from functools import wraps
23
23
  from pathlib import Path
24
24
  from torch.nn import Module
25
- from torch_einops_kit import (
26
- ConfigArgsKwargs, DehydratedCheckpoint, DehydratedTorchNNModule, exists, map_values, StrPath, TorchNNModule, TVar)
27
- from typing import Any, cast, overload, TYPE_CHECKING
25
+ from torch_einops_kit import DehydratedCheckpoint, DehydratedTorchNNModule, exists, map_values
26
+ from typing import cast, overload, TYPE_CHECKING
28
27
  import pickle
29
28
  import torch
30
29
  import warnings
31
30
 
32
31
  if TYPE_CHECKING:
33
32
  from collections.abc import Callable
33
+ from torch_einops_kit import ConfigArgsKwargs, StrPath, TorchNNModule, TVar
34
+ from typing import Any
34
35
 
35
36
  def dehydrate_config(config: TVar, config_instance_var_name: str) -> TVar:
36
37
  """Convert nested decorated modules in `config` into reconstruction records.
@@ -320,8 +321,8 @@ def save_load(
320
321
 
321
322
  path = Path('test_model_init.pt')
322
323
  model = SimpleNet(10, 20)
323
- model.save(str(path))
324
- restored_model = SimpleNet.init_and_load(str(path))
324
+ model.save(path)
325
+ restored_model = SimpleNet.init_and_load(path)
325
326
  ```
326
327
 
327
328
  From `tests.test_save_load_extended` [8]:
@@ -417,9 +418,9 @@ def save_load(
417
418
  model=self.state_dict(), config=pickle.dumps(dehydrate_config(config, config_instance_var_name)), version=version
418
419
  )
419
420
 
420
- torch.save(pkg, str(path))
421
+ torch.save(pkg, path)
421
422
 
422
- def _load(self: TorchNNModule, path: StrPath | Path, *, strict: bool = True) -> None:
423
+ def _load(self: TorchNNModule, path: StrPath, *, strict: bool = True) -> None:
423
424
  """Restore model state from a checkpoint file.
424
425
 
425
426
  You can use this method to load parameter values into an already-constructed decorated
@@ -428,7 +429,7 @@ def save_load(
428
429
 
429
430
  Parameters
430
431
  ----------
431
- path : StrPath | Path
432
+ path : StrPath
432
433
  The filesystem path to read the checkpoint from.
433
434
  strict : bool = True
434
435
  Forwarded to `load_state_dict`. When `True`, the key sets of the checkpoint and the
@@ -455,7 +456,7 @@ def save_load(
455
456
  message: str = f'I received `{path = }`, but no file exists at that path.'
456
457
  raise FileNotFoundError(message)
457
458
 
458
- pkg: DehydratedCheckpoint = torch.load(str(path), map_location='cpu')
459
+ pkg: DehydratedCheckpoint = torch.load(path, map_location='cpu')
459
460
 
460
461
  if exists(version) and exists(pkg['version']) and (version != pkg['version']):
461
462
  message: str = (
@@ -466,7 +467,7 @@ def save_load(
466
467
  self.load_state_dict(pkg['model'], strict=strict)
467
468
 
468
469
  @classmethod
469
- def _init_and_load_from(cls: type[TorchNNModule], path: StrPath | Path, *, strict: bool = True) -> TorchNNModule:
470
+ def _init_and_load_from(cls: type[TorchNNModule], path: StrPath, *, strict: bool = True) -> TorchNNModule:
470
471
  """Construct a new instance of the decorated class and restore its state from a checkpoint file.
471
472
 
472
473
  You can use this classmethod to reconstruct a model that was previously saved with the
@@ -476,7 +477,7 @@ def save_load(
476
477
 
477
478
  Parameters
478
479
  ----------
479
- path : StrPath | Path
480
+ path : StrPath
480
481
  The filesystem path to read the checkpoint from.
481
482
  strict : bool = True
482
483
  Forwarded to `load_state_dict`. When `True`, the key sets of the checkpoint and the
@@ -502,7 +503,7 @@ def save_load(
502
503
  if not path.exists():
503
504
  message: str = f'I received `{path = }`, but no file exists at that path.'
504
505
  raise FileNotFoundError(message)
505
- pkg: DehydratedCheckpoint = torch.load(str(path), map_location='cpu')
506
+ pkg: DehydratedCheckpoint = torch.load(path, map_location='cpu')
506
507
 
507
508
  if 'config' not in pkg:
508
509
  message: str = 'model configs were not found in this saved checkpoint'
@@ -25,12 +25,15 @@ Classes
25
25
 
26
26
  from __future__ import annotations
27
27
 
28
- from torch import nn, SymInt, Tensor
29
- from torch.nn import Module
28
+ from torch import nn
30
29
  from torch_einops_kit import exists, pad_right_ndim
30
+ from typing import TYPE_CHECKING
31
31
  import torch
32
32
  import torch.nn.functional as F
33
33
 
34
+ if TYPE_CHECKING:
35
+ from torch import SymInt, Tensor
36
+
34
37
  def exclusive_cumsum(t: Tensor, dim: int = -1) -> Tensor:
35
38
  """Compute the exclusive prefix sum of `Tensor` `t` along its dimension `dim`.
36
39
 
@@ -258,7 +261,7 @@ def reverse_cumsum(t: Tensor, dim: int = -1, *, keepdim: bool = True) -> Tensor:
258
261
  """
259
262
  return t.sum(dim=dim, keepdim=keepdim) - t.cumsum(dim=dim) + t
260
263
 
261
- class RMSNorm(Module):
264
+ class RMSNorm(nn.Module):
262
265
  """Normalize feature vectors with root-mean-square scaling and a learned rescaling parameter.
263
266
 
264
267
  You can use `RMSNorm` as a pre-normalization layer before attention, feedforward, or linear
@@ -14,12 +14,16 @@ Functions
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
- from torch import is_tensor, Tensor
18
- from torch.utils._pytree import PyTree, tree_flatten, tree_map, tree_unflatten # noqa: PLC2701
19
- from typing import Any, TYPE_CHECKING
17
+ from torch import is_tensor
18
+ from torch.utils._pytree import tree_flatten, tree_map, tree_unflatten # noqa: PLC2701
19
+ from typing import TYPE_CHECKING
20
20
 
21
21
  if TYPE_CHECKING:
22
22
  from collections.abc import Callable, Iterable
23
+ from torch import Tensor
24
+ from torch.utils._pytree import PyTree
25
+ from torch_einops_kit import 木
26
+ from typing import Any
23
27
 
24
28
  def tree_map_tensor(fn: Callable[[Tensor], Tensor], tree: PyTree) -> PyTree:
25
29
  """Apply `fn` to every `torch.Tensor` leaf in `tree`, leaving non-tensor leaves unchanged.
@@ -88,7 +92,7 @@ def tree_map_tensor(fn: Callable[[Tensor], Tensor], tree: PyTree) -> PyTree:
88
92
 
89
93
  return tree_map(func, tree)
90
94
 
91
- def tree_flatten_with_inverse(tree: PyTree) -> tuple[list[Any], Callable[[Iterable[Any]], PyTree]]:
95
+ def tree_flatten_with_inverse(tree: 木) -> tuple[list[Any], Callable[[Iterable[Any]], 木]]:
92
96
  """Flatten `tree` into a list of leaves and return a paired inverse function.
93
97
 
94
98
  You can use this function to decompose a nested PyTree [1] structure into a flat list of leaves