Skip to content

Commit 4840061

Browse files
committed
cache primary context
1 parent 8cc1b68 commit 4840061

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

cuda_core/cuda/core/experimental/_device.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1022,6 +1022,18 @@ def _check_context_initialized(self):
10221022
f"Device {self._id} is not yet initialized, perhaps you forgot to call .set_current() first?"
10231023
)
10241024

1025+
def _get_primary_context(self) -> driver.CUcontext:
1026+
try:
1027+
primary_ctxs = _tls.primary_ctxs
1028+
except AttributeError:
1029+
total = len(_tls.devices)
1030+
primary_ctxs = _tls.primary_ctxs = [None] * total
1031+
ctx = primary_ctxs[self._id]
1032+
if ctx is None:
1033+
ctx = handle_return(driver.cuDevicePrimaryCtxRetain(self._id))
1034+
primary_ctxs[self._id] = ctx
1035+
return ctx
1036+
10251037
def _get_current_context(self, check_consistency=False) -> driver.CUcontext:
10261038
err, ctx = driver.cuCtxGetCurrent()
10271039

@@ -1189,13 +1201,13 @@ def set_current(self, ctx: Context = None) -> Union[Context, None]:
11891201
ctx = handle_return(driver.cuCtxGetCurrent())
11901202
if int(ctx) == 0:
11911203
# use primary ctx
1192-
ctx = handle_return(driver.cuDevicePrimaryCtxRetain(self._id))
1204+
ctx = self._get_primary_context()
11931205
handle_return(driver.cuCtxPushCurrent(ctx))
11941206
else:
11951207
ctx_id = handle_return(driver.cuCtxGetDevice())
11961208
if ctx_id != self._id:
11971209
# use primary ctx
1198-
ctx = handle_return(driver.cuDevicePrimaryCtxRetain(self._id))
1210+
ctx = self._get_primary_context()
11991211
handle_return(driver.cuCtxPushCurrent(ctx))
12001212
else:
12011213
# no-op, a valid context already exists and is set current

0 commit comments

Comments
 (0)