Skip to content
Open
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
18 changes: 17 additions & 1 deletion kernels/src/kernels/_internals/resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

from huggingface_hub.errors import IncompleteSnapshotError, LocalEntryNotFoundError
from huggingface_hub.hf_api import HfApi
from huggingface_hub.utils.tqdm import tqdm as hf_tqdm

from kernels._internals import digest
from kernels._internals._versions import _get_available_versions, _record_ref_in_cache, resolve_kernel_version
from kernels._internals.hf_hub import _check_trust_remote_code, _get_cache_dir
from kernels._internals.variants import (
Expand All @@ -15,7 +17,7 @@
resolve_variant,
variants_trace_str,
)
from kernels._rust import KernelDependency, KernelLocks, KernelPaths, Metadata, Oid
from kernels._rust import KernelDependency, KernelLocation, KernelLocks, KernelPaths, Metadata, Oid

# Exclude pattern for bytecode. These are not included in kernel builds,
# but builds not done using kernel-builder might accidentally include
Expand All @@ -26,6 +28,14 @@
logger = logging.getLogger(__name__)


class _SilentTqdm(hf_tqdm):
"""Disabled hub progress bar."""

def __init__(self, *args, **kwargs):
kwargs["disable"] = True
super().__init__(*args, **kwargs)


@dataclass(frozen=True)
class LocalKernel:
"""
Expand Down Expand Up @@ -81,6 +91,11 @@ def get_file(self, filename: str, *, api: HfApi) -> Path:
def install(self, *, api: HfApi) -> LocalKernel:
allow_patterns = [f"build/{self.variant.variant_str}/*"]

# A receipt means the variant was verified before, so hide the progress bars.
location = KernelLocation.remote(self.repo_id, self.revision, self.variant_str)
store = digest._open_digest_receipt_store()
cached = store is not None and digest._has_receipt(store, location)

repo_path = Path(
str(
api.snapshot_download(
Expand All @@ -91,6 +106,7 @@ def install(self, *, api: HfApi) -> LocalKernel:
cache_dir=_get_cache_dir(),
revision=str(self.revision),
local_files_only=False,
tqdm_class=_SilentTqdm if cached else None,
)
)
)
Expand Down
42 changes: 42 additions & 0 deletions kernels/tests/test_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from kernels._internals._versions import resolve_version_spec_as_ref
from kernels._internals.hf_hub import _get_hf_api
from kernels._internals.install import install_kernel
from kernels._internals.load import get_kernel
from kernels._internals.resolver import (
HubCacheResolver,
HubResolver,
Expand Down Expand Up @@ -567,3 +568,44 @@ def test_resolve_local_kernel_keeps_rejection_reasons(tmp_path):
# The `build/` pass finds no variants and must not drop the reasons from
# the pass over `tmp_path`.
assert "torch-xpu: " in str(exc_info.value)


@pytest.fixture
def snapshot_download_calls(monkeypatch, tmp_path):
"""Record `snapshot_download` kwargs using an empty kernels cache."""
monkeypatch.setenv("KERNELS_CACHE", str(tmp_path))
calls = []
snapshot_download = HfApi.snapshot_download

def recording_snapshot_download(self, *args, **kwargs):
calls.append(kwargs)
return snapshot_download(self, *args, **kwargs)

monkeypatch.setattr(HfApi, "snapshot_download", recording_snapshot_download)
return calls


def test_remote_kernel_install_cached_is_quiet(snapshot_download_calls, capfd):
get_kernel("kernels-community/relu", version=1, backend="cpu")
assert snapshot_download_calls[-1].get("tqdm_class") is None
capfd.readouterr()

get_kernel("kernels-community/relu", version=1, backend="cpu")
assert snapshot_download_calls[-1].get("tqdm_class") is resolver_module._SilentTqdm
assert "Fetching" not in capfd.readouterr().err


def test_remote_kernel_install_cached_restores_deleted_file(snapshot_download_calls):
import torch
import torch.nn.functional as F

variant_path = install_kernel("kernels-community/relu", version=1, backend="cpu")
get_kernel("kernels-community/relu", version=1, backend="cpu")
(so_path,) = variant_path.glob("*.so")
so_path.unlink()

relu = get_kernel("kernels-community/relu", version=1, backend="cpu")
assert snapshot_download_calls[-1].get("tqdm_class") is resolver_module._SilentTqdm
assert so_path.exists()
x = torch.randn(10, 20)
torch.testing.assert_close(relu.relu(x), F.relu(x))
Loading