model-runtime 0.5.0__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.
- model_runtime-0.5.0.dist-info/METADATA +618 -0
- model_runtime-0.5.0.dist-info/RECORD +36 -0
- model_runtime-0.5.0.dist-info/WHEEL +4 -0
- model_runtime-0.5.0.dist-info/entry_points.txt +2 -0
- model_runtime-0.5.0.dist-info/licenses/LICENSE +202 -0
- model_runtime-0.5.0.dist-info/licenses/NOTICE +6 -0
- saturn/__init__.py +28 -0
- saturn/adapters/__init__.py +63 -0
- saturn/adapters/_residency.py +196 -0
- saturn/adapters/decoder.py +1679 -0
- saturn/adapters/diffusion.py +438 -0
- saturn/adapters/flux1.py +661 -0
- saturn/adapters/flux2.py +630 -0
- saturn/adapters/mamba.py +620 -0
- saturn/adapters/qwen.py +637 -0
- saturn/causal.py +260 -0
- saturn/cli.py +382 -0
- saturn/contracts.py +175 -0
- saturn/core.py +1979 -0
- saturn/dependencies.py +61 -0
- saturn/interop/__init__.py +37 -0
- saturn/interop/circuit_tracer.py +1198 -0
- saturn/investigation.py +109 -0
- saturn/numerics.py +213 -0
- saturn/observers.py +289 -0
- saturn/paths.py +324 -0
- saturn/program.py +364 -0
- saturn/route.py +774 -0
- saturn/shared_store.py +257 -0
- saturn/store.py +835 -0
- saturn/symbols.py +398 -0
- saturn/training/__init__.py +61 -0
- saturn/training/_checkpoint.py +1618 -0
- saturn/trial.py +514 -0
- saturn/values.py +223 -0
- saturn/writers.py +82 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
saturn/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Saturn's public execution vocabulary. Model frameworks are loaded on demand."""
|
|
2
|
+
|
|
3
|
+
from .contracts import (
|
|
4
|
+
ExecutionPoint,
|
|
5
|
+
NumericalContract,
|
|
6
|
+
SlotSpec,
|
|
7
|
+
StateAddress,
|
|
8
|
+
SurfaceManifest,
|
|
9
|
+
TransitionSpec,
|
|
10
|
+
)
|
|
11
|
+
from .core import Act, Adapter, Frame, PortStop, Receipt, Session, StateCut
|
|
12
|
+
|
|
13
|
+
__version__ = "0.5.0"
|
|
14
|
+
__all__ = [
|
|
15
|
+
"Act",
|
|
16
|
+
"Adapter",
|
|
17
|
+
"Frame",
|
|
18
|
+
"PortStop",
|
|
19
|
+
"Receipt",
|
|
20
|
+
"Session",
|
|
21
|
+
"StateCut",
|
|
22
|
+
"ExecutionPoint",
|
|
23
|
+
"NumericalContract",
|
|
24
|
+
"SlotSpec",
|
|
25
|
+
"StateAddress",
|
|
26
|
+
"SurfaceManifest",
|
|
27
|
+
"TransitionSpec",
|
|
28
|
+
]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Optional native adapters. Import a specific module to load its framework.
|
|
2
|
+
|
|
3
|
+
``load`` is a small dispatcher that selects a native adapter by ``model_type``:
|
|
4
|
+
|
|
5
|
+
from saturn.adapters import load
|
|
6
|
+
adapter = load("EleutherAI/pythia-70m")
|
|
7
|
+
|
|
8
|
+
Autoregressive decoder families (gpt2, gpt_neox, phi, llama, mistral, mixtral, gemma, qwen2,
|
|
9
|
+
qwen3) resolve to ``decoder.DecoderAdapter``; ``mamba`` resolves to ``mamba.MambaAdapter``.
|
|
10
|
+
Qwen2/Qwen2.5 also work through the dedicated ``qwen.QwenAdapter``. Importing this module does
|
|
11
|
+
not import PyTorch; the framework loads only when ``load`` (or a specific adapter) is used.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
_DECODER_FAMILIES = frozenset(
|
|
20
|
+
{"gpt2", "gpt_neox", "phi", "llama", "mistral", "mixtral", "gemma", "gemma2", "qwen2", "qwen3"}
|
|
21
|
+
)
|
|
22
|
+
_MAMBA_FAMILIES = frozenset({"mamba"})
|
|
23
|
+
_PEEK_KEYS = (
|
|
24
|
+
"revision",
|
|
25
|
+
"local_files_only",
|
|
26
|
+
"cache_dir",
|
|
27
|
+
"token",
|
|
28
|
+
"trust_remote_code",
|
|
29
|
+
"subfolder",
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def supported_families() -> tuple[str, ...]:
|
|
34
|
+
"""Model types the dispatcher can load."""
|
|
35
|
+
return tuple(sorted(_DECODER_FAMILIES | _MAMBA_FAMILIES))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _adapter_class(model_type: str | None) -> type:
|
|
39
|
+
if model_type in _MAMBA_FAMILIES:
|
|
40
|
+
from .mamba import MambaAdapter
|
|
41
|
+
|
|
42
|
+
return MambaAdapter
|
|
43
|
+
if model_type in _DECODER_FAMILIES:
|
|
44
|
+
from .decoder import DecoderAdapter
|
|
45
|
+
|
|
46
|
+
return DecoderAdapter
|
|
47
|
+
raise ValueError(
|
|
48
|
+
f"unregistered model_type: {model_type!r}; supported families are "
|
|
49
|
+
f"{', '.join(supported_families())}"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def load(path_or_model: Any, *, granularity: str = "layer", **kwargs: Any) -> Any:
|
|
54
|
+
"""Return a native adapter for a checkpoint path or an already-loaded HF model."""
|
|
55
|
+
if isinstance(path_or_model, (str, os.PathLike)):
|
|
56
|
+
from transformers import AutoConfig
|
|
57
|
+
|
|
58
|
+
peek = {key: kwargs[key] for key in _PEEK_KEYS if key in kwargs}
|
|
59
|
+
model_type = AutoConfig.from_pretrained(str(path_or_model), **peek).model_type
|
|
60
|
+
adapter_class = _adapter_class(model_type)
|
|
61
|
+
return adapter_class.from_pretrained(str(path_or_model), granularity=granularity, **kwargs)
|
|
62
|
+
model_type = getattr(getattr(path_or_model, "config", None), "model_type", None)
|
|
63
|
+
return _adapter_class(model_type)(path_or_model, granularity=granularity)
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Adapter-owned block-streamed weight residency for models larger than device memory.
|
|
2
|
+
|
|
3
|
+
Two modes share one call site:
|
|
4
|
+
|
|
5
|
+
``resident``
|
|
6
|
+
Frozen weights already live on the execution device; native modules are called
|
|
7
|
+
directly with zero overhead and unchanged numerics.
|
|
8
|
+
|
|
9
|
+
``streamed``
|
|
10
|
+
Frozen weights stay in host memory (optionally pinned). For each native module the
|
|
11
|
+
adapter copies exactly that module's parameters and buffers to the device, runs the
|
|
12
|
+
module functionally on the device, and lets the transient device copies fall out of
|
|
13
|
+
scope. The host weights themselves never move, so the adapter's frozen-model guard
|
|
14
|
+
(parameter ``id``/``_version``/``data_ptr``) still holds after every block.
|
|
15
|
+
|
|
16
|
+
Copying a parameter with ``Tensor.to(device)`` is a byte-preserving move (no dtype or
|
|
17
|
+
layout change), and ``torch.func.functional_call`` substitutes the supplied tensors
|
|
18
|
+
without altering the module, so a streamed block computes the same bits a resident block
|
|
19
|
+
would on the same device. That equality is proved by tests and measured on real weights.
|
|
20
|
+
|
|
21
|
+
Two optional transport refinements change only *when* and *which* bytes cross the bus,
|
|
22
|
+
never the arithmetic:
|
|
23
|
+
|
|
24
|
+
``prefetch`` (requires ``pin_host``)
|
|
25
|
+
Learns each module's successor from the call order (a decode visits embed, rotary,
|
|
26
|
+
layers, norm, head in the same order every token) and copies the predicted next
|
|
27
|
+
module's weights on a side CUDA stream while the current module computes. The compute
|
|
28
|
+
stream waits on that copy's event before use. A wrong prediction only wastes a copy.
|
|
29
|
+
|
|
30
|
+
``host_embedding``
|
|
31
|
+
An ``nn.Embedding`` lookup is a row gather. Streamed residency would otherwise copy the
|
|
32
|
+
whole table (1.24 GB for Qwen3-8B) to read a handful of rows; this gathers the rows in
|
|
33
|
+
host memory and copies only them. A gather moves bytes and does no arithmetic, so the
|
|
34
|
+
output bytes are those of the device lookup.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
from typing import Any
|
|
40
|
+
|
|
41
|
+
import torch
|
|
42
|
+
from torch.func import functional_call
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BlockResidency:
|
|
46
|
+
"""Place frozen weights for a declared residency and run native modules under it."""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
device: Any,
|
|
51
|
+
*,
|
|
52
|
+
mode: str = "resident",
|
|
53
|
+
pin_host: bool = False,
|
|
54
|
+
prefetch: bool = False,
|
|
55
|
+
host_embedding: bool = False,
|
|
56
|
+
):
|
|
57
|
+
if mode not in {"resident", "streamed"}:
|
|
58
|
+
raise ValueError("residency mode must be 'resident' or 'streamed'")
|
|
59
|
+
device = torch.device(device)
|
|
60
|
+
if device.type == "cuda" and device.index is None:
|
|
61
|
+
# A bare "cuda" has index None, but tensors moved to it become "cuda:N";
|
|
62
|
+
# resolve the concrete index so state device checks compare equal.
|
|
63
|
+
device = torch.device("cuda", torch.cuda.current_device())
|
|
64
|
+
self.device = device
|
|
65
|
+
self.mode = mode
|
|
66
|
+
self.pin_host = bool(pin_host)
|
|
67
|
+
self.prefetch = bool(prefetch)
|
|
68
|
+
self.host_embedding = bool(host_embedding)
|
|
69
|
+
if pin_host and mode != "streamed":
|
|
70
|
+
raise ValueError("host pinning only applies to streamed residency")
|
|
71
|
+
if pin_host and self.device.type != "cuda":
|
|
72
|
+
raise ValueError("host pinning is only useful for a CUDA execution device")
|
|
73
|
+
if (prefetch or host_embedding) and mode != "streamed":
|
|
74
|
+
raise ValueError("prefetch and host embedding only apply to streamed residency")
|
|
75
|
+
if prefetch and not pin_host:
|
|
76
|
+
raise ValueError("prefetch needs pin_host=True: pageable copies cannot overlap")
|
|
77
|
+
# Modules smaller than this (rotary tables, norms) are copied inline and kept out of
|
|
78
|
+
# the successor chain: a decoder calls rotary before every layer, so chaining it
|
|
79
|
+
# would make every layer's successor "rotary" and drop the staged layer each time.
|
|
80
|
+
self.prefetch_min_bytes = 4 << 20
|
|
81
|
+
self._module_bytes: dict[int, int] = {}
|
|
82
|
+
self._successor: dict[int, Any] = {}
|
|
83
|
+
self._previous: Any = None
|
|
84
|
+
self._staged: dict[int, tuple[dict[str, torch.Tensor], Any]] = {}
|
|
85
|
+
self._copy_stream = torch.cuda.Stream(device=self.device) if self.prefetch else None
|
|
86
|
+
self.stats = {"prefetch_hits": 0, "prefetch_misses": 0, "prefetch_wasted": 0,
|
|
87
|
+
"host_embedding_calls": 0}
|
|
88
|
+
|
|
89
|
+
def place(self, *modules: Any) -> BlockResidency:
|
|
90
|
+
"""Position frozen weights for this residency; call before freezing identity.
|
|
91
|
+
|
|
92
|
+
``resident`` moves weights onto the execution device (matching direct calls).
|
|
93
|
+
``streamed`` parks weights in host memory and optionally pins them so later
|
|
94
|
+
device copies are asynchronous. Pinning reassigns storage, so this must run
|
|
95
|
+
before the adapter records its frozen-parameter guard.
|
|
96
|
+
"""
|
|
97
|
+
for module in modules:
|
|
98
|
+
if module is None:
|
|
99
|
+
continue
|
|
100
|
+
if self.mode == "resident":
|
|
101
|
+
module.to(self.device)
|
|
102
|
+
else:
|
|
103
|
+
module.to("cpu")
|
|
104
|
+
if self.pin_host:
|
|
105
|
+
for parameter in module.parameters(recurse=True):
|
|
106
|
+
if not parameter.data.is_pinned():
|
|
107
|
+
parameter.data = parameter.data.pin_memory()
|
|
108
|
+
return self
|
|
109
|
+
|
|
110
|
+
def _copy(self, module: Any) -> dict[str, torch.Tensor]:
|
|
111
|
+
tensors: dict[str, torch.Tensor] = {}
|
|
112
|
+
for name, parameter in module.named_parameters():
|
|
113
|
+
tensors[name] = parameter.to(self.device, non_blocking=self.pin_host)
|
|
114
|
+
for name, buffer in module.named_buffers():
|
|
115
|
+
tensors[name] = buffer.to(self.device, non_blocking=self.pin_host)
|
|
116
|
+
return tensors
|
|
117
|
+
|
|
118
|
+
def _stage(self, module: Any) -> None:
|
|
119
|
+
"""Start copying ``module`` on the side stream (it waits for nothing on compute)."""
|
|
120
|
+
key = id(module)
|
|
121
|
+
if key in self._staged or self._copy_stream is None:
|
|
122
|
+
return
|
|
123
|
+
with torch.cuda.stream(self._copy_stream):
|
|
124
|
+
tensors = self._copy(module)
|
|
125
|
+
event = torch.cuda.Event()
|
|
126
|
+
event.record(self._copy_stream)
|
|
127
|
+
self._staged[key] = (tensors, event)
|
|
128
|
+
|
|
129
|
+
def _bytes(self, module: Any) -> int:
|
|
130
|
+
key = id(module)
|
|
131
|
+
size = self._module_bytes.get(key)
|
|
132
|
+
if size is None:
|
|
133
|
+
size = sum(t.numel() * t.element_size() for t in module.parameters()) + sum(
|
|
134
|
+
t.numel() * t.element_size() for t in module.buffers()
|
|
135
|
+
)
|
|
136
|
+
self._module_bytes[key] = size
|
|
137
|
+
return size
|
|
138
|
+
|
|
139
|
+
def _fetch(self, module: Any) -> dict[str, torch.Tensor]:
|
|
140
|
+
if self._copy_stream is None or self._bytes(module) < self.prefetch_min_bytes:
|
|
141
|
+
return self._copy(module)
|
|
142
|
+
# Learn the successor edge, then serve this module from its staged copy if present.
|
|
143
|
+
if self._previous is not None:
|
|
144
|
+
self._successor[id(self._previous)] = module
|
|
145
|
+
self._previous = module
|
|
146
|
+
staged = self._staged.pop(id(module), None)
|
|
147
|
+
for key in list(self._staged): # a mispredicted copy is dropped, never reused
|
|
148
|
+
self._staged.pop(key)
|
|
149
|
+
self.stats["prefetch_wasted"] += 1
|
|
150
|
+
compute = torch.cuda.current_stream(self.device)
|
|
151
|
+
if staged is None:
|
|
152
|
+
self.stats["prefetch_misses"] += 1
|
|
153
|
+
self._stage(module)
|
|
154
|
+
staged = self._staged.pop(id(module))
|
|
155
|
+
else:
|
|
156
|
+
self.stats["prefetch_hits"] += 1
|
|
157
|
+
tensors, event = staged
|
|
158
|
+
compute.wait_event(event)
|
|
159
|
+
for tensor in tensors.values():
|
|
160
|
+
# Memory allocated on the copy stream is used on the compute stream: keep the
|
|
161
|
+
# caching allocator from handing it out again before compute is done with it.
|
|
162
|
+
tensor.record_stream(compute)
|
|
163
|
+
nxt = self._successor.get(id(module))
|
|
164
|
+
if nxt is not None:
|
|
165
|
+
self._stage(nxt)
|
|
166
|
+
return tensors
|
|
167
|
+
|
|
168
|
+
def run(self, module: Any, *args: Any, **kwargs: Any) -> Any:
|
|
169
|
+
"""Execute ``module`` under the declared residency, returning native output."""
|
|
170
|
+
if self.mode == "resident":
|
|
171
|
+
return module(*args, **kwargs)
|
|
172
|
+
if (
|
|
173
|
+
self.host_embedding
|
|
174
|
+
and isinstance(module, torch.nn.Embedding)
|
|
175
|
+
and module.max_norm is None
|
|
176
|
+
and not kwargs
|
|
177
|
+
and len(args) == 1
|
|
178
|
+
):
|
|
179
|
+
self.stats["host_embedding_calls"] += 1
|
|
180
|
+
rows = module(args[0].to("cpu"))
|
|
181
|
+
return rows.to(self.device, non_blocking=False)
|
|
182
|
+
return functional_call(module, self._fetch(module), args, kwargs)
|
|
183
|
+
|
|
184
|
+
def to_dict(self) -> dict[str, Any]:
|
|
185
|
+
out = {
|
|
186
|
+
"mode": self.mode,
|
|
187
|
+
"device": {"type": self.device.type, "index": self.device.index},
|
|
188
|
+
"host_pinned": self.pin_host,
|
|
189
|
+
}
|
|
190
|
+
# Transport-only options are recorded only when on, so receipts written before they
|
|
191
|
+
# existed stay byte-identical.
|
|
192
|
+
if self.prefetch:
|
|
193
|
+
out["prefetch"] = True
|
|
194
|
+
if self.host_embedding:
|
|
195
|
+
out["host_embedding"] = True
|
|
196
|
+
return out
|