[Bugfix][MiniMax-Music3] Resolve stage subdirs against a real snapshot (#6640)

Signed-off-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
Yueqian Lin authored and GitHub committed 2026-08-30 06:51:24 +00:00
1 parent 8be601ed7f
commit a6b559cf54
7 files changed
+1172 -27

No files matched your search

+193 -14
View File
@@ -14,19 +14,24 @@ from __future__ import annotations
import copy
import fcntl
import importlib
import json
import multiprocessing as mp
import os
import time
from collections.abc import Callable, Generator, Mapping, Sequence
from collections.abc import Callable, Collection, Generator, Mapping, Sequence
from contextlib import contextmanager
from dataclasses import dataclass, fields, replace
from pathlib import Path
from typing import Any, Literal, cast
import regex as re
from vllm.logger import init_logger
from vllm.pooling_params import PoolingParams
from vllm.renderers import BaseRenderer
from vllm.sampling_params import SamplingParams
from vllm.tokenizers import cached_tokenizer_from_config
from vllm.transformers_utils.repo_utils import hf_api
from vllm.transformers_utils.runai_utils import is_runai_obj_uri
from vllm.usage.usage_lib import UsageContext
from vllm.v1.engine.input_processor import InputProcessor
from vllm.v1.executor import Executor
@@ -82,22 +87,144 @@ class LogicalStageInitPlan:
replicas: list[ReplicaInitPlan]
def _resolve_model_to_local_path(model: str) -> str:
"""Resolve an HF Hub model ID to a local cache path."""
def _missing_stage_subdirs(base: str, subdirs: Sequence[str]) -> list[str]:
"""Return the entries of ``subdirs`` that are not directories under ``base``."""
return [subdir for subdir in subdirs if not os.path.isdir(os.path.join(base, subdir))]
# Artifacts that make a snapshot subfolder trustworthy. A directory that
# exists but holds none of these is an interrupted download, not a snapshot;
# treating it as complete strips the Hub fallback vLLM would need later.
_WEIGHT_ARTIFACT_PATTERNS = ("*.safetensors", "*.bin", "*.pt", "*.gguf")
# Vocabulary-bearing files. Configs and chat templates are small and download
# first, so their presence alone cannot distinguish a tokenizer folder from an
# interrupted download.
_TOKENIZER_ARTIFACT_NAMES = (
"tokenizer.json",
"tokenizer.model",
"spiece.model",
"sentencepiece.bpe.model",
"vocab.json",
"vocab.txt",
)
# HF sharded checkpoints name their pieces `<stem>-NNNNN-of-NNNNN.<ext>` and
# always ship an index; a shard-named file without one is a partial download.
_SHARD_NAME_RE = re.compile(r"-\d+-of-\d+\.(safetensors|bin)$")
def _indexed_shards_complete(folder: Path) -> bool | None:
"""Check sharded weights against their index; ``None`` when no index exists."""
indexes = list(folder.rglob("*.index.json"))
if not indexes:
return None
for index in indexes:
try:
weight_map = json.loads(index.read_text()).get("weight_map") or {}
except (OSError, ValueError):
return False
shards = set(weight_map.values())
if not shards or any(not (index.parent / shard).is_file() for shard in shards):
return False
return True
def _subdir_is_populated(base: str, subdir: str, needs_weights: bool) -> bool:
folder = Path(base) / subdir
if not folder.is_dir():
return False
if needs_weights:
indexed = _indexed_shards_complete(folder)
if indexed is not None:
return indexed
weights = [path for pattern in _WEIGHT_ARTIFACT_PATTERNS for path in folder.rglob(pattern)]
if not weights:
return False
return not any(_SHARD_NAME_RE.search(path.name) for path in weights)
return any((folder / name).is_file() for name in _TOKENIZER_ARTIFACT_NAMES)
def _incomplete_stage_subdirs(
base: str,
subdirs: Sequence[str],
weight_subdirs: Collection[str] = (),
) -> list[str]:
"""Return the entries of ``subdirs`` without a POPULATED directory under ``base``.
Hub-snapshot paths use this stricter check: ``os.path.isdir`` alone accepts
a subfolder holding only config.json from an interrupted download, and the
warm-cache early return would then convert the Hub ID into a local path
vLLM cannot fetch missing weights for. ``weight_subdirs`` names the entries
that must contain a weight artifact, not merely any file.
"""
return [
subdir for subdir in subdirs if not _subdir_is_populated(base, subdir, needs_weights=subdir in weight_subdirs)
]
def _resolve_model_to_local_path(
model: str,
required_subdirs: Sequence[str] = (),
weight_subdirs: Collection[str] = (),
*,
revision: str | None = None,
download_dir: str | None = None,
) -> str:
"""Resolve an HF Hub model ID to a local path that holds ``required_subdirs``.
``snapshot_download(local_files_only=True)`` returns the snapshot root as
soon as *any* file of the repo is cached, even when the subfolders this
stage needs were never materialized. Joining a stage subdir onto such a
root produces a path that exists nowhere, and upstream ``EngineArgs``
forwards a non-directory ``model`` to HuggingFace as a repo id, which fails
with an ``HFValidationError`` about the cache path. Verify the subfolders
here and pull just the missing ones, so the join always lands on a real
directory or raises an error that names what is missing.
``revision`` and ``download_dir`` mirror the engine args of the same name:
once the repo ID is replaced by a local path, downstream ModelConfig can no
longer correct either, so they must shape the snapshot selection here.
"""
if os.path.isdir(model):
return model
# Keep the warm-cache path offline-friendly: no Hub round trip when the
# stage's subfolders are already there.
try:
from huggingface_hub import snapshot_download
# Keep init path resolution offline-friendly.
return snapshot_download(model, local_files_only=True)
except Exception:
logger.warning(
"[stage_init] Could not resolve %s to local snapshot; using as-is",
model,
cached_root: str | None = hf_api().snapshot_download(
model, local_files_only=True, revision=revision, cache_dir=download_dir
)
return model
except Exception:
cached_root = None
if cached_root is not None and not _incomplete_stage_subdirs(cached_root, required_subdirs, weight_subdirs):
return cached_root
# Cold cache, or a snapshot root whose stage subfolders were never (or
# only partially) downloaded: pull exactly the subfolders this stage asked
# for. snapshot_download resumes a partial subfolder for free.
allow_patterns = [f"{subdir.strip('/')}/*" for subdir in required_subdirs] or None
try:
resolved = hf_api().snapshot_download(
model, allow_patterns=allow_patterns, revision=revision, cache_dir=download_dir
)
except Exception as exc:
raise RuntimeError(
f"[stage_init] Could not resolve {model!r} to a local snapshot containing "
f"{sorted(required_subdirs)}: the download failed and "
+ (
f"the cached snapshot {cached_root!r} is missing or incomplete for "
f"{sorted(_incomplete_stage_subdirs(cached_root, required_subdirs, weight_subdirs))}."
if cached_root is not None
else "nothing is cached locally."
)
) from exc
missing = _incomplete_stage_subdirs(resolved, required_subdirs, weight_subdirs)
if missing:
raise RuntimeError(
f"[stage_init] Snapshot {resolved!r} for {model!r} has no populated {sorted(missing)} "
"subfolder; the stage cannot be initialized from it."
)
return resolved
def _resolve_model_tokenizer_paths(model: str, engine_args: dict[str, Any]) -> str:
@@ -107,14 +234,66 @@ def _resolve_model_tokenizer_paths(model: str, engine_args: dict[str, Any]) -> s
if model_subdir is None and tokenizer_subdir is None:
return model
resolved_base = _resolve_model_to_local_path(model)
revision = engine_args.get("revision")
tokenizer_revision = engine_args.get("tokenizer_revision")
download_dir = engine_args.get("download_dir")
# A tokenizer pinned to a different revision cannot come from the model's
# snapshot; resolve it against its own. An empty subdir means the snapshot
# root and still needs its own revision.
split_tokenizer = tokenizer_subdir is not None and tokenizer_revision is not None and tokenizer_revision != revision
required_subdirs = [subdir for subdir in (model_subdir, tokenizer_subdir) if subdir]
model_required = [subdir for subdir in (model_subdir,) if subdir] if split_tokenizer else required_subdirs
weight_subdirs = frozenset(subdir for subdir in (model_subdir,) if subdir)
if is_runai_obj_uri(model):
# Object-storage URIs stay opaque until each stage builds its own
# ModelConfig, so the joins below are resolved by vLLM's streamer
# rather than by the local filesystem.
resolved_base = model
tokenizer_base = model
else:
resolved_base = _resolve_model_to_local_path(
model, model_required, weight_subdirs, revision=revision, download_dir=download_dir
)
# Reachable for a local model directory; the Hub branch above has
# already failed closed on a missing subfolder.
missing = _missing_stage_subdirs(resolved_base, model_required)
if missing:
raise RuntimeError(
f"[stage_init] Model directory {resolved_base!r} has no {sorted(missing)} "
"subfolder; the stage cannot be initialized from it."
)
if split_tokenizer:
# An empty subdir targets the snapshot root, which cannot be
# subset by allow_patterns; resolve the whole revision.
tokenizer_required = [tokenizer_subdir] if tokenizer_subdir else []
tokenizer_base = _resolve_model_to_local_path(
model, tokenizer_required, revision=tokenizer_revision, download_dir=download_dir
)
missing = _missing_stage_subdirs(tokenizer_base, tokenizer_required)
if missing:
raise RuntimeError(
f"[stage_init] Tokenizer directory {tokenizer_base!r} has no {sorted(missing)} "
"subfolder; the stage cannot be initialized from it."
)
if not tokenizer_required and not _subdir_is_populated(tokenizer_base, "", False):
# An empty subdir means the tokenizer lives at the snapshot
# root, so there is no subfolder for the check above to look
# at and any resolved root would otherwise pass. Require the
# vocabulary artifacts themselves.
raise RuntimeError(
f"[stage_init] Tokenizer directory {tokenizer_base!r} holds none of "
f"{list(_TOKENIZER_ARTIFACT_NAMES)}; the stage cannot be initialized from it."
)
else:
tokenizer_base = resolved_base
if model_subdir:
model = os.path.join(resolved_base, model_subdir)
logger.info("[stage_init] Using model subdirectory: %s", model)
if tokenizer_subdir is not None:
tokenizer_path = os.path.join(resolved_base, tokenizer_subdir) if tokenizer_subdir else resolved_base
tokenizer_path = os.path.join(tokenizer_base, tokenizer_subdir) if tokenizer_subdir else tokenizer_base
engine_args["tokenizer"] = tokenizer_path
logger.info("[stage_init] Using tokenizer from: %s", tokenizer_path)
elif model_subdir and "tokenizer" not in engine_args: