11import ctypes
2+ import glob
3+ import importlib .util
24import os
5+ import sys
36from typing import Iterable , List
47
58
@@ -63,12 +66,94 @@ def preload_hpcc() -> None:
6366 _try_load (prefixes , lib )
6467
6568
69+ def preload_torch_hip () -> None :
70+ """
71+ Best-effort preload of torch HIP runtime libs with RTLD_GLOBAL.
72+
73+ This helps external extensions resolve c10::hip symbols when they are
74+ not recorded as direct DT_NEEDED dependencies.
75+ """
76+ spec = importlib .util .find_spec ("torch" )
77+ if spec is None or not spec .origin :
78+ return
79+ torch_dir = os .path .dirname (spec .origin )
80+ torch_libdir = os .path .join (torch_dir , "lib" )
81+ if not os .path .isdir (torch_libdir ):
82+ return
83+
84+ libs = [
85+ "libtorch_global_deps.so" ,
86+ "libc10.so" ,
87+ "libc10_hip.so" ,
88+ "libtorch_cpu.so" ,
89+ "libtorch.so" ,
90+ "libtorch_hip.so" ,
91+ ]
92+ for lib in libs :
93+ full = os .path .join (torch_libdir , lib )
94+ if os .path .exists (full ):
95+ try :
96+ ctypes .CDLL (full , mode = ctypes .RTLD_GLOBAL )
97+ except OSError :
98+ # Best-effort preload, continue on errors.
99+ pass
100+
101+
102+ def preload_flash_attn () -> None :
103+ """
104+ Best-effort preload of flash_attn_2_cuda extension with RTLD_GLOBAL.
105+
106+ InfiniCore hygon wrapper resolves C symbols like `mha_varlen_fwd` from the
107+ flash-attn extension at runtime via dlsym(RTLD_DEFAULT, ...). The symbols
108+ only need to be available when the operator is actually called, not at
109+ library load time. So this preload is a convenience — if it fails, the
110+ symbols will be resolved later when torch + flash_attn are imported by
111+ the application (e.g. InfiniLM).
112+ """
113+ candidates : List [str ] = []
114+ from_env = os .getenv ("FLASH_ATTN_PREBUILT" )
115+ if from_env :
116+ if os .path .isfile (from_env ):
117+ candidates .append (from_env )
118+ elif os .path .isdir (from_env ):
119+ candidates .extend (glob .glob (os .path .join (from_env , "flash_attn_2_cuda*.so" )))
120+
121+ # Try resolving via Python import metadata.
122+ spec = importlib .util .find_spec ("flash_attn_2_cuda" )
123+ if spec and spec .origin and os .path .exists (spec .origin ):
124+ candidates .append (spec .origin )
125+
126+ # Fallback: scan python paths for extension module.
127+ for p in sys .path :
128+ if not p :
129+ continue
130+ candidates .extend (glob .glob (os .path .join (p , "flash_attn_2_cuda*.so" )))
131+
132+ # Common installation locations.
133+ candidates .extend (glob .glob ("/usr/local/lib/python*/dist-packages/flash_attn_2_cuda*.so" ))
134+ candidates .extend (glob .glob ("/root/.infini/lib/flash_attn_2_cuda*.so" ))
135+
136+ seen = set ()
137+ for so_path in candidates :
138+ if not so_path or so_path in seen :
139+ continue
140+ seen .add (so_path )
141+ if not os .path .exists (so_path ):
142+ continue
143+ try :
144+ ctypes .CDLL (so_path , mode = ctypes .RTLD_GLOBAL )
145+ return
146+ except OSError :
147+ continue
148+
149+
66150def _should_preload_device (device_type : str ) -> bool :
67151 """
68152 Check if preload is needed for a specific device type.
69153 """
70154 device_env_map = {
71155 "METAX" : ["HPCC_PATH" , "INFINICORE_PRELOAD_HPCC" ], # HPCC/METAX
156+ "HYGON" : ["DTK_ROOT" , "INFINICORE_PRELOAD_TORCH_HIP" ],
72157 # Add other device types here as needed:
73158 # "ASCEND": ["ASCEND_PATH"],
74159 # "CAMBRICON": ["NEUWARE_HOME"],
@@ -90,6 +175,8 @@ def preload_device(device_type: str) -> None:
90175 """
91176 if device_type == "METAX" :
92177 preload_hpcc ()
178+ elif device_type == "HYGON" :
179+ preload_torch_hip ()
93180 # Add other device preload functions here as needed:
94181 # elif device_type == "ASCEND":
95182 # preload_ascend()
@@ -103,9 +190,20 @@ def preload() -> None:
103190 This function detects available device types and preloads their runtime libraries
104191 if the environment indicates they are needed.
105192 """
193+ # Always try torch HIP preload first (best-effort, no-op if torch/HIP is absent).
194+ try :
195+ preload_torch_hip ()
196+ except Exception :
197+ pass
198+ try :
199+ preload_flash_attn ()
200+ except Exception :
201+ pass
202+
106203 # Device types that may require preload
107204 device_types = [
108205 "METAX" , # HPCC/METAX
206+ "HYGON" ,
109207 # Add other device types here as they are implemented:
110208 # "ASCEND",
111209 # "CAMBRICON",
0 commit comments