Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/citest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jobs:
python-version: ${{ matrix.python-version }}

- name: Install package with dev dependencies
run: pip install -e ".[dev]"
run: pip install -e ".[dev,kernels]"

- name: Run unit tests (mock mode)
run: pytest tests/ --ignore=tests/integration -q
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,13 @@ from modelscope_hub.kernels import get_kernel
activation = get_kernel("kernels-community/activation", version=1)
```

Also available: `has_kernel()` (environment compatibility check), `get_kernel_variants()` (build-variant decisions), `get_local_kernel()` (load from a local path, dependencies from ModelScope), `install_kernel()` (download to the local cache without importing — CI pre-installation / offline preparation), `install_kernel_all_variants()` (download every build variant plus the dependency tree), `get_locked_kernel()` (load a kernel pinned by a lockfile, downloading missing pieces), and `load_kernel()` (import an already-installed locked kernel; never downloads). Under `patch_kernels_hub()` every other networked `kernels` entry point (the `layer`/`kernelize` APIs, benchmarks, etc.) is redirected the same way, because the whole library routes through one Hub API factory.
Also available: `has_kernel()` (environment compatibility check), `get_kernel_variants()` (build-variant decisions), `get_local_kernel()` (load from a local path, dependencies from ModelScope), `install_kernel()` (download to the local cache without importing — CI pre-installation / offline preparation), `install_kernel_all_variants()` (download every build variant plus the dependency tree), `lock_kernels()` (resolve the dependency tree against ModelScope and write a `kernels.lock` file — the in-process equivalent of `kernels lock`), `get_locked_kernel()` (load a kernel pinned by a lockfile, downloading missing pieces), and `load_kernel()` (import an already-installed locked kernel; never downloads). The same lockfile can be created from the command line with `ms-hub kernels lock [project_dir]`, which reads `[tool.kernels.dependencies]` from `pyproject.toml`. Under `patch_kernels_hub()` every other networked `kernels` entry point (the `layer`/`kernelize` APIs, benchmarks, etc.) is redirected the same way, because the whole library routes through one Hub API factory. The upstream `kernels lock` console script runs in its own process and therefore cannot pick up the in-process patch; use `lock_kernels()` or `ms-hub kernels lock` instead.

Notes:

- The kernel loading, variant resolution, and dependency logic of `kernels` are reused unchanged — only its Hub API factory is swapped for a ModelScope-backed shim while a `modelscope_hub.kernels` call is in flight, so a plain `import kernels` elsewhere keeps using the Hugging Face Hub. `patch_kernels_hub()` / `unpatch_kernels_hub()` / `patch_scope()` switch this explicitly if you need it globally; the `modelscope` package's `patch_hub()` builds on the same implementation.
- `version=N` resolves against the repository's `v<N>` branches/tags. A mirror that only carries `master` exposes it as kernel version `v1` automatically.
- Kernel lockfiles record hub-specific commit hashes: a lockfile created against the Hugging Face Hub cannot resolve on ModelScope (the two hubs have different git histories). Create the lockfile in the ModelScope environment (`get_locked_kernel` / `install_kernel_all_variants`, or the `kernels` CLI under `patch_kernels_hub()`) so it records ModelScope commits; a commit-hash revision that cannot be found raises with a note explaining this.
- Kernel lockfiles record hub-specific commit hashes: a lockfile created against the Hugging Face Hub cannot resolve on ModelScope (the two hubs have different git histories). Create the lockfile in the ModelScope environment (`lock_kernels()`, `install_kernel_all_variants`, or `ms-hub kernels lock`) so it records ModelScope commits; a commit-hash revision that cannot be found raises with a note explaining this.
- ModelScope has no trusted-publisher flag, so untrusted publishers are rejected by default: only `kernels-community` is trusted out of the box. Extend the allowlist with `MS_KERNELS_TRUSTED_PUBLISHERS` (comma-separated), or allow specific repositories / all repositories through the trust parameters of `get_kernel` (its docstring mirrors the kernel library's API).
- The mirror must contain kernels built for your exact Torch version and platform (`kernels` selects `build/torchXY-...-<cpu>-<os>/`); a repository whose builds predate `kernels` 0.17 metadata cannot be loaded until it is rebuilt with a current `kernel-builder`.

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,5 @@ strict = false
warn_return_any = false

[[tool.mypy.overrides]]
module = ["tqdm.*", "modelscope.*", "kernels.*", "huggingface_hub.*"]
module = ["tqdm.*", "modelscope.*", "kernels.*", "huggingface_hub.*", "tomllib", "tomli"]
ignore_missing_imports = true
131 changes: 131 additions & 0 deletions src/modelscope_hub/cli/kernels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""``ms-hub kernels`` — kernel lockfile helpers backed by ModelScope.

The upstream ``kernels lock`` console command runs in its own process, so it
cannot pick up the in-process ``patch_kernels_hub()`` redirection and always
resolves against the Hugging Face Hub. This subcommand is the ModelScope
equivalent: it reads the same ``[tool.kernels.dependencies]`` table from
``pyproject.toml`` and writes the same ``kernels.lock`` file, with every
dependency resolved against ModelScope instead.
"""

from __future__ import annotations

from argparse import ArgumentParser
from pathlib import Path
from types import ModuleType

from ..errors import InvalidParameter
from .base import CLICommand, error, info


def _require_kernels() -> ModuleType:
"""Import ``kernels`` or raise an actionable CLI error."""
try:
import kernels # noqa: F401
except ImportError as e:
raise InvalidParameter(
"The `kernels` package is required by `ms-hub kernels` but is not installed. "
'Install it with: pip install "modelscope-hub[kernels]"',
) from e
return kernels


def _require_kernels_locking() -> None:
"""Fail early with an upgrade hint when ``kernels`` predates lockfiles."""
try:
import kernels.locking # noqa: F401
except ImportError as e:
raise InvalidParameter(
"Kernel lockfiles require `kernels>=0.18`, which is not installed. Upgrade with: pip install -U kernels",
) from e


def _read_dependencies(project_dir: Path) -> dict[str, int | str]:
"""Read ``[tool.kernels.dependencies]`` from the project's ``pyproject.toml``."""
try:
import tomllib
except ImportError:
try:
from kernels.compat import tomllib # kernels>=0.18 ships a fallback
except ImportError:
try:
import tomli as tomllib # explicit fallback for Python < 3.11
except ImportError as e:
raise InvalidParameter(
"Reading pyproject.toml on Python < 3.11 requires a TOML parser. "
"Install one with: pip install tomli",
) from e

pyproject = project_dir / "pyproject.toml"
if not pyproject.exists():
raise InvalidParameter(
f"No pyproject.toml found in {project_dir}; kernel dependencies are declared in its "
"[tool.kernels.dependencies] table.",
)
with open(pyproject, "rb") as f:
data = tomllib.load(f)
dependencies = data.get("tool", {}).get("kernels", {}).get("dependencies")
if not dependencies:
raise InvalidParameter(
"No [tool.kernels.dependencies] table in pyproject.toml; declare the kernels to lock, "
'e.g. [tool.kernels.dependencies]\n"kernels-community/flash-attn2" = "3".',
)
return dependencies


class KernelsCommand(CLICommand):
"""``ms-hub kernels lock``: write a ModelScope-resolved ``kernels.lock``."""

@staticmethod
def register(subparsers) -> None:
parser: ArgumentParser = subparsers.add_parser(
"kernels",
help="Kernel lockfile helpers resolved against the ModelScope Hub.",
)
sub = parser.add_subparsers(dest="kernels_command", metavar="ACTION")
sub.required = True

lock = sub.add_parser(
"lock",
help="Write kernels.lock from [tool.kernels.dependencies] (ModelScope commits).",
)
lock.add_argument(
"project_dir",
nargs="?",
type=Path,
default=Path("."),
help="Project directory holding pyproject.toml (default: current directory).",
)
lock.add_argument(
"--lockfile",
type=Path,
default=None,
help="Lockfile path (default: <project_dir>/kernels.lock).",
)
lock.set_defaults(_command=KernelsCommand)

def execute(self) -> None:
action = getattr(self.args, "kernels_command", None)
if action != "lock": # pragma: no cover - argparse enforces the choice
error("Unknown kernels action; try `ms-hub kernels --help`.")
return

_require_kernels()
_require_kernels_locking()
dependencies = _read_dependencies(self.args.project_dir)
if not isinstance(dependencies, dict) or not all(isinstance(repo, str) for repo in dependencies):
raise InvalidParameter(
"[tool.kernels.dependencies] must be a table of repo ids to versions, "
'e.g. [tool.kernels.dependencies]\n"kernels-community/flash-attn2" = "3".',
)

# Imported lazily: the kernels extra is optional and `ms-hub` must stay
# importable without it.
from ..kernels import lock_kernels

default_lockfile = self.args.project_dir / "kernels.lock"
path = lock_kernels(
dependencies,
lockfile=self.args.lockfile or default_lockfile,
)
info(f"Wrote {path} — commit it to your project for reproducible kernel loads.")
2 changes: 2 additions & 0 deletions src/modelscope_hub/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from .cache import CacheCommand, _CacheClear, _CacheScan
from .deploy import DeployCommand, LogsCommand, SettingsCommand, StopCommand
from .download import DownloadCommand
from .kernels import KernelsCommand
from .login import LoginCommand, LogoutCommand, WhoamiCommand
from .mcp import McpCommand
from .repo import CreateCommand, DeleteCommand, InfoCommand, ListCommand, RepoCommand
Expand Down Expand Up @@ -68,6 +69,7 @@
CacheCommand,
AgentCommand,
AgentIdpCommand,
KernelsCommand,
]

# Plugin entry-point group name
Expand Down
2 changes: 2 additions & 0 deletions src/modelscope_hub/kernels/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
install_kernel,
install_kernel_all_variants,
load_kernel,
lock_kernels,
)
from modelscope_hub.kernels._patch import patch_kernels_hub, patch_scope, unpatch_kernels_hub

Expand All @@ -50,6 +51,7 @@
"install_kernel_all_variants",
"get_locked_kernel",
"load_kernel",
"lock_kernels",
"patch_kernels_hub",
"patch_scope",
"unpatch_kernels_hub",
Expand Down
45 changes: 38 additions & 7 deletions src/modelscope_hub/kernels/_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@
# Full git commit hashes (SHA-1); lockfiles pin revisions this way.
_COMMIT_HASH_RE = re.compile(r"[0-9a-f]{40}", re.IGNORECASE)

# A real commit hash a ref points at (SHA-1 40-hex or SHA-256 64-hex), as
# accepted by ``Oid.from_str`` in kernels 0.18.
_REAL_COMMIT_RE = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}", re.IGNORECASE)

# Keys a ModelScope revisions entry may use to carry the real commit hash
# (probed in order; none exists today, so synthetic OIDs stay the default).
_COMMIT_KEY_CANDIDATES = ("Commit", "CommitHash", "commit")

_LOCKFILE_COMMIT_HINT = (
"Revision {revision!r} looks like a commit hash. Commit hashes are "
"hub-specific: a kernel lockfile created against the Hugging Face Hub "
Expand Down Expand Up @@ -94,6 +102,24 @@ def _resolve_revision(revision: str | None) -> str | None:
return _synthetic_oids.get(str(revision), revision)


def _ref_target_commit(repo_id: str, ref: dict) -> str:
"""A ref's target commit: the platform's real hash when it exposes one.

When the ModelScope revisions entry carries a real commit hash, it is
used verbatim: kernels lockfiles then pin an immutable snapshot instead
of a (moving) branch name. A real hash is *not* registered in the
synthetic-OID table, so downloads by hash pass through unchanged —
this relies on the platform's download API accepting commit hashes.
Without a hash the deterministic synthetic OID stands in (see
:func:`_synthetic_oid`), which pins the ref name rather than content.
"""
for key in _COMMIT_KEY_CANDIDATES:
value = ref.get(key)
if isinstance(value, str) and _REAL_COMMIT_RE.fullmatch(value.strip()):
return value.strip().lower()
return _synthetic_oid(repo_id, ref["Revision"])


def _ms_repo_type(repo_type: str | None) -> str:
"""Map HF repo types onto ModelScope repo types (kernel repos are models)."""
return "model" if repo_type in (None, "kernel", "model") else repo_type
Expand Down Expand Up @@ -215,10 +241,12 @@ def hf_hub_download(
def list_repo_refs(self, repo_id: str | None = None, *, repo_type: str | None = None, **kwargs):
"""List repository branches and tags, mirroring ``HfApi.list_repo_refs``.

ModelScope's revision API does not expose git commit hashes, so every
ref's ``target_commit`` is a deterministic synthetic OID for the ref
name (see :func:`_synthetic_oid`); the download entry points map it
back to the real name, so both kernels 0.17 (which downloads by
When a revision entry carries a real commit hash, it becomes the
ref's ``target_commit`` verbatim (see :func:`_ref_target_commit`),
so kernel lockfiles pin an immutable snapshot. Otherwise
``target_commit`` is a deterministic synthetic OID for the ref name
(see :func:`_synthetic_oid`); the download entry points map it back
to the real name, so both kernels 0.17 (which downloads by
``target_commit`` verbatim) and kernels 0.18 (which validates it with
``Oid.from_str`` before fetching) work unchanged. When the repository
carries no ``v<N>`` refs at all (typical for a plain mirror with only
Expand All @@ -235,21 +263,24 @@ def list_repo_refs(self, repo_id: str | None = None, *, repo_type: str | None =
GitRefInfo(
name=ref["Revision"],
ref=f"refs/heads/{ref['Revision']}",
target_commit=_synthetic_oid(repo_id, ref["Revision"]),
target_commit=_ref_target_commit(repo_id, ref),
)
for ref in branches or []
]
tag_refs = [
GitRefInfo(
name=ref["Revision"],
ref=f"refs/tags/{ref['Revision']}",
target_commit=_synthetic_oid(repo_id, ref["Revision"]),
target_commit=_ref_target_commit(repo_id, ref),
)
for ref in tags or []
]
if not any(_VERSION_REF_RE.fullmatch(ref.name) for ref in branch_refs + tag_refs):
# The synthesized v1 points at whatever master points at.
master = next((ref for ref in branches or [] if ref["Revision"] == "master"), None)
master = master if master is not None else {"Revision": "master"}
branch_refs.append(
GitRefInfo(name="v1", ref="refs/heads/v1", target_commit=_synthetic_oid(repo_id, "master"))
GitRefInfo(name="v1", ref="refs/heads/v1", target_commit=_ref_target_commit(repo_id, master))
)
return SimpleNamespace(branches=branch_refs, tags=tag_refs, converts=[])

Expand Down
66 changes: 66 additions & 0 deletions src/modelscope_hub/kernels/_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"install_kernel_all_variants",
"get_locked_kernel",
"load_kernel",
"lock_kernels",
]


Expand Down Expand Up @@ -330,3 +331,68 @@ def load_kernel(
lockfile=lockfile,
backend=backend,
)


def lock_kernels(
dependencies: dict[str, int | str],
*,
lockfile: Path | str | None = None,
) -> Path:
"""Resolve a kernel dependency tree against ModelScope and write a lockfile.

This is the in-process equivalent of the ``kernels lock`` CLI command:
every entry in ``dependencies`` (and, recursively, each kernel's own
dependencies — for *every* build variant) is resolved against the
ModelScope Hub and the resulting commits are written to a
``kernels.lock`` JSON file that :func:`get_locked_kernel` /
:func:`load_kernel` (and ``kernels`` itself) can consume.

Requires ``kernels>=0.18``: the lockfile machinery (``kernels.locking``)
does not exist in older releases.

Args:
dependencies (`dict[str, int | str]`):
Kernel repositories to lock, mapping repo id to a version — an
``int`` (or numeric string) selects the ``v<N>`` generation, any
other string is used as the revision (branch, tag, or commit).
lockfile (`Path | str`, *optional*):
Where to write the lockfile. Defaults to ``kernels.lock`` in the
current working directory.

Returns:
`Path`: The lockfile that was written. Commit it to your project so
other machines load exactly the same kernels.

Example:
```python
from modelscope_hub.kernels import lock_kernels, get_locked_kernel

lock_kernels({"kernels-community/flash-attn2": 3})
kernel = get_locked_kernel("kernels-community/flash-attn2")
```
"""
_require_kernels()
try:
from kernels._rust import KernelDependency, KernelVersion
from kernels.locking import extract_dependency_locks
except ImportError as e:
raise ImportError(
"Kernel lockfiles require `kernels>=0.18`, which is not installed. Upgrade with: pip install -U kernels"
) from e

def _version_of(value: int | str) -> object:
as_str = str(value)
return KernelVersion.Version(int(as_str)) if as_str.isdigit() else KernelVersion.Revision(as_str)

depends = [
KernelDependency(repo_id=repo_id, version=_version_of(version)) for repo_id, version in dependencies.items()
]
with patch_scope():
# Imported inside the scope: _get_hf_api is rebound to the ModelScope
# factory while the patch is in effect, so `api` is our shim.
from kernels.hf_hub import _get_hf_api

locks = extract_dependency_locks(depends, api=_get_hf_api())
path = Path(lockfile) if lockfile is not None else Path("kernels.lock")
path.write_text(locks.to_json(), encoding="utf-8")
return path
Loading
Loading