Skip to content

cli: add tensorfold tfq3 MODEL subcommand for TFQ3 conversion and inspection - #5018

Merged
ashhart merged 14 commits into
mainfrom
feat/tfq3-cli
Nov 28, 2026
Merged

ashhart merged 14 commits into
mainfrom
feat/tfq3-cli

Conversation

@ashhart

@ashhart ashhart commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds the tensorfold tfq3 CLI subcommand so users can pull, convert, and inspect cross-platform TFQ3 checkpoints directly from TensorFold — for both dedicated families and any Safetensors architecture, with zero-install native Zig encoding when the external tfq3 GPU binary is not installed.

What's included

  • tensorfold tfq3 MODEL (zig/src/cli/tfq3.zig, zig/src/cli/cli.zig):
    • Accepts a local directory or a Hugging Face repo id (owner/name[@revision]), pulling uncached repos through tensorfold pull unless --no-pull is set.
    • Auto-detects dedicated TFQ3 families (qwen3_5, qwen4_exp, glm5_next) and Qwen3.8-27B residual precision (bf16 vs. q8) from config.json.
    • Routes any other Safetensors architecture (or invocations passing --bits 3|4|5, --target-gib GB, --fit auto|GB, --quantize-vision, --quantize-drafter, or --quantize-embed) to the model-agnostic converter.
    • Dispatches to tfq3 (https://github.com/ashhart/TFQ) when installed, fails closed if an explicit --converter PATH is missing, and supports --dry-run and tensorfold tfq3 doctor.
  • Built-in zero-install pure-Zig TFQ3 encoder (zig/src/cli/tfq3_encode.zig):
    • Automatically runs when tfq3 is not installed (or when --native is passed), supporting BF16/F16/F32 Safetensors, arbitrary 2D tensor shapes zero-padded to 128-multiples (TfpnTensorMeta.pad[0..2]), --target-gib / --fit auto (via sys.machine.detect), and --quantize-vision / --quantize-drafter / --quantize-embed.
    • Generates deterministic 16 KiB Max-Lloyd PWV3 v3 tables, 16 KiB-aligned TFPN v3 shards, residual.safetensors, and copies config.json / tokenizer files.
  • Native shard inspection (tensorfold tfq3 inspect [-v] DIR):
    • Validates pw_v3_tables.bin and 16 KiB-aligned TFPN / TFPW v3 shards natively when tfq3 is absent.
  • Tests & Docs (zig/src/cli/tfq3_test.zig, docs/quantization.md, CHANGELOG.md):
    • Unit tests covering argument parsing, HF pull/caching, dedicated + generic family routing, explicit --converter fail-closed behavior, --dry-run, doctor, native inspection + negative alignment controls, and end-to-end native Zig encoding (--bits 4 and --fit auto).

Verification (Head 43bd130)

  • zig fmt --check build.zig zig — pass
  • zig build test-cuda-host — pass (includes cli/tests.zig, tfq3_test.zig, and Windows checkpoint_cli cross-compile)
  • zig build native -Dcpu=apple_m1 — pass (including libc_mem check)
  • Cross-tool live interop (tensorfold-native tfq3 --native --bits 3|4|5 → tfq3-inspect -v → reference/tfq3_reference.py):
    • 3-bit: 14.59 dB (exact 0.00 dB encoder/decoder match, pad_rms = 0.00000)
    • 4-bit: 19.73 dB (exact 0.00 dB match, pad_rms = 0.00000)
    • 5-bit: 24.04 dB (exact 0.00 dB match, pad_rms = 0.00000)
  • python3 tools/pr_check.py --pr 5018 — merge base b6ab6dbfd7c6f7cde6e524433ee67dc7fc664c31; 9 changed files; lean 165 vs 165, 0 new; 0 error(s), 0 warning(s)

ashhart added a commit that referenced this pull request Nov 25, 2026
ashhart added a commit that referenced this pull request Nov 25, 2026
ashhart added a commit that referenced this pull request Nov 25, 2026
@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Rebased onto origin/main (47a605aa, head aa2941a6, MERGEABLE, pr_check.py --pr 5018: 0 error(s), 0 warning(s); lean 164 vs 164, 0 new) and accelerated the built-in pure-Zig TFQ3 encoder with $O(\log g)$ separable Max-Lloyd lookup:

  • [4096 x 4096] BF16 single-threaded CPU throughput: 37.8M weights/s (3b, 14.61 dB), 33.7M weights/s (4b, 19.76 dB), 30.7M weights/s (5b, 24.07 dB)
  • Cross-tool parity (tensorfold-native tfq3 --native -> tfq3-inspect -> tfq3_reference.py): exact 0.00 dB match across 3b/4b/5b.

ashhart added a commit that referenced this pull request Nov 25, 2026
@jschmied

Copy link
Copy Markdown
Contributor

@ashhart some error paths and options in the converter, read at 8f9fccd8bc (not run):

  1. An impossible --target-gib still succeeds (zig/src/cli/tfq3_encode.zig:470-490). Every job starts at 3 bits without checking that the 3-bit total fits budget, so --target-gib 1 (budget 0) writes an all-3-bit checkpoint and reports success. Rejecting a target below the 3-bit minimum, and checking the written size, would close it.
  2. owner/name@rev is parsed but not used (tfq3.zig:292, :305). hub.cachedSnapshot(root, repo) takes refs/main or the newest snapshot, so another cached revision gets converted without notice. Looking up the requested revision, and writing the source sha into the output, would make conversions reproducible.
  3. --out can equal the source. Nothing rejects the alias (or a symlink to it). writeResidualSafetensors creates out/residual.safetensors while it reads tensors from the source, so a source with its own residual.safetensors gets truncated before it is read. Writing into a temporary directory and renaming it at the end would also cover stale shards in an existing --out.
  4. The safetensors header parser skips the checks core/checkpoint.zig does (tfq3_encode.zig:338-352). A negative data_offsets traps at @intCast, o1 < o0 underflows len, and neither offsets against the file size nor shape x dtype against the byte count are checked before decodeToPaddedF32 indexes the buffer.
  5. The whole compressed model is in memory twice. all_scales/all_words collect every tensor, and writeTfpnShard then allocates another total_size buffer to serialize it. On a 128 GB box this limits the native path to roughly half the memory in output.
  6. The native path drops options without saying so (runNativeEncode, tfq3.zig:378-399). --residual, --ple-bits, --trace, --nonmoe-model, --family and --skip-existing are not passed on, --profile 3.5b becomes 4 bits, and --quantize-drafter sets flag_drafter on every tensor (tfq3_encode.zig:448). Refusing options the native path can't honour would keep its output what the command line asked for.
  7. inspect on the native path checks only pw_v3_tables.bin (size, magic, version), then lists the shards. The tensor metadata, offsets and lengths are not validated, although CUDA: native TFQ3 (3/4/5-bit 2D-FWHT) runtime + drafters for Qwen3.8-27B, GLM-5.3-Flash, and Flash Next #4986's validateTfpn/validateTfpw already do that. One format module shared by the CLI, Metal and CUDA would keep the checks from drifting.
  8. Smaller: names of 80+ bytes keep their last 79 bytes (tfq3_encode.zig:452), so two long names can collide in the TFPN table; residual tensor names go into the JSON header unescaped (:567); padded dims are stored as the tensor size (m.r = pad_r, :510), so CUDA: native TFQ3 (3/4/5-bit 2D-FWHT) runtime + drafters for Qwen3.8-27B, GLM-5.3-Flash, and Flash Next #4986's findChecked refuses a non-128-multiple projection with Tfq3Shape, which makes "loads unmodified on both Metal and CUDA" in docs/quantization.md broader than what is tested.

Use explicit conversion admission with ordinary verified pulls and publish requested revision refs. Preserve generic residual choices, normalize local default outputs, and accept the Flash Next MTP shard identity. Validate direct encoder names and head widths, propagate config stat errors, and release scales on allocation failure. Pin each boundary with host regressions and describe native conversion limits.
@ashhart
ashhart merged commit 53f24ba into main Nov 28, 2026
1 check failed
@ashhart
ashhart deleted the feat/tfq3-cli branch November 28, 2026 08:25
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