@@ -264,12 +264,22 @@ def _insertion_index(parameters: list[inspect.Parameter]) -> int:
264264 return len (parameters )
265265
266266
267- # Thread-local storage for GPU streams and contexts
268- _thread_gpu_contexts = threading . local ()
267+ class ThreadGPUContext :
268+ """Runtime-owned thread- local streams keyed by framework/device identity.
269269
270+ Keep the runtime handle on its importable owner, not in decorator function
271+ globals. A retained, unpublished decorated callable is serialized by value;
272+ its durable closure must not pull a ``threading.local`` into history.
273+ """
270274
271- class ThreadGPUContext :
272- """Thread-local streams keyed by framework-local device identity."""
275+ _contexts : ClassVar [threading .local ] = threading .local ()
276+
277+ @classmethod
278+ def current (cls ) -> "ThreadGPUContext" :
279+ """Return this thread's runtime context without serializing its handle."""
280+ if not hasattr (cls ._contexts , "context" ):
281+ cls ._contexts .context = cls ()
282+ return cls ._contexts .context
273283
274284 def __init__ (self ):
275285 self ._streams : dict [tuple [MemoryType , int ], Any ] = {}
@@ -301,13 +311,6 @@ def stream_for(
301311 return device_id , self ._streams [key ]
302312
303313
304- def _get_thread_gpu_context ():
305- """Get or create thread-local GPU context."""
306- if not hasattr (_thread_gpu_contexts , "context" ):
307- _thread_gpu_contexts .context = ThreadGPUContext ()
308- return _thread_gpu_contexts .context
309-
310-
311314def memory_types (
312315 input_type : str | MemoryType ,
313316 output_type : str | MemoryType ,
@@ -461,7 +464,7 @@ def gpu_wrapper(*args, **kwargs):
461464 # Check if GPU is available for this framework
462465 if framework is not None and mem_type .available_device_ids (framework ):
463466 # Get thread-local context
464- ctx = _get_thread_gpu_context ()
467+ ctx = ThreadGPUContext . current ()
465468
466469 device_id , stream = ctx .stream_for (mem_type , framework )
467470
0 commit comments