Skip to content

Commit 23bc351

Browse files
committed
[KMCompiler][TLERaw] Support nvshmem
1 parent 33d73bf commit 23bc351

11 files changed

Lines changed: 1150 additions & 1 deletion

File tree

python/triton/experimental/tle/raw/cache_key.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,16 @@ def compute_tle_raw_source_cache_key(
9494
return hasher.hexdigest()
9595

9696

97+
def compute_tle_raw_host_cache_key(source: Union[str, Path], arch: str) -> str:
98+
"""Hash CUDA host source files."""
99+
source_path = Path(source).resolve()
100+
hasher = hashlib.sha256()
101+
hasher.update(_read_source(source_path).encode())
102+
hasher.update(str(arch).encode())
103+
104+
return hasher.hexdigest()
105+
106+
97107
def bind_tle_raw_source_cache_key(edsl: Any, **dialect_kwargs) -> None:
98108
"""Attach __triton_tle_raw_source_cache_key__ to a @dialect edsl object."""
99109
if getattr(edsl, TLE_RAW_SOURCE_CACHE_KEY_ATTR, None) is not None:

python/triton/experimental/tle/raw/cuda/runtime.py

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,23 @@
66
from pathlib import Path
77
import subprocess
88
from typing import Any, Final
9+
import ctypes
10+
from triton import knobs
911

1012
import torch
1113

1214
from triton._C.libtriton import llvm # pyright: ignore[reportMissingImports]
1315
from triton._C.libtriton.tle.llvm import parse_llvm_ir # pyright: ignore[reportMissingImports]
1416
from triton.experimental.tle.raw.source_store import register_source
17+
from triton.experimental.tle.raw.nvshmem.utils import get_nvshmem_home
1518

1619
# TODO: We use cli tools to compile CUDA code temporarily, and plan to replace it with LLVM components Python bindings in the future.
1720
CLANG = os.getenv("CLANG", "clang")
1821
CLANG_FLAGS = shlex.split(os.getenv("CLANG_FLAGS", ""))
1922

23+
_cumodule_hook_installed = False
24+
_nvshmemx_cumodule_init = None
25+
2026

2127
def _sanitize_clang_ir(ir: str) -> str:
2228
# Newer clang emits attributes that this Triton branch's LLVM parser does
@@ -46,10 +52,43 @@ def _get_cuda_gpu_arch() -> str:
4652
return f"--cuda-gpu-arch=sm_{major}{minor}"
4753

4854

55+
def _get_nvshmemx_cumodule_init():
56+
global _nvshmemx_cumodule_init
57+
if _nvshmemx_cumodule_init is not None:
58+
return _nvshmemx_cumodule_init
59+
60+
nvshmem_home = get_nvshmem_home()
61+
library = ctypes.CDLL(str(Path(nvshmem_home) / "lib" / "libnvshmem_host.so"))
62+
fn = library.nvshmemx_cumodule_init
63+
fn.argtypes = [ctypes.c_void_p]
64+
fn.restype = ctypes.c_int
65+
_nvshmemx_cumodule_init = fn
66+
return fn
67+
68+
69+
def _install_cumodule_hook():
70+
global _cumodule_hook_installed
71+
if _cumodule_hook_installed:
72+
return
73+
74+
def hook(*args, **kwargs):
75+
key = kwargs["key"]
76+
function = kwargs["fn"].jit_function
77+
device = kwargs["compile"]["device"]
78+
kernel = function.device_caches[device][0].get(key)
79+
assert kernel is not None
80+
kernel._init_handles()
81+
result = _get_nvshmemx_cumodule_init()(ctypes.c_void_p(kernel.module))
82+
assert result == 0, f"nvshmemx_cumodule_init failed: {result}"
83+
84+
knobs.runtime.jit_post_compile_hook = hook
85+
_cumodule_hook_installed = True
86+
87+
4988
class CUDAJITFunction(object):
5089

5190
def __init__(self, fn: Any, file: Path, *args, **kwargs) -> None:
52-
super().__init__(*args, **{k: v for k, v in kwargs.items() if k not in ("extern_func_name", "deferred")})
91+
super().__init__()
5392
self.fn: Final[Any] = fn
5493
self.code: Final[str] = file.read_text()
5594
self.region_dialect: Final[str] = "cuda"
@@ -60,6 +99,9 @@ def __init__(self, fn: Any, file: Path, *args, **kwargs) -> None:
6099
self.deferred: Final[bool] = kwargs.get("deferred", False)
61100
self.__triton_builtin__: Final[bool] = True
62101

102+
if "nvshmem" in self.code:
103+
_install_cumodule_hook()
104+
63105
def register_pending_source(self, *, hint: str = "") -> str:
64106
if not self.extern_func_name:
65107
raise RuntimeError("deferred tle_raw CUDA source requires extern_func_name= "
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <cstring>
2+
#include <cuda_runtime.h>
3+
#include <nvshmem.h>
4+
#include <nvshmemx.h>
5+
#include <stdint.h>
6+
#include <stdio.h>
7+
8+
#undef CUDA_CHECK
9+
#define CUDA_CHECK(stmt) \
10+
do { \
11+
cudaError_t result = (stmt); \
12+
if (cudaSuccess != result) { \
13+
fprintf(stderr, "[%s:%d] cuda failed with %s \n", __FILE__, __LINE__, \
14+
cudaGetErrorString(result)); \
15+
exit(-1); \
16+
} \
17+
} while (0)
18+
19+
extern "C" int nvshmem_get_unique_id_bytes(void *uid_buffer,
20+
size_t uid_buffer_size) {
21+
if (uid_buffer_size < sizeof(nvshmemx_uniqueid_t)) {
22+
return -1;
23+
}
24+
25+
nvshmemx_uniqueid_t uid;
26+
nvshmemx_get_uniqueid(&uid);
27+
memcpy(uid_buffer, &uid, sizeof(uid));
28+
return 0;
29+
}
30+
31+
extern "C" int nvshmem_init_from_torch_distributed(int rank, int nranks,
32+
int cuda_device,
33+
void *uid_buffer,
34+
size_t uid_buffer_size) {
35+
if (uid_buffer_size < sizeof(nvshmemx_uniqueid_t)) {
36+
return -1;
37+
}
38+
39+
CUDA_CHECK(cudaSetDevice(cuda_device));
40+
41+
nvshmemx_uniqueid_t uid;
42+
memcpy(&uid, uid_buffer, sizeof(uid));
43+
44+
nvshmemx_init_attr_t attr;
45+
memset(&attr, 0, sizeof(attr));
46+
nvshmemx_set_attr_uniqueid_args(rank, nranks, &uid, &attr);
47+
nvshmemx_init_attr(NVSHMEMX_INIT_WITH_UNIQUEID, &attr);
48+
49+
return 0;
50+
}
51+
52+
extern "C" int nvshmem_finalize_from_torch_distributed() {
53+
nvshmem_finalize();
54+
55+
return 0;
56+
}

0 commit comments

Comments
 (0)