tensoracle 2.6.0__cp312-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. tensoracle/__init__.py +28 -0
  2. tensoracle/_cli.py +172 -0
  3. tensoracle/_comparison.py +46 -0
  4. tensoracle/_native.pyd +0 -0
  5. tensoracle/_native.pyi +48 -0
  6. tensoracle/_version.py +24 -0
  7. tensoracle/bundle.py +45 -0
  8. tensoracle/convert.py +71 -0
  9. tensoracle/cpp/bin/tensoracle-2.dll +0 -0
  10. tensoracle/cpp/cmake/TensoracleCubinPlugin.cmake +59 -0
  11. tensoracle/cpp/cmake/TensoracleCuda.cmake +119 -0
  12. tensoracle/cpp/include/tensoracle/builder.h +128 -0
  13. tensoracle/cpp/include/tensoracle/builder.hpp +130 -0
  14. tensoracle/cpp/include/tensoracle/cache.h +110 -0
  15. tensoracle/cpp/include/tensoracle/cache.hpp +57 -0
  16. tensoracle/cpp/include/tensoracle/cubin.h +103 -0
  17. tensoracle/cpp/include/tensoracle/cubin.hpp +72 -0
  18. tensoracle/cpp/include/tensoracle/cubin_plugin.hpp +175 -0
  19. tensoracle/cpp/include/tensoracle/engine.h +109 -0
  20. tensoracle/cpp/include/tensoracle/engine.hpp +109 -0
  21. tensoracle/cpp/include/tensoracle/plugins.h +48 -0
  22. tensoracle/cpp/include/tensoracle/plugins.hpp +48 -0
  23. tensoracle/cpp/include/tensoracle/tensoracle.h +165 -0
  24. tensoracle/cpp/include/tensoracle/tensoracle.hpp +75 -0
  25. tensoracle/cpp/lib/cmake/tensoracle/tensoracleConfig.cmake +71 -0
  26. tensoracle/cpp/lib/cmake/tensoracle/tensoracleConfigVersion.cmake +65 -0
  27. tensoracle/cpp/lib/cmake/tensoracle/tensoracleTargets-release.cmake +19 -0
  28. tensoracle/cpp/lib/cmake/tensoracle/tensoracleTargets.cmake +109 -0
  29. tensoracle/cpp/lib/tensoracle.lib +0 -0
  30. tensoracle/cpp/licenses/miniz/LICENSE +22 -0
  31. tensoracle/cpp/licenses/nlohmann-json/LICENSE.MIT +21 -0
  32. tensoracle/cpp/src/cubin_plugin.cpp +360 -0
  33. tensoracle/cpp/src/sha256.hpp +195 -0
  34. tensoracle/producer.py +48 -0
  35. tensoracle/py.typed +0 -0
  36. tensoracle-2.6.0.dist-info/METADATA +196 -0
  37. tensoracle-2.6.0.dist-info/RECORD +40 -0
  38. tensoracle-2.6.0.dist-info/WHEEL +5 -0
  39. tensoracle-2.6.0.dist-info/entry_points.txt +3 -0
  40. tensoracle-2.6.0.dist-info/licenses/LICENSE +21 -0
tensoracle/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ """Compare outputs, produce and inspect cubins, manage caches, and convert checkpoints."""
2
+
3
+ import os as _os
4
+ from importlib import import_module as _import_module
5
+ from pathlib import Path as _Path
6
+
7
+ if _os.name == "nt":
8
+ # Keep the registration alive for bindings imported later in this process.
9
+ # Editable installs keep Python sources and native files in different package paths.
10
+ _dll_root = next(
11
+ _Path(location) / "cpp" / "bin"
12
+ for location in __path__
13
+ if (_Path(location) / "cpp" / "bin").is_dir()
14
+ )
15
+ _dll_directory = _os.add_dll_directory(str(_dll_root))
16
+
17
+ __all__ = [
18
+ "OutputComparison",
19
+ "compare_outputs",
20
+ ]
21
+
22
+
23
+ def __getattr__(name: str):
24
+ if name not in __all__:
25
+ raise AttributeError(name)
26
+ value = getattr(_import_module("._comparison", __name__), name)
27
+ globals()[name] = value
28
+ return value
tensoracle/_cli.py ADDED
@@ -0,0 +1,172 @@
1
+ """List and prune saved TensorRT engines without importing TensorRT."""
2
+
3
+ import argparse
4
+ import json
5
+ import re
6
+ import sys
7
+ from datetime import UTC, datetime
8
+ from decimal import Decimal, DecimalException, InvalidOperation
9
+
10
+ _DAY_NS = 86_400_000_000_000
11
+
12
+
13
+ def _details(entry: dict) -> dict:
14
+ """Format metadata copied from a native result; never inspect a cache file here."""
15
+ details = {key: entry[key] for key in ("file", "status", "size_bytes")}
16
+ seconds = entry["recorded_at_seconds"]
17
+ if seconds is not None:
18
+ details["recorded_at_ns"] = seconds * 1_000_000_000 + entry["recorded_at_nanoseconds"]
19
+ try:
20
+ details["recorded_at"] = datetime.fromtimestamp(seconds, UTC).isoformat()
21
+ except (OverflowError, OSError, ValueError):
22
+ details["recorded_at"] = None
23
+ if "header" in entry:
24
+ details["conditions"] = entry["header"]["conditions"]
25
+ details["workspace_limit"] = entry["header"].get("workspace_limit", "unknown")
26
+ for key in ("weight_paths", "reason"):
27
+ if key in entry:
28
+ details[key] = entry[key]
29
+ return details
30
+
31
+
32
+ def _entries(result, collection="entries") -> list[dict]:
33
+ return [_details(entry) for entry in result.entries(collection)]
34
+
35
+
36
+ def _list(result) -> int:
37
+ summary = result.summary()
38
+ print(
39
+ json.dumps(
40
+ {
41
+ "directory": summary["directory"],
42
+ "entries": _entries(result),
43
+ "total_size_bytes": summary["total_size_bytes"],
44
+ }
45
+ )
46
+ )
47
+ return 0
48
+
49
+
50
+ def _prune(native, plan, *, dry_run: bool) -> int:
51
+ summary = plan.summary()
52
+ print(
53
+ json.dumps(
54
+ {
55
+ "event": "plan",
56
+ "directory": summary["directory"],
57
+ "dry_run": dry_run,
58
+ "rebuild_notice": "Removed engines will be rebuilt the next time they are used.",
59
+ "targets": _entries(plan, "targets"),
60
+ "excluded": _entries(plan, "excluded"),
61
+ "total_size_bytes": summary["total_size_bytes"],
62
+ }
63
+ ),
64
+ flush=True,
65
+ )
66
+ result = native.cache_apply_prune(plan, dry_run=dry_run)
67
+ summary = result.summary()
68
+ print(
69
+ json.dumps(
70
+ {
71
+ "event": "result",
72
+ "dry_run": summary["dry_run"],
73
+ "removed": _entries(result, "removed"),
74
+ "excluded": _entries(result, "excluded"),
75
+ "failed": [
76
+ {"file": entry["file"], "reason": entry["reason"]}
77
+ for entry in result.entries("failed")
78
+ ],
79
+ "missing": [
80
+ {"file": entry["file"], "reason": entry["reason"]}
81
+ for entry in result.entries("missing")
82
+ ],
83
+ **{
84
+ key: summary[key]
85
+ for key in (
86
+ "removed_size_bytes",
87
+ "remaining_size_bytes",
88
+ "projected_size_bytes",
89
+ "max_size_bytes",
90
+ "max_size_reached",
91
+ )
92
+ },
93
+ }
94
+ )
95
+ )
96
+ return int(not summary["succeeded"])
97
+
98
+
99
+ def _days(value: str) -> Decimal:
100
+ try:
101
+ days = Decimal(value)
102
+ if days.is_finite() and days >= 0:
103
+ return days
104
+ except InvalidOperation:
105
+ pass
106
+ raise argparse.ArgumentTypeError("days must be a finite, nonnegative number")
107
+
108
+
109
+ def _size(value: str) -> int:
110
+ match = re.fullmatch(r"(\d+(?:\.\d+)?)\s*(B|KiB|MiB|GiB|TiB)?", value, re.IGNORECASE)
111
+ if match is None:
112
+ raise argparse.ArgumentTypeError(
113
+ "use nonnegative bytes or B, KiB, MiB, GiB, TiB (e.g. 1.5GiB)"
114
+ )
115
+ units = {"b": 1, "kib": 1024, "mib": 1024**2, "gib": 1024**3, "tib": 1024**4}
116
+ return int(Decimal(match[1]) * units[(match[2] or "B").lower()])
117
+
118
+
119
+ def main(argv: list[str] | None = None) -> int:
120
+ """Run the installed ``tensoracle cache`` commands; return 0, 1, or usage error 2."""
121
+ parser = argparse.ArgumentParser(prog="tensoracle")
122
+ commands = parser.add_subparsers(dest="command", required=True)
123
+ cache = commands.add_parser("cache", help="inspect or prune saved TensorRT engines")
124
+ actions = cache.add_subparsers(dest="action", required=True)
125
+ actions.add_parser(
126
+ "list", help="show conditions, sizes, recorded times, and known weight paths as JSON"
127
+ )
128
+ prune = actions.add_parser(
129
+ "prune",
130
+ help="remove old engines during maintenance",
131
+ description=(
132
+ "Print selected engines and a rebuild notice before removal, then report results as JSON. "
133
+ "Use during maintenance without concurrent engine builds or opens; these are not locked. "
134
+ "Empty and unrecognized files are kept and count toward the total .engine bytes."
135
+ ),
136
+ )
137
+ criteria = prune.add_mutually_exclusive_group(required=True)
138
+ criteria.add_argument(
139
+ "--unused-for",
140
+ type=_days,
141
+ metavar="DAYS",
142
+ help="remove engines recorded strictly before DAYS days ago (24 hours/day; fractions allowed)",
143
+ )
144
+ criteria.add_argument(
145
+ "--max-size",
146
+ type=_size,
147
+ metavar="SIZE",
148
+ help="remove oldest engines until total .engine bytes <= SIZE; bytes or B/KiB/MiB/GiB/TiB; fractions rounded down",
149
+ )
150
+ prune.add_argument(
151
+ "--dry-run", action="store_true", help="show the same selection without removing files"
152
+ )
153
+ args = parser.parse_args(argv)
154
+ try:
155
+ from . import _native
156
+
157
+ if args.action == "list":
158
+ return _list(_native.cache_list())
159
+ plan = _native.cache_plan_prune(
160
+ unused_for_ns=None if args.unused_for is None else int(args.unused_for * _DAY_NS),
161
+ max_size_bytes=args.max_size,
162
+ )
163
+ return _prune(_native, plan, dry_run=args.dry_run)
164
+ except (ValueError, DecimalException, OverflowError) as error:
165
+ parser.error(str(error))
166
+ except (OSError, RuntimeError) as error:
167
+ print(f"tensoracle: {error}", file=sys.stderr)
168
+ return 1
169
+
170
+
171
+ if __name__ == "__main__":
172
+ raise SystemExit(main())
@@ -0,0 +1,46 @@
1
+ """Model-independent measurements for one pair of CPU output arrays."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ import numpy as np
6
+
7
+ from . import _native
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class OutputComparison:
12
+ """Measurements for a candidate output against its reference output.
13
+
14
+ Float measurements are ``None`` for integer or boolean arrays and when
15
+ either float array contains a non-finite value. Tolerance measurements are
16
+ also ``None`` when the caller has not supplied both tolerances. Mismatch
17
+ measurements apply only to integer and boolean arrays.
18
+ """
19
+
20
+ candidate_nonfinite_count: int
21
+ reference_nonfinite_count: int
22
+ max_absolute_error: float | None = None
23
+ relative_l2_error: float | None = None
24
+ cosine_similarity: float | None = None
25
+ outside_tolerance_count: int | None = None
26
+ outside_tolerance_fraction: float | None = None
27
+ mismatch_count: int | None = None
28
+ mismatch_fraction: float | None = None
29
+
30
+
31
+ def compare_outputs(
32
+ candidate: np.ndarray,
33
+ reference: np.ndarray,
34
+ *,
35
+ atol: float | None = None,
36
+ rtol: float | None = None,
37
+ ) -> OutputComparison:
38
+ """Measure one candidate output against the corresponding reference output.
39
+
40
+ Both inputs must be nonempty NumPy arrays of equal shape and the same kind:
41
+ floating point, integer, or boolean. Floating point inputs are converted
42
+ to float64 before arithmetic. Tolerances must be finite, nonnegative, and
43
+ supplied together. This function reports measurements; the caller chooses
44
+ the limits that constitute an acceptable output.
45
+ """
46
+ return OutputComparison(*_native.compare_outputs(candidate, reference, atol=atol, rtol=rtol))
tensoracle/_native.pyd ADDED
Binary file
tensoracle/_native.pyi ADDED
@@ -0,0 +1,48 @@
1
+ """Thin bindings to tensoracle's shared C ABI"""
2
+
3
+
4
+
5
+ class BundleError(ValueError):
6
+ pass
7
+
8
+ class MissingCubinError(BundleError):
9
+ pass
10
+
11
+ class CorruptCubinError(BundleError):
12
+ pass
13
+
14
+ class CubinArchitectureError(BundleError):
15
+ pass
16
+
17
+ class PluginBundleMismatchError(BundleError):
18
+ pass
19
+
20
+ class CompilationError(BundleError):
21
+ pass
22
+
23
+ def cubin_sm(arg: bytes, /) -> str: ...
24
+
25
+ def bundle_sha256(arg: str, /) -> str: ...
26
+
27
+ def inspect_bundle(path: str, plugin: object | None) -> str: ...
28
+
29
+ def inspect_wheel(path: str, plugin: object | None) -> str: ...
30
+
31
+ def compile_bundle(inputs: list, output: str, root: str, ptxas: object | None, cuobjdump: object | None, nvrtc: object | None) -> str: ...
32
+
33
+ def version() -> tuple: ...
34
+
35
+ def tensorrt_version() -> tuple: ...
36
+
37
+ def compare_outputs(candidate: object, reference: object, *, atol: object | None = None, rtol: object | None = None) -> tuple: ...
38
+
39
+ class _CacheResult:
40
+ def summary(self) -> dict: ...
41
+
42
+ def entries(self, collection: str = 'entries') -> list: ...
43
+
44
+ def cache_list() -> _CacheResult: ...
45
+
46
+ def cache_plan_prune(*, unused_for_ns: object | None = None, max_size_bytes: object | None = None) -> _CacheResult: ...
47
+
48
+ def cache_apply_prune(plan: _CacheResult, *, dry_run: bool = False) -> _CacheResult: ...
tensoracle/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '2.6.0'
22
+ __version_tuple__ = version_tuple = (2, 6, 0)
23
+
24
+ __commit_id__ = commit_id = None
tensoracle/bundle.py ADDED
@@ -0,0 +1,45 @@
1
+ """Inspect cubin bundles and wheels through the C++ implementation."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from . import _native
7
+ from ._native import (
8
+ BundleError,
9
+ CorruptCubinError,
10
+ CubinArchitectureError,
11
+ MissingCubinError,
12
+ PluginBundleMismatchError,
13
+ )
14
+
15
+ __all__ = [
16
+ "BundleError",
17
+ "CorruptCubinError",
18
+ "CubinArchitectureError",
19
+ "MissingCubinError",
20
+ "PluginBundleMismatchError",
21
+ "bundle_sha256",
22
+ "cubin_sm",
23
+ "inspect_bundle",
24
+ "inspect_wheel",
25
+ ]
26
+
27
+
28
+ def bundle_sha256(manifest: dict) -> str:
29
+ """Return the C++ manifest identity, excluding its own digest field."""
30
+ return _native.bundle_sha256(json.dumps(manifest))
31
+
32
+
33
+ def cubin_sm(data: bytes) -> str:
34
+ """Read a cubin's NVIDIA architecture without initializing CUDA."""
35
+ return _native.cubin_sm(bytes(data))
36
+
37
+
38
+ def inspect_bundle(root: Path, *, plugin: Path | None = None) -> str:
39
+ """Verify the manifest, cubins, and optional plugin without loading the plugin."""
40
+ return _native.inspect_bundle(str(root), None if plugin is None else str(plugin))
41
+
42
+
43
+ def inspect_wheel(path: Path, *, plugin: str | None = None) -> str:
44
+ """Inspect the one cubin bundle inside a wheel without installing it."""
45
+ return _native.inspect_wheel(str(path), plugin)
tensoracle/convert.py ADDED
@@ -0,0 +1,71 @@
1
+ """Convert PyTorch tensor checkpoints to safetensors with optional torch dependencies."""
2
+
3
+ import argparse
4
+ import os
5
+ import pickle
6
+ from collections.abc import Mapping
7
+
8
+
9
+ def pth_to_safetensors(source: str | os.PathLike[str], destination: str | os.PathLike[str]) -> None:
10
+ """Write a tensor mapping to safetensors without unrestricted pickle loading.
11
+
12
+ Nested string keys are joined with ``.``. Invalid mapping keys or leaves
13
+ raise ``TypeError``; duplicate flattened names raise ``ValueError``.
14
+ Both are rejected before the destination is written.
15
+ Torch is required only when this function is called.
16
+ """
17
+ try:
18
+ import torch
19
+ except ImportError as exc:
20
+ raise ImportError(
21
+ "Checkpoint conversion requires torch; install it with pip install 'tensoracle[convert]'"
22
+ ) from exc
23
+ from safetensors.torch import save_file
24
+
25
+ try:
26
+ checkpoint = torch.load(source, map_location="cpu", weights_only=True)
27
+ except pickle.UnpicklingError as exc:
28
+ raise ValueError(f"Cannot safely load tensor checkpoint: {source}") from exc
29
+ if not isinstance(checkpoint, Mapping):
30
+ raise TypeError("Checkpoint must be a mapping of string keys to tensors or nested mappings")
31
+
32
+ tensors = {}
33
+ active_mappings = set()
34
+
35
+ def flatten(mapping: Mapping, prefix: tuple[str, ...]) -> None:
36
+ if id(mapping) in active_mappings:
37
+ raise ValueError("Checkpoint contains a cyclic mapping")
38
+ active_mappings.add(id(mapping))
39
+ for key, value in mapping.items():
40
+ if not isinstance(key, str):
41
+ raise TypeError("Checkpoint mapping keys must be strings")
42
+ parts = (*prefix, key)
43
+ name = ".".join(parts)
44
+ if isinstance(value, Mapping):
45
+ flatten(value, parts)
46
+ elif isinstance(value, torch.Tensor):
47
+ if name in tensors:
48
+ raise ValueError(f"Duplicate flattened tensor name: {name}")
49
+ # Separate shared storage and make views contiguous without changing values.
50
+ tensors[name] = value.detach().clone(memory_format=torch.contiguous_format)
51
+ else:
52
+ raise TypeError(f"Checkpoint value at {name!r} must be a tensor or mapping")
53
+ active_mappings.remove(id(mapping))
54
+
55
+ flatten(checkpoint, ())
56
+ save_file(tensors, destination)
57
+
58
+
59
+ def _main() -> None:
60
+ parser = argparse.ArgumentParser(description="Convert a PyTorch checkpoint to safetensors")
61
+ parser.add_argument("source", help="input .pth checkpoint")
62
+ parser.add_argument("destination", help="output .safetensors file")
63
+ args = parser.parse_args()
64
+ try:
65
+ pth_to_safetensors(args.source, args.destination)
66
+ except (ImportError, OSError, TypeError, ValueError, RuntimeError) as exc:
67
+ parser.exit(1, f"{parser.prog}: {exc}\n")
68
+
69
+
70
+ if __name__ == "__main__":
71
+ _main()
Binary file
@@ -0,0 +1,59 @@
1
+ include_guard(GLOBAL)
2
+ include("${CMAKE_CURRENT_LIST_DIR}/TensoracleCuda.cmake")
3
+
4
+ function(tensoracle_add_cubin_plugin)
5
+ cmake_parse_arguments(ARG "" "TARGET;TYPE;TENSORRT_ROOT;BUNDLE_ROOT" "SOURCES" ${ARGN})
6
+ if(NOT ARG_TARGET OR NOT ARG_TENSORRT_ROOT OR NOT ARG_BUNDLE_ROOT OR NOT ARG_SOURCES)
7
+ message(FATAL_ERROR "TARGET, TENSORRT_ROOT, BUNDLE_ROOT, and SOURCES are required")
8
+ endif()
9
+ if(NOT DEFINED ARG_TYPE)
10
+ set(ARG_TYPE SHARED)
11
+ endif()
12
+ if(NOT ARG_TYPE MATCHES "^(SHARED|STATIC|OBJECT)$")
13
+ message(FATAL_ERROR "TYPE must be SHARED, STATIC, or OBJECT")
14
+ endif()
15
+
16
+ if(WIN32)
17
+ # CMake source lists use forward slashes, including paths supplied by a
18
+ # native Windows caller rather than CMAKE_CURRENT_SOURCE_DIR.
19
+ file(TO_CMAKE_PATH "${ARG_TENSORRT_ROOT}" ARG_TENSORRT_ROOT)
20
+ file(TO_CMAKE_PATH "${ARG_BUNDLE_ROOT}" ARG_BUNDLE_ROOT)
21
+ set(_tensoracle_sources)
22
+ foreach(_source IN LISTS ARG_SOURCES)
23
+ file(TO_CMAKE_PATH "${_source}" _source)
24
+ list(APPEND _tensoracle_sources "${_source}")
25
+ endforeach()
26
+ set(ARG_SOURCES "${_tensoracle_sources}")
27
+ endif()
28
+
29
+ get_filename_component(_tensoracle_cpp "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/.." ABSOLUTE)
30
+ _tensoracle_find_cuda()
31
+ find_path(TENSORACLE_NVINFER_INCLUDE NvInfer.h
32
+ PATHS "${ARG_TENSORRT_ROOT}/include" NO_DEFAULT_PATH REQUIRED)
33
+ set(_tensoracle_nvinfer_names nvinfer)
34
+ if(WIN32)
35
+ list(PREPEND _tensoracle_nvinfer_names nvinfer_11)
36
+ endif()
37
+ find_library(TENSORACLE_NVINFER_LIBRARY NAMES ${_tensoracle_nvinfer_names}
38
+ PATHS "${ARG_TENSORRT_ROOT}/lib" "${ARG_TENSORRT_ROOT}/lib64"
39
+ NO_DEFAULT_PATH REQUIRED)
40
+
41
+ add_library(${ARG_TARGET} ${ARG_TYPE}
42
+ ${ARG_SOURCES}
43
+ "${_tensoracle_cpp}/src/cubin_plugin.cpp"
44
+ "${ARG_BUNDLE_ROOT}/bundle.cpp")
45
+ target_compile_features(${ARG_TARGET} PRIVATE cxx_std_17)
46
+ target_compile_options(${ARG_TARGET} PRIVATE
47
+ $<$<CXX_COMPILER_ID:GNU,Clang>:-Wno-deprecated-declarations>)
48
+ target_include_directories(${ARG_TARGET} PRIVATE
49
+ "${_tensoracle_cpp}/include" "${TENSORACLE_NVINFER_INCLUDE}")
50
+ target_link_libraries(${ARG_TARGET} PRIVATE
51
+ "${TENSORACLE_NVINFER_LIBRARY}" tensoracle_internal_cuda_driver)
52
+ if(NOT WIN32)
53
+ find_package(Threads REQUIRED)
54
+ target_link_libraries(${ARG_TARGET} PRIVATE Threads::Threads)
55
+ endif()
56
+ set_target_properties(${ARG_TARGET} PROPERTIES
57
+ POSITION_INDEPENDENT_CODE ON
58
+ CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN YES)
59
+ endfunction()
@@ -0,0 +1,119 @@
1
+ include_guard(GLOBAL)
2
+
3
+ # Only the Driver API is needed by the C++ helpers. Runtime-only Conan SDKs
4
+ # supply the headers and link stub without nvcc or an OS toolkit installation.
5
+ function(_tensoracle_find_cuda)
6
+ if(CUDAToolkit_ROOT)
7
+ set(_roots "${CUDAToolkit_ROOT}")
8
+ elseif(DEFINED ENV{CUDAToolkit_ROOT} AND NOT "$ENV{CUDAToolkit_ROOT}" STREQUAL "")
9
+ set(_roots "$ENV{CUDAToolkit_ROOT}")
10
+ else()
11
+ set(_roots "${CMAKE_CUDA_COMPILER_TOOLKIT_ROOT}")
12
+ foreach(_compiler IN ITEMS "${CMAKE_CUDA_COMPILER}" "$ENV{CUDACXX}")
13
+ if(EXISTS "${_compiler}")
14
+ get_filename_component(_bin "${_compiler}" DIRECTORY)
15
+ get_filename_component(_root "${_bin}/.." ABSOLUTE)
16
+ list(APPEND _roots "${_root}")
17
+ endif()
18
+ endforeach()
19
+ find_program(_tensoracle_cuda_nvcc NAMES nvcc nvcc.exe)
20
+ if(_tensoracle_cuda_nvcc)
21
+ get_filename_component(_nvcc "${_tensoracle_cuda_nvcc}" REALPATH)
22
+ get_filename_component(_bin "${_nvcc}" DIRECTORY)
23
+ get_filename_component(_root "${_bin}/.." ABSOLUTE)
24
+ list(APPEND _roots "${_root}")
25
+ endif()
26
+ # Remove private find results before CMake writes its cache (CMake 3.20
27
+ # predates find_program/find_library's NO_CACHE option).
28
+ unset(_tensoracle_cuda_nvcc CACHE)
29
+ if(DEFINED ENV{CUDA_PATH})
30
+ list(APPEND _roots "$ENV{CUDA_PATH}")
31
+ endif()
32
+ if(WIN32)
33
+ file(GLOB _defaults "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v*")
34
+ else()
35
+ file(GLOB _defaults "/usr/local/cuda-*")
36
+ list(APPEND _roots "/usr/local/cuda")
37
+ endif()
38
+ list(SORT _defaults COMPARE NATURAL ORDER DESCENDING)
39
+ list(APPEND _roots ${_defaults})
40
+ endif()
41
+
42
+ set(_searched_includes)
43
+ set(_include)
44
+ foreach(_root IN LISTS _roots)
45
+ foreach(_candidate IN ITEMS "${_root}/include" "${_root}/targets/x86_64-linux/include")
46
+ list(APPEND _searched_includes "${_candidate}")
47
+ if(EXISTS "${_candidate}/cuda.h")
48
+ set(_include "${_candidate}")
49
+ set(_selected_root "${_root}")
50
+ break()
51
+ endif()
52
+ endforeach()
53
+ if(_include)
54
+ break()
55
+ endif()
56
+ endforeach()
57
+ set(_root "${_selected_root}")
58
+ if(NOT _include)
59
+ message(FATAL_ERROR "CUDA header cuda.h was not found. Searched: ${_searched_includes}. "
60
+ "Prepare cuda-toolkit/13.2.2 with Conan and set CUDAToolkit_ROOT "
61
+ "to its user.cuda:root, or supply an existing CUDA SDK root.")
62
+ endif()
63
+
64
+ if(WIN32)
65
+ set(_driver_paths "${_root}/lib/x64")
66
+ find_library(_tensoracle_cuda_driver_library NAMES cuda
67
+ PATHS ${_driver_paths} NO_DEFAULT_PATH)
68
+ else()
69
+ set(_driver_paths "${_root}/lib64/stubs" "${_root}/lib/stubs"
70
+ "${_root}/targets/x86_64-linux/lib/stubs" "${_root}/lib64" "${_root}/lib"
71
+ "${_root}/targets/x86_64-linux/lib")
72
+ find_library(_tensoracle_cuda_driver_library NAMES cuda PATHS ${_driver_paths} NO_DEFAULT_PATH)
73
+ if(NOT _tensoracle_cuda_driver_library)
74
+ list(APPEND _driver_paths "/usr/lib/wsl/lib")
75
+ find_library(_tensoracle_cuda_driver_library NAMES cuda
76
+ HINTS "/usr/lib/wsl/lib")
77
+ endif()
78
+ endif()
79
+ set(_driver "${_tensoracle_cuda_driver_library}")
80
+ unset(_tensoracle_cuda_driver_library CACHE)
81
+ if(NOT _driver)
82
+ message(FATAL_ERROR "CUDA driver link library was not found. Searched: ${_driver_paths} "
83
+ "and system library directories. Prepare cuda-toolkit/13.2.2 with Conan "
84
+ "and set CUDAToolkit_ROOT to its user.cuda:root. Existing CUDA SDK roots "
85
+ "and the installed NVIDIA driver on Linux remain supported.")
86
+ endif()
87
+ message(STATUS "tensoracle CUDA headers: ${_include}")
88
+ message(STATUS "tensoracle CUDA driver: ${_driver}")
89
+ if(NOT TARGET tensoracle_internal_cuda_driver)
90
+ add_library(tensoracle_internal_cuda_driver UNKNOWN IMPORTED GLOBAL)
91
+ set_target_properties(tensoracle_internal_cuda_driver PROPERTIES
92
+ IMPORTED_LOCATION "${_driver}" INTERFACE_INCLUDE_DIRECTORIES "${_include}")
93
+ endif()
94
+ if(NOT TARGET tensoracle_cuda_driver)
95
+ add_library(tensoracle_cuda_driver ALIAS tensoracle_internal_cuda_driver)
96
+ endif()
97
+ set(_tensoracle_cuda_root "${_root}" PARENT_SCOPE)
98
+ endfunction()
99
+
100
+ # Return the same CUDA inputs used by tensoracle_add_cubin_plugin and expose
101
+ # tensoracle_cuda_driver for consumers that only need to link the Driver API.
102
+ function(tensoracle_find_cuda)
103
+ cmake_parse_arguments(PARSE_ARGV 0 ARG "" "OUT_INCLUDE_DIR;OUT_DRIVER_LIBRARY" "")
104
+ if(DEFINED ARG_UNPARSED_ARGUMENTS)
105
+ message(FATAL_ERROR "Unrecognized tensoracle_find_cuda arguments: ${ARG_UNPARSED_ARGUMENTS}")
106
+ endif()
107
+ if(ARG_KEYWORDS_MISSING_VALUES OR
108
+ NOT DEFINED ARG_OUT_INCLUDE_DIR OR "${ARG_OUT_INCLUDE_DIR}" STREQUAL "" OR
109
+ NOT DEFINED ARG_OUT_DRIVER_LIBRARY OR "${ARG_OUT_DRIVER_LIBRARY}" STREQUAL "")
110
+ message(FATAL_ERROR
111
+ "tensoracle_find_cuda requires OUT_INCLUDE_DIR and OUT_DRIVER_LIBRARY variable names")
112
+ endif()
113
+
114
+ _tensoracle_find_cuda()
115
+ get_target_property(_include tensoracle_cuda_driver INTERFACE_INCLUDE_DIRECTORIES)
116
+ get_target_property(_driver tensoracle_cuda_driver IMPORTED_LOCATION)
117
+ set("${ARG_OUT_INCLUDE_DIR}" "${_include}" PARENT_SCOPE)
118
+ set("${ARG_OUT_DRIVER_LIBRARY}" "${_driver}" PARENT_SCOPE)
119
+ endfunction()