1010 PROFILE_PREFILL_STOP_STEP / PROFILE_DECODE_STOP_STEP - stop step
1111 SGLANG_TORCH_PROFILER_DIR - output dir for traces
1212
13- Applied automatically via sitecustomize .py when PROFILING_MODE is set .
14- Uses a post-import hook so the patch applies after dynamo.trtllm loads .
13+ Applied by appending import+call to handler_base .py via setup script .
14+ Falls back to a post-import hook if used standalone .
1515"""
1616
1717import importlib
@@ -77,20 +77,30 @@ async def _patched_generate(self, request, *args, **kwargs):
7777
7878
7979def patch ():
80- """Install a post-import hook that patches HandlerBase after dynamo.trtllm loads."""
80+ """Patch HandlerBase.generate with profiler wrapping.
81+
82+ When this file is appended to handler_base.py, HandlerBase is already
83+ defined in the current module scope — so we apply the patch directly.
84+ If called standalone before the module is imported, we install a
85+ post-import hook as a fallback.
86+ """
8187 mode = os .environ .get ("PROFILING_MODE" , "" )
8288 if not mode :
8389 return
8490
85- # If the module is already imported, patch immediately
86- if "dynamo.trtllm.request_handlers.handler_base" in sys .modules :
87- try :
88- _apply_patch ()
89- except Exception as e :
90- print (f"[trtllm-patch] Failed: { e } " , file = sys .stderr , flush = True )
91+ # If HandlerBase is already importable (e.g. this code was appended to
92+ # handler_base.py, or the module was already imported), patch immediately.
93+ try :
94+ from dynamo .trtllm .request_handlers .handler_base import HandlerBase # noqa: F401
95+ _apply_patch ()
96+ return
97+ except ImportError :
98+ pass
99+ except Exception as e :
100+ print (f"[trtllm-patch] Direct patch failed: { e } " , file = sys .stderr , flush = True )
91101 return
92102
93- # Otherwise, install a meta path finder that triggers after the module loads
103+ # Fallback: install a meta path finder for deferred patching
94104 class _PatchFinder :
95105 _patched = False
96106
@@ -100,13 +110,10 @@ def find_module(self, fullname, path=None):
100110 return None
101111
102112 def load_module (self , fullname ):
103- # Remove ourselves to avoid recursion
104113 self ._patched = True
105- # Let the real import happen
106114 if self in sys .meta_path :
107115 sys .meta_path .remove (self )
108116 mod = importlib .import_module (fullname )
109- # Now apply the patch
110117 try :
111118 _apply_patch ()
112119 except Exception as e :
0 commit comments