Skip to content

census: send an HF token when one is in the environment - #633

Merged
bong-water-water-bong merged 4 commits into
mainfrom
census/hf-token
Oct 30, 2026
Merged

bong-water-water-bong merged 4 commits into
mainfrom
census/hf-token

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Half of #619 is blocked on something the watcher cannot do at all: it never sent credentials.

The five UNVERIFIABLE rows are gated (auto-access) repos — HF answers the listing without config, so architectures_of() returns '' and the class is never seen. The advice printed next to them ("gated repos need a token") was therefore unfollowable: installing a token changed nothing.

Change

  • HF_TOKEN, or HUGGING_FACE_HUB_TOKEN (the name huggingface_hub writes), is sent as Authorization: Bearer … by request_headers() on the architecture walk's listing requests (hf_get_page). With no token in the environment the request is byte-identical to what the watcher always sent. No token file is read: hf_token() looks only at those two variables, so the standard ~/.cache/huggingface/token changes nothing.
  • A 401 in hf_get_page sets _AUTH_REJECTED, prints the token was rejected (401); continuing without it and retries the page anonymously, so a token some endpoint rejects costs a warning rather than the sweep. (That path is a guard, not one the watcher exercises — see the correction below.)
  • The UNVERIFIABLE line now says whether a token was already sent ((HF_TOKEN sent, still no config)), so it stops advising a token at a run that sent one.
  • docs/arch-gaps.md, section Unverifiable: gated configs (which this PR previously left stale, still claiming the watcher "sends no Authorization header on purpose"): now names the two variables the code reads and the fact that no token file is read, says what happens with no token (unverifiable row: reported once, remembered, no alert, exit code unmoved), says a rejected token is not fatal, notes that the header goes on the architecture walk only (the FastFlowLM org/detail/release fetches in get_json() still send User-Agent: 1bit-census-watch alone), and corrects the cestaristudio/granite-switch-4.1-3b-preview example: with no token it stays unverifiable and does not alert — it was never !! UNCOVERED — and a token granted access to it would classify it like any other row.

Correction: a dead token does not empty the sweep

An earlier revision of this body said one dead token "silently emptied the sweep", and the 401 fallback was justified that way. That claim is wrong, and the code cannot detect a dead token the way it implied. Measured today with Authorization: Bearer hf_invalid_probe_token:

GET /api/models?limit=3&pipeline_tag=text-generation&config=true   bad Bearer -> 200  (3 models returned)
GET /api/models?limit=1                                           anonymous  -> 200
GET /api/whoami-v2                                                bad Bearer -> 401

hf_get_page() puts the header on the listing route, and HF answers that route 200 even with an invalid Bearer — no 401 arrives there, the page comes back with models and inline configs, and the sweep is neither emptied nor degraded. The only endpoint observed to reject the token is /api/whoami-v2, which the watcher never calls; so no, the code does not probe an endpoint that distinguishes a good token from a bad one. The 401 branch in hf_get_page is therefore a guard for an endpoint that does reject it, pinned only against a stubbed urlopen in tests/census_watch_test.py (check 17), not against observed HF behaviour. I did not add a whoami probe: it would be an extra unverified request per run feeding a diagnosis nothing consumes.

Verification

python3 tests/census_watch_test.py — header construction for both variable names, report text with and without a token, and the 401 fallback through a stubbed urlopen (no network):

ok   no token in the environment -> UA only
ok   HF_TOKEN -> Bearer header
ok   HUGGING_FACE_HUB_TOKEN is the fallback
ok   the unverifiable line names the token it already sent
ok   with no token the line stays the plain advice
ok   a 401 falls back to anonymous instead of failing the run
all checks passed

The same file fails on the base commit (5c2aee2): run against an extracted 5c2aee2 tree it dies at check 16 with AttributeError: module 'census_watch' has no attribute 'TOKEN_VARS', so the new checks pin this commit's code and not the old behavior.

  • python3 tools/registry_build.py --check-gaps — clean (none of the 27 reviewed significant classes is mapped without a reason).
  • python3 tools/registry_build.py --check-pins — clean (registry/architectures.json records the committed pins). (--check-gaps/--check-pins live on tools/registry_build.py; tools/census_watch.py takes --limit/--state/--full only.)
  • python3 tools/copyright.py --check — clean.
  • python3 tools/census_watch.py --limit 5 still runs and still exits 1 on the real FastFlowLM alerts (!! NEW FLM FastFlowLM/LFM3-1.7B-NPU2, .../MiniCPM-V-4.7-1B-NPU2, .../smolvla-NPU2).

What this does NOT claim

That HF returns config for a gated repo to a valid token — unverified, because the token on this box is revoked (401 on whoami-v2), and I will not write that claim without a working one. Nothing here was run with a valid token. It also does not touch the four public classes in #619 (LiveMemForCausalLM, CDMMoELMPoincare, GraniteSwitchForCausalLM, Senryu2ForCausalLM); those need the reviewed-not-an-alias writeup in docs/arch-gaps.md.

Refs #619.

engine#619's five UNVERIFIABLE rows are gated (auto-access) repos: HF answers the listing
without `config`, so the architecture is unknowable and the class is never seen. The
watcher sent no credentials at all, so no token could ever resolve those rows however many
were installed.

HF_TOKEN (or HUGGING_FACE_HUB_TOKEN, the name huggingface_hub writes) is now sent as a
Bearer header on every HF request. With none in the environment the request is
byte-identical to what the watcher always sent. A rejected token (401) turns the header off
for the rest of the run and the page is retried anonymously, so a stale token costs a
warning instead of the whole sweep, and the UNVERIFIABLE line then says the token was
already sent rather than advising a token at a run that sent one.

Tests: tests/census_watch_test.py pins the header for both variable names, the report text
with and without a token, and the 401 fallback through a stubbed urlopen (no network).

Not verified here: that HF exposes `config` for a gated repo to a valid token. The token on
this box is revoked (401 on whoami-v2), so that half waits for a working one.

Refs: #619
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 0aaa829)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

619 - Partially compliant

Compliant requirements:

  • The PR maps new HF model classes by enabling token-based access to gated repos
  • The census watcher now sends HF tokens when available
  • The PR handles 401 errors gracefully by falling back to anonymous requests
  • The documentation in docs/arch-gaps.md has been updated to reflect the new token handling behavior

Non-compliant requirements:

  • The PR does not include the actual mapping of the new architectures in registry/architectures.json (this would be a follow-up step)

Requires further human verification:

  • Verification that the new architectures are properly handled by the engine backend
  • Confirmation that the token handling works correctly in the actual deployment environment
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Token Handling Logic

The new token handling logic in request_headers() and hf_get_page() introduces a global state variable _AUTH_REJECTED that could lead to unexpected behavior if not properly managed. Specifically, if a token is rejected early in the run, subsequent requests will continue to use anonymous access even if a valid token is available later in the same run. This could mask issues with token validity or cause inconsistent behavior.

_AUTH_REJECTED = False  # a 401 on the token turns it off for the rest of the run


def request_headers():
    """Headers for every HF request: the UA, plus Authorization when a token is present."""
    headers = {"User-Agent": "1bit-census-watch"}
    token = hf_token()
    if token and not _AUTH_REJECTED:
        headers["Authorization"] = "Bearer " + token
    return headers

# A derivative carries no config.json of its own by design (a quantized GGUF, a LoRA
# adapter); the raw release it derives from carries the config and is what gets checked.
DERIVATIVE_TAGS = ("gguf", "lora", "peft")

# Library names that are not Transformers. A model published through one of these (a raw
# PyTorch checkpoint, an MLX or ONNX export) has no Transformers implementation either, so
# its `architectures[0]` is the same kind of unmappable one-off as an `auto_map` class.
# engine#296: Ihatetomatoes/nanoBeard-sloop-14M is `library_name: pytorch`, declares
# `model_type: nanobeard-gpt` and `architectures: ["GPT"]`, and no backend has a "GPT" arch.
NON_TRANSFORMERS_LIBRARIES = frozenset((
    "pytorch", "onnx", "onnxruntime-genai", "mlx", "mlx-serve", "litert-lm", "llama.cpp",
    "mlc-llm", "tensorflow", "tf-keras", "keras", "jax", "flax", "openvino", "coreml",
))

COVERED, UNCOVERED, UNVERIFIABLE, DERIVATIVE = "covered", "uncovered", "unverifiable", "derivative"


def hf_get_page(url, tries=4):
    """GET one listing page: (models, the rel="next" cursor or "").

    HF ignores `p=` when the listing is sorted (every page returns the first one), so
    pagination follows the Link header's cursor — the same way tools/census.py walks the
    full sweep. A page fetched with `p=` overlaps the previous one 100%, which silently
    capped this watcher at 100 models however large --limit was.
    """
    for t in range(tries):
        try:
            req = urllib.request.Request(url, headers=request_headers())
            with urllib.request.urlopen(req, timeout=60) as r:
                return json.load(r), r.headers.get("Link", "")
        except urllib.error.HTTPError as e:
            # A rejected token must not cost the whole run: fall back to anonymous and say so.
            # A gated repo then answers with no config again, which is what UNVERIFIABLE reports.
            if e.code == 401 and "Authorization" in req.headers:
                global _AUTH_REJECTED
                _AUTH_REJECTED = True
                print(f"hf_get_page {url}: the token was rejected (401); continuing without it",
                      file=sys.stderr)
                continue
            if t == tries - 1:
                print(f"hf_get_page {url}: {e}", file=sys.stderr)
                return [], ""
            time.sleep(2 * (t + 1))
Token Validation

The code assumes that a 401 response from hf_get_page indicates a rejected token, but this is not strictly validated. It's possible that other authentication-related issues (e.g., network errors, misconfigured proxies) could also result in a 401, potentially causing the system to incorrectly assume the token is invalid and fall back to anonymous access.

if e.code == 401 and "Authorization" in req.headers:
    global _AUTH_REJECTED
    _AUTH_REJECTED = True
    print(f"hf_get_page {url}: the token was rejected (401); continuing without it",
          file=sys.stderr)
    continue

…ne costs

The 'Unverifiable: gated configs' section still claimed the watcher sends no
`Authorization` header on purpose and that a token "needs [to be] in the watcher";
that is false as of the parent commit. Describe the code: `hf_token()` reads
HF_TOKEN, then HUGGING_FACE_HUB_TOKEN (no token *file* is read, so the standard
~/.cache/huggingface/token changes nothing), `request_headers()` adds the Bearer
header on the architecture walk's listing pages only (FastFlowLM's `get_json`
fetches still send the UA alone), with no token the request is byte-identical and a
gated row stays unverifiable - reported once, remembered, no alert - and a 401 sets
_AUTH_REJECTED and retries anonymously instead of ending the run.

HF answers the listing 200 even with an invalid Bearer (measured: /api/models 200,
only /api/whoami-v2 401), so that fallback is a guard, not a path the watcher
exercises, and the section now says so. The
`cestaristudio/granite-switch-4.1-3b-preview` example is corrected: without a token
it stays unverifiable and does not alert (it was never `!! UNCOVERED`), and a token
granted access to it would classify it like any other row.

Docs only - tools/census_watch.py and its test are untouched.
@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 7fc8536

bong-water-water-bong added 2 commits October 29, 2026 19:57
main now reviews Granite-Switch in the same section, so the gated-listing note keeps both
halves: the row stays unverifiable without a token, and the class it would have named is
already reviewed.
@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 0aaa829

@bong-water-water-bong
bong-water-water-bong merged commit 5b11658 into main Oct 30, 2026
8 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the census/hf-token branch October 30, 2026 01:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant