Skip to content
16 changes: 3 additions & 13 deletions src/huggingface_hub/file_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,14 +565,12 @@ def xet_get(
if len(displayed_filename) > 40:
displayed_filename = f"{displayed_filename[:40]}(…)"

from .utils._xet import abort_xet_session, get_xet_session, refresh_xet_connection_info, xet_headers_without_auth
from .utils._xet import abort_xet_session, get_xet_session, xet_download_group_kwargs
from .utils._xet_progress_reporting import XetDownloadProgressReporter

xet_headers = xet_headers_without_auth(headers)

# Fetched once per repo revision and cached; otherwise each download group would request its own
# token, i.e. one Hub API call per file (rate-limited on large snapshot downloads, see #4722).
connection_info = refresh_xet_connection_info(file_data=xet_file_data, headers=headers)
group_kwargs = xet_download_group_kwargs(xet_file_data, headers)

session = get_xet_session()

Expand All @@ -586,15 +584,7 @@ def xet_get(
external_reconstruction_bar=_tqdm_bar,
) as progress:
try:
with session.new_file_download_group(
endpoint=connection_info.endpoint,
token=connection_info.access_token,
token_expiry_unix_secs=connection_info.expiration_unix_epoch,
token_refresh_url=xet_file_data.refresh_route,
token_refresh_headers=headers,
custom_headers=xet_headers,
progress_callback=progress.update_progress,
) as group:
with session.new_file_download_group(**group_kwargs, progress_callback=progress.update_progress) as group:
group.start_download_file(
XetFileInfo(xet_file_data.file_hash, expected_size), str(incomplete_path.absolute())
)
Expand Down
57 changes: 54 additions & 3 deletions src/huggingface_hub/hf_file_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
from functools import cached_property
from pathlib import Path, PurePosixPath
from typing import Any, NoReturn, Union
from urllib.parse import quote, unquote
Expand All @@ -33,7 +34,14 @@
from .hf_api import SPECIAL_REFS_REVISION_REGEX, HfApi, LastCommitInfo, RepoFile, RepoFolder
from .utils import HFValidationError, XetFileData, hf_raise_for_status, http_backoff, http_stream_backoff, parse_hf_uri
from .utils._runtime import is_xet_available
from .utils._xet import XetTokenType, xet_connection_info_refresh_url
from .utils._xet import (
XetTokenType,
_cache_key,
abort_xet_session,
get_xet_session,
xet_connection_info_refresh_url,
xet_download_group_kwargs,
)
from .utils.insecure_hashlib import md5


Expand Down Expand Up @@ -232,6 +240,8 @@ def __init__(
self._repo_and_revision_exists_cache: dict[tuple[str, str, str | None], tuple[bool, Exception | None]] = {}
# Same for buckets
self._bucket_exists_cache: dict[str, tuple[bool, Exception | None]] = {}
# Xet session and download stream group per process, repo revision and token
self._xet_stream_groups: dict[str, tuple[Any, Any]] = {}
# Note: special case for buckets: revision is always None
# Maps parent directory path to path infos
self.dircache: dict[str, list[dict[str, Any]]] = {}
Expand Down Expand Up @@ -1109,6 +1119,26 @@ def _get_xet_file_data(
)
return XetFileData(file_hash=xet_hash, refresh_route=refresh_route)

def _read_xet(self, xet_file_data: XetFileData, size: int, start: int, end: int | None = None) -> Iterator[bytes]:
"""Stream the bytes `[start, end)` of a file from Xet storage."""
from hf_xet import XetFileInfo

# Files of a revision share one group, so they share its connection pool. The key holds the PID so that a
# forked process never drops the groups of its parent (a group is not fork-safe), and the token so that a
# new token gets a group with up-to-date refresh headers. The group is rebuilt after `abort_xet_session`.
headers = self._api._build_hf_headers()
key = f"{os.getpid()}|{_cache_key(xet_file_data.refresh_route, headers)}"
session = get_xet_session()
cached = self._xet_stream_groups.get(key)
if cached is None or cached[0] is not session:
group = session.new_download_stream_group(**xet_download_group_kwargs(xet_file_data, headers))
cached = self._xet_stream_groups[key] = (session, group)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
try:
yield from cached[1].download_stream(XetFileInfo(xet_file_data.file_hash, size), start=start, end=end)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
except KeyboardInterrupt:
abort_xet_session()
raise
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

def get_file(self, rpath, lpath=None, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None:
"""
Copy single remote file to local.
Expand Down Expand Up @@ -1241,6 +1271,8 @@ def __del__(self):
return super().__del__()

def _fetch_range(self, start: int, end: int) -> bytes:
if self._xet_file_data is not None:
return b"".join(self.fs._read_xet(self._xet_file_data, self.size, start=start, end=end))
headers = {
"range": f"bytes={start}-{end - 1}",
**self.fs._api._build_hf_headers(),
Expand All @@ -1250,6 +1282,10 @@ def _fetch_range(self, start: int, end: int) -> bytes:
hf_raise_for_status(r)
return r.content

@cached_property
def _xet_file_data(self) -> XetFileData | None:
return self.fs._get_xet_file_data(self.resolved_path, self.details)

def _initiate_upload(self) -> None:
self.temp_file = tempfile.NamedTemporaryFile(prefix="hffs-", delete=False)

Expand Down Expand Up @@ -1343,13 +1379,13 @@ def read(self, length: int = -1):

If reading the stream fails, we retry with a new connection.
"""
if self.response is None:
if self._stream_iterator is None:
self._open_connection()

retried_once = False
while True:
try:
if self.response is None or self._stream_iterator is None:
if self._stream_iterator is None:
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return b"" # Already read the entire file
out = self._read_from_stream(self._stream_iterator, length)
self.loc += len(out)
Expand Down Expand Up @@ -1410,12 +1446,27 @@ def __del__(self):
def __reduce__(self):
return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name)

@cached_property
def _xet_file_data(self) -> XetFileData | None:
# Checked first to skip the `info()` call when hf_xet is not installed
if not is_xet_available():
return None
if self.size is None:
self.details = self.fs.info(self.path)
self.size = self.details["size"]
return self.fs._get_xet_file_data(self.resolved_path, self.details)

def _open_connection(self):
"""Open a connection to the remote file."""
# reset streaming state
self._stream_buffer.clear()
self._stream_iterator = None

if self._xet_file_data is not None:
if self.loc < self.size:
self._stream_iterator = self.fs._read_xet(self._xet_file_data, self.size, start=self.loc)
return

url = self.url()
headers = self.fs._api._build_hf_headers()
if self.loc > 0:
Expand Down
16 changes: 16 additions & 0 deletions src/huggingface_hub/utils/_xet.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,22 @@ def xet_headers_without_auth(headers: dict[str, str]) -> dict[str, str]:
return {key: value for key, value in headers.items() if key.lower() != "authorization"}


def xet_download_group_kwargs(file_data: XetFileData, headers: dict[str, str]) -> dict[str, Any]:
"""Return the connection arguments of an hf_xet download group for a file.

The connection info is cached per repo revision, so building a group does not request a new token.
"""
connection_info = refresh_xet_connection_info(file_data=file_data, headers=headers)
return {
"endpoint": connection_info.endpoint,
"token": connection_info.access_token,
"token_expiry_unix_secs": connection_info.expiration_unix_epoch,
"token_refresh_url": file_data.refresh_route,
"token_refresh_headers": headers,
"custom_headers": xet_headers_without_auth(headers),
}


def abort_xet_session():
"""Abort the global xet session after a KeyboardInterrupt.

Expand Down
33 changes: 29 additions & 4 deletions tests/test_hf_file_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,17 +118,17 @@ def test_stream_file_retry(self):
assert isinstance(f, HfFileSystemStreamFile)
assert f.read(6) == b"dummy "
# Simulate that streaming fails mid-way
f.response = None
f._stream_iterator = None
assert f.read(6) == b"binary"
assert f.response is not None # a new connection has been created
assert f._stream_iterator is not None # a new stream has been opened

def test_stream_file_reuse_response(self):
with self.hffs.open(self.hf_path + "/data/binary_data.bin", block_size=0) as f:
assert isinstance(f, HfFileSystemStreamFile)
assert f.read(6) == b"dummy "
first_response = f.response
first_stream = f._stream_iterator
assert f.read(6) == b"binary"
assert f.response == first_response
assert f._stream_iterator is first_stream

def _make_stream_file_with_fake_response(self, chunks: Iterable[bytes]):
"""Helper: create iterator from specified chunks to simulate a stream response."""
Expand Down Expand Up @@ -636,6 +636,31 @@ def test_get_file_with_xet(self):
assert Path(temp_dir, "pr.bin").read_bytes() == b"dummy binary data on pr"
assert xet_mock.call_count == 2

@pytest.mark.xet
def test_read_range_with_xet(self):
with (
patch.object(self.hffs, "_read_xet", wraps=self.hffs._read_xet) as xet_mock,
patch.object(hf_file_system, "http_backoff") as http_mock,
):
with self.hffs.open(self.hf_path + "/data/binary_data.bin", "rb", block_size=4) as f:
f.seek(6)
assert f.read(6) == b"binary"
assert xet_mock.called
http_mock.assert_not_called()

@pytest.mark.xet
def test_stream_with_xet(self):
with (
patch.object(self.hffs, "_read_xet", wraps=self.hffs._read_xet) as xet_mock,
patch.object(hf_file_system, "http_stream_backoff") as http_mock,
):
with self.hffs.open(self.hf_path + "/data/binary_data.bin", "rb", block_size=0) as f:
assert f.read(6) == b"dummy "
assert f.read() == b"binary data"
assert f.read() == b""
assert xet_mock.call_count == 1
http_mock.assert_not_called()

def test_list_data_directory_with_revision(self):
files = self.hffs.ls(self.hf_path + "@refs%2Fpr%2F1" + "/data")

Expand Down
Loading