RamTorch 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.
- ramtorch-0.1.0/LICENSE +201 -0
- ramtorch-0.1.0/PKG-INFO +16 -0
- ramtorch-0.1.0/README.md +2 -0
- ramtorch-0.1.0/RamTorch.egg-info/PKG-INFO +16 -0
- ramtorch-0.1.0/RamTorch.egg-info/SOURCES.txt +12 -0
- ramtorch-0.1.0/RamTorch.egg-info/dependency_links.txt +1 -0
- ramtorch-0.1.0/RamTorch.egg-info/top_level.txt +1 -0
- ramtorch-0.1.0/pyproject.toml +19 -0
- ramtorch-0.1.0/ramtorch/__init__.py +0 -0
- ramtorch-0.1.0/ramtorch/helpers.py +0 -0
- ramtorch-0.1.0/ramtorch/modules/__init__.py +0 -0
- ramtorch-0.1.0/ramtorch/modules/linear.py +204 -0
- ramtorch-0.1.0/ramtorch/zero1.py +66 -0
- ramtorch-0.1.0/setup.cfg +4 -0
ramtorch-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
ramtorch-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: RamTorch
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: RAM is All You Need
|
|
5
|
+
Author-email: Lodestone <lodestone.rock@gmail.com>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/lodestone-rock/RamTorch
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# RamTorch
|
|
16
|
+
RAM is all you need
|
ramtorch-0.1.0/README.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: RamTorch
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: RAM is All You Need
|
|
5
|
+
Author-email: Lodestone <lodestone.rock@gmail.com>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/lodestone-rock/RamTorch
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# RamTorch
|
|
16
|
+
RAM is all you need
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
RamTorch.egg-info/PKG-INFO
|
|
5
|
+
RamTorch.egg-info/SOURCES.txt
|
|
6
|
+
RamTorch.egg-info/dependency_links.txt
|
|
7
|
+
RamTorch.egg-info/top_level.txt
|
|
8
|
+
ramtorch/__init__.py
|
|
9
|
+
ramtorch/helpers.py
|
|
10
|
+
ramtorch/zero1.py
|
|
11
|
+
ramtorch/modules/__init__.py
|
|
12
|
+
ramtorch/modules/linear.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ramtorch
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=45", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "RamTorch"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
authors = [{name = "Lodestone", email = "lodestone.rock@gmail.com"}]
|
|
9
|
+
description = "RAM is All You Need"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = {text = "Apache-2.0"}
|
|
12
|
+
requires-python = ">=3.8"
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Operating System :: OS Independent",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Homepage = "https://github.com/lodestone-rock/RamTorch"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CPU Linear Module
|
|
3
|
+
|
|
4
|
+
A memory-efficient linear layer implementation that keeps parameters on CPU
|
|
5
|
+
and transfers them to GPU on-demand using asynchronous CUDA streams.
|
|
6
|
+
|
|
7
|
+
This approach interleave compute and data transfer, making it useful for:
|
|
8
|
+
- Very large models that don't fit in GPU memory
|
|
9
|
+
- Scenarios where GPU memory is limited but CPU memory is abundant
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import torch
|
|
14
|
+
import torch.nn as nn
|
|
15
|
+
import torch.nn.functional as F
|
|
16
|
+
|
|
17
|
+
# Global CUDA stream for asynchronous weight transfers
|
|
18
|
+
# Using a dedicated stream allows transfers to overlap with computation
|
|
19
|
+
TRANSFER_STREAM = torch.cuda.Stream()
|
|
20
|
+
|
|
21
|
+
# Maximum number of in-flight transfers to prevent unbounded memory growth
|
|
22
|
+
# Can be configured via environment variable
|
|
23
|
+
MAX_INFLIGHT = int(os.getenv("MAX_INFLIGHT", 2))
|
|
24
|
+
|
|
25
|
+
# Queue to track pending transfer events for synchronization
|
|
26
|
+
PENDING_EVENTS = []
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BouncingLinearFn(torch.autograd.Function):
|
|
30
|
+
"""
|
|
31
|
+
Custom autograd function implementing the bouncing linear operation.
|
|
32
|
+
|
|
33
|
+
This function handles:
|
|
34
|
+
1. Asynchronous transfer of weights from CPU to GPU
|
|
35
|
+
2. Throttling of concurrent transfers to manage memory
|
|
36
|
+
3. Proper synchronization between transfer and compute streams
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
@staticmethod
|
|
40
|
+
def forward(ctx, x, weight_cpu, bias_cpu, device="cuda"):
|
|
41
|
+
"""
|
|
42
|
+
Forward pass of bouncing linear layer.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
ctx: PyTorch autograd context for saving backward pass info
|
|
46
|
+
x (torch.Tensor): Input tensor on GPU
|
|
47
|
+
weight_cpu (torch.Tensor): Weight matrix stored on CPU
|
|
48
|
+
bias_cpu (torch.Tensor, optional): Bias vector stored on CPU
|
|
49
|
+
device (str): Target GPU device for computation
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
torch.Tensor: Linear transformation output (x @ weight.T + bias)
|
|
53
|
+
|
|
54
|
+
Flow:
|
|
55
|
+
1. Initiate async transfer of weights to GPU
|
|
56
|
+
2. Record completion event and add to pending queue
|
|
57
|
+
3. Throttle if too many transfers are in-flight
|
|
58
|
+
4. Wait for transfer completion before computation
|
|
59
|
+
5. Perform linear operation and return result
|
|
60
|
+
"""
|
|
61
|
+
global PENDING_EVENTS
|
|
62
|
+
|
|
63
|
+
# enqueue transfer on transfer stream
|
|
64
|
+
with torch.cuda.stream(TRANSFER_STREAM):
|
|
65
|
+
w = weight_cpu.to(device, non_blocking=True)
|
|
66
|
+
b = bias_cpu.to(device, non_blocking=True) if bias_cpu is not None else None
|
|
67
|
+
|
|
68
|
+
# record event after transfer
|
|
69
|
+
evt = torch.cuda.Event()
|
|
70
|
+
evt.record(TRANSFER_STREAM)
|
|
71
|
+
PENDING_EVENTS.append(evt)
|
|
72
|
+
|
|
73
|
+
# throttle: wait if too many inflight
|
|
74
|
+
if len(PENDING_EVENTS) > MAX_INFLIGHT:
|
|
75
|
+
PENDING_EVENTS[0].synchronize()
|
|
76
|
+
PENDING_EVENTS.pop(0)
|
|
77
|
+
|
|
78
|
+
# make compute stream wait for this transfer
|
|
79
|
+
torch.cuda.current_stream().wait_event(evt)
|
|
80
|
+
|
|
81
|
+
out = F.linear(x, w, b)
|
|
82
|
+
|
|
83
|
+
# save for backward
|
|
84
|
+
ctx.save_for_backward(x, weight_cpu, bias_cpu)
|
|
85
|
+
ctx.device = device
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
@staticmethod
|
|
89
|
+
def backward(ctx, grad_out):
|
|
90
|
+
"""
|
|
91
|
+
Backward pass for gradient computation.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
ctx: Autograd context containing saved forward pass data
|
|
95
|
+
grad_out (torch.Tensor): Gradient w.r.t. layer output
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
tuple: Gradients w.r.t. (input, weight, bias, device)
|
|
99
|
+
Device gradient is None (not differentiable)
|
|
100
|
+
|
|
101
|
+
Note:
|
|
102
|
+
Weights need to be transferred again for gradient computation
|
|
103
|
+
since they're not kept on GPU between forward and backward passes.
|
|
104
|
+
"""
|
|
105
|
+
global PENDING_EVENTS
|
|
106
|
+
x, weight_cpu, bias_cpu = ctx.saved_tensors
|
|
107
|
+
device = ctx.device
|
|
108
|
+
|
|
109
|
+
# enqueue transfer on transfer stream
|
|
110
|
+
with torch.cuda.stream(TRANSFER_STREAM):
|
|
111
|
+
w = weight_cpu.to(device, non_blocking=True)
|
|
112
|
+
evt = torch.cuda.Event()
|
|
113
|
+
evt.record(TRANSFER_STREAM)
|
|
114
|
+
PENDING_EVENTS.append(evt)
|
|
115
|
+
|
|
116
|
+
# throttle: wait if too many inflight
|
|
117
|
+
if len(PENDING_EVENTS) > MAX_INFLIGHT:
|
|
118
|
+
PENDING_EVENTS[0].synchronize()
|
|
119
|
+
PENDING_EVENTS.pop(0)
|
|
120
|
+
|
|
121
|
+
torch.cuda.current_stream().wait_event(evt)
|
|
122
|
+
|
|
123
|
+
# grad computation
|
|
124
|
+
grad_input = grad_out @ w
|
|
125
|
+
grad_weight = grad_out.t() @ x
|
|
126
|
+
grad_bias = grad_out.sum(0) if bias_cpu is not None else None
|
|
127
|
+
|
|
128
|
+
return grad_input, grad_weight, grad_bias, None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class CPUBouncingLinear(nn.Module):
|
|
132
|
+
"""
|
|
133
|
+
Linear layer with CPU-stored parameters that bounce to GPU on demand.
|
|
134
|
+
|
|
135
|
+
This module provides a drop-in replacement for nn.Linear but with different
|
|
136
|
+
memory characteristics:
|
|
137
|
+
- Parameters stored on CPU (using shared memory for multiprocessing)
|
|
138
|
+
- Transferred to GPU only during forward/backward passes
|
|
139
|
+
- Automatic cleanup after each operation
|
|
140
|
+
|
|
141
|
+
Trade-offs:
|
|
142
|
+
+ Drastically reduced GPU memory usage
|
|
143
|
+
+ Enables training much larger models
|
|
144
|
+
- Requires batching to mask the latency
|
|
145
|
+
|
|
146
|
+
Best suited for:
|
|
147
|
+
- Models too large for GPU memory
|
|
148
|
+
- Inference scenarios with memory constraints
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
def __init__(self, in_features, out_features, bias=True, device="cuda"):
|
|
152
|
+
"""
|
|
153
|
+
Initialize CPU linear layer.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
in_features (int): Input feature dimension
|
|
157
|
+
out_features (int): Output feature dimension
|
|
158
|
+
bias (bool): Whether to include learnable bias term
|
|
159
|
+
device (str): Target GPU device for computation
|
|
160
|
+
|
|
161
|
+
Note:
|
|
162
|
+
Parameters are initialized on CPU with proper weight initialization.
|
|
163
|
+
share_memory_() enables efficient sharing in multiprocessing contexts.
|
|
164
|
+
"""
|
|
165
|
+
super().__init__()
|
|
166
|
+
self.in_features = in_features
|
|
167
|
+
self.out_features = out_features
|
|
168
|
+
self.device = device
|
|
169
|
+
|
|
170
|
+
# parameters live on CPU
|
|
171
|
+
self.weight = nn.Parameter(
|
|
172
|
+
torch.empty(out_features, in_features, device="cpu").share_memory_()
|
|
173
|
+
)
|
|
174
|
+
self.bias = (
|
|
175
|
+
nn.Parameter(torch.empty(out_features, device="cpu").share_memory_())
|
|
176
|
+
if bias
|
|
177
|
+
else None
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
# init
|
|
181
|
+
nn.init.kaiming_uniform_(self.weight, a=5**0.5)
|
|
182
|
+
if self.bias is not None:
|
|
183
|
+
fan_in = in_features
|
|
184
|
+
bound = 1 / fan_in**0.5
|
|
185
|
+
nn.init.uniform_(self.bias, -bound, bound)
|
|
186
|
+
|
|
187
|
+
def forward(self, x):
|
|
188
|
+
"""
|
|
189
|
+
Forward pass through CPU linear layer.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
x (torch.Tensor): Input tensor (should be on GPU)
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
torch.Tensor: Linear transformation output
|
|
196
|
+
|
|
197
|
+
Note:
|
|
198
|
+
Input tensor should already be on the target GPU device.
|
|
199
|
+
The autograd function handles all weight transfer logic.
|
|
200
|
+
"""
|
|
201
|
+
return BouncingLinearFn.apply(x, self.weight, self.bias, self.device)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
Linear = CPUBouncingLinear
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from typing import List, Dict, Any, Tuple
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
import torch.distributed as dist
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def create_zero_param_groups(
|
|
8
|
+
param_groups: List[Dict[str, Any]], rank: int, world_size: int
|
|
9
|
+
) -> Tuple[List[Dict[str, Any]], List[int]]:
|
|
10
|
+
"""
|
|
11
|
+
Create parameter groups for ZeRO-1 optimizer sharding and generate a map
|
|
12
|
+
of parameter owners for broadcasting.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
param_groups: Original parameter groups (list of dicts with 'params' key)
|
|
16
|
+
rank: Current process rank
|
|
17
|
+
world_size: Total number of processes
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
A tuple containing:
|
|
21
|
+
- List of parameter groups containing only parameters owned by this rank.
|
|
22
|
+
- A list where the index corresponds to a parameter's global index and
|
|
23
|
+
the value is the rank of the process that owns it. This is the pre-computed
|
|
24
|
+
index for the broadcast function.
|
|
25
|
+
"""
|
|
26
|
+
if not dist.is_initialized():
|
|
27
|
+
raise RuntimeError("torch.distributed must be initialized")
|
|
28
|
+
|
|
29
|
+
sharded_groups = []
|
|
30
|
+
owner_ranks = []
|
|
31
|
+
global_param_idx = 0
|
|
32
|
+
|
|
33
|
+
for group in param_groups:
|
|
34
|
+
# Copy all group settings except params
|
|
35
|
+
sharded_group = {k: v for k, v in group.items() if k != "params"}
|
|
36
|
+
sharded_group["params"] = []
|
|
37
|
+
|
|
38
|
+
# Add only parameters owned by this rank
|
|
39
|
+
for param in group["params"]:
|
|
40
|
+
owner_rank = global_param_idx % world_size
|
|
41
|
+
owner_ranks.append(owner_rank)
|
|
42
|
+
|
|
43
|
+
if owner_rank == rank:
|
|
44
|
+
sharded_group["params"].append(param)
|
|
45
|
+
global_param_idx += 1
|
|
46
|
+
|
|
47
|
+
# Only add group if it has parameters for this rank
|
|
48
|
+
if sharded_group["params"]:
|
|
49
|
+
sharded_groups.append(sharded_group)
|
|
50
|
+
|
|
51
|
+
return sharded_groups, owner_ranks
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def broadcast_zero_params(all_params: List[torch.Tensor], owner_ranks: List[int]):
|
|
55
|
+
"""
|
|
56
|
+
Broadcast updated parameters from their owning ranks to all other ranks
|
|
57
|
+
using a pre-computed index of owner ranks.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
all_params: List of all model parameters (in the same order across all ranks)
|
|
61
|
+
owner_ranks: A list mapping each parameter's global index to its owner rank.
|
|
62
|
+
"""
|
|
63
|
+
with torch.no_grad():
|
|
64
|
+
for i, param in enumerate(all_params):
|
|
65
|
+
owner_rank = owner_ranks[i]
|
|
66
|
+
dist.broadcast(param.data, src=owner_rank)
|
ramtorch-0.1.0/setup.cfg
ADDED