From a4853666b46e800422c5738e69b98143c8c64aad Mon Sep 17 00:00:00 2001 From: vecnode Date: Sat, 28 Nov 2026 09:11:44 +0000 Subject: [PATCH] dsh-huggingface: size a cached checkpoint for the LOAD, from its files The download size only half-answers "should I fetch this?". Once the bytes are on disk the question becomes "will it run here", and every number that decides it is already in the cache. hf_repo now answers it for a cached repo, with no model loaded and no Python: weights = the sum of the weight files params = weights / bytes-per-parameter KV/token = 2 x layers x kv_heads x head_dim x dtype_bytes total = weights + KV x context + max(512 MiB, 10% of the weights) Pass freeBytes and the context table gets a FITS column; pass contexts to choose the lengths. A repo that is not cached, or is metadata only, gets no estimate and says why - the attention heads live in a config that was never downloaded. The dtype is read from the SAFETENSORS HEADER, not from config.json, and that is a measured finding rather than a preference: sentence-transformers/all-mpnet-base-v2 states no torch_dtype and stores F32, so an fp16 assumption reported ~219M parameters for a 109M model and HALF its real KV cache (36 KB/token rather than 72). An fp16 config claiming fp16 weights is now also reported as a disagreement rather than silently believed. Checks: 243 in the package (up from 217) - the arithmetic asserted against exact bytes, an fp32 fixture with a REAL safetensors header, a metadata-only repo with no fit, and a FITS/NO pair. check-node-routes, check-no-secrets, check-scripts all pass. --- .dsh-version.json | 2 +- ARCHITECTURE.md | 2 +- README.md | 2 +- packages/dsh-huggingface/README.md | 14 +- .../checks/check-huggingface-node.mjs | 80 ++++++- packages/dsh-huggingface/lib/model.js | 215 ++++++++++++++++++ packages/dsh-huggingface/lib/tools.js | 93 +++++++- .../skills/huggingface-cache/SKILL.md | 29 +++ .../skills/huggingface-hub/SKILL.md | 2 +- 9 files changed, 423 insertions(+), 16 deletions(-) create mode 100644 packages/dsh-huggingface/lib/model.js diff --git a/.dsh-version.json b/.dsh-version.json index d05eb6d..6be2944 100644 --- a/.dsh-version.json +++ b/.dsh-version.json @@ -183,7 +183,7 @@ "huggingface" ], "rowOverrides": [], - "role": "The Hugging Face Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk - `hf_status` (the CLI and its version, the cache root with the variable that chose it, every repo with BYTE-EXACT sizes, and the split between complete repos and metadata-only stubs), `hf_search` (models / datasets / spaces, ranked), `hf_repo` (one repo's licence, gated flag, architecture, parameter count, weight with the MEASURE named, the files each consumer would fetch, and whether the local copy is complete / stub / stale / absent), `hf_cache` (list without any CLI, plus verify / prune / rm, where an UNCONFIRMED removal is the CLI's own --dry-run, rm needs the repo id repeated back and prune the word \"prune\") and `hf_download` (the only bytes-moving call: the weight first, a byte ceiling it will not cross, the repo id repeated back, and the bytes the cache actually GAINED) - plus two bundled skills (the CLI, the cache layout) whose examples the package check parses. The cache scan walks the directory tree because the CLI's own JSON answers \"17.9G\" and \"3 months ago\", and it is what makes the finding reportable: MEASURED on this machine, 42 of 49 cached repos are a config.json and nothing else. Auth is reported as a PRESENCE only: no token is ever read, echoed or accepted as an argument. Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine, no socket. See packages/dsh-huggingface/README.md.", + "role": "The Hugging Face Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk - `hf_status` (the CLI and its version, the cache root with the variable that chose it, every repo with BYTE-EXACT sizes, and the split between complete repos and metadata-only stubs), `hf_search` (models / datasets / spaces, ranked), `hf_repo` (one repo's licence, gated flag, architecture, parameter count, weight with the MEASURE named, the files each consumer would fetch, and whether the local copy is complete / stub / stale / absent), `hf_cache` (list without any CLI, plus verify / prune / rm, where an UNCONFIRMED removal is the CLI's own --dry-run, rm needs the repo id repeated back and prune the word \"prune\") and `hf_download` (the only bytes-moving call: the weight first, a byte ceiling it will not cross, the repo id repeated back, and the bytes the cache actually GAINED) - plus two bundled skills (the CLI, the cache layout) whose examples the package check parses. The cache scan walks the directory tree because the CLI's own JSON answers \"17.9G\" and \"3 months ago\", and it is what makes the finding reportable: MEASURED on this machine, 42 of 49 cached repos are a config.json and nothing else. Auth is reported as a PRESENCE only: no token is ever read, echoed or accepted as an argument. Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine, no socket. and for a repo that is cached it sizes the LOAD too - parameters implied by the weight bytes, KV cache as `2 x layers x kv_heads x head_dim x dtype_bytes` per token, and a context table with a FITS column against the `freeBytes` given - with the dtype read from the safetensors HEADER rather than the config (MEASURED: `all-mpnet-base-v2` states none and stores F32). See packages/dsh-huggingface/README.md.", "uses": [ "@deepseek-ai/dsh-tools (the registry the five tools are registered into)", "@deepseek-ai/dsh-skill (ctx.skills, resolved lazily; the two skills are also copied into $DSH_HOME/skills by both installers)", diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index f8a22b0..1c770ad 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -69,7 +69,7 @@ disable/replace a core row **in its own layer** — a later layer wins per row. | `dsh-docker` | `docker` | Docker (or Podman) as a surface: nine `docker_*` tools over the machine's CLI, a `docker_start` that launches Docker Desktop or a podman machine and waits for its **daemon**, and a Docker tab of containers and images. argv-only and validated; no `exec`, no `system prune`, no free-form `run` | | `dsh-sql-server` | `sqlserver` | SQL Server as a surface: seven `sql_*` tools over a container this row owns (2022 image, 1433, named volume) or the `sqlcmd` on PATH, keeping apart a **server** / a **client** / a **listening port** / the machine-wide **ODBC driver** an application connects with; `start` waits until the server ANSWERS a statement, and a dump loads through `-i` (stdin silently dropped rows) with BOM-aware code pages and an optional filter for the dump's own `CREATE DATABASE` header. Host-only, no route, no browser half | | `dsh-ollama` | `ollama` | Ollama as a **measured** surface: five `ollama_*` tools over the machine's own daemon — status (models on disk, what is loaded, and `ollama serve` when nothing answers), one bounded inference with the daemon's token counts and nanosecond durations, a benchmark that **refuses fewer than 3 runs** and reports a median with spread (cold vs warm stated at the first token), models with pull/delete confirmed by repeating the tag, embeddings with cosine similarity — three skills whose examples a check parses, and a **loopback fence** that refuses a daemon on another machine before any request. Host-only, no route, no browser half | -| `dsh-huggingface` | `huggingface` | the Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk. `hf_status` resolves the cache root through the library's own precedence (`HF_HUB_CACHE` > `HUGGINGFACE_HUB_CACHE` > `HF_HOME/hub` > default, with `TRANSFORMERS_CACHE` flagged deprecated) and counts every repo with BYTE-EXACT sizes, separating complete repos from the metadata-only stubs that look identical in a listing; `hf_repo` answers one repo's licence, gated flag, architecture, parameter count, weight (the Hub's `used_storage`, labelled as the measure it is, because this CLI line reports no per-file sizes), which files each consumer would fetch, and whether the local copy is complete / a stub / stale by revision / absent; `hf_cache` lists, verifies, prunes and removes — an UNCONFIRMED removal is the CLI's own `--dry-run`, `rm` needs the repo id repeated back and `prune` the word "prune"; `hf_download` reports the weight, refuses over a byte ceiling, needs the id repeated back, and answers with the bytes the cache actually GAINED. The cache scan is of the directory tree because the CLI's JSON answers `"size": "17.9G"` and `"last_accessed": "3 months ago"`, and it is what makes the finding reportable: MEASURED on this machine, 42 of 49 cached repos are a `config.json` and nothing else. Two skills (`huggingface-hub`, `huggingface-cache`) whose examples the package check parses. Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine, no socket, and no token ever read | +| `dsh-huggingface` | `huggingface` | the Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk. `hf_status` resolves the cache root through the library's own precedence (`HF_HUB_CACHE` > `HUGGINGFACE_HUB_CACHE` > `HF_HOME/hub` > default, with `TRANSFORMERS_CACHE` flagged deprecated) and counts every repo with BYTE-EXACT sizes, separating complete repos from the metadata-only stubs that look identical in a listing; `hf_repo` answers one repo's licence, gated flag, architecture, parameter count, weight (the Hub's `used_storage`, labelled as the measure it is, because this CLI line reports no per-file sizes), which files each consumer would fetch, and whether the local copy is complete / a stub / stale by revision / absent; `hf_cache` lists, verifies, prunes and removes — an UNCONFIRMED removal is the CLI's own `--dry-run`, `rm` needs the repo id repeated back and `prune` the word "prune"; `hf_download` reports the weight, refuses over a byte ceiling, needs the id repeated back, and answers with the bytes the cache actually GAINED. The cache scan is of the directory tree because the CLI's JSON answers `"size": "17.9G"` and `"last_accessed": "3 months ago"`, and it is what makes the finding reportable: MEASURED on this machine, 42 of 49 cached repos are a `config.json` and nothing else. Two skills (`huggingface-hub`, `huggingface-cache`) whose examples the package check parses. For a cached repo `hf_repo` also sizes the LOAD from the files alone - parameters implied by the weight bytes, KV cache as `2 x layers x kv_heads x head_dim x dtype_bytes` per token, and a context table with a FITS column against the `freeBytes` given - with the dtype read from the safetensors HEADER rather than the config, because MEASURED `all-mpnet-base-v2` states none and stores F32, which an fp16 assumption reports as twice the parameters and half the KV cache. Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine, no socket, and no token ever read | | `dsh-proto-lab` | `proto-lab` | the **prototyping lab**: five `lab_*` tools write a run into the lab root (`~/Desktop/vncode-lab/runs///` on a machine with a Desktop, `/lab` otherwise, `DSH_PROTO_LAB_ROOT` to move it; gitignored — the bundle ships the generator, not the runs), a runtime registry (`p5js`, `openframeworks`, and a template for the third) whose every module the checks drive, a committed example library beside each skill, an offline-vendored p5.js, and verification as an explicit ladder — `t0-structure` → `t4-measure` — that always names the tier it reached | | `dsh-browser` | `browser` | web surface: the host fetches and renders a page in a disposable sandboxed browser (**currently disabled by the master**) | | `dsh-themes` | `themes` | extra palettes (Nord, Monokai, Hacker, Cyber), header controls, branding, account-menu trimming | diff --git a/README.md b/README.md index 9e445a5..824dd93 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ way and what it touches. The exact versions are in | [`dsh-editor`](packages/dsh-editor/README.md) | Text and code tabs over a vendored CodeMirror 6, with save/create and a Markdown preview. Every extension is mapped through a guard, so an older engine opens the document unhighlighted instead of killing the tab. It also backs the `.scd`, diagram-source and research-document editors. | | [`dsh-frontend-craft`](packages/dsh-frontend-craft/README.md) | Front-end design craft: Impeccable's Apache-2.0 corpus vendored at a pinned commit, plus its 61-rule detector built to WebAssembly inside the package. Five `fe_*` tools include `fe_render`, which renders a page in headless Chrome or Edge and measures contrast, tap targets and overflow. There is no `npx impeccable`, no engine download and no network. A Frontend tab shows findings, artifacts and the direction round. | | [`dsh-gittree`](packages/dsh-gittree/README.md) | A read-only History tab: the workspace commits as a graph rail with lanes, merges and PR chips. Each commit lists the files it touched. It never runs a write. | -| [`dsh-huggingface`](packages/dsh-huggingface/README.md) | The Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk. `hf_repo` gives one repo's licence, gated flag, weight (the Hub's `used_storage`, labelled as such) and whether this disk already has it — complete, metadata-only, stale or absent; `hf_status` counts the stubs that look cached and cannot load; `hf_cache` verifies and reclaims, with an unconfirmed removal being the CLI's own dry run; `hf_download` reports the weight, refuses over a ceiling, and needs the repo id repeated back. Two skills teach the CLI and the cache layout. Host-only, zero npm dependencies, no bundled engine. | +| [`dsh-huggingface`](packages/dsh-huggingface/README.md) | The Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk. `hf_repo` gives one repo's licence, gated flag, weight (the Hub's `used_storage`, labelled as such) and whether this disk already has it — complete, metadata-only, stale or absent; `hf_status` counts the stubs that look cached and cannot load; `hf_cache` verifies and reclaims, with an unconfirmed removal being the CLI's own dry run; `hf_download` reports the weight, refuses over a ceiling, and needs the repo id repeated back. For a repo already cached it also sizes the LOAD — parameters from the weight bytes, the KV cache per token from the checkpoint's own attention heads, and a context table that says FITS against the `freeBytes` you pass — without loading the model. Two skills teach the CLI and the cache layout. Host-only, zero npm dependencies, no bundled engine. | | [`dsh-image`](packages/dsh-image/README.md) | An image viewer that fits, zooms and pans, and reads the source pixel under the pointer. It opens from the Files tab and the Media panel. | | [`dsh-image-upscale`](packages/dsh-image-upscale/README.md) | Four `upscale_*` tools over Real-ESRGAN, through the Python and torch this machine already has. It writes a NEW file and never the original, a manifest batch is a dry run by default, and the weight fetch refuses without `confirm`. Host-only, with no engine bundled. | | [`dsh-media`](packages/dsh-media/README.md) | The pack ffmpeg owner: `media_probe`, `media_run` and `media_frames` over a pinned, SHA-256-verified ffmpeg copy. It also serves the Range routes the video tab streams through. No other package ships ffmpeg. | diff --git a/packages/dsh-huggingface/README.md b/packages/dsh-huggingface/README.md index 61ea7a3..5b5ab4e 100644 --- a/packages/dsh-huggingface/README.md +++ b/packages/dsh-huggingface/README.md @@ -34,7 +34,11 @@ Measured on the machine that wrote this: `hf` is **1.26.1**, the cache holds the measure named**, which files each consumer would fetch (transformers, sentence-transformers, diffusers, GGUF quants, ONNX), and the local verdict — `complete`, `stub`, `stale` (cached revision vs the Hub's current `sha`) or - `absent`. + `absent`. For a repo that is **cached** it also answers the half a download size + does not: **WILL IT FIT** — the parameters the weight bytes imply, the KV cache + per token from the checkpoint's own attention heads, and a context-by-context + VRAM table that says `FITS` against the `freeBytes` you pass. Read from the + files, with no model loaded. - **`hf_cache`** — `list` (no CLI, no network), `verify`, `prune`, `rm`. An **unconfirmed removal is the CLI's own `--dry-run`**, so the answer is a real preview with the bytes it would cost; `rm` needs the repo id repeated back and @@ -63,6 +67,14 @@ directory). at all: the plan says so instead of inventing a number, and the ceiling is applied only to a measured size. +**A checkpoint's dtype is in its safetensors HEADER, not in its config.** The +parameter estimate and the KV size both divide or multiply by bytes-per-parameter, +so trusting `config.torch_dtype` — or defaulting to fp16 — misreports a whole +class of models. MEASURED: `sentence-transformers/all-mpnet-base-v2` states no +dtype and stores **F32**; assumed fp16 it reported *~219M parameters at 109M* and +**half** its real 72 KB/token KV cache. Reading the header's own `dtype` field +fixed both, and the answer names where the dtype came from. + ## How it plugs in | Piece | Value | diff --git a/packages/dsh-huggingface/checks/check-huggingface-node.mjs b/packages/dsh-huggingface/checks/check-huggingface-node.mjs index e2147f8..d2d03dd 100644 --- a/packages/dsh-huggingface/checks/check-huggingface-node.mjs +++ b/packages/dsh-huggingface/checks/check-huggingface-node.mjs @@ -14,7 +14,7 @@ // ceiling runs NO download, and an unconfirmed removal is a dry run. // // Run: node checks/check-huggingface-node.mjs -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { fileURLToPath } from 'node:url' @@ -36,7 +36,8 @@ import { selected, } from '../lib/hf.js' import { CLI_CANDIDATES, parseVersion, resolveCli } from '../lib/cli.js' -import { buildTools, formatBytes, formatParamCount } from '../lib/tools.js' +import { estimateVram, modelFields, safetensorsDtype } from '../lib/model.js' +import { buildTools, fitLines, formatBytes, formatParamCount } from '../lib/tools.js' import { SKILL_FILES, apply, createDeps, parseSkillFile, PLUGIN_VERSION, __internals } from '../lib/index.js' const here = path.dirname(fileURLToPath(import.meta.url)) @@ -84,7 +85,11 @@ function makeCache() { put(path.join(alpha, 'blobs', 'f'.repeat(64)), Buffer.alloc(3000, 1)) put(path.join(alpha, 'blobs', 'e'.repeat(64)), Buffer.alloc(100, 2)) put(path.join(alpha, 'snapshots', SHA_A, 'model.safetensors'), Buffer.alloc(3000, 1)) - put(path.join(alpha, 'snapshots', SHA_A, 'config.json'), Buffer.alloc(100, 2)) + // A REAL config, so the fit arithmetic has the head fields it needs. + put( + path.join(alpha, 'snapshots', SHA_A, 'config.json'), + JSON.stringify({ architectures: ['LlamaForCausalLM'], model_type: 'llama', hidden_size: 4096, num_hidden_layers: 32, num_attention_heads: 32, num_key_value_heads: 8, head_dim: 128, max_position_embeddings: 32768, torch_dtype: 'float16' }), + ) // acme/stub - metadata only const stub = path.join(root, 'models--acme--stub') put(path.join(stub, 'refs', 'main'), SHA_B + '\n') @@ -96,9 +101,24 @@ function makeCache() { const beta = path.join(root, 'models--acme--beta') put(path.join(beta, 'refs', 'main'), 'd'.repeat(40) + '\n') put(path.join(beta, 'snapshots', 'd'.repeat(40), 'model.safetensors'), Buffer.alloc(5000, 4)) + // acme/fp32 - a REAL safetensors header that says F32, with a config that says + // nothing about dtype: the header must be what the arithmetic uses. + const fp32 = path.join(root, 'models--acme--fp32') + put(path.join(fp32, 'refs', 'main'), 'f'.repeat(40) + '\n') + put(path.join(fp32, 'snapshots', 'f'.repeat(40), 'model.safetensors'), safetensorsFile('F32', 4000)) + put(path.join(fp32, 'snapshots', 'f'.repeat(40), 'config.json'), JSON.stringify({ hidden_size: 4096, num_hidden_layers: 32, num_attention_heads: 32, num_key_value_heads: 8, head_dim: 128 })) return root } +/** A minimal but REAL safetensors file: u64 header length, padded JSON, data. */ +function safetensorsFile(dtype, dataBytes) { + const header = JSON.stringify({ weight: { dtype, shape: [Math.round(dataBytes / 4)], data_offsets: [0, dataBytes] } }) + const padded = header + ' '.repeat((8 - (Buffer.byteLength(header) % 8)) % 8) + const prefix = Buffer.alloc(8) + prefix.writeBigUInt64LE(BigInt(Buffer.byteLength(padded)), 0) + return Buffer.concat([prefix, Buffer.from(padded, 'utf8'), Buffer.alloc(dataBytes, 1)]) +} + // --------------------------------------------------------------------------- // The manifest // --------------------------------------------------------------------------- @@ -132,10 +152,10 @@ check('no token at all', tokenPresence({}, false).present, false) // --------------------------------------------------------------------------- const root = makeCache() const scan = scanCache(root) -check('the scan finds every repo', scan.counts.repos, 4) +check('the scan finds every repo', scan.counts.repos, 5) check('...and marks the directory as present', scan.exists, true) check('the count splits complete from metadata-only', scan.counts.stubs, 1) -check('...with the rest complete', scan.counts.complete, 3) +check('...with the rest complete', scan.counts.complete, 4) check('types are counted separately', scan.counts.byType.dataset, 1) check('splitRepoDir reads a model directory', splitRepoDir('models--acme--alpha').id, 'acme/alpha') check('splitRepoDir reads a dataset directory', splitRepoDir('datasets--acme--data').type, 'dataset') @@ -164,7 +184,7 @@ check('...although it has no weight file', dataset.weights, false) check('a dataset is still a stub when it is only metadata', describeRepoDir(root, 'datasets--acme--data').stub === false, true) const filtered = scanCache(root, { type: 'model' }) -check('a type filter drops the others', filtered.counts.repos, 3) +check('a type filter drops the others', filtered.counts.repos, 4) const byName = scanCache(root, { filter: 'alph' }) check('a text filter selects by id', byName.repos.length === 1 && byName.repos[0].id, 'acme/alpha') const limited = scanCache(root, { limit: 2 }) @@ -172,6 +192,24 @@ check('a limit shortens the list', limited.repos.length, 2) check('...and is reported as limited', limited.limited, true) check('a missing cache root is an answer, not an error', scanCache(path.join(root, 'nope')).exists, false) +// --------------------------------------------------------------------------- +// The fit arithmetic: exact bytes, because "it fits" is the claim +// --------------------------------------------------------------------------- +const FIT_CONFIG = { architectures: ['LlamaForCausalLM'], hidden_size: 4096, num_hidden_layers: 32, num_attention_heads: 32, num_key_value_heads: 8, head_dim: 128, torch_dtype: 'float16' } +const fitFields = modelFields(FIT_CONFIG) +check('the fit reads layers', fitFields.layers, 32) +check('...KV heads (grouped-query attention)', fitFields.kvHeads, 8) +check('...and head dim', fitFields.headDim, 128) +const fitEstimate = estimateVram({ weightsBytes: 2_000_000, fields: fitFields, dtype: 'fp16', contexts: [4096] }) +check('KV per token = 2 x layers x kv_heads x head_dim x 2', fitEstimate.kvPerToken, 2 * 32 * 8 * 128 * 2) +check('...which is 128 KiB for this shape', fitEstimate.kvPerToken, 131_072) +check('parameters are implied by the bytes', fitEstimate.params, 1_000_000) +check('the allowance keeps its 512 MiB floor', fitEstimate.overhead, 512 * 1024 * 1024) +check('total = weights + KV x context + allowance', fitEstimate.vram[0].total, 2_000_000 + 131_072 * 4096 + 512 * 1024 * 1024) +check('fp32 doubles the KV term', estimateVram({ weightsBytes: 10, fields: fitFields, dtype: 'fp32' }).kvPerToken, 2 * 32 * 8 * 128 * 4) +check('a config with no head fields reports KV as UNKNOWN', estimateVram({ weightsBytes: 10, fields: modelFields({}) }).kvKnown, false) +check('a multimodal config is read through text_config', modelFields({ text_config: { num_hidden_layers: 24, num_attention_heads: 16, num_key_value_heads: 4, head_dim: 64 } }).layers, 24) + // --------------------------------------------------------------------------- // The CLI: the version trap, and how the binary is found // --------------------------------------------------------------------------- @@ -338,7 +376,7 @@ const versionOk = { status: 0, stdout: '1.26.1\n', stderr: 'Hint: a new version const { calls, tools } = harness({ HF_HUB_CACHE: root }, () => versionOk) const answer = await tool(tools, 'hf_status').execute({}) check('hf_status reports the CLI', answer.view.cli.bin + ' ' + answer.view.cli.version, 'hf 1.26.1') - check('hf_status counts the fixture repos', answer.view.cache.counts.repos, 4) + check('hf_status counts the fixture repos', answer.view.cache.counts.repos, 5) check('hf_status separates the stub', answer.view.cache.counts.stubs, 1) check('hf_status names the stub', answer.view.stubs[0].id, 'acme/stub') check('hf_status made exactly ONE process call', calls.length, 1) @@ -352,7 +390,7 @@ const versionOk = { status: 0, stdout: '1.26.1\n', stderr: 'Hint: a new version { const { tools } = harness({ HF_HUB_CACHE: root }, () => ({ status: null, error: 'ENOENT' })) const answer = await tool(tools, 'hf_status').execute({}) - check('with no CLI the cache scan still answers', answer.view.cache.counts.repos, 4) + check('with no CLI the cache scan still answers', answer.view.cache.counts.repos, 5) check('...and the install line is named', answer.text.includes('pip install -U huggingface_hub'), true) } @@ -390,6 +428,32 @@ const versionOk = { status: 0, stdout: '1.26.1\n', stderr: 'Hint: a new version check('...and the prose says not cached', absent.text.includes('not cached'), true) check('...and says nothing was downloaded', absent.text.includes('Nothing was downloaded') || absent.text.includes('hf_download'), true) + // The FIT is read from the files on disk - no Python, no load. + const fitted = await tool(tools, 'hf_repo').execute({ repo: 'acme/alpha', freeBytes: 25_769_803_776, contexts: [4096, 32768] }) + check('hf_repo estimates the fit from the cached files', fitted.view.fit.available, true) + check('...with the KV per token from the config', fitted.view.fit.estimate.kvPerToken, 131_072) + check('...and a FITS verdict against free VRAM', fitted.text.includes('FITS'), true) + check('...saying yes when it fits', fitted.text.includes('yes'), true) + const tight = await tool(tools, 'hf_repo').execute({ repo: 'acme/alpha', freeBytes: 1_000_000, contexts: [4096] }) + check('...and NO when the free VRAM is too small', tight.text.includes('NO'), true) + check('...naming the largest context that does fit', tight.text.includes('none of these fits'), true) + const noFit = await tool(tools, 'hf_repo').execute({ repo: 'acme/stub' }) + check('a metadata-only repo gets no fit estimate', noFit.view.fit.available, false) + check('...and the reason is the missing weights', noFit.text.includes('metadata only'), true) + const absentFit = await tool(tools, 'hf_repo').execute({ repo: 'acme/not-here' }) + check('an absent repo has no fit at all', absentFit.view.fit, null) + + // The dtype comes from the FILE, not from the config's claim. + const fp32Dir = path.join(root, 'models--acme--fp32', 'snapshots', 'f'.repeat(40)) + check('a safetensors header reports its own dtype', safetensorsDtype(path.join(fp32Dir, 'model.safetensors')), 'float32') + check('a file with no valid header reports none', safetensorsDtype(path.join(root, 'models--acme--alpha', 'snapshots', SHA_A, 'model.safetensors')), '') + const fp32Fit = await tool(tools, 'hf_repo').execute({ repo: 'acme/fp32', contexts: [4096] }) + check('the fit uses the header dtype', fp32Fit.view.fit.estimate.dtype, 'float32') + const fp32Bytes = statSync(path.join(fp32Dir, 'model.safetensors')).size + check('...so parameters divide by 4 bytes (header bytes included, a rounding error at real sizes)', fp32Fit.view.fit.estimate.params, Math.round(fp32Bytes / 4)) + check('...and the KV term is 4 bytes per element', fp32Fit.view.fit.estimate.kvPerToken, 2 * 32 * 8 * 128 * 4) + check('...and the answer says where the dtype came from', fp32Fit.text.includes('safetensors header'), true) + const stale = await tool(tools, 'hf_repo').execute({ repo: 'acme/beta' }) check('hf_repo detects a revision that moved', stale.view.local.state, 'stale') check('...and names the Hub revision it differs from', stale.text.includes(SHA_A.slice(0, 12)), true) diff --git a/packages/dsh-huggingface/lib/model.js b/packages/dsh-huggingface/lib/model.js new file mode 100644 index 0000000..c513ecc --- /dev/null +++ b/packages/dsh-huggingface/lib/model.js @@ -0,0 +1,215 @@ +/** + * dsh-huggingface — what a cached checkpoint will cost to LOAD, from its files. + * + * This is the half of a model-runner row that belongs to a Hub row: the question + * "should I download this?" does not end at the download size, it ends at "can + * this machine run it". Both halves are answered from the same bytes on disk, so + * no Python, no torch and no model load are involved. + * + * The arithmetic, and the reason each term is here: + * + * weights = the sum of the checkpoint's weight files (a safetensors file is + * stored at its save dtype, so its size IS its weight bytes) + * params = weights / bytes-per-parameter at that dtype (an ESTIMATE, and + * labelled as one: a sharded index would give the exact count) + * KV = 2 x layers x kv_heads x head_dim x dtype_bytes, PER TOKEN + * overhead = max(512 MiB, 10% of the weights) for activations, the allocator + * and workspaces + * + * The KV term is the one people get wrong, and the reason this file exists: on + * the machine that wrote this, a 32-layer model with 8 KV heads at head_dim 128 + * needs 128 KiB PER TOKEN, so 32k context is 4 GiB on top of the weights while + * 4k is 512 MiB. A model that "fits" at 4k and OOMs at 32k is behaving exactly + * as described here. + * + * Grouped-query attention is what makes the number smaller than a naive + * `2 x layers x heads x head_dim` would suggest, and a config that does not + * state its heads is reported as UNKNOWN rather than assumed. + */ + +import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs' +import path from 'node:path' + +/** The extensions a checkpoint keeps its weights in. */ +export const WEIGHT_FILES = /\.(safetensors|bin|pt|pth|ckpt)$/i + +/** Bytes per parameter, by dtype name. */ +export const DTYPE_BYTES = { float32: 4, fp32: 4, float16: 2, fp16: 2, bfloat16: 2, bf16: 2, int8: 1, int4: 0.5 } + +/** The safetensors dtype codes, mapped to the names a reader knows. */ +export const SAFETENSORS_DTYPE = { F32: 'float32', F16: 'float16', BF16: 'bfloat16', F8_E4M3: 'float8', F8_E5M2: 'float8', I64: 'int64', I32: 'int32', I16: 'int16', I8: 'int8', U8: 'uint8', BOOL: 'bool' } + +/** + * The dtype a `.safetensors` file ACTUALLY holds, from its header. + * + * The parameter estimate and the KV-cache size both divide or multiply by the + * bytes-per-parameter, so assuming fp16 because the config SAYS fp16 is how a + * 109M-parameter model is reported as 219M. MEASURED: on the machine that wrote + * this, `sentence-transformers/all-mpnet-base-v2` has no `torch_dtype` in its + * config and its weights are F32 - so the bytes divided by 2 and the model was + * called twice its size until the header was read. + * + * The header is a little-endian u64 length followed by that many bytes of JSON: + * a few tens of KB read from the FRONT of the file, never the tensors. + * + * @param file - a `.safetensors` path. + * @returns the dtype name, or '' when the header cannot be read. + */ +export function safetensorsDtype(file) { + let handle = null + try { + handle = openSync(file, 'r') + const lengthBytes = Buffer.alloc(8) + if (readSync(handle, lengthBytes, 0, 8, 0) !== 8) return '' + const length = Number(lengthBytes.readBigUInt64LE(0)) + if (!Number.isFinite(length) || length <= 0 || length > 100 * 1024 * 1024) return '' + const header = Buffer.alloc(length) + if (readSync(handle, header, 0, length, 8) !== length) return '' + const parsed = JSON.parse(header.toString('utf8')) + const counts = new Map() + for (const [key, value] of Object.entries(parsed)) { + if (key === '__metadata__' || value === null || typeof value !== 'object') continue + const dtype = typeof value.dtype === 'string' ? value.dtype : '' + if (dtype === '') continue + counts.set(dtype, (counts.get(dtype) ?? 0) + 1) + } + let best = '' + let bestCount = 0 + for (const [dtype, count] of counts) { + if (count > bestCount) { + best = dtype + bestCount = count + } + } + return SAFETENSORS_DTYPE[best] ?? '' + } catch (error) { + return '' + } finally { + if (handle !== null) { + try { + closeSync(handle) + } catch (error) { + /* already closed */ + } + } + } +} + +/** A number, or null. */ +function number(value) { + return typeof value === 'number' && Number.isFinite(value) ? value : null +} + +/** + * The language-model view of a config, including the multimodal nesting. + * + * A vision-language checkpoint keeps its text model under `text_config`, so + * reading only the top level finds no layers and reports the KV cache as + * unknown - which would be honest but useless. + */ +export function modelFields(config) { + const base = config !== null && typeof config === 'object' ? config : {} + const inner = base.text_config !== null && typeof base.text_config === 'object' ? base.text_config : base + const layers = number(inner.num_hidden_layers) ?? number(inner.n_layer) ?? number(inner.num_layers) + const heads = number(inner.num_attention_heads) ?? number(inner.n_head) + const kvHeads = number(inner.num_key_value_heads) ?? number(inner.multi_query_group_num) ?? heads + const hidden = number(inner.hidden_size) ?? number(inner.n_embd) ?? number(inner.d_model) + const headDim = number(inner.head_dim) ?? (hidden !== null && heads !== null && heads > 0 ? Math.round(hidden / heads) : null) + return { + architectures: Array.isArray(base.architectures) ? base.architectures.filter((entry) => typeof entry === 'string') : [], + modelType: typeof base.model_type === 'string' ? base.model_type : '', + layers, + heads, + kvHeads, + headDim, + hiddenSize: hidden, + contextLength: number(inner.max_position_embeddings) ?? number(inner.n_positions) ?? number(inner.seq_length) ?? number(inner.model_max_length), + vocabSize: number(inner.vocab_size), + torchDtype: typeof base.torch_dtype === 'string' ? base.torch_dtype : typeof base.dtype === 'string' ? base.dtype : '', + quantization: base.quantization_config !== null && typeof base.quantization_config === 'object' ? base.quantization_config : null, + } +} + +/** + * Read a checkpoint folder: its config and its weight bytes. + * + * @param dir - the directory holding `config.json` and the weights. + * @returns `{ config, weights, weightsBytes, hasWeights, warnings }`. + */ +export function readCheckpoint(dir) { + const warnings = [] + let config = null + if (existsSync(path.join(dir, 'config.json'))) { + try { + const raw = readFileSync(path.join(dir, 'config.json'), 'utf8') + config = JSON.parse(raw.slice(0, 2_000_000)) + } catch (error) { + warnings.push('config.json could not be read as JSON: ' + (error && error.message ? error.message : String(error))) + } + } else { + warnings.push('no config.json in this snapshot') + } + const weights = [] + let entries = [] + try { + entries = readdirSync(dir, { withFileTypes: true }) + } catch (error) { + entries = [] + } + for (const entry of entries) { + if (!entry.isFile() || !WEIGHT_FILES.test(entry.name)) continue + try { + weights.push({ name: entry.name, bytes: statSync(path.join(dir, entry.name)).size }) + } catch (error) { + /* a file removed mid-read is not a checkpoint we can size */ + } + } + const weightsBytes = weights.reduce((sum, file) => sum + file.bytes, 0) + // The dtype is read from a safetensors HEADER when there is one, because the + // config's claim and the file's contents disagree often enough to matter. + const safetensors = weights.find((file) => /\.safetensors$/i.test(file.name)) + const fileDtype = safetensors === undefined ? '' : safetensorsDtype(path.join(dir, safetensors.name)) + if (fileDtype !== '' && config !== null && typeof config.torch_dtype === 'string') { + const claimed = String(config.torch_dtype).toLowerCase() + if (/float32|fp32/.test(claimed) === false && /float32/.test(fileDtype)) { + warnings.push('config.json claims ' + config.torch_dtype + ' but the weights are ' + fileDtype + '; the header wins') + } + } + return { config, weights, weightsBytes, hasWeights: weights.length > 0, fileDtype, warnings } +} + +/** + * Size a checkpoint for a set of contexts. + * + * @param options - `{ weightsBytes, fields, dtype, contexts }`. + * @returns `{ params, dtype, bytesPerParam, kvPerToken, kvKnown, overhead, vram }` + * where each `vram` row is `{ context, weights, kv, total }`. + */ +export function estimateVram(options = {}) { + const weightsBytes = Number.isFinite(options.weightsBytes) ? options.weightsBytes : 0 + const fields = options.fields ?? {} + const dtype = String(options.dtype ?? fields.torchDtype ?? 'float16').toLowerCase() + const bytesPerParam = DTYPE_BYTES[dtype] ?? 2 + const params = weightsBytes > 0 && bytesPerParam > 0 ? Math.round(weightsBytes / bytesPerParam) : null + + const layers = fields.layers ?? 0 + const kvHeads = fields.kvHeads ?? 0 + const headDim = fields.headDim ?? 0 + // The cache is written at the model's own dtype; fp32 weights keep an fp32 + // cache, everything smaller is stored at 2 bytes. + const kvBytes = bytesPerParam >= 4 ? 4 : 2 + const kvPerToken = 2 * layers * kvHeads * headDim * kvBytes + const overhead = Math.max(512 * 1024 * 1024, Math.round(weightsBytes * 0.1)) + + const wanted = Array.isArray(options.contexts) && options.contexts.length > 0 ? options.contexts : [4096, 8192, 32768] + const vram = wanted + .filter((context) => Number.isFinite(context) && context > 0) + .slice(0, 6) + .map((context) => ({ + context, + weights: weightsBytes, + kv: kvPerToken * context, + total: weightsBytes + kvPerToken * context + overhead, + })) + return { params, dtype, bytesPerParam, kvPerToken, kvKnown: kvPerToken > 0, overhead, vram } +} diff --git a/packages/dsh-huggingface/lib/tools.js b/packages/dsh-huggingface/lib/tools.js index 2648a3d..142cdee 100644 --- a/packages/dsh-huggingface/lib/tools.js +++ b/packages/dsh-huggingface/lib/tools.js @@ -25,6 +25,7 @@ import path from 'node:path' import { HfError, messageOf } from './errors.js' import { CAPS, validateCache, validateDownload, validateRepo, validateSearch } from './validate.js' import { describeRepoDir, repoDirName, scanCache } from './cache.js' +import { estimateVram, modelFields, readCheckpoint } from './model.js' import { offlineOf, resolveCacheRoot, tokenPresence } from './paths.js' import { resolveCli } from './cli.js' import { @@ -119,7 +120,7 @@ function localState(root, type, id) { if (directory === null) return null const entry = describeRepoDir(root, directory) if (entry === null) return null - return { bytes: entry.bytes, files: entry.files, revision: entry.revision, weights: entry.weights, stub: entry.stub, layout: entry.layout, modifiedMs: entry.modifiedMs } + return { dir: entry.path, bytes: entry.bytes, files: entry.files, revision: entry.revision, weights: entry.weights, stub: entry.stub, layout: entry.layout, modifiedMs: entry.modifiedMs } } /** The local verdict for one repo against the Hub's current revision. */ @@ -148,6 +149,78 @@ export function weightLine(info) { return 'size not reported' } +/** + * What the cached checkpoint would cost to LOAD, or why it cannot be said. + * + * Only files on disk are read: a repo that is not cached, or is metadata only, + * has no weight bytes to size, and inventing them from the Hub's figure would be + * a claim about a model nobody has. + * + * @returns `{ available, reason?, fields?, estimate? }` or null when there is no + * local checkpoint at all. + */ +export function fitOf(local, spec, options = {}) { + if (local === null || typeof local.dir !== 'string') return null + if (local.stub === true || local.weights === false) { + return { available: false, reason: 'this copy is metadata only - there are no weight files to size' } + } + // A cache repo's root holds `snapshots//`; a local checkout holds the + // files directly. The config and the weights live in the SNAPSHOT, so that is + // what is read - the root would find neither. + const snapshot = typeof local.revision === 'string' && local.revision !== '' ? path.join(local.dir, 'snapshots', local.revision) : null + const target = snapshot !== null && existsSync(path.join(snapshot, 'config.json')) ? snapshot : local.dir + const checkpoint = readCheckpoint(target) + if (checkpoint.config === null) { + return { available: false, reason: checkpoint.warnings[0] ?? 'no config.json in this snapshot, so the attention heads are unknown' } + } + const fields = modelFields(checkpoint.config) + const wanted = String(options.dtype ?? 'auto').toLowerCase() + // Order matters: what the FILE holds beats what the config claims, because the + // bytes-per-parameter is the divisor for the parameter count and the KV size. + const dtype = wanted === 'auto' ? checkpoint.fileDtype || fields.torchDtype || 'float16' : options.dtype + const dtypeSource = wanted !== 'auto' ? 'asked for' : checkpoint.fileDtype !== '' ? 'from the safetensors header' : fields.torchDtype !== '' ? 'from config.json' : 'defaulted to fp16' + const contexts = Array.isArray(options.contexts) && options.contexts.length > 0 ? options.contexts : [4096, 8192, 32768] + const estimate = estimateVram({ weightsBytes: checkpoint.weightsBytes, fields, dtype, contexts }) + return { available: true, fields, estimate, weightsBytes: checkpoint.weightsBytes, dtypeSource, warnings: checkpoint.warnings } +} + +/** The fit section, as lines - shared by the online and offline answers. */ +export function fitLines(fit, freeBytes) { + const lines = [] + if (fit === null || fit.available !== true) { + lines.push('Fit: not estimated - ' + (fit !== null && fit.reason ? fit.reason : 'nothing on disk to size') + '.') + return lines + } + const estimate = fit.estimate + const free = typeof freeBytes === 'number' && Number.isFinite(freeBytes) ? freeBytes : null + lines.push('Fit - from the ' + formatBytes(fit.weightsBytes) + ' of weights on disk, no model loaded:') + const facts = [] + if (estimate.params !== null) facts.push('~' + formatParamCount(estimate.params) + ' params at ' + estimate.dtype + (fit.dtypeSource ? ' (' + fit.dtypeSource + ')' : '')) + if (estimate.kvKnown) facts.push('KV ' + formatBytes(estimate.kvPerToken) + '/token') + if (facts.length > 0) lines.push(' ' + facts.join(' \u00b7 ')) + if (!estimate.kvKnown) lines.push(' KV cache: UNKNOWN - this config does not state its attention heads, so only the weights are sized') + lines.push(' allowance: ' + formatBytes(estimate.overhead) + ' (activations and fragmentation: 10% of the weights, with a 512 MB floor)') + if (estimate.vram.length > 0) { + const headers = ['CONTEXT', 'WEIGHTS', 'KV CACHE', 'TOTAL'] + if (free !== null) headers.push('FITS ' + formatBytes(free)) + lines.push( + table( + headers, + estimate.vram.map((row) => { + const cells = [String(row.context), formatBytes(row.weights), formatBytes(row.kv), formatBytes(row.total)] + if (free !== null) cells.push(row.total <= free ? 'yes' : 'NO') + return cells + }), + ), + ) + if (free !== null) { + const fitting = estimate.vram.filter((row) => row.total <= free) + lines.push(fitting.length > 0 ? ' largest context that fits ' + formatBytes(free) + ': ' + fitting[fitting.length - 1].context : ' none of these fits in ' + formatBytes(free) + ': a smaller dtype or a shorter context is the answer') + } + } + return lines +} + /** Build the tools. @param deps - `{ env, runner, now, cache, log }`. */ export function buildTools(deps) { /** `hf_status`: what is here, without touching the network. */ @@ -282,7 +355,8 @@ export function buildTools(deps) { name: 'hf_repo', description: [ 'Describe ONE Hub repo before anything is fetched: licence, gated status (and the page that accepts it), downloads and likes, the architecture and parameter count when the card reports them, the file list, the repo weight AS THE HUB REPORTS IT, which files each CONSUMER would actually fetch (transformers, sentence-transformers, diffusers, llama.cpp/Ollama quants, ONNX), and whether THIS machine already holds it - complete, metadata-only, at an older revision, or absent.', - 'This is the tool that answers "how big is it and do I already have it" without downloading a byte. MEASURED: this CLI line gives no per-file sizes (its `--expand siblings` carries only names), so the weight is the Hub\'s `used_storage` - labelled as such rather than summed from files that were never sized.', + 'For a repo that IS cached, it goes one step further and answers the question the download size only half-answers: WILL IT FIT. It reads the cached `config.json` and the weight files and reports the parameters those bytes imply plus the KV-cache arithmetic - `2 x layers x kv_heads x head_dim x dtype_bytes` PER TOKEN - as a table of context lengths against total VRAM. Pass `freeBytes` (what your GPU has free) and each row says FITS or not; pass `contexts` to choose the lengths. No model is loaded, so the answer costs nothing.', + 'This is the tool that answers "how big is it, do I already have it, and can I run it" without downloading a byte. MEASURED: this CLI line gives no per-file sizes (its `--expand siblings` carries only names), so the weight is the Hub\'s `used_storage` - labelled as such rather than summed from files that were never sized. The FIT estimate is the opposite: it is read from the files on disk, and is absent rather than guessed when the repo is not cached.', 'With no network (or in offline mode) it reports what is on disk and says the Hub side was not asked.', ].join('\n'), parameters: { @@ -293,6 +367,9 @@ export function buildTools(deps) { repo: { type: 'string', description: 'A Hub id as `org/name`, e.g. "sentence-transformers/all-mpnet-base-v2".' }, type: { type: 'string', enum: ['model', 'dataset', 'space'], description: 'Repo kind. Default model.' }, revision: { type: 'string', description: 'A branch, tag or commit to describe instead of the default branch.' }, + freeBytes: { type: 'number', description: 'VRAM you actually have free, in bytes. Each fit row then says FITS or not. Omit and the sizes are reported without a verdict.' }, + contexts: { type: 'array', items: { type: 'number' }, description: 'Context lengths to size, up to 6. Default 4096, 8192, 32768.' }, + dtype: { type: 'string', enum: ['auto', 'bf16', 'fp16', 'fp32'], description: 'The dtype a load would use. Default: what config.json says, else fp16.' }, }, }, output: OUTPUT, @@ -302,6 +379,7 @@ export function buildTools(deps) { const spec = validateRepo(args) const cacheRoot = resolveCacheRoot(deps.env) const local = localState(cacheRoot.root, spec.type, spec.repo) + const fit = fitOf(local, spec, { dtype: args.dtype, contexts: args.contexts }) const offline = offlineOf(deps.env) if (offline) { const verdict = localVerdict(local, '') @@ -310,9 +388,13 @@ export function buildTools(deps) { lines.push(' ' + formatBytes(local.bytes) + ' in ' + local.files + ' file(s), revision ' + (local.revision === '' ? 'unknown' : local.revision.slice(0, 12)) + ', layout ' + local.layout) if (local.weights === false) lines.push(' No weight file is present: this copy cannot be loaded, and a load would need the network this machine has turned off.') } + if (fit !== null) { + lines.push('') + lines.push(...fitLines(fit, args.freeBytes)) + } lines.push('') lines.push('Unset HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE to ask the Hub about the licence, sizes and current revision.') - return { text: lines.join('\n'), view: { ok: true, offline: true, repo: { id: spec.repo, type: spec.type }, local: { ...verdict, entry: local } } } + return { text: lines.join('\n'), view: { ok: true, offline: true, repo: { id: spec.repo, type: spec.type }, local: { ...verdict, entry: local }, fit } } } const answer = await runHf(deps, buildInfoArgv, spec, { timeoutMs: CAPS.readTimeoutMs }) const info = normalizeInfo(answer.data, spec) @@ -340,6 +422,10 @@ export function buildTools(deps) { lines.push('') lines.push('Local: ' + verdict.label) if (verdict.state === 'complete' && local !== null) lines.push(' revision ' + local.revision.slice(0, 12) + ' \u00b7 layout ' + local.layout + ' \u00b7 ' + local.files + ' file(s)') + if (fit !== null) { + lines.push('') + lines.push(...fitLines(fit, args.freeBytes)) + } if (consumers.length > 0) { lines.push('') lines.push('What a consumer would fetch:') @@ -387,6 +473,7 @@ export function buildTools(deps) { files: info.files, }, local: { ...verdict, entry: local }, + fit, consumers, }, } diff --git a/packages/dsh-huggingface/skills/huggingface-cache/SKILL.md b/packages/dsh-huggingface/skills/huggingface-cache/SKILL.md index c903e61..52e44fb 100644 --- a/packages/dsh-huggingface/skills/huggingface-cache/SKILL.md +++ b/packages/dsh-huggingface/skills/huggingface-cache/SKILL.md @@ -142,6 +142,35 @@ making a blobs-only size rule report zero. `HF_HUB_DISABLE_SYMLINKS=1` forces copies deliberately (for example on a network share) and the `HF_HUB_DISABLE_SYMLINKS_WARNING=1` variable only silences the notice. +## Will it fit, read from the files + +A cached checkpoint can be sized for a LOAD without loading it, because the +numbers are all on disk: + +``` +weights = the sum of the weight files (a safetensors file is stored at its + save dtype, so its size IS its weight bytes) +params = weights / bytes-per-parameter (2 for fp16/bf16, 4 for fp32) +KV/token = 2 x layers x kv_heads x head_dim x dtype_bytes +total = weights + KV/token x context x batch + max(512 MiB, 10% of weights) +``` + +`hf_repo` on a cached repo does exactly this: pass `freeBytes` (what the GPU has +free) and it prints a context table with a `FITS` column; pass `contexts` to +choose the lengths. The KV term is the one that surprises people - a 32-layer +model with 8 KV heads at head_dim 128 needs **128 KiB per token**, so 4k is +512 MiB and 32k is 4 GiB on top of the weights. + +**The dtype must come from the file.** A safetensors header carries its own +`dtype` per tensor, and that is authoritative - `config.torch_dtype` is often +absent or stale. Measured here: `all-mpnet-base-v2` states nothing and stores +F32; assuming fp16 reported twice the parameters and half the KV cache. `hf_repo` +reads the header and says which source it used. + +If the repo is NOT cached, there is no estimate - the answer says so rather than +inventing one from the Hub's storage figure, because the attention heads live in +the config file that was never downloaded. + ## What a correct size report says A number is only honest with its method attached: diff --git a/packages/dsh-huggingface/skills/huggingface-hub/SKILL.md b/packages/dsh-huggingface/skills/huggingface-hub/SKILL.md index f04f191..53b1c8d 100644 --- a/packages/dsh-huggingface/skills/huggingface-hub/SKILL.md +++ b/packages/dsh-huggingface/skills/huggingface-hub/SKILL.md @@ -192,7 +192,7 @@ is worth using instead of shelling out when the question is one of these: |---|---| | `hf_status` | is `hf` here, which version, where the cache is, what is in it (complete vs metadata-only) | | `hf_search` | what exists, ranked, with licence and gated flags | -| `hf_repo` | what ONE repo weighs, what a consumer would fetch, whether this disk already has it, at which revision | +| `hf_repo` | what ONE repo weighs, what a consumer would fetch, whether this disk already has it, at which revision — and for a cached repo, whether it will FIT (KV arithmetic, `freeBytes`) | | `hf_cache` | list / verify / prune / rm, with an unconfirmed removal being a dry run | | `hf_download` | fetch, after reporting the size and taking the repo id back as `confirm` |