patch_vllm_b12x_c128a_topk_alignment.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. #!/usr/bin/env python3
  2. """Import the C128A top-k alignment used by the B12X DeepSeek V4 path.
  3. The local-inference-lab B12X branch added a dynamic C128A top-k width that
  4. references ``_C128A_TOPK_ALIGNMENT`` without importing it from
  5. ``compressor_utils``. Keep this workaround opt-in, idempotent, and strict
  6. about the vulnerable source shape so regular vLLM builds remain untouched.
  7. """
  8. from __future__ import annotations
  9. import ast
  10. import os
  11. import sys
  12. from pathlib import Path
  13. FLAG_NAME = "VLLM_PATCH_B12X_C128A_ALIGNMENT"
  14. ALIGNMENT_NAME = "_C128A_TOPK_ALIGNMENT"
  15. TARGET_REL = Path("vllm/models/deepseek_v4/sparse_mla.py")
  16. HELPER_REL = Path("vllm/v1/attention/backends/mla/compressor_utils.py")
  17. IMPORT_BLOCK = (
  18. "from vllm.v1.attention.backends.mla.compressor_utils import (\n"
  19. " get_c128a_topk_width,\n"
  20. " get_compressed_slot_mapping,\n"
  21. ")"
  22. )
  23. PATCHED_IMPORT_BLOCK = (
  24. "from vllm.v1.attention.backends.mla.compressor_utils import (\n"
  25. f" {ALIGNMENT_NAME},\n"
  26. " get_c128a_topk_width,\n"
  27. " get_compressed_slot_mapping,\n"
  28. ")"
  29. )
  30. TRUE_VALUES = {"1", "true", "TRUE", "yes", "YES"}
  31. FALSE_VALUES = {"", "0", "false", "FALSE", "no", "NO"}
  32. def module_binds_name(tree: ast.Module, name: str) -> bool:
  33. """Return whether the module establishes ``name`` before runtime use."""
  34. for node in tree.body:
  35. if isinstance(node, ast.ImportFrom):
  36. if any((alias.asname or alias.name) == name for alias in node.names):
  37. return True
  38. elif isinstance(node, ast.Assign):
  39. if any(
  40. isinstance(target, ast.Name) and target.id == name
  41. for target in node.targets
  42. ):
  43. return True
  44. elif isinstance(node, ast.AnnAssign):
  45. if isinstance(node.target, ast.Name) and node.target.id == name:
  46. return True
  47. return False
  48. def module_constant_is_128(tree: ast.Module, name: str) -> bool:
  49. """Return whether ``name`` is assigned the expected value at module scope."""
  50. for node in tree.body:
  51. value: ast.expr | None = None
  52. if isinstance(node, ast.Assign) and any(
  53. isinstance(target, ast.Name) and target.id == name
  54. for target in node.targets
  55. ):
  56. value = node.value
  57. elif (
  58. isinstance(node, ast.AnnAssign)
  59. and isinstance(node.target, ast.Name)
  60. and node.target.id == name
  61. ):
  62. value = node.value
  63. if isinstance(value, ast.Constant) and value.value == 128:
  64. return True
  65. return False
  66. raw_flag = os.environ.get(FLAG_NAME, "0")
  67. if raw_flag not in TRUE_VALUES | FALSE_VALUES:
  68. raise SystemExit(f"Invalid {FLAG_NAME} value: {raw_flag!r}")
  69. if raw_flag not in TRUE_VALUES:
  70. print("B12X C128A alignment workaround not requested; skipping")
  71. raise SystemExit(0)
  72. source_root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path.cwd()
  73. target = source_root / TARGET_REL
  74. helper = source_root / HELPER_REL
  75. if not target.exists():
  76. print(f"{TARGET_REL} is absent; B12X C128A workaround is not applicable")
  77. raise SystemExit(0)
  78. text = target.read_text()
  79. try:
  80. tree = ast.parse(text, filename=str(target))
  81. except SyntaxError as exc:
  82. raise SystemExit(f"Cannot inspect invalid Python source {target}: {exc}") from exc
  83. uses_alignment = any(
  84. isinstance(node, ast.Name)
  85. and node.id == ALIGNMENT_NAME
  86. and isinstance(node.ctx, ast.Load)
  87. for node in ast.walk(tree)
  88. )
  89. if not uses_alignment:
  90. print("DeepSeek V4 source does not use the missing C128A alignment; skipping")
  91. raise SystemExit(0)
  92. if module_binds_name(tree, ALIGNMENT_NAME):
  93. print("DeepSeek V4 C128A alignment is already defined or imported; skipping")
  94. raise SystemExit(0)
  95. if not helper.exists():
  96. raise SystemExit(
  97. f"{target} uses {ALIGNMENT_NAME}, but {helper} is missing; refusing to guess"
  98. )
  99. helper_text = helper.read_text()
  100. try:
  101. helper_tree = ast.parse(helper_text, filename=str(helper))
  102. except SyntaxError as exc:
  103. raise SystemExit(f"Cannot inspect invalid Python source {helper}: {exc}") from exc
  104. if not module_constant_is_128(helper_tree, ALIGNMENT_NAME):
  105. raise SystemExit(
  106. f"{target} uses {ALIGNMENT_NAME}, but {helper} does not define it as 128; "
  107. "refusing to patch an unknown source shape"
  108. )
  109. anchor_count = text.count(IMPORT_BLOCK)
  110. if anchor_count != 1:
  111. raise SystemExit(
  112. f"Expected one DeepSeek V4 compressor_utils import block, found "
  113. f"{anchor_count}; refusing to patch an unknown source shape"
  114. )
  115. updated = text.replace(IMPORT_BLOCK, PATCHED_IMPORT_BLOCK, 1)
  116. compile(updated, str(target), "exec")
  117. updated_tree = ast.parse(updated, filename=str(target))
  118. if not module_binds_name(updated_tree, ALIGNMENT_NAME):
  119. raise SystemExit("B12X C128A alignment import was not established after patching")
  120. target.write_text(updated)
  121. print("Applied B12X DeepSeek V4 C128A top-k alignment import workaround")