rgpu 0.1.0__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 (39) hide show
  1. rgpu-0.1.0/LICENSE +202 -0
  2. rgpu-0.1.0/PKG-INFO +35 -0
  3. rgpu-0.1.0/README.md +15 -0
  4. rgpu-0.1.0/pyproject.toml +39 -0
  5. rgpu-0.1.0/rgpu/__init__.py +18 -0
  6. rgpu-0.1.0/rgpu/autocast.py +140 -0
  7. rgpu-0.1.0/rgpu/compile.py +169 -0
  8. rgpu-0.1.0/rgpu/device.py +120 -0
  9. rgpu-0.1.0/rgpu/dispatch.py +277 -0
  10. rgpu-0.1.0/rgpu/server/__init__.py +1 -0
  11. rgpu-0.1.0/rgpu/server/__main__.py +193 -0
  12. rgpu-0.1.0/rgpu/server/graphs.py +60 -0
  13. rgpu-0.1.0/rgpu/server/ops.py +31 -0
  14. rgpu-0.1.0/rgpu/server/session.py +231 -0
  15. rgpu-0.1.0/rgpu/session.py +371 -0
  16. rgpu-0.1.0/rgpu/tensor.py +127 -0
  17. rgpu-0.1.0/rgpu/wire.py +390 -0
  18. rgpu-0.1.0/rgpu.egg-info/PKG-INFO +35 -0
  19. rgpu-0.1.0/rgpu.egg-info/SOURCES.txt +37 -0
  20. rgpu-0.1.0/rgpu.egg-info/dependency_links.txt +1 -0
  21. rgpu-0.1.0/rgpu.egg-info/entry_points.txt +3 -0
  22. rgpu-0.1.0/rgpu.egg-info/requires.txt +5 -0
  23. rgpu-0.1.0/rgpu.egg-info/top_level.txt +2 -0
  24. rgpu-0.1.0/rgpu_run.py +127 -0
  25. rgpu-0.1.0/setup.cfg +4 -0
  26. rgpu-0.1.0/tests/test_aliasing.py +97 -0
  27. rgpu-0.1.0/tests/test_amp.py +74 -0
  28. rgpu-0.1.0/tests/test_compile.py +228 -0
  29. rgpu-0.1.0/tests/test_complex.py +100 -0
  30. rgpu-0.1.0/tests/test_connection.py +458 -0
  31. rgpu-0.1.0/tests/test_device.py +187 -0
  32. rgpu-0.1.0/tests/test_ladder.py +50 -0
  33. rgpu-0.1.0/tests/test_memory.py +52 -0
  34. rgpu-0.1.0/tests/test_reconnect.py +205 -0
  35. rgpu-0.1.0/tests/test_run.py +79 -0
  36. rgpu-0.1.0/tests/test_server_net.py +189 -0
  37. rgpu-0.1.0/tests/test_server_session.py +147 -0
  38. rgpu-0.1.0/tests/test_training.py +100 -0
  39. rgpu-0.1.0/tests/test_wire.py +111 -0
rgpu-0.1.0/LICENSE ADDED
@@ -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.
rgpu-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: rgpu
3
+ Version: 0.1.0
4
+ Summary: A PyTorch device whose tensors live on a remote GPU
5
+ Author: Yan Michalevsky
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Documentation, https://rgpu.pages.dev/docs/
8
+ Project-URL: Source, https://github.com/ymcrcat/rgpu
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: torch>=2.14
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest>=8; extra == "test"
18
+ Requires-Dist: torchvision; extra == "test"
19
+ Dynamic: license-file
20
+
21
+ # rgpu
22
+
23
+ A PyTorch device whose tensors live on a remote GPU. Train on a laptop with
24
+ `device="rgpu"` while the work runs on a GPU host you reach over SSH.
25
+
26
+ ```sh
27
+ pip install rgpu
28
+ ```
29
+
30
+ The GPU host runs `rgpu-opserver`; the laptop runs your script through
31
+ `rgpu-run --server 127.0.0.1:9720 python train.py`. The protocol has no
32
+ authentication, so keep the server on localhost and reach it through an SSH
33
+ tunnel.
34
+
35
+ Documentation: https://rgpu.pages.dev/docs/
rgpu-0.1.0/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # rgpu
2
+
3
+ A PyTorch device whose tensors live on a remote GPU. Train on a laptop with
4
+ `device="rgpu"` while the work runs on a GPU host you reach over SSH.
5
+
6
+ ```sh
7
+ pip install rgpu
8
+ ```
9
+
10
+ The GPU host runs `rgpu-opserver`; the laptop runs your script through
11
+ `rgpu-run --server 127.0.0.1:9720 python train.py`. The protocol has no
12
+ authentication, so keep the server on localhost and reach it through an SSH
13
+ tunnel.
14
+
15
+ Documentation: https://rgpu.pages.dev/docs/
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "rgpu"
7
+ version = "0.1.0"
8
+ description = "A PyTorch device whose tensors live on a remote GPU"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Yan Michalevsky" }]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Operating System :: OS Independent",
16
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
17
+ ]
18
+ requires-python = ">=3.10"
19
+ dependencies = ["torch>=2.14"]
20
+
21
+ [project.urls]
22
+ Documentation = "https://rgpu.pages.dev/docs/"
23
+ Source = "https://github.com/ymcrcat/rgpu"
24
+
25
+ [project.optional-dependencies]
26
+ test = ["pytest>=8", "torchvision"]
27
+
28
+ [project.scripts]
29
+ rgpu-opserver = "rgpu.server.__main__:main"
30
+ rgpu-run = "rgpu_run:main"
31
+
32
+ [tool.setuptools]
33
+ # A top-level module on purpose: the launcher only opens an ssh tunnel and
34
+ # spawns a child, so importing the rgpu package - which registers the device
35
+ # and pulls in torch, about three seconds - would be pure startup cost.
36
+ py-modules = ["rgpu_run"]
37
+
38
+ [tool.setuptools.packages.find]
39
+ include = ["rgpu*"]
@@ -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"]
@@ -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])
@@ -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())