diff --git a/.github/workflows/kernels_data_python_release.yaml b/.github/workflows/kernels_data_python_release.yaml new file mode 100644 index 000000000..007de1b14 --- /dev/null +++ b/.github/workflows/kernels_data_python_release.yaml @@ -0,0 +1,228 @@ +# This file is autogenerated by maturin v1.13.1 +# To update, run +# +# maturin generate-ci github -m kernels-data/bindings/python/Cargo.toml -o .github/workflows/kernels_data_python_release.yaml +# +# Post-generation edits: +# - manifest paths made relative +# - publish step switched from `uv publish` + API token to +# `PyO3/maturin-action` + PyPI trusted publishing (see plan.md §3a, §3b) +# - pull_request trigger gained `paths-ignore` for docs-only PRs +name: CI + +on: + push: + branches: + - main + - master + tags: + - '*' + pull_request: + paths-ignore: + - "docs/**" + - "*.md" + workflow_dispatch: + +permissions: + contents: read + +jobs: + linux: + runs-on: ${{ matrix.platform.runner }} + strategy: + matrix: + platform: + - runner: ubuntu-22.04 + target: x86_64 + - runner: ubuntu-22.04 + target: x86 + - runner: ubuntu-22.04 + target: aarch64 + - runner: ubuntu-22.04 + target: armv7 + - runner: ubuntu-22.04 + target: s390x + - runner: ubuntu-22.04 + target: ppc64le + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 + with: + python-version: 3.8 + - name: Build wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.platform.target }} + args: --release --out dist --manifest-path kernels-data/bindings/python/Cargo.toml + sccache: ${{ !startsWith(github.ref, 'refs/tags/') }} + manylinux: auto + - name: Build free-threaded wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.platform.target }} + args: --release --out dist --manifest-path kernels-data/bindings/python/Cargo.toml -i python3.14t + sccache: ${{ !startsWith(github.ref, 'refs/tags/') }} + manylinux: auto + - name: Upload wheels + uses: actions/upload-artifact@v6 + with: + name: wheels-linux-${{ matrix.platform.target }} + path: dist + + musllinux: + runs-on: ${{ matrix.platform.runner }} + strategy: + matrix: + platform: + - runner: ubuntu-22.04 + target: x86_64 + - runner: ubuntu-22.04 + target: x86 + - runner: ubuntu-22.04 + target: aarch64 + - runner: ubuntu-22.04 + target: armv7 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 + with: + python-version: 3.8 + - name: Build wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.platform.target }} + args: --release --out dist --manifest-path kernels-data/bindings/python/Cargo.toml + sccache: ${{ !startsWith(github.ref, 'refs/tags/') }} + manylinux: musllinux_1_2 + - name: Build free-threaded wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.platform.target }} + args: --release --out dist --manifest-path kernels-data/bindings/python/Cargo.toml -i python3.14t + sccache: ${{ !startsWith(github.ref, 'refs/tags/') }} + manylinux: musllinux_1_2 + - name: Upload wheels + uses: actions/upload-artifact@v6 + with: + name: wheels-musllinux-${{ matrix.platform.target }} + path: dist + + windows: + runs-on: ${{ matrix.platform.runner }} + strategy: + matrix: + platform: + - runner: windows-latest + target: x64 + python_arch: x64 + - runner: windows-latest + target: x86 + python_arch: x86 + - runner: windows-11-arm + target: aarch64 + python_arch: arm64 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 + with: + python-version: 3.13 + architecture: ${{ matrix.platform.python_arch }} + - name: Build wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.platform.target }} + args: --release --out dist --manifest-path kernels-data/bindings/python/Cargo.toml + sccache: ${{ !startsWith(github.ref, 'refs/tags/') }} + - uses: actions/setup-python@v6 + with: + python-version: 3.14t + architecture: ${{ matrix.platform.python_arch }} + - name: Build free-threaded wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.platform.target }} + args: --release --out dist --manifest-path kernels-data/bindings/python/Cargo.toml -i python3.14t + sccache: ${{ !startsWith(github.ref, 'refs/tags/') }} + - name: Upload wheels + uses: actions/upload-artifact@v6 + with: + name: wheels-windows-${{ matrix.platform.target }} + path: dist + + macos: + runs-on: ${{ matrix.platform.runner }} + strategy: + matrix: + platform: + - runner: macos-15-intel + target: x86_64 + - runner: macos-latest + target: aarch64 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 + with: + python-version: 3.8 + - name: Build wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.platform.target }} + args: --release --out dist --manifest-path kernels-data/bindings/python/Cargo.toml + sccache: ${{ !startsWith(github.ref, 'refs/tags/') }} + - uses: actions/setup-python@v6 + with: + python-version: 3.14t + - name: Build free-threaded wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.platform.target }} + args: --release --out dist --manifest-path kernels-data/bindings/python/Cargo.toml -i python3.14t + sccache: ${{ !startsWith(github.ref, 'refs/tags/') }} + - name: Upload wheels + uses: actions/upload-artifact@v6 + with: + name: wheels-macos-${{ matrix.platform.target }} + path: dist + + sdist: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: Build sdist + uses: PyO3/maturin-action@v1 + with: + command: sdist + args: --out dist --manifest-path kernels-data/bindings/python/Cargo.toml + - name: Upload sdist + uses: actions/upload-artifact@v6 + with: + name: wheels-sdist + path: dist + + release: + name: Release + runs-on: ubuntu-latest + if: ${{ startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch' }} + needs: [linux, musllinux, windows, macos, sdist] + environment: + name: pypi + url: https://pypi.org/p/kernels-data + permissions: + # Use to sign the release artifacts + id-token: write + # Used to upload release artifacts + contents: write + # Used to generate artifact attestation + attestations: write + steps: + - uses: actions/download-artifact@v7 + - name: Generate artifact attestation + uses: actions/attest-build-provenance@v3 + with: + subject-path: 'wheels-*/*' + - name: Publish to PyPI + if: ${{ startsWith(github.ref, 'refs/tags/') }} + uses: PyO3/maturin-action@v1 + with: + command: upload + args: --non-interactive --skip-existing wheels-*/* diff --git a/.github/workflows/rust.yaml b/.github/workflows/rust.yaml index 6369af1ce..cc2f95854 100644 --- a/.github/workflows/rust.yaml +++ b/.github/workflows/rust.yaml @@ -16,7 +16,9 @@ jobs: ( cd kernel-abi-check/kernel-abi-check && cargo fmt --all -- --check ) ( cd kernel-abi-check/bindings/python && cargo fmt --all -- --check ) - name: Cargo fmt (kernels-data) - run: ( cd kernels-data && cargo fmt --all -- --check ) + run: | + ( cd kernels-data && cargo fmt --all -- --check ) + ( cd kernels-data/bindings/python && cargo fmt --all -- --check ) - name: Cargo fmt (kernel-builder) run: ( cd kernel-builder && cargo fmt --all -- --check ) @@ -42,6 +44,8 @@ jobs: ( cd kernel-abi-check/kernel-abi-check && cargo clippy -- -D warnings ) ( cd kernel-abi-check/bindings/python && cargo clippy -- -D warnings ) - name: Clippy (kernels-data) - run: ( cd kernels-data && cargo clippy -- -D warnings ) + run: | + ( cd kernels-data && cargo clippy -- -D warnings ) + ( cd kernels-data/bindings/python && cargo clippy -- -D warnings ) - name: Clippy (kernel-builder) run: ( cd kernel-builder && cargo clippy -- -D warnings ) diff --git a/.github/workflows/test_python.yaml b/.github/workflows/test_python.yaml index 2ab25ecee..e26b8d71c 100644 --- a/.github/workflows/test_python.yaml +++ b/.github/workflows/test_python.yaml @@ -16,8 +16,8 @@ concurrency: cancel-in-progress: true jobs: - build: - name: Run tests + kernel-abi-check: + name: kernel-abi-check bindings runs-on: ubuntu-latest strategy: matrix: @@ -40,3 +40,31 @@ jobs: - name: Run tests run: ( cd kernel-abi-check/bindings/python && uv run pytest tests ) + + kernels-data: + name: kernels-data bindings + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.12"] + + env: + UV_PYTHON_PREFERENCE: only-managed + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Install uv and set the python version + uses: astral-sh/setup-uv@v7 + with: + python-version: ${{ matrix.python-version }} + + - name: Install the project + run: ( cd kernels-data/bindings/python && uv sync --all-extras --dev) + + - name: Run tests + run: ( cd kernels-data/bindings/python && uv run pytest tests ) + + - name: Check type stubs match runtime + run: ( cd kernels-data/bindings/python && uv run python -m mypy.stubtest kernels_data --allowlist stubtest-allowlist.txt ) diff --git a/Cargo.lock b/Cargo.lock index 95f32cf3b..1072bbfe1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1562,6 +1562,14 @@ dependencies = [ "url", ] +[[package]] +name = "kernels-data-python" +version = "0.0.1" +dependencies = [ + "kernels-data", + "pyo3", +] + [[package]] name = "konst" version = "0.4.3" diff --git a/Cargo.toml b/Cargo.toml index 9ec18104c..0979c04a5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,5 +4,6 @@ members = [ "kernel-abi-check/bindings/python", "kernel-builder", "kernels-data", + "kernels-data/bindings/python", ] resolver = "2" diff --git a/kernels-data/bindings/python/Cargo.toml b/kernels-data/bindings/python/Cargo.toml new file mode 100644 index 000000000..41a31fa8b --- /dev/null +++ b/kernels-data/bindings/python/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "kernels-data-python" +version = "0.0.1" +edition = "2024" +description = "Kernels data structures (Python bindings)" +homepage = "https://github.com/huggingface/kernels" +license = "Apache-2.0" +repository = "https://github.com/huggingface/kernels" + +[lib] +name = "kernels_data" +crate-type = ["cdylib"] + +[dependencies] +pyo3 = { version = "0.26", features = ["abi3", "abi3-py38"] } + +[dependencies.kernels-data] +path = "../.." diff --git a/kernels-data/bindings/python/MANIFEST.in b/kernels-data/bindings/python/MANIFEST.in new file mode 100644 index 000000000..5444e43d7 --- /dev/null +++ b/kernels-data/bindings/python/MANIFEST.in @@ -0,0 +1,4 @@ +include Cargo.toml +include pyproject.toml +include ../../../LICENSE +recursive-include src * diff --git a/kernels-data/bindings/python/kernels_data.pyi b/kernels-data/bindings/python/kernels_data.pyi new file mode 100644 index 000000000..fde03be99 --- /dev/null +++ b/kernels-data/bindings/python/kernels_data.pyi @@ -0,0 +1,109 @@ +"""Type stubs for kernels_data module.""" + +from enum import Enum +from typing import Optional, final +import os + +__all__ = ["Backend", "KernelName", "Metadata", "Version", "__version__"] + +__version__: str + +@final +class Backend(Enum): + """Kernel backend (hardware target).""" + + CANN = "CANN" + CPU = "CPU" + CUDA = "CUDA" + Metal = "Metal" + Neuron = "Neuron" + ROCm = "ROCm" + XPU = "XPU" + + @staticmethod + def from_str(s: str) -> "Backend": + """Parse a backend name. + + Args: + s: One of ``"cann"``, ``"cpu"``, ``"cuda"``, ``"metal"``, + ``"neuron"``, ``"rocm"``, ``"xpu"``. + + Raises: + ValueError: If the backend name is unknown. + """ + ... + + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + +@final +class Version: + """A dotted numeric version (e.g. ``12.8.0``). + + Trailing zeros are stripped during normalization. + """ + + @staticmethod + def from_str(s: str) -> "Version": + """Parse a version string of the form ``X``, ``X.Y``, ``X.Y.Z``, ... + + Raises: + ValueError: If the string is empty or contains non-numeric parts. + """ + ... + + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __eq__(self, value: object, /) -> bool: ... + def __lt__(self, value: "Version", /) -> bool: ... + def __le__(self, value: "Version", /) -> bool: ... + def __gt__(self, value: "Version", /) -> bool: ... + def __ge__(self, value: "Version", /) -> bool: ... + def __hash__(self) -> int: ... + +@final +class KernelName: + """A validated kernel name matching ``^[a-z][-a-z0-9]*[a-z0-9]$``.""" + + def __new__(cls, name: str) -> "KernelName": + """Create a new ``KernelName``. + + Raises: + ValueError: If the name does not match the required pattern. + """ + ... + + @property + def python_name(self) -> str: + """The name with dashes replaced by underscores.""" + ... + + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + +@final +class Metadata: + """Parsed ``metadata.json`` for a kernel build variant.""" + + @staticmethod + def load(metadata_path: os.PathLike[str] | str) -> "Metadata": + """Parse ``metadata.json`` at the given path. + + Raises: + ValueError: On any I/O or parse error. + """ + ... + + @property + def version(self) -> Optional[int]: ... + @property + def license(self) -> Optional[str]: ... + @property + def upstream(self) -> Optional[str]: ... + @property + def python_depends(self) -> list[str]: ... + @property + def backend(self) -> Backend: ... + def __repr__(self) -> str: ... diff --git a/kernels-data/bindings/python/pyproject.toml b/kernels-data/bindings/python/pyproject.toml new file mode 100644 index 000000000..6d16671f7 --- /dev/null +++ b/kernels-data/bindings/python/pyproject.toml @@ -0,0 +1,27 @@ +[project] +name = "kernels-data" +requires-python = '>=3.8' +classifiers = [ + "Programming Language :: Rust", + "Programming Language :: Python :: Implementation :: CPython", +] +dynamic = [ + 'description', + 'readme', + 'version', +] + +[build-system] +requires = ["maturin>=1,<2"] +build-backend = "maturin" + +[dependency-groups] +dev = [ + "pytest>=8", + "mypy>=1.11", +] + +[tool.maturin] +module-name = "kernels_data" +bindings = 'pyo3' +features = ["pyo3/extension-module"] diff --git a/kernels-data/bindings/python/src/lib.rs b/kernels-data/bindings/python/src/lib.rs new file mode 100644 index 000000000..0c830f170 --- /dev/null +++ b/kernels-data/bindings/python/src/lib.rs @@ -0,0 +1,230 @@ +use std::path::PathBuf; +use std::str::FromStr; + +use kernels_data::config::{Backend, KernelName}; +use kernels_data::metadata::{Metadata, parse_metadata}; +use kernels_data::version::Version; +use pyo3::Bound as PyBound; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; + +/// A dotted numeric version (e.g. `12.8.0`). Trailing zeros are stripped +/// during normalization. +#[pyclass(name = "Version", frozen, eq, ord, hash)] +#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +struct PyVersion { + inner: Version, +} + +#[pymethods] +impl PyVersion { + /// Parse a version string of the form `X`, `X.Y`, `X.Y.Z`, ... + #[staticmethod] + #[pyo3(name = "from_str")] + fn py_from_str(s: &str) -> PyResult { + Version::from_str(s) + .map(|inner| Self { inner }) + .map_err(|err| PyValueError::new_err(format!("Cannot parse version `{s}`: {err}"))) + } + + fn __str__(&self) -> String { + self.inner.to_string() + } + + fn __repr__(&self) -> String { + format!("Version('{}')", self.inner) + } +} + +/// A validated kernel name matching `^[a-z][-a-z0-9]*[a-z0-9]$`. +#[pyclass(name = "KernelName", frozen, eq, hash)] +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct PyKernelName { + inner: KernelName, +} + +#[pymethods] +impl PyKernelName { + #[new] + fn new(name: String) -> PyResult { + KernelName::new(name) + .map(|inner| Self { inner }) + .map_err(|err| PyValueError::new_err(err.to_string())) + } + + fn __str__(&self) -> String { + self.inner.to_string() + } + + fn __repr__(&self) -> String { + format!("KernelName('{}')", self.inner) + } + + /// The kernel name with dashes replaced by underscores, suitable for + /// use as a Python identifier. + #[getter] + fn python_name(&self) -> String { + self.inner.python_name() + } +} + +/// Kernel backend (hardware target). +#[pyclass(name = "Backend", eq, frozen, hash)] +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +enum PyBackend { + #[pyo3(name = "CANN")] + Cann, + #[pyo3(name = "CPU")] + Cpu, + #[pyo3(name = "CUDA")] + Cuda, + #[pyo3(name = "Metal")] + Metal, + #[pyo3(name = "Neuron")] + Neuron, + #[pyo3(name = "ROCm")] + Rocm, + #[pyo3(name = "XPU")] + Xpu, +} + +impl From for PyBackend { + fn from(b: Backend) -> Self { + match b { + Backend::Cann => PyBackend::Cann, + Backend::Cpu => PyBackend::Cpu, + Backend::Cuda => PyBackend::Cuda, + Backend::Metal => PyBackend::Metal, + Backend::Neuron => PyBackend::Neuron, + Backend::Rocm => PyBackend::Rocm, + Backend::Xpu => PyBackend::Xpu, + } + } +} + +impl From for Backend { + fn from(b: PyBackend) -> Self { + match b { + PyBackend::Cann => Backend::Cann, + PyBackend::Cpu => Backend::Cpu, + PyBackend::Cuda => Backend::Cuda, + PyBackend::Metal => Backend::Metal, + PyBackend::Neuron => Backend::Neuron, + PyBackend::Rocm => Backend::Rocm, + PyBackend::Xpu => Backend::Xpu, + } + } +} + +#[pymethods] +impl PyBackend { + /// Parse a backend name (`"cann"`, `"cpu"`, `"cuda"`, `"metal"`, + /// `"neuron"`, `"rocm"`, `"xpu"`). + #[staticmethod] + #[pyo3(name = "from_str")] + fn py_from_str(s: &str) -> PyResult { + Backend::from_str(s) + .map(Into::into) + .map_err(PyValueError::new_err) + } + + fn __str__(&self) -> &'static str { + Backend::from(*self).as_str() + } + + fn __repr__(&self) -> String { + let variant = match self { + PyBackend::Cann => "CANN", + PyBackend::Cpu => "CPU", + PyBackend::Cuda => "CUDA", + PyBackend::Metal => "Metal", + PyBackend::Neuron => "Neuron", + PyBackend::Rocm => "ROCm", + PyBackend::Xpu => "XPU", + }; + format!("Backend.{variant}") + } +} + +/// Parsed `metadata.json` for a kernel build variant. +#[pyclass(name = "Metadata", frozen)] +#[derive(Clone, Debug)] +struct PyMetadata { + version: Option, + license: Option, + upstream: Option, + python_depends: Vec, + backend: PyBackend, +} + +impl From for PyMetadata { + fn from(m: Metadata) -> Self { + Self { + version: m.version, + license: m.license, + upstream: m.upstream.map(|u| u.to_string()), + python_depends: m.python_depends, + backend: m.backend.backend_type.into(), + } + } +} + +#[pymethods] +impl PyMetadata { + /// Parse `metadata.json` at the given path. + /// + /// Raises `ValueError` on any I/O or parse error. + #[staticmethod] + fn load(metadata_path: PathBuf) -> PyResult { + parse_metadata(&metadata_path) + .map(Into::into) + .map_err(|err| PyValueError::new_err(format!("{err:#}"))) + } + + #[getter] + fn version(&self) -> Option { + self.version + } + + #[getter] + fn license(&self) -> Option<&String> { + self.license.as_ref() + } + + #[getter] + fn upstream(&self) -> Option<&String> { + self.upstream.as_ref() + } + + #[getter] + fn python_depends(&self) -> &[String] { + &self.python_depends + } + + #[getter] + fn backend(&self) -> PyBackend { + self.backend + } + + fn __repr__(&self) -> String { + format!( + "Metadata(version={:?}, license={:?}, upstream={:?}, python_depends={:?}, backend={})", + self.version, + self.license, + self.upstream, + self.python_depends, + self.backend.__repr__() + ) + } +} + +#[pyo3::pymodule(name = "kernels_data")] +fn kernels_data_py(m: &PyBound<'_, PyModule>) -> PyResult<()> { + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + + m.add("__version__", env!("CARGO_PKG_VERSION"))?; + Ok(()) +} diff --git a/kernels-data/bindings/python/stubtest-allowlist.txt b/kernels-data/bindings/python/stubtest-allowlist.txt new file mode 100644 index 000000000..1f7a2b29f --- /dev/null +++ b/kernels-data/bindings/python/stubtest-allowlist.txt @@ -0,0 +1,3 @@ +# The `.so` submodule `kernels_data.kernels_data` is a pyo3/maturin +# implementation detail; end users import from the `kernels_data` package. +kernels_data\.kernels_data diff --git a/kernels-data/bindings/python/tests/test_kernels_data.py b/kernels-data/bindings/python/tests/test_kernels_data.py new file mode 100644 index 000000000..7ab3152d6 --- /dev/null +++ b/kernels-data/bindings/python/tests/test_kernels_data.py @@ -0,0 +1,163 @@ +import json + +import pytest + +from kernels_data import Backend, KernelName, Metadata, Version + + +def _write_metadata(path, **fields): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(fields)) + return path + + +def test_version_parse_and_normalize(): + assert str(Version.from_str("12.8.0")) == "12.8" + assert str(Version.from_str("1")) == "1" + assert str(Version.from_str("1.2.3")) == "1.2.3" + + +def test_version_ordering_and_hash(): + v1 = Version.from_str("1.2") + v2 = Version.from_str("1.2.0") + v3 = Version.from_str("1.3") + assert v1 == v2 + assert v1 < v3 + assert hash(v1) == hash(v2) + assert {v1, v2, v3} == {v1, v3} + + +def test_version_invalid(): + with pytest.raises(ValueError): + Version.from_str("abc") + with pytest.raises(ValueError): + Version.from_str("") + + +def test_kernel_name_valid(): + n = KernelName("my-kernel") + assert str(n) == "my-kernel" + assert n.python_name == "my_kernel" + + +def test_kernel_name_hash_and_eq(): + assert KernelName("flash-attention") == KernelName("flash-attention") + assert {KernelName("a1"), KernelName("a1")} == {KernelName("a1")} + + +def test_kernel_name_invalid(): + with pytest.raises(ValueError): + KernelName("My-Kernel") + with pytest.raises(ValueError): + KernelName("1kernel") + with pytest.raises(ValueError): + KernelName("-kernel") + + +def test_backend_from_str_and_repr(): + assert Backend.from_str("cuda") == Backend.CUDA + assert Backend.from_str("CUDA") == Backend.CUDA + assert str(Backend.CUDA) == "cuda" + assert repr(Backend.CUDA) == "Backend.CUDA" + + +def test_backend_hash(): + d = {Backend.CUDA: 1, Backend.CPU: 2} + assert d[Backend.CUDA] == 1 + + +def test_backend_unknown(): + with pytest.raises(ValueError): + Backend.from_str("tpu") + + +def test_backend_all_variants_and_casing(): + assert str(Backend.Metal) == "metal" + assert repr(Backend.Metal) == "Backend.Metal" + assert str(Backend.Neuron) == "neuron" + assert repr(Backend.Neuron) == "Backend.Neuron" + assert str(Backend.ROCm) == "rocm" + assert repr(Backend.ROCm) == "Backend.ROCm" + assert repr(Backend.XPU) == "Backend.XPU" + assert repr(Backend.CANN) == "Backend.CANN" + assert Backend.from_str("cann") == Backend.CANN + assert Backend.from_str("ROCM") == Backend.ROCm + assert Backend.from_str("metal") == Backend.Metal + + +def test_metadata_load_full(tmp_path): + path = tmp_path / "metadata.json" + path.write_text( + json.dumps( + { + "version": 1, + "license": "Apache-2.0", + "upstream": "https://github.com/example/kernel", + "python-depends": ["torch"], + "backend": {"type": "cuda"}, + } + ) + ) + m = Metadata.load(path) + assert m.version == 1 + assert m.license == "Apache-2.0" + assert m.upstream == "https://github.com/example/kernel" + assert m.python_depends == ["torch"] + assert m.backend == Backend.CUDA + + +def test_metadata_load_minimal(tmp_path): + path = tmp_path / "metadata.json" + path.write_text( + json.dumps({"python-depends": [], "backend": {"type": "cpu"}}) + ) + m = Metadata.load(path) + assert m.version is None + assert m.license is None + assert m.upstream is None + assert m.python_depends == [] + assert m.backend == Backend.CPU + + +def test_metadata_load_cann(tmp_path): + path = tmp_path / "metadata.json" + path.write_text( + json.dumps({"python-depends": [], "backend": {"type": "cann"}}) + ) + assert Metadata.load(path).backend == Backend.CANN + + +def test_metadata_load_unknown_field_rejected(tmp_path): + path = tmp_path / "metadata.json" + path.write_text( + json.dumps( + { + "python-depends": [], + "backend": {"type": "cpu"}, + "surprise": "not allowed", + } + ) + ) + with pytest.raises(ValueError): + Metadata.load(path) + + +def test_metadata_load_malformed(tmp_path): + path = tmp_path / "metadata.json" + path.write_text("{not json") + with pytest.raises(ValueError): + Metadata.load(path) + + +def test_metadata_load(tmp_path): + path = _write_metadata( + tmp_path / "variant" / "metadata.json", + **{"python-depends": ["torch"], "backend": {"type": "cuda"}}, + ) + m = Metadata.load(path) + assert m.backend == Backend.CUDA + + +def test_metadata_load_missing_file(tmp_path): + with pytest.raises(ValueError): + Metadata.load(tmp_path / "does-not-exist.json") diff --git a/kernels-data/src/config/mod.rs b/kernels-data/src/config/mod.rs index 6e4a848c8..12d2c588c 100644 --- a/kernels-data/src/config/mod.rs +++ b/kernels-data/src/config/mod.rs @@ -286,6 +286,7 @@ impl Kernel { #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] pub enum Backend { + Cann, Cpu, Cuda, Metal, @@ -295,8 +296,9 @@ pub enum Backend { } impl Backend { - pub const fn all() -> [Backend; 6] { + pub const fn all() -> [Backend; 7] { [ + Backend::Cann, Backend::Cpu, Backend::Cuda, Backend::Metal, @@ -308,6 +310,7 @@ impl Backend { pub const fn as_str(&self) -> &'static str { match self { + Backend::Cann => "cann", Backend::Cpu => "cpu", Backend::Cuda => "cuda", Backend::Metal => "metal", @@ -321,6 +324,7 @@ impl Backend { impl Display for Backend { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + Backend::Cann => write!(f, "cann"), Backend::Cpu => write!(f, "cpu"), Backend::Cuda => write!(f, "cuda"), Backend::Metal => write!(f, "metal"), @@ -336,6 +340,7 @@ impl FromStr for Backend { fn from_str(s: &str) -> Result { match s.to_lowercase().as_str() { + "cann" => Ok(Backend::Cann), "cpu" => Ok(Backend::Cpu), "cuda" => Ok(Backend::Cuda), "metal" => Ok(Backend::Metal), diff --git a/kernels-data/src/config/name.rs b/kernels-data/src/config/name.rs index ffc75fbf8..8151f023d 100644 --- a/kernels-data/src/config/name.rs +++ b/kernels-data/src/config/name.rs @@ -4,7 +4,7 @@ use regex::Regex; use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; /// A validated kernel name matching `^[a-z][-a-z0-9]*[a-z0-9]$`. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Eq, Hash, PartialEq)] pub struct KernelName(String); impl KernelName { diff --git a/kernels-data/src/config/v1.rs b/kernels-data/src/config/v1.rs index a9d5cd351..523d283be 100644 --- a/kernels-data/src/config/v1.rs +++ b/kernels-data/src/config/v1.rs @@ -83,6 +83,7 @@ impl TryFrom for super::Build { let backends = if universal { vec![ + Backend::Cann, Backend::Cpu, Backend::Cuda, Backend::Metal, diff --git a/kernels-data/src/config/v2.rs b/kernels-data/src/config/v2.rs index 84f9f19ed..866ab6fe9 100644 --- a/kernels-data/src/config/v2.rs +++ b/kernels-data/src/config/v2.rs @@ -129,6 +129,7 @@ impl TryFrom for super::Build { let backends = if build.general.universal { vec![ + Backend::Cann, Backend::Cpu, Backend::Cuda, Backend::Metal, diff --git a/kernels-data/src/config/v3.rs b/kernels-data/src/config/v3.rs index a74cd7ee2..5a4c4be96 100644 --- a/kernels-data/src/config/v3.rs +++ b/kernels-data/src/config/v3.rs @@ -149,6 +149,7 @@ pub enum Kernel { #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] pub enum Backend { + Cann, Cpu, Cuda, Metal, @@ -256,6 +257,7 @@ impl From for super::TvmFfi { impl From for super::Backend { fn from(backend: Backend) -> Self { match backend { + Backend::Cann => super::Backend::Cann, Backend::Cpu => super::Backend::Cpu, Backend::Cuda => super::Backend::Cuda, Backend::Metal => super::Backend::Metal, @@ -437,6 +439,7 @@ impl From for TvmFfi { impl From for Backend { fn from(backend: super::Backend) -> Self { match backend { + super::Backend::Cann => Backend::Cann, super::Backend::Cpu => Backend::Cpu, super::Backend::Cuda => Backend::Cuda, super::Backend::Metal => Backend::Metal,