lupine 2.2.0__py3-none-win_amd64.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.
- lupine/__init__.py +284 -0
- lupine/_backend/__init__.py +39 -0
- lupine/_backend/csrc/backend.h +31 -0
- lupine/_backend/csrc/host.cpp +541 -0
- lupine/_backend/csrc/module.cpp +160 -0
- lupine/_backend/device.py +157 -0
- lupine/_backend/ext.py +190 -0
- lupine/_backend/native/__init__.py +952 -0
- lupine/_backend/native/aten.py +104 -0
- lupine/_backend/native/cudnn.py +201 -0
- lupine/_backend/native/runtime.py +254 -0
- lupine/_backend/setup.py +43 -0
- lupine/_libs/nvcuda.dll +0 -0
- lupine/_libs/nvml.dll +0 -0
- lupine/_native.py +192 -0
- lupine-2.2.0.dist-info/METADATA +249 -0
- lupine-2.2.0.dist-info/RECORD +18 -0
- lupine-2.2.0.dist-info/WHEEL +4 -0
lupine/__init__.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""PyTorch adapter for LUPINE-backed CUDA devices.
|
|
2
|
+
|
|
3
|
+
``lupine.connect(...)`` points the process at one or more LUPINE GPU
|
|
4
|
+
servers and preloads the native client the wheel carries (the CUDA driver
|
|
5
|
+
API and NVML) so ordinary CUDA consumers — PyTorch included — transparently
|
|
6
|
+
run on the remote GPUs:
|
|
7
|
+
|
|
8
|
+
.. code-block:: python
|
|
9
|
+
|
|
10
|
+
import lupine
|
|
11
|
+
|
|
12
|
+
with lupine.connect(host="gpu-host:14833") as session:
|
|
13
|
+
import torch
|
|
14
|
+
|
|
15
|
+
x = torch.arange(8, device=session.device(), dtype=torch.float32)
|
|
16
|
+
print((x * 2).cpu())
|
|
17
|
+
|
|
18
|
+
The adapter returns ordinary ``torch.device("cuda:N")`` objects; PyTorch
|
|
19
|
+
keeps its built-in CUDA dispatch path, and its own CUDA runtime and
|
|
20
|
+
libraries run against the LUPINE driver shim underneath it. No NVIDIA driver
|
|
21
|
+
is required on the client.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import os
|
|
27
|
+
import sys
|
|
28
|
+
from collections.abc import Sequence
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
from typing import Any
|
|
31
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
32
|
+
|
|
33
|
+
DEFAULT_PORT = 14833
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class LupineError(RuntimeError):
|
|
37
|
+
"""Raised when the LUPINE adapter cannot select a usable device."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _torch() -> Any:
|
|
41
|
+
try:
|
|
42
|
+
import torch
|
|
43
|
+
except ModuleNotFoundError as exc:
|
|
44
|
+
raise LupineError("PyTorch is required to use LUPINE devices.") from exc
|
|
45
|
+
return torch
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _normalize_server(host: str, port: int | None = None) -> str:
|
|
49
|
+
host = str(host).strip()
|
|
50
|
+
if not host:
|
|
51
|
+
raise LupineError("host must not be empty")
|
|
52
|
+
if host.startswith(("http://", "https://")):
|
|
53
|
+
try:
|
|
54
|
+
parsed = urlsplit(host)
|
|
55
|
+
hostname = parsed.hostname
|
|
56
|
+
need_port = port is not None or (
|
|
57
|
+
parsed.scheme == "http" and parsed.port is None
|
|
58
|
+
)
|
|
59
|
+
except ValueError as exc:
|
|
60
|
+
raise LupineError("host must include a server name") from exc
|
|
61
|
+
if not hostname:
|
|
62
|
+
raise LupineError("host must include a server name")
|
|
63
|
+
netloc = parsed.netloc
|
|
64
|
+
if need_port:
|
|
65
|
+
endpoint_port = int(port) if port is not None else DEFAULT_PORT
|
|
66
|
+
if ":" in hostname and not hostname.startswith("["):
|
|
67
|
+
hostname = f"[{hostname}]"
|
|
68
|
+
userinfo, sep, _ = netloc.rpartition("@")
|
|
69
|
+
netloc = f"{userinfo}{sep}{hostname}:{endpoint_port}"
|
|
70
|
+
return urlunsplit(
|
|
71
|
+
(parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment)
|
|
72
|
+
)
|
|
73
|
+
if not host.startswith("[") and host.count(":") > 1:
|
|
74
|
+
host = f"[{host}]"
|
|
75
|
+
has_port = "]:" in host if host.startswith("[") else ":" in host
|
|
76
|
+
if has_port:
|
|
77
|
+
server, port_str = host.rsplit(":", 1)
|
|
78
|
+
else:
|
|
79
|
+
server, port_str = host, ""
|
|
80
|
+
if host.startswith("["):
|
|
81
|
+
if not server.endswith("]") or not server[1:-1].strip():
|
|
82
|
+
raise LupineError("host must include a server name")
|
|
83
|
+
elif not server:
|
|
84
|
+
raise LupineError("host must include a server name")
|
|
85
|
+
if port is not None:
|
|
86
|
+
# An explicit port replaces the one in the host, as it does for URLs.
|
|
87
|
+
return f"{server}:{int(port)}"
|
|
88
|
+
if has_port:
|
|
89
|
+
if not port_str:
|
|
90
|
+
raise LupineError("host port must not be empty")
|
|
91
|
+
return host
|
|
92
|
+
return f"{server}:{DEFAULT_PORT}"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _normalize_hosts(
|
|
96
|
+
host: str | Sequence[str], port: int | None = None
|
|
97
|
+
) -> tuple[str, ...]:
|
|
98
|
+
if isinstance(host, str):
|
|
99
|
+
return (_normalize_server(host, port),)
|
|
100
|
+
return tuple(_normalize_server(item, port) for item in host)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _servers_from_env() -> tuple[str, ...]:
|
|
104
|
+
value = os.environ.get("LUPINE_SERVER", "")
|
|
105
|
+
if not value:
|
|
106
|
+
return ()
|
|
107
|
+
return tuple(s for server in value.split(",") if (s := server.strip()))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class Session:
|
|
112
|
+
"""A process-local LUPINE connection declaration.
|
|
113
|
+
|
|
114
|
+
Entering the session exports ``LUPINE_SERVER`` and loads the selected
|
|
115
|
+
native shims; both stay in effect for the process after exit (library
|
|
116
|
+
unloading is not possible once CUDA state references the shims).
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
servers: tuple[str, ...]
|
|
120
|
+
# "driver" uses a CUDA-enabled torch; "torch" uses the native Lupine device.
|
|
121
|
+
backend: str = "driver"
|
|
122
|
+
_previous_server: str | None = field(default=None, repr=False)
|
|
123
|
+
_loaded: bool = field(default=False, repr=False)
|
|
124
|
+
|
|
125
|
+
def __enter__(self) -> Session: # noqa: PYI034
|
|
126
|
+
if not self.servers:
|
|
127
|
+
return self
|
|
128
|
+
if self._loaded:
|
|
129
|
+
# Already active (e.g. connect() entered before returning the
|
|
130
|
+
# session); re-entering must not reload or reset state.
|
|
131
|
+
return self
|
|
132
|
+
configured = _servers_from_env()
|
|
133
|
+
if configured and configured != self.servers:
|
|
134
|
+
raise LupineError(
|
|
135
|
+
"LUPINE_SERVER is already configured differently; start a new "
|
|
136
|
+
"process or pass the same hosts to lupine.connect()."
|
|
137
|
+
)
|
|
138
|
+
self._previous_server = os.environ.get("LUPINE_SERVER")
|
|
139
|
+
if not configured:
|
|
140
|
+
os.environ["LUPINE_SERVER"] = ",".join(self.servers)
|
|
141
|
+
if sys.platform == "darwin":
|
|
142
|
+
from . import _backend
|
|
143
|
+
|
|
144
|
+
_backend.start()
|
|
145
|
+
self.backend = "torch"
|
|
146
|
+
else:
|
|
147
|
+
from . import _native
|
|
148
|
+
|
|
149
|
+
_native.load(missing_ok=False)
|
|
150
|
+
self._loaded = True
|
|
151
|
+
return self
|
|
152
|
+
|
|
153
|
+
def _device_type(self) -> str:
|
|
154
|
+
return "lupine" if self.backend == "torch" else "cuda"
|
|
155
|
+
|
|
156
|
+
def _device_count(self) -> int:
|
|
157
|
+
torch = _torch()
|
|
158
|
+
return int(getattr(torch, self._device_type()).device_count())
|
|
159
|
+
|
|
160
|
+
def __exit__(self, exc_type: object, exc: object, tb: object) -> bool:
|
|
161
|
+
if self._previous_server is None:
|
|
162
|
+
os.environ.pop("LUPINE_SERVER", None)
|
|
163
|
+
else:
|
|
164
|
+
os.environ["LUPINE_SERVER"] = self._previous_server
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
def devices(self) -> list[Any]:
|
|
168
|
+
"""Return every GPU in LUPINE's virtual device topology."""
|
|
169
|
+
|
|
170
|
+
if not self.servers:
|
|
171
|
+
return []
|
|
172
|
+
if not self._loaded and not _native_loaded():
|
|
173
|
+
raise LupineError(
|
|
174
|
+
"Session is not active; use 'with lupine.connect(...) as s:'."
|
|
175
|
+
)
|
|
176
|
+
torch = _torch()
|
|
177
|
+
kind = self._device_type()
|
|
178
|
+
return [torch.device(kind, index) for index in range(self._device_count())]
|
|
179
|
+
|
|
180
|
+
def device(self, index: int = 0) -> Any:
|
|
181
|
+
"""Return one GPU from LUPINE's virtual device topology."""
|
|
182
|
+
|
|
183
|
+
torch = _torch()
|
|
184
|
+
count = self._device_count() if self.servers else 0
|
|
185
|
+
if index >= count or index < -count:
|
|
186
|
+
hint = ""
|
|
187
|
+
from . import _native
|
|
188
|
+
|
|
189
|
+
if count == 0 and _native.native_arm64_windows():
|
|
190
|
+
hint = (
|
|
191
|
+
"; this is a native arm64 Python on Windows on ARM, which has "
|
|
192
|
+
"no CUDA runtime: run an x64 Python (under the OS's x64 "
|
|
193
|
+
"emulation) with the x64 CUDA torch wheel"
|
|
194
|
+
)
|
|
195
|
+
raise LupineError(
|
|
196
|
+
f"device index {index} out of range ({count} devices){hint}"
|
|
197
|
+
)
|
|
198
|
+
return torch.device(self._device_type(), range(count)[index])
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _native_loaded() -> bool:
|
|
202
|
+
from . import _backend, _native
|
|
203
|
+
|
|
204
|
+
return bool(_native.loaded()) or _backend.is_started()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def connect(
|
|
208
|
+
*,
|
|
209
|
+
host: str | Sequence[str] | None = None,
|
|
210
|
+
port: int | None = None,
|
|
211
|
+
) -> Session:
|
|
212
|
+
"""Create a LUPINE session for one or more remote GPU hosts.
|
|
213
|
+
|
|
214
|
+
Use the session before any CUDA operation (including ``import torch``
|
|
215
|
+
on platforms where PyTorch eagerly resolves CUDA symbols):
|
|
216
|
+
|
|
217
|
+
``with lupine.connect(host=["a:14833", "b:14833"]) as s:``
|
|
218
|
+
|
|
219
|
+
``host`` defaults to ``LUPINE_SERVER``, which is how a launcher such as
|
|
220
|
+
``lupine run`` hands the session its already-bound hosts.
|
|
221
|
+
|
|
222
|
+
``s.devices()`` then returns every CUDA ordinal in LUPINE's virtual
|
|
223
|
+
device topology.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
if host is None:
|
|
227
|
+
host = _servers_from_env()
|
|
228
|
+
if not host:
|
|
229
|
+
raise LupineError("pass host=... or set LUPINE_SERVER")
|
|
230
|
+
|
|
231
|
+
session = Session(servers=_normalize_hosts(host, port))
|
|
232
|
+
# Bind immediately: the caller may import torch right after connect()
|
|
233
|
+
# without using the context manager form.
|
|
234
|
+
session.__enter__()
|
|
235
|
+
return session
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def devices() -> list[Any]:
|
|
239
|
+
"""Return devices in PyTorch's current LUPINE-backed CUDA topology."""
|
|
240
|
+
|
|
241
|
+
torch = _torch()
|
|
242
|
+
count = int(torch.cuda.device_count())
|
|
243
|
+
return [torch.device("cuda", index) for index in range(count)]
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def servers() -> tuple[str, ...]:
|
|
247
|
+
"""Return configured LUPINE servers from ``LUPINE_SERVER``."""
|
|
248
|
+
|
|
249
|
+
return _servers_from_env()
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def is_configured() -> bool:
|
|
253
|
+
"""Return true when ``LUPINE_SERVER`` names at least one server."""
|
|
254
|
+
|
|
255
|
+
return bool(servers())
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def load_native(*, missing_ok: bool = True) -> dict[str, str]:
|
|
259
|
+
"""Load the native shims; see :mod:`lupine._native`."""
|
|
260
|
+
|
|
261
|
+
from . import _native
|
|
262
|
+
|
|
263
|
+
return _native.load(missing_ok=missing_ok)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def libdir() -> Any:
|
|
267
|
+
"""Directory holding the native shims."""
|
|
268
|
+
|
|
269
|
+
from . import _native
|
|
270
|
+
|
|
271
|
+
return _native.libdir()
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
__all__ = [
|
|
275
|
+
"DEFAULT_PORT",
|
|
276
|
+
"LupineError",
|
|
277
|
+
"Session",
|
|
278
|
+
"connect",
|
|
279
|
+
"devices",
|
|
280
|
+
"is_configured",
|
|
281
|
+
"libdir",
|
|
282
|
+
"load_native",
|
|
283
|
+
"servers",
|
|
284
|
+
]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""The native Lupine PyTorch backend and its process-wide device state.
|
|
2
|
+
|
|
3
|
+
Metadata and autograd live in native PyTorch. Storage and arithmetic use
|
|
4
|
+
local CUDA dylibs and GPU kernels through the Lupine driver client.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
_started: dict[str, Any] = {}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _extension() -> Any:
|
|
15
|
+
from . import ext
|
|
16
|
+
|
|
17
|
+
return ext.load()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_started() -> bool:
|
|
21
|
+
backend = _started.get("backend")
|
|
22
|
+
return backend is not None and not backend.runtime.closed
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def info() -> dict[str, Any]:
|
|
26
|
+
return dict(_started.get("info", {}))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def start() -> dict[str, Any]:
|
|
30
|
+
from . import native
|
|
31
|
+
|
|
32
|
+
return native.start()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def close() -> None:
|
|
36
|
+
backend = _started.get("backend")
|
|
37
|
+
if backend is not None:
|
|
38
|
+
_extension().unregister()
|
|
39
|
+
backend.close()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Device registration for the torch backend: what libtorch demands in C++
|
|
2
|
+
// (allocator, device guard, hooks, generator, the metadata kernels). Every
|
|
3
|
+
// operator is implemented by the native Python bindings and GPU kernels.
|
|
4
|
+
#ifndef LUPINE_TORCH_BACKEND_H
|
|
5
|
+
#define LUPINE_TORCH_BACKEND_H
|
|
6
|
+
|
|
7
|
+
#include <cstdint>
|
|
8
|
+
|
|
9
|
+
namespace lupine_torch {
|
|
10
|
+
|
|
11
|
+
// A storage's data pointer is its handle shifted left, so Python reads the
|
|
12
|
+
// handle back from any tensor (untyped_storage().data_ptr() >> kHandleShift)
|
|
13
|
+
// while the native runtime maps each handle to a real CUDA allocation.
|
|
14
|
+
constexpr int kHandleShift = 20;
|
|
15
|
+
|
|
16
|
+
using release_fn = void (*)(uint64_t handle);
|
|
17
|
+
using sync_fn = void (*)();
|
|
18
|
+
|
|
19
|
+
// Register the native PrivateUse1 device. Release drops a storage allocation;
|
|
20
|
+
// sync waits for the native runtime through the device guard.
|
|
21
|
+
void register_backend(int device_count, release_fn release, sync_fn sync);
|
|
22
|
+
// Stops the callbacks (interpreter exit).
|
|
23
|
+
void clear_callbacks();
|
|
24
|
+
int device_count();
|
|
25
|
+
int current_device();
|
|
26
|
+
void set_device(int index);
|
|
27
|
+
int exchange_device(int index);
|
|
28
|
+
|
|
29
|
+
} // namespace lupine_torch
|
|
30
|
+
|
|
31
|
+
#endif
|