Skip to content

Commit 81086e0

Browse files
committed
merge main and update the options class
1 parent 92aa731 commit 81086e0

File tree

2 files changed

+298
-0
lines changed

2 files changed

+298
-0
lines changed
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
from cuda.core.experimental._module import ObjectCode
2+
from cuda.core.experimental._utils import check_or_create_options
3+
from dataclasses import dataclass
4+
from typing import Optional
5+
from cuda.bindings import nvjitlink
6+
7+
8+
@dataclass
9+
class LinkerOptions:
10+
arch: str # /**< -arch=sm_<N> Pass SM architecture value. See nvcc for valid values of <N>. Can use compute_<N> value instead if only generating PTX. This is a required option. */
11+
max_register_count: Optional[int] = None # /**< -maxrregcount=<N> Maximum register count. */
12+
time: Optional[bool] = None # /**< -time Print timing information to InfoLog. */
13+
verbose: Optional[bool] = None # /**< -verbose Print verbose messages to InfoLog. */
14+
link_time_optimization: Optional[bool] = None # /**< -lto Do link time optimization. */
15+
ptx: Optional[bool] = None # /**< -ptx Emit ptx after linking instead of cubin; only supported with -lto. */
16+
optimization_level: Optional[int] = None # /**< -O<N> Optimization level. Only 0 and 3 are accepted. */
17+
debug: Optional[bool] = None # /**< -g Generate debug information. */
18+
lineinfo: Optional[bool] = None # /**< -lineinfo Generate line information. */
19+
ftz: Optional[bool] = None # /**< -ftz=<n> Flush to zero. */
20+
prec_div: Optional[bool] = None # /**< -prec-div=<n> Precise divide. */
21+
prec_sqrt: Optional[bool] = None # /**< -prec-sqrt=<n> Precise square root. */
22+
fma: Optional[bool] = None # /**< -fma=<n> Fast multiply add. */
23+
kernels_used: Optional[list[str]] = None # /**< -kernels-used=<name> Pass list of kernels that are used; any not in the list can be removed. This option can be specified multiple times. */
24+
variables_used: Optional[list[str]] = None # /**< -variables-used=<name> Pass list of variables that are used; any not in the list can be removed. This option can be specified multiple times. */
25+
optimize_unused_variables: Optional[bool] = None # /**< -optimize-unused-variables Normally device code optimization is limited by not knowing what the host code references. With this option it can assume that if a variable is not referenced in device code then it can be removed. */
26+
xptxas: Optional[list[str]] = None # /**< -Xptxas=<opt> Pass <opt> to ptxas. This option can be called multiple times. */
27+
split_compile: Optional[int] = None # /**< -split-compile=<N> Split compilation maximum thread count. Use 0 to use all available processors. Value of 1 disables split compilation (default). */
28+
split_compile_extended: Optional[int] = None # /**< -split-compile-extended=<N> A more aggressive form of split compilation available in LTO mode only. Accepts a maximum thread count value. Use 0 to use all available processors. Value of 1 disables extended split compilation (default). Note: This option can potentially impact performance of the compiled binary. */
29+
jump_table_density: Optional[int] = None # /**< -jump-table-density=<N> When doing LTO, specify the case density percentage in switch statements, and use it as a minimal threshold to determine whether jump table(brx.idx instruction) will be used to implement a switch statement. Default value is 101. The percentage ranges from 0 to 101 inclusively. */
30+
no_cache: Optional[bool] = None # /**< -no-cache Don’t cache the intermediate steps of nvJitLink. */
31+
device_stack_protector: Optional[bool] = None # /**< -device-stack-protector Enable stack canaries in device code. Stack canaries make it more difficult to exploit certain types of memory safety bugs involving stack-local variables. The compiler uses heuristics to assess the risk of such a bug in each function. Only those functions which are deemed high-risk make use of a stack canary. */
32+
33+
34+
def __post_init__(self):
35+
self.formatted_options = []
36+
if self.arch is not None:
37+
self.formatted_options.append(f"-arch={self.arch}")
38+
if self.max_register_count is not None:
39+
self.formatted_options.append(f"-maxrregcount={self.max_register_count}")
40+
if self.time is not None:
41+
self.formatted_options.append("-time")
42+
if self.verbose is not None:
43+
self.formatted_options.append("-verbose")
44+
if self.link_time_optimization is not None:
45+
self.formatted_options.append("-lto")
46+
if self.ptx is not None:
47+
self.formatted_options.append("-ptx")
48+
if self.optimization_level is not None:
49+
self.formatted_options.append(f"-O{self.optimization_level}")
50+
if self.debug is not None:
51+
self.formatted_options.append("-g")
52+
if self.lineinfo is not None:
53+
self.formatted_options.append("-lineinfo")
54+
if self.ftz is not None:
55+
self.formatted_options.append(f"-ftz={'true' if self.ftz else 'false'}")
56+
if self.prec_div is not None:
57+
self.formatted_options.append(f"-prec-div={'true' if self.prec_div else 'false'}")
58+
if self.prec_sqrt is not None:
59+
self.formatted_options.append(f"-prec-sqrt={'true' if self.prec_sqrt else 'false'}")
60+
if self.fma is not None:
61+
self.formatted_options.append(f"-fma={'true' if self.fma else 'false'}")
62+
if self.kernels_used is not None:
63+
for kernel in self.kernels_used:
64+
self.formatted_options.append(f"-kernels-used={kernel}")
65+
if self.variables_used is not None:
66+
for variable in self.variables_used:
67+
self.formatted_options.append(f"-variables-used={variable}")
68+
if self.optimize_unused_variables is not None:
69+
self.formatted_options.append("-optimize-unused-variables")
70+
if self.xptxas is not None:
71+
for opt in self.xptxas:
72+
self.formatted_options.append(f"-Xptxas={opt}")
73+
if self.split_compile is not None:
74+
self.formatted_options.append(f"-split-compile={self.split_compile}")
75+
if self.split_compile_extended is not None:
76+
self.formatted_options.append(f"-split-compile-extended={self.split_compile_extended}")
77+
if self.jump_table_density is not None:
78+
self.formatted_options.append(f"-jump-table-density={self.jump_table_density}")
79+
if self.no_cache is not None:
80+
self.formatted_options.append("-no-cache")
81+
if self.device_stack_protector is not None:
82+
self.formatted_options.append("-device-stack-protector")
83+
84+
85+
class Linker:
86+
87+
__slots__ = ("_handle")
88+
89+
def __init__(self, options: LinkerOptions, object_codes = None):
90+
self._handle = None
91+
options = check_or_create_options(LinkerOptions, options, "Linker options")
92+
self._handle = nvjitlink.create(len(options.formatted_options), options.formatted_options)
93+
94+
if object_codes is not None:
95+
if object_codes.__iter__:
96+
for code in object_codes:
97+
self.add_code_object(code)
98+
else:
99+
self.add_code_object(object_codes)
100+
101+
102+
def add_code_object(self, object_code: ObjectCode):
103+
data = object_code._module
104+
assert isinstance(data, bytes)
105+
nvjitlink.add_data(
106+
self._handle,
107+
self._input_type_from_code_type(object_code._code_type),
108+
data,
109+
len(data),
110+
f"{object_code._handle}_{object_code._code_type}",
111+
)
112+
113+
114+
def link(self, target_type) -> ObjectCode:
115+
nvjitlink.complete(self._handle)
116+
if target_type not in ["cubin", "ptx"]:
117+
raise ValueError(f"Unsupported target type: {target_type}")
118+
code = None
119+
if target_type == "cubin":
120+
cubin_size = nvjitlink.get_linked_cubin_size(self._handle)
121+
code = bytearray(cubin_size)
122+
nvjitlink.get_linked_cubin(self._handle, code)
123+
else:
124+
ptx_size = nvjitlink.get_linked_ptx_size(self._handle)
125+
code = bytearray(ptx_size)
126+
nvjitlink.get_linked_ptx(self._handle, code)
127+
128+
return ObjectCode(bytes(code), target_type)
129+
130+
131+
def get_error_log(self) -> str:
132+
log_size = nvjitlink.get_error_log_size(self._handle)
133+
log = bytearray(log_size)
134+
nvjitlink.get_error_log(self._handle, log)
135+
return log.decode()
136+
137+
138+
def get_info_log(self) -> str:
139+
log_size = nvjitlink.get_info_log_size(self._handle)
140+
log = bytearray(log_size)
141+
nvjitlink.get_info_log(self._handle, log)
142+
return log.decode()
143+
144+
145+
def _input_type_from_code_type(self, code_type: str) -> nvjitlink.InputType:
146+
# this list is based on the supported values for code_type in the ObjectCode class definition. nvjitlink supports other options for input type
147+
if code_type == "ptx":
148+
return nvjitlink.InputType.PTX
149+
elif code_type == "cubin":
150+
return nvjitlink.InputType.CUBIN
151+
elif code_type == "fatbin":
152+
return nvjitlink.InputType.FATBIN
153+
elif code_type == "ltoir":
154+
return nvjitlink.InputType.LTOIR
155+
elif code_type == "object":
156+
return nvjitlink.InputType.OBJECT
157+
else:
158+
raise ValueError(
159+
f"Unknown code_type associated with ObjectCode: {code_type}"
160+
)
161+
162+
163+
@property
164+
def handle(self) -> int:
165+
return self._handle
166+
167+
def __del__(self):
168+
if self._handle is not None:
169+
nvjitlink.destroy(self._handle)
170+
self._handle = None

cuda_core/tests/test_linker.py

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import pytest
2+
from cuda.core.experimental._linker import Linker, LinkerOptions
3+
from cuda.core.experimental._module import ObjectCode
4+
from cuda.core.experimental._program import Program
5+
6+
ARCH = "sm_80" # use sm_80 for testing the oop nvJitLink wrapper
7+
empty_entrypoint_kernel = "__global__ void A() {}"
8+
empty_kernel = "__device__ void B() {}"
9+
addition_kernel = "__device__ int C(int a, int b) { return a + b; }"
10+
11+
12+
@pytest.fixture(scope="module")
13+
def compile_ptx_functions(init_cuda):
14+
15+
object_code_a_ptx = Program(empty_entrypoint_kernel, "c++").compile("ptx")
16+
object_code_b_ptx = Program(empty_kernel, "c++").compile("ptx")
17+
object_code_c_ptx = Program(addition_kernel, "c++").compile("ptx")
18+
19+
return object_code_a_ptx, object_code_b_ptx, object_code_c_ptx
20+
21+
22+
@pytest.fixture(scope="module")
23+
def compile_ltoir_functions(init_cuda):
24+
object_code_a_ltoir = Program(empty_entrypoint_kernel, "c++").compile("ltoir", options=("-dlto",))
25+
object_code_b_ltoir = Program(empty_kernel, "c++").compile("ltoir", options=("-dlto",))
26+
object_code_c_ltoir = Program(addition_kernel, "c++").compile("ltoir", options=("-dlto",))
27+
28+
return object_code_a_ltoir, object_code_b_ltoir, object_code_c_ltoir
29+
30+
31+
def test_linker_init_valid_options():
32+
options = LinkerOptions(arch=ARCH)
33+
linker = Linker(options)
34+
assert linker.handle is not None
35+
36+
def test_linker_init_invalid_arch():
37+
options = LinkerOptions(arch=None)
38+
with pytest.raises(ValueError):
39+
Linker(options)
40+
41+
def test_linker_init(compile_ptx_functions):
42+
combinations = [
43+
LinkerOptions(arch=ARCH),
44+
LinkerOptions(arch=ARCH, max_register_count=32),
45+
LinkerOptions(arch=ARCH, time=True),
46+
LinkerOptions(arch=ARCH, verbose=True),
47+
LinkerOptions(arch=ARCH, optimization_level=3),
48+
LinkerOptions(arch=ARCH, debug=True),
49+
LinkerOptions(arch=ARCH, lineinfo=True),
50+
LinkerOptions(arch=ARCH, ftz=True),
51+
LinkerOptions(arch=ARCH, prec_div=True),
52+
LinkerOptions(arch=ARCH, prec_sqrt=True),
53+
LinkerOptions(arch=ARCH, fma=True),
54+
LinkerOptions(arch=ARCH, kernels_used=["kernel1"]),
55+
LinkerOptions(arch=ARCH, variables_used=["var1"]),
56+
LinkerOptions(arch=ARCH, optimize_unused_variables=True),
57+
LinkerOptions(arch=ARCH, xptxas=["-v"]),
58+
LinkerOptions(arch=ARCH, split_compile=0),
59+
LinkerOptions(arch=ARCH, split_compile_extended=1),
60+
LinkerOptions(arch=ARCH, jump_table_density=100),
61+
LinkerOptions(arch=ARCH, no_cache=True)
62+
]
63+
64+
# Try the combinations, with and without providing object codes to the constructor
65+
for i, options in enumerate(combinations):
66+
linker = Linker(options, object_codes=compile_ptx_functions)
67+
object_code = linker.link("cubin")
68+
assert isinstance(object_code, ObjectCode)
69+
70+
def test_linker_add_code_object(compile_ptx_functions):
71+
options = LinkerOptions(arch=ARCH)
72+
linker = Linker(options)
73+
functions = compile_ptx_functions
74+
linker.add_code_object(functions[0])
75+
linker.add_code_object(functions[1])
76+
linker.add_code_object(functions[2])
77+
78+
def test_linker_link_ptx(compile_ltoir_functions):
79+
options = LinkerOptions(arch=ARCH, link_time_optimization=True, ptx=True)
80+
linker = Linker(options)
81+
functions = compile_ltoir_functions
82+
linker.add_code_object(functions[0])
83+
linker.add_code_object(functions[1])
84+
linker.add_code_object(functions[2])
85+
linked_code = linker.link("ptx")
86+
assert isinstance(linked_code, ObjectCode)
87+
88+
def test_linker_link_cubin(compile_ptx_functions):
89+
options = LinkerOptions(arch=ARCH)
90+
linker = Linker(options)
91+
functions = compile_ptx_functions
92+
linker.add_code_object(functions[0])
93+
linker.add_code_object(functions[1])
94+
linker.add_code_object(functions[2])
95+
linked_code = linker.link("cubin")
96+
assert isinstance(linked_code, ObjectCode)
97+
98+
def test_linker_link_invalid_target_type(compile_ptx_functions):
99+
options = LinkerOptions(arch=ARCH)
100+
linker = Linker(options)
101+
functions = compile_ptx_functions
102+
linker.add_code_object(functions[0])
103+
linker.add_code_object(functions[1])
104+
linker.add_code_object(functions[2])
105+
with pytest.raises(ValueError):
106+
linker.link("invalid_target")
107+
108+
def test_linker_get_error_log(compile_ptx_functions):
109+
options = LinkerOptions(arch=ARCH)
110+
linker = Linker(options)
111+
functions = compile_ptx_functions
112+
linker.add_code_object(functions[0])
113+
linker.add_code_object(functions[1])
114+
linker.add_code_object(functions[2])
115+
linker.link("cubin")
116+
log = linker.get_error_log()
117+
assert isinstance(log, str)
118+
119+
def test_linker_get_info_log(compile_ptx_functions):
120+
options = LinkerOptions(arch=ARCH)
121+
linker = Linker(options)
122+
functions = compile_ptx_functions
123+
linker.add_code_object(functions[0])
124+
linker.add_code_object(functions[1])
125+
linker.add_code_object(functions[2])
126+
linker.link("cubin")
127+
log = linker.get_info_log()
128+
assert isinstance(log, str)

0 commit comments

Comments
 (0)