rgpu 0.1.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.
- rgpu/__init__.py +18 -0
- rgpu/autocast.py +140 -0
- rgpu/compile.py +169 -0
- rgpu/device.py +120 -0
- rgpu/dispatch.py +277 -0
- rgpu/server/__init__.py +1 -0
- rgpu/server/__main__.py +193 -0
- rgpu/server/graphs.py +60 -0
- rgpu/server/ops.py +31 -0
- rgpu/server/session.py +231 -0
- rgpu/session.py +371 -0
- rgpu/tensor.py +127 -0
- rgpu/wire.py +390 -0
- rgpu-0.1.0.dist-info/METADATA +35 -0
- rgpu-0.1.0.dist-info/RECORD +20 -0
- rgpu-0.1.0.dist-info/WHEEL +5 -0
- rgpu-0.1.0.dist-info/entry_points.txt +3 -0
- rgpu-0.1.0.dist-info/licenses/LICENSE +202 -0
- rgpu-0.1.0.dist-info/top_level.txt +2 -0
- rgpu_run.py +127 -0
rgpu/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""A PyTorch device whose tensors live on a remote GPU.
|
|
2
|
+
|
|
3
|
+
import rgpu, torch
|
|
4
|
+
x = torch.randn(1024, 1024, device="rgpu") # the data is on the server
|
|
5
|
+
y = (x @ x).relu().sum().item() # one round trip, at .item()
|
|
6
|
+
|
|
7
|
+
Set RGPU_OPSERVER=host:port to reach rgpu-opserver (default 127.0.0.1:9720),
|
|
8
|
+
normally through an ssh tunnel: the server has no authentication.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from .device import register_device as _register_device
|
|
12
|
+
|
|
13
|
+
_register_device()
|
|
14
|
+
|
|
15
|
+
from .compile import compile_backend # noqa: E402
|
|
16
|
+
from .session import RemoteError, SessionLost, stats # noqa: E402
|
|
17
|
+
|
|
18
|
+
__all__ = ["RemoteError", "SessionLost", "compile_backend", "stats"]
|
rgpu/autocast.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Autocast for rgpu: which ops run in half precision and which stay float32.
|
|
2
|
+
|
|
3
|
+
PyTorch ships an autocast policy only for its own devices. A new device gets
|
|
4
|
+
none, and under autocast every op fails until something is registered at its
|
|
5
|
+
Autocast key. This registers a fallthrough for everything, then kernels for a
|
|
6
|
+
documented subset of what PyTorch registers for AutocastCUDA: LOWER runs in
|
|
7
|
+
the autocast dtype, FP32 widens half inputs back to float32, and BANNED
|
|
8
|
+
raises the way CUDA does. Everything else falls through uncast.
|
|
9
|
+
|
|
10
|
+
Falling through is right for most of what is missing, because much of CUDA's
|
|
11
|
+
list is CompositeImplicitAutograd and decomposes into ops that are covered -
|
|
12
|
+
einsum and layer_norm were checked and come out as they do on CUDA. These are
|
|
13
|
+
the differences that remain, where rgpu is not CUDA:
|
|
14
|
+
|
|
15
|
+
- grid_sampler and the RNN cells (lstm_cell, gru_cell, rnn_tanh_cell,
|
|
16
|
+
rnn_relu_cell, and the fused _thnn_* forms), which CUDA runs in the
|
|
17
|
+
autocast dtype and rgpu leaves alone.
|
|
18
|
+
- dot, vdot, bilinear and conv_tbc, likewise on CUDA's lower-precision list
|
|
19
|
+
and not here.
|
|
20
|
+
- CUDA's whole "promote" category, which runs an op at the widest dtype
|
|
21
|
+
among its inputs: addcmul, addcdiv, atan2, cross, index_put, scatter_add
|
|
22
|
+
and the upsample_* family. On rgpu a mix of float16 and float32 inputs
|
|
23
|
+
reaches them unpromoted.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import torch
|
|
27
|
+
from torch.utils._pytree import tree_map
|
|
28
|
+
|
|
29
|
+
# Ops that run in the autocast dtype (PyTorch's CUDA "lower precision" list).
|
|
30
|
+
LOWER = [
|
|
31
|
+
"mm", "addmm", "bmm", "baddbmm", "addbmm", "addmv", "addr", "matmul", "mv",
|
|
32
|
+
"linear", "conv1d", "conv2d", "conv3d", "conv_transpose1d", "conv_transpose2d",
|
|
33
|
+
"conv_transpose3d", "convolution", "_convolution", "prelu", "chain_matmul",
|
|
34
|
+
"linalg_multi_dot", "scaled_dot_product_attention",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
# Ops whose half-precision inputs are widened to float32 (the CUDA fp32 list).
|
|
38
|
+
FP32 = [
|
|
39
|
+
"acos", "asin", "cosh", "erfinv", "exp", "expm1", "log", "log10", "log2",
|
|
40
|
+
"log1p", "reciprocal", "rsqrt", "sinh", "tan", "pow", "softplus", "layer_norm",
|
|
41
|
+
"group_norm", "norm", "nuclear_norm", "cosine_similarity", "poisson_nll_loss",
|
|
42
|
+
"cosine_embedding_loss", "nll_loss", "nll_loss2d", "hinge_embedding_loss",
|
|
43
|
+
"kl_div", "l1_loss", "smooth_l1_loss", "huber_loss", "mse_loss",
|
|
44
|
+
"margin_ranking_loss", "multilabel_margin_loss", "soft_margin_loss",
|
|
45
|
+
"triplet_margin_loss", "multi_margin_loss", "binary_cross_entropy_with_logits",
|
|
46
|
+
"dist", "pdist", "cdist", "renorm", "logsumexp", "softmax", "log_softmax",
|
|
47
|
+
"cross_entropy_loss", "cumprod", "cumsum", "prod", "sum",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
# Ops CUDA refuses under autocast rather than casting, because they are
|
|
51
|
+
# unsafe in half precision. Running one anyway would diverge silently from a
|
|
52
|
+
# local GPU, so rgpu refuses them with the same advice.
|
|
53
|
+
BANNED = {
|
|
54
|
+
"binary_cross_entropy": (
|
|
55
|
+
"torch.nn.functional.binary_cross_entropy and torch.nn.BCELoss are unsafe to "
|
|
56
|
+
"autocast. Many models use a sigmoid layer right before the binary cross "
|
|
57
|
+
"entropy layer. In this case, combine the two layers using "
|
|
58
|
+
"torch.nn.functional.binary_cross_entropy_with_logits or "
|
|
59
|
+
"torch.nn.BCEWithLogitsLoss. binary_cross_entropy_with_logits and "
|
|
60
|
+
"BCEWithLogits are safe to autocast."),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
_KEY = torch._C.DispatchKey.AutocastPrivateUse1
|
|
64
|
+
_libs = []
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _kernel(op, target, eligible):
|
|
68
|
+
def kernel(*args, **kwargs):
|
|
69
|
+
dtype = target()
|
|
70
|
+
|
|
71
|
+
def cast(x):
|
|
72
|
+
if (isinstance(x, torch.Tensor) and x.device.type == "rgpu"
|
|
73
|
+
and eligible(x.dtype) and x.dtype != dtype):
|
|
74
|
+
return x.to(dtype)
|
|
75
|
+
return x
|
|
76
|
+
|
|
77
|
+
with torch._C._ExcludeDispatchKeyGuard(torch._C.DispatchKeySet(_KEY)):
|
|
78
|
+
return op(*tree_map(cast, args), **tree_map(cast, kwargs))
|
|
79
|
+
|
|
80
|
+
return kernel
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _refusing_kernel(message):
|
|
84
|
+
def kernel(*args, **kwargs):
|
|
85
|
+
raise RuntimeError(message)
|
|
86
|
+
|
|
87
|
+
return kernel
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _has_out_argument(schema):
|
|
91
|
+
"""True if any argument writes into a tensor the caller passed in.
|
|
92
|
+
|
|
93
|
+
An out= kernel's cast() would allocate a fresh cast tensor, compute into
|
|
94
|
+
that, and leave the caller's out tensor untouched - silently wrong
|
|
95
|
+
values, no exception. PyTorch's own CUDA autocast policy does not cover
|
|
96
|
+
out= variants either, so - like CUDA - they fall through to the uncast
|
|
97
|
+
path instead of getting a cast kernel here.
|
|
98
|
+
"""
|
|
99
|
+
return any(a.alias_info is not None and a.alias_info.is_write for a in schema.arguments)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def install():
|
|
103
|
+
if _libs:
|
|
104
|
+
return
|
|
105
|
+
everything = torch.library.Library("_", "IMPL")
|
|
106
|
+
everything.fallback(torch.library.fallthrough_kernel, "AutocastPrivateUse1")
|
|
107
|
+
lib = torch.library.Library("aten", "IMPL")
|
|
108
|
+
|
|
109
|
+
def lower_eligible(dt):
|
|
110
|
+
return dt.is_floating_point and dt != torch.float64
|
|
111
|
+
|
|
112
|
+
def fp32_eligible(dt):
|
|
113
|
+
return dt in (torch.float16, torch.bfloat16)
|
|
114
|
+
|
|
115
|
+
for names, target, eligible in [
|
|
116
|
+
(LOWER, lambda: torch.get_autocast_dtype("rgpu"), lower_eligible),
|
|
117
|
+
(FP32, lambda: torch.float32, fp32_eligible),
|
|
118
|
+
]:
|
|
119
|
+
for name in names:
|
|
120
|
+
packet = getattr(torch.ops.aten, name, None)
|
|
121
|
+
if packet is None:
|
|
122
|
+
continue
|
|
123
|
+
for overload in packet.overloads():
|
|
124
|
+
op = getattr(packet, overload)
|
|
125
|
+
if _has_out_argument(op._schema):
|
|
126
|
+
continue
|
|
127
|
+
qualified = name if overload == "default" else f"{name}.{overload}"
|
|
128
|
+
lib.impl(qualified, _kernel(op, target, eligible), "AutocastPrivateUse1")
|
|
129
|
+
|
|
130
|
+
for name, message in BANNED.items():
|
|
131
|
+
packet = getattr(torch.ops.aten, name, None)
|
|
132
|
+
if packet is None:
|
|
133
|
+
continue
|
|
134
|
+
# Every overload, out= included: this kernel computes nothing, so the
|
|
135
|
+
# reason out= variants are skipped above does not apply.
|
|
136
|
+
for overload in packet.overloads():
|
|
137
|
+
qualified = name if overload == "default" else f"{name}.{overload}"
|
|
138
|
+
lib.impl(qualified, _refusing_kernel(message), "AutocastPrivateUse1")
|
|
139
|
+
|
|
140
|
+
_libs.extend([everything, lib])
|
rgpu/compile.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""torch.compile for rgpu: ship the graph once, then one message per call.
|
|
2
|
+
|
|
3
|
+
The backend hooks aot_autograd, which hands over forward and backward graphs
|
|
4
|
+
of aten ops. Each is serialized with the same op names and argument encoding
|
|
5
|
+
as eager ops, sent once, and compiled on the server. After that a call is a
|
|
6
|
+
single CALL message, and it streams: output shapes come from the traced
|
|
7
|
+
graph, so nothing has to wait for them.
|
|
8
|
+
|
|
9
|
+
Compiled code works on the unwrapped meta tensors, never on RemoteTensor
|
|
10
|
+
itself, which is why each tensor's id lives on its meta tensor: inputs are
|
|
11
|
+
looked up by it and outputs are given one.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import itertools
|
|
15
|
+
import logging
|
|
16
|
+
import operator
|
|
17
|
+
|
|
18
|
+
import torch
|
|
19
|
+
from torch._dynamo.backends.common import aot_autograd
|
|
20
|
+
from torch.utils._pytree import tree_map
|
|
21
|
+
|
|
22
|
+
from . import session, wire
|
|
23
|
+
from .tensor import RemoteTensor, id_of, meta_like, register
|
|
24
|
+
|
|
25
|
+
log = logging.getLogger("rgpu")
|
|
26
|
+
_graph_ids = itertools.count(1)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Unshippable(Exception):
|
|
30
|
+
"""A graph containing something the wire cannot carry."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class UnsupportedOp(Unshippable):
|
|
34
|
+
"""An op in the graph that rgpu-opserver would refuse to run.
|
|
35
|
+
|
|
36
|
+
Unlike the other refusals this one has no eager fallback. Running the
|
|
37
|
+
graph through the ordinary dispatch path posts the very same op as a RUN,
|
|
38
|
+
and the server resolves ops by name and runs only aten ops, so it fails
|
|
39
|
+
there instead - later, and with a worse message. Raising at compile time
|
|
40
|
+
says the true thing: this cannot run on rgpu at all.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def serialize(gm):
|
|
45
|
+
nodes, index = [], {}
|
|
46
|
+
|
|
47
|
+
def ref(a):
|
|
48
|
+
if isinstance(a, torch.fx.Node):
|
|
49
|
+
return wire.NodeRef(index[a])
|
|
50
|
+
if isinstance(a, torch.Tensor):
|
|
51
|
+
raise Unshippable("a constant tensor inside the graph")
|
|
52
|
+
if isinstance(a, torch.device):
|
|
53
|
+
# An rgpu tensor is a meta tensor on this side, so a graph traced
|
|
54
|
+
# through one allocates on "meta". On the server that means rgpu.
|
|
55
|
+
return wire.Dev("rgpu" if a.type in ("rgpu", "meta") else str(a))
|
|
56
|
+
if isinstance(a, (torch.SymInt, torch.SymFloat)):
|
|
57
|
+
raise Unshippable("dynamic shapes; compile with dynamic=False")
|
|
58
|
+
try:
|
|
59
|
+
wire.encode(a)
|
|
60
|
+
except wire.EncodeError as e:
|
|
61
|
+
raise Unshippable(str(e)) from None
|
|
62
|
+
return a
|
|
63
|
+
|
|
64
|
+
for n in gm.graph.nodes:
|
|
65
|
+
if n.op == "placeholder":
|
|
66
|
+
nodes.append(["placeholder"])
|
|
67
|
+
elif n.op == "call_function":
|
|
68
|
+
t = n.target
|
|
69
|
+
if t is operator.getitem:
|
|
70
|
+
# Not an op: how a graph picks one output of an op that has
|
|
71
|
+
# several, which aot_autograd writes for max_pool2d_with_indices,
|
|
72
|
+
# native_batch_norm and the rest. It travels as its own kind of
|
|
73
|
+
# node, so the server still runs nothing but aten ops.
|
|
74
|
+
src, i = n.args
|
|
75
|
+
if not isinstance(src, torch.fx.Node) or not isinstance(i, int):
|
|
76
|
+
raise Unshippable(f"getitem with a {type(i).__name__} index")
|
|
77
|
+
nodes.append(["getitem", wire.NodeRef(index[src]), i])
|
|
78
|
+
index[n] = len(nodes) - 1
|
|
79
|
+
continue
|
|
80
|
+
if not isinstance(t, torch._ops.OpOverload):
|
|
81
|
+
# A plain Python callable: not shippable as part of a graph,
|
|
82
|
+
# but the ops it calls are, so eager still works.
|
|
83
|
+
raise Unshippable(f"{t} is not an aten op")
|
|
84
|
+
if t.namespace != "aten":
|
|
85
|
+
raise UnsupportedOp(
|
|
86
|
+
f"{t._schema.name}.{t._overloadname} cannot run on rgpu: "
|
|
87
|
+
"rgpu-opserver runs aten ops only, so a custom op has nowhere "
|
|
88
|
+
"to run, compiled or eager")
|
|
89
|
+
nodes.append(["call", t._schema.name, t._overloadname,
|
|
90
|
+
tree_map(ref, list(n.args)),
|
|
91
|
+
{k: tree_map(ref, v) for k, v in n.kwargs.items()}])
|
|
92
|
+
elif n.op == "output":
|
|
93
|
+
outs = n.args[0] if isinstance(n.args[0], (list, tuple)) else [n.args[0]]
|
|
94
|
+
nodes.append(["output", [tree_map(ref, o) for o in outs]])
|
|
95
|
+
else:
|
|
96
|
+
raise Unshippable(f"a {n.op} node")
|
|
97
|
+
index[n] = len(nodes) - 1
|
|
98
|
+
return nodes
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _output_values(gm):
|
|
102
|
+
out = next(n for n in gm.graph.nodes if n.op == "output")
|
|
103
|
+
outs = out.args[0] if isinstance(out.args[0], (list, tuple)) else [out.args[0]]
|
|
104
|
+
return [o.meta.get("val") if isinstance(o, torch.fx.Node) else o for o in outs]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _boxed(fn):
|
|
108
|
+
def run(args):
|
|
109
|
+
return fn(*args)
|
|
110
|
+
run._boxed_call = True
|
|
111
|
+
return run
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _ship(gid, nodes, compiler, mode):
|
|
115
|
+
session.get().post(wire.COMPILE, gid, nodes, compiler, mode)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _eager(gm):
|
|
119
|
+
"""Run a graph that cannot be shipped op by op, through the normal path."""
|
|
120
|
+
def run(*inner):
|
|
121
|
+
wrapped = [RemoteTensor(x) if isinstance(x, torch.Tensor) else x for x in inner]
|
|
122
|
+
outs = gm(*wrapped)
|
|
123
|
+
return [o._rgpu_meta if isinstance(o, RemoteTensor) else o for o in outs]
|
|
124
|
+
return _boxed(run)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _compiler(mode, compiler):
|
|
128
|
+
def compile_graph(gm, example_inputs):
|
|
129
|
+
try:
|
|
130
|
+
nodes = serialize(gm)
|
|
131
|
+
values = _output_values(gm)
|
|
132
|
+
if any(isinstance(s, torch.SymInt) for v in values
|
|
133
|
+
if isinstance(v, torch.Tensor) for s in v.shape):
|
|
134
|
+
raise Unshippable("dynamic shapes; compile with dynamic=False")
|
|
135
|
+
except UnsupportedOp:
|
|
136
|
+
raise # no eager fallback exists for this one; see UnsupportedOp
|
|
137
|
+
except Unshippable as e:
|
|
138
|
+
log.warning("rgpu: running a graph eagerly because it has %s", e)
|
|
139
|
+
return _eager(gm)
|
|
140
|
+
gid = next(_graph_ids)
|
|
141
|
+
_ship(gid, nodes, compiler, mode)
|
|
142
|
+
|
|
143
|
+
def run(*inputs):
|
|
144
|
+
in_ids = [id_of(x) for x in inputs]
|
|
145
|
+
outs, out_ids = [], []
|
|
146
|
+
for v in values:
|
|
147
|
+
if isinstance(v, torch.Tensor):
|
|
148
|
+
m = meta_like(v.dtype, list(v.shape), list(v.stride()), v.storage_offset(),
|
|
149
|
+
v.is_conj(), v.is_neg())
|
|
150
|
+
out_ids.append(register(m))
|
|
151
|
+
outs.append(m)
|
|
152
|
+
else:
|
|
153
|
+
out_ids.append(None)
|
|
154
|
+
outs.append(v)
|
|
155
|
+
session.get().post(wire.CALL, gid, in_ids, out_ids)
|
|
156
|
+
return outs
|
|
157
|
+
|
|
158
|
+
return _boxed(run)
|
|
159
|
+
|
|
160
|
+
return compile_graph
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def compile_backend(mode=None, compiler="inductor"):
|
|
164
|
+
"""A torch.compile backend that compiles on the rgpu server."""
|
|
165
|
+
comp = _compiler(mode, compiler)
|
|
166
|
+
return aot_autograd(fw_compiler=comp, bw_compiler=comp)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
torch._dynamo.register_backend(name="rgpu")(compile_backend())
|
rgpu/device.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Makes "rgpu" a PyTorch device, from Python alone.
|
|
2
|
+
|
|
3
|
+
PyTorch reserves one device slot for backends outside it (PrivateUse1). Its
|
|
4
|
+
Python-backend hook, marked experimental, registers the device guard and
|
|
5
|
+
hooks a backend would otherwise have to write in C++.
|
|
6
|
+
|
|
7
|
+
Factory functions - torch.zeros(..., device="rgpu") and the like - have no
|
|
8
|
+
tensor argument to dispatch on, so they need kernels of their own. Every
|
|
9
|
+
factory op is registered, not just empty: ops such as arange build an empty
|
|
10
|
+
tensor and resize it through out=, and a wrapper's shape is fixed when it is
|
|
11
|
+
made, so going through empty would leave it describing a size-zero tensor.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import types
|
|
15
|
+
|
|
16
|
+
import torch
|
|
17
|
+
|
|
18
|
+
from . import session, wire
|
|
19
|
+
from .tensor import RemoteTensor, register
|
|
20
|
+
|
|
21
|
+
_SKIP_FACTORIES = ("sparse", "quantized", "cudnn", "mkldnn", "nested", "_make_dep_token",
|
|
22
|
+
"from_file")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def synchronize(device=None):
|
|
26
|
+
session.get().request(wire.SYNC)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def manual_seed(seed):
|
|
30
|
+
session.get().post(wire.SEED, int(seed))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _set_device(device):
|
|
34
|
+
index = device.index if isinstance(device, torch.device) else device
|
|
35
|
+
if index not in (0, None):
|
|
36
|
+
raise ValueError("rgpu has one device, rgpu:0")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _module():
|
|
40
|
+
m = types.ModuleType("torch.rgpu")
|
|
41
|
+
m.is_available = lambda: True
|
|
42
|
+
m.device_count = lambda: 1
|
|
43
|
+
m.current_device = lambda: 0
|
|
44
|
+
m.set_device = _set_device
|
|
45
|
+
m.is_initialized = lambda: True
|
|
46
|
+
m._is_in_bad_fork = lambda: False
|
|
47
|
+
m.synchronize = synchronize
|
|
48
|
+
m.manual_seed = manual_seed
|
|
49
|
+
m.manual_seed_all = manual_seed
|
|
50
|
+
m.get_amp_supported_dtype = lambda: [torch.float16, torch.bfloat16]
|
|
51
|
+
return m
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _factory_kernel(op):
|
|
55
|
+
name, overload = op._schema.name, op._overloadname
|
|
56
|
+
|
|
57
|
+
def kernel(*args, **kwargs):
|
|
58
|
+
meta_kwargs = dict(kwargs)
|
|
59
|
+
meta_kwargs["device"] = torch.device("meta")
|
|
60
|
+
if "pin_memory" in meta_kwargs:
|
|
61
|
+
meta_kwargs["pin_memory"] = None
|
|
62
|
+
meta = op(*args, **meta_kwargs)
|
|
63
|
+
wire_kwargs = {k: v for k, v in kwargs.items() if k != "pin_memory"}
|
|
64
|
+
wire_kwargs["device"] = wire.Dev("rgpu")
|
|
65
|
+
session.get().post(wire.RUN, name, overload, list(args), wire_kwargs, [register(meta)])
|
|
66
|
+
return RemoteTensor(meta)
|
|
67
|
+
|
|
68
|
+
return kernel
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _copy_from_kernel(self, dst, non_blocking=False):
|
|
72
|
+
"""Fills a tensor this backend just made, in place of copy_.
|
|
73
|
+
|
|
74
|
+
torch.tensor(data, device="rgpu") builds the destination through a
|
|
75
|
+
factory kernel above, then reaches PrivateUse1's _copy_from directly
|
|
76
|
+
rather than going through __torch_dispatch__ - the same aten op that
|
|
77
|
+
the ordinary CPU->rgpu path already runs as copy_.default.
|
|
78
|
+
"""
|
|
79
|
+
from . import dispatch
|
|
80
|
+
return dispatch.handle(torch.ops.aten.copy_.default, (dst, self, non_blocking), {})
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _factories():
|
|
84
|
+
"""Every aten overload with a device argument and no tensor arguments."""
|
|
85
|
+
for full in torch._C._dispatch_get_all_op_names():
|
|
86
|
+
if not full.startswith("aten::") or any(s in full for s in _SKIP_FACTORIES):
|
|
87
|
+
continue
|
|
88
|
+
name, _, overload = full[len("aten::"):].partition(".")
|
|
89
|
+
try:
|
|
90
|
+
op = getattr(getattr(torch.ops.aten, name), overload or "default")
|
|
91
|
+
except (AttributeError, RuntimeError):
|
|
92
|
+
continue
|
|
93
|
+
schema = op._schema
|
|
94
|
+
if len(schema.returns) != 1 or "Tensor" not in str(schema.returns[0].type):
|
|
95
|
+
continue
|
|
96
|
+
if not any(a.name == "device" for a in schema.arguments):
|
|
97
|
+
continue
|
|
98
|
+
if any("Tensor" in str(a.type) for a in schema.arguments):
|
|
99
|
+
continue
|
|
100
|
+
yield full[len("aten::"):], op
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
_libs = []
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def register_device():
|
|
107
|
+
if _libs:
|
|
108
|
+
return
|
|
109
|
+
torch.utils.backend_registration._setup_privateuseone_for_python_backend(
|
|
110
|
+
"rgpu", backend_module=_module())
|
|
111
|
+
lib = torch.library.Library("aten", "IMPL")
|
|
112
|
+
for qualified, op in _factories():
|
|
113
|
+
lib.impl(qualified, _factory_kernel(op), "PrivateUse1")
|
|
114
|
+
# torch.tensor(data, device="rgpu") calls this directly, bypassing
|
|
115
|
+
# __torch_dispatch__: see _copy_from_kernel.
|
|
116
|
+
lib.impl("_copy_from", _copy_from_kernel, "PrivateUse1")
|
|
117
|
+
_libs.append(lib) # registrations live only as long as the Library object
|
|
118
|
+
|
|
119
|
+
from . import autocast
|
|
120
|
+
autocast.install()
|