Merge commit '6fe1ff7709c72c08bbfc33a7e14b73ec94135549' into codex-issue-7035-h100-determinism
Signed-off-by: david6666666 <530634352@qq.com>
This commit is contained in:
commit
f9253ae1ad
96 files changed
+8480
-822
No files matched your search
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Apply declarative parallel strategies onto merged stage configs.
|
||||
|
||||
This is the *override-after-merge* seam. ``merge_pipeline_deploy`` first fuses
|
||||
@@ -198,10 +198,41 @@ def _check_devices(runtime: dict[str, Any], cfg: OmniParallelConfig, *, role: Ro
|
||||
|
||||
|
||||
def _apply_to_stage(stage: Any, cfg: OmniParallelConfig, *, role: RoleKey) -> None:
|
||||
declared = set(cfg.l1_owners.keys())
|
||||
if hasattr(stage, "parallel_config") and hasattr(stage, "runtime_config"):
|
||||
parallel = stage.parallel_config
|
||||
for kind, field_name in _ENGINE_FIELD_BY_KIND.items():
|
||||
if kind in declared:
|
||||
existing = getattr(parallel, field_name, None)
|
||||
value = getattr(cfg, field_name)
|
||||
if existing not in (None, 1, value):
|
||||
_fail(
|
||||
f"role {role!r}: strategy derives {field_name}={value} "
|
||||
f"but structured config already set {existing}"
|
||||
)
|
||||
setattr(parallel, field_name, value)
|
||||
if "ep" in declared and cfg.enable_expert_parallel:
|
||||
setattr(parallel, "enable_expert_parallel", True)
|
||||
if "stage_replica" in declared:
|
||||
existing = stage.runtime_config.num_replicas
|
||||
if existing not in (None, 1, cfg.stage_replica_size):
|
||||
_fail(
|
||||
f"role {role!r}: strategy derives "
|
||||
f"num_replicas={cfg.stage_replica_size} but structured config already set {existing}"
|
||||
)
|
||||
stage.runtime_config.num_replicas = cfg.stage_replica_size
|
||||
check_device_layout(
|
||||
stage.runtime_config.devices,
|
||||
tensor_parallel_size=cfg.tensor_parallel_size,
|
||||
data_parallel_size=cfg.data_parallel_size,
|
||||
pipeline_parallel_size=cfg.pipeline_parallel_size,
|
||||
num_replicas=int(stage.runtime_config.num_replicas or 1),
|
||||
role=role,
|
||||
)
|
||||
return
|
||||
|
||||
engine_args = stage.yaml_engine_args
|
||||
runtime = stage.yaml_runtime
|
||||
|
||||
declared = set(cfg.l1_owners.keys())
|
||||
for kind, field_name in _ENGINE_FIELD_BY_KIND.items():
|
||||
if kind in declared:
|
||||
_set_explicit(engine_args, field_name, getattr(cfg, field_name), role=role)
|
||||
@@ -209,7 +240,6 @@ def _apply_to_stage(stage: Any, cfg: OmniParallelConfig, *, role: RoleKey) -> No
|
||||
_set_explicit(engine_args, "enable_expert_parallel", True, role=role)
|
||||
if "stage_replica" in declared:
|
||||
_set_num_replicas(runtime, cfg.stage_replica_size, role=role)
|
||||
|
||||
_check_devices(runtime, cfg, role=role)
|
||||
|
||||
|
||||
|
||||
@@ -25,6 +25,9 @@ from vllm_omni.config.stage_config import (
|
||||
DeployConfig,
|
||||
PipelineConfig,
|
||||
StageConfig,
|
||||
StageDeployConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
StageType,
|
||||
build_stage_runtime_overrides,
|
||||
load_deploy_config,
|
||||
@@ -373,6 +376,7 @@ class StageConfigFactory:
|
||||
trust_remote_code: bool | None,
|
||||
cli_overrides: dict[str, Any],
|
||||
deploy_config_path: str | None,
|
||||
strategy_specs: Mapping[Any, Any] | None = None,
|
||||
) -> VllmOmniConfig | None:
|
||||
"""Build the structured Omni config for a model/deploy pair."""
|
||||
user_deploy_config = cls._load_user_deploy_config(deploy_config_path)
|
||||
@@ -387,6 +391,20 @@ class StageConfigFactory:
|
||||
if pipeline_cfg is None:
|
||||
return None
|
||||
|
||||
# Keep the typed representation's topology in lockstep with the
|
||||
# compatibility launch representation. The aligner is a real extra
|
||||
# stage, not an engine-only setting, so it must be injected before
|
||||
# either representation is built.
|
||||
if user_deploy_config is None:
|
||||
if pipeline_cfg.default_deploy_config_name is not None:
|
||||
default_deploy_path = _DEPLOY_DIR / pipeline_cfg.default_deploy_config_name
|
||||
user_deploy_config = load_deploy_config(default_deploy_path)
|
||||
deploy_config_path = str(default_deploy_path)
|
||||
else:
|
||||
user_deploy_config = DeployConfig()
|
||||
from vllm_omni.utils.forced_aligner import inject_forced_aligner_stage
|
||||
|
||||
pipeline_cfg, user_deploy_config = inject_forced_aligner_stage(pipeline_cfg, user_deploy_config, cli_overrides)
|
||||
registry_cli_overrides = with_trust_remote_code_override(
|
||||
{**cli_overrides, "model": model},
|
||||
trust_remote_code,
|
||||
@@ -396,6 +414,7 @@ class StageConfigFactory:
|
||||
user_deploy_config=user_deploy_config,
|
||||
deploy_config_path=deploy_config_path,
|
||||
cli_overrides=registry_cli_overrides,
|
||||
strategy_specs=strategy_specs,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -621,13 +640,11 @@ class StageConfigFactory:
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def create_default_diffusion(cls, kwargs: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Build the temporary runtime ABI for a generic diffusion stage.
|
||||
|
||||
The terminal diffusion config owns engine defaults and normalization;
|
||||
this compatibility builder only adds Omni stage topology, request
|
||||
defaults, and device placement.
|
||||
"""
|
||||
def _normalize_default_diffusion(
|
||||
cls,
|
||||
kwargs: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], DiffusionParallelConfig, dict[str, Any], str]:
|
||||
"""Normalize inputs shared by typed and compatibility diffusion builders."""
|
||||
raw_sampling_params = kwargs.get("default_sampling_params")
|
||||
if isinstance(raw_sampling_params, str):
|
||||
try:
|
||||
@@ -643,8 +660,6 @@ class StageConfigFactory:
|
||||
if kwargs.get("num_gpus") is not None:
|
||||
parallel_config.resolve_data_parallel_size(int(kwargs["num_gpus"]))
|
||||
engine_args = OmniDiffusionConfig.normalize_init_kwargs(kwargs)
|
||||
engine_args["parallel_config"] = asdict(parallel_config)
|
||||
engine_args["model_stage"] = "diffusion"
|
||||
|
||||
extras = dict(engine_args.get("extras") or {})
|
||||
for key, default in (
|
||||
@@ -665,6 +680,21 @@ class StageConfigFactory:
|
||||
final_output_type,
|
||||
model_class_name,
|
||||
)
|
||||
return engine_args, parallel_config, default_sampling_params, final_output_type
|
||||
|
||||
@classmethod
|
||||
def create_default_diffusion(cls, kwargs: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Build the temporary runtime ABI for a generic diffusion stage.
|
||||
|
||||
The terminal diffusion config owns engine defaults and normalization;
|
||||
this compatibility builder only adds Omni stage topology, request
|
||||
defaults, and device placement.
|
||||
"""
|
||||
engine_args, parallel_config, default_sampling_params, final_output_type = cls._normalize_default_diffusion(
|
||||
kwargs
|
||||
)
|
||||
engine_args["parallel_config"] = asdict(parallel_config)
|
||||
engine_args["model_stage"] = "diffusion"
|
||||
|
||||
return [
|
||||
{
|
||||
@@ -681,6 +711,50 @@ class StageConfigFactory:
|
||||
}
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def create_typed_default_diffusion(
|
||||
cls,
|
||||
model: str,
|
||||
kwargs: dict[str, Any],
|
||||
) -> VllmOmniConfig:
|
||||
"""Build generic diffusion directly into the structured runtime config."""
|
||||
engine_overrides, parallel_config, default_sampling_params, final_output_type = (
|
||||
cls._normalize_default_diffusion(kwargs)
|
||||
)
|
||||
engine_overrides.update(asdict(parallel_config))
|
||||
model_class_name = engine_overrides.get("model_class_name")
|
||||
pipeline = PipelineConfig(
|
||||
model_type="generic_diffusion",
|
||||
model_arch=str(model_class_name or ""),
|
||||
stages=(
|
||||
StagePipelineConfig(
|
||||
stage_id=0,
|
||||
model_stage="diffusion",
|
||||
execution_type=StageExecutionType.DIFFUSION,
|
||||
final_output=True,
|
||||
final_output_type=final_output_type,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
# These values have already been normalized for this diffusion stage.
|
||||
# Scope them explicitly so diffusion-only fields such as engine_backend
|
||||
# and extras are not filtered by the global LLM CLI argument surface.
|
||||
stage_overrides = {
|
||||
f"stage_0_{key}": value for key, value in engine_overrides.items() if key not in {"model", "stage_id"}
|
||||
}
|
||||
stage_overrides["stage_0_devices"] = (
|
||||
kwargs.get("stage_0_devices")
|
||||
or kwargs.get("devices")
|
||||
or ",".join(str(i) for i in range(parallel_config.world_size))
|
||||
)
|
||||
# Caller defaults belong to deployment, not immutable pipeline constraints:
|
||||
# explicit request sampling parameters must still be able to override them.
|
||||
deploy = DeployConfig(stages=[StageDeployConfig(stage_id=0, default_sampling_params=default_sampling_params)])
|
||||
return VllmOmniConfig.from_pipeline_config(
|
||||
pipeline, user_deploy_config=deploy, cli_overrides={"model": model, **stage_overrides}
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _merge_cli_overrides(
|
||||
cls,
|
||||
|
||||
@@ -29,7 +29,9 @@ from vllm.config import ProfilerConfig as VllmProfilerConfig
|
||||
from vllm.config import SchedulerConfig as VllmSchedulerConfig
|
||||
from vllm.config.utils import config
|
||||
from vllm.engine.arg_utils import EngineArgs as VllmEngineArgs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
from vllm.pooling_params import PoolingParams
|
||||
|
||||
from vllm_omni.config.stage_config import (
|
||||
_DEPLOY_DIR,
|
||||
@@ -42,11 +44,13 @@ from vllm_omni.config.stage_config import (
|
||||
StagePipelineConfig,
|
||||
StageType,
|
||||
_apply_platform_overrides,
|
||||
_get_recursively_merged_dict,
|
||||
_resolve_scheduler,
|
||||
_scheduler_path,
|
||||
_select_processor_funcs,
|
||||
build_stage_runtime_overrides,
|
||||
load_deploy_config,
|
||||
merge_pipeline_deploy,
|
||||
merge_sampling_constraints,
|
||||
normalize_pipeline_cli_overrides,
|
||||
reconcile_diffusion_attention_overrides,
|
||||
@@ -55,6 +59,8 @@ from vllm_omni.config.stage_config import (
|
||||
)
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_EXECUTION_TYPE_TO_STAGE_WORKER: dict[StageExecutionType, tuple[StageType, str | None]] = {
|
||||
StageExecutionType.LLM_AR: (StageType.LLM, "ar"),
|
||||
StageExecutionType.LLM_GENERATION: (StageType.LLM, "generation"),
|
||||
@@ -186,6 +192,11 @@ class _ModelEngineOverrides(TypedDict, total=False):
|
||||
enable_prompt_embeds: bool
|
||||
|
||||
|
||||
class _PoolingEngineOverrides(TypedDict, total=False):
|
||||
runner: str
|
||||
pooling_output_decoder: str
|
||||
|
||||
|
||||
class _LoadEngineOverrides(TypedDict, total=False):
|
||||
tokenizer: str
|
||||
download_dir: str
|
||||
@@ -261,6 +272,7 @@ class _StageEngineValues:
|
||||
quantization: _QuantizationEngineOverrides
|
||||
model: _ModelEngineOverrides
|
||||
load: _LoadEngineOverrides
|
||||
pooling: _PoolingEngineOverrides
|
||||
cache: _CacheEngineOverrides
|
||||
scheduler: _SchedulerEngineOverrides
|
||||
connector: _ConnectorEngineOverrides
|
||||
@@ -476,6 +488,15 @@ class OmniStageModelConfig(_TrackExplicitConfigFields):
|
||||
enable_prompt_embeds: bool | None = None
|
||||
|
||||
|
||||
@config(config=ConfigDict(arbitrary_types_allowed=True))
|
||||
class OmniStagePoolingConfig:
|
||||
"""Typed inputs owned by vLLM pooling stages."""
|
||||
|
||||
runner: str | None = None
|
||||
pooling_output_decoder: str | None = None
|
||||
default_pooling_params: PoolingParams | None = None
|
||||
|
||||
|
||||
@_enforce_keyword_only_init
|
||||
@config(kw_only=True)
|
||||
class OmniStageLoadConfig(_TrackExplicitConfigFields, VllmLoadConfig):
|
||||
@@ -817,6 +838,8 @@ class _DiffusionConfigProjection:
|
||||
enable_stage_verification: bool = True
|
||||
prompt_file_path: str | None = None
|
||||
quantization_config: _QuantizationConfigType = None
|
||||
# Internal provenance, retained across config projection and worker transport.
|
||||
quantization_config_is_auto_detected: bool = False
|
||||
extras: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@field_validator("kv_transfer_config", mode="before")
|
||||
@@ -831,12 +854,12 @@ class _DiffusionConfigProjection:
|
||||
from vllm_omni.diffusion.data import normalize_omni_diffusion_kwargs
|
||||
from vllm_omni.diffusion.offloader.config import parse_diffusion_offload_config
|
||||
|
||||
normalized_kwargs = normalize_omni_diffusion_kwargs(kwargs)
|
||||
config_kwargs = normalize_omni_diffusion_kwargs(kwargs)
|
||||
# Validate before stage construction while retaining the raw mapping
|
||||
# needed by dataclass/config serialization across process boundaries.
|
||||
parse_diffusion_offload_config(normalized_kwargs.get("diffusion_offload_config"))
|
||||
parse_diffusion_offload_config(config_kwargs.get("diffusion_offload_config"))
|
||||
valid_fields = {f.name for f in fields(cast(Any, cls))}
|
||||
return cls(**{k: v for k, v in normalized_kwargs.items() if k in valid_fields})
|
||||
return cls(**{k: v for k, v in config_kwargs.items() if k in valid_fields})
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Keep diffusion imports lazy so importing vllm_omni.config does not
|
||||
@@ -964,6 +987,8 @@ class _DiffusionConfigProjection:
|
||||
or (is_checkpoint_nvfp4 and self._is_generic_nvfp4_quant_config(self.quantization_config))
|
||||
)
|
||||
if should_use_checkpoint_config:
|
||||
if self.quantization_config is None:
|
||||
self.quantization_config_is_auto_detected = True
|
||||
self.quantization_config = quant_config
|
||||
if quant_method is not None:
|
||||
self.additional_config.setdefault("auto_detected_quant_method", quant_method)
|
||||
@@ -1141,6 +1166,7 @@ _MODEL_ENGINE_FIELDS = frozenset(_ModelEngineOverrides.__annotations__)
|
||||
_LOAD_ENGINE_FIELDS = frozenset(_LoadEngineOverrides.__annotations__)
|
||||
_CACHE_ENGINE_FIELDS = frozenset(_CacheEngineOverrides.__annotations__)
|
||||
_SCHEDULER_ENGINE_FIELDS = frozenset(_SchedulerEngineOverrides.__annotations__)
|
||||
_POOLING_ENGINE_FIELDS = frozenset(_PoolingEngineOverrides.__annotations__)
|
||||
_CONNECTOR_ENGINE_FIELDS = frozenset(_ConnectorEngineOverrides.__annotations__)
|
||||
_RUNTIME_ENGINE_FIELDS = frozenset(_RuntimeEngineOverrides.__annotations__)
|
||||
_DIRECT_VLLM_CONFIG_ENGINE_FIELDS = frozenset({"compilation_config", "profiler_config"})
|
||||
@@ -1171,6 +1197,7 @@ _LLM_STAGE_ENGINE_FIELDS = (
|
||||
| _LLM_CACHE_ENGINE_FIELDS
|
||||
| _LLM_SCHEDULER_ENGINE_FIELDS
|
||||
| _LLM_PARALLEL_CONFIG_ENGINE_FIELDS
|
||||
| _POOLING_ENGINE_FIELDS
|
||||
| {"parallel_config"}
|
||||
)
|
||||
_DIFFUSION_OWNED_STAGE_ENGINE_FIELDS = (
|
||||
@@ -1304,7 +1331,12 @@ def _stage_engine_values(
|
||||
if topology.execution_type == StageExecutionType.DIFFUSION:
|
||||
# Mirror StageConfig.to_omegaconf so both projections resolve alike.
|
||||
reconcile_diffusion_attention_overrides(engine, stage_cli_overrides)
|
||||
engine.update(_copy_value(stage_cli_overrides))
|
||||
for key, value in stage_cli_overrides.items():
|
||||
existing = engine.get(key)
|
||||
if key != "omni_kv_config" and isinstance(existing, dict) and isinstance(value, Mapping):
|
||||
engine[key] = _get_recursively_merged_dict(existing, dict(value))
|
||||
else:
|
||||
engine[key] = _copy_value(value)
|
||||
_validate_stage_engine_override_ownership(
|
||||
topology.stage_id,
|
||||
topology.execution_type,
|
||||
@@ -1330,6 +1362,10 @@ def _stage_engine_values(
|
||||
),
|
||||
model=cast(_ModelEngineOverrides, _select_engine_overrides(engine, _MODEL_ENGINE_FIELDS)),
|
||||
load=cast(_LoadEngineOverrides, _select_engine_overrides(engine, load_engine_fields)),
|
||||
pooling=cast(
|
||||
_PoolingEngineOverrides,
|
||||
_select_engine_overrides(engine, _POOLING_ENGINE_FIELDS),
|
||||
),
|
||||
cache=cast(_CacheEngineOverrides, _select_engine_overrides(engine, cache_engine_fields)),
|
||||
scheduler=cast(
|
||||
_SchedulerEngineOverrides,
|
||||
@@ -1402,6 +1438,7 @@ class BaseVllmOmniStageConfig:
|
||||
cache_config: OmniStageCacheConfig = field(default_factory=OmniStageCacheConfig)
|
||||
scheduler_config: OmniStageSchedulerConfig = field(default_factory=OmniStageSchedulerConfig)
|
||||
connector_config: OmniStageConnectorConfig = field(default_factory=OmniStageConnectorConfig)
|
||||
pooling_config: OmniStagePoolingConfig = field(default_factory=OmniStagePoolingConfig)
|
||||
runtime_config: OmniStageRuntimeConfig = field(default_factory=OmniStageRuntimeConfig)
|
||||
parallel_config: OmniStageParallelConfig = field(default_factory=OmniStageParallelConfig)
|
||||
compilation_config: VllmCompilationConfig | None = None
|
||||
@@ -1486,6 +1523,10 @@ class BaseVllmOmniStageConfig:
|
||||
def prompt_transform_func(self) -> str | None:
|
||||
return self.stage_pipeline_config.prompt_transform_func
|
||||
|
||||
@property
|
||||
def sampling_constraints(self) -> dict[str, Any]:
|
||||
return dict(self.stage_pipeline_config.sampling_constraints)
|
||||
|
||||
@property
|
||||
def cfg_kv_collect_func(self) -> str | None:
|
||||
return self.stage_pipeline_config.cfg_kv_collect_func
|
||||
@@ -1539,6 +1580,7 @@ def _build_common_stage_config_kwargs(
|
||||
model=model,
|
||||
),
|
||||
"load_config": _build_load_config(topology, engine.load),
|
||||
"pooling_config": _build_pooling_config(stage_deploy, engine.pooling),
|
||||
"cache_config": _build_cache_config(
|
||||
deploy,
|
||||
engine.cache,
|
||||
@@ -1752,6 +1794,20 @@ def _build_model_config(
|
||||
)
|
||||
|
||||
|
||||
def _build_pooling_config(
|
||||
stage_deploy: StageDeployConfig | None,
|
||||
engine: _PoolingEngineOverrides,
|
||||
) -> OmniStagePoolingConfig:
|
||||
default_pooling_params = None
|
||||
if stage_deploy is not None and stage_deploy.default_pooling_params:
|
||||
default_pooling_params = PoolingParams(**dict(stage_deploy.default_pooling_params))
|
||||
return cast(Any, OmniStagePoolingConfig)(
|
||||
runner=_copy_value(engine.get("runner")),
|
||||
pooling_output_decoder=_copy_value(engine.get("pooling_output_decoder")),
|
||||
default_pooling_params=default_pooling_params,
|
||||
)
|
||||
|
||||
|
||||
def _build_load_config(
|
||||
topology: StagePipelineConfig,
|
||||
engine: _LoadEngineOverrides,
|
||||
@@ -1930,6 +1986,10 @@ class VllmOmniConfig:
|
||||
pipeline_config: PipelineConfig
|
||||
stage_configs: tuple[StageConfigType, ...]
|
||||
orchestrator_config: VllmOmniOrchestratorConfig = field(default_factory=VllmOmniOrchestratorConfig)
|
||||
# Keep strategy provenance separate from the effective orchestrator value:
|
||||
# an explicit CLI policy may be present even when the strategy declares no
|
||||
# stage-replica axis.
|
||||
strategy_omni_lb_policy: str | None = None
|
||||
|
||||
def stage_by_id(self, stage_id: int) -> StageConfigType:
|
||||
for stage in self.stage_configs:
|
||||
@@ -1945,6 +2005,7 @@ class VllmOmniConfig:
|
||||
user_deploy_config: DeployConfig | None = None,
|
||||
deploy_config_path: str | None = None,
|
||||
cli_overrides: dict[str, Any] | None = None,
|
||||
strategy_specs: Mapping[Any, Any] | None = None,
|
||||
) -> VllmOmniConfig:
|
||||
"""Create a structured config from a resolved pipeline and deploy YAML."""
|
||||
if cli_overrides is None:
|
||||
@@ -1969,6 +2030,62 @@ class VllmOmniConfig:
|
||||
deploy.async_chunk = False
|
||||
_validate_async_chunk_support(pipeline_cfg, deploy)
|
||||
validate_stage_async_chunk_edges(pipeline_cfg, deploy)
|
||||
|
||||
strategy_result = None
|
||||
if strategy_specs:
|
||||
from vllm_omni.config.composable_parallel import apply_strategy_specs
|
||||
|
||||
strategy_stages = merge_pipeline_deploy(pipeline_cfg, copy.deepcopy(deploy), {})
|
||||
strategy_result = apply_strategy_specs(strategy_stages, strategy_specs)
|
||||
strategy_overrides: dict[str, Any] = {}
|
||||
axis_fields = {
|
||||
"tp": "tensor_parallel_size",
|
||||
"dp": "data_parallel_size",
|
||||
"pp": "pipeline_parallel_size",
|
||||
}
|
||||
for stage_id, parallel in strategy_result.per_stage_config.items():
|
||||
declared = set(parallel.l1_owners)
|
||||
explicit = build_stage_runtime_overrides(stage_id, cli_overrides)
|
||||
for axis, field_name in axis_fields.items():
|
||||
if axis not in declared:
|
||||
continue
|
||||
derived = getattr(parallel, field_name)
|
||||
value = explicit.get(field_name)
|
||||
if value is None:
|
||||
value = derived
|
||||
elif value != derived:
|
||||
logger.warning(
|
||||
"[composable_parallel] stage %s: CLI %s=%s overrides the "
|
||||
"strategy-derived %s=%s. The CLI value wins; remove one to avoid ambiguity.",
|
||||
stage_id,
|
||||
field_name,
|
||||
value,
|
||||
field_name,
|
||||
derived,
|
||||
)
|
||||
strategy_overrides[f"stage_{stage_id}_{field_name}"] = value
|
||||
if "ep" in declared and parallel.enable_expert_parallel:
|
||||
strategy_overrides[f"stage_{stage_id}_enable_expert_parallel"] = bool(
|
||||
explicit.get("enable_expert_parallel", True)
|
||||
)
|
||||
if "stage_replica" in declared:
|
||||
derived = parallel.stage_replica_size
|
||||
value = explicit.get("num_replicas")
|
||||
if value is None:
|
||||
value = derived
|
||||
elif value != derived:
|
||||
logger.warning(
|
||||
"[composable_parallel] stage %s: CLI num_replicas=%s overrides the "
|
||||
"strategy-derived num_replicas=%s. The CLI value wins; remove one to avoid ambiguity.",
|
||||
stage_id,
|
||||
value,
|
||||
derived,
|
||||
)
|
||||
strategy_overrides[f"stage_{stage_id}_num_replicas"] = value
|
||||
cli_overrides = {**strategy_overrides, **cli_overrides}
|
||||
if strategy_result.omni_lb_policy is not None and cli_overrides.get("omni_lb_policy") is None:
|
||||
cli_overrides["omni_lb_policy"] = strategy_result.omni_lb_policy
|
||||
|
||||
deploy_by_id = {stage.stage_id: stage for stage in deploy.stages}
|
||||
model = cli_overrides.get("model")
|
||||
|
||||
@@ -1991,6 +2108,20 @@ class VllmOmniConfig:
|
||||
)
|
||||
for topology in pipeline_cfg.stages
|
||||
)
|
||||
if strategy_result is not None:
|
||||
from vllm_omni.config.composable_parallel import check_device_layout
|
||||
|
||||
by_id = {stage.stage_id: stage for stage in stage_configs}
|
||||
for stage_id in strategy_result.per_stage_config:
|
||||
stage = by_id[stage_id]
|
||||
check_device_layout(
|
||||
stage.runtime_config.devices,
|
||||
tensor_parallel_size=stage.parallel_config.tensor_parallel_size,
|
||||
data_parallel_size=stage.parallel_config.data_parallel_size,
|
||||
pipeline_parallel_size=stage.parallel_config.pipeline_parallel_size,
|
||||
num_replicas=stage.runtime_config.num_replicas,
|
||||
role=stage.model_stage,
|
||||
)
|
||||
|
||||
orchestrator_config = cast(Any, VllmOmniOrchestratorConfig)(
|
||||
deploy_config_path=loaded_deploy_config_path,
|
||||
@@ -2000,6 +2131,7 @@ class VllmOmniConfig:
|
||||
pipeline_config=pipeline_cfg,
|
||||
stage_configs=stage_configs,
|
||||
orchestrator_config=orchestrator_config,
|
||||
strategy_omni_lb_policy=(strategy_result.omni_lb_policy if strategy_result is not None else None),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ from vllm_omni.config.config_factory import StageConfigFactory, with_trust_remot
|
||||
from vllm_omni.config.endpoint_policy import EndpointRestriction
|
||||
from vllm_omni.config.omni_config import VllmOmniConfig
|
||||
from vllm_omni.config.stage_config import PipelineConfig
|
||||
from vllm_omni.config.yaml_util import create_config
|
||||
from vllm_omni.diffusion.data import resolve_model_class_name
|
||||
from vllm_omni.diffusion.registry import DiffusionModelRegistry
|
||||
from vllm_omni.diffusion.utils.hf_utils import is_diffusion_model
|
||||
@@ -24,19 +23,10 @@ logger = init_logger(__name__)
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OmniConfigResolution:
|
||||
"""Migration envelope returned by the production config resolver.
|
||||
|
||||
``stage_configs`` intentionally carries the current OmegaConf-compatible
|
||||
runtime ABI only until stage startup consumes ``VllmOmniConfig`` directly.
|
||||
``pipeline_config`` is the effective topology after runtime stage injection,
|
||||
so both fields always describe the same set of stages.
|
||||
It is not a stable authoring or extension API; new production callers
|
||||
should resolve through :func:`resolve_omni_config` and must not construct or
|
||||
merge this compatibility shape themselves.
|
||||
"""
|
||||
"""Canonical typed result returned by the production config resolver."""
|
||||
|
||||
config_path: str | None
|
||||
stage_configs: tuple[Any, ...] # Temporary StageConfig/OmegaConf bridge.
|
||||
stage_configs: tuple[Any, ...]
|
||||
pipeline_config: PipelineConfig | None = None
|
||||
omni_lb_policy: str | None = None
|
||||
|
||||
@@ -176,27 +166,13 @@ def _load_strategy_specs(strategy_config_path: str | None) -> Mapping[Any, Any]
|
||||
|
||||
def _build_registered_resolution(
|
||||
structured_config: VllmOmniConfig,
|
||||
*,
|
||||
cli_overrides: dict[str, Any],
|
||||
strategy_config_path: str | None,
|
||||
) -> OmniConfigResolution:
|
||||
"""Build the temporary runtime view for an already-resolved pipeline."""
|
||||
# Runtime consumers have not yet moved to typed per-stage configs. Use the
|
||||
# factory-owned compatibility bridge instead of reimplementing legacy YAML
|
||||
# discovery and merging in this resolver.
|
||||
effective_deploy_path = structured_config.orchestrator_config.deploy_config_path
|
||||
legacy_resolution = StageConfigFactory._resolve_legacy_from_registry(
|
||||
structured_config.pipeline_config,
|
||||
cli_overrides,
|
||||
effective_deploy_path,
|
||||
strategy_specs=_load_strategy_specs(strategy_config_path),
|
||||
)
|
||||
|
||||
"""Return the canonical structured runtime view for a resolved pipeline."""
|
||||
return OmniConfigResolution(
|
||||
config_path=effective_deploy_path,
|
||||
stage_configs=tuple(stage.to_omegaconf() for stage in legacy_resolution.stage_configs),
|
||||
pipeline_config=legacy_resolution.pipeline_config,
|
||||
omni_lb_policy=legacy_resolution.omni_lb_policy,
|
||||
config_path=structured_config.orchestrator_config.deploy_config_path,
|
||||
stage_configs=tuple(structured_config.stage_configs),
|
||||
pipeline_config=structured_config.pipeline_config,
|
||||
omni_lb_policy=getattr(structured_config, "strategy_omni_lb_policy", None),
|
||||
)
|
||||
|
||||
|
||||
@@ -231,18 +207,16 @@ def resolve_omni_config(
|
||||
registry_overrides = dict(normalized_overrides)
|
||||
_flatten_stage_overrides(registry_overrides, stage_overrides)
|
||||
|
||||
strategy_specs = _load_strategy_specs(strategy_config_path)
|
||||
structured_config = StageConfigFactory.create_from_model(
|
||||
model,
|
||||
trust_remote_code=trust_remote_code,
|
||||
cli_overrides=registry_overrides,
|
||||
deploy_config_path=deploy_config_path,
|
||||
strategy_specs=strategy_specs,
|
||||
)
|
||||
if structured_config is not None:
|
||||
return _build_registered_resolution(
|
||||
structured_config,
|
||||
cli_overrides=registry_overrides,
|
||||
strategy_config_path=strategy_config_path,
|
||||
)
|
||||
return _build_registered_resolution(structured_config)
|
||||
|
||||
_apply_generic_stage_overrides(normalized_overrides, stage_overrides)
|
||||
supported, model_class_name = _resolve_generic_diffusion_model_class(model, normalized_overrides)
|
||||
@@ -252,11 +226,12 @@ def resolve_omni_config(
|
||||
)
|
||||
if model_class_name is not None:
|
||||
normalized_overrides.setdefault("model_class_name", model_class_name)
|
||||
default_stages = StageConfigFactory.create_default_diffusion(normalized_overrides)
|
||||
default_config = StageConfigFactory.create_typed_default_diffusion(model, normalized_overrides)
|
||||
|
||||
return OmniConfigResolution(
|
||||
config_path=deploy_config_path,
|
||||
stage_configs=tuple(create_config(_convert_dataclasses_to_dict(default_stages))),
|
||||
stage_configs=tuple(default_config.stage_configs),
|
||||
pipeline_config=default_config.pipeline_config,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,15 @@
|
||||
# Profile validated for the c64 / PROMPTS=512 performance experiments:
|
||||
# Stage 0 talker on GPU 0 with S0=64, Stage 1 Code2Wav on GPU 1 with S1=10.
|
||||
#
|
||||
# For CPU-bound frontend or orchestration workloads, this profile can be used
|
||||
# with ``--api-server-count 2`` or higher to run multiple API frontends over
|
||||
# one shared set of local stage engines. This can improve request parsing,
|
||||
# multimodal/audio preprocessing, and response handling under concurrency;
|
||||
# it does not duplicate GPU engines or make a single GPU-bound request faster.
|
||||
# Each frontend keeps process-local state, so runtime voice mutations, sleep /
|
||||
# wakeup, async video jobs, and resumable duplex sessions are not supported
|
||||
# with more than one API worker. See docs/cli/serve.md for the full boundary.
|
||||
#
|
||||
async_chunk: true
|
||||
|
||||
connectors:
|
||||
|
||||
@@ -1021,6 +1021,8 @@ class OmniDiffusionConfig:
|
||||
# str is resolved to {"method": <str>} internally.
|
||||
# Per-component: {"transformer": {"method": "fp8"}, "vae": None}
|
||||
quantization_config: str | QuantizationConfig | dict[str, Any] | None = None
|
||||
# Internal provenance, retained across config projection and worker transport.
|
||||
quantization_config_is_auto_detected: bool = False
|
||||
# Explicit runtime override for ModelOpt FP8 diffusion checkpoints. This
|
||||
# does not enable FP8 by itself; it only selects CUTLASS once the checkpoint
|
||||
# has already resolved to vLLM's ModelOpt FP8 linear method.
|
||||
@@ -1358,6 +1360,8 @@ class OmniDiffusionConfig:
|
||||
or (is_checkpoint_nvfp4 and self._is_generic_nvfp4_quant_config(self.quantization_config))
|
||||
)
|
||||
if should_use_checkpoint_config:
|
||||
if self.quantization_config is None:
|
||||
self.quantization_config_is_auto_detected = True
|
||||
self.quantization_config = tf_config.quant_config
|
||||
logger.info(
|
||||
"Auto-detected quantization '%s' from model config",
|
||||
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from collections.abc import Generator, Iterable, Sequence
|
||||
from collections.abc import Callable, Generator, Iterable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
@@ -481,8 +481,14 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
)
|
||||
|
||||
def _get_expected_parameter_names(self, model: nn.Module) -> set[str]:
|
||||
"""Return parameter names that should be covered by strict load checks."""
|
||||
all_parameter_names = {name for name, _ in model.named_parameters()}
|
||||
"""Return parameter names that should be covered by strict load checks.
|
||||
|
||||
A parameter with an initialized checkpoint default can explicitly set
|
||||
``is_checkpoint_optional``. It is still loaded when present on disk.
|
||||
"""
|
||||
all_parameter_names = {
|
||||
name for name, param in model.named_parameters() if not getattr(param, "is_checkpoint_optional", False)
|
||||
}
|
||||
sources = self._get_weight_sources(model)
|
||||
|
||||
# Keep strict behavior if no source metadata exists.
|
||||
@@ -853,9 +859,24 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
del model
|
||||
return self.load_fresh_canonical_model()
|
||||
raise
|
||||
self._log_w4a8_fallback_load_summaries(model)
|
||||
self._attach_offload_startup_state(model)
|
||||
return model
|
||||
|
||||
@staticmethod
|
||||
def _log_w4a8_fallback_load_summaries(model: nn.Module) -> None:
|
||||
"""Ask discovered DiTs to report W4A8 state at the common load exit.
|
||||
|
||||
Each DiT derives readiness from its processed layers, so a deferred
|
||||
weight plan cannot be mistaken for the ordinary or HSDP load path.
|
||||
"""
|
||||
components = ModuleDiscovery.discover(model)
|
||||
for component_name, dit in zip(components.dit_names, components.dits):
|
||||
candidate = getattr(dit, "_log_w4a8_fallback_load_summary", None)
|
||||
if callable(candidate):
|
||||
reporter = cast(Callable[[str], None], candidate)
|
||||
reporter(component_name)
|
||||
|
||||
@staticmethod
|
||||
def _request_offload_after_quant(model: nn.Module) -> int:
|
||||
"""Ask online-quant layers to return to host memory once quantized.
|
||||
@@ -1065,6 +1086,16 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
# that have loaded weights tracking currently.
|
||||
if loaded_weights is not None:
|
||||
weights_not_loaded = weights_to_load - loaded_weights
|
||||
# Offline formats can require scales that older online loaders
|
||||
# were allowed to synthesize. Do not apply that legacy tolerance
|
||||
# to an explicitly required checkpoint tensor.
|
||||
required_missing = {
|
||||
name
|
||||
for name, param in model.named_parameters()
|
||||
if name in weights_not_loaded and getattr(param, "is_checkpoint_required", False)
|
||||
}
|
||||
if required_missing:
|
||||
raise ValueError(f"Required weights were not initialized from checkpoint: {required_missing}")
|
||||
# NOTE: if the model is quantized, ignore not_loaded check for scale
|
||||
# weights. ModelOpt FP8 carries a per-tensor `weight_scale` and a
|
||||
# static activation `input_scale`, which the quant method may
|
||||
|
||||
@@ -102,6 +102,7 @@ _MODEL_LEVEL_TARGETS = {
|
||||
"time_embedder.linear_2": "time_embedder.proj_out",
|
||||
"norm_out.linear": "final_layer.adaln_proj.linear",
|
||||
"norm_out.norm": "final_layer.norm",
|
||||
"token_refiner.final_norm": "token_refiner.final_norm",
|
||||
}
|
||||
|
||||
# Per-block adapter suffix -> (native suffix, how a delta enters the native
|
||||
@@ -115,6 +116,8 @@ _BLOCK_TARGETS = {
|
||||
"attn.to_v": ("attn.qkv_proj", _QKV_V),
|
||||
"attn.to_out.0": ("attn.out_proj", _PLAIN),
|
||||
"attn.to_gate_compress": ("attn.to_gate_compress", _PLAIN),
|
||||
"attn.norm_q": ("attn.q_norm", _PLAIN),
|
||||
"attn.norm_k": ("attn.k_norm", _PLAIN),
|
||||
"ff.net.0.proj": ("mlp.fc1", _SWAP_HALVES),
|
||||
"ff.net.2": ("mlp.fc2", _PLAIN),
|
||||
"adaln_proj.linear": ("adaln_proj.linear", _PLAIN),
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Sampling contract for FastVideo FastH3 full checkpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from vllm_omni.diffusion.sched.sigma_schedule import DMD2SigmaSchedule
|
||||
from vllm_omni.errors import OmniClientError
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
|
||||
|
||||
from .fasth3 import FASTH3_BASE_MODEL, _resolve_dit_attention_backend
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
FASTH3_V2_MODEL_ID = "FastVideo/FastVideo-FastH3-8-Step-V2"
|
||||
FASTH3_V2_BASE_SCHEDULE = DMD2SigmaSchedule.from_positions((0.999, 0.874, 0.749, 0.624, 0.5, 0.375, 0.25, 0.125, 0.0))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FastH3CheckpointSpec:
|
||||
"""The full V2 release has its own schedule and trained attention policy.
|
||||
|
||||
This is independent of ``FastH3WeightFusion``: the released weights already
|
||||
contain the entire student, including its learned compression gates.
|
||||
"""
|
||||
|
||||
vsa_sparsity: float = 0.8
|
||||
|
||||
@classmethod
|
||||
def from_metadata(cls, metadata: Mapping[str, object]) -> FastH3CheckpointSpec:
|
||||
"""Validate the release's own fastvideo_inference.json."""
|
||||
required = {
|
||||
"model_id": FASTH3_V2_MODEL_ID,
|
||||
"schema_version": "fasth3-inference-contract-v1",
|
||||
"dmd_denoising_steps": [999, 874, 749, 624, 500, 375, 250, 125],
|
||||
"transformer_forwards": 8,
|
||||
"video_scheduler_shift": 10.0,
|
||||
"audio_scheduler_shift": 3.0,
|
||||
"guidance_scale": 1.0,
|
||||
"attention_backend": "VIDEO_SPARSE_ATTN_H3",
|
||||
"vsa_sparsity": 0.8,
|
||||
"vsa_tile_size": 64,
|
||||
"task": "t2av",
|
||||
}
|
||||
for key, expected in required.items():
|
||||
if metadata.get(key) != expected:
|
||||
raise ValueError(f"unsupported FastH3 contract: {key}={metadata.get(key)!r}, expected {expected!r}")
|
||||
return cls()
|
||||
|
||||
def release_metadata(self) -> dict[str, Any]:
|
||||
"""Express the sampling policy in the existing H3 pipeline schema."""
|
||||
return {
|
||||
"partition": "fl2va",
|
||||
"tasks": ["t2va"],
|
||||
"sigma_shift_scales": {"video": 10.0, "audio": 3.0},
|
||||
"base_schedule": list(FASTH3_V2_BASE_SCHEDULE.base_schedule),
|
||||
}
|
||||
|
||||
def resolve_native_vaes(self, model_root: Path) -> Path:
|
||||
"""Reuse the frozen base VAEs with Omni's native tiled/parallel runtime.
|
||||
|
||||
Only VAE components are fetched; the student and text encoder come
|
||||
directly from the FastVideo release. The release pins the base revision.
|
||||
"""
|
||||
provenance = json.loads((model_root / "provenance.json").read_text(encoding="utf-8"))
|
||||
base = provenance.get("base_model", "")
|
||||
prefix = f"hf://{FASTH3_BASE_MODEL}@"
|
||||
if not isinstance(base, str) or not base.startswith(prefix) or not base[len(prefix) :]:
|
||||
raise ValueError("FastH3 V2 provenance must pin a MiniMaxAI/MiniMax-H3 base revision")
|
||||
return (
|
||||
Path(
|
||||
download_weights_from_hf_specific(
|
||||
model_name_or_path=FASTH3_BASE_MODEL,
|
||||
cache_dir=None,
|
||||
allow_patterns=["FL2VA/video_vae/**", "FL2VA/audio_vae/**"],
|
||||
revision=base[len(prefix) :],
|
||||
require_all=True,
|
||||
)
|
||||
)
|
||||
/ "FL2VA"
|
||||
)
|
||||
|
||||
def check_serving_contract(self, *, partition: str, od_config: OmniDiffusionConfig) -> None:
|
||||
if partition != "fl2va":
|
||||
raise ValueError("FastH3 V2 requires --task-type fl2va (T2VA requests only)")
|
||||
if getattr(od_config, "lora_path", None):
|
||||
raise ValueError("FastH3 V2 is a full checkpoint; additional LoRA adapters are unsupported")
|
||||
if _resolve_dit_attention_backend(od_config) != "FASTVIDEO_VSA":
|
||||
raise ValueError("FastH3 V2 requires --diffusion-attention-backend FASTVIDEO_VSA")
|
||||
attention_config = getattr(od_config, "diffusion_attention_config", None)
|
||||
per_role = getattr(attention_config, "per_role", None) or {}
|
||||
spec = per_role.get("self") or getattr(attention_config, "default", None)
|
||||
if getattr(spec, "fastvideo_vsa_topk", None) is not None:
|
||||
raise ValueError("FastH3 V2 pins VSA sparsity=0.8; remove the fixed fastvideo_vsa_topk override")
|
||||
parallel = getattr(od_config, "parallel_config", None)
|
||||
if any(int(getattr(parallel, key, 1) or 1) != 1 for key in ("ring_degree", "allgather_degree")):
|
||||
raise ValueError("FastH3 V2 supports local attention or pure Ulysses sequence parallelism")
|
||||
|
||||
def check_request(self, sampling: OmniDiffusionSamplingParams, *, step_execution: bool = False) -> None:
|
||||
if step_execution:
|
||||
# StepScheduler admits requests before the pipeline hook runs and
|
||||
# derives its lifetime from these fields. The pinned schedule must
|
||||
# therefore be explicit and cannot be overridden by custom arrays.
|
||||
if sampling.num_inference_steps != FASTH3_V2_BASE_SCHEDULE.num_inference_steps:
|
||||
raise OmniClientError("FastH3 V2 step execution requires num_inference_steps=8")
|
||||
if sampling.timesteps is not None or sampling.sigmas is not None:
|
||||
raise OmniClientError("FastH3 V2 step execution does not support custom timesteps or sigmas")
|
||||
if sampling.lora_request is not None:
|
||||
raise OmniClientError("FastH3 V2 does not support per-request LoRA adapters")
|
||||
steps = sampling.num_inference_steps
|
||||
if steps is not None and steps != FASTH3_V2_BASE_SCHEDULE.num_inference_steps:
|
||||
raise OmniClientError("FastH3 V2 requires num_inference_steps=8 (nine sigma points), or omitted")
|
||||
extra = sampling.extra_args or {}
|
||||
for key, expected in (("flow_shift", 10.0), ("audio_flow_shift", 3.0)):
|
||||
try:
|
||||
value = float(extra.get(key, expected))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise OmniClientError(f"FastH3 V2 requires {key}={expected:g}") from exc
|
||||
if not math.isclose(value, expected):
|
||||
raise OmniClientError(f"FastH3 V2 requires {key}={expected:g}, got {value:g}")
|
||||
if sampling.guidance_scale is not None and sampling.guidance_scale != 1.0:
|
||||
raise OmniClientError("FastH3 V2 requires guidance_scale=1")
|
||||
@@ -55,6 +55,8 @@ from vllm_omni.diffusion.layers.rope import RotaryEmbedding
|
||||
from vllm_omni.diffusion.models.host_weight_contract import FinalLayoutModelContract
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .fasth3 import _resolve_native_target
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import (
|
||||
QuantizationConfig,
|
||||
@@ -118,6 +120,18 @@ class MiniMaxH3DiTArchConfig:
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, config: Mapping[str, Any]) -> MiniMaxH3DiTArchConfig:
|
||||
# The modular Diffusers checkpoint uses these spellings for the same
|
||||
# architecture. Normalize before constructing the existing native DiT.
|
||||
aliases = {
|
||||
"num_refiner_layers": "token_refiner_num_layers",
|
||||
"ffn_dim": "ffn_hidden_size",
|
||||
"in_channels": "latents_dim",
|
||||
"audio_in_channels": "audio_latents_dim",
|
||||
"freq_dim": "timestep_input_dim",
|
||||
"time_embed_hidden_dim": "time_embed_hidden_size",
|
||||
"rope_freq_dim": "rope_inv_freq_len",
|
||||
}
|
||||
config = {aliases.get(name, name): value for name, value in config.items()}
|
||||
fields = cls.__dataclass_fields__
|
||||
values = {name: config[name] for name in fields if name in config}
|
||||
if "patch_size" in values:
|
||||
@@ -394,6 +408,9 @@ def _sdpa_varlen_attention(
|
||||
|
||||
|
||||
class MiniMaxH3Attention(nn.Module):
|
||||
# Full sparse checkpoints pin a ratio; legacy adapters use backend top-k.
|
||||
vsa_sparsity: float | None = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
arch: MiniMaxH3DiTArchConfig,
|
||||
@@ -588,6 +605,7 @@ class MiniMaxH3Attention(nn.Module):
|
||||
# (see MINIMAX_H3_LASER_INPUT_SCALE). Ignored by every other
|
||||
# backend/path.
|
||||
"laser_input_scale": MINIMAX_H3_LASER_INPUT_SCALE,
|
||||
**({"vsa_h3_sparsity": self.vsa_sparsity} if self.vsa_sparsity is not None else {}),
|
||||
# Present only for a VSA artifact; the VSA backend reads it as
|
||||
# the learned compression gate and every other backend ignores it.
|
||||
**({"gate_compress": gate_compress.unsqueeze(0)} if gate_compress is not None else {}),
|
||||
@@ -1127,10 +1145,23 @@ class MiniMaxH3DiTModel(nn.Module):
|
||||
self,
|
||||
od_config: OmniDiffusionConfig,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
*,
|
||||
diffusers_weights: bool | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
tf_config = od_config.tf_model_config
|
||||
config_mapping = tf_config.to_dict() if hasattr(tf_config, "to_dict") else dict(tf_config)
|
||||
# The native MiniMax-H3 Hub snapshot advertises the Diffusers
|
||||
# transformer class in its root config, while its FL2VA/Ref2VA
|
||||
# components still contain native weights. The pipeline has already
|
||||
# resolved the actual source format, so let it override the
|
||||
# class-name heuristic. Keep the heuristic for standalone callers.
|
||||
self._diffusers_weights = (
|
||||
config_mapping.get("_class_name") == "MiniMaxH3Transformer3DModel"
|
||||
if diffusers_weights is None
|
||||
else diffusers_weights
|
||||
)
|
||||
self._rope_theta = float(config_mapping.get("rope_theta", 10000.0))
|
||||
arch = MiniMaxH3DiTArchConfig.from_mapping(config_mapping)
|
||||
self.arch = arch
|
||||
self.od_config = od_config
|
||||
@@ -1211,7 +1242,7 @@ class MiniMaxH3DiTModel(nn.Module):
|
||||
)
|
||||
self._mark_missing_params_required()
|
||||
|
||||
def enable_vsa_gates(self) -> None:
|
||||
def enable_vsa_gates(self, *, sparsity: float | None = None) -> None:
|
||||
"""Give every DiT block's attention a VSA compression gate.
|
||||
|
||||
A FastH3 VSA artifact assigns these projections rather than adding to
|
||||
@@ -1223,6 +1254,9 @@ class MiniMaxH3DiTModel(nn.Module):
|
||||
return
|
||||
for block in self.blocks:
|
||||
block.attn.enable_vsa_gate()
|
||||
block.attn.vsa_sparsity = sparsity
|
||||
if sparsity is not None:
|
||||
block.attn.to_gate_compress.weight.missing_param_init = "error"
|
||||
self.vsa_gates_enabled = True
|
||||
|
||||
def _mark_missing_params_required(self) -> None:
|
||||
@@ -1293,17 +1327,37 @@ class MiniMaxH3DiTModel(nn.Module):
|
||||
self,
|
||||
weights: Iterable[tuple[str, torch.Tensor]],
|
||||
) -> set[str]:
|
||||
"""Load exact H3 checkpoint names with logical TP-aware loaders."""
|
||||
"""Load native or Diffusers H3 weights with the existing TP-aware loaders."""
|
||||
params = dict(self.named_parameters())
|
||||
params.update(dict(self.named_buffers()))
|
||||
loaded: set[str] = set()
|
||||
diffusers_weights = getattr(self, "_diffusers_weights", False)
|
||||
qkv_parts: dict[str, set[str]] = {}
|
||||
source_names: set[str] = set()
|
||||
for name, loaded_weight in weights:
|
||||
layout = "plain"
|
||||
if diffusers_weights:
|
||||
if name in source_names:
|
||||
raise ValueError(f"duplicate Diffusers H3 weight: {name}")
|
||||
source_names.add(name)
|
||||
module, _, kind = name.rpartition(".")
|
||||
target = _resolve_native_target(module)
|
||||
if target is None or kind not in {"weight", "bias"}:
|
||||
raise ValueError(f"unsupported Diffusers H3 weight: {name}")
|
||||
name, layout = f"{target[0]}.{kind}", target[1]
|
||||
param = params.get(name)
|
||||
if param is None:
|
||||
if diffusers_weights:
|
||||
raise ValueError(f"Diffusers H3 weight has no model parameter: {name}")
|
||||
logger.warning("Skipping MiniMax H3 weight not present in model: %s", name)
|
||||
continue
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
if name.endswith(".attn.qkv_proj.weight"):
|
||||
if layout in {"q", "k", "v"}:
|
||||
# vLLM can load each projection directly into its packed QKV
|
||||
# parameter, including TP slicing and online quantization.
|
||||
weight_loader(param, loaded_weight, layout)
|
||||
qkv_parts.setdefault(name, set()).add(layout)
|
||||
elif name.endswith(".attn.qkv_proj.weight"):
|
||||
# Transform checkpoint layout before entering vLLM's loader so
|
||||
# online FP8 can keep ``online_process_loader`` outermost.
|
||||
loaded_weight = _reorder_grouped_qkv_to_qkv(
|
||||
@@ -1319,12 +1373,26 @@ class MiniMaxH3DiTModel(nn.Module):
|
||||
"MiniMax H3 fc1 checkpoint rows must split evenly into "
|
||||
f"gate/up matrices, got {tuple(loaded_weight.shape)}"
|
||||
)
|
||||
gate, up = loaded_weight.chunk(2, dim=0)
|
||||
first, second = loaded_weight.chunk(2, dim=0)
|
||||
gate, up = (second, first) if layout == "swap_halves" else (first, second)
|
||||
weight_loader(param, gate, 0)
|
||||
weight_loader(param, up, 1)
|
||||
else:
|
||||
weight_loader(param, loaded_weight)
|
||||
loaded.add(name)
|
||||
if diffusers_weights:
|
||||
for name, parts in qkv_parts.items():
|
||||
if parts != {"q", "k", "v"}:
|
||||
raise ValueError(f"incomplete Diffusers H3 QKV group {name}: {sorted(parts)}")
|
||||
# Diffusers reconstructs RoPE from config instead of storing this
|
||||
# native checkpoint buffer. Compute on CPU for identical values.
|
||||
freq_dim = self.arch.rope_inv_freq_len
|
||||
rope = 1.0 / (
|
||||
self._rope_theta
|
||||
** (torch.arange(0, 2 * freq_dim, 2, dtype=torch.float32, device="cpu") / (2 * freq_dim))
|
||||
)
|
||||
default_weight_loader(params["rope.inv_freq"], rope)
|
||||
loaded.add("rope.inv_freq")
|
||||
return loaded
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -67,6 +67,7 @@ from vllm_omni.model_executor.model_loader.weight_utils import (
|
||||
download_weights_from_hf_specific,
|
||||
)
|
||||
from vllm_omni.model_executor.models.minimax_h3.checkpoint import (
|
||||
is_minimax_h3_modular,
|
||||
resolve_minimax_h3_partition,
|
||||
)
|
||||
from vllm_omni.model_executor.models.minimax_h3.conditioning import (
|
||||
@@ -106,6 +107,7 @@ from .denoise_loop import (
|
||||
)
|
||||
from .encoder import MiniMaxH3Qwen3VLEncoder
|
||||
from .fasth3 import FastH3WeightFusion, resolve_fasth3_fusion
|
||||
from .fasth3_checkpoint import FastH3CheckpointSpec
|
||||
from .lora import TurboSpec, load_minimax_h3_turbo_lora
|
||||
from .minimax_h3_transformer import (
|
||||
MiniMaxH3Attention,
|
||||
@@ -213,7 +215,11 @@ def _resolve_minimax_h3_model_root(
|
||||
if path.name in {"FL2VA", "Ref2VA"}:
|
||||
return path.parent
|
||||
return path
|
||||
if load_text_encoder:
|
||||
if is_minimax_h3_modular(model, revision):
|
||||
allow_patterns = ["modular_model_index.json", "fastvideo_inference.json", "provenance.json", "transformer/**"]
|
||||
if load_text_encoder:
|
||||
allow_patterns += ["text_encoder/**", "tokenizer/**", "processor/**"]
|
||||
elif load_text_encoder:
|
||||
allow_patterns = (
|
||||
MINIMAX_H3_DOWNLOAD_PATTERNS if partition == "combined" else MINIMAX_H3_TASK_DOWNLOAD_PATTERNS[partition]
|
||||
)
|
||||
@@ -314,6 +320,8 @@ def resolve_minimax_h3_diffusion_model_path(
|
||||
partition,
|
||||
load_text_encoder=False,
|
||||
)
|
||||
if is_minimax_h3_modular(str(model_root), revision):
|
||||
return str(model_root)
|
||||
if partition == "combined":
|
||||
return str(model_root)
|
||||
subdir = "Ref2VA" if partition == "ref2va" else "FL2VA"
|
||||
@@ -575,6 +583,7 @@ class MiniMaxH3Pipeline(
|
||||
_base_schedule_by_partition: ClassVar[Mapping[str, DMD2SigmaSchedule | None]] = {}
|
||||
# Set from --lora-path during construction; absent means no FastH3 adapter.
|
||||
_fasth3: FastH3WeightFusion | None = None
|
||||
_fasth3_checkpoint: FastH3CheckpointSpec | None = None
|
||||
|
||||
def _load_diffusion_lora_adapter(
|
||||
self,
|
||||
@@ -800,10 +809,13 @@ class MiniMaxH3Pipeline(
|
||||
self._PROFILER_TARGETS.remove("encode_prompt")
|
||||
if not self.load_vae_encoder:
|
||||
self._PROFILER_TARGETS.remove("_encode_local_media")
|
||||
modular = is_minimax_h3_modular(str(od_config.model), od_config.revision)
|
||||
self.partition = _minimax_h3_partition_for_task(
|
||||
getattr(od_config, "task_type", None),
|
||||
str(od_config.model),
|
||||
)
|
||||
if modular and str(od_config.task_type or "auto").lower() == "auto":
|
||||
self.partition = "fl2va"
|
||||
self._turbo_lora_specs: dict[int, TurboSpec] = {}
|
||||
self._native_lora_adapter_ids: set[int] = set()
|
||||
self._lora_sigma_schedules: dict[int, DMD2SigmaSchedule] = {}
|
||||
@@ -813,9 +825,19 @@ class MiniMaxH3Pipeline(
|
||||
self.partition,
|
||||
load_text_encoder=self.load_text_encoder,
|
||||
)
|
||||
model_path = model_root / ("Ref2VA" if self.partition == "ref2va" else "FL2VA")
|
||||
model_index = json.loads((model_path / "model_index.json").read_text(encoding="utf-8"))
|
||||
release = model_index.get("_minimax_h3") or {}
|
||||
if modular:
|
||||
model_path = model_root
|
||||
self._fasth3_checkpoint = FastH3CheckpointSpec.from_metadata(
|
||||
json.loads((model_root / "fastvideo_inference.json").read_text(encoding="utf-8"))
|
||||
)
|
||||
self._fasth3_checkpoint.check_serving_contract(partition=self.partition, od_config=od_config)
|
||||
release = self._fasth3_checkpoint.release_metadata()
|
||||
vae_model_path = self._fasth3_checkpoint.resolve_native_vaes(model_root)
|
||||
else:
|
||||
model_path = model_root / ("Ref2VA" if self.partition == "ref2va" else "FL2VA")
|
||||
model_index = json.loads((model_path / "model_index.json").read_text(encoding="utf-8"))
|
||||
release = model_index.get("_minimax_h3") or {}
|
||||
vae_model_path = model_path
|
||||
partition = str(release.get("partition", "")).lower()
|
||||
expected_partition = "ref2va" if self.partition == "ref2va" else "fl2va"
|
||||
if partition != expected_partition:
|
||||
@@ -876,11 +898,18 @@ class MiniMaxH3Pipeline(
|
||||
self.transformer = MiniMaxH3DiTModel(
|
||||
od_config,
|
||||
quant_config=transformer_quant_config,
|
||||
diffusers_weights=modular,
|
||||
)
|
||||
if self._fasth3_checkpoint is not None:
|
||||
self.transformer.enable_vsa_gates(sparsity=self._fasth3_checkpoint.vsa_sparsity)
|
||||
logger.info(
|
||||
"FastH3 V2 full checkpoint: 8 transformer forwards, video/audio shifts 10/3, VSA sparsity=0.8 tile=64"
|
||||
)
|
||||
if ref2va_model_path is not None:
|
||||
self.transformers_ref = MiniMaxH3DiTModel(
|
||||
od_config,
|
||||
quant_config=transformer_quant_config,
|
||||
diffusers_weights=modular,
|
||||
)
|
||||
|
||||
self._fasth3 = resolve_fasth3_fusion(od_config, self.transformer)
|
||||
@@ -963,14 +992,14 @@ class MiniMaxH3Pipeline(
|
||||
# so VAEs stay resident for new configurations.
|
||||
component_load_device = torch.device("cpu") if legacy_manual_components else self.device
|
||||
self.video_vae = MiniMaxH3VideoVAE(
|
||||
os.path.join(model_path, "video_vae"),
|
||||
os.path.join(vae_model_path, "video_vae"),
|
||||
device=self.device,
|
||||
load_device=component_load_device,
|
||||
decode_only=not self.load_vae_encoder,
|
||||
trust_remote_code=od_config.trust_remote_code,
|
||||
)
|
||||
self.audio_vae = MiniMaxH3AudioVAE(
|
||||
os.path.join(model_path, "audio_vae"),
|
||||
os.path.join(vae_model_path, "audio_vae"),
|
||||
device=self.device,
|
||||
load_device=component_load_device,
|
||||
decode_only=not self.load_vae_encoder,
|
||||
@@ -1046,6 +1075,12 @@ class MiniMaxH3Pipeline(
|
||||
# load_weights only warns on a parameter the model does not have, so
|
||||
# close the adapter against what the DiT actually consumed.
|
||||
self._fasth3.validate_fully_applied(transformer_loaded)
|
||||
if self._fasth3_checkpoint is not None:
|
||||
required_gates = {
|
||||
f"blocks.{i}.attn.to_gate_compress.weight" for i in range(self.transformer.arch.num_layers)
|
||||
}
|
||||
if missing_gates := required_gates - transformer_loaded:
|
||||
raise ValueError(f"FastH3 V2 checkpoint is missing compression gates: {sorted(missing_gates)}")
|
||||
return loaded_with_prefix
|
||||
|
||||
@property
|
||||
@@ -2056,6 +2091,11 @@ class MiniMaxH3Pipeline(
|
||||
self._validate_turbo_sampling(sampling, turbo_spec)
|
||||
if has_native_lora:
|
||||
self._validate_native_sampling(sampling, task=task)
|
||||
if self._fasth3_checkpoint is not None:
|
||||
self._fasth3_checkpoint.check_request(
|
||||
sampling,
|
||||
step_execution=bool(getattr(self.od_config, "step_execution", False)),
|
||||
)
|
||||
if self._fasth3 is not None:
|
||||
self._fasth3.check_request(
|
||||
sampling,
|
||||
|
||||
@@ -179,8 +179,36 @@ def load_transformer_config(model_path: str, subfolder: str = "transformer", loc
|
||||
return {}
|
||||
|
||||
|
||||
def resolve_wan_transformer_quant_config(
|
||||
config: dict, quant_config: QuantizationConfig | None, component: str
|
||||
) -> QuantizationConfig | None:
|
||||
"""Resolve the expert before applying its checkpoint's storage contract."""
|
||||
from vllm_omni.quantization.component_config import ComponentQuantizationConfig
|
||||
from vllm_omni.quantization.factory import resolve_quant_config_from_disk
|
||||
|
||||
# Wan experts are siblings: "transformer_2" must not inherit "transformer"
|
||||
# through the generic layer-prefix resolver. Select the whole expert name.
|
||||
component_quant_config = (
|
||||
quant_config.component_configs.get(component, quant_config.default_config)
|
||||
if isinstance(quant_config, ComponentQuantizationConfig)
|
||||
else quant_config
|
||||
)
|
||||
quantization_disabled = isinstance(quant_config, ComponentQuantizationConfig) and component_quant_config is None
|
||||
resolved_quant_config = resolve_quant_config_from_disk(component_quant_config, config.get("quantization_config"))
|
||||
if quantization_disabled and resolved_quant_config is not None:
|
||||
raise ValueError(
|
||||
f"Quantization is disabled for component {component!r}, but its checkpoint declares quantization. "
|
||||
"Use a BF16 checkpoint for this component or enable its matching quantization method."
|
||||
)
|
||||
return resolved_quant_config
|
||||
|
||||
|
||||
def create_transformer_from_config(
|
||||
config: dict, quant_config: QuantizationConfig | None = None, prefix: str = ""
|
||||
config: dict,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
*,
|
||||
component: str = "transformer",
|
||||
) -> WanTransformer3DModel:
|
||||
"""Create WanTransformer3DModel from config dict."""
|
||||
kwargs: dict = {}
|
||||
@@ -216,11 +244,7 @@ def create_transformer_from_config(
|
||||
if "pos_embed_seq_len" in config:
|
||||
kwargs["pos_embed_seq_len"] = config["pos_embed_seq_len"]
|
||||
|
||||
if "quantization_config" in config:
|
||||
from vllm_omni.quantization.factory import resolve_quant_config_from_disk
|
||||
|
||||
quant_config = resolve_quant_config_from_disk(quant_config, config["quantization_config"])
|
||||
|
||||
quant_config = resolve_wan_transformer_quant_config(config, quant_config, component)
|
||||
if quant_config is not None:
|
||||
kwargs["quant_config"] = quant_config
|
||||
if prefix:
|
||||
@@ -460,13 +484,13 @@ class Wan22Pipeline(
|
||||
# Initialize transformers with correct config (weights loaded via load_weights)
|
||||
if load_transformer:
|
||||
transformer_config = load_transformer_config(model, "transformer", local_files_only)
|
||||
self.transformer = self._create_transformer(transformer_config)
|
||||
self.transformer = self._create_transformer(transformer_config, component="transformer")
|
||||
else:
|
||||
self.transformer = None
|
||||
|
||||
if load_transformer_2:
|
||||
transformer_2_config = load_transformer_config(model, "transformer_2", local_files_only)
|
||||
self.transformer_2 = self._create_transformer(transformer_2_config)
|
||||
self.transformer_2 = self._create_transformer(transformer_2_config, component="transformer_2")
|
||||
else:
|
||||
self.transformer_2 = None
|
||||
|
||||
@@ -504,10 +528,17 @@ class Wan22Pipeline(
|
||||
enable_diffusion_pipeline_profiler=self.od_config.enable_diffusion_pipeline_profiler
|
||||
)
|
||||
|
||||
def _create_transformer(self, config: dict) -> WanTransformer3DModel:
|
||||
def _create_transformer(self, config: dict, component: str = "transformer") -> WanTransformer3DModel:
|
||||
"""Create a transformer from a config dict. Respects od_config.quantization_config."""
|
||||
quant_config = getattr(self.od_config, "quantization_config", None)
|
||||
return create_transformer_from_config(config, quant_config=quant_config)
|
||||
# Startup metadata describes the first expert, not a user policy for both.
|
||||
if getattr(self.od_config, "quantization_config_is_auto_detected", False):
|
||||
quant_config = None
|
||||
return create_transformer_from_config(
|
||||
config,
|
||||
quant_config=quant_config,
|
||||
component=component,
|
||||
)
|
||||
|
||||
@property
|
||||
def guidance_scale(self):
|
||||
|
||||
@@ -304,25 +304,10 @@ class Wan22I2VPipeline(
|
||||
# Transformers (weights loaded via load_weights)
|
||||
# Load config from model directory or HF Hub to get correct in_channels for I2V models
|
||||
transformer_config = load_transformer_config(model, "transformer", local_files_only)
|
||||
self.transformer = create_transformer_from_config(
|
||||
transformer_config,
|
||||
quant_config=od_config.quantization_config,
|
||||
)
|
||||
self.transformer = self._create_transformer(transformer_config, component="transformer")
|
||||
if self.has_transformer_2:
|
||||
transformer_2_config = load_transformer_config(model, "transformer_2", local_files_only)
|
||||
t2_quant = transformer_2_config.get("quantization_config")
|
||||
if isinstance(t2_quant, dict) and "quant_method" in t2_quant:
|
||||
from vllm_omni.quantization.factory import build_quant_config
|
||||
|
||||
method = t2_quant["quant_method"]
|
||||
kwargs = {k: v for k, v in t2_quant.items() if k != "quant_method"}
|
||||
t2_quant = build_quant_config(method, **kwargs)
|
||||
else:
|
||||
t2_quant = None
|
||||
self.transformer_2 = create_transformer_from_config(
|
||||
transformer_2_config,
|
||||
quant_config=t2_quant,
|
||||
)
|
||||
self.transformer_2 = self._create_transformer(transformer_2_config, component="transformer_2")
|
||||
else:
|
||||
self.transformer_2 = None
|
||||
|
||||
@@ -462,10 +447,13 @@ class Wan22I2VPipeline(
|
||||
image_embeds = self.image_encoder(pixel_values, output_hidden_states=True)
|
||||
return image_embeds.hidden_states[-2]
|
||||
|
||||
def _create_transformer(self, config: dict) -> WanTransformer3DModel:
|
||||
def _create_transformer(self, config: dict, component: str = "transformer") -> WanTransformer3DModel:
|
||||
"""Create a transformer from a config dict. Respects od_config.quantization_config."""
|
||||
quant_config = getattr(self.od_config, "quantization_config", None)
|
||||
return create_transformer_from_config(config, quant_config=quant_config)
|
||||
# Startup metadata describes the first expert, not a user policy for both.
|
||||
if getattr(self.od_config, "quantization_config_is_auto_detected", False):
|
||||
quant_config = None
|
||||
return create_transformer_from_config(config, quant_config=quant_config, component=component)
|
||||
|
||||
def forward(self, req: DiffusionRequestBatch) -> list[DiffusionOutput]:
|
||||
sampling_params_list = req.sampling_params_list
|
||||
|
||||
@@ -28,6 +28,7 @@ from vllm_omni.diffusion.models.interface import SupportImageInput
|
||||
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
|
||||
Wan22Pipeline,
|
||||
load_wan_weights_with_optional_gate,
|
||||
resolve_wan_transformer_quant_config,
|
||||
retrieve_latents,
|
||||
)
|
||||
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
|
||||
@@ -60,6 +61,8 @@ def create_vace_transformer_from_config(
|
||||
config: dict,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
*,
|
||||
component: str = "transformer",
|
||||
) -> WanVACETransformer3DModel:
|
||||
"""Create WanVACETransformer3DModel from config dict."""
|
||||
kwargs = {}
|
||||
@@ -97,6 +100,7 @@ def create_vace_transformer_from_config(
|
||||
kwargs["vace_layers"] = config["vace_layers"]
|
||||
if "vace_in_channels" in config:
|
||||
kwargs["vace_in_channels"] = config["vace_in_channels"]
|
||||
quant_config = resolve_wan_transformer_quant_config(config, quant_config, component)
|
||||
if quant_config is not None:
|
||||
kwargs["quant_config"] = quant_config
|
||||
if prefix:
|
||||
@@ -205,10 +209,13 @@ class Wan22VACEPipeline(Wan22Pipeline, SupportImageInput):
|
||||
|
||||
super().__init__(od_config=od_config, prefix=prefix)
|
||||
|
||||
def _create_transformer(self, config: dict) -> WanVACETransformer3DModel:
|
||||
def _create_transformer(self, config: dict, component: str = "transformer") -> WanVACETransformer3DModel:
|
||||
"""Build VACE transformer. Respects od_config.quantization_config."""
|
||||
quant_config = getattr(self.od_config, "quantization_config", None)
|
||||
return create_vace_transformer_from_config(config, quant_config=quant_config)
|
||||
# Startup metadata describes the first expert, not a user policy for both.
|
||||
if getattr(self.od_config, "quantization_config_is_auto_detected", False):
|
||||
quant_config = None
|
||||
return create_vace_transformer_from_config(config, quant_config=quant_config, component=component)
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
|
||||
@@ -18,7 +18,7 @@ from vllm.distributed import (
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.conv import Conv3dLayer
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear, QKVParallelLinear, RowParallelLinear
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear, LinearBase, QKVParallelLinear, RowParallelLinear
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.model_executor.models.utils import (
|
||||
@@ -45,6 +45,7 @@ from vllm_omni.diffusion.layers.adalayernorm import AdaLayerNorm
|
||||
from vllm_omni.diffusion.layers.norm import LayerNorm, RMSNorm
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbeddingWan
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
from vllm_omni.quantization.mxfp4_config import NPUMxfp4LinearMethod
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -985,6 +986,68 @@ class WanTransformer3DModel(nn.Module):
|
||||
# ROPE helper
|
||||
self._cached_rope_emb = None
|
||||
self._cached_rope_resolution = None
|
||||
self._validate_w4a8_fallback_layers(quant_config)
|
||||
|
||||
def _validate_w4a8_fallback_layers(self, quant_config: QuantizationConfig | None) -> None:
|
||||
"""Reject checkpoint aliases/typos before loading weights or running inference."""
|
||||
requested = tuple(getattr(quant_config, "w4a8_fallback_layers", []))
|
||||
self._w4a8_fallback_layers = requested
|
||||
self._local_w4a8_fallback_layers: tuple[str, ...] = ()
|
||||
if not requested:
|
||||
return
|
||||
modules = dict(self.named_modules())
|
||||
missing_pp_prefixes = [name for name, module in modules.items() if isinstance(module, PPMissingLayer)]
|
||||
local_layers = [
|
||||
name for name in requested if not any(name.startswith(prefix + ".") for prefix in missing_pp_prefixes)
|
||||
]
|
||||
self._local_w4a8_fallback_layers = tuple(local_layers)
|
||||
invalid = [name for name in local_layers if not isinstance(modules.get(name), LinearBase)]
|
||||
if invalid:
|
||||
raise ValueError(
|
||||
"w4a8_fallback_layers requires exact runtime Linear paths relative to each Wan transformer; "
|
||||
f"unknown/non-Linear paths: {invalid}. Use attn1.to_qkv for fused self-attention, "
|
||||
"not checkpoint attn1.to_q/to_k/to_v names."
|
||||
)
|
||||
|
||||
def _log_w4a8_fallback_load_summary(self, component_name: str) -> None:
|
||||
"""Log post-load transforms/cache readiness, not numerical acceptance."""
|
||||
requested = self._w4a8_fallback_layers
|
||||
if not requested:
|
||||
return
|
||||
modules = dict(self.named_modules())
|
||||
local_layers = self._local_w4a8_fallback_layers
|
||||
selected_layers = [
|
||||
name for name in local_layers if getattr(modules[name].quant_method, "is_w4a8_fallback_layer", False)
|
||||
]
|
||||
bf16_overrides = [name for name in local_layers if name not in selected_layers]
|
||||
processed = [
|
||||
name
|
||||
for name in selected_layers
|
||||
if getattr(modules[name], "_already_called_process_weights_after_loading", False)
|
||||
]
|
||||
if not selected_layers:
|
||||
processing_state = "not-required"
|
||||
elif len(processed) == len(selected_layers):
|
||||
processing_state = "ready"
|
||||
else:
|
||||
processing_state = "not-ready"
|
||||
|
||||
def qualified(names: Iterable[str]) -> list[str]:
|
||||
return [f"{component_name}.{name}" for name in names]
|
||||
|
||||
logger.info(
|
||||
"Wan W4A8 post-load summary: component=%s; selected=%d %s; BF16 overrides=%d %s; "
|
||||
"weight/A8 processing state=%s (%d/%d selected layers processed); other PP ranks=%d",
|
||||
component_name,
|
||||
len(selected_layers),
|
||||
qualified(selected_layers),
|
||||
len(bf16_overrides),
|
||||
qualified(bf16_overrides),
|
||||
processing_state,
|
||||
len(processed),
|
||||
len(selected_layers),
|
||||
len(requested) - len(local_layers),
|
||||
)
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
@@ -1155,7 +1218,22 @@ class WanTransformer3DModel(nn.Module):
|
||||
}
|
||||
|
||||
params_dict = dict(self.named_parameters())
|
||||
single_scale_prefixes = {
|
||||
name
|
||||
for name, module in self.named_modules()
|
||||
if isinstance(getattr(module, "quant_method", None), NPUMxfp4LinearMethod)
|
||||
}
|
||||
|
||||
def reject_dualscale_tensor(name: str) -> None:
|
||||
if name.endswith(".weight_dual_scale") and name.rsplit(".", 1)[0] in single_scale_prefixes:
|
||||
raise ValueError(
|
||||
f"Single-scale mxfp4 cannot load DualScale tensor {name}; "
|
||||
"changing quant_method does not convert a checkpoint."
|
||||
)
|
||||
|
||||
loaded_params: set[str] = set()
|
||||
loaded_qkv_shards: dict[str, set[str]] = {}
|
||||
qkv_smooth_scales: dict[str, torch.Tensor] = {}
|
||||
|
||||
for name, loaded_weight in weights:
|
||||
name = weight_name_remapping.get(name, name)
|
||||
@@ -1166,15 +1244,32 @@ class WanTransformer3DModel(nn.Module):
|
||||
# Pre-fused to_qkv tensors (from offline MXFP8 merged checkpoint) fall
|
||||
# through to the else branch and are loaded directly.
|
||||
for param_name, weight_name, shard_id in stacked_params_mapping:
|
||||
if weight_name not in original_name:
|
||||
if f"{weight_name}." not in original_name:
|
||||
continue
|
||||
lookup_name = original_name.replace(weight_name, param_name)
|
||||
lookup_name = original_name.replace(f"{weight_name}.", f"{param_name}.", 1)
|
||||
reject_dualscale_tensor(lookup_name)
|
||||
# Skip weights that belong to PP stages other than this one
|
||||
if is_pp_missing_parameter(lookup_name, self) or lookup_name not in params_dict:
|
||||
break
|
||||
param = params_dict[lookup_name]
|
||||
if lookup_name.endswith(".mul_scale"):
|
||||
previous_scale = qkv_smooth_scales.get(lookup_name)
|
||||
if previous_scale is not None and not torch.equal(previous_scale, loaded_weight):
|
||||
raise ValueError(f"Fused Q/K/V must share the same Smooth tensor: {lookup_name}")
|
||||
if previous_scale is None:
|
||||
qkv_smooth_scales[lookup_name] = loaded_weight.clone()
|
||||
weight_loader = param.weight_loader
|
||||
weight_loader(param, loaded_weight, shard_id)
|
||||
loaded_params.add(original_name)
|
||||
if getattr(param, "output_dim", None) is None and not getattr(param, "needs_scalar_to_array", False):
|
||||
# Shared input-channel Smooth is a complete tensor even
|
||||
# when supplied under a single Q/K/V source name.
|
||||
loaded_params.add(lookup_name)
|
||||
else:
|
||||
shards = loaded_qkv_shards.setdefault(lookup_name, set())
|
||||
shards.add(shard_id)
|
||||
if shards == {"q", "k", "v"}:
|
||||
loaded_params.add(lookup_name)
|
||||
break
|
||||
else:
|
||||
# diffusers: ffn.net.0.proj.weight -> our: ffn.net_0.proj.weight
|
||||
@@ -1198,6 +1293,7 @@ class WanTransformer3DModel(nn.Module):
|
||||
if is_pp_missing_parameter(lookup_name, self):
|
||||
continue
|
||||
|
||||
reject_dualscale_tensor(lookup_name)
|
||||
if lookup_name not in params_dict:
|
||||
logger.warning(f"Skipping weight {original_name} -> {lookup_name}")
|
||||
continue
|
||||
@@ -1222,8 +1318,6 @@ class WanTransformer3DModel(nn.Module):
|
||||
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, loaded_weight)
|
||||
|
||||
loaded_params.add(original_name)
|
||||
loaded_params.add(lookup_name)
|
||||
loaded_params.update((original_name, lookup_name))
|
||||
|
||||
return loaded_params
|
||||
@@ -61,11 +61,12 @@ from vllm_omni.engine.stage_client import StageClient
|
||||
from vllm_omni.engine.stage_init_utils import build_stage0_input_processor
|
||||
from vllm_omni.engine.stage_pool import StagePool
|
||||
from vllm_omni.engine.stage_runtime import (
|
||||
OmniClientConfig,
|
||||
StageRuntimeInfo,
|
||||
create_stage_runtime,
|
||||
)
|
||||
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
|
||||
from vllm_omni.entrypoints.utils import parse_stage_overrides
|
||||
from vllm_omni.entrypoints.utils import prepare_stage_config_inputs
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
from vllm_omni.metrics.prometheus import OmniRequestCounter
|
||||
|
||||
@@ -122,6 +123,7 @@ class OmniEngineBase:
|
||||
_transfer_emitter: Any = None
|
||||
_prom_metrics: Any = None
|
||||
_enable_orch_monitor: bool = False
|
||||
_client_config: OmniClientConfig | None = None
|
||||
# Lazily created by get_output_blocking_async().
|
||||
_output_drain_executor: concurrent.futures.ThreadPoolExecutor | None = None
|
||||
|
||||
@@ -136,6 +138,7 @@ class OmniEngineBase:
|
||||
log_stats: bool = False,
|
||||
tokenizer: str | None = None,
|
||||
trust_remote_code: bool | None = None,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
self.model = model
|
||||
@@ -155,6 +158,7 @@ class OmniEngineBase:
|
||||
# --log-stats CLI flag set by the user via OmniBase.
|
||||
self._log_stats = log_stats
|
||||
self._enable_orch_monitor = bool(kwargs.pop("enable_orch_monitor", False))
|
||||
self._client_config = client_config
|
||||
|
||||
logger.info(f"[OmniEngine] Initializing with model {model}")
|
||||
|
||||
@@ -166,6 +170,8 @@ class OmniEngineBase:
|
||||
_stage_id_kwarg = kwargs.get("stage_id")
|
||||
if isinstance(_stage_id_kwarg, int) and not single_stage_mode:
|
||||
single_stage_mode = True
|
||||
if client_config is not None and int(client_config.get("client_count", 1)) > 1 and single_stage_mode:
|
||||
raise ValueError("Multiple API servers cannot be combined with single-stage distributed mode")
|
||||
|
||||
self.single_stage_mode: bool = single_stage_mode
|
||||
self._single_stage_id_filter: int | None = (
|
||||
@@ -272,7 +278,14 @@ class OmniEngineBase:
|
||||
|
||||
self.num_stages = len(self.stage_configs)
|
||||
self.async_chunk = any(
|
||||
bool(getattr(getattr(stage, "engine_args", None), "async_chunk", False)) for stage in self.stage_configs
|
||||
bool(
|
||||
getattr(
|
||||
getattr(stage, "connector_config", None),
|
||||
"async_chunk",
|
||||
getattr(getattr(stage, "engine_args", None), "async_chunk", False),
|
||||
)
|
||||
)
|
||||
for stage in self.stage_configs
|
||||
)
|
||||
self.stage_pools: list[StagePool] = []
|
||||
self.stage_clients: list[StageClient] = [] # logical-stage view for external readers
|
||||
@@ -371,6 +384,7 @@ class OmniEngineBase:
|
||||
omni_lb_policy=self._omni_lb_policy,
|
||||
request_queue=self.request_queue,
|
||||
log_stats=self._log_stats,
|
||||
client_config=self._client_config,
|
||||
)
|
||||
self._runtime.initialize()
|
||||
|
||||
@@ -885,24 +899,15 @@ class OmniEngineBase:
|
||||
) -> tuple[str, list[Any]]:
|
||||
"""Resolve stage configs and inject defaults shared by orchestrator/headless."""
|
||||
|
||||
for legacy_arg in ("stage_configs_path", "stage_configs"):
|
||||
if legacy_arg in kwargs:
|
||||
raise ValueError(f"`{legacy_arg}` is no longer supported; use `deploy_config` instead.")
|
||||
|
||||
# log_stats is captured by __init__; its CLI-only negative alias must
|
||||
# not cross into per-stage structured config ownership validation.
|
||||
kwargs.pop("disable_log_stats", None)
|
||||
deploy_config_path = kwargs.pop("deploy_config", None)
|
||||
strategy_config_path = kwargs.pop("strategy_config", None)
|
||||
# CLI callers arrive pre-parsed; offline Python callers may use the
|
||||
# JSON-string form documented in recipes.
|
||||
stage_overrides = parse_stage_overrides(kwargs.pop("stage_overrides", None))
|
||||
|
||||
# ``diffusion_streaming_output`` is the public AsyncOmni/serve kwarg;
|
||||
# stage configs know the field as ``streaming_output``. Mirror only a
|
||||
# truthy value so the CLI's False default does not override deploy YAML.
|
||||
if kwargs.get("diffusion_streaming_output") and kwargs.get("streaming_output") is None:
|
||||
kwargs["streaming_output"] = True
|
||||
config_inputs = prepare_stage_config_inputs(
|
||||
model,
|
||||
kwargs,
|
||||
trust_remote_code=trust_remote_code,
|
||||
)
|
||||
kwargs = config_inputs.kwargs
|
||||
deploy_config_path = config_inputs.deploy_config_path
|
||||
strategy_config_path = config_inputs.strategy_config_path
|
||||
stage_overrides = config_inputs.stage_overrides
|
||||
|
||||
resolution = cast(
|
||||
_ConfigResolutionResult,
|
||||
|
||||
@@ -287,8 +287,13 @@ def check_admission(
|
||||
|
||||
|
||||
def _diffusion_utilization(replica: Any) -> float | None:
|
||||
"""Best-effort gpu_memory_utilization for a diffusion replica from raw args."""
|
||||
"""Resolve a diffusion replica's memory budget from typed or legacy config."""
|
||||
stage_cfg = getattr(replica, "stage_cfg", None)
|
||||
cache_config = getattr(stage_cfg, "cache_config", None)
|
||||
util = getattr(cache_config, "gpu_memory_utilization", None)
|
||||
if util is not None:
|
||||
return float(util)
|
||||
|
||||
engine_args = getattr(stage_cfg, "engine_args", None)
|
||||
if isinstance(engine_args, dict):
|
||||
util = engine_args.get("gpu_memory_utilization")
|
||||
|
||||
@@ -13,10 +13,12 @@ import threading
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from multiprocessing import connection
|
||||
from multiprocessing.process import BaseProcess
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import msgspec
|
||||
import torch
|
||||
import zmq
|
||||
from omegaconf import OmegaConf
|
||||
from vllm.config import VllmConfig
|
||||
@@ -33,6 +35,7 @@ from vllm.v1.engine.utils import (
|
||||
)
|
||||
from vllm.v1.executor import Executor
|
||||
|
||||
from vllm_omni.config.omni_config import BaseVllmOmniStageConfig
|
||||
from vllm_omni.distributed.omni_connectors.utils import initialization
|
||||
from vllm_omni.engine import stage_init_utils
|
||||
from vllm_omni.engine.stage_init_utils import (
|
||||
@@ -67,11 +70,13 @@ def _serialize_stage_config(stage_config: Any) -> Any:
|
||||
"""Convert a stage config to msgpack-friendly builtins."""
|
||||
if stage_config is None or isinstance(stage_config, (str, bytes, int, float, bool)):
|
||||
return stage_config
|
||||
if isinstance(stage_config, torch.dtype):
|
||||
return str(stage_config).removeprefix("torch.")
|
||||
|
||||
if OmegaConf.is_config(stage_config):
|
||||
return _serialize_stage_config(OmegaConf.to_container(stage_config, resolve=True))
|
||||
|
||||
if dataclasses.is_dataclass(stage_config):
|
||||
if dataclasses.is_dataclass(stage_config) and not isinstance(stage_config, type):
|
||||
return _serialize_stage_config(dataclasses.asdict(stage_config))
|
||||
|
||||
if isinstance(stage_config, dict):
|
||||
@@ -1134,6 +1139,8 @@ def launch_stage_replica(
|
||||
stage_visible_devices: str | None = None,
|
||||
spawn_device_lock: threading.Lock | None = None,
|
||||
omni_parallel_stage_init: bool = False,
|
||||
num_api_servers: int = 1,
|
||||
watched_frontend_processes: list[BaseProcess] | None = None,
|
||||
) -> Iterator[StageReplicaResources]:
|
||||
"""Launch a local LLM stage replica.
|
||||
|
||||
@@ -1144,6 +1151,8 @@ def launch_stage_replica(
|
||||
keep the same returned resource bundle.
|
||||
"""
|
||||
if omni_master_server is not None:
|
||||
if num_api_servers != 1:
|
||||
raise ValueError("Multiple API servers are not supported with distributed stage launch")
|
||||
with _launch_omni_core_engines(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=executor_class,
|
||||
@@ -1169,7 +1178,16 @@ def launch_stage_replica(
|
||||
|
||||
from vllm_omni.engine.stage_engine_core_proc_manager import StageEngineCoreProcManager
|
||||
|
||||
addresses = get_engine_zmq_addresses(vllm_config)
|
||||
if num_api_servers > 1:
|
||||
# Multi-API Omni is intentionally local-only. IPC paths avoid the
|
||||
# bind-after-allocation race of tcp://host:0 and are stable for every
|
||||
# stage, including stages that are not used by APIServerProcessManager.
|
||||
addresses = EngineZmqAddresses(
|
||||
inputs=[get_open_zmq_ipc_path() for _ in range(num_api_servers)],
|
||||
outputs=[get_open_zmq_ipc_path() for _ in range(num_api_servers)],
|
||||
)
|
||||
else:
|
||||
addresses = get_engine_zmq_addresses(vllm_config)
|
||||
handshake_address = get_open_zmq_ipc_path()
|
||||
engines_to_handshake = [CoreEngine(index=0, local=True)]
|
||||
with scoped_spawn_device_env(stage_visible_devices, spawn_device_lock, stage_id=stage_id, replica_id=replica_id):
|
||||
@@ -1193,18 +1211,21 @@ def launch_stage_replica(
|
||||
manager=engine_manager,
|
||||
addresses=addresses,
|
||||
)
|
||||
engine_launch = CoreEngineLaunch(
|
||||
engine_manager=engine_manager,
|
||||
coordinator=None,
|
||||
addresses=addresses,
|
||||
tensor_queue=None,
|
||||
)
|
||||
if watched_frontend_processes is not None:
|
||||
engine_launch.watched_frontend_processes = watched_frontend_processes
|
||||
wait_for_engine_startup(
|
||||
handshake_socket,
|
||||
engines_to_handshake,
|
||||
vllm_config.parallel_config,
|
||||
False, # coordinated_dp
|
||||
vllm_config.cache_config,
|
||||
CoreEngineLaunch(
|
||||
engine_manager=engine_manager,
|
||||
coordinator=None,
|
||||
addresses=addresses,
|
||||
tensor_queue=None,
|
||||
),
|
||||
engine_launch,
|
||||
)
|
||||
|
||||
|
||||
@@ -1403,7 +1424,7 @@ def get_headless_replica_devices(
|
||||
omni_dp_size_local: int,
|
||||
) -> list[str | None]:
|
||||
"""Return per-replica device slices for a headless stage."""
|
||||
runtime_cfg = getattr(stage_cfg, "runtime", None)
|
||||
runtime_cfg = getattr(stage_cfg, "runtime_config", getattr(stage_cfg, "runtime", None))
|
||||
devices_str: str | None = None
|
||||
if runtime_cfg is not None:
|
||||
devices_str = (
|
||||
@@ -1509,10 +1530,11 @@ def launch_headless_diffusion_replicas(
|
||||
stage_id,
|
||||
)
|
||||
|
||||
# Headless diffusion startup and its downstream helpers still consume the
|
||||
# legacy StageConfig shape; switch this with the coordinated RFC #4021
|
||||
# stage-init cutover.
|
||||
metadata = stage_init_utils.extract_legacy_stage_metadata(stage_cfg)
|
||||
metadata = (
|
||||
stage_init_utils.extract_stage_metadata_from_omni_stage_config(stage_cfg)
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig)
|
||||
else stage_init_utils.extract_legacy_stage_metadata(stage_cfg)
|
||||
)
|
||||
if omni_conn_cfg:
|
||||
inject_omni_kv_config(stage_cfg, omni_conn_cfg, omni_from, omni_to)
|
||||
# Headless single-stage launch must still infer cross-stage TP topology
|
||||
|
||||
@@ -402,6 +402,11 @@ def _tp_size_for_stage(stage_configs: Sequence[Any], stage_id: Any) -> int | Non
|
||||
for stage_cfg in stage_configs:
|
||||
if str(getattr(stage_cfg, "stage_id", None)) not in id_strs:
|
||||
continue
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig):
|
||||
try:
|
||||
return max(1, int(stage_cfg.parallel_config.tensor_parallel_size))
|
||||
except (TypeError, ValueError):
|
||||
return 1
|
||||
engine_args = getattr(stage_cfg, "engine_args", None)
|
||||
if engine_args is None:
|
||||
return 1
|
||||
@@ -489,11 +494,15 @@ def inject_kv_stage_info(stage_cfg: Any, stage_id: int, stage_configs: Sequence[
|
||||
rank mappings automatically.
|
||||
"""
|
||||
try:
|
||||
engine_args = stage_cfg.engine_args
|
||||
if hasattr(engine_args, "get"):
|
||||
omni_kv = engine_args.get("omni_kv_config", None)
|
||||
connector_config = getattr(stage_cfg, "connector_config", None)
|
||||
if connector_config is not None:
|
||||
omni_kv = connector_config.omni_kv_config
|
||||
else:
|
||||
omni_kv = getattr(engine_args, "omni_kv_config", None)
|
||||
engine_args = stage_cfg.engine_args
|
||||
if hasattr(engine_args, "get"):
|
||||
omni_kv = engine_args.get("omni_kv_config", None)
|
||||
else:
|
||||
omni_kv = getattr(engine_args, "omni_kv_config", None)
|
||||
|
||||
if omni_kv is None:
|
||||
return
|
||||
@@ -504,7 +513,11 @@ def inject_kv_stage_info(stage_cfg: Any, stage_id: int, stage_configs: Sequence[
|
||||
if "stage_id" not in omni_kv:
|
||||
omni_kv["stage_id"] = stage_id
|
||||
|
||||
engine_input_source = getattr(stage_cfg, "engine_input_source", None)
|
||||
engine_input_source = (
|
||||
getattr(stage_cfg, "input_sources", None)
|
||||
if connector_config is not None
|
||||
else getattr(stage_cfg, "engine_input_source", None)
|
||||
)
|
||||
if engine_input_source is not None:
|
||||
if hasattr(omni_kv, "setdefault"):
|
||||
omni_kv.setdefault("engine_input_source", list(engine_input_source))
|
||||
@@ -703,17 +716,16 @@ def _resolve_omni_metadata_hook(path: str | None) -> Callable | None:
|
||||
def extract_stage_metadata_from_omni_stage_config(
|
||||
stage_config: BaseVllmOmniStageConfig,
|
||||
) -> StageMetadata:
|
||||
"""Project one typed stage config into metadata for a future cutover.
|
||||
|
||||
This projection is not used by production startup yet. Current replica
|
||||
layout, engine-argument, remote-diffusion, and platform setup paths still
|
||||
require the legacy StageConfig/OmegaConf shape.
|
||||
"""
|
||||
"""Project one typed stage config into production runtime metadata."""
|
||||
stage_type: Literal["llm", "diffusion"] = "diffusion" if stage_config.stage_type == StageType.DIFFUSION else "llm"
|
||||
sampling_params_cls = SamplingParams if stage_type == "llm" else OmniDiffusionSamplingParams
|
||||
sampling_params: OmniSamplingParams = sampling_params_cls(
|
||||
**(stage_config.model_config.default_sampling_params or {})
|
||||
)
|
||||
pooling_config = stage_config.pooling_config
|
||||
if stage_type == "llm" and (pooling_config.runner or "").lower() == "pooling":
|
||||
sampling_params: OmniSamplingParams | PoolingParams = (
|
||||
copy.deepcopy(pooling_config.default_pooling_params) or PoolingParams()
|
||||
)
|
||||
else:
|
||||
sampling_params_cls = SamplingParams if stage_type == "llm" else OmniDiffusionSamplingParams
|
||||
sampling_params = sampling_params_cls(**(stage_config.model_config.default_sampling_params or {}))
|
||||
custom_process_input_func = _resolve_omni_metadata_hook(stage_config.custom_process_input_func)
|
||||
|
||||
if stage_type == "diffusion":
|
||||
@@ -878,7 +890,9 @@ def _get_local_llm_parallel_sizes(
|
||||
unset.
|
||||
"""
|
||||
if engine_args is None:
|
||||
engine_args = getattr(stage_cfg, "engine_args", {})
|
||||
engine_args = getattr(stage_cfg, "parallel_config", None)
|
||||
if engine_args is None:
|
||||
engine_args = getattr(stage_cfg, "engine_args", {})
|
||||
tp_size = int(_get_attr_or_item(engine_args, "tensor_parallel_size", 1) or 1)
|
||||
pp_size = int(_get_attr_or_item(engine_args, "pipeline_parallel_size", 1) or 1)
|
||||
local_dp_size = _get_attr_or_item(engine_args, "data_parallel_size_local", None)
|
||||
@@ -889,9 +903,12 @@ def _get_local_llm_parallel_sizes(
|
||||
|
||||
def get_stage_devices_per_replica(stage_cfg: Any, engine_args: Any | None = None) -> int:
|
||||
"""Return the number of devices consumed by one replica of *stage_cfg*."""
|
||||
if engine_args is None:
|
||||
engine_args = getattr(stage_cfg, "engine_args", {})
|
||||
if getattr(stage_cfg, "stage_type", "llm") == "diffusion":
|
||||
typed_parallel_config = getattr(stage_cfg, "parallel_config", None)
|
||||
if typed_parallel_config is not None:
|
||||
return max(1, int(typed_parallel_config.world_size))
|
||||
if engine_args is None:
|
||||
engine_args = getattr(stage_cfg, "engine_args", {})
|
||||
parallel_config = _get_attr_or_item(engine_args, "parallel_config")
|
||||
if parallel_config is None:
|
||||
return 1
|
||||
@@ -933,7 +950,7 @@ def compute_replica_layout(
|
||||
"""
|
||||
replicas_per_stage: list[int] = []
|
||||
for stage_cfg in stage_configs:
|
||||
runtime_cfg = getattr(stage_cfg, "runtime", {})
|
||||
runtime_cfg = getattr(stage_cfg, "runtime_config", getattr(stage_cfg, "runtime", {}))
|
||||
num_replicas = int(
|
||||
runtime_cfg.get("num_replicas", 1)
|
||||
if hasattr(runtime_cfg, "get")
|
||||
@@ -948,7 +965,7 @@ def compute_replica_layout(
|
||||
num_replicas = replicas_per_stage[stage_id]
|
||||
if num_replicas <= 1:
|
||||
continue
|
||||
runtime_cfg = getattr(stage_cfg, "runtime", {})
|
||||
runtime_cfg = getattr(stage_cfg, "runtime_config", getattr(stage_cfg, "runtime", {}))
|
||||
devices_str = (
|
||||
runtime_cfg.get("devices") if hasattr(runtime_cfg, "get") else getattr(runtime_cfg, "devices", None)
|
||||
)
|
||||
@@ -1086,15 +1103,31 @@ def _project_omni_stage_engine_args(
|
||||
diffusion_stage = cast(VllmOmniDiffusionStageConfig, stage_config)
|
||||
engine_args.update(_project_omni_config_fields(diffusion_stage.diffusion_config))
|
||||
|
||||
model_excluded_fields = {
|
||||
"default_sampling_params",
|
||||
"has_sampling_extra_args",
|
||||
}
|
||||
runtime_excluded_fields = {"devices", "num_replicas", "env", "num_gpus"}
|
||||
if not is_diffusion:
|
||||
# These values configure OmniDiffusionConfig or its worker process;
|
||||
# OmniEngineArgs has no matching fields for LLM stages.
|
||||
model_excluded_fields.update(
|
||||
{
|
||||
"disable_autocast",
|
||||
"enable_multithread_weight_load",
|
||||
"num_weight_load_threads",
|
||||
}
|
||||
)
|
||||
runtime_excluded_fields.add("log_level")
|
||||
|
||||
for config, excluded_fields in (
|
||||
(
|
||||
stage_config.model_config,
|
||||
frozenset({"default_sampling_params", "has_sampling_extra_args"}),
|
||||
frozenset(model_excluded_fields),
|
||||
),
|
||||
(
|
||||
stage_config.runtime_config,
|
||||
frozenset({"devices", "num_replicas", "env", "num_gpus"})
|
||||
| (frozenset({"additional_config"}) if is_diffusion else frozenset()),
|
||||
frozenset(runtime_excluded_fields) | (frozenset({"additional_config"}) if is_diffusion else frozenset()),
|
||||
),
|
||||
):
|
||||
engine_args.update(
|
||||
@@ -1103,6 +1136,11 @@ def _project_omni_stage_engine_args(
|
||||
exclude=excluded_fields,
|
||||
)
|
||||
)
|
||||
pooling_config = stage_config.pooling_config
|
||||
if pooling_config.runner is not None:
|
||||
engine_args["runner"] = pooling_config.runner
|
||||
if pooling_config.pooling_output_decoder is not None:
|
||||
engine_args["pooling_output_decoder"] = pooling_config.pooling_output_decoder
|
||||
|
||||
if is_diffusion:
|
||||
for config, field_map in (
|
||||
@@ -1330,11 +1368,9 @@ def build_engine_args_dict(
|
||||
stage_connector_spec: dict[str, Any] | None = None,
|
||||
cli_tokenizer: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build engine arguments through the stable production entry point.
|
||||
"""Preserve the legacy engine-argument API for compatibility callers.
|
||||
|
||||
Production inputs still use the legacy stage representation. Keep that
|
||||
compatibility choice behind this function so callers do not bind directly
|
||||
to a representation-specific implementation.
|
||||
Typed runtime stages use ``build_engine_args_dict_from_omni_stage_config``.
|
||||
"""
|
||||
return build_legacy_engine_args_dict(
|
||||
stage_config,
|
||||
@@ -1350,13 +1386,7 @@ def build_engine_args_dict_from_omni_stage_config(
|
||||
stage_connector_spec: dict[str, Any] | None = None,
|
||||
cli_tokenizer: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Project one typed stage config into backend engine arguments.
|
||||
|
||||
This projection is prepared for the RFC #4021 stage-init cutover. Current
|
||||
production startup reaches the legacy implementation through
|
||||
``build_engine_args_dict`` while strategy and startup-plan inputs still
|
||||
use the legacy representation.
|
||||
"""
|
||||
"""Project one typed production stage config into backend engine arguments."""
|
||||
engine_args_dict = _project_omni_stage_engine_args(stage_config)
|
||||
_apply_rocm_attention_backend(engine_args_dict, stage_config.stage_type)
|
||||
return _finalize_engine_args_dict(
|
||||
@@ -1391,7 +1421,7 @@ def _check_stage_device_layout(stage_config: Any, engine_args_dict: dict[str, An
|
||||
"""
|
||||
from vllm_omni.config.composable_parallel import StrategyApplyError, check_device_layout
|
||||
|
||||
runtime = getattr(stage_config, "runtime", None)
|
||||
runtime = getattr(stage_config, "runtime_config", getattr(stage_config, "runtime", None))
|
||||
devices = _get_attr_or_item(runtime, "devices", None) if runtime is not None else None
|
||||
if devices is None:
|
||||
# No explicit placement -> vLLM assigns devices itself; nothing to check.
|
||||
@@ -1445,6 +1475,8 @@ def build_vllm_config(
|
||||
stage_connector_spec: dict[str, Any] | None = None,
|
||||
engine_args_dict: dict[str, Any] | None = None,
|
||||
headless: bool = False,
|
||||
api_process_count: int = 1,
|
||||
api_process_rank: int = 0,
|
||||
) -> tuple[Any, type]:
|
||||
"""Build engine args, then create VllmConfig and executor_class.
|
||||
|
||||
@@ -1452,13 +1484,18 @@ def build_vllm_config(
|
||||
(vllm_config, executor_class)
|
||||
"""
|
||||
if engine_args_dict is None:
|
||||
engine_args_dict = build_engine_args_dict(
|
||||
stage_config,
|
||||
model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
engine_args_dict = (
|
||||
build_engine_args_dict_from_omni_stage_config(
|
||||
stage_config, model, stage_connector_spec=stage_connector_spec
|
||||
)
|
||||
if isinstance(stage_config, BaseVllmOmniStageConfig)
|
||||
else build_engine_args_dict(stage_config, model, stage_connector_spec=stage_connector_spec)
|
||||
)
|
||||
|
||||
filtered_engine_args_dict = filter_dataclass_kwargs(OmniEngineArgs, engine_args_dict)
|
||||
if api_process_count != 1 or api_process_rank != 0:
|
||||
filtered_engine_args_dict["_api_process_count"] = api_process_count
|
||||
filtered_engine_args_dict["_api_process_rank"] = api_process_rank
|
||||
|
||||
# _to_dict serializes dataclass fields (e.g. StructuredOutputsConfig) into
|
||||
# plain dicts. When OmniEngineArgs is instantiated with the dict, these
|
||||
@@ -1715,6 +1752,7 @@ def acquire_device_locks(
|
||||
stage_id: int,
|
||||
engine_args_dict: dict[str, Any],
|
||||
stage_init_timeout: int,
|
||||
locked_devices: set[int] | None = None,
|
||||
) -> list[int]:
|
||||
"""Acquire exclusive file locks on devices needed by this stage.
|
||||
|
||||
@@ -1769,8 +1807,7 @@ def acquire_device_locks(
|
||||
f"but only {len(physical_devices)} device(s) are available: {physical_devices}"
|
||||
)
|
||||
|
||||
num_devices_to_lock = num_devices_per_stage
|
||||
devices_to_lock = sorted(physical_devices[:num_devices_to_lock])
|
||||
devices_to_lock = sorted(set(physical_devices[:num_devices_per_stage]) - (locked_devices or set()))
|
||||
|
||||
logger.debug(
|
||||
"Parallel config: TP=%d, PP=%d, DP=%d, PCP=%d, SP=%d, CFG=%d; will lock %d devices: %s",
|
||||
@@ -1780,7 +1817,7 @@ def acquire_device_locks(
|
||||
prefill_context_parallel_size,
|
||||
sequence_parallel_size,
|
||||
cfg_parallel_size,
|
||||
num_devices_to_lock,
|
||||
len(devices_to_lock),
|
||||
devices_to_lock,
|
||||
)
|
||||
|
||||
@@ -1798,6 +1835,8 @@ def acquire_device_locks(
|
||||
record_lock_holder_pid(lock_fd, lock_writable)
|
||||
lock_acquired = True
|
||||
lock_fds.append(lock_fd)
|
||||
if locked_devices is not None:
|
||||
locked_devices.add(device_id)
|
||||
logger.debug("Acquired exclusive lock for device %s", device_id)
|
||||
except BlockingIOError:
|
||||
os.close(lock_fd)
|
||||
@@ -1927,7 +1966,11 @@ def build_diffusion_config(
|
||||
) -> Any:
|
||||
"""Build diffusion config for a stage."""
|
||||
|
||||
engine_args_dict = build_engine_args_dict(stage_cfg, model)
|
||||
engine_args_dict = (
|
||||
build_engine_args_dict_from_omni_stage_config(stage_cfg, model)
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig)
|
||||
else build_engine_args_dict(stage_cfg, model)
|
||||
)
|
||||
od_config = OmniDiffusionConfig.from_kwargs(**engine_args_dict)
|
||||
|
||||
num_devices_per_stage = od_config.parallel_config.world_size
|
||||
|
||||
+371
-151
@@ -6,19 +6,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import contextlib
|
||||
import copy
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable, Iterator, Mapping, Sequence
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, cast
|
||||
from contextlib import AbstractContextManager, contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from multiprocessing.process import BaseProcess
|
||||
from typing import Any, TypedDict, cast
|
||||
|
||||
import janus
|
||||
from omegaconf import OmegaConf
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.config.omni_config import BaseVllmOmniStageConfig
|
||||
from vllm_omni.distributed.omni_connectors.utils.initialization import (
|
||||
resolve_omni_kv_config_for_stage,
|
||||
)
|
||||
@@ -49,11 +50,13 @@ from vllm_omni.engine.stage_init_utils import (
|
||||
_inject_inferred_kv_tp_topology,
|
||||
acquire_device_locks,
|
||||
build_engine_args_dict,
|
||||
build_engine_args_dict_from_omni_stage_config,
|
||||
build_llm_stage_output_processor,
|
||||
build_vllm_config,
|
||||
compute_replica_layout,
|
||||
device_overlap_group_keys,
|
||||
extract_legacy_stage_metadata,
|
||||
extract_stage_metadata_from_omni_stage_config,
|
||||
get_stage_connector_spec,
|
||||
inject_kv_stage_info,
|
||||
inject_omni_kv_connector_config,
|
||||
@@ -92,6 +95,44 @@ class StageRemoteFactoryContext:
|
||||
executor_class: type | None = None
|
||||
|
||||
|
||||
class OmniClientConfig(TypedDict, total=False):
|
||||
"""Per-frontend transport/configuration passed across process boundaries."""
|
||||
|
||||
client_count: int
|
||||
client_index: int
|
||||
stage_addresses: dict[int | str, dict[int | str, dict[str, Any]]]
|
||||
input_address: str
|
||||
output_address: str
|
||||
stats_update_address: str
|
||||
actual_address_pipe: Any
|
||||
tensor_queue: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class StageEngineLaunch:
|
||||
"""Engine resources handed to a local client or the serving parent.
|
||||
|
||||
Successful launch transfers resource ownership to the caller. Startup or
|
||||
attachment failures are rolled back by ``launch_stage_engines``.
|
||||
"""
|
||||
|
||||
client_configs: list[OmniClientConfig]
|
||||
resources: list[StageReplicaResources]
|
||||
watched_frontend_processes: list[BaseProcess] = field(default_factory=list)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
seen: set[int] = set()
|
||||
for stage_resources in reversed(self.resources):
|
||||
for resource in (stage_resources.manager, stage_resources.coordinator):
|
||||
if resource is None or id(resource) in seen:
|
||||
continue
|
||||
seen.add(id(resource))
|
||||
try:
|
||||
resource.shutdown()
|
||||
except Exception:
|
||||
logger.warning("[StageEngineLaunch] resource shutdown failed", exc_info=True)
|
||||
|
||||
|
||||
def _build_load_balancer_factory(policy: str) -> Callable[[], LoadBalancer]:
|
||||
try:
|
||||
normalized = LoadBalancingPolicy(policy)
|
||||
@@ -123,13 +164,14 @@ class StageRuntime:
|
||||
self,
|
||||
stage_configs: list[Any],
|
||||
model: str,
|
||||
config_path: str,
|
||||
config_path: str | None,
|
||||
*,
|
||||
stage_init_timeout: int,
|
||||
async_chunk: bool,
|
||||
tokenizer: str | None = None,
|
||||
parallel_stage_init: bool = False,
|
||||
log_stats: bool = False,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
) -> None:
|
||||
self._stage_configs = stage_configs
|
||||
self._model = model
|
||||
@@ -144,6 +186,14 @@ class StageRuntime:
|
||||
self._parallel_stage_init = parallel_stage_init
|
||||
self._log_stats = log_stats
|
||||
self._num_stages = len(stage_configs)
|
||||
self._client_count = int((client_config or {}).get("client_count", 1))
|
||||
self._client_index = int((client_config or {}).get("client_index", 0))
|
||||
if self._client_count < 1:
|
||||
raise ValueError(f"client_count must be >= 1, got {self._client_count}")
|
||||
if self._client_index != -1 and not 0 <= self._client_index < self._client_count:
|
||||
raise ValueError(f"client_index must be in [0, {self._client_count}), got {self._client_index}")
|
||||
self._external_stage_addresses = (client_config or {}).get("stage_addresses")
|
||||
self._api_process_rank = self._client_index
|
||||
|
||||
# Populated by initialize()
|
||||
self.stage_pools: list[StagePool] = []
|
||||
@@ -262,6 +312,205 @@ class StageRuntime:
|
||||
self._cleanup_after_initialize_failure()
|
||||
raise exc
|
||||
|
||||
@contextmanager
|
||||
def launch_stage_engines(
|
||||
self,
|
||||
num_api_servers: int = 1,
|
||||
*,
|
||||
stage_plans: Sequence[LogicalStageInitPlan] | None = None,
|
||||
stage_init_timeout: int | None = None,
|
||||
) -> Iterator[StageEngineLaunch]:
|
||||
"""Launch EngineCore stages for local or subprocess client attachment.
|
||||
|
||||
The regular runtime supplies a replica plan from its device-group
|
||||
scheduler; the serving parent resolves the whole pipeline here. Both
|
||||
use the same device locks, spawn, readiness and rollback machinery.
|
||||
One client completes readiness before attachment, preserving the
|
||||
existing in-process frontend. Multiple clients attach in the caller's
|
||||
``with`` body before readiness completes on context exit.
|
||||
"""
|
||||
if self._external_stage_addresses is not None:
|
||||
raise ValueError("A runtime attached to external stage engines cannot launch engines")
|
||||
if num_api_servers < 1:
|
||||
raise ValueError(f"num_api_servers must be >= 1, got {num_api_servers}")
|
||||
timeout = self._stage_init_timeout if stage_init_timeout is None else stage_init_timeout
|
||||
resolve_plans = stage_plans is None
|
||||
if stage_plans is None:
|
||||
self._client_count = num_api_servers
|
||||
self._api_process_rank = -1 if num_api_servers > 1 else self._client_index
|
||||
self._init_visible_devices_baseline = os.environ.get(current_omni_platform.device_control_env_var)
|
||||
stage_plans = self._prepare_stage_plans()
|
||||
|
||||
unsupported = [
|
||||
plan.stage_id
|
||||
for plan in stage_plans
|
||||
if any(replica.metadata.stage_type == "diffusion" for replica in plan.replicas)
|
||||
]
|
||||
if unsupported:
|
||||
raise ValueError(
|
||||
"--api-server-count currently supports EngineCore stages only; "
|
||||
f"diffusion stage(s) are not supported: {unsupported}"
|
||||
)
|
||||
if any(replica.launch_mode != "local" for plan in stage_plans for replica in plan.replicas):
|
||||
raise ValueError("--api-server-count is not supported with remote or headless stages")
|
||||
|
||||
if num_api_servers > 1:
|
||||
parallel_configs: list[Any] = []
|
||||
for plan in stage_plans:
|
||||
for replica in plan.replicas:
|
||||
if replica.stage_vllm_config is None or replica.executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} is missing its engine configuration")
|
||||
parallel_configs.append(replica.stage_vllm_config.parallel_config)
|
||||
if any(getattr(parallel_config, "enable_fault_tolerance", False) for parallel_config in parallel_configs):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-fault-tolerance")
|
||||
if any(getattr(parallel_config, "enable_elastic_ep", False) for parallel_config in parallel_configs):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-elastic-ep")
|
||||
if any(
|
||||
getattr(parallel_config, "data_parallel_size", 1) != 1 or getattr(parallel_config, "use_ray", False)
|
||||
for parallel_config in parallel_configs
|
||||
):
|
||||
raise ValueError(
|
||||
"--api-server-count > 1 currently supports one local process group per replica; "
|
||||
"intra-replica data parallelism and Ray backends are not supported"
|
||||
)
|
||||
|
||||
if resolve_plans and self._parallel_stage_init:
|
||||
self._reject_unguardable_executors(stage_plans)
|
||||
self._run_stage_admission(stage_plans)
|
||||
|
||||
client_configs: list[OmniClientConfig] = [
|
||||
OmniClientConfig(
|
||||
client_count=num_api_servers,
|
||||
client_index=client_index,
|
||||
stage_addresses={},
|
||||
)
|
||||
for client_index in range(num_api_servers)
|
||||
]
|
||||
entered_contexts: list[AbstractContextManager[StageReplicaResources]] = []
|
||||
resources: list[StageReplicaResources] = []
|
||||
watched_frontend_processes: list[BaseProcess] = []
|
||||
# launch_stage_replica performs its readiness handshake in __exit__,
|
||||
# after API workers are started, so initialization locks must remain
|
||||
# held until all launch contexts have exited.
|
||||
lock_fds: list[int] = []
|
||||
locked_devices: set[int] = set()
|
||||
launch: StageEngineLaunch | None = None
|
||||
exited_contexts = 0
|
||||
|
||||
try:
|
||||
for plan in stage_plans:
|
||||
for replica in plan.replicas:
|
||||
if replica.stage_vllm_config is None or replica.executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} is missing its engine configuration")
|
||||
if replica.engine_args_dict is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} is missing engine args")
|
||||
|
||||
physical_devices = self._resolve_replica_physical_devices(
|
||||
replica.metadata.stage_id,
|
||||
replica.metadata.runtime_cfg,
|
||||
)
|
||||
if not self._parallel_stage_init:
|
||||
with self._scoped_spawn_device_env(physical_devices):
|
||||
lock_fds.extend(
|
||||
acquire_device_locks(
|
||||
replica.metadata.stage_id,
|
||||
replica.engine_args_dict,
|
||||
timeout,
|
||||
locked_devices,
|
||||
)
|
||||
)
|
||||
|
||||
launch_context = launch_stage_replica(
|
||||
vllm_config=replica.stage_vllm_config,
|
||||
executor_class=replica.executor_class,
|
||||
log_stats=self._log_stats,
|
||||
stage_id=replica.metadata.stage_id,
|
||||
replica_id=replica.replica_id,
|
||||
stage_config=replica.stage_cfg,
|
||||
omni_master_server=self._get_omni_master_server(),
|
||||
omni_coordinator_address=self._get_coordinator_address(),
|
||||
stage_visible_devices=physical_devices,
|
||||
spawn_device_lock=self._spawn_device_lock,
|
||||
omni_parallel_stage_init=self._parallel_stage_init,
|
||||
num_api_servers=num_api_servers,
|
||||
watched_frontend_processes=watched_frontend_processes if num_api_servers > 1 else None,
|
||||
)
|
||||
# Environment overlays are process-global. Serialize spawn;
|
||||
# parallel initialization waits for READY outside this lock.
|
||||
with self._replica_launch_lock:
|
||||
with stage_runtime_env(replica.metadata.stage_id, replica.metadata.runtime_cfg):
|
||||
stage_resources = launch_context.__enter__()
|
||||
entered_contexts.append(launch_context)
|
||||
if stage_resources is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} launcher returned no resources")
|
||||
resources.append(stage_resources)
|
||||
if num_api_servers == 1:
|
||||
exited_contexts += 1
|
||||
launch_context.__exit__(None, None, None)
|
||||
addresses = stage_resources.addresses
|
||||
# The generic resource bundle allows no addresses (e.g.
|
||||
# diffusion), but EngineCore attachment requires them.
|
||||
if addresses is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} launcher returned no addresses")
|
||||
# Unlike the single-client handshake, only stage 0 is
|
||||
# handed to APIServerProcessManager for address updates.
|
||||
# Other stages must already expose connectable endpoints.
|
||||
if num_api_servers > 1 and any(
|
||||
address.startswith("tcp://") and address.rsplit(":", 1)[-1] == "0"
|
||||
for address in (*addresses.inputs, *addresses.outputs)
|
||||
):
|
||||
raise RuntimeError(
|
||||
f"Stage {plan.stage_id} returned deferred TCP addresses; "
|
||||
"multi-API launch requires fixed ports or IPC addresses"
|
||||
)
|
||||
if len(addresses.inputs) != num_api_servers or len(addresses.outputs) != num_api_servers:
|
||||
raise RuntimeError(
|
||||
f"Stage {plan.stage_id} returned {len(addresses.inputs)} input and "
|
||||
f"{len(addresses.outputs)} output addresses for {num_api_servers} API servers"
|
||||
)
|
||||
|
||||
if num_api_servers == 1 and lock_fds:
|
||||
release_device_locks(lock_fds)
|
||||
lock_fds.clear()
|
||||
locked_devices.clear()
|
||||
|
||||
for client_index, client_config in enumerate(client_configs):
|
||||
stage_addresses = client_config["stage_addresses"]
|
||||
replica_addresses = stage_addresses.setdefault(plan.stage_id, {})
|
||||
replica_addresses[replica.replica_id] = {
|
||||
"input_address": addresses.inputs[client_index],
|
||||
"output_address": addresses.outputs[client_index],
|
||||
}
|
||||
if addresses.frontend_stats_publish_address is not None:
|
||||
replica_addresses[replica.replica_id]["stats_update_address"] = (
|
||||
addresses.frontend_stats_publish_address
|
||||
)
|
||||
|
||||
launch = StageEngineLaunch(
|
||||
client_configs=client_configs,
|
||||
resources=resources,
|
||||
watched_frontend_processes=watched_frontend_processes,
|
||||
)
|
||||
yield launch
|
||||
|
||||
while exited_contexts < len(entered_contexts):
|
||||
entered_context = entered_contexts[exited_contexts]
|
||||
exited_contexts += 1
|
||||
entered_context.__exit__(None, None, None)
|
||||
except BaseException as exc:
|
||||
if launch is not None:
|
||||
launch.shutdown()
|
||||
else:
|
||||
StageEngineLaunch(client_configs=client_configs, resources=resources).shutdown()
|
||||
exc_info = (type(exc), exc, exc.__traceback__)
|
||||
for pending_context in reversed(entered_contexts[exited_contexts:]):
|
||||
with contextlib.suppress(BaseException):
|
||||
pending_context.__exit__(*exc_info)
|
||||
raise
|
||||
finally:
|
||||
if lock_fds:
|
||||
release_device_locks(lock_fds)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
for pool in self.stage_pools:
|
||||
for client in pool.clients:
|
||||
@@ -345,12 +594,12 @@ class StageRuntime:
|
||||
"""Build startup plans for every logical stage and replica."""
|
||||
stage_plans: list[LogicalStageInitPlan] = []
|
||||
|
||||
# RFC #4021 transition boundary: stage planning still relies on legacy
|
||||
# StageConfig.runtime and StageConfig.engine_args for replica and engine
|
||||
# setup. Keep metadata extraction on the legacy path until the
|
||||
# coordinated stage-init cutover.
|
||||
for stage_idx, stage_cfg in enumerate(self._stage_configs):
|
||||
base_metadata = extract_legacy_stage_metadata(stage_cfg)
|
||||
base_metadata = (
|
||||
extract_stage_metadata_from_omni_stage_config(stage_cfg)
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig)
|
||||
else extract_legacy_stage_metadata(stage_cfg)
|
||||
)
|
||||
stage_id = int(base_metadata.stage_id)
|
||||
if stage_id != stage_idx:
|
||||
raise ValueError(
|
||||
@@ -374,14 +623,20 @@ class StageRuntime:
|
||||
executor_class = None
|
||||
engine_args_dict = None
|
||||
if base_metadata.stage_type != "diffusion":
|
||||
# The stable adapter entry point still receives the same
|
||||
# legacy stage object as replica planning. Its implementation
|
||||
# switches only at the coordinated RFC #4021 cutover.
|
||||
engine_args_dict = build_engine_args_dict(
|
||||
stage_cfg,
|
||||
self._model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
cli_tokenizer=self._tokenizer,
|
||||
engine_args_dict = (
|
||||
build_engine_args_dict_from_omni_stage_config(
|
||||
stage_cfg,
|
||||
self._model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
cli_tokenizer=self._tokenizer,
|
||||
)
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig)
|
||||
else build_engine_args_dict(
|
||||
stage_cfg,
|
||||
self._model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
cli_tokenizer=self._tokenizer,
|
||||
)
|
||||
)
|
||||
inject_omni_kv_connector_config(
|
||||
engine_args_dict,
|
||||
@@ -398,14 +653,25 @@ class StageRuntime:
|
||||
self._model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
engine_args_dict=engine_args_dict,
|
||||
api_process_count=self._client_count,
|
||||
api_process_rank=self._api_process_rank,
|
||||
)
|
||||
|
||||
for replica_id in range(num_replicas):
|
||||
replica_cfg = copy.deepcopy(stage_cfg) if replica_id > 0 else stage_cfg
|
||||
# Keep the logical stage's device pool intact; each replica owns
|
||||
# the same config throughout planning, metadata and launch.
|
||||
replica_cfg = copy.deepcopy(stage_cfg) if num_replicas > 1 else stage_cfg
|
||||
if stage_idx in replica_devices_map:
|
||||
replica_cfg.runtime.devices = replica_devices_map[stage_idx][replica_id]
|
||||
devices = replica_devices_map[stage_idx][replica_id]
|
||||
runtime_cfg = getattr(replica_cfg, "runtime_config", getattr(replica_cfg, "runtime", None))
|
||||
if runtime_cfg is not None:
|
||||
runtime_cfg.devices = devices
|
||||
|
||||
replica_metadata = extract_legacy_stage_metadata(replica_cfg)
|
||||
replica_metadata = (
|
||||
extract_stage_metadata_from_omni_stage_config(replica_cfg)
|
||||
if isinstance(replica_cfg, BaseVllmOmniStageConfig)
|
||||
else extract_legacy_stage_metadata(replica_cfg)
|
||||
)
|
||||
replica_metadata.replica_id = replica_id
|
||||
if launch_mode == "remote" and replica_metadata.stage_type != "diffusion":
|
||||
replica_metadata.runtime_cfg = None
|
||||
@@ -720,122 +986,70 @@ class StageRuntime:
|
||||
stage_init_timeout: int,
|
||||
) -> StagePoolClient:
|
||||
"""Initialize one local LLM replica using vLLM's launch/attach pattern."""
|
||||
resources: StageReplicaResources | None = None
|
||||
stage_client = None
|
||||
lock_fds: list[int] = []
|
||||
try:
|
||||
physical_devices = self._resolve_replica_physical_devices(
|
||||
plan.metadata.stage_id,
|
||||
plan.metadata.runtime_cfg,
|
||||
)
|
||||
if physical_devices:
|
||||
logger.info(
|
||||
"[stage_init] Stage-%s set runtime devices: %s",
|
||||
plan.metadata.stage_id,
|
||||
physical_devices,
|
||||
)
|
||||
vllm_config = plan.stage_vllm_config
|
||||
executor_class = plan.executor_class
|
||||
if vllm_config is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing vllm_config")
|
||||
if executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing executor_class")
|
||||
if plan.engine_args_dict is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing engine args")
|
||||
# G3 device locks: in the default (serial) path the parent holds a
|
||||
# per-device LOCK_EX across the whole child init. When parallel stage
|
||||
# init is enabled the engine-core child takes phased SH/EX locks
|
||||
# itself (see stage_phase_lock), so the parent must NOT also hold the
|
||||
# lock here — it would self-deadlock while waiting for the child's
|
||||
# READY handshake.
|
||||
if not self._parallel_stage_init:
|
||||
g3_start = time.perf_counter()
|
||||
with self._scoped_spawn_device_env(physical_devices):
|
||||
lock_fds = acquire_device_locks(
|
||||
plan.metadata.stage_id,
|
||||
plan.engine_args_dict,
|
||||
stage_init_timeout,
|
||||
)
|
||||
logger.debug(
|
||||
"[stage_init] Stage-%s G3 device-lock acquire took %.3fs",
|
||||
plan.metadata.stage_id,
|
||||
time.perf_counter() - g3_start,
|
||||
)
|
||||
|
||||
launch_cm = launch_stage_replica(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=executor_class,
|
||||
log_stats=self._log_stats,
|
||||
stage_id=plan.metadata.stage_id,
|
||||
replica_id=plan.replica_id,
|
||||
stage_config=plan.stage_cfg,
|
||||
omni_master_server=self._get_omni_master_server(),
|
||||
omni_coordinator_address=self._get_coordinator_address(),
|
||||
stage_visible_devices=physical_devices,
|
||||
spawn_device_lock=self._spawn_device_lock,
|
||||
omni_parallel_stage_init=self._parallel_stage_init,
|
||||
)
|
||||
# Only process spawning and the runtime.env overlay need the global
|
||||
# launch lock. The launch context's exit waits for READY: holding the
|
||||
# lock there serializes model loading and compilation even across
|
||||
# different GPUs. Default initialization keeps its per-device EX
|
||||
# locks until READY; parallel_stage_init uses child phase locks.
|
||||
g2_start = time.perf_counter()
|
||||
with ExitStack() as launch_stack:
|
||||
with self._replica_launch_lock:
|
||||
g2_locked = time.perf_counter()
|
||||
with stage_runtime_env(plan.metadata.stage_id, plan.metadata.runtime_cfg):
|
||||
resources = launch_stack.enter_context(launch_cm)
|
||||
g2_spawned = time.perf_counter()
|
||||
logger.debug(
|
||||
"[stage_init] Stage-%s G2 launch-lock wait=%.3fs, spawn=%.3fs, READY=%.3fs",
|
||||
plan.metadata.stage_id,
|
||||
g2_locked - g2_start,
|
||||
g2_spawned - g2_locked,
|
||||
time.perf_counter() - g2_spawned,
|
||||
external_addresses = self._get_external_client_addresses(
|
||||
plan.metadata.stage_id,
|
||||
plan.replica_id,
|
||||
)
|
||||
if external_addresses is not None:
|
||||
if plan.stage_vllm_config is None or plan.executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing its engine configuration")
|
||||
return cast(
|
||||
StagePoolClient,
|
||||
StageEngineCoreClientBase.make_async_mp_client(
|
||||
vllm_config=plan.stage_vllm_config,
|
||||
executor_class=plan.executor_class,
|
||||
log_stats=self._log_stats,
|
||||
metadata=plan.metadata,
|
||||
client_addresses=external_addresses,
|
||||
client_count=self._client_count,
|
||||
client_index=self._client_index,
|
||||
),
|
||||
)
|
||||
|
||||
logger.info("[StageRuntime] Stage %s engine startup completed", plan.metadata.stage_id)
|
||||
if resources is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} launcher returned no resources")
|
||||
if resources.addresses is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} launcher returned no addresses")
|
||||
stage_client = StageEngineCoreClientBase.make_async_mp_client(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=executor_class,
|
||||
log_stats=self._log_stats,
|
||||
metadata=plan.metadata,
|
||||
client_addresses=self._client_addresses_from_zmq(resources.addresses),
|
||||
engine_manager=resources.manager,
|
||||
coordinator=resources.coordinator,
|
||||
if plan.stage_vllm_config is None or plan.executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing its engine configuration")
|
||||
stage_plan = LogicalStageInitPlan(
|
||||
stage_idx=plan.metadata.stage_id,
|
||||
stage_id=plan.metadata.stage_id,
|
||||
replicas=[plan],
|
||||
)
|
||||
with self.launch_stage_engines(
|
||||
stage_plans=[stage_plan],
|
||||
stage_init_timeout=stage_init_timeout,
|
||||
) as launch:
|
||||
resources = launch.resources[0]
|
||||
return cast(
|
||||
StagePoolClient,
|
||||
StageEngineCoreClientBase.make_async_mp_client(
|
||||
vllm_config=plan.stage_vllm_config,
|
||||
executor_class=plan.executor_class,
|
||||
log_stats=self._log_stats,
|
||||
metadata=plan.metadata,
|
||||
client_addresses=self._client_addresses_from_zmq(resources.addresses),
|
||||
engine_manager=resources.manager,
|
||||
coordinator=resources.coordinator,
|
||||
),
|
||||
)
|
||||
|
||||
logger.info("[StageRuntime] Stage %s initialized", plan.metadata.stage_id)
|
||||
return cast(StagePoolClient, stage_client)
|
||||
except Exception:
|
||||
if stage_client is not None:
|
||||
try:
|
||||
stage_client.shutdown()
|
||||
except Exception as cleanup_error:
|
||||
logger.warning(
|
||||
"[StageRuntime] Failed to cleanup stage %s after init failure: %s",
|
||||
plan.metadata.stage_id,
|
||||
cleanup_error,
|
||||
)
|
||||
else:
|
||||
self._cleanup_launched_resources(
|
||||
stage_id=plan.metadata.stage_id,
|
||||
resources=resources,
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
if lock_fds:
|
||||
release_device_locks(lock_fds)
|
||||
|
||||
def _get_coordinator_address(self) -> str | None:
|
||||
"""Return coordinator router address. Overridden by DistStageRuntime."""
|
||||
return None
|
||||
|
||||
def _get_external_client_addresses(self, stage_id: int, replica_id: int) -> dict[str, Any] | None:
|
||||
if self._external_stage_addresses is None:
|
||||
return None
|
||||
stage_addresses = self._external_stage_addresses.get(stage_id)
|
||||
if stage_addresses is None:
|
||||
stage_addresses = self._external_stage_addresses.get(str(stage_id))
|
||||
if stage_addresses is None:
|
||||
raise ValueError(f"Missing external addresses for stage {stage_id}")
|
||||
replica_addresses = stage_addresses.get(replica_id)
|
||||
if replica_addresses is None:
|
||||
replica_addresses = stage_addresses.get(str(replica_id))
|
||||
if replica_addresses is None:
|
||||
raise ValueError(f"Missing external addresses for stage {stage_id} replica {replica_id}")
|
||||
return dict(replica_addresses)
|
||||
|
||||
def _get_omni_master_server(self) -> OmniMasterServer | None:
|
||||
"""Return the master server for local distributed launches, if any."""
|
||||
return None
|
||||
@@ -859,17 +1073,25 @@ class StageRuntime:
|
||||
raise RuntimeError("Omni KV connector requires source and destination stages")
|
||||
inject_omni_kv_config(plan.stage_cfg, omni_conn_cfg, omni_from, omni_to)
|
||||
inject_kv_stage_info(plan.stage_cfg, plan.metadata.stage_id, self._stage_configs)
|
||||
engine_args = getattr(plan.stage_cfg, "engine_args", {})
|
||||
inline_diffusion = (
|
||||
engine_args.get("inline_diffusion", False)
|
||||
if hasattr(engine_args, "get")
|
||||
else getattr(engine_args, "inline_diffusion", False)
|
||||
)
|
||||
custom_pipeline_args = (
|
||||
engine_args.get("custom_pipeline_args")
|
||||
if hasattr(engine_args, "get")
|
||||
else getattr(engine_args, "custom_pipeline_args", None)
|
||||
)
|
||||
if isinstance(plan.stage_cfg, BaseVllmOmniStageConfig):
|
||||
inline_diffusion = plan.stage_cfg.stage_pipeline_config.inline_diffusion
|
||||
custom_pipeline_args = getattr(
|
||||
getattr(plan.stage_cfg, "diffusion_config", None),
|
||||
"custom_pipeline_args",
|
||||
None,
|
||||
)
|
||||
else:
|
||||
engine_args = getattr(plan.stage_cfg, "engine_args", {})
|
||||
inline_diffusion = (
|
||||
engine_args.get("inline_diffusion", False)
|
||||
if hasattr(engine_args, "get")
|
||||
else getattr(engine_args, "inline_diffusion", False)
|
||||
)
|
||||
custom_pipeline_args = (
|
||||
engine_args.get("custom_pipeline_args")
|
||||
if hasattr(engine_args, "get")
|
||||
else getattr(engine_args, "custom_pipeline_args", None)
|
||||
)
|
||||
client, resources = launch_diffusion_stage_replica(
|
||||
model=self._model,
|
||||
stage_config=plan.stage_cfg,
|
||||
@@ -966,7 +1188,7 @@ class DistStageRuntime(StageRuntime):
|
||||
self,
|
||||
stage_configs: list[Any],
|
||||
model: str,
|
||||
config_path: str,
|
||||
config_path: str | None,
|
||||
*,
|
||||
stage_init_timeout: int,
|
||||
async_chunk: bool,
|
||||
@@ -1028,7 +1250,7 @@ class DistStageRuntime(StageRuntime):
|
||||
|
||||
for idx, stage_cfg in enumerate(self._stage_configs):
|
||||
stage_id = int(getattr(stage_cfg, "stage_id", idx))
|
||||
runtime_cfg = getattr(stage_cfg, "runtime", None)
|
||||
runtime_cfg = getattr(stage_cfg, "runtime_config", getattr(stage_cfg, "runtime", None))
|
||||
if runtime_cfg is None:
|
||||
continue
|
||||
if stage_id == target_stage_id:
|
||||
@@ -1100,13 +1322,9 @@ class DistStageRuntime(StageRuntime):
|
||||
if registered_stage_cfg is None:
|
||||
raise ValueError(f"Remote stage {plan.metadata.stage_id} registered without stage config")
|
||||
|
||||
# Remote diffusion registration still transports the legacy mapping
|
||||
# shape. Reconstruct and project that shape until its RFC #4021 cutover.
|
||||
metadata = (
|
||||
extract_legacy_stage_metadata(OmegaConf.create(registered_stage_cfg))
|
||||
if plan.metadata.stage_type == "diffusion"
|
||||
else copy.deepcopy(plan.metadata)
|
||||
)
|
||||
# Registration is transport-only: the head-side typed plan remains
|
||||
# authoritative for metadata and topology.
|
||||
metadata = extract_stage_metadata_from_omni_stage_config(plan.stage_cfg)
|
||||
metadata.replica_id = plan.replica_id
|
||||
ctx = StageRemoteFactoryContext(
|
||||
stage_id=plan.metadata.stage_id,
|
||||
@@ -1303,7 +1521,7 @@ class DistStageRuntime(StageRuntime):
|
||||
def create_stage_runtime(
|
||||
stage_configs: list[Any],
|
||||
model: str,
|
||||
config_path: str,
|
||||
config_path: str | None,
|
||||
*,
|
||||
single_stage_mode: bool,
|
||||
stage_init_timeout: int,
|
||||
@@ -1319,6 +1537,7 @@ def create_stage_runtime(
|
||||
omni_lb_policy: str = "random",
|
||||
request_queue: janus.Queue[EngineQueueMessage] | None = None,
|
||||
log_stats: bool = False,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
) -> StageRuntime:
|
||||
"""Factory: select StageRuntime or DistStageRuntime."""
|
||||
if single_stage_mode:
|
||||
@@ -1350,4 +1569,5 @@ def create_stage_runtime(
|
||||
tokenizer=tokenizer,
|
||||
parallel_stage_init=parallel_stage_init,
|
||||
log_stats=log_stats,
|
||||
client_config=client_config,
|
||||
)
|
||||
@@ -8,13 +8,16 @@ Supports both multi-stage LLM models (e.g., Qwen2.5-Omni) and
|
||||
diffusion models (e.g., Qwen-Image) through the same CLI interface.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import signal
|
||||
from types import FrameType
|
||||
from typing import Any, cast
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import uvloop
|
||||
from vllm.entrypoints.cli.types import CLISubcommand
|
||||
@@ -23,10 +26,18 @@ from vllm.entrypoints.serve.utils.api_utils import VLLM_SUBCMD_PARSER_EPILOG
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.entrypoints.cli.logo import log_logo
|
||||
from vllm_omni.entrypoints.openai.api_server import omni_run_server
|
||||
from vllm_omni.entrypoints.utils import parse_stage_overrides
|
||||
from vllm_omni.entrypoints.openai.api_server import (
|
||||
omni_run_server,
|
||||
run_omni_api_server_worker_proc,
|
||||
)
|
||||
from vllm_omni.entrypoints.utils import parse_stage_overrides, prepare_stage_config_inputs
|
||||
from vllm_omni.utils.tracking_parser import TrackingArgumentParser, TrackingNamespace
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.utils import APIServerProcessManager
|
||||
|
||||
from vllm_omni.engine.stage_runtime import StageEngineLaunch, StageRuntime
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
DESCRIPTION = """Launch a local OpenAI-compatible API server to serve Omni models
|
||||
@@ -141,6 +152,8 @@ class OmniServeCommand(CLISubcommand):
|
||||
|
||||
if args.headless:
|
||||
run_headless(args)
|
||||
elif (getattr(args, "api_server_count", None) or 1) > 1:
|
||||
run_multi_api_server_omni(args)
|
||||
else:
|
||||
uvloop.run(omni_run_server(args))
|
||||
|
||||
@@ -198,6 +211,39 @@ class OmniServeCommand(CLISubcommand):
|
||||
if getattr(args, "omni_replica_address", None) is not None and not args.headless:
|
||||
raise ValueError("--omni-replica-address requires --headless to be set")
|
||||
|
||||
api_server_count = getattr(args, "api_server_count", None)
|
||||
if api_server_count is not None and api_server_count < 1 and not args.headless:
|
||||
raise ValueError("--api-server-count must be >= 1 unless --headless is set")
|
||||
if args.headless and api_server_count is not None and api_server_count > 0:
|
||||
raise ValueError("--api-server-count cannot be used with --headless")
|
||||
if api_server_count is not None and api_server_count > 1:
|
||||
distributed_args = (
|
||||
"stage_id",
|
||||
"omni_master_address",
|
||||
"omni_master_port",
|
||||
"omni_replica_address",
|
||||
)
|
||||
if any(getattr(args, name, None) is not None for name in distributed_args):
|
||||
raise ValueError(
|
||||
"--api-server-count > 1 cannot be combined with stage-based "
|
||||
"or distributed stage arguments (--stage-id/--omni-master-* / "
|
||||
"--omni-replica-address)"
|
||||
)
|
||||
if getattr(args, "omni_dp_size_local", 1) != 1:
|
||||
raise ValueError("--api-server-count > 1 requires --omni-dp-size-local=1")
|
||||
if getattr(args, "worker_backend", "multi_process") != "multi_process":
|
||||
raise ValueError("--api-server-count > 1 requires --worker-backend=multi_process")
|
||||
if getattr(args, "enable_fault_tolerance", False):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-fault-tolerance")
|
||||
if getattr(args, "enable_elastic_ep", False):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-elastic-ep")
|
||||
if getattr(args, "enable_sleep_mode", False):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-sleep-mode")
|
||||
from vllm import envs as vllm_envs
|
||||
|
||||
if getattr(vllm_envs, "VLLM_ALLOW_RUNTIME_LORA_UPDATING", False):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with VLLM_ALLOW_RUNTIME_LORA_UPDATING")
|
||||
|
||||
# --omni-dp-size-local is process-local. A value other than 1 only
|
||||
# makes sense when this process owns a stage (head or headless).
|
||||
omni_dp_size_local = getattr(args, "omni_dp_size_local", None)
|
||||
@@ -221,7 +267,6 @@ class OmniServeCommand(CLISubcommand):
|
||||
"data_parallel_rpc_port": "--data-parallel-rpc-port",
|
||||
"data_parallel_start_rank": "--data-parallel-start-rank",
|
||||
"data_parallel_backend": "--data-parallel-backend",
|
||||
"api_server_count": "--api-server-count",
|
||||
"enable_expert_parallel": "--enable-expert-parallel",
|
||||
}
|
||||
offenders = sorted(flag for dest, flag in prohibited_with_omni.items() if dest in explicit_cli_keys)
|
||||
@@ -261,6 +306,8 @@ class OmniServeCommand(CLISubcommand):
|
||||
|
||||
model = getattr(args, "model_tag", None) or getattr(args, "model", None)
|
||||
if model and is_diffusion_model(model):
|
||||
if api_server_count is not None and api_server_count > 1:
|
||||
raise ValueError("--api-server-count > 1 is not supported for diffusion models")
|
||||
logger.info("Detected diffusion model: %s", model)
|
||||
return
|
||||
validate_parsed_serve_args(args)
|
||||
@@ -1027,6 +1074,207 @@ class OmniServeCommand(CLISubcommand):
|
||||
return serve_parser
|
||||
|
||||
|
||||
def _build_multi_api_stage_runtime(args: TrackingNamespace, num_api_servers: int) -> StageRuntime:
|
||||
"""Resolve the local EngineCore stages that the parent process owns."""
|
||||
from vllm_omni.config.resolver import resolve_omni_config
|
||||
from vllm_omni.engine.stage_runtime import StageRuntime
|
||||
|
||||
kwargs = args.get_explicit_kwargs_dict()
|
||||
model = kwargs.pop("model", None) or args.model
|
||||
|
||||
trust_remote_code = kwargs.get("trust_remote_code")
|
||||
if trust_remote_code is False:
|
||||
trust_remote_code = None
|
||||
config_inputs = prepare_stage_config_inputs(
|
||||
model,
|
||||
kwargs,
|
||||
trust_remote_code=trust_remote_code,
|
||||
snapshot_model=True,
|
||||
)
|
||||
model = config_inputs.model
|
||||
kwargs = config_inputs.kwargs
|
||||
resolved = resolve_omni_config(
|
||||
model,
|
||||
cli_overrides=kwargs,
|
||||
trust_remote_code=config_inputs.trust_remote_code,
|
||||
deploy_config_path=config_inputs.deploy_config_path,
|
||||
stage_overrides=config_inputs.stage_overrides,
|
||||
strategy_config_path=config_inputs.strategy_config_path,
|
||||
)
|
||||
|
||||
config_path = resolved.config_path
|
||||
stage_configs = list(resolved.stage_configs)
|
||||
|
||||
sleep_stages = [
|
||||
int(getattr(stage_config, "stage_id", stage_index))
|
||||
for stage_index, stage_config in enumerate(stage_configs)
|
||||
if bool(
|
||||
getattr(
|
||||
getattr(stage_config, "model_config", getattr(stage_config, "engine_args", None)),
|
||||
"enable_sleep_mode",
|
||||
False,
|
||||
)
|
||||
)
|
||||
]
|
||||
if sleep_stages:
|
||||
raise ValueError(
|
||||
"--api-server-count > 1 cannot be combined with sleep mode; "
|
||||
f"disable enable_sleep_mode for stage(s) {sleep_stages}"
|
||||
)
|
||||
|
||||
async_chunk = any(
|
||||
bool(
|
||||
getattr(
|
||||
getattr(stage, "connector_config", None),
|
||||
"async_chunk",
|
||||
getattr(getattr(stage, "engine_args", None), "async_chunk", False),
|
||||
)
|
||||
)
|
||||
for stage in stage_configs
|
||||
)
|
||||
return StageRuntime(
|
||||
stage_configs=stage_configs,
|
||||
model=model,
|
||||
config_path=config_path,
|
||||
stage_init_timeout=int(getattr(args, "stage_init_timeout", 300)),
|
||||
parallel_stage_init=bool(getattr(args, "parallel_stage_init", False)),
|
||||
async_chunk=async_chunk,
|
||||
tokenizer=getattr(args, "tokenizer", None),
|
||||
log_stats=not bool(getattr(args, "disable_log_stats", False)),
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_multi_api_server_completion(
|
||||
api_server_manager: APIServerProcessManager,
|
||||
engine_launch: StageEngineLaunch,
|
||||
) -> None:
|
||||
"""Wait until API workers complete or any shared stage engine fails."""
|
||||
from multiprocessing import connection
|
||||
|
||||
api_processes = list(api_server_manager.processes)
|
||||
engine_processes = [
|
||||
process
|
||||
for resources in engine_launch.resources
|
||||
if resources.manager is not None
|
||||
for process in resources.manager.processes
|
||||
]
|
||||
api_by_sentinel = {process.sentinel: process for process in api_processes}
|
||||
engine_by_sentinel = {process.sentinel: process for process in engine_processes}
|
||||
|
||||
while api_by_sentinel:
|
||||
ready = connection.wait([*api_by_sentinel, *engine_by_sentinel])
|
||||
for sentinel in ready:
|
||||
if sentinel in engine_by_sentinel:
|
||||
process = engine_by_sentinel[sentinel]
|
||||
raise RuntimeError(
|
||||
f"Shared stage engine process {process.name} (PID: {process.pid}) "
|
||||
f"exited with code {process.exitcode}"
|
||||
)
|
||||
process = api_by_sentinel.pop(sentinel)
|
||||
if process.exitcode != 0:
|
||||
raise RuntimeError(
|
||||
f"API server process {process.name} (PID: {process.pid}) exited with code {process.exitcode}"
|
||||
)
|
||||
|
||||
|
||||
def _start_api_server_process_manager(
|
||||
*,
|
||||
cleanup_timeout: float,
|
||||
**manager_kwargs: object,
|
||||
) -> APIServerProcessManager:
|
||||
"""Construct vLLM's manager with rollback for a partial ``__init__``.
|
||||
|
||||
``APIServerProcessManager`` starts workers one by one in ``__init__`` and
|
||||
installs its finalizer only after every ``Process.start`` succeeds. Keep a
|
||||
reference to the partially initialized object so workers started before a
|
||||
later failure are still terminated.
|
||||
"""
|
||||
from vllm.v1.utils import APIServerProcessManager, shutdown
|
||||
|
||||
manager = APIServerProcessManager.__new__(APIServerProcessManager)
|
||||
try:
|
||||
APIServerProcessManager.__init__(manager, **manager_kwargs)
|
||||
except BaseException:
|
||||
try:
|
||||
for pipe in getattr(manager, "_address_pipes", ()):
|
||||
with contextlib.suppress(Exception):
|
||||
pipe.close()
|
||||
# A Process whose start() raised is still present in the upstream
|
||||
# manager's list, but calling is_alive() on it raises because it
|
||||
# has no Popen object. Only hand successfully started children to
|
||||
# vLLM's shutdown helper.
|
||||
started_processes = [process for process in getattr(manager, "processes", ()) if process.pid is not None]
|
||||
if started_processes:
|
||||
shutdown(started_processes, timeout=cleanup_timeout)
|
||||
except Exception:
|
||||
logger.exception("Failed to clean up partially started API server processes")
|
||||
raise
|
||||
return manager
|
||||
|
||||
|
||||
def run_multi_api_server_omni(args: TrackingNamespace) -> None:
|
||||
"""Launch API subprocesses that share one set of local stage engines."""
|
||||
from vllm.entrypoints.openai.api_server import setup_server
|
||||
from vllm.v1.metrics.prometheus import setup_multiprocess_prometheus
|
||||
|
||||
num_api_servers = int(args.api_server_count)
|
||||
if num_api_servers < 2:
|
||||
raise ValueError(f"api_server_count must be >= 2, got {num_api_servers}")
|
||||
|
||||
setup_multiprocess_prometheus()
|
||||
shutdown_requested = False
|
||||
|
||||
def signal_handler(signum: int, frame: FrameType | None) -> None:
|
||||
nonlocal shutdown_requested
|
||||
logger.debug("Received %d signal.", signum)
|
||||
if not shutdown_requested:
|
||||
shutdown_requested = True
|
||||
raise SystemExit
|
||||
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
listen_address, sock = setup_server(args, reuse_port=True)
|
||||
stage_runtime = None
|
||||
api_server_manager = None
|
||||
engine_launch = None
|
||||
try:
|
||||
stage_runtime = _build_multi_api_stage_runtime(args, num_api_servers)
|
||||
with stage_runtime.launch_stage_engines(num_api_servers) as engine_launch:
|
||||
args._omni_stage_client_configs = engine_launch.client_configs
|
||||
primary_addresses = engine_launch.resources[0].addresses
|
||||
if primary_addresses is None:
|
||||
raise RuntimeError("Primary stage engine returned no addresses")
|
||||
timeout = float(getattr(args, "shutdown_timeout", 5) or 5)
|
||||
api_server_manager = _start_api_server_process_manager(
|
||||
cleanup_timeout=timeout,
|
||||
listen_address=listen_address,
|
||||
sock=sock,
|
||||
args=args,
|
||||
num_servers=num_api_servers,
|
||||
input_addresses=primary_addresses.inputs,
|
||||
output_addresses=primary_addresses.outputs,
|
||||
target_server_fn=run_omni_api_server_worker_proc,
|
||||
)
|
||||
engine_launch.watched_frontend_processes.extend(api_server_manager.processes)
|
||||
actual_inputs, actual_outputs = api_server_manager.gather_actual_addresses()
|
||||
primary_addresses.inputs = actual_inputs
|
||||
primary_addresses.outputs = actual_outputs
|
||||
|
||||
_wait_for_multi_api_server_completion(api_server_manager, engine_launch)
|
||||
finally:
|
||||
timeout = float(getattr(args, "shutdown_timeout", 5) or 5)
|
||||
if api_server_manager is not None:
|
||||
api_server_manager.shutdown(timeout=timeout)
|
||||
if engine_launch is not None:
|
||||
engine_launch.shutdown()
|
||||
if stage_runtime is not None:
|
||||
stage_runtime.shutdown()
|
||||
sock.close()
|
||||
if shutdown_requested:
|
||||
logger.info("Shared API server shutdown completed")
|
||||
|
||||
|
||||
def run_headless(args: TrackingNamespace) -> None:
|
||||
"""Run a single stage in headless mode.
|
||||
|
||||
@@ -1048,6 +1296,7 @@ def run_headless(args: TrackingNamespace) -> None:
|
||||
)
|
||||
from vllm_omni.engine.stage_init_utils import (
|
||||
build_engine_args_dict,
|
||||
build_engine_args_dict_from_omni_stage_config,
|
||||
build_vllm_config,
|
||||
get_stage_connector_spec,
|
||||
inject_omni_kv_connector_config,
|
||||
@@ -1074,15 +1323,6 @@ def run_headless(args: TrackingNamespace) -> None:
|
||||
|
||||
# Filter down to a dict of things explicitly requested by the user
|
||||
args_dict = args.get_explicit_kwargs_dict()
|
||||
# This controls only the API-process WebSocket and is not a stage-engine option.
|
||||
args_dict.pop("robot_openpi_idle_timeout", None)
|
||||
# This CLI-only negative alias is consumed below when selecting the
|
||||
# launcher log_stats value; it is not a per-stage config override.
|
||||
args_dict.pop("disable_log_stats", None)
|
||||
|
||||
deploy_config_path = args_dict.pop("deploy_config", None)
|
||||
strategy_config_path = args_dict.pop("strategy_config", None)
|
||||
stage_overrides = args_dict.pop("stage_overrides", None)
|
||||
|
||||
# ``--replica-id`` is deprecated and ignored — replica ids are
|
||||
# auto-assigned by ``OmniMasterServer`` so headless processes carry
|
||||
@@ -1098,15 +1338,21 @@ def run_headless(args: TrackingNamespace) -> None:
|
||||
)
|
||||
args_dict.pop("replica_id")
|
||||
|
||||
resolved = resolve_omni_config(
|
||||
config_inputs = prepare_stage_config_inputs(
|
||||
model,
|
||||
args_dict,
|
||||
# store_true cannot express an explicit False: absent maps to None
|
||||
# ("not specified") so the deploy yaml's per-stage value applies.
|
||||
trust_remote_code=getattr(args, "trust_remote_code", None) or None,
|
||||
)
|
||||
args_dict = config_inputs.kwargs
|
||||
resolved = resolve_omni_config(
|
||||
model,
|
||||
trust_remote_code=config_inputs.trust_remote_code,
|
||||
cli_overrides=args_dict,
|
||||
deploy_config_path=deploy_config_path,
|
||||
stage_overrides=stage_overrides,
|
||||
strategy_config_path=strategy_config_path,
|
||||
deploy_config_path=config_inputs.deploy_config_path,
|
||||
stage_overrides=config_inputs.stage_overrides,
|
||||
strategy_config_path=config_inputs.strategy_config_path,
|
||||
)
|
||||
config_path = resolved.config_path
|
||||
stage_configs = list(resolved.stage_configs)
|
||||
@@ -1141,21 +1387,21 @@ def run_headless(args: TrackingNamespace) -> None:
|
||||
stage_connector_spec = get_stage_connector_spec(
|
||||
omni_transfer_config=omni_transfer_config,
|
||||
stage_id=stage_id,
|
||||
async_chunk=bool(stage_cfg.engine_args.get("async_chunk", False)),
|
||||
async_chunk=bool(
|
||||
getattr(getattr(stage_cfg, "connector_config", None), "async_chunk", None)
|
||||
if hasattr(stage_cfg, "connector_config")
|
||||
else stage_cfg.engine_args.get("async_chunk", False)
|
||||
),
|
||||
)
|
||||
|
||||
# ``runtime_cfg`` is mostly inherited from the parent's
|
||||
# CUDA_VISIBLE_DEVICES; when ``--omni-dp-size-local > 1`` we additionally
|
||||
# bracket each replica's spawn below with setup_stage_devices so they
|
||||
# don't all stack on cuda:0 (see ``per_replica_devices`` above).
|
||||
# Headless startup still supplies the legacy OmegaConf stage shape through
|
||||
# the stable adapter entry point. The implementation switches only when
|
||||
# RFC #4021 threads structured stage configs through the launch plan.
|
||||
engine_args_dict = build_engine_args_dict(
|
||||
stage_cfg,
|
||||
model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
cli_tokenizer=getattr(args, "tokenizer", None),
|
||||
engine_args_dict = (
|
||||
build_engine_args_dict_from_omni_stage_config(
|
||||
stage_cfg, model, stage_connector_spec=stage_connector_spec, cli_tokenizer=getattr(args, "tokenizer", None)
|
||||
)
|
||||
if hasattr(stage_cfg, "connector_config")
|
||||
else build_engine_args_dict(
|
||||
stage_cfg, model, stage_connector_spec=stage_connector_spec, cli_tokenizer=getattr(args, "tokenizer", None)
|
||||
)
|
||||
)
|
||||
|
||||
inject_omni_kv_connector_config(engine_args_dict, omni_kv_connector, stage_id)
|
||||
|
||||
@@ -6,6 +6,7 @@ This module owns app construction, server startup, app-state initialization,
|
||||
and route bodies that have not yet moved to endpoint-owned modules."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import dataclasses
|
||||
import json
|
||||
import multiprocessing
|
||||
@@ -14,6 +15,8 @@ import os
|
||||
|
||||
# Image generation API imports
|
||||
import random
|
||||
import signal
|
||||
import socket
|
||||
import time
|
||||
from argparse import Namespace
|
||||
from collections.abc import AsyncIterator
|
||||
@@ -22,6 +25,7 @@ from http import HTTPStatus
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
import uvloop
|
||||
import vllm.envs as envs
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile, WebSocket
|
||||
from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse
|
||||
@@ -81,12 +85,14 @@ from vllm.renderers.online_renderer import OnlineRenderer
|
||||
from vllm.tasks import POOLING_TASKS
|
||||
from vllm.tool_parsers import ToolParserManager
|
||||
from vllm.utils import random_uuid
|
||||
from vllm.utils.system_utils import decorate_logs
|
||||
from vllm.utils.system_utils import decorate_logs, set_process_title
|
||||
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
|
||||
|
||||
from vllm_omni.config.endpoint_policy import (
|
||||
shutdown_unsupported_routes,
|
||||
)
|
||||
from vllm_omni.engine.stage_init_utils import set_death_signal
|
||||
from vllm_omni.engine.stage_runtime import OmniClientConfig
|
||||
from vllm_omni.entrypoints.async_omni import ABORT_TIMEOUT_S, AsyncOmni
|
||||
from vllm_omni.entrypoints.duplex.serving import OmniDuplexSessionHandler
|
||||
from vllm_omni.entrypoints.duplex.warmup import _warmup_duplex_realtime
|
||||
@@ -232,8 +238,55 @@ async def omni_run_server(args, **uvicorn_kwargs) -> None:
|
||||
await omni_run_server_worker(listen_address, sock, args, **uvicorn_kwargs)
|
||||
|
||||
|
||||
async def omni_run_server_worker(listen_address, sock, args, client_config=None, **uvicorn_kwargs) -> None:
|
||||
def run_omni_api_server_worker_proc(
|
||||
listen_address: str,
|
||||
sock: socket.socket,
|
||||
args: TrackingNamespace,
|
||||
client_config: dict[str, Any] | None = None,
|
||||
**uvicorn_kwargs: object,
|
||||
) -> None:
|
||||
"""Entrypoint used by vLLM's API server process manager."""
|
||||
set_death_signal(signal.SIGTERM)
|
||||
manager_config = client_config or {}
|
||||
client_index = int(manager_config.get("client_index", 0))
|
||||
all_client_configs = getattr(args, "_omni_stage_client_configs", None)
|
||||
if not all_client_configs or not 0 <= client_index < len(all_client_configs):
|
||||
raise RuntimeError(f"Missing Omni stage client configuration for API server {client_index}")
|
||||
|
||||
omni_client_config: OmniClientConfig = copy.deepcopy(all_client_configs[client_index])
|
||||
omni_client_config["client_count"] = int(manager_config.get("client_count", 1))
|
||||
omni_client_config["client_index"] = client_index
|
||||
|
||||
stage_addresses = omni_client_config["stage_addresses"]
|
||||
first_stage_id = min(stage_addresses)
|
||||
first_replica_id = min(stage_addresses[first_stage_id])
|
||||
first_addresses = stage_addresses[first_stage_id][first_replica_id]
|
||||
for key in ("input_address", "output_address", "actual_address_pipe", "tensor_queue"):
|
||||
if key in manager_config:
|
||||
first_addresses[key] = manager_config[key]
|
||||
|
||||
set_process_title("APIServer", str(client_index))
|
||||
decorate_logs("APIServer", skip_if_decorated=True)
|
||||
uvloop.run(
|
||||
omni_run_server_worker(
|
||||
listen_address,
|
||||
sock,
|
||||
args,
|
||||
client_config=omni_client_config,
|
||||
**uvicorn_kwargs,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def omni_run_server_worker(
|
||||
listen_address: str,
|
||||
sock: socket.socket,
|
||||
args: TrackingNamespace,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
**uvicorn_kwargs: object,
|
||||
) -> None:
|
||||
"""Run a single API server worker."""
|
||||
api_server_count = _resolve_api_server_count(args, client_config)
|
||||
|
||||
if args.tool_parser_plugin and len(args.tool_parser_plugin) > 3:
|
||||
ToolParserManager.import_tool_parser(args.tool_parser_plugin)
|
||||
@@ -273,6 +326,7 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
|
||||
|
||||
# OMNI: Pass supported_tasks to build_app (required by upstream vLLM)
|
||||
app = build_openai_app(args, supported_tasks)
|
||||
app.state.api_server_count = api_server_count
|
||||
|
||||
# OMNI: Remove upstream routes that we override with omni-specific handlers
|
||||
remove_route_from_app(app, "/v1/chat/completions", {"POST"})
|
||||
@@ -348,6 +402,7 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
|
||||
if scope["type"] == "http":
|
||||
scope.setdefault("state", {})
|
||||
scope["state"]["request_timestamp"] = time.time()
|
||||
|
||||
await self._inner(scope, receive, send)
|
||||
|
||||
# Startup duplex warmup (duplex_session.warmup_frames in the deploy
|
||||
@@ -406,7 +461,7 @@ async def build_async_omni(
|
||||
args: TrackingNamespace,
|
||||
*,
|
||||
disable_frontend_multiprocessing: bool | None = None,
|
||||
client_config: dict[str, Any] | None = None,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
) -> AsyncIterator[EngineClient]:
|
||||
"""Build an AsyncOmni instance from command-line arguments.
|
||||
|
||||
@@ -437,6 +492,7 @@ async def build_async_omni(
|
||||
async with build_async_omni_from_stage_config(
|
||||
args,
|
||||
disable_frontend_multiprocessing=disable_frontend_multiprocessing,
|
||||
client_config=client_config,
|
||||
) as async_omni:
|
||||
yield async_omni
|
||||
|
||||
@@ -476,6 +532,7 @@ async def build_async_omni_from_stage_config(
|
||||
args: TrackingNamespace,
|
||||
*,
|
||||
disable_frontend_multiprocessing: bool = False,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
) -> AsyncIterator[EngineClient]:
|
||||
"""Create AsyncOmni from stage configuration.
|
||||
|
||||
@@ -532,6 +589,8 @@ async def build_async_omni_from_stage_config(
|
||||
kwargs.pop("robot_openpi_idle_timeout", None)
|
||||
model = kwargs.pop("model", None) or args.model
|
||||
kwargs.setdefault("log_stats", not args.disable_log_stats)
|
||||
if client_config is not None:
|
||||
kwargs["client_config"] = client_config
|
||||
if _should_serve_duplex(model, kwargs):
|
||||
async_omni = DuplexOmni(model=model, **kwargs)
|
||||
else:
|
||||
@@ -1430,6 +1489,42 @@ async def list_voices(raw_request: Request):
|
||||
return JSONResponse(content={"voices": speakers, "uploaded_voices": uploaded_speakers})
|
||||
|
||||
|
||||
def _resolve_api_server_count(args: Namespace, client_config: OmniClientConfig | None) -> int:
|
||||
"""Resolve frontend topology once, from the launcher's client configuration."""
|
||||
requested = getattr(args, "api_server_count", None)
|
||||
actual = 1 if client_config is None else client_config.get("client_count")
|
||||
if type(actual) is not int or actual < 1:
|
||||
raise ValueError("API client configuration requires a positive integer client_count")
|
||||
if requested is not None and (type(requested) is not int or requested < 1 or requested != actual):
|
||||
raise ValueError("API server count does not match the frontend launch configuration")
|
||||
return actual
|
||||
|
||||
|
||||
def _reject_process_local_state_with_multiple_api_workers(raw_request: Request, operation: str) -> None:
|
||||
"""Reject access to frontend state that is not shared across API workers."""
|
||||
api_server_count = getattr(raw_request.app.state, "api_server_count", None)
|
||||
if type(api_server_count) is not int or api_server_count < 1:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail="API worker topology is not initialized.",
|
||||
)
|
||||
if api_server_count > 1:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.CONFLICT.value,
|
||||
detail=(
|
||||
f"{operation} is not supported with --api-server-count > 1 because "
|
||||
"the operation uses process-local frontend state"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def _require_single_api_video_store(raw_request: Request) -> None:
|
||||
# VIDEO_STORE and VIDEO_TASKS are process-local, including reads and
|
||||
# cancellation. Keep this independent of the temporary diffusion launch
|
||||
# restriction: enabling multi-API diffusion alone cannot make jobs shared.
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Asynchronous video jobs")
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/audio/voices",
|
||||
responses={
|
||||
@@ -1475,6 +1570,7 @@ async def upload_voice(
|
||||
Returns:
|
||||
JSON response with voice information
|
||||
"""
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Runtime voice upload")
|
||||
handler = Omnispeech(raw_request)
|
||||
if handler is None:
|
||||
return _create_speech_error_json_response(
|
||||
@@ -1540,6 +1636,7 @@ async def delete_voice(name: str, raw_request: Request):
|
||||
Returns:
|
||||
JSON response indicating success or failure
|
||||
"""
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Runtime voice deletion")
|
||||
handler = Omnispeech(raw_request)
|
||||
if handler is None:
|
||||
return _create_speech_error_json_response(
|
||||
@@ -1633,13 +1730,15 @@ async def streaming_video_output(websocket: WebSocket):
|
||||
@router.websocket("/v1/realtime")
|
||||
async def realtime_websocket(websocket: WebSocket):
|
||||
"""WebSocket endpoint for OpenAI-style realtime interactions."""
|
||||
await _wait_for_duplex_warmup(websocket)
|
||||
duplex_handler = getattr(websocket.app.state, "openai_serving_duplex", None)
|
||||
duplex_query = websocket.query_params.get("duplex")
|
||||
use_duplex_realtime = duplex_handler is not None and (
|
||||
duplex_query is None or (isinstance(duplex_query, str) and duplex_query.lower() in {"1", "true", "on"})
|
||||
)
|
||||
if use_duplex_realtime and duplex_handler is not None:
|
||||
if await _reject_multi_api_duplex(websocket):
|
||||
return
|
||||
await _wait_for_duplex_warmup(websocket)
|
||||
await duplex_handler.handle_realtime_session(websocket)
|
||||
return
|
||||
|
||||
@@ -1669,6 +1768,8 @@ async def _wait_for_duplex_warmup(websocket: WebSocket) -> None:
|
||||
@router.websocket("/v1/duplex")
|
||||
async def duplex_websocket(websocket: WebSocket):
|
||||
"""Alias of ``/v1/realtime?duplex=1``: the same Realtime duplex session protocol."""
|
||||
if await _reject_multi_api_duplex(websocket):
|
||||
return
|
||||
await _wait_for_duplex_warmup(websocket)
|
||||
handler = getattr(websocket.app.state, "openai_serving_duplex", None)
|
||||
if handler is None:
|
||||
@@ -1709,6 +1810,24 @@ async def realtime_robot_openpi(websocket: WebSocket):
|
||||
await connection.handle_connection()
|
||||
|
||||
|
||||
async def _reject_multi_api_duplex(websocket: WebSocket) -> bool:
|
||||
# Session credentials and replay state are local to each frontend; a shared
|
||||
# listening socket cannot route reconnects back to the session owner.
|
||||
count = getattr(websocket.app.state, "api_server_count", None)
|
||||
if count is None or (type(count) is int and count == 1):
|
||||
return False
|
||||
await websocket.accept()
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "error",
|
||||
"error": "Duplex sessions require a single API worker with initialized topology.",
|
||||
"code": "multi_api_duplex_unsupported",
|
||||
}
|
||||
)
|
||||
await websocket.close(code=1008)
|
||||
return True
|
||||
|
||||
|
||||
# RL Rollout serving (RFC #3747, P0)
|
||||
|
||||
|
||||
@@ -2476,6 +2595,7 @@ async def edit_images(
|
||||
|
||||
@router.post(
|
||||
"/v1/videos",
|
||||
dependencies=[Depends(_require_single_api_video_store)],
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"model": VideoResponse},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
@@ -2617,7 +2737,7 @@ async def create_video_sync(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/v1/videos", response_model=VideoListResponse)
|
||||
@router.get("/v1/videos", response_model=VideoListResponse, dependencies=[Depends(_require_single_api_video_store)])
|
||||
async def list_videos(
|
||||
after: str | None = None,
|
||||
limit: int | None = Query(None, ge=0, le=100),
|
||||
@@ -2654,7 +2774,7 @@ async def list_videos(
|
||||
return VideoListResponse(data=jobs, has_more=has_more, first_id=first_id, last_id=last_id)
|
||||
|
||||
|
||||
@router.get("/v1/videos/{video_id}", response_model=None)
|
||||
@router.get("/v1/videos/{video_id}", response_model=None, dependencies=[Depends(_require_single_api_video_store)])
|
||||
async def retrieve_video(video_id: str) -> VideoResponse | JSONResponse:
|
||||
"""Retrieve metadata for a previously created video job.
|
||||
|
||||
@@ -2682,7 +2802,7 @@ async def retrieve_video(video_id: str) -> VideoResponse | JSONResponse:
|
||||
return job
|
||||
|
||||
|
||||
@router.delete("/v1/videos/{video_id}")
|
||||
@router.delete("/v1/videos/{video_id}", dependencies=[Depends(_require_single_api_video_store)])
|
||||
async def delete_video(video_id: str, raw_request: Request) -> VideoDeleteResponse:
|
||||
"""Delete a stored video job and any generated output.
|
||||
|
||||
@@ -2752,7 +2872,7 @@ async def delete_video(video_id: str, raw_request: Request) -> VideoDeleteRespon
|
||||
return VideoDeleteResponse(id=job.id, deleted=True)
|
||||
|
||||
|
||||
@router.get("/v1/videos/{video_id}/content")
|
||||
@router.get("/v1/videos/{video_id}/content", dependencies=[Depends(_require_single_api_video_store)])
|
||||
async def download_video(video_id: str) -> Response:
|
||||
"""Download the generated file for a completed video job.
|
||||
|
||||
@@ -2845,6 +2965,7 @@ async def stop_profile(raw_request: Request, request: ProfileRequest | None = No
|
||||
|
||||
@router.post("/v1/omni/sleep")
|
||||
async def omni_sleep(request: OmniSleepRequest, raw_request: Request):
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Sleep")
|
||||
engine_client = raw_request.app.state.engine_client
|
||||
sleeping_set = raw_request.app.state.sleeping_stages
|
||||
if not hasattr(engine_client, "sleep"):
|
||||
@@ -2857,6 +2978,7 @@ async def omni_sleep(request: OmniSleepRequest, raw_request: Request):
|
||||
|
||||
@router.post("/v1/omni/wakeup")
|
||||
async def omni_wakeup(request: OmniWakeupRequest, raw_request: Request):
|
||||
_reject_process_local_state_with_multiple_api_workers(raw_request, "Wakeup")
|
||||
engine_client = raw_request.app.state.engine_client
|
||||
sleeping_set = raw_request.app.state.sleeping_stages
|
||||
if not any(sid in sleeping_set for sid in request.stage_ids):
|
||||
|
||||
@@ -248,10 +248,27 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
return obj.get(key, default)
|
||||
return getattr(obj, key, default)
|
||||
|
||||
@classmethod
|
||||
def _stage_model_metadata(cls, stage: Any) -> tuple[str | None, str | None]:
|
||||
"""Return ``(model_arch, model_stage)`` for typed or legacy stages."""
|
||||
model_config = cls._stage_get(stage, "model_config")
|
||||
model_arch = cls._stage_get(model_config, "model_arch")
|
||||
model_stage = cls._stage_get(stage, "model_stage")
|
||||
|
||||
topology = cls._stage_get(stage, "stage_pipeline_config")
|
||||
if model_stage is None:
|
||||
model_stage = cls._stage_get(topology, "model_stage")
|
||||
|
||||
engine_args = cls._stage_get(stage, "engine_args")
|
||||
if model_arch is None:
|
||||
model_arch = cls._stage_get(engine_args, "model_arch")
|
||||
if model_stage is None:
|
||||
model_stage = cls._stage_get(engine_args, "model_stage")
|
||||
return model_arch, model_stage
|
||||
|
||||
def _has_minicpmo45_stage(self) -> bool:
|
||||
for stage in getattr(self.engine_client, "stage_configs", []) or []:
|
||||
engine_args = self._stage_get(stage, "engine_args")
|
||||
model_arch = self._stage_get(engine_args, "model_arch")
|
||||
model_arch, _ = self._stage_model_metadata(stage)
|
||||
if model_arch == "MiniCPMO45OmniForConditionalGeneration":
|
||||
return True
|
||||
return False
|
||||
@@ -324,11 +341,10 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
if not hasattr(sp, "output_kind"):
|
||||
continue
|
||||
|
||||
engine_args = self._stage_get(stage, "engine_args")
|
||||
if self._stage_get(engine_args, "model_arch") != "MiniCPMO45OmniForConditionalGeneration":
|
||||
model_arch, model_stage = self._stage_model_metadata(stage)
|
||||
if model_arch != "MiniCPMO45OmniForConditionalGeneration":
|
||||
continue
|
||||
|
||||
model_stage = self._stage_get(engine_args, "model_stage")
|
||||
if model_stage == "llm":
|
||||
sp.output_kind = RequestOutputKind.FINAL_ONLY
|
||||
elif model_stage == "tts":
|
||||
|
||||
@@ -36,6 +36,7 @@ from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
from vllm.utils import random_uuid
|
||||
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
|
||||
|
||||
from vllm_omni.config.stage_config import StagePipelineConfig
|
||||
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin, StreamingAudioResampler
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import (
|
||||
AudioResponse,
|
||||
@@ -76,6 +77,24 @@ _SPEECH_USAGE_TOTAL_TOKENS_HEADER = "X-VLLM-OMNI-TOTAL-TOKENS"
|
||||
_SPEECH_USAGE_INPUT_TEXT_TOKENS_HEADER = "X-VLLM-OMNI-INPUT-TEXT-TOKENS"
|
||||
_SPEECH_USAGE_INPUT_AUDIO_TOKENS_HEADER = "X-VLLM-OMNI-INPUT-AUDIO-TOKENS"
|
||||
|
||||
|
||||
def _stage_speech_metadata(stage: Any) -> tuple[str | None, str | None, str | None]:
|
||||
"""Return speech routing metadata from typed or legacy stage configs."""
|
||||
topology = getattr(stage, "stage_pipeline_config", None)
|
||||
if isinstance(topology, StagePipelineConfig):
|
||||
return (
|
||||
getattr(topology, "model_stage", None),
|
||||
getattr(getattr(stage, "model_config", None), "model_arch", None),
|
||||
getattr(stage, "worker_type", None),
|
||||
)
|
||||
engine_args = getattr(stage, "engine_args", None)
|
||||
return (
|
||||
getattr(engine_args, "model_stage", None),
|
||||
getattr(engine_args, "model_arch", None),
|
||||
getattr(engine_args, "worker_type", None),
|
||||
)
|
||||
|
||||
|
||||
# TTS Configuration
|
||||
#
|
||||
# The stage-key -> model-type mapping is NOT declared here: it is derived from
|
||||
@@ -472,12 +491,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
"""Find and return the TTS stage config, or None if not found."""
|
||||
tts_stage_keys = all_tts_stage_keys()
|
||||
entry_stage_archs = tts_entry_stage_archs()
|
||||
all_stages = frozenset(stage.engine_args.model_stage for stage in self.engine_client.stage_configs)
|
||||
all_stages = frozenset(
|
||||
model_stage
|
||||
for stage in self.engine_client.stage_configs
|
||||
if (model_stage := _stage_speech_metadata(stage)[0]) is not None
|
||||
)
|
||||
for stage in self.engine_client.stage_configs:
|
||||
engine_args = stage.engine_args
|
||||
model_stage = engine_args.model_stage
|
||||
model_arch = getattr(engine_args, "model_arch", None)
|
||||
worker_type = getattr(engine_args, "worker_type", None)
|
||||
model_stage, model_arch, worker_type = _stage_speech_metadata(stage)
|
||||
if model_stage in tts_stage_keys:
|
||||
# Owning the stage key is not always enough: a model may be
|
||||
# speech-capable only in some deployment topologies. Ask the
|
||||
@@ -501,10 +521,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
"""
|
||||
if self._tts_stage is None:
|
||||
return None
|
||||
return detect_tts_model_type(
|
||||
getattr(self._tts_stage.engine_args, "model_stage", None),
|
||||
getattr(self._tts_stage.engine_args, "model_arch", None),
|
||||
)
|
||||
return detect_tts_model_type(*_stage_speech_metadata(self._tts_stage)[:2])
|
||||
|
||||
def _compute_max_instructions_length(self) -> int:
|
||||
"""Compute max instructions length with precedence: CLI > stage config > default.
|
||||
@@ -518,7 +535,12 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
|
||||
# 2. Try to get from TTS stage config
|
||||
if self._tts_stage is not None:
|
||||
tts_args = getattr(self._tts_stage, "tts_args", {})
|
||||
topology = getattr(self._tts_stage, "stage_pipeline_config", None)
|
||||
tts_args = (
|
||||
getattr(topology, "extras", {}).get("tts_args", {})
|
||||
if isinstance(topology, StagePipelineConfig)
|
||||
else getattr(self._tts_stage, "tts_args", {})
|
||||
)
|
||||
if "max_instructions_length" in tts_args:
|
||||
return tts_args["max_instructions_length"]
|
||||
|
||||
@@ -1896,9 +1918,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
# chat-template markers (im_start_token_id 151644). A raw-text
|
||||
# prompt produces a 1-token placeholder that crashes the talker's
|
||||
# prefill/decode handoff. Reject early with an actionable message.
|
||||
stage_names = {
|
||||
getattr(getattr(s, "engine_args", None), "model_stage", None) for s in self.engine_client.stage_configs
|
||||
}
|
||||
stage_names = {_stage_speech_metadata(s)[0] for s in self.engine_client.stage_configs}
|
||||
if "talker" in stage_names:
|
||||
raise ValueError(
|
||||
"The /v1/audio/speech endpoint is only supported for "
|
||||
|
||||
@@ -53,6 +53,30 @@ logger = init_logger(__name__)
|
||||
|
||||
_VIDEO_RESPONSE_FRAME_CONVERSION_WORKERS = 8
|
||||
|
||||
|
||||
def _config_value(config: Any, key: str, default: Any = None) -> Any:
|
||||
if isinstance(config, Mapping):
|
||||
return config.get(key, default)
|
||||
return getattr(config, key, default)
|
||||
|
||||
|
||||
def _stage_diffusion_model_class_name(stage_config: Any) -> str | None:
|
||||
"""Resolve a stage's diffusion class across typed and legacy shapes."""
|
||||
diffusion_config = _config_value(stage_config, "diffusion_config")
|
||||
model_class_name = _config_value(diffusion_config, "model_class_name")
|
||||
if model_class_name:
|
||||
return str(model_class_name)
|
||||
|
||||
model_config = _config_value(stage_config, "model_config")
|
||||
model_arch = _config_value(model_config, "model_arch") or _config_value(stage_config, "model_arch")
|
||||
if model_arch:
|
||||
return str(model_arch)
|
||||
|
||||
engine_args = _config_value(stage_config, "engine_args", {})
|
||||
model_class_name = _config_value(engine_args, "model_class_name")
|
||||
return str(model_class_name) if model_class_name else None
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
|
||||
@@ -195,18 +219,7 @@ class OmniOpenAIServingVideo:
|
||||
model_class_name = getattr(od_config, "model_class_name", None)
|
||||
model_archs = [model_class_name]
|
||||
for stage_config in self.stage_configs or ():
|
||||
stage_get = (
|
||||
stage_config.get if isinstance(stage_config, Mapping) else lambda key: getattr(stage_config, key, None)
|
||||
)
|
||||
engine_args = stage_get("engine_args") or {}
|
||||
model_archs.extend(
|
||||
(
|
||||
stage_get("model_arch"),
|
||||
engine_args.get("model_class_name")
|
||||
if isinstance(engine_args, Mapping)
|
||||
else getattr(engine_args, "model_class_name", None),
|
||||
)
|
||||
)
|
||||
model_archs.append(_stage_diffusion_model_class_name(stage_config))
|
||||
metadata_capability = any(
|
||||
get_diffusion_model_metadata(model_arch).supports_mixed_reference_inputs for model_arch in model_archs
|
||||
)
|
||||
@@ -223,18 +236,7 @@ class OmniOpenAIServingVideo:
|
||||
od_config = self._resolve_diffusion_od_config()
|
||||
model_archs = [None if od_config is None else getattr(od_config, "model_class_name", None)]
|
||||
for stage_config in self.stage_configs or ():
|
||||
stage_get = (
|
||||
stage_config.get if isinstance(stage_config, Mapping) else lambda key: getattr(stage_config, key, None)
|
||||
)
|
||||
engine_args = stage_get("engine_args") or {}
|
||||
model_archs.extend(
|
||||
(
|
||||
stage_get("model_arch"),
|
||||
engine_args.get("model_class_name")
|
||||
if isinstance(engine_args, Mapping)
|
||||
else getattr(engine_args, "model_class_name", None),
|
||||
)
|
||||
)
|
||||
model_archs.append(_stage_diffusion_model_class_name(stage_config))
|
||||
|
||||
supported: set[str] = set()
|
||||
for model_arch in model_archs:
|
||||
|
||||
@@ -42,7 +42,11 @@ class AudexAdapter(ARTTSAdapter):
|
||||
|
||||
from vllm_omni.model_executor.models.audex.checkpoint import ensure_audex_snapshot
|
||||
|
||||
stage = getattr(getattr(self.ctx.server._tts_stage, "engine_args", None), "model_stage", None)
|
||||
stage_config = self.ctx.server._tts_stage
|
||||
topology = getattr(stage_config, "stage_pipeline_config", None)
|
||||
stage = getattr(topology, "model_stage", None)
|
||||
if stage is None:
|
||||
stage = getattr(getattr(stage_config, "engine_args", None), "model_stage", None)
|
||||
profile, folder = (
|
||||
("full", "checkpoint_folder_full") if stage == "audex_omni" else ("tts", "checkpoint_folder_audiogen")
|
||||
)
|
||||
|
||||
@@ -39,6 +39,21 @@ DEFAULT_TTS_LANGUAGES = frozenset(
|
||||
)
|
||||
|
||||
|
||||
def resolve_stage_model_path(engine_client: Any) -> str | None:
|
||||
"""Prefer typed stage model overrides, then legacy and served-model values."""
|
||||
stages = getattr(engine_client, "stage_configs", ()) or ()
|
||||
for stage in stages:
|
||||
model_path = getattr(getattr(stage, "model_config", None), "model", None)
|
||||
if model_path:
|
||||
return str(model_path)
|
||||
for stage in stages:
|
||||
model_path = getattr(getattr(stage, "engine_args", None), "model", None)
|
||||
if model_path:
|
||||
return str(model_path)
|
||||
model_path = getattr(engine_client, "model", None)
|
||||
return str(model_path) if model_path else None
|
||||
|
||||
|
||||
def conditioning_cache_salt(request: "OpenAICreateSpeechRequest", tts_params: dict | None = None) -> str:
|
||||
"""Stable hash of the real Stage 0 conditioning for the prefix cache.
|
||||
|
||||
|
||||
@@ -9,7 +9,12 @@ import numpy as np
|
||||
from vllm.inputs import tokens_input
|
||||
|
||||
from vllm_omni.entrypoints.openai.tts_adapters import register_tts_adapter
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import ARTTSAdapter, PreparedRequest, apply_max_new_tokens
|
||||
from vllm_omni.entrypoints.openai.tts_adapters.base import (
|
||||
ARTTSAdapter,
|
||||
PreparedRequest,
|
||||
apply_max_new_tokens,
|
||||
resolve_stage_model_path,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import OpenAICreateSpeechRequest
|
||||
@@ -81,17 +86,7 @@ class HiggsAudioV2Adapter(ARTTSAdapter):
|
||||
|
||||
from transformers import AutoProcessor
|
||||
|
||||
model_path = None
|
||||
for stage in self.engine_client.stage_configs:
|
||||
model_path = getattr(getattr(stage, "engine_args", None), "model", None)
|
||||
if model_path:
|
||||
break
|
||||
if model_path is None:
|
||||
# Fallback: the orchestrator stores the served model id on the engine
|
||||
# itself (set by AsyncOmniEngine.__init__). Stage-level engine_args
|
||||
# may not surface ``model`` when the deploy yaml doesn't set it per
|
||||
# stage (the CLI-passed model id is the single source of truth).
|
||||
model_path = getattr(self.engine_client, "model", None)
|
||||
model_path = resolve_stage_model_path(self.engine_client)
|
||||
if model_path is None:
|
||||
raise RuntimeError("higgs_audio_v2 serving could not resolve the model path from the engine stage configs")
|
||||
processor = AutoProcessor.from_pretrained(model_path)
|
||||
|
||||
@@ -16,6 +16,7 @@ from vllm_omni.entrypoints.openai.tts_adapters.base import (
|
||||
PreparedRequest,
|
||||
apply_max_new_tokens,
|
||||
conditioning_cache_salt,
|
||||
resolve_stage_model_path,
|
||||
)
|
||||
|
||||
_REF_CODE_CACHE_MAX_ENTRIES = 256
|
||||
@@ -170,13 +171,7 @@ class HiggsAudioV3Adapter(ARTTSAdapter):
|
||||
HiggsAudioV3TokenizerAdapter,
|
||||
)
|
||||
|
||||
model_path = None
|
||||
for stage in self.engine_client.stage_configs:
|
||||
model_path = getattr(getattr(stage, "engine_args", None), "model", None)
|
||||
if model_path:
|
||||
break
|
||||
if model_path is None:
|
||||
model_path = getattr(self.engine_client, "model", None)
|
||||
model_path = resolve_stage_model_path(self.engine_client)
|
||||
if model_path is None:
|
||||
raise RuntimeError("higgs_audio_v3 serving could not resolve model path")
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
||||
|
||||
@@ -58,6 +58,7 @@ from vllm_omni.entrypoints.openai.serving_video import (
|
||||
ReferenceAudio,
|
||||
ReferenceImage,
|
||||
ReferenceVideo,
|
||||
_stage_diffusion_model_class_name,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.storage import STORAGE_MANAGER
|
||||
from vllm_omni.entrypoints.openai.stores import VIDEO_STORE
|
||||
@@ -136,10 +137,6 @@ def _config_get(config: Any, key: str, default: Any = None) -> Any:
|
||||
return getattr(config, key, default)
|
||||
|
||||
|
||||
def _stage_engine_args(stage_cfg: Any) -> Any:
|
||||
return _config_get(stage_cfg, "engine_args", {}) or {}
|
||||
|
||||
|
||||
def _diffusion_model_classes(stage_configs: list[Any] | None) -> list[type]:
|
||||
if not stage_configs:
|
||||
return []
|
||||
@@ -150,7 +147,7 @@ def _diffusion_model_classes(stage_configs: list[Any] | None) -> list[type]:
|
||||
for stage_cfg in stage_configs:
|
||||
if get_stage_type(stage_cfg) != "diffusion":
|
||||
continue
|
||||
model_class_name = _config_get(_stage_engine_args(stage_cfg), "model_class_name")
|
||||
model_class_name = _stage_diffusion_model_class_name(stage_cfg)
|
||||
if not model_class_name:
|
||||
continue
|
||||
model_cls = DiffusionModelRegistry._try_load_model_cls(model_class_name)
|
||||
|
||||
@@ -103,6 +103,14 @@ class ServingRealtimeRobotOpenPI:
|
||||
for stage_config in getattr(engine_client, "stage_configs", []) or []:
|
||||
if getattr(stage_config, "stage_type", None) != "diffusion":
|
||||
continue
|
||||
# Typed diffusion stages keep model-owned OpenPI handshake
|
||||
# metadata in diffusion_config.model_config. The out-of-process
|
||||
# head only has this stage view because full od_config lives in
|
||||
# the worker.
|
||||
diffusion_config = getattr(stage_config, "diffusion_config", None)
|
||||
model_config = getattr(diffusion_config, "model_config", None)
|
||||
if model_config is not None:
|
||||
break
|
||||
engine_args = getattr(stage_config, "engine_args", None)
|
||||
model_config = getattr(engine_args, "model_config", None)
|
||||
if model_config is not None:
|
||||
|
||||
@@ -4,18 +4,20 @@
|
||||
|
||||
|
||||
def _should_enable_profiler_endpoints(stage_configs: list | None) -> bool:
|
||||
"""Check if any stage has profiler_config set in its engine_args."""
|
||||
"""Check whether any typed or legacy stage enables a profiler."""
|
||||
if not stage_configs:
|
||||
return False
|
||||
for stage in stage_configs:
|
||||
engine_args = stage.get("engine_args") if isinstance(stage, dict) else getattr(stage, "engine_args", None)
|
||||
if engine_args is None:
|
||||
continue
|
||||
profiler_config = (
|
||||
engine_args.get("profiler_config")
|
||||
if isinstance(engine_args, dict)
|
||||
else getattr(engine_args, "profiler_config", None)
|
||||
stage.get("profiler_config") if isinstance(stage, dict) else getattr(stage, "profiler_config", None)
|
||||
)
|
||||
if profiler_config is None:
|
||||
engine_args = stage.get("engine_args") if isinstance(stage, dict) else getattr(stage, "engine_args", None)
|
||||
profiler_config = (
|
||||
engine_args.get("profiler_config")
|
||||
if isinstance(engine_args, dict)
|
||||
else getattr(engine_args, "profiler_config", None)
|
||||
)
|
||||
if profiler_config is not None:
|
||||
profiler = (
|
||||
profiler_config.get("profiler")
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import asdict, is_dataclass
|
||||
from multiprocessing import shared_memory as _shm
|
||||
from typing import Any
|
||||
|
||||
@@ -274,6 +278,8 @@ def _to_dict(x: Any) -> dict[str, Any]:
|
||||
try:
|
||||
if isinstance(x, dict):
|
||||
return dict(x)
|
||||
if is_dataclass(x) and not isinstance(x, type):
|
||||
return asdict(x)
|
||||
return _omega_to_dict(x)
|
||||
except Exception:
|
||||
try:
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
import json
|
||||
import os
|
||||
import types
|
||||
from dataclasses import fields, is_dataclass
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, fields, is_dataclass
|
||||
from typing import Any, get_args, get_origin
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
|
||||
from vllm_omni.config.config_factory import with_trust_remote_code_override
|
||||
from vllm_omni.entrypoints.stage_utils import _to_dict
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
|
||||
@@ -18,6 +20,13 @@ logger = init_logger(__name__)
|
||||
|
||||
def inject_omni_kv_config(stage: Any, omni_conn_cfg: dict[str, Any], omni_from: str, omni_to: str) -> None:
|
||||
"""Inject connector configuration into stage engine arguments."""
|
||||
typed_connector_config = getattr(stage, "connector_config", None)
|
||||
if typed_connector_config is not None:
|
||||
omni_conf_dict = dict(typed_connector_config.omni_kv_config or {})
|
||||
omni_conf_dict.update(connector_config=omni_conn_cfg, omni_from_stage=omni_from, omni_to_stage=omni_to)
|
||||
typed_connector_config.omni_kv_config = omni_conf_dict
|
||||
return
|
||||
|
||||
# Prepare omni_kv_config dict
|
||||
omni_conf_dict = {}
|
||||
try:
|
||||
@@ -79,6 +88,64 @@ def parse_stage_overrides(value: Any) -> dict[str, dict[str, Any]] | None:
|
||||
return parsed
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StageConfigInputs:
|
||||
"""Normalized inputs shared by all stage-config loading paths."""
|
||||
|
||||
model: str
|
||||
kwargs: dict[str, Any]
|
||||
trust_remote_code: bool | None
|
||||
deploy_config_path: str | None
|
||||
stage_overrides: dict[str, dict[str, Any]] | None
|
||||
strategy_config_path: str | None
|
||||
|
||||
|
||||
def prepare_stage_config_inputs(
|
||||
model: str,
|
||||
kwargs: Mapping[str, Any],
|
||||
*,
|
||||
trust_remote_code: bool | None,
|
||||
snapshot_model: bool = False,
|
||||
) -> StageConfigInputs:
|
||||
"""Normalize model/config arguments before resolving stage configs.
|
||||
|
||||
The standard API worker, multi-API parent, and headless entrypoint must
|
||||
apply the same legacy-key filtering, trust-remote-code precedence, and
|
||||
config-file extraction before calling :func:`resolve_omni_config`.
|
||||
"""
|
||||
resolved_model = model
|
||||
if snapshot_model:
|
||||
# Keep model materialization at the CLI boundary for the parent-owned
|
||||
# launch path. The API worker's OmniBase has already done this work.
|
||||
from vllm_omni.entrypoints.omni_base import omni_snapshot_download
|
||||
|
||||
resolved_model = omni_snapshot_download(model)
|
||||
|
||||
resolved_kwargs = dict(kwargs)
|
||||
for legacy_arg in ("stage_configs_path", "stage_configs"):
|
||||
if legacy_arg in resolved_kwargs:
|
||||
raise ValueError(f"`{legacy_arg}` is no longer supported; use `deploy_config` instead.")
|
||||
# Frontend process count is not a stage engine override.
|
||||
resolved_kwargs.pop("api_server_count", None)
|
||||
resolved_kwargs.pop("disable_log_stats", None)
|
||||
if resolved_kwargs.get("diffusion_streaming_output") and resolved_kwargs.get("streaming_output") is None:
|
||||
resolved_kwargs["streaming_output"] = True
|
||||
resolved_kwargs.pop("model_tag", None)
|
||||
|
||||
resolved_kwargs = with_trust_remote_code_override(resolved_kwargs, trust_remote_code)
|
||||
deploy_config_path = resolved_kwargs.pop("deploy_config", None)
|
||||
strategy_config_path = resolved_kwargs.pop("strategy_config", None)
|
||||
stage_overrides = parse_stage_overrides(resolved_kwargs.pop("stage_overrides", None))
|
||||
return StageConfigInputs(
|
||||
model=resolved_model,
|
||||
kwargs=resolved_kwargs,
|
||||
trust_remote_code=trust_remote_code,
|
||||
deploy_config_path=deploy_config_path,
|
||||
stage_overrides=stage_overrides,
|
||||
strategy_config_path=strategy_config_path,
|
||||
)
|
||||
|
||||
|
||||
def get_final_stage_id_for_e2e(
|
||||
output_modalities: list[str] | None, default_modalities: list[str], stage_list: list
|
||||
) -> int:
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""MiniMax H3 checkpoint resolution for the AR text-encoder stage."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from vllm_omni.diffusion.utils.hf_utils import get_diffusion_model_index
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import (
|
||||
download_weights_from_hf_specific,
|
||||
)
|
||||
|
||||
_FASTH3_MODULAR_MODEL_PREFIX = "FastVideo/"
|
||||
|
||||
MINIMAX_H3_ENCODER_DOWNLOAD_PATTERNS = {
|
||||
partition: [
|
||||
f"{subdir}/text_encoder/**",
|
||||
@@ -16,6 +22,22 @@ MINIMAX_H3_ENCODER_DOWNLOAD_PATTERNS = {
|
||||
MINIMAX_H3_ENCODER_DOWNLOAD_PATTERNS["combined"] = MINIMAX_H3_ENCODER_DOWNLOAD_PATTERNS["fl2va"]
|
||||
|
||||
|
||||
def is_minimax_h3_modular(model: str, revision: str | None = None) -> bool:
|
||||
path = Path(model)
|
||||
if path.is_dir():
|
||||
# Native MiniMax-H3 snapshots can advertise the Diffusers modular
|
||||
# class in ``model_index.json`` while retaining the legacy FL2VA /
|
||||
# Ref2VA layout. FastH3 modular releases carry this marker file.
|
||||
return (path / "modular_model_index.json").is_file() or (path / "fastvideo_inference.json").is_file()
|
||||
# The FastVideo release is the modular checkpoint handled by this
|
||||
# resolver. Do not classify the native MiniMax-H3 Hub repository from
|
||||
# its class name alone; its partition files are still required here.
|
||||
if not model.startswith(_FASTH3_MODULAR_MODEL_PREFIX):
|
||||
return False
|
||||
index = get_diffusion_model_index(model, revision=revision) or {}
|
||||
return index.get("_class_name") == "MiniMaxH3ModularPipeline"
|
||||
|
||||
|
||||
def resolve_minimax_h3_partition(
|
||||
model: str,
|
||||
task_type: str | None,
|
||||
@@ -42,10 +64,13 @@ def resolve_minimax_h3_encoder_model_root(
|
||||
) -> str:
|
||||
path = Path(model)
|
||||
partition = resolve_minimax_h3_partition(model, task_type, auto_partition="fl2va")
|
||||
modular = is_minimax_h3_modular(model, revision)
|
||||
|
||||
if path.is_dir():
|
||||
if path.name == "text_encoder" and (path / "config.json").is_file():
|
||||
return str(path)
|
||||
if modular:
|
||||
return str(path / "text_encoder")
|
||||
if path.name in {"FL2VA", "Ref2VA"}:
|
||||
path = path.parent
|
||||
subdir = "Ref2VA" if partition == "ref2va" else "FL2VA"
|
||||
@@ -53,11 +78,13 @@ def resolve_minimax_h3_encoder_model_root(
|
||||
snapshot = download_weights_from_hf_specific(
|
||||
model_name_or_path=model,
|
||||
cache_dir=None,
|
||||
allow_patterns=MINIMAX_H3_ENCODER_DOWNLOAD_PATTERNS[partition],
|
||||
allow_patterns=["text_encoder/**"] if modular else MINIMAX_H3_ENCODER_DOWNLOAD_PATTERNS[partition],
|
||||
revision=revision,
|
||||
require_all=True,
|
||||
)
|
||||
|
||||
if modular:
|
||||
return str(Path(snapshot) / "text_encoder")
|
||||
subdir = "Ref2VA" if partition == "ref2va" else "FL2VA"
|
||||
return str(Path(snapshot) / subdir / "text_encoder")
|
||||
|
||||
|
||||
@@ -177,6 +177,7 @@ class NPUARModelRunner(OmniNPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
|
||||
num_scheduled_tokens_np=np.ones(bsz, dtype=np.int32),
|
||||
max_num_scheduled_tokens=1,
|
||||
use_cascade_attn=False,
|
||||
force_uniform_decode=True,
|
||||
)
|
||||
n = batch_desc.num_tokens
|
||||
ids = self.talker_mtp_input_ids.gpu[:n]
|
||||
|
||||
@@ -446,6 +446,33 @@ def _disk_marks_serialized(qc_kwargs: dict[str, Any], quant_config: object) -> b
|
||||
return False
|
||||
|
||||
|
||||
_MXFP4_SERIALIZED_FLAGS = {
|
||||
"mxfp4": "is_checkpoint_mxfp4_serialized",
|
||||
"mxfp4_dualscale": "is_checkpoint_serialized",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_serialized_mxfp4_layer_policy(qc_method: str, qc_kwargs: dict[str, Any]) -> None:
|
||||
"""Canonicalize the BF16 layer policy owned by serialized MXFP4 metadata.
|
||||
|
||||
A serialized checkpoint config is a complete storage contract: an omitted
|
||||
layer list means no explicit BF16 layers. Method-only online metadata does
|
||||
not carry that contract and must leave caller-provided layer policy intact.
|
||||
"""
|
||||
method = _normalize_quant_method_alias(qc_method)
|
||||
if method is None:
|
||||
return
|
||||
serialized_flag = _MXFP4_SERIALIZED_FLAGS.get(method)
|
||||
if serialized_flag is None or not qc_kwargs.get(serialized_flag):
|
||||
return
|
||||
|
||||
ignored_layers = qc_kwargs.get("ignored_layers")
|
||||
if not ignored_layers:
|
||||
ignored_layers = qc_kwargs.get("modules_to_not_convert")
|
||||
qc_kwargs["ignored_layers"] = ignored_layers or []
|
||||
qc_kwargs.pop("modules_to_not_convert", None)
|
||||
|
||||
|
||||
def resolve_quant_config_from_disk(
|
||||
quant_config: QuantizationConfig | None,
|
||||
disk_qc: dict[str, Any] | str | None,
|
||||
@@ -460,22 +487,24 @@ def resolve_quant_config_from_disk(
|
||||
- quant_config is None: auto-detect from disk_qc (full build).
|
||||
- Methods mismatch: raise ValueError — prevents silent weight corruption.
|
||||
- Disk marks serialized but quant_config is online: rebuild from disk.
|
||||
- ignored_layers differ: rebuild from disk (per-transformer BF16 routing).
|
||||
- Serialized MXFP4 metadata owns the complete BF16 layer policy; omitted
|
||||
ignored_layers means the checkpoint default (no explicit BF16 layers).
|
||||
- Method-only metadata carries no storage policy and preserves caller
|
||||
ignored_layers and runtime fallback policies.
|
||||
"""
|
||||
if disk_qc is None:
|
||||
return quant_config
|
||||
|
||||
if isinstance(disk_qc, str):
|
||||
if quant_config is None:
|
||||
logger.info("Auto-detected quantization from config.json: method=%s", disk_qc)
|
||||
return build_quant_config(disk_qc)
|
||||
return quant_config
|
||||
qc_method = disk_qc
|
||||
qc_kwargs: dict[str, Any] = {}
|
||||
else:
|
||||
if not isinstance(disk_qc, Mapping) or "quant_method" not in disk_qc:
|
||||
return quant_config
|
||||
qc_method = disk_qc["quant_method"]
|
||||
qc_kwargs = {k: v for k, v in disk_qc.items() if k != "quant_method"}
|
||||
|
||||
if not isinstance(disk_qc, Mapping) or "quant_method" not in disk_qc:
|
||||
return quant_config
|
||||
|
||||
qc_method: str = disk_qc["quant_method"]
|
||||
qc_kwargs: dict[str, Any] = {k: v for k, v in disk_qc.items() if k != "quant_method"}
|
||||
_normalize_serialized_mxfp4_layer_policy(qc_method, qc_kwargs)
|
||||
|
||||
if quant_config is None:
|
||||
logger.info(
|
||||
@@ -494,6 +523,26 @@ def resolve_quant_config_from_disk(
|
||||
"Pass a matching --quantization flag or omit it for auto-detection."
|
||||
)
|
||||
|
||||
if isinstance(disk_qc, str):
|
||||
return quant_config
|
||||
|
||||
# Serialized checkpoint metadata owns storage and BF16 layer routing. The
|
||||
# active config owns runtime step/layer policies, including explicit empty
|
||||
# lists. Preserve them when each cascade transformer rebuilds from disk.
|
||||
for policy in ("w4a8_fallback_steps", "w4a8_fallback_layers"):
|
||||
if hasattr(quant_config, policy):
|
||||
qc_kwargs[policy] = list(getattr(quant_config, policy))
|
||||
if hasattr(quant_config, "mxfp4_scale_alg"):
|
||||
# Runtime activation policy is independent of how offline W4 was made.
|
||||
qc_kwargs["mxfp4_scale_alg"] = quant_config.mxfp4_scale_alg
|
||||
if hasattr(quant_config, "require_smooth_scale"):
|
||||
disk_requires_smooth = qc_kwargs.get("require_smooth_scale", False)
|
||||
if not isinstance(disk_requires_smooth, bool):
|
||||
raise ValueError("require_smooth_scale must be a boolean")
|
||||
# Either a calibrated checkpoint or an explicit caller can require
|
||||
# Smooth. Per-expert rebuilds must never weaken that requirement.
|
||||
qc_kwargs["require_smooth_scale"] = quant_config.require_smooth_scale or disk_requires_smooth
|
||||
|
||||
if _disk_marks_serialized(qc_kwargs, quant_config):
|
||||
logger.info(
|
||||
"config.json marks checkpoint as serialized; switching to offline %s mode.",
|
||||
@@ -501,6 +550,14 @@ def resolve_quant_config_from_disk(
|
||||
)
|
||||
return build_quant_config(qc_method, **qc_kwargs)
|
||||
|
||||
if (
|
||||
"require_smooth_scale" in qc_kwargs
|
||||
and hasattr(quant_config, "require_smooth_scale")
|
||||
and qc_kwargs["require_smooth_scale"] != quant_config.require_smooth_scale
|
||||
):
|
||||
logger.info("config.json Smooth requirement differs from active config; rebuilding quant_config.")
|
||||
return build_quant_config(qc_method, **qc_kwargs)
|
||||
|
||||
# AutoRound MXFP checkpoints use data_type="mx_fp" instead of
|
||||
# is_checkpoint_*_serialized; rebuild so the offline MXFP4/MXFP8 path is
|
||||
# selected according to the checkpoint's bit width.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""W4A4 MXFP4 (Microscaling FP4) online/offline quantization for diffusion transformers.
|
||||
|
||||
Architecture mirrors mxfp8_config.py:
|
||||
@@ -41,7 +41,7 @@ Dual-scale (W4A4_MXFP4_DUALSCALE):
|
||||
and npu_dual_level_quant_matmul. Weight stored in NZ hardware format via npu_format_cast.
|
||||
|
||||
Checkpoint tensor shapes for dual-scale:
|
||||
weight : (N, K) float8_e4m3fn – FP4 packed
|
||||
weight : (N, K) float8_e4m3fn – numeric FP4 values (packed after loading)
|
||||
weight_scale : (N, K//32) uint8 – fine scale (float8_e8m0fnu bits)
|
||||
weight_dual_scale : (N, K//512, 1) float32 – coarse scale (extra dim avoids shape assert)
|
||||
mul_scale : (K,) float32 – per-input-channel activation pre-scale
|
||||
@@ -51,9 +51,9 @@ Reference: MindIE-SD W4A4MXFP4QuantLinear / W4A4MXFP4DualQuantLinear (mindiesd/q
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
from vllm.logger import init_logger
|
||||
@@ -83,9 +83,54 @@ from vllm_omni.quantization.mxfp8_config import (
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.models.utils import WeightsMapper
|
||||
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _validate_w4a8_fallback_steps(steps: list[int] | None) -> list[int]:
|
||||
if steps is None:
|
||||
return []
|
||||
if not isinstance(steps, list) or any(type(step) is not int or step < 0 for step in steps):
|
||||
raise ValueError("w4a8_fallback_steps must be a list of non-negative integer denoise step indices.")
|
||||
return sorted(set(steps))
|
||||
|
||||
|
||||
def _validate_w4a8_fallback_layers(layers: list[str] | None) -> list[str]:
|
||||
"""Names are exact runtime Linear paths, not checkpoint aliases or patterns."""
|
||||
if layers is None:
|
||||
return []
|
||||
if not isinstance(layers, list) or any(
|
||||
not isinstance(name, str) or re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_0-9]+)*", name) is None
|
||||
for name in layers
|
||||
):
|
||||
raise ValueError("w4a8_fallback_layers must be a list of non-empty exact runtime Linear paths.")
|
||||
return sorted(set(layers))
|
||||
|
||||
|
||||
def _is_w4a8_fallback_step(steps: list[int]) -> bool:
|
||||
"""Read the request's zero-based denoise index; never keep state on a Linear."""
|
||||
if not steps:
|
||||
return False
|
||||
|
||||
from vllm_omni.diffusion.forward_context import (
|
||||
get_forward_context,
|
||||
is_forward_context_available,
|
||||
)
|
||||
|
||||
step = get_forward_context().denoise_step_idx if is_forward_context_available() else None
|
||||
if step is None:
|
||||
raise RuntimeError("W4A8 step fallback requires a pipeline that publishes its denoise step in ForwardContext.")
|
||||
return step in steps
|
||||
|
||||
|
||||
def _validate_smooth_scale(scale: torch.Tensor) -> None:
|
||||
"""Reject malformed calibration before loading or activation dtype conversion."""
|
||||
if scale.ndim != 1 or not scale.is_floating_point():
|
||||
raise ValueError("MXFP4 mul_scale must be a one-dimensional floating-point Smooth tensor.")
|
||||
if not bool(torch.isfinite(scale).all()) or not bool((scale > 0).all()):
|
||||
raise ValueError("MXFP4 mul_scale must contain finite, strictly positive Smooth values.")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -105,10 +150,24 @@ class DiffusionMXFP4Config(QuantizationConfig):
|
||||
self,
|
||||
is_checkpoint_mxfp4_serialized: bool = False,
|
||||
ignored_layers: list[str] | None = None,
|
||||
w4a8_fallback_steps: list[int] | None = None,
|
||||
require_smooth_scale: bool = False,
|
||||
w4a8_fallback_layers: list[str] | None = None,
|
||||
mxfp4_scale_alg: int = 0,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.is_checkpoint_mxfp4_serialized = is_checkpoint_mxfp4_serialized
|
||||
self.ignored_layers = ignored_layers or []
|
||||
self.w4a8_fallback_steps = _validate_w4a8_fallback_steps(w4a8_fallback_steps)
|
||||
self.w4a8_fallback_layers = _validate_w4a8_fallback_layers(w4a8_fallback_layers)
|
||||
if not isinstance(require_smooth_scale, bool):
|
||||
raise ValueError("require_smooth_scale must be a boolean")
|
||||
if require_smooth_scale and not self.is_checkpoint_mxfp4_serialized:
|
||||
raise ValueError("require_smooth_scale requires an offline MXFP4 checkpoint")
|
||||
self.require_smooth_scale = require_smooth_scale
|
||||
if type(mxfp4_scale_alg) is not int or mxfp4_scale_alg not in (0, 2):
|
||||
raise ValueError("mxfp4_scale_alg must be 0 (OCP MX) or 2 (UOS with dst_type_max=7.25).")
|
||||
self.mxfp4_scale_alg = mxfp4_scale_alg
|
||||
|
||||
@classmethod
|
||||
def get_name(cls) -> QuantizationMethods:
|
||||
@@ -139,6 +198,10 @@ class DiffusionMXFP4Config(QuantizationConfig):
|
||||
return cls(
|
||||
is_checkpoint_mxfp4_serialized=is_serialized,
|
||||
ignored_layers=ignored_layers,
|
||||
w4a8_fallback_steps=config.get("w4a8_fallback_steps"),
|
||||
w4a8_fallback_layers=config.get("w4a8_fallback_layers"),
|
||||
require_smooth_scale=config.get("require_smooth_scale", False),
|
||||
mxfp4_scale_alg=config.get("mxfp4_scale_alg", 0),
|
||||
)
|
||||
|
||||
def get_quant_method(
|
||||
@@ -155,9 +218,15 @@ class DiffusionMXFP4Config(QuantizationConfig):
|
||||
return UnquantizedLinearMethod()
|
||||
if current_omni_platform.is_npu():
|
||||
if self.is_checkpoint_mxfp4_serialized:
|
||||
return NPUMxfp4LinearMethod(self)
|
||||
return NPUMxfp4OnlineLinearMethod(self)
|
||||
return NPUMxfp4LinearMethod(self, prefix=prefix)
|
||||
return NPUMxfp4OnlineLinearMethod(self, prefix=prefix)
|
||||
if current_omni_platform.is_rocm():
|
||||
if self.mxfp4_scale_alg != 0:
|
||||
raise NotImplementedError("MXFP4 UOS quantization is currently only supported on NPU (Ascend).")
|
||||
if self.w4a8_fallback_steps or self.w4a8_fallback_layers:
|
||||
raise NotImplementedError(
|
||||
"MXFP4 W4A8 step/layer fallback is currently only supported on NPU (Ascend)."
|
||||
)
|
||||
gcn_arch = torch.cuda.get_device_properties(torch.accelerator.current_device_index()).gcnArchName
|
||||
if "gfx950" not in gcn_arch:
|
||||
raise NotImplementedError(f"MXFP4 on ROCm requires gfx950 (MI355X). Detected: {gcn_arch}")
|
||||
@@ -176,6 +245,56 @@ class DiffusionMXFP4Config(QuantizationConfig):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _npu_quantize_mxfp4(x: torch.Tensor, scale_alg: int) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Quantize weight or activation using the same explicit FP4 algorithm."""
|
||||
import torch_npu
|
||||
|
||||
# Universal Optimal Scaling (Qmax=7.25), MXAttention Section 4.1:
|
||||
# https://arxiv.org/abs/2607.24377
|
||||
scale_kwargs = {"dst_type_max": 7.25} if scale_alg == 2 else {}
|
||||
return torch_npu.npu_dynamic_mx_quant(
|
||||
x,
|
||||
dst_type=torch_npu.float4_e2m1fn_x2,
|
||||
axis=-1,
|
||||
block_size=32,
|
||||
round_mode="rint",
|
||||
scale_alg=scale_alg,
|
||||
**scale_kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _npu_w4a8_matmul(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
weight_scale: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
output_dtype: torch.dtype,
|
||||
) -> torch.Tensor:
|
||||
"""MXFP8 activations with prepared single-scale MXFP4 weights (N, K)."""
|
||||
import torch_npu
|
||||
|
||||
x_q, x_scale = torch_npu.npu_dynamic_mx_quant(
|
||||
x, dst_type=torch_npu.float8_e4m3fn, axis=-1, block_size=32, round_mode="rint", scale_alg=0
|
||||
)
|
||||
# Use the BF16 output/bias pair supported by the mixed FP8/FP4 kernel
|
||||
# in the target A5 runtime. Restore the caller's dtype afterwards.
|
||||
if bias is not None:
|
||||
bias = bias.to(torch.bfloat16).reshape(1, -1)
|
||||
output = torch_npu.npu_quant_matmul(
|
||||
x_q,
|
||||
weight.transpose(0, 1),
|
||||
weight_scale.transpose(0, 1),
|
||||
scale_dtype=torch_npu.float8_e8m0fnu,
|
||||
x2_dtype=torch_npu.float4_e2m1fn_x2,
|
||||
pertoken_scale=x_scale,
|
||||
pertoken_scale_dtype=torch_npu.float8_e8m0fnu,
|
||||
bias=bias,
|
||||
output_dtype=torch.bfloat16,
|
||||
group_sizes=[0, 0, 32],
|
||||
)
|
||||
return output.to(output_dtype)
|
||||
|
||||
|
||||
class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
"""NPU W4A4 MXFP4 offline linear method for pre-quantized checkpoints.
|
||||
|
||||
@@ -187,7 +306,8 @@ class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
NPUMxfp4OnlineLinearMethod normalizes to the same layout so apply() is shared.
|
||||
"""
|
||||
|
||||
def __init__(self, quant_config: DiffusionMXFP4Config) -> None:
|
||||
def __init__(self, quant_config: DiffusionMXFP4Config, *, prefix: str = "") -> None:
|
||||
self.is_w4a8_fallback_layer = prefix in quant_config.w4a8_fallback_layers
|
||||
self.quant_config = quant_config
|
||||
self.out_dtype = torch.get_default_dtype()
|
||||
|
||||
@@ -210,11 +330,14 @@ class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
layer.orig_dtype = params_dtype
|
||||
layer.weight_block_size = None
|
||||
|
||||
# BF16 placeholder; cast to float4_e2m1fn_x2 in process_weights.
|
||||
layer.register_parameter(
|
||||
"weight",
|
||||
ModelWeightParameter(
|
||||
data=torch.empty(output_size_per_partition, input_size_per_partition, dtype=params_dtype),
|
||||
data=torch.empty(
|
||||
output_size_per_partition,
|
||||
input_size_per_partition,
|
||||
dtype=params_dtype,
|
||||
),
|
||||
input_dim=1,
|
||||
output_dim=0,
|
||||
weight_loader=weight_loader,
|
||||
@@ -234,12 +357,42 @@ class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
),
|
||||
)
|
||||
|
||||
# Older single-scale checkpoints have no Smooth tensor. Keep their
|
||||
# identity transform while allowing calibrated checkpoints to load it.
|
||||
def smooth_weight_loader(
|
||||
param: ModelWeightParameter, loaded_weight: torch.Tensor, *args: Any, **kwargs: Any
|
||||
) -> None:
|
||||
_validate_smooth_scale(loaded_weight)
|
||||
if not callable(weight_loader):
|
||||
raise ValueError("Loading MXFP4 Smooth requires a callable weight_loader")
|
||||
weight_loader(param, loaded_weight, *args, **kwargs)
|
||||
|
||||
layer.register_parameter(
|
||||
"mul_scale",
|
||||
ModelWeightParameter(
|
||||
data=torch.ones(input_size_per_partition, dtype=torch.float32),
|
||||
input_dim=0,
|
||||
output_dim=None,
|
||||
weight_loader=smooth_weight_loader,
|
||||
),
|
||||
)
|
||||
setattr(layer.mul_scale, "ignore_warning", True)
|
||||
setattr(layer.mul_scale, "is_checkpoint_optional", not self.quant_config.require_smooth_scale)
|
||||
if self.quant_config.is_checkpoint_mxfp4_serialized:
|
||||
setattr(layer.weight_scale, "is_checkpoint_required", True)
|
||||
|
||||
def process_weights_after_loading(self, layer: Module) -> None:
|
||||
if getattr(layer, "_already_called_process_weights_after_loading", False):
|
||||
return
|
||||
|
||||
import torch_npu
|
||||
|
||||
smooth_param = cast(torch.Tensor, layer.mul_scale)
|
||||
_validate_smooth_scale(smooth_param)
|
||||
smooth = smooth_param.data.to(dtype=cast(torch.dtype, layer.orig_dtype)).contiguous()
|
||||
# Finite FP32 values can overflow or underflow in the activation dtype.
|
||||
_validate_smooth_scale(smooth)
|
||||
|
||||
# NPU: cast to float4_e2m1fn_x2. Weight stays (N, K) — no pre-transpose.
|
||||
w = layer.weight
|
||||
if w.dtype != torch_npu.float4_e2m1fn_x2:
|
||||
@@ -258,15 +411,31 @@ class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
|
||||
|
||||
replace_parameter(layer, "weight", w)
|
||||
replace_parameter(layer, "weight_scale", s)
|
||||
# Keep loader metadata while converting the calibration tensor once.
|
||||
layer.mul_scale.data = smooth.to(device=cast(torch.Tensor, w).device)
|
||||
layer._already_called_process_weights_after_loading = True
|
||||
|
||||
# --- NPU MXFP4 ops — shared with online path via inheritance ---
|
||||
|
||||
def _quantize_activation(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
import torch_npu
|
||||
def _apply_inner(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
ori_dtype: torch.dtype,
|
||||
) -> torch.Tensor:
|
||||
# Online quantization has no calibrated Smooth tensor. For offline
|
||||
# weights the same pre-scale must precede both A4 and A8 quantization.
|
||||
if (mul_scale := getattr(layer, "mul_scale", None)) is not None:
|
||||
x = x * mul_scale.to(x.dtype)
|
||||
if self.is_w4a8_fallback_layer or _is_w4a8_fallback_step(self.quant_config.w4a8_fallback_steps):
|
||||
return _npu_w4a8_matmul(
|
||||
x, cast(torch.Tensor, layer.weight), cast(torch.Tensor, layer.weight_scale), bias, ori_dtype
|
||||
)
|
||||
return super()._apply_inner(layer, x, bias, ori_dtype)
|
||||
|
||||
# No dst_type: npu_dynamic_mx_quant defaults to float4_e2m1fn_x2.
|
||||
return torch_npu.npu_dynamic_mx_quant(x)
|
||||
def _quantize_activation(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return _npu_quantize_mxfp4(x, self.quant_config.mxfp4_scale_alg)
|
||||
|
||||
def _quant_matmul(
|
||||
self,
|
||||
@@ -318,8 +487,6 @@ class NPUMxfp4OnlineLinearMethod(_LazyWeightMixin, NPUMxfp4LinearMethod):
|
||||
if getattr(layer, "_already_called_process_weights_after_loading", False):
|
||||
return
|
||||
|
||||
import torch_npu
|
||||
|
||||
if layer.weight.device == torch.device("meta"):
|
||||
weight = ModelWeightParameter(
|
||||
data=torch.empty_like(layer.weight, device=layer._load_device),
|
||||
@@ -331,8 +498,10 @@ class NPUMxfp4OnlineLinearMethod(_LazyWeightMixin, NPUMxfp4LinearMethod):
|
||||
layer.register_parameter("weight", weight)
|
||||
initialize_single_dummy_weight(layer.weight)
|
||||
|
||||
# NPU: quantize BF16/FP16 (N, K) → FP4. No dst_type → float4_e2m1fn_x2.
|
||||
weight_fp4, weight_scale_raw = torch_npu.npu_dynamic_mx_quant(layer.weight)
|
||||
# Prepare once; offline checkpoints keep their existing weight algorithm.
|
||||
weight_fp4, weight_scale_raw = _npu_quantize_mxfp4(
|
||||
cast(torch.Tensor, layer.weight), self.quant_config.mxfp4_scale_alg
|
||||
)
|
||||
|
||||
# Weight stays (N, K) — no pre-transpose for FP4 packed format.
|
||||
# Scale: (N, S) → (N, S/2, 2). Not pre-transposed; done inline in _quant_matmul.
|
||||
@@ -497,7 +666,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
"""NPU W4A4 MXFP4 dual-scale offline method for pre-quantized checkpoints.
|
||||
|
||||
Checkpoint tensors and their canonical post-load shapes:
|
||||
weight : (N, K) float8_e4m3fn – FP4 packed (2 values per byte)
|
||||
weight : (N, K) float8_e4m3fn – numeric FP4 values; packed into NZ after loading
|
||||
weight_scale : (N, K//32) uint8 – fine scale (float8_e8m0fnu bits); reshaped to (N, K//64, 2)
|
||||
weight_dual_scale : (N, K//512, 1) float32 – coarse scale; transposed to (K//512, N)
|
||||
mul_scale : (K,) float32 – per-input-channel activation pre-scale (from calibration)
|
||||
@@ -509,7 +678,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
Reference: MindIE-SD W4A4MXFP4DualQuantLinear.
|
||||
"""
|
||||
|
||||
def __init__(self, quant_config: Any) -> None:
|
||||
def __init__(self, quant_config: DiffusionMXFP4DualScaleMixedConfig) -> None:
|
||||
self.quant_config = quant_config
|
||||
self.out_dtype = torch.get_default_dtype()
|
||||
|
||||
@@ -532,7 +701,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
layer.orig_dtype = params_dtype
|
||||
layer.weight_block_size = None
|
||||
|
||||
# FP4 packed: 2 values per float8_e4m3fn byte → checkpoint stores as float8_e4m3fn; register as BF16
|
||||
# Checkpoint FP4 values are stored numerically in FP8; BF16 preserves them exactly.
|
||||
layer.register_parameter(
|
||||
"weight",
|
||||
ModelWeightParameter(
|
||||
@@ -587,6 +756,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
),
|
||||
)
|
||||
setattr(layer.mul_scale, "ignore_warning", True)
|
||||
setattr(layer.weight_scale, "is_checkpoint_required", True)
|
||||
|
||||
def process_weights_after_loading(self, layer: Module) -> None:
|
||||
if getattr(layer, "_already_called_process_weights_after_loading", False):
|
||||
@@ -594,7 +764,7 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
|
||||
import torch_npu
|
||||
|
||||
# float8_e4m3fn (FP4 packed) → float4_e2m1fn_x2 → NZ hardware format (format ID 29).
|
||||
# Numeric FP4 values → packed float4_e2m1fn_x2 → NZ hardware format (format ID 29).
|
||||
# NZ layout is required by npu_dual_level_quant_matmul for FP4 weight matrices.
|
||||
w = torch_npu.npu_dtype_cast(layer.weight.data.npu(), torch_npu.float4_e2m1fn_x2)
|
||||
w = torch_npu.npu_format_cast(w.view(torch.int8), 29, customize_dtype=torch.int8)
|
||||
@@ -631,7 +801,10 @@ class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
|
||||
"""
|
||||
if ori_dtype not in (torch.bfloat16, torch.float16):
|
||||
x = x.to(torch.bfloat16)
|
||||
x_q, l0_scale, l1_scale = self._quantize_activation(x, layer.mul_scale)
|
||||
# The dual-level activation kernel requires x and Smooth to have the
|
||||
# same dtype. Prepared calibration scales are BF16, including online.
|
||||
smooth_scale = cast(torch.Tensor, layer.mul_scale).to(x.dtype)
|
||||
x_q, l0_scale, l1_scale = self._quantize_activation(x, smooth_scale)
|
||||
return self._quant_matmul(x_q, l0_scale, l1_scale, layer, bias, ori_dtype)
|
||||
|
||||
def _quantize_activation( # type: ignore[override]
|
||||
@@ -785,11 +958,20 @@ class DiffusionMXFP4DualScaleMixedConfig(QuantizationConfig):
|
||||
is_checkpoint_serialized: bool = False,
|
||||
ignored_layers: list[str] | None = None,
|
||||
num_bf16_fallback_layers: int = 5,
|
||||
w4a8_fallback_steps: list[int] | None = None,
|
||||
w4a8_fallback_layers: list[str] | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.is_checkpoint_serialized = is_checkpoint_serialized
|
||||
self.ignored_layers = ignored_layers or []
|
||||
self.num_bf16_fallback_layers = num_bf16_fallback_layers
|
||||
self.w4a8_fallback_steps = _validate_w4a8_fallback_steps(w4a8_fallback_steps)
|
||||
self.w4a8_fallback_layers = _validate_w4a8_fallback_layers(w4a8_fallback_layers)
|
||||
if self.w4a8_fallback_steps or self.w4a8_fallback_layers:
|
||||
raise ValueError(
|
||||
"mxfp4_dualscale does not support W4A8 fallback. Use mxfp4 with single-scale weights; "
|
||||
"changing a DualScale checkpoint's method name does not convert its storage format."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_name(cls) -> QuantizationMethods:
|
||||
@@ -822,6 +1004,8 @@ class DiffusionMXFP4DualScaleMixedConfig(QuantizationConfig):
|
||||
is_checkpoint_serialized=is_serialized,
|
||||
ignored_layers=ignored_layers,
|
||||
num_bf16_fallback_layers=num_bf16_fallback_layers,
|
||||
w4a8_fallback_steps=config.get("w4a8_fallback_steps"),
|
||||
w4a8_fallback_layers=config.get("w4a8_fallback_layers"),
|
||||
)
|
||||
|
||||
def get_quant_method(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import argparse
|
||||
from typing import Any
|
||||
@@ -52,12 +52,28 @@ class TrackingNamespace(argparse.Namespace):
|
||||
else:
|
||||
setattr(self.unfiltered_ns, name, value)
|
||||
|
||||
def __getstate__(self) -> dict[str, Any]:
|
||||
"""Preserve wrapper state when API workers use ``spawn``.
|
||||
|
||||
Our __dict__ property exposes the inner namespace, so default state
|
||||
serialization would lose unfiltered_ns and explicit_keys.
|
||||
"""
|
||||
return {
|
||||
"unfiltered_ns": self.unfiltered_ns,
|
||||
"explicit_keys": self.explicit_keys,
|
||||
}
|
||||
|
||||
def __setstate__(self, state: dict[str, Any]) -> None:
|
||||
object.__setattr__(self, "unfiltered_ns", state["unfiltered_ns"])
|
||||
object.__setattr__(self, "explicit_keys", state["explicit_keys"])
|
||||
|
||||
def get_explicit_kwargs_dict(self):
|
||||
"""Return a dict containing only the explicitly passed key-value pairs."""
|
||||
return {k: v for k, v in vars(self.unfiltered_ns).items() if k in self.explicit_keys}
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self.unfiltered_ns, name)
|
||||
namespace = object.__getattribute__(self, "unfiltered_ns")
|
||||
return getattr(namespace, name)
|
||||
|
||||
@property
|
||||
def __dict__(self):
|
||||
|
||||
@@ -812,7 +812,7 @@ class GPUGenerationModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin
|
||||
|
||||
if self.uses_mrope:
|
||||
positions = self.mrope_positions.gpu[:, :num_tokens_padded]
|
||||
elif self.uses_xdrope_dim > 0:
|
||||
elif getattr(self, "uses_xdrope_dim", 0) > 0:
|
||||
positions = self.xdrope_positions.gpu[:, :num_tokens_padded]
|
||||
else:
|
||||
positions = self.positions[:num_tokens_padded]
|
||||
|
||||
@@ -690,7 +690,7 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
self._init_mrope_positions(req_state)
|
||||
|
||||
# Only relevant for models using XD-RoPE (e.g, HunYuan-VL)
|
||||
if self.uses_xdrope_dim > 0:
|
||||
if getattr(self, "uses_xdrope_dim", 0) > 0:
|
||||
self._init_xdrope_positions(req_state)
|
||||
|
||||
reqs_to_add.append(self.requests[req_id])
|
||||
@@ -1164,7 +1164,7 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
|
||||
if self.uses_mrope:
|
||||
positions = self.mrope_positions.gpu[:, :num_tokens_padded]
|
||||
elif self.uses_xdrope_dim > 0:
|
||||
elif getattr(self, "uses_xdrope_dim", 0) > 0:
|
||||
positions = self.xdrope_positions.gpu[:, :num_tokens_padded]
|
||||
else:
|
||||
positions = self.positions[:num_tokens_padded]
|
||||
@@ -1701,7 +1701,7 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
|
||||
if self.uses_mrope:
|
||||
positions = self.mrope_positions.gpu[:, :num_input_tokens]
|
||||
elif self.uses_xdrope_dim > 0:
|
||||
elif getattr(self, "uses_xdrope_dim", 0) > 0:
|
||||
positions = self.xdrope_positions.gpu[:, :num_input_tokens]
|
||||
else:
|
||||
positions = self.positions[:num_input_tokens]
|
||||
|
||||
Reference in new issue
Block a user