33# SPDX-License-Identifier: LicenseRef-NVIDIA-SOFTWARE-LICENSE
44
55from dataclasses import dataclass
6+ from typing import Optional , Any
67
78from cuda .core .experimental ._utils .clear_error_support import assert_type
89from cuda .core .experimental ._utils .cuda_utils import driver
@@ -16,13 +17,57 @@ class ContextOptions:
1617class Context :
1718 __slots__ = ("_handle" , "_id" )
1819
19- def __new__ (self , * args , ** kwargs ) :
20+ def __new__ (self , * args : Any , ** kwargs : Any ) -> None :
2021 raise RuntimeError ("Context objects cannot be instantiated directly. Please use Device or Stream APIs." )
2122
2223 @classmethod
23- def _from_ctx (cls , obj , dev_id ) :
24+ def _from_ctx (cls , obj : driver . CUcontext , dev_id : int ) -> "Context" :
2425 assert_type (obj , driver .CUcontext )
2526 ctx = super ().__new__ (cls )
2627 ctx ._handle = obj
2728 ctx ._id = dev_id
2829 return ctx
30+
31+ @classmethod
32+ def _init (cls , device_id : int , options : Optional [ContextOptions ] = None ) -> "Context" :
33+ """Initialize a new context."""
34+ handle = driver .CUcontext ()
35+ handle_return (driver .cuCtxCreate (handle , options , device_id ))
36+ return cls ._from_ctx (handle , device_id )
37+
38+ @classmethod
39+ def current (cls ) -> Optional ["Context" ]:
40+ """Get the current context."""
41+ handle = driver .CUcontext ()
42+ handle_return (driver .cuCtxGetCurrent (handle ))
43+ if int (handle ) == 0 :
44+ return None
45+ device_id = driver .CUdevice ()
46+ handle_return (driver .cuCtxGetDevice (device_id ))
47+ return cls ._from_ctx (handle , device_id )
48+
49+ def set_current (self ) -> None :
50+ """Set this context as the current context."""
51+ handle_return (driver .cuCtxSetCurrent (self ._handle ))
52+
53+ def pop_current (self ) -> None :
54+ """Pop this context from the current thread's context stack."""
55+ handle_return (driver .cuCtxPopCurrent (self ._handle ))
56+
57+ def push_current (self ) -> None :
58+ """Push this context onto the current thread's context stack."""
59+ handle_return (driver .cuCtxPushCurrent (self ._handle ))
60+
61+ @property
62+ def handle (self ) -> driver .CUcontext :
63+ """Get the CUDA context handle."""
64+ return self ._handle
65+
66+ @property
67+ def device_id (self ) -> int :
68+ """Get the device ID associated with this context."""
69+ return self ._id
70+
71+ def __repr__ (self ) -> str :
72+ """Return a string representation of the context."""
73+ return f"Context(device_id={ self ._id } )"
0 commit comments