krrood-compute-resources 26.10.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.
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: krrood_compute_resources
3
+ Version: 26.10.0
4
+ Summary: The processor cores, memory and GPUs a computation runs on, and how a machine is divided among processes.
5
+ Author-email: Tom Schierenbeck <tom_sch@uni-bremen.de>
6
+ License-Expression: LGPL-3.0-only
7
+ Project-URL: Source, https://github.com/cram2/cognitive_robot_abstract_machine
8
+ Project-URL: Bug Tracker, https://github.com/cram2/cognitive_robot_abstract_machine/issues
9
+ Project-URL: Changelog, https://github.com/cram2/cognitive_robot_abstract_machine/blob/main/CHANGELOG.md
10
+ Keywords: compute resources,memory,gpu,scheduling
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Requires-Python: <3.13,>=3.12
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: krrood>=26.10.0
17
+ Requires-Dist: typing_extensions
18
+ Provides-Extra: jax
19
+ Requires-Dist: jax>=0.6.0; extra == "jax"
20
+ Provides-Extra: torch
21
+ Requires-Dist: torch>=2.4; extra == "torch"
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest<8.0.0,>=7.0.0; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # krrood_compute_resources
27
+
28
+ The processor cores, memory and GPUs a computation runs on, and how a machine is divided
29
+ among processes that run side by side.
30
+
31
+ - `krrood_compute_resources.devices`: `Device`, the kinds of device a computation runs on.
32
+ - `krrood_compute_resources.memory`: `DeviceMemory`, the free memory of a device;
33
+ `HostMemory`, the main memory of a Linux host within its control group; and
34
+ `BudgetedMemory`, the share of a device's memory one process may use.
35
+ - `krrood_compute_resources.machine`: `Machine`, the cores and memory of the machine a
36
+ process runs on; `MachineDivision`, which divides it into `MachineShare`s; and the
37
+ environment and core affinity that keep a process within its share.
38
+ - `krrood_compute_resources.jax_memory`, with the extra `krrood_compute_resources[jax]`:
39
+ `JaxDeviceMemory`, the memory of an accelerator jax stores arrays on.
40
+ - `krrood_compute_resources.torch_memory`, with the extra `krrood_compute_resources[torch]`:
41
+ `TorchDeviceMemory`, the memory of a CUDA device torch stores tensors on.
@@ -0,0 +1,16 @@
1
+ # krrood_compute_resources
2
+
3
+ The processor cores, memory and GPUs a computation runs on, and how a machine is divided
4
+ among processes that run side by side.
5
+
6
+ - `krrood_compute_resources.devices`: `Device`, the kinds of device a computation runs on.
7
+ - `krrood_compute_resources.memory`: `DeviceMemory`, the free memory of a device;
8
+ `HostMemory`, the main memory of a Linux host within its control group; and
9
+ `BudgetedMemory`, the share of a device's memory one process may use.
10
+ - `krrood_compute_resources.machine`: `Machine`, the cores and memory of the machine a
11
+ process runs on; `MachineDivision`, which divides it into `MachineShare`s; and the
12
+ environment and core affinity that keep a process within its share.
13
+ - `krrood_compute_resources.jax_memory`, with the extra `krrood_compute_resources[jax]`:
14
+ `JaxDeviceMemory`, the memory of an accelerator jax stores arrays on.
15
+ - `krrood_compute_resources.torch_memory`, with the extra `krrood_compute_resources[torch]`:
16
+ `TorchDeviceMemory`, the memory of a CUDA device torch stores tensors on.
@@ -0,0 +1,61 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "krrood_compute_resources"
7
+ authors = [
8
+ { name = "Tom Schierenbeck", email = "tom_sch@uni-bremen.de" },
9
+ ]
10
+ description = "The processor cores, memory and GPUs a computation runs on, and how a machine is divided among processes."
11
+ readme = "README.md"
12
+ requires-python = ">=3.12,<3.13"
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Operating System :: POSIX :: Linux",
16
+ ]
17
+ keywords = ["compute resources", "memory", "gpu", "scheduling"]
18
+ license = "LGPL-3.0-only"
19
+ dynamic = ["version"]
20
+ dependencies = [
21
+ "krrood>=26.10.0",
22
+ "typing_extensions",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ jax = [
27
+ "jax>=0.6.0",
28
+ ]
29
+ torch = [
30
+ "torch>=2.4",
31
+ ]
32
+ dev = [
33
+ "pytest>=7.0.0,<8.0.0",
34
+ ]
35
+
36
+ [project.urls]
37
+ "Source" = 'https://github.com/cram2/cognitive_robot_abstract_machine'
38
+ "Bug Tracker" = "https://github.com/cram2/cognitive_robot_abstract_machine/issues"
39
+ "Changelog" = "https://github.com/cram2/cognitive_robot_abstract_machine/blob/main/CHANGELOG.md"
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
43
+ include = ["krrood_compute_resources*"]
44
+
45
+ [tool.setuptools.dynamic]
46
+ version = { attr = "krrood_compute_resources._version.__version__" }
47
+
48
+ [tool.krrood.core-boundary]
49
+ # The modules a plain `pip install krrood_compute_resources` must be able to load; the
50
+ # memory of jax and torch devices needs the extras of the same name.
51
+ core = [
52
+ "krrood_compute_resources._version",
53
+ "krrood_compute_resources.devices",
54
+ "krrood_compute_resources.exceptions",
55
+ "krrood_compute_resources.machine",
56
+ "krrood_compute_resources.memory",
57
+ ]
58
+ dependencies = [
59
+ "krrood",
60
+ "typing-extensions",
61
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ from ._version import __version__
@@ -0,0 +1 @@
1
+ __version__ = "26.10.0"
@@ -0,0 +1,19 @@
1
+ """
2
+ The kinds of device a computation runs on.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ # %% imports
8
+ from enum import StrEnum
9
+
10
+ # %% devices
11
+
12
+
13
+ class Device(StrEnum):
14
+ """
15
+ The kind of device a computation runs on, valued as jax names its platform.
16
+ """
17
+
18
+ CENTRAL_PROCESSOR = "cpu"
19
+ GRAPHICS_PROCESSOR = "gpu"
@@ -0,0 +1,75 @@
1
+ """
2
+ Exceptions of the compute resources model.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ # %% imports
8
+ from dataclasses import dataclass
9
+
10
+ from krrood.exceptions import DataclassException
11
+
12
+ # %% memory
13
+
14
+
15
+ @dataclass(kw_only=True)
16
+ class MissingMemoryFieldError(DataclassException, LookupError):
17
+ """
18
+ Exception raised when a Linux memory file lacks a field that is read from it.
19
+ """
20
+
21
+ memory_file: str
22
+ """
23
+ The memory file that was read.
24
+ """
25
+
26
+ memory_field: str
27
+ """
28
+ The memory field that was not found in it.
29
+ """
30
+
31
+ def error_message(self) -> str:
32
+ return f"{self.memory_file} has no field {self.memory_field}."
33
+
34
+ def suggest_correction(self) -> str:
35
+ return "Run on a Linux kernel that reports this field."
36
+
37
+
38
+ # %% division of a machine
39
+
40
+
41
+ @dataclass(kw_only=True)
42
+ class EmptyMachineDivisionError(DataclassException, ValueError):
43
+ """
44
+ Exception raised when a machine is divided into no shares at all.
45
+ """
46
+
47
+ def error_message(self) -> str:
48
+ return "A machine division needs at least one share."
49
+
50
+ def suggest_correction(self) -> str:
51
+ return "Give at least one share of the GPU or of the processor cores."
52
+
53
+
54
+ @dataclass(kw_only=True)
55
+ class MissingGraphicsProcessorError(DataclassException, LookupError):
56
+ """
57
+ Exception raised when shares of the GPU are asked of a machine without one.
58
+ """
59
+
60
+ graphics_processor_shares: int
61
+ """
62
+ The number of shares of the GPU that were asked for.
63
+ """
64
+
65
+ def error_message(self) -> str:
66
+ return (
67
+ f"{self.graphics_processor_shares} shares of the GPU were asked for, but "
68
+ f"the machine has no GPU."
69
+ )
70
+
71
+ def suggest_correction(self) -> str:
72
+ return (
73
+ "Give the machine the memory of its GPU, or divide it into shares of the "
74
+ "processor cores only."
75
+ )
@@ -0,0 +1,42 @@
1
+ """
2
+ The memory of the accelerators jax stores arrays on.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ # %% imports
8
+ from dataclasses import dataclass
9
+ from enum import StrEnum
10
+
11
+ import jax
12
+
13
+ from krrood_compute_resources.memory import DeviceMemory
14
+
15
+ # %% memory of a jax device
16
+
17
+
18
+ class JaxMemoryStatistic(StrEnum):
19
+ """
20
+ The entries of :meth:`jax.Device.memory_stats` that are read, each in bytes.
21
+ """
22
+
23
+ LIMIT = "bytes_limit"
24
+ IN_USE = "bytes_in_use"
25
+
26
+
27
+ @dataclass(kw_only=True)
28
+ class JaxDeviceMemory(DeviceMemory):
29
+ """
30
+ The memory of an accelerator jax stores arrays on.
31
+ """
32
+
33
+ device: jax.Device
34
+ """
35
+ The accelerator.
36
+ """
37
+
38
+ def free_bytes(self) -> int:
39
+ statistics = self.device.memory_stats()
40
+ return (
41
+ statistics[JaxMemoryStatistic.LIMIT] - statistics[JaxMemoryStatistic.IN_USE]
42
+ )
@@ -0,0 +1,235 @@
1
+ """
2
+ The machine a process runs on, and its division into shares that processes running side
3
+ by side each keep to.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ # %% imports
9
+ import os
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+
13
+ from krrood_compute_resources.devices import Device
14
+ from krrood_compute_resources.exceptions import (
15
+ EmptyMachineDivisionError,
16
+ MissingGraphicsProcessorError,
17
+ )
18
+ from krrood_compute_resources.memory import DeviceMemory, HostMemory
19
+
20
+ # %% environment of a process
21
+
22
+
23
+ class ThreadVariable(StrEnum):
24
+ """
25
+ The environment variables that cap the threads of the numeric libraries.
26
+ """
27
+
28
+ OPEN_MULTI_PROCESSING = "OMP_NUM_THREADS"
29
+ OPEN_BASIC_LINEAR_ALGEBRA_SUBPROGRAMS = "OPENBLAS_NUM_THREADS"
30
+ MATH_KERNEL_LIBRARY = "MKL_NUM_THREADS"
31
+
32
+
33
+ class GraphicsProcessorVariable(StrEnum):
34
+ """
35
+ The environment variables that configure how a process uses the GPU.
36
+ """
37
+
38
+ JAX_MEMORY_PREALLOCATION = "XLA_PYTHON_CLIENT_PREALLOCATE"
39
+ """
40
+ Whether jax claims most of the GPU memory when it starts.
41
+ """
42
+
43
+ VISIBLE_DEVICES = "CUDA_VISIBLE_DEVICES"
44
+ """
45
+ The GPUs a process sees.
46
+ """
47
+
48
+
49
+ # %% machine
50
+
51
+
52
+ @dataclass(kw_only=True)
53
+ class Machine:
54
+ """
55
+ The processor cores and memory of the machine a process runs on.
56
+ """
57
+
58
+ processor_cores: set[int]
59
+ """
60
+ The processor cores the process may run on.
61
+ """
62
+
63
+ host_memory: DeviceMemory
64
+ """
65
+ The main memory of the machine.
66
+ """
67
+
68
+ graphics_processor_memory: DeviceMemory | None = None
69
+ """
70
+ The memory of the GPU, ``None`` on a machine without one.
71
+ """
72
+
73
+ @classmethod
74
+ def from_current_process(
75
+ cls, *, graphics_processor_memory: DeviceMemory | None = None
76
+ ) -> Machine:
77
+ """
78
+ :param graphics_processor_memory: The memory of the GPU, ``None`` without one.
79
+ :return: The machine as the current process sees it: the cores it may run on
80
+ and the memory of the host within its control group.
81
+ """
82
+ return cls(
83
+ processor_cores=os.sched_getaffinity(0),
84
+ host_memory=HostMemory(),
85
+ graphics_processor_memory=graphics_processor_memory,
86
+ )
87
+
88
+
89
+ # %% shares of a machine
90
+
91
+
92
+ @dataclass(kw_only=True)
93
+ class MachineShare:
94
+ """
95
+ A share of a machine that one process uses at a time.
96
+ """
97
+
98
+ device: Device
99
+ """
100
+ The device the process computes on.
101
+ """
102
+
103
+ processor_cores: set[int]
104
+ """
105
+ The processor cores of the share.
106
+ """
107
+
108
+ memory_budget_bytes: int
109
+ """
110
+ The memory of its device the process may allocate.
111
+ """
112
+
113
+ host_memory_limit_bytes: int
114
+ """
115
+ The resident host memory above which the process is stopped.
116
+ """
117
+
118
+ def process_environment(self, *, environment: dict[str, str]) -> dict[str, str]:
119
+ """
120
+ :param environment: The environment the process would otherwise get.
121
+ :return: That environment, with the threads of the numeric libraries capped at
122
+ the cores of the share, and with the GPU hidden from a share on the CPU and
123
+ shared without preallocation on a share of the GPU.
124
+ """
125
+ confined = dict(environment)
126
+ for variable in ThreadVariable:
127
+ confined[variable] = str(len(self.processor_cores))
128
+ if self.device is Device.GRAPHICS_PROCESSOR:
129
+ confined[GraphicsProcessorVariable.JAX_MEMORY_PREALLOCATION] = "false"
130
+ else:
131
+ confined[GraphicsProcessorVariable.VISIBLE_DEVICES] = ""
132
+ return confined
133
+
134
+ def confine_current_process(self) -> None:
135
+ """
136
+ Restrict the current process to the processor cores of the share.
137
+ """
138
+ os.sched_setaffinity(0, self.processor_cores)
139
+
140
+
141
+ @dataclass(kw_only=True)
142
+ class MachineDivision:
143
+ """
144
+ The division of a machine into shares of the GPU and shares of the processor cores
145
+ alone.
146
+ """
147
+
148
+ graphics_processor_shares: int = 3
149
+ """
150
+ The number of shares that compute on the GPU.
151
+ """
152
+
153
+ processor_core_shares: int = 7
154
+ """
155
+ The number of shares that compute on the processor cores alone.
156
+ """
157
+
158
+ host_memory_fraction: float = 0.8
159
+ """
160
+ The fraction of the free host memory that is divided among the shares.
161
+ """
162
+
163
+ host_memory_limit_shares: float = 2.0
164
+ """
165
+ The number of host memory shares a process may hold before it is stopped.
166
+ """
167
+
168
+ graphics_processor_memory_fraction: float = 0.9
169
+ """
170
+ The fraction of the free GPU memory that is divided among the GPU shares, the rest
171
+ kept free since the memory a process needs is often only estimated.
172
+ """
173
+
174
+ def __post_init__(self) -> None:
175
+ """
176
+ :raises EmptyMachineDivisionError: If the division has no shares.
177
+ """
178
+ if self.graphics_processor_shares + self.processor_core_shares == 0:
179
+ raise EmptyMachineDivisionError()
180
+
181
+ def shares_device(self, *, device: Device) -> bool:
182
+ """
183
+ :param device: A kind of device.
184
+ :return: Whether the division has a share that computes on it.
185
+ """
186
+ if device is Device.GRAPHICS_PROCESSOR:
187
+ return self.graphics_processor_shares > 0
188
+ return self.processor_core_shares > 0
189
+
190
+ def shares(self, *, machine: Machine) -> list[MachineShare]:
191
+ """
192
+ :param machine: The machine to divide.
193
+ :return: The shares of the GPU, then the shares of the processor cores, each
194
+ with its own equal part of the cores and of the free memory of its device.
195
+ :raises MissingGraphicsProcessorError: If shares of the GPU are asked of a
196
+ machine without one.
197
+ """
198
+ if self.graphics_processor_shares and machine.graphics_processor_memory is None:
199
+ raise MissingGraphicsProcessorError(
200
+ graphics_processor_shares=self.graphics_processor_shares
201
+ )
202
+ count = self.graphics_processor_shares + self.processor_core_shares
203
+ cores = sorted(machine.processor_cores)
204
+ cores_per_share = len(cores) // count
205
+ host_share = int(
206
+ self.host_memory_fraction * machine.host_memory.free_bytes() / count
207
+ )
208
+ graphics_processor_share = (
209
+ int(
210
+ self.graphics_processor_memory_fraction
211
+ * machine.graphics_processor_memory.free_bytes()
212
+ / self.graphics_processor_shares
213
+ )
214
+ if self.graphics_processor_shares
215
+ else 0
216
+ )
217
+ return [
218
+ MachineShare(
219
+ device=(
220
+ Device.GRAPHICS_PROCESSOR
221
+ if index < self.graphics_processor_shares
222
+ else Device.CENTRAL_PROCESSOR
223
+ ),
224
+ processor_cores=set(
225
+ cores[index * cores_per_share : (index + 1) * cores_per_share]
226
+ ),
227
+ memory_budget_bytes=(
228
+ graphics_processor_share
229
+ if index < self.graphics_processor_shares
230
+ else host_share
231
+ ),
232
+ host_memory_limit_bytes=int(self.host_memory_limit_shares * host_share),
233
+ )
234
+ for index in range(count)
235
+ ]
@@ -0,0 +1,181 @@
1
+ """
2
+ The memory of the devices arrays are stored on: how much is free, how much is in use, and
3
+ the most that was in use at once.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ # %% imports
9
+ from abc import ABC, abstractmethod
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+
13
+ from krrood.patterns.classproperty import classproperty
14
+ from krrood.patterns.path_enumeration import PathEnumeration
15
+
16
+ from krrood_compute_resources.exceptions import MissingMemoryFieldError
17
+
18
+ # %% linux memory files
19
+
20
+
21
+ class LinuxMemoryFile(PathEnumeration):
22
+ """
23
+ The files Linux reports memory in.
24
+ """
25
+
26
+ MEMORY_INFORMATION = "/proc/meminfo"
27
+ PROCESS_STATUS = "/proc/self/status"
28
+ CLEAR_REFERENCES = "/proc/self/clear_refs"
29
+ CONTROL_GROUP_LIMIT = "/sys/fs/cgroup/memory.max"
30
+ CONTROL_GROUP_USAGE = "/sys/fs/cgroup/memory.current"
31
+
32
+
33
+ class LinuxMemoryField(StrEnum):
34
+ """
35
+ The fields of :attr:`LinuxMemoryFile.MEMORY_INFORMATION` and
36
+ :attr:`LinuxMemoryFile.PROCESS_STATUS` that are read, each in kibibytes.
37
+ """
38
+
39
+ AVAILABLE = "MemAvailable"
40
+ RESIDENT = "VmRSS"
41
+ PEAK_RESIDENT = "VmHWM"
42
+
43
+
44
+ class LinuxMemoryValue(StrEnum):
45
+ """
46
+ Fixed values of the Linux memory files.
47
+ """
48
+
49
+ UNLIMITED = "max"
50
+ """
51
+ The content of :attr:`LinuxMemoryFile.CONTROL_GROUP_LIMIT` without a limit.
52
+ """
53
+
54
+ RESET_PEAK_RESIDENT = "5"
55
+ """
56
+ Written to :attr:`LinuxMemoryFile.CLEAR_REFERENCES`, resets the peak resident memory.
57
+ """
58
+
59
+
60
+ # %% memory of a device
61
+
62
+
63
+ class DeviceMemory(ABC):
64
+ """
65
+ The memory of a device that arrays are stored on.
66
+ """
67
+
68
+ @abstractmethod
69
+ def free_bytes(self) -> int:
70
+ """
71
+ :return: The number of bytes that can still be allocated on the device.
72
+ """
73
+
74
+
75
+ class PeakTrackingMemory(DeviceMemory, ABC):
76
+ """
77
+ Device memory that records the most memory in use since its peak was last reset.
78
+ """
79
+
80
+ @abstractmethod
81
+ def in_use_bytes(self) -> int:
82
+ """
83
+ :return: The number of bytes in use now.
84
+ """
85
+
86
+ @abstractmethod
87
+ def peak_bytes(self) -> int:
88
+ """
89
+ :return: The most bytes in use at once since :meth:`reset_peak`.
90
+ """
91
+
92
+ @abstractmethod
93
+ def reset_peak(self) -> None:
94
+ """
95
+ Start recording the peak anew from the memory in use now.
96
+ """
97
+
98
+
99
+ @dataclass(kw_only=True)
100
+ class HostMemory(PeakTrackingMemory):
101
+ """
102
+ The main memory of a Linux host, as seen by this process and its control group.
103
+ """
104
+
105
+ @classproperty
106
+ def bytes_per_kibibyte(cls) -> int:
107
+ """
108
+ :return: The unit the Linux memory fields are given in, in bytes.
109
+ """
110
+ return 1024
111
+
112
+ def free_bytes(self) -> int:
113
+ available = self.field_bytes(
114
+ memory_file=LinuxMemoryFile.MEMORY_INFORMATION,
115
+ memory_field=LinuxMemoryField.AVAILABLE,
116
+ )
117
+ if not LinuxMemoryFile.CONTROL_GROUP_LIMIT.exists():
118
+ return available
119
+ limit = LinuxMemoryFile.CONTROL_GROUP_LIMIT.read_text().strip()
120
+ if limit == LinuxMemoryValue.UNLIMITED:
121
+ return available
122
+ usage = int(LinuxMemoryFile.CONTROL_GROUP_USAGE.read_text())
123
+ return min(available, int(limit) - usage)
124
+
125
+ def in_use_bytes(self) -> int:
126
+ return self.field_bytes(
127
+ memory_file=LinuxMemoryFile.PROCESS_STATUS,
128
+ memory_field=LinuxMemoryField.RESIDENT,
129
+ )
130
+
131
+ def peak_bytes(self) -> int:
132
+ return self.field_bytes(
133
+ memory_file=LinuxMemoryFile.PROCESS_STATUS,
134
+ memory_field=LinuxMemoryField.PEAK_RESIDENT,
135
+ )
136
+
137
+ def reset_peak(self) -> None:
138
+ LinuxMemoryFile.CLEAR_REFERENCES.write_text(
139
+ LinuxMemoryValue.RESET_PEAK_RESIDENT
140
+ )
141
+
142
+ def field_bytes(
143
+ self, *, memory_file: LinuxMemoryFile, memory_field: LinuxMemoryField
144
+ ) -> int:
145
+ """
146
+ :param memory_file: The file that holds the field, one ``name: value kB`` line
147
+ per field.
148
+ :param memory_field: The field to read.
149
+ :return: The value of the field, in bytes.
150
+ """
151
+ for line in memory_file.read_text().splitlines():
152
+ name, value = line.split(":", 1)
153
+ if name == memory_field:
154
+ return int(value.split()[0]) * self.bytes_per_kibibyte
155
+ raise MissingMemoryFieldError(
156
+ memory_file=str(memory_file), memory_field=memory_field
157
+ )
158
+
159
+
160
+ # %% memory budget
161
+
162
+
163
+ @dataclass(kw_only=True)
164
+ class BudgetedMemory(DeviceMemory):
165
+ """
166
+ The memory of a device of which a process may use at most a fixed amount, since other
167
+ processes share the device.
168
+ """
169
+
170
+ memory: DeviceMemory
171
+ """
172
+ The memory of the device.
173
+ """
174
+
175
+ budget_bytes: int
176
+ """
177
+ The most bytes the process may allocate.
178
+ """
179
+
180
+ def free_bytes(self) -> int:
181
+ return min(self.memory.free_bytes(), self.budget_bytes)
@@ -0,0 +1,39 @@
1
+ """
2
+ The memory of the CUDA devices torch stores tensors on.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ # %% imports
8
+ from dataclasses import dataclass
9
+
10
+ import torch
11
+
12
+ from krrood_compute_resources.memory import PeakTrackingMemory
13
+
14
+ # %% memory of a torch device
15
+
16
+
17
+ @dataclass(kw_only=True)
18
+ class TorchDeviceMemory(PeakTrackingMemory):
19
+ """
20
+ The memory of a CUDA device torch stores tensors on.
21
+ """
22
+
23
+ device: torch.device
24
+ """
25
+ The CUDA device.
26
+ """
27
+
28
+ def free_bytes(self) -> int:
29
+ free, _ = torch.cuda.mem_get_info(self.device)
30
+ return free
31
+
32
+ def in_use_bytes(self) -> int:
33
+ return torch.cuda.memory_allocated(self.device)
34
+
35
+ def peak_bytes(self) -> int:
36
+ return torch.cuda.max_memory_allocated(self.device)
37
+
38
+ def reset_peak(self) -> None:
39
+ torch.cuda.reset_peak_memory_stats(self.device)
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: krrood_compute_resources
3
+ Version: 26.10.0
4
+ Summary: The processor cores, memory and GPUs a computation runs on, and how a machine is divided among processes.
5
+ Author-email: Tom Schierenbeck <tom_sch@uni-bremen.de>
6
+ License-Expression: LGPL-3.0-only
7
+ Project-URL: Source, https://github.com/cram2/cognitive_robot_abstract_machine
8
+ Project-URL: Bug Tracker, https://github.com/cram2/cognitive_robot_abstract_machine/issues
9
+ Project-URL: Changelog, https://github.com/cram2/cognitive_robot_abstract_machine/blob/main/CHANGELOG.md
10
+ Keywords: compute resources,memory,gpu,scheduling
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Requires-Python: <3.13,>=3.12
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: krrood>=26.10.0
17
+ Requires-Dist: typing_extensions
18
+ Provides-Extra: jax
19
+ Requires-Dist: jax>=0.6.0; extra == "jax"
20
+ Provides-Extra: torch
21
+ Requires-Dist: torch>=2.4; extra == "torch"
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest<8.0.0,>=7.0.0; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # krrood_compute_resources
27
+
28
+ The processor cores, memory and GPUs a computation runs on, and how a machine is divided
29
+ among processes that run side by side.
30
+
31
+ - `krrood_compute_resources.devices`: `Device`, the kinds of device a computation runs on.
32
+ - `krrood_compute_resources.memory`: `DeviceMemory`, the free memory of a device;
33
+ `HostMemory`, the main memory of a Linux host within its control group; and
34
+ `BudgetedMemory`, the share of a device's memory one process may use.
35
+ - `krrood_compute_resources.machine`: `Machine`, the cores and memory of the machine a
36
+ process runs on; `MachineDivision`, which divides it into `MachineShare`s; and the
37
+ environment and core affinity that keep a process within its share.
38
+ - `krrood_compute_resources.jax_memory`, with the extra `krrood_compute_resources[jax]`:
39
+ `JaxDeviceMemory`, the memory of an accelerator jax stores arrays on.
40
+ - `krrood_compute_resources.torch_memory`, with the extra `krrood_compute_resources[torch]`:
41
+ `TorchDeviceMemory`, the memory of a CUDA device torch stores tensors on.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/krrood_compute_resources/__init__.py
5
+ src/krrood_compute_resources/_version.py
6
+ src/krrood_compute_resources/devices.py
7
+ src/krrood_compute_resources/exceptions.py
8
+ src/krrood_compute_resources/jax_memory.py
9
+ src/krrood_compute_resources/machine.py
10
+ src/krrood_compute_resources/memory.py
11
+ src/krrood_compute_resources/torch_memory.py
12
+ src/krrood_compute_resources.egg-info/PKG-INFO
13
+ src/krrood_compute_resources.egg-info/SOURCES.txt
14
+ src/krrood_compute_resources.egg-info/dependency_links.txt
15
+ src/krrood_compute_resources.egg-info/requires.txt
16
+ src/krrood_compute_resources.egg-info/top_level.txt
@@ -0,0 +1,11 @@
1
+ krrood>=26.10.0
2
+ typing_extensions
3
+
4
+ [dev]
5
+ pytest<8.0.0,>=7.0.0
6
+
7
+ [jax]
8
+ jax>=0.6.0
9
+
10
+ [torch]
11
+ torch>=2.4