Skip to content

package_manager: native Hugging Face Xet downloads - #1222

Merged
0xShug0 merged 4 commits into
0xShug0:mainfrom
drphero:feature/native-xet-download
Nov 6, 2026
Merged

0xShug0 merged 4 commits into
0xShug0:mainfrom
drphero:feature/native-xet-download

Conversation

@drphero

@drphero drphero commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Native Hugging Face Xet downloads for the package manager

Most large model files on Hugging Face are now stored with Xet. The native package manager currently follows the /resolve redirect and streams each file over one connection, which is why hf download (backed by hf_xet) is noticeably faster. This PR adds a download-only Xet client in C++ to audiocpp_package_manager, so audiocpp_model_manager and the server/WebUI get the faster transfer path without any Python dependency.

How it works

  1. The existing un-followed /resolve metadata request now also keeps X-Xet-Hash, the commit-pinned rel="xet-auth" link, and X-Linked-ETag (the file's SHA-256). No extra request is needed.
  2. A read-scoped CAS token comes from /api/models/{repo}/xet-read-token/{revision}.
  3. GET {casUrl}/v2/reconstructions/{hash} is requested in 10 GB Range batches, as the spec recommends.
  4. The signed xorb ranges are fetched in parallel (default 16, AUDIOCPP_HF_XET_CONCURRENCY). Responses are parsed as they stream (raw 206 or strict multipart/byteranges, with every part's Content-Range checked against the signed range set). Chunks are decoded with no compression, LZ4 frame, or ByteGrouping4 + LZ4, and written straight to their term offsets in the existing staging file. Whole ranges are never buffered, so peak RSS stays around 10–15 MiB.
  5. Every term's decoded length is checked against unpacked_length, as the spec requires. The file size is checked, and the SHA-256 is verified against X-Linked-ETag on a background thread that hashes the completed prefix while the transfer runs (AUDIOCPP_HF_XET_VERIFY=0 turns this off).

Staging, size validation, atomic publication, manifests (etags stay the same), install locks, cancellation, and progress all go through the existing install path unchanged. Xet only fills the staged file.

Fallback and safety

  • Non-Xet files, ModelScope, AUDIOCPP_HF_XET=0, and any Xet failure before publication (token or v2 unavailable, unsupported recipe layout, protocol error, retries exhausted) fall back to the existing HTTP download. The progress message names the route used.
  • A complete reconstruction that fails size or SHA-256 verification is reported as an error, not silently retried.
  • Credentials stay scoped. The HF token goes only to the Hub origin, the CAS token only to the returned CAS origin, and the signed xorb URLs receive no credentials. No Xet request follows redirects, and signed URLs are sent unchanged (set_path_encode(false)).
  • Retries: exponential backoff on connection errors, 429 and 5xx. A 401 on CAS refreshes the token. A 403 or expired signature on a xorb URL re-queries the reconstruction and redoes only the unfinished terms.
  • Out of scope: the deprecated v1 reconstruction API (its fetch schema isn't documented; v2 404/501 falls back to HTTP), a persistent xorb cache, resuming across restarts, and uploads.

Dependencies

  • Vendors unmodified LZ4 v1.10.0 lib/ sources (BSD-2-Clause) under external/lz4. They are compiled only with AUDIOCPP_BUILD_NATIVE_MODEL_MANAGER=ON. Xet chunks use the LZ4 frame format.
  • SHA-256 uses EVP from the BoringSSL/OpenSSL already linked for HTTPS.
  • No Python, libcurl, or new system package.

Changes

  • src/framework/package_manager/xet.{h,cpp}: the Xet client
  • src/framework/package_manager/http_util.{h,cpp}: URL/client helpers moved out of manager.cpp (pure move) so both transports share them
  • manager.cpp: carries the Xet metadata in RemoteFileInfo; download_file() tries Xet, then HTTP
  • tests/unittests/test_package_manager_xet.cpp: offline tests (below)
  • docs/model_manager.md: new "Hugging Face Xet Transfers" section
  • CMakeLists.txt: lz4_vendor target, the new sources, and the test (same guards as the existing package-manager tests)

Validation

Unit/integration tests (package_manager_xet_test, fully offline): a local httplib fixture plays Hub, CAS and xorb host, serving xorbs built in the test from known bytes.

  • BG4 inverse for every length 0–63
  • chunk decoding with mixed schemes, fed 1 byte at a time and in random splits; rejects bad version/scheme/sizes, truncated, extra or missing chunks, and corrupt LZ4
  • multipart parser: parts out of order, quoted boundary, padding, preamble and epilogue; rejects wrong, missing, duplicate or unrequested parts and bad delimiters
  • end to end: multi-xorb with reused chunks (multipart for the gapped xorb, each xorb fetched once), segmented reconstruction with offset_into_first_range > 0, a 403 refreshing the recipe, a 503 retry, 200-instead-of-206 rejected, unpacked_length mismatch rejected, SHA-256 mismatch, v2 501
  • through PackageManager::install: the Xet route is used, AUDIOCPP_HF_XET=0, fallback on v2 404/501, token 403 and a protocol error, an integrity failure publishes nothing, cancellation publishes nothing, the manifest etag is unchanged, and no credential leaks (checked on every request)
  • The tests were mutation-checked: breaking BG4 remainder handling, multipart part matching, offset_into_first_range, or the unpacked_length check each makes the suite fail.

Also: package_manager_http_test, package_manager_modelscope_test and server_model_installer_test pass. The Xet and HTTP tests are clean under ASan+UBSan. Helgrind reports no data races in the downloader. (TSan can't run in the container used for testing.)

Real downloads: each output is byte-identical to the current HTTP route (cmp / per-file SHA-256) and matches the Hub SHA-256.

Linux x86_64, 6 vCPU, datacenter network. Release build. Wall time per install. Runs alternate between routes so neither one always gets a warm CDN.

Download main (HTTP) This PR (Xet, SHA-256 verified) hf download (huggingface_hub 2.2.0, hf_xet 1.7.0)
qwen3_asr_0_6b_q8_0 (1 file, 1.15 GB) 33.2 s cold, 12.5 / 11.8 s 9.7 / 11.0 / 9.1 s 12.0 / 12.5 s
qwen3_asr_1_7b_f16 (1 file, 4.09 GB) 41.2 / 41.0 s 20.5 / 20.6 s 18.1 s
index_tts2_safetensors (21 files, 8.08 GB) 248.3 / 160.1 s 100.7 / 62.7 s 28.2 / 27.8 s (peak RSS 1.8–2.1 GB)
Peak RSS ~10 MiB 12–15 MiB 570–880 MiB

On this link that is about 2–2.6× faster than the current native route. For single large files it is close to hf download at a small fraction of its memory. Multi-file packages still trail hf download, because the installer downloads a package's files one after another, while hf download fetches several files concurrently. Parallelism here is within a file only. Single-connection throughput depends on latency, so the gain over the current route should be larger on higher-latency consumer links, where a single stream is the bottleneck. The numbers above come only from the machine described.

Not tested

  • Windows and macOS builds and runs (Linux/GCC only here; the code uses only std, cpp-httplib and EVP APIs already used in the tree)
  • gated or private Xet repositories with a real token (the auth flow is covered by the fixture)

Unmodified lib/ sources of LZ4 v1.10.0 (BSD-2-Clause). The native package
manager uses the LZ4 frame decoder for Hugging Face Xet xorb chunks; the
library is only compiled with AUDIOCPP_BUILD_NATIVE_MODEL_MANAGER=ON.
Xet-backed files are reconstructed with the Xet CAS protocol instead of
streaming the /resolve redirect over a single connection:

- read X-Xet-Hash and the commit-pinned xet-auth link from the existing
  un-followed /resolve metadata request
- get a read-scoped CAS token and query v2 reconstructions in 10 GB ranges
- fetch the signed xorb ranges in parallel (AUDIOCPP_HF_XET_CONCURRENCY,
  default 16), parse raw or multipart/byteranges 206 bodies as they stream,
  decode none/LZ4/ByteGrouping4-LZ4 chunks and write them at their term
  offsets in the staging file with bounded memory
- validate every term's unpacked_length, the final size, and the Hub
  SHA-256 (hashed on a background thread while the transfer runs;
  AUDIOCPP_HF_XET_VERIFY=0 skips it)
- retry transient errors, refresh the CAS token on 401, and re-query the
  reconstruction when a signed xorb URL is rejected

Non-Xet files, ModelScope, AUDIOCPP_HF_XET=0 and any Xet failure before
publication fall back to the existing HTTP download. Staging, atomic
publication, manifests and progress are unchanged. Hub, CAS and signed
storage URLs each receive only their own credentials.

The shared URL/client helpers move from manager.cpp to http_util.{h,cpp}
without behavior changes. package_manager_xet_test covers the decoders,
the multipart parser, and full transfers and fallbacks against a local
fixture.
@0xShug0

0xShug0 commented Nov 6, 2026

Copy link
Copy Markdown
Owner

@drphero Thanks for the improvement! I found two issues:

  • C++17 build failure. The progress callback captures a structured-binding variable, which requires C++20. CI missed this because native model management is disabled in its normal builds. In C++17 build it throws:
manager.cpp:714: error: reference to local binding 'remote'
declared in enclosing function

Please restore the ordinary progress_message capture used on main.

  • Incorrect progress after retries. After a partial transfer and signed-URL refresh, downloaded bytes are counted again. My test reported 410,808 bytes for a 345,272-byte file. The file was correct, but progress can reach 100% too early. Please preserve progress accounting across refreshes.

Capture a copied progress message instead of the structured binding
`remote`, which C++17 does not allow in lambda captures (GCC accepts it
as an extension; Clang rejects it).

Count Xet progress per term as the furthest byte any attempt has
written, kept across signed-URL refresh passes, so bytes redone after a
refresh are not reported twice and progress cannot pass the file size.
Add a fixture case that interrupts a partly written transfer with a
refresh.
@drphero

drphero commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for testing this! Both are fixed in 89f5b17.

  • C++17 build: the progress callback now captures a copied progress_message, as on main, plus the transport note. I reproduced the error with Clang 18 -std=c++17 (GCC accepts the capture as an extension, which is why my builds missed it). The native manager, server and tests now build cleanly with Clang in C++17.
  • Progress after a refresh: progress now records the furthest byte each term has reached across retries and refresh passes, so bytes redone after a signed-URL refresh are counted only once and the total can't pass the file size. A new fixture case streams one xorb slowly and rejects the other mid-transfer with a 403, forcing a refresh after partial writes. It fails on the previous commit (progress went past the file size) and passes now.

Unrelated to this PR: server_model_installer_test is intermittent on main for me (6 of 10 runs fail at "per-file ETag version check reports up to date"), so a failure there may not come from these changes.

@0xShug0
0xShug0 merged commit 8fe585c into 0xShug0:main Nov 6, 2026
7 checks passed
@0xShug0

0xShug0 commented Nov 6, 2026

Copy link
Copy Markdown
Owner

@drphero Thanks! PR merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants