sitecustomize.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. """Install storage adapter in every serving worker, only when explicitly enabled."""
  2. import importlib.abc
  3. import importlib.machinery
  4. import os
  5. import sys
  6. def _tp4_launcher():
  7. """True only inside containers started by start-tp4.sh (DSV41_LAUNCHER=tp4)."""
  8. return os.environ.get('DSV41_LAUNCHER', '') == 'tp4'
  9. class EngramLoader(importlib.abc.Loader):
  10. def __init__(self, original):
  11. self.original = original
  12. def create_module(self, spec):
  13. return self.original.create_module(spec)
  14. def exec_module(self, module):
  15. self.original.exec_module(module)
  16. if module.__name__ == 'sglang.srt.layers.engram':
  17. from engram_backend import install
  18. install(module)
  19. # After engram_backend: Engram rows fetched on a side stream right after the
  20. # hasher. Gated on DSV41_ENGRAM_PREFETCH, inactive by default.
  21. from engram_prefetch import install as install_engram_prefetch
  22. install_engram_prefetch(module)
  23. elif module.__name__ == 'sglang.srt.model_loader.utils':
  24. if os.environ.get('DSV41_SERIAL_WEIGHT_LOAD', '0') == '1':
  25. # On GB10 the CPU shard pages and CUDA allocations share RAM.
  26. # Do not retain a queue of pending H2D copies while advancing
  27. # through the checkpoint; consume each tensor before the next.
  28. if not callable(getattr(module, 'should_async_load', None)):
  29. raise RuntimeError(
  30. 'DSV41_SERIAL_WEIGHT_LOAD requires model_loader.utils.'
  31. 'should_async_load; rebuild against a compatible SGLang image'
  32. )
  33. module.should_async_load = lambda *args, **kwargs: False
  34. print('DSV41: synchronous weight copies enabled (UMA safeguard)', flush=True)
  35. elif module.__name__ == 'sglang.srt.layers.quantization.fp8_utils':
  36. from mxfp8_b12x import install
  37. install(module)
  38. # TP4 only, and AFTER b12x, so shared_pad wraps its wrapper rather than the original.
  39. # Gated on DSV41_SHARED_PAD_K inside the module. L2 prefetch records which MXFP8
  40. # weights follow each RoCE collective; outermost wrapper, weight pointer only.
  41. if _tp4_launcher():
  42. from shared_pad_k import install as install_shared_pad
  43. install_shared_pad(module)
  44. if os.environ.get('DSV41_L2_PREFETCH', '0').strip() not in ('0', 'off', 'false', ''):
  45. from l2_prefetch import install_fp8_utils as install_l2_prefetch_fp8
  46. install_l2_prefetch_fp8(module)
  47. elif module.__name__ == 'sglang.srt.layers.quantization.fp8':
  48. from mxfp8_b12x import install_fp8
  49. install_fp8(module)
  50. if _tp4_launcher():
  51. from shared_pad_k import install_fp8 as install_shared_pad_fp8
  52. install_shared_pad_fp8(module)
  53. elif module.__name__ == 'sglang.srt.model_executor.model_runner':
  54. from prefill_empty_cache import install
  55. install(module)
  56. elif module.__name__ == 'sglang.srt.layers.attention.deepseek_v4_backend' and _tp4_launcher():
  57. # sglang#39187 backport: dense prefill indexer scored in bounded row chunks.
  58. # Gate checked BEFORE the import so a disabled flag imports nothing. v1 targets
  59. # the dev-dsv41 image backend (self.candidate_masks); v3 is the PR for
  60. # candidate_metadata backends (dsv4.1 branch >= f80c91a4b) plus the SG18 prefill
  61. # TP split. Each refuses the other.
  62. if os.environ.get('DSV41_INDEXER_CHUNKED', '0').strip() not in ('0', 'off', 'false', ''):
  63. import inspect as _inspect
  64. _src = _inspect.getsource(module.DeepseekV4AttnBackend._low_ratio_index_topk_dense)
  65. if 'self.candidate_masks' in _src:
  66. from indexer_chunked import install as install_indexer_chunked
  67. else:
  68. from indexer_chunked_v3 import install as install_indexer_chunked
  69. install_indexer_chunked(module)
  70. elif module.__name__ == 'sglang.srt.entrypoints.openai.encoding_dsv41':
  71. from encoding_compat import install_encoder
  72. install_encoder(module)
  73. elif module.__name__ == 'sglang.srt.entrypoints.openai.serving_chat':
  74. from encoding_compat import install_serving_chat
  75. install_serving_chat(module)
  76. elif module.__name__ == 'sglang.srt.model_loader.weight_utils' and _tp4_launcher():
  77. # Gated on DSV41_FAST_LOAD: this rank's tensors are read eagerly by a thread
  78. # pool instead of page-faulted through the loader's mmap (adapter/fast_load.py).
  79. from fast_load import install_weight_utils
  80. install_weight_utils(module)
  81. elif module.__name__ == 'sglang.srt.models.deepseek_v4':
  82. if _tp4_launcher():
  83. from fast_load import install_deepseek_v4
  84. install_deepseek_v4(module)
  85. # Gated on DSV41_WO_A_W8: verify/draft wo_a reads its fp8 checkpoint bytes.
  86. if os.environ.get('DSV41_WO_A_W8', '0').strip() not in ('0', 'off', 'false', ''):
  87. from wo_a_w8 import install_model as install_wo_a_w8
  88. install_wo_a_w8(module)
  89. # Gated on DSV41_VERIFY_CAP: marks target-verify forwards for the dead-row expert remap.
  90. if os.environ.get('DSV41_VERIFY_CAP', '').strip() not in ('', '0', 'off'):
  91. from verify_cap import install_model as install_verify_cap_model
  92. install_verify_cap_model(module)
  93. # TP4 only. DSV41_PREFILL_SP=comm|1: prefill sequence parallel (adapter/prefill_sp.py).
  94. # DSV41_PREFILL_SP_DEBUG alone (fingerprints on an otherwise stock boot) also installs it.
  95. if _tp4_launcher() and (
  96. os.environ.get('DSV41_PREFILL_SP', '0').strip() not in ('0', 'off', 'false', '')
  97. or os.environ.get('DSV41_PREFILL_SP_DEBUG', '').strip()):
  98. from prefill_sp import install as install_prefill_sp
  99. install_prefill_sp(module)
  100. # TP4 only. DSV41_L2_PREFETCH: brackets decode/verify forwards so each RoCE collective
  101. # forks an L2 prefetch of the weights that follow it (adapter/l2_prefetch.py).
  102. if _tp4_launcher() and os.environ.get('DSV41_L2_PREFETCH', '0').strip() not in ('0', 'off', 'false', ''):
  103. from l2_prefetch import install_model as install_l2_prefetch_model
  104. install_l2_prefetch_model(module)
  105. elif module.__name__ == 'sglang.srt.models.deepseek_v4_dspark':
  106. # DSV41_VERIFY_CAP=conf:T needs the draft confidence head, which the engine only builds
  107. # in the ragged-verify modes.
  108. if os.environ.get('DSV41_VERIFY_CAP', '').strip().startswith('conf:'):
  109. from verify_cap import install_dspark as install_verify_cap_dspark
  110. install_verify_cap_dspark(module)
  111. if _tp4_launcher():
  112. from fast_load import install_dspark
  113. install_dspark(module)
  114. if os.environ.get('DSV41_WO_A_W8', '0').strip() not in ('0', 'off', 'false', ''):
  115. from wo_a_w8 import install_dspark as install_wo_a_w8_dspark
  116. install_wo_a_w8_dspark(module)
  117. # TP4 only. DSV41_DRAFT_MAIN_PROJ_SPLIT: the draft's replicated main_proj column-split
  118. # over TP (fp8 shard + all-gather; target untouched).
  119. if _tp4_launcher() and os.environ.get('DSV41_DRAFT_MAIN_PROJ_SPLIT', '0').strip() not in ('0', 'off', 'false', ''):
  120. from draft_main_proj import install as install_draft_main_proj
  121. install_draft_main_proj(module)
  122. # Gated on DSV41_DRAFT_HEAD_FP8: the draft's LM head from an fp8 copy (target untouched).
  123. # On the TP4 launcher, DSV41_DRAFT_HEAD_FP8_IMPL=tp4 selects the batch-sized row tiles of
  124. # draft_head_fp8_tp4.py. ./start.sh always installs draft_head_fp8.py.
  125. if os.environ.get('DSV41_DRAFT_HEAD_FP8', '0').strip() not in ('0', 'off', 'false', ''):
  126. if _tp4_launcher() and os.environ.get('DSV41_DRAFT_HEAD_FP8_IMPL', '').strip() == 'tp4':
  127. from draft_head_fp8_tp4 import install as install_draft_head_fp8
  128. else:
  129. from draft_head_fp8 import install as install_draft_head_fp8
  130. install_draft_head_fp8(module)
  131. elif module.__name__ == 'sglang.srt.speculative.dspark_components.dspark_draft_sampler':
  132. # Gated on DSV41_DRAFT_TAU (unset or 1 = off): draft proposal temperature.
  133. if os.environ.get('DSV41_DRAFT_TAU', '1').strip() not in ('', '1', '1.0'):
  134. from draft_tau import install as install_draft_tau
  135. install_draft_tau(module)
  136. elif module.__name__ == 'sglang.kernels.ops.speculative.dspark.dspark_accept':
  137. # Gated on DSV41_BLOCK_VERIFY: block verification for sampled rows (lossless).
  138. if os.environ.get('DSV41_BLOCK_VERIFY', '0').strip() not in ('0', 'off', 'false', ''):
  139. from block_verify import install as install_block_verify
  140. install_block_verify(module)
  141. elif module.__name__ == 'sglang.srt.speculative.dspark_components.dspark_verify':
  142. # Gated on DSV41_FOLDED_FENCE: folded results cloned off the persistent verify buffers
  143. # (sglang#40919 race under overlap scheduling).
  144. if os.environ.get('DSV41_FOLDED_FENCE', '0').strip() not in ('0', 'off', 'false', ''):
  145. from folded_result_fence import install as install_folded_fence
  146. install_folded_fence(module)
  147. # Gated on DSV41_VERIFY_CAP: per-request verify length through the acceptance cutoff.
  148. if os.environ.get('DSV41_VERIFY_CAP', '').strip() not in ('', '0', 'off'):
  149. from verify_cap import install_verify as install_verify_cap_verify
  150. install_verify_cap_verify(module)
  151. elif module.__name__ == 'sglang.kernels.ops.moe.moe_fused_gate':
  152. if os.environ.get('DSV41_VERIFY_CAP', '').strip() not in ('', '0', 'off'):
  153. from verify_cap import install_gate as install_verify_cap_gate
  154. install_verify_cap_gate(module)
  155. elif module.__name__ == 'sglang.srt.speculative.dspark_components.dspark_draft':
  156. if os.environ.get('DSV41_VERIFY_CAP', '').strip() not in ('', '0', 'off'):
  157. from verify_cap import install_draft as install_verify_cap_draft
  158. install_verify_cap_draft(module)
  159. elif module.__name__ == 'sglang.srt.speculative.dspark_components.dspark_planner':
  160. if os.environ.get('DSV41_VERIFY_CAP', '').strip() not in ('', '0', 'off'):
  161. from verify_cap import install_planner as install_verify_cap_planner
  162. install_verify_cap_planner(module)
  163. elif module.__name__ == 'sglang.srt.model_executor.runner.flashinfer_autotune':
  164. # Gated on DSV41_AUTOTUNE_KEEP: keep the FlashInfer autotune cache across boots under EP
  165. # (sglang#40320: the stock gate deletes it on every boot).
  166. if os.environ.get('DSV41_AUTOTUNE_KEEP', '0').strip() not in ('0', 'off', 'false', ''):
  167. from autotune_keep import install as install_autotune_keep
  168. install_autotune_keep(module)
  169. elif _tp4_launcher() and module.__name__ == 'sglang.srt.layers.linear':
  170. # Gated on DSV41_REPLICATED_SPLIT=<prefix suffixes>: chosen ReplicatedLinear layers
  171. # column-split over TP, enabled per layer only when bit-identical on every rank.
  172. if os.environ.get('DSV41_REPLICATED_SPLIT', '').strip():
  173. from replicated_split import install as install_replicated_split
  174. install_replicated_split(module)
  175. elif _tp4_launcher() and module.__name__ == 'sglang.srt.distributed.device_communicators.pynccl':
  176. # Gated on DSV41_ROCE_GATHER=<max bytes per rank>: small TP all-gathers (the draft's
  177. # vocab-parallel logits) take the RoCEnante one-shot kernel instead of NCCL.
  178. if os.environ.get('DSV41_ROCE_GATHER', '0').strip() not in ('', '0'):
  179. from roce_gather import install as install_roce_gather
  180. install_roce_gather(module)
  181. elif _tp4_launcher() and module.__name__ == 'sglang.srt.layers.quantization.mxfp4_flashinfer_cutlass_moe':
  182. # Gated on DSV41_MOE_B12X_NEXT: routed experts on b12x main (package b12x_next), which
  183. # also runs EP_SIZE=1 at TP4 (N=576 per rank). Gate checked BEFORE the import.
  184. if os.environ.get('DSV41_MOE_B12X_NEXT', '0').strip() not in ('0', 'off', 'false', ''):
  185. from moe_b12x_next import install_method as install_moe_b12x_next
  186. install_moe_b12x_next(module)
  187. elif _tp4_launcher() and module.__name__ == 'sglang.srt.layers.moe.moe_runner.flashinfer_cutlass':
  188. if os.environ.get('DSV41_MOE_B12X_NEXT', '0').strip() not in ('0', 'off', 'false', ''):
  189. from moe_b12x_next import install_runner as install_moe_b12x_next_runner
  190. install_moe_b12x_next_runner(module)
  191. elif _tp4_launcher() and module.__name__ == 'sglang.kernels.ops.layernorm.mhc':
  192. # Gated on DSV41_HC_FUSED: prefill-size hc mix stats in one K walk, bit-identical to
  193. # the stock split-K + reduce (adapter/hc_fused.py). Gate checked BEFORE the import.
  194. if os.environ.get('DSV41_HC_FUSED', '0').strip() not in ('0', 'off', 'false', ''):
  195. from hc_fused import install as install_hc_fused
  196. install_hc_fused(module)
  197. elif _tp4_launcher() and module.__name__ == 'sglang.srt.models.deepseek_v2':
  198. # Gated on DSV41_L2_PREFETCH: the bf16 router (tiny_gemm_bf16) is recorded too.
  199. if os.environ.get('DSV41_L2_PREFETCH', '0').strip() not in ('0', 'off', 'false', ''):
  200. from l2_prefetch import install_router as install_l2_prefetch_router
  201. install_l2_prefetch_router(module)
  202. elif _tp4_launcher() and module.__name__ in ('b12x.comm.roce.roce_oneshot', 'b12x.comm.roce_ring.roce_oneshot'):
  203. # Gated on DSV41_L2_PREFETCH: RoCEnante all-reduce/all-gather fork the prefetch branch.
  204. # Outside sglang; the finder sees its first import whichever package imports it first,
  205. # and install_model re-checks sys.modules in case it was imported before the finder.
  206. if os.environ.get('DSV41_L2_PREFETCH', '0').strip() not in ('0', 'off', 'false', ''):
  207. from l2_prefetch import install_roce as install_l2_prefetch_roce
  208. install_l2_prefetch_roce(module)
  209. elif module.__name__ == 'sglang.srt.managers.schedule_batch':
  210. from loop_abort import install as install_loop_abort
  211. install_loop_abort(module)
  212. else:
  213. # V4.1 ratio-1/2 indexers always call the FP4 DeepGEMM kernel.
  214. # SM120 needs its split-128 planner even when the legacy FP8
  215. # indexer uses the torch path. The upstream guard misses this case.
  216. cls = module.PagedIndexerMetadata
  217. original = cls.__post_init__
  218. def post_init(self):
  219. sm12 = bool(getattr(module, '_IS_SM120', False) or
  220. getattr(module, '_IS_SM121', False))
  221. if sm12 and self.compress_ratio in (1, 2):
  222. self.force_deep_gemm_metadata = True
  223. original(self)
  224. cls.__post_init__ = post_init
  225. class EngramFinder(importlib.abc.MetaPathFinder):
  226. def find_spec(self, fullname, path=None, target=None):
  227. if (fullname == 'sglang.srt.model_loader.utils' and
  228. os.environ.get('DSV41_SERIAL_WEIGHT_LOAD', '0') != '1'):
  229. return None
  230. # The second tuple is the TP4 production line. start-tp4.sh is what puts
  231. # DSV41_LAUNCHER=tp4 in the container; ./start.sh never intercepts these.
  232. if fullname not in ('sglang.srt.layers.engram',
  233. 'sglang.srt.model_loader.utils',
  234. 'sglang.srt.layers.quantization.fp8_utils',
  235. 'sglang.srt.layers.quantization.fp8',
  236. 'sglang.srt.model_executor.model_runner',
  237. 'sglang.srt.entrypoints.openai.encoding_dsv41',
  238. 'sglang.srt.entrypoints.openai.serving_chat',
  239. 'sglang.srt.models.deepseek_v4',
  240. 'sglang.srt.models.deepseek_v4_dspark',
  241. 'sglang.srt.speculative.dspark_components.dspark_verify',
  242. 'sglang.srt.speculative.dspark_components.dspark_draft_sampler',
  243. 'sglang.kernels.ops.speculative.dspark.dspark_accept',
  244. 'sglang.srt.managers.schedule_batch',
  245. 'sglang.kernels.ops.moe.moe_fused_gate',
  246. 'sglang.srt.speculative.dspark_components.dspark_draft',
  247. 'sglang.srt.speculative.dspark_components.dspark_planner',
  248. 'sglang.srt.model_executor.runner.flashinfer_autotune',
  249. 'sglang.srt.layers.attention.dsv4.metadata'):
  250. if not _tp4_launcher() or fullname not in (
  251. 'sglang.srt.layers.attention.deepseek_v4_backend',
  252. 'sglang.srt.model_loader.weight_utils',
  253. 'sglang.srt.distributed.device_communicators.pynccl',
  254. 'sglang.srt.layers.linear',
  255. 'sglang.srt.layers.quantization.mxfp4_flashinfer_cutlass_moe',
  256. 'sglang.srt.layers.moe.moe_runner.flashinfer_cutlass',
  257. 'sglang.kernels.ops.layernorm.mhc',
  258. 'sglang.srt.models.deepseek_v2',
  259. 'b12x.comm.roce.roce_oneshot',
  260. 'b12x.comm.roce_ring.roce_oneshot'):
  261. return None
  262. spec = importlib.machinery.PathFinder.find_spec(fullname, path)
  263. if spec is not None:
  264. spec.loader = EngramLoader(spec.loader)
  265. return spec
  266. if os.environ.get('DSV41_SOURCE'):
  267. sys.meta_path.insert(0, EngramFinder())
  268. try:
  269. import tp3_pad
  270. tp3_pad.install()
  271. except Exception as exc:
  272. print(f'DSV41 TP pad not installed: {exc}', flush=True)