Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
226 lines (183 loc) · 7.64 KB
/
Copy path__init__.py
File metadata and controls
226 lines (183 loc) · 7.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the AFD plugin project
"""vLLM AFD plugin: Attention-FFN Disaggregation support."""
from __future__ import annotations
import importlib.util
import logging
import multiprocessing
import os
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
from types import MappingProxyType
from typing import Any, cast
from afd_plugin.config import AFDConfig, parse_afd_config, parse_optional_afd_config
def __getattr__(name: str):
if name in {
"AFDAttentionModelRunner",
"AFDAttentionWorker",
"AFDFFNWorker",
"AFDUBatchWrapper",
"GPUFFNModelRunner",
}:
from afd_plugin.v1 import worker
return getattr(worker, name)
if name == "assert_compatible_afd_stack":
from afd_plugin.validation import assert_compatible_afd_stack
return assert_compatible_afd_stack
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
try:
__version__ = version("vllm-afd-plugin")
except PackageNotFoundError:
try:
from setuptools_scm import get_version
__version__ = get_version(root=str(Path(__file__).resolve().parents[1]))
except (ImportError, LookupError):
__version__ = "0.0.0+unknown"
_logger = logging.getLogger(__name__)
_registered = False
def _force_spawn_multiprocessing_if_requested() -> None:
"""Pin Python's default context for the A3 Python 3.12 runtime.
``VLLM_WORKER_MULTIPROC_METHOD`` controls vLLM's explicit context only.
Some NPU runtime helpers use Python's default context and otherwise retain
the task's inherited ``forkserver`` setting, which cannot restore the
signal-handler state in this environment. Keep the override opt-in so it
remains isolated to the affected CAM async recipe.
"""
if os.environ.get("AFD_FORCE_SPAWN_MULTIPROCESSING") != "1":
return
multiprocessing.set_start_method("spawn", force=True)
# A few optional runtime helpers request ``forkserver`` explicitly instead
# of consulting the default start method. On the A3 Python 3.12 image the
# forkserver cannot restore its inherited signal-handler state, so every
# child it starts exits before running user code. Keep this narrowly
# opt-in with the recipe environment variable above: callers requesting a
# forkserver receive the equivalent spawn context instead.
contexts = cast(Any, multiprocessing.context)._concrete_contexts
contexts["forkserver"] = contexts["spawn"]
# TE Fusion keeps a module reference to ``multiprocessing`` and calls its
# public ``get_context("forkserver")`` API directly inside each model
# worker. Replacing the registry alone is not sufficient for all Python
# 3.12 context instances, so redirect that explicit request as well.
multiprocessing_module = cast(Any, multiprocessing)
if not getattr(multiprocessing_module, "_afd_spawn_context_redirect", False):
original_get_context = multiprocessing.get_context
def get_spawn_context(method: str | None = None):
if method == "forkserver":
method = "spawn"
return original_get_context(method)
multiprocessing.get_context = get_spawn_context
multiprocessing_module._afd_spawn_context_redirect = True
# vLLM model workers import the configured worker class directly in spawned
# child interpreters; they do not invoke the general-plugin entry point below.
# Apply the opt-in setting at package import time so it is also in effect before
# Ascend TE Fusion initializes its compilation workers.
_force_spawn_multiprocessing_if_requested()
_DEEPSEEK_MODEL_REGISTRATIONS = {
"DeepseekForCausalLM": (
"afd_plugin.model_executor.models.deepseek_v2:AFDDeepseekForCausalLM"
),
"DeepseekV2ForCausalLM": (
"afd_plugin.model_executor.models.deepseek_v2:AFDDeepseekV2ForCausalLM"
),
"DeepseekV3ForCausalLM": (
"afd_plugin.model_executor.models.deepseek_v2:AFDDeepseekV3ForCausalLM"
),
"DeepseekV32ForCausalLM": (
"afd_plugin.model_executor.models.deepseek_v2:AFDDeepseekV3ForCausalLM"
),
"DeepseekV4ForCausalLM": (
"afd_plugin.model_executor.models.npu.deepseek_v4:AFDDeepseekV4ForCausalLM"
if importlib.util.find_spec("torch_npu") is not None
else "afd_plugin.model_executor.models.deepseek_v4:AFDDeepseekV4ForCausalLM"
),
"GlmMoeDsaForCausalLM": (
"afd_plugin.model_executor.models.deepseek_v2:AFDGlmMoeDsaForCausalLM"
),
}
_QWEN_MODEL_REGISTRATIONS = {
"Qwen3MoeForCausalLM": (
"afd_plugin.model_executor.models.qwen3_moe:AFDQwen3MoeForCausalLM"
),
}
_QWEN3_5_MODEL_REGISTRATIONS = MappingProxyType(
{
"Qwen3_5MoeForConditionalGeneration": (
"afd_plugin.model_executor.models.qwen3_5:AFDQwen3_5MoeForConditionalGeneration"
),
}
)
_MODEL_REGISTRATIONS = MappingProxyType(
{
**_DEEPSEEK_MODEL_REGISTRATIONS,
**_QWEN_MODEL_REGISTRATIONS,
**_QWEN3_5_MODEL_REGISTRATIONS,
}
)
def register_afd() -> None:
"""Entry point for ``vllm.general_plugins``.
Perform plugin runtime registration when vLLM is available. Importing this
package or calling this function remains safe without vLLM installed, which
keeps local CPU smoke tests useful on non-CUDA machines.
"""
global _registered
if _registered:
_logger.debug("AFD plugin: register_afd() already completed")
return
_force_spawn_multiprocessing_if_requested()
_logger.debug("AFD plugin: register_afd() called")
if importlib.util.find_spec("vllm") is None:
_logger.debug("AFD plugin: vLLM not found, skipping runtime registration")
_registered = True
return
try:
from afd_plugin.compat.vllm import assert_vllm_version_supported
assert_vllm_version_supported(strict=False)
except Exception:
_logger.debug(
"AFD plugin: vLLM version check could not be completed",
exc_info=True,
)
try:
import afd_plugin.compat.patches.async_dp_engine # noqa: F401
import afd_plugin.compat.patches.async_dp_forward_context # noqa: F401
import afd_plugin.compat.patches.config_validation # noqa: F401
import afd_plugin.compat.patches.engine_core # noqa: F401
except Exception:
_logger.debug(
"AFD plugin: compatibility patches could not be applied",
exc_info=True,
)
from afd_plugin.model_executor.routing_simulator import (
register_afd_balanced_routing_strategy,
)
register_afd_balanced_routing_strategy()
try:
from afd_plugin.v1.worker.dbo import register_dbo_yield_custom_op
register_dbo_yield_custom_op()
except Exception:
_logger.debug(
"AFD plugin: DBO yield custom op could not be registered",
exc_info=True,
)
# NPU compatibility patches are applied during AFD config construction and
# worker startup, after vLLM-Ascend completes its platform initialization.
from vllm.model_executor.models import ModelRegistry
for model_arch, model_cls in _MODEL_REGISTRATIONS.items():
ModelRegistry.register_model(f"AFD{model_arch}", model_cls)
_registered = True
__all__ = [
"AFDConfig",
"AFDAttentionModelRunner",
"AFDAttentionWorker",
"AFDFFNWorker",
"GPUFFNModelRunner",
"assert_compatible_afd_stack",
"parse_afd_config",
"parse_optional_afd_config",
"__version__",
"_DEEPSEEK_MODEL_REGISTRATIONS",
"_MODEL_REGISTRATIONS",
"_QWEN_MODEL_REGISTRATIONS",
"_QWEN3_5_MODEL_REGISTRATIONS",
"register_afd",
]