cjm-torch-plugin-utils 0.0.1__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.
@@ -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 2022, fastai
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.
@@ -0,0 +1,5 @@
1
+ include pyproject.toml
2
+ include LICENSE
3
+ include CONTRIBUTING.md
4
+ include README.md
5
+ recursive-exclude * __pycache__
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.4
2
+ Name: cjm-torch-plugin-utils
3
+ Version: 0.0.1
4
+ Summary: PyTorch helpers for cjm-plugin-system plugins: GPU memory release, typed CUDA-OOM handling, and device selection.
5
+ Author-email: "Christian J. Mills" <9126128+cj-mills@users.noreply.github.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/cj-mills/cjm-torch-plugin-utils
8
+ Project-URL: Documentation, https://cj-mills.github.io/cjm-torch-plugin-utils/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.12
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: cjm-plugin-system>=0.0.37
16
+ Requires-Dist: numpy
17
+ Requires-Dist: torch
18
+ Dynamic: license-file
19
+
20
+ # cjm-torch-plugin-utils
21
+
22
+
23
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
24
+
25
+ ## Install
26
+
27
+ ``` bash
28
+ pip install cjm_torch_plugin_utils
29
+ ```
30
+
31
+ ## Project Structure
32
+
33
+ nbs/
34
+ ├── device.ipynb # Resolve a device spec ("auto" / "cpu" / "cuda" / "cuda:N") to a concrete torch device string.
35
+ ├── memory.ipynb # Robust move-to-CPU + drop-references + gc + CUDA-cache cleanup for releasing models, factored out of the per-plugin reimplementations.
36
+ └── oom.ipynb # Convert torch CUDA out-of-memory exceptions into the substrate's typed `PluginResourceError` (SG-47 Track B) so CR-7 reactive retry can evict and reload.
37
+
38
+ Total: 3 notebooks
39
+
40
+ ## Module Dependencies
41
+
42
+ ``` mermaid
43
+ graph LR
44
+ device["device<br/>Device resolution"]
45
+ memory["memory<br/>GPU model release"]
46
+ oom["oom<br/>CUDA OOM handling"]
47
+ ```
48
+
49
+ No cross-module dependencies detected.
50
+
51
+ ## CLI Reference
52
+
53
+ No CLI commands found in this project.
54
+
55
+ ## Module Overview
56
+
57
+ Detailed documentation for each module in the project:
58
+
59
+ ### Device resolution (`device.ipynb`)
60
+
61
+ > Resolve a device spec (“auto” / “cpu” / “cuda” / “cuda:N”) to a
62
+ > concrete torch device string.
63
+
64
+ #### Import
65
+
66
+ ``` python
67
+ from cjm_torch_plugin_utils.device import (
68
+ resolve_torch_device
69
+ )
70
+ ```
71
+
72
+ #### Functions
73
+
74
+ ``` python
75
+ def resolve_torch_device(
76
+ spec: str = "auto", # Requested device: "auto", "cpu", "cuda", or "cuda:N"
77
+ ) -> str: # Concrete device string
78
+ """
79
+ Resolve a device spec to a concrete torch device string.
80
+
81
+ `"auto"` resolves to `"cuda"` when CUDA is available, else `"cpu"`. Any
82
+ explicit spec (`"cpu"`, `"cuda"`, `"cuda:0"`, ...) is returned unchanged.
83
+ """
84
+ ```
85
+
86
+ ### GPU model release (`memory.ipynb`)
87
+
88
+ > Robust move-to-CPU + drop-references + gc + CUDA-cache cleanup for
89
+ > releasing models, factored out of the per-plugin reimplementations.
90
+
91
+ #### Import
92
+
93
+ ``` python
94
+ from cjm_torch_plugin_utils.memory import (
95
+ release_model
96
+ )
97
+ ```
98
+
99
+ #### Functions
100
+
101
+ ``` python
102
+ def release_model(
103
+ obj: Any, # The plugin instance holding the model attribute(s)
104
+ model_attr_names: List[str], # Names of the attributes to release, in release order
105
+ device: str = "cuda", # Device the model is on; gates the CUDA-specific cleanup
106
+ *,
107
+ logger: logging.Logger, # Logger for best-effort failure reporting
108
+ ) -> None
109
+ """
110
+ Release one or more model objects: move to CPU, drop references, gc, free CUDA cache.
111
+
112
+ For each name in `model_attr_names`, if `obj` has a non-None attribute:
113
+ 1. when on CUDA, best-effort `.to('cpu')` (frees GPU tensors; skipped for
114
+ objects without a `.to` method, e.g. processors/tokenizers),
115
+ 2. `setattr(obj, name, None)` and drop the local reference.
116
+ Then a single `gc.collect()` and — on CUDA — `empty_cache()` + `synchronize()`.
117
+
118
+ Best-effort throughout: failures are logged and swallowed. Missing or
119
+ already-None attributes are skipped, so the call is idempotent.
120
+ """
121
+ ```
122
+
123
+ ### CUDA OOM handling (`oom.ipynb`)
124
+
125
+ > Convert torch CUDA out-of-memory exceptions into the substrate’s typed
126
+ > `PluginResourceError` (SG-47 Track B) so CR-7 reactive retry can evict
127
+ > and reload.
128
+
129
+ #### Import
130
+
131
+ ``` python
132
+ from cjm_torch_plugin_utils.oom import (
133
+ cuda_oom_to_plugin_resource_error
134
+ )
135
+ ```
136
+
137
+ #### Functions
138
+
139
+ ``` python
140
+ def cuda_oom_to_plugin_resource_error(
141
+ exc: BaseException, # The caught CUDA OOM exception (e.g. torch.cuda.OutOfMemoryError)
142
+ *,
143
+ label: str, # Context for the message, e.g. "loading model 'X'" or "inference"
144
+ headroom_mb: float = 100.0, # Best-effort margin added to `available` to estimate `needed`
145
+ ) -> PluginResourceError: # Typed error for the substrate's CR-7 reactive-retry path
146
+ """
147
+ Convert a CUDA out-of-memory exception into a substrate-typed `PluginResourceError`.
148
+
149
+ SG-47 Track B: a plugin's GPU inference / model-load site catches
150
+ `torch.cuda.OutOfMemoryError` and re-raises the result of this helper so the
151
+ substrate sees a typed resource error (evict + reload + retry via CR-7)
152
+ instead of an opaque crash.
153
+
154
+ `needed` is a best-effort estimate (`available + headroom_mb`): the true
155
+ required VRAM is unknowable from the exception, and CR-7 triggers eviction
156
+ regardless of magnitude, so an approximation above `available` is sufficient.
157
+
158
+ The caller raises the returned error, preserving the original cause:
159
+
160
+ try:
161
+ model = Model.from_pretrained(repo_id, ...)
162
+ except torch.cuda.OutOfMemoryError as e:
163
+ raise cuda_oom_to_plugin_resource_error(e, label=f"loading {repo_id!r}") from e
164
+ """
165
+ ```
@@ -0,0 +1,146 @@
1
+ # cjm-torch-plugin-utils
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ ## Install
7
+
8
+ ``` bash
9
+ pip install cjm_torch_plugin_utils
10
+ ```
11
+
12
+ ## Project Structure
13
+
14
+ nbs/
15
+ ├── device.ipynb # Resolve a device spec ("auto" / "cpu" / "cuda" / "cuda:N") to a concrete torch device string.
16
+ ├── memory.ipynb # Robust move-to-CPU + drop-references + gc + CUDA-cache cleanup for releasing models, factored out of the per-plugin reimplementations.
17
+ └── oom.ipynb # Convert torch CUDA out-of-memory exceptions into the substrate's typed `PluginResourceError` (SG-47 Track B) so CR-7 reactive retry can evict and reload.
18
+
19
+ Total: 3 notebooks
20
+
21
+ ## Module Dependencies
22
+
23
+ ``` mermaid
24
+ graph LR
25
+ device["device<br/>Device resolution"]
26
+ memory["memory<br/>GPU model release"]
27
+ oom["oom<br/>CUDA OOM handling"]
28
+ ```
29
+
30
+ No cross-module dependencies detected.
31
+
32
+ ## CLI Reference
33
+
34
+ No CLI commands found in this project.
35
+
36
+ ## Module Overview
37
+
38
+ Detailed documentation for each module in the project:
39
+
40
+ ### Device resolution (`device.ipynb`)
41
+
42
+ > Resolve a device spec (“auto” / “cpu” / “cuda” / “cuda:N”) to a
43
+ > concrete torch device string.
44
+
45
+ #### Import
46
+
47
+ ``` python
48
+ from cjm_torch_plugin_utils.device import (
49
+ resolve_torch_device
50
+ )
51
+ ```
52
+
53
+ #### Functions
54
+
55
+ ``` python
56
+ def resolve_torch_device(
57
+ spec: str = "auto", # Requested device: "auto", "cpu", "cuda", or "cuda:N"
58
+ ) -> str: # Concrete device string
59
+ """
60
+ Resolve a device spec to a concrete torch device string.
61
+
62
+ `"auto"` resolves to `"cuda"` when CUDA is available, else `"cpu"`. Any
63
+ explicit spec (`"cpu"`, `"cuda"`, `"cuda:0"`, ...) is returned unchanged.
64
+ """
65
+ ```
66
+
67
+ ### GPU model release (`memory.ipynb`)
68
+
69
+ > Robust move-to-CPU + drop-references + gc + CUDA-cache cleanup for
70
+ > releasing models, factored out of the per-plugin reimplementations.
71
+
72
+ #### Import
73
+
74
+ ``` python
75
+ from cjm_torch_plugin_utils.memory import (
76
+ release_model
77
+ )
78
+ ```
79
+
80
+ #### Functions
81
+
82
+ ``` python
83
+ def release_model(
84
+ obj: Any, # The plugin instance holding the model attribute(s)
85
+ model_attr_names: List[str], # Names of the attributes to release, in release order
86
+ device: str = "cuda", # Device the model is on; gates the CUDA-specific cleanup
87
+ *,
88
+ logger: logging.Logger, # Logger for best-effort failure reporting
89
+ ) -> None
90
+ """
91
+ Release one or more model objects: move to CPU, drop references, gc, free CUDA cache.
92
+
93
+ For each name in `model_attr_names`, if `obj` has a non-None attribute:
94
+ 1. when on CUDA, best-effort `.to('cpu')` (frees GPU tensors; skipped for
95
+ objects without a `.to` method, e.g. processors/tokenizers),
96
+ 2. `setattr(obj, name, None)` and drop the local reference.
97
+ Then a single `gc.collect()` and — on CUDA — `empty_cache()` + `synchronize()`.
98
+
99
+ Best-effort throughout: failures are logged and swallowed. Missing or
100
+ already-None attributes are skipped, so the call is idempotent.
101
+ """
102
+ ```
103
+
104
+ ### CUDA OOM handling (`oom.ipynb`)
105
+
106
+ > Convert torch CUDA out-of-memory exceptions into the substrate’s typed
107
+ > `PluginResourceError` (SG-47 Track B) so CR-7 reactive retry can evict
108
+ > and reload.
109
+
110
+ #### Import
111
+
112
+ ``` python
113
+ from cjm_torch_plugin_utils.oom import (
114
+ cuda_oom_to_plugin_resource_error
115
+ )
116
+ ```
117
+
118
+ #### Functions
119
+
120
+ ``` python
121
+ def cuda_oom_to_plugin_resource_error(
122
+ exc: BaseException, # The caught CUDA OOM exception (e.g. torch.cuda.OutOfMemoryError)
123
+ *,
124
+ label: str, # Context for the message, e.g. "loading model 'X'" or "inference"
125
+ headroom_mb: float = 100.0, # Best-effort margin added to `available` to estimate `needed`
126
+ ) -> PluginResourceError: # Typed error for the substrate's CR-7 reactive-retry path
127
+ """
128
+ Convert a CUDA out-of-memory exception into a substrate-typed `PluginResourceError`.
129
+
130
+ SG-47 Track B: a plugin's GPU inference / model-load site catches
131
+ `torch.cuda.OutOfMemoryError` and re-raises the result of this helper so the
132
+ substrate sees a typed resource error (evict + reload + retry via CR-7)
133
+ instead of an opaque crash.
134
+
135
+ `needed` is a best-effort estimate (`available + headroom_mb`): the true
136
+ required VRAM is unknowable from the exception, and CR-7 triggers eviction
137
+ regardless of magnitude, so an approximation above `available` is sufficient.
138
+
139
+ The caller raises the returned error, preserving the original cause:
140
+
141
+ try:
142
+ model = Model.from_pretrained(repo_id, ...)
143
+ except torch.cuda.OutOfMemoryError as e:
144
+ raise cuda_oom_to_plugin_resource_error(e, label=f"loading {repo_id!r}") from e
145
+ """
146
+ ```
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
@@ -0,0 +1,13 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/cjm-torch-plugin-utils',
5
+ 'doc_host': 'https://cj-mills.github.io',
6
+ 'git_url': 'https://github.com/cj-mills/cjm-torch-plugin-utils',
7
+ 'lib_path': 'cjm_torch_plugin_utils'},
8
+ 'syms': { 'cjm_torch_plugin_utils.device': { 'cjm_torch_plugin_utils.device.resolve_torch_device': ( 'device.html#resolve_torch_device',
9
+ 'cjm_torch_plugin_utils/device.py')},
10
+ 'cjm_torch_plugin_utils.memory': { 'cjm_torch_plugin_utils.memory.release_model': ( 'memory.html#release_model',
11
+ 'cjm_torch_plugin_utils/memory.py')},
12
+ 'cjm_torch_plugin_utils.oom': { 'cjm_torch_plugin_utils.oom.cuda_oom_to_plugin_resource_error': ( 'oom.html#cuda_oom_to_plugin_resource_error',
13
+ 'cjm_torch_plugin_utils/oom.py')}}}
@@ -0,0 +1,24 @@
1
+ """Resolve a device spec ("auto" / "cpu" / "cuda" / "cuda:N") to a concrete torch device string.
2
+
3
+ Docs: https://cj-mills.github.io/cjm-torch-plugin-utilsdevice.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/device.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['resolve_torch_device']
9
+
10
+ # %% ../nbs/device.ipynb #exports
11
+ import torch
12
+
13
+ # %% ../nbs/device.ipynb #resolve-device
14
+ def resolve_torch_device(
15
+ spec: str = "auto", # Requested device: "auto", "cpu", "cuda", or "cuda:N"
16
+ ) -> str: # Concrete device string
17
+ """Resolve a device spec to a concrete torch device string.
18
+
19
+ `"auto"` resolves to `"cuda"` when CUDA is available, else `"cpu"`. Any
20
+ explicit spec (`"cpu"`, `"cuda"`, `"cuda:0"`, ...) is returned unchanged.
21
+ """
22
+ if spec != "auto":
23
+ return spec
24
+ return "cuda" if torch.cuda.is_available() else "cpu"
@@ -0,0 +1,55 @@
1
+ """Robust move-to-CPU + drop-references + gc + CUDA-cache cleanup for releasing models, factored out of the per-plugin reimplementations.
2
+
3
+ Docs: https://cj-mills.github.io/cjm-torch-plugin-utilsmemory.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/memory.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['release_model']
9
+
10
+ # %% ../nbs/memory.ipynb #exports
11
+ import gc
12
+ import logging
13
+ from typing import Any, List
14
+
15
+ import torch
16
+
17
+ # %% ../nbs/memory.ipynb #release-model
18
+ def release_model(
19
+ obj: Any, # The plugin instance holding the model attribute(s)
20
+ model_attr_names: List[str], # Names of the attributes to release, in release order
21
+ device: str = "cuda", # Device the model is on; gates the CUDA-specific cleanup
22
+ *,
23
+ logger: logging.Logger, # Logger for best-effort failure reporting
24
+ ) -> None:
25
+ """Release one or more model objects: move to CPU, drop references, gc, free CUDA cache.
26
+
27
+ For each name in `model_attr_names`, if `obj` has a non-None attribute:
28
+ 1. when on CUDA, best-effort `.to('cpu')` (frees GPU tensors; skipped for
29
+ objects without a `.to` method, e.g. processors/tokenizers),
30
+ 2. `setattr(obj, name, None)` and drop the local reference.
31
+ Then a single `gc.collect()` and — on CUDA — `empty_cache()` + `synchronize()`.
32
+
33
+ Best-effort throughout: failures are logged and swallowed. Missing or
34
+ already-None attributes are skipped, so the call is idempotent.
35
+ """
36
+ on_cuda = device.startswith("cuda")
37
+ for name in model_attr_names:
38
+ val = getattr(obj, name, None)
39
+ if val is None:
40
+ continue
41
+ if on_cuda:
42
+ try:
43
+ if hasattr(val, "to"):
44
+ val.to("cpu")
45
+ except Exception as e:
46
+ logger.warning(f"release_model: .to('cpu') failed for {name!r}: {e}")
47
+ setattr(obj, name, None)
48
+ del val
49
+ gc.collect()
50
+ if on_cuda and torch.cuda.is_available():
51
+ try:
52
+ torch.cuda.empty_cache()
53
+ torch.cuda.synchronize()
54
+ except Exception as e:
55
+ logger.debug(f"release_model: CUDA cleanup failed: {e}")
@@ -0,0 +1,54 @@
1
+ """Convert torch CUDA out-of-memory exceptions into the substrate's typed `PluginResourceError` (SG-47 Track B) so CR-7 reactive retry can evict and reload.
2
+
3
+ Docs: https://cj-mills.github.io/cjm-torch-plugin-utilsoom.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/oom.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['cuda_oom_to_plugin_resource_error']
9
+
10
+ # %% ../nbs/oom.ipynb #exports
11
+ import torch
12
+
13
+ from cjm_plugin_system.core.errors import PluginResourceError, ResourceShortfall
14
+
15
+ # %% ../nbs/oom.ipynb #cuda-oom
16
+ def cuda_oom_to_plugin_resource_error(
17
+ exc: BaseException, # The caught CUDA OOM exception (e.g. torch.cuda.OutOfMemoryError)
18
+ *,
19
+ label: str, # Context for the message, e.g. "loading model 'X'" or "inference"
20
+ headroom_mb: float = 100.0, # Best-effort margin added to `available` to estimate `needed`
21
+ ) -> PluginResourceError: # Typed error for the substrate's CR-7 reactive-retry path
22
+ """Convert a CUDA out-of-memory exception into a substrate-typed `PluginResourceError`.
23
+
24
+ SG-47 Track B: a plugin's GPU inference / model-load site catches
25
+ `torch.cuda.OutOfMemoryError` and re-raises the result of this helper so the
26
+ substrate sees a typed resource error (evict + reload + retry via CR-7)
27
+ instead of an opaque crash.
28
+
29
+ `needed` is a best-effort estimate (`available + headroom_mb`): the true
30
+ required VRAM is unknowable from the exception, and CR-7 triggers eviction
31
+ regardless of magnitude, so an approximation above `available` is sufficient.
32
+
33
+ The caller raises the returned error, preserving the original cause:
34
+
35
+ try:
36
+ model = Model.from_pretrained(repo_id, ...)
37
+ except torch.cuda.OutOfMemoryError as e:
38
+ raise cuda_oom_to_plugin_resource_error(e, label=f"loading {repo_id!r}") from e
39
+ """
40
+ try:
41
+ free_bytes = torch.cuda.mem_get_info()[0] if torch.cuda.is_available() else 0
42
+ except Exception:
43
+ # mem_get_info can raise on some driver / edge states; fall back to 0.
44
+ # CR-7 evicts regardless of the reported magnitude, so 0 is safe.
45
+ free_bytes = 0
46
+ available_mb = free_bytes / (1024 ** 2)
47
+ return PluginResourceError(
48
+ f"CUDA OOM {label}: {exc}",
49
+ resource_shortfall=ResourceShortfall(
50
+ resource="gpu_vram_mb",
51
+ needed=available_mb + headroom_mb,
52
+ available=available_mb,
53
+ ),
54
+ )
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.4
2
+ Name: cjm-torch-plugin-utils
3
+ Version: 0.0.1
4
+ Summary: PyTorch helpers for cjm-plugin-system plugins: GPU memory release, typed CUDA-OOM handling, and device selection.
5
+ Author-email: "Christian J. Mills" <9126128+cj-mills@users.noreply.github.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/cj-mills/cjm-torch-plugin-utils
8
+ Project-URL: Documentation, https://cj-mills.github.io/cjm-torch-plugin-utils/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.12
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: cjm-plugin-system>=0.0.37
16
+ Requires-Dist: numpy
17
+ Requires-Dist: torch
18
+ Dynamic: license-file
19
+
20
+ # cjm-torch-plugin-utils
21
+
22
+
23
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
24
+
25
+ ## Install
26
+
27
+ ``` bash
28
+ pip install cjm_torch_plugin_utils
29
+ ```
30
+
31
+ ## Project Structure
32
+
33
+ nbs/
34
+ ├── device.ipynb # Resolve a device spec ("auto" / "cpu" / "cuda" / "cuda:N") to a concrete torch device string.
35
+ ├── memory.ipynb # Robust move-to-CPU + drop-references + gc + CUDA-cache cleanup for releasing models, factored out of the per-plugin reimplementations.
36
+ └── oom.ipynb # Convert torch CUDA out-of-memory exceptions into the substrate's typed `PluginResourceError` (SG-47 Track B) so CR-7 reactive retry can evict and reload.
37
+
38
+ Total: 3 notebooks
39
+
40
+ ## Module Dependencies
41
+
42
+ ``` mermaid
43
+ graph LR
44
+ device["device<br/>Device resolution"]
45
+ memory["memory<br/>GPU model release"]
46
+ oom["oom<br/>CUDA OOM handling"]
47
+ ```
48
+
49
+ No cross-module dependencies detected.
50
+
51
+ ## CLI Reference
52
+
53
+ No CLI commands found in this project.
54
+
55
+ ## Module Overview
56
+
57
+ Detailed documentation for each module in the project:
58
+
59
+ ### Device resolution (`device.ipynb`)
60
+
61
+ > Resolve a device spec (“auto” / “cpu” / “cuda” / “cuda:N”) to a
62
+ > concrete torch device string.
63
+
64
+ #### Import
65
+
66
+ ``` python
67
+ from cjm_torch_plugin_utils.device import (
68
+ resolve_torch_device
69
+ )
70
+ ```
71
+
72
+ #### Functions
73
+
74
+ ``` python
75
+ def resolve_torch_device(
76
+ spec: str = "auto", # Requested device: "auto", "cpu", "cuda", or "cuda:N"
77
+ ) -> str: # Concrete device string
78
+ """
79
+ Resolve a device spec to a concrete torch device string.
80
+
81
+ `"auto"` resolves to `"cuda"` when CUDA is available, else `"cpu"`. Any
82
+ explicit spec (`"cpu"`, `"cuda"`, `"cuda:0"`, ...) is returned unchanged.
83
+ """
84
+ ```
85
+
86
+ ### GPU model release (`memory.ipynb`)
87
+
88
+ > Robust move-to-CPU + drop-references + gc + CUDA-cache cleanup for
89
+ > releasing models, factored out of the per-plugin reimplementations.
90
+
91
+ #### Import
92
+
93
+ ``` python
94
+ from cjm_torch_plugin_utils.memory import (
95
+ release_model
96
+ )
97
+ ```
98
+
99
+ #### Functions
100
+
101
+ ``` python
102
+ def release_model(
103
+ obj: Any, # The plugin instance holding the model attribute(s)
104
+ model_attr_names: List[str], # Names of the attributes to release, in release order
105
+ device: str = "cuda", # Device the model is on; gates the CUDA-specific cleanup
106
+ *,
107
+ logger: logging.Logger, # Logger for best-effort failure reporting
108
+ ) -> None
109
+ """
110
+ Release one or more model objects: move to CPU, drop references, gc, free CUDA cache.
111
+
112
+ For each name in `model_attr_names`, if `obj` has a non-None attribute:
113
+ 1. when on CUDA, best-effort `.to('cpu')` (frees GPU tensors; skipped for
114
+ objects without a `.to` method, e.g. processors/tokenizers),
115
+ 2. `setattr(obj, name, None)` and drop the local reference.
116
+ Then a single `gc.collect()` and — on CUDA — `empty_cache()` + `synchronize()`.
117
+
118
+ Best-effort throughout: failures are logged and swallowed. Missing or
119
+ already-None attributes are skipped, so the call is idempotent.
120
+ """
121
+ ```
122
+
123
+ ### CUDA OOM handling (`oom.ipynb`)
124
+
125
+ > Convert torch CUDA out-of-memory exceptions into the substrate’s typed
126
+ > `PluginResourceError` (SG-47 Track B) so CR-7 reactive retry can evict
127
+ > and reload.
128
+
129
+ #### Import
130
+
131
+ ``` python
132
+ from cjm_torch_plugin_utils.oom import (
133
+ cuda_oom_to_plugin_resource_error
134
+ )
135
+ ```
136
+
137
+ #### Functions
138
+
139
+ ``` python
140
+ def cuda_oom_to_plugin_resource_error(
141
+ exc: BaseException, # The caught CUDA OOM exception (e.g. torch.cuda.OutOfMemoryError)
142
+ *,
143
+ label: str, # Context for the message, e.g. "loading model 'X'" or "inference"
144
+ headroom_mb: float = 100.0, # Best-effort margin added to `available` to estimate `needed`
145
+ ) -> PluginResourceError: # Typed error for the substrate's CR-7 reactive-retry path
146
+ """
147
+ Convert a CUDA out-of-memory exception into a substrate-typed `PluginResourceError`.
148
+
149
+ SG-47 Track B: a plugin's GPU inference / model-load site catches
150
+ `torch.cuda.OutOfMemoryError` and re-raises the result of this helper so the
151
+ substrate sees a typed resource error (evict + reload + retry via CR-7)
152
+ instead of an opaque crash.
153
+
154
+ `needed` is a best-effort estimate (`available + headroom_mb`): the true
155
+ required VRAM is unknowable from the exception, and CR-7 triggers eviction
156
+ regardless of magnitude, so an approximation above `available` is sufficient.
157
+
158
+ The caller raises the returned error, preserving the original cause:
159
+
160
+ try:
161
+ model = Model.from_pretrained(repo_id, ...)
162
+ except torch.cuda.OutOfMemoryError as e:
163
+ raise cuda_oom_to_plugin_resource_error(e, label=f"loading {repo_id!r}") from e
164
+ """
165
+ ```
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ cjm_torch_plugin_utils/__init__.py
6
+ cjm_torch_plugin_utils/_modidx.py
7
+ cjm_torch_plugin_utils/device.py
8
+ cjm_torch_plugin_utils/memory.py
9
+ cjm_torch_plugin_utils/oom.py
10
+ cjm_torch_plugin_utils.egg-info/PKG-INFO
11
+ cjm_torch_plugin_utils.egg-info/SOURCES.txt
12
+ cjm_torch_plugin_utils.egg-info/dependency_links.txt
13
+ cjm_torch_plugin_utils.egg-info/entry_points.txt
14
+ cjm_torch_plugin_utils.egg-info/requires.txt
15
+ cjm_torch_plugin_utils.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ cjm_torch_plugin_utils = cjm_torch_plugin_utils._modidx:d
@@ -0,0 +1,3 @@
1
+ cjm-plugin-system>=0.0.37
2
+ numpy
3
+ torch
@@ -0,0 +1 @@
1
+ cjm_torch_plugin_utils
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cjm-torch-plugin-utils"
7
+ dynamic = ["version"]
8
+ description = "PyTorch helpers for cjm-plugin-system plugins: GPU memory release, typed CUDA-OOM handling, and device selection."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [{name = "Christian J. Mills", email = "9126128+cj-mills@users.noreply.github.com"}]
13
+ keywords = ['nbdev']
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ ]
18
+ dependencies = ['cjm-plugin-system>=0.0.37', 'numpy', 'torch']
19
+
20
+ [project.urls]
21
+ Repository = "https://github.com/cj-mills/cjm-torch-plugin-utils"
22
+ Documentation = "https://cj-mills.github.io/cjm-torch-plugin-utils/"
23
+
24
+ [project.entry-points.nbdev]
25
+ cjm_torch_plugin_utils = "cjm_torch_plugin_utils._modidx:d"
26
+
27
+ [tool.setuptools.dynamic]
28
+ version = {attr = "cjm_torch_plugin_utils.__version__"}
29
+
30
+ [tool.setuptools.packages.find]
31
+ include = ["cjm_torch_plugin_utils"]
32
+
33
+ [tool.nbdev]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+