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
43 changes: 39 additions & 4 deletions src/huggingface_hub/hf_file_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import tempfile
import threading
from collections import deque
from collections.abc import Iterable, Iterator
from collections.abc import Callable, Iterable, Iterator
from contextlib import ExitStack
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
from functools import cached_property, partial
from pathlib import Path, PurePosixPath
from typing import Any, NoReturn, Union
from urllib.parse import quote, unquote
Expand All @@ -33,7 +34,7 @@
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, get_xet_session, xet_connection_info_refresh_url, xet_download_group_kwargs
from .utils.insecure_hashlib import md5


Expand Down Expand Up @@ -1109,6 +1110,19 @@ def _get_xet_file_data(
)
return XetFileData(file_hash=xet_hash, refresh_route=refresh_route)

def _xet_stream_opener(
self, resolved_path: HfFileSystemResolvedRepositoryPath | HfFileSystemResolvedBucketPath, info: dict[str, Any]
) -> Callable[..., Iterator[bytes]] | None:
"""Return `open(start=..., end=...)`, which streams bytes of the file from Xet storage, or None if the file is not in Xet."""
if (xet_file_data := self._get_xet_file_data(resolved_path, info)) is None:
return None
from hf_xet import XetFileInfo

group = get_xet_session().new_download_stream_group(
**xet_download_group_kwargs(xet_file_data, self._api._build_hf_headers())
)
return partial(group.download_stream, XetFileInfo(xet_file_data.file_hash, info["size"]))
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 +1255,8 @@ def __del__(self):
return super().__del__()

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

@cached_property
def _open_xet_stream(self) -> Callable[..., Iterator[bytes]] | None:
return self.fs._xet_stream_opener(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 +1363,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 +1430,27 @@ def __del__(self):
def __reduce__(self):
return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name)

@cached_property
def _open_xet_stream(self) -> Callable[..., Iterator[bytes]] | 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._xet_stream_opener(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._open_xet_stream is not None:
if self.loc < self.size:
self._stream_iterator = self._open_xet_stream(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, "_xet_stream_opener", wraps=self.hffs._xet_stream_opener) 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, "_xet_stream_opener", wraps=self.hffs._xet_stream_opener) 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