8000 Qwen3.5 GGUF support, repo @revision/:variant specs, benchmark_generate, and qwen3.5-4b-gguf modeltests by janpfeifer · Pull Request #99 · gomlx/go-huggingface · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ go-huggingface/
│ └── ModelTests.md # Architecture & developer guide for full model tests (modeltests/)
├── examples/
│ ├── BAAI-bge-small-en-v1.5/ # BGE Small repo constants & README
│ ├── dolly/ # Dolly dataset browser demo
│ ├── dolly/ # Dolly dataset schema & generation benchmark (`benchmark_generate`)
│ ├── gemma4-e4bit/ # Gemma 4 E4B interactive generation demo
│ ├── kalmgemma3/ # KaLM-Gemma3 12B repo helpers & task prompts
│ ├── minilm-l6-v2-gguf/ # GGUF MiniLM repo constants
Expand Down Expand Up @@ -73,7 +73,7 @@ go-huggingface/
### 3.1. `hub`
Manages downloading and access to HuggingFace repositories.
- **Three Repository Modes**:
1. **Remote (`hub.New(id)`)**: Downloads from HuggingFace Hub into the local cache (`~/.cache/huggingface/hub/` or `$XDG_CACHE_HOME/huggingface/hub/`).
1. **Remote (`hub.New(id)`)**: Downloads from HuggingFace Hub into the local cache (`~/.cache/huggingface/hub/` or `$XDG_CACHE_HOME/huggingface/hub/`). `id` supports the inline `<owner>/<repo>[@<revision>][:<variant>]` syntax (parsed by `hub.ParseRepoSpec`), setting `Repo.Revision()` and `Repo.Variant()` while keeping `Repo.ID` clean for cache compatibility.
2. **Local (`hub.NewLocal(dir)`)**: Reads directly from a local folder on disk without any network requests. Useful for offline environments, `git clone` checkouts, or Docker images.
3. **Embedded (`hub.NewEmbed(fsys, subDir)`)**: Reads directly from an `fs.FS` (e.g., `//go:embed`). Operates fully in-memory.
- **Preferred File Access APIs**:
Expand Down Expand Up @@ -111,7 +111,7 @@ Manages downloading and access to HuggingFace repositories.
- Features pure-Go dequantizers and raw `Uint8` GGML block loaders (`ReadTensorRaw`, `ToGGMLQuantType`) for standard and k-quant block formats:
- `Q8_0`, `Q4_0`, `Q4_1`, `Q5_0`, `Q5_1`, `IQ4_NL`
- `Q2_K`, `Q3_K`, `Q4_K`, `Q5_K`, `Q6_K`, `Q8_K`
- Provides multi-file `.gguf` quantization selection (`SelectGGUFFile`, preferring `Q4_K_M` first, overridable via `Model.WithFile`) and embedded tokenizer extraction (`File.TokenizerParams`, `File.LoadTokenizer`).
- Provides multi-file `.gguf` quantization selection (`SelectGGUFFile`, preferring `Q4_K_M` first, `SelectGGUFFileForVariant` reading `hub.Repo.Variant()` such as `:Q4_K_M` or `:UD-Q4_K_XL`, overridable via `Model.WithFile`) and embedded tokenizer extraction (`File.TokenizerParams`, `File.LoadTokenizer`).
- Reads half-precision FP16 scales using `compute/dtypes/float16`.

### 3.5. `models/transformer`
Expand Down
48 changes: 45 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,51 @@ See examples:
a small library that provides easy access to this specific dataset, and serves as an example of how to access others.
It includes [benchmark_embed](https://github.com/gomlx/go-huggingface/tree/main/examples/msmarco/benchmark_embed/),
a command-line benchmark of sentence embeddings, that also serves as an example of how to use the library.
* [Tencent's KaLM-Embedding-Gemma3-12B-2511 Sentence Encoder](https://github.com/gomlx/go-huggingface/tree/main/examples/kalmgemma3):
a small library that makes it trivial to use this model and serves as an example of how to use others.
* [BAAI (Beijing Academy of Artificial Intelligence) BGE Small Sentence Embedder (English) v1.5](https://github.com/gomlx/go-huggingface/tree/main/examples/BAAI-bge-small-en-v1.5): a small and very performant sentence embedder (BERT-based).
* [Databricks Dolly 15k dataset](https://github.com/gomlx/go-huggingface/tree/main/examples/dolly):
a small library with a pre-generated Go struct schema for the instruction-following dataset.
It includes [benchmark_generate](https://github.com/gomlx/go-huggingface/tree/main/examples/dolly/benchmark_generate/),
a command-line benchmark and example for text generation (supporting GoMLX models, Ollama, and teacher-forced comparisons).

### Models Known to Work

The models below are verified end-to-end against independent reference runtimes (PyTorch/HuggingFace and `llama.cpp`) in [`modeltests/`](https://github.com/gomlx/go-huggingface/tree/main/modeltests) (see [`docs/ModelTests.md`](https://github.com/gomlx/go-huggingface/blob/main/docs/ModelTests.md)).

Many other variants, or similar models also work, but we don't keep track of them.

Also, it's generally very easy to add support to new models (at least if they fit in my memory/GPU), just create an issue for models you would like to see supported.

* **Generative LLMs**:
* `Qwen/Qwen3.5-4B` (SafeTensors, BF16 — hybrid Gated DeltaNet + gated GQA)
* `unsloth/Qwen3.5-4B-GGUF` (GGUF — e.g., `:Q4_0`, `:Q4_K_M`, etc.)
* `google/gemma-4-E2B-it` and `google/gemma-4-E4B-it` (SafeTensors, BF16 — gated repos)
* **Sentence Embedders**:
* `BAAI/bge-small-en-v1.5` (SafeTensors, FP32)
* `sentence-transformers/all-MiniLM-L6-v2` (SafeTensors, FP32)
* `ChristianAzinn/bge-base-en-v1.5-gguf` (GGUF, e.g., `:Q4_0`)
* `second-state/All-MiniLM-L6-v2-Embedding-GGUF` (GGUF — all 13 quantizations: `Q2_K` through `Q8_0` and `F16`)
* `tencent/KaLM-Embedding-Gemma3-12B-2511` (SafeTensors, BF16)
* **Time-Series & Vision**:
* `mistralai/Timestral-28M` and `mistralai/Timestral-123M` (time-series forecasting, `models/timestral`)
* Segment Anything 2 (`models/sam2`)

### How To Specify A Model

`hub.New(spec)` (and CLI tools such as `hubinfo`, `benchmark_embed`, and `benchmark_generate`) accepts a repository specifier of the form:

```text
<owner>/<repo>[@<revision>][:<variant>]
```

* **`<owner>/<repo>`**: Standard HuggingFace Hub repository ID (e.g., `Qwen/Qwen3.5-4B`, `BAAI/bge-small-en-v1.5`, `unsloth/Qwen3.5-4B-GGUF`).
* **`@<revision>`** *(optional)*: Git branch, tag, or 40-character commit SHA to pin (defaults to `main`). Programmatic equivalent: `repo.WithRevision(rev)`.
* **`:<variant>`** *(optional)*: Sub-variant selector, most commonly used to pick a specific GGUF quantization in multi-file `.gguf` repositories (e.g., `:Q4_K_M`, `:Q4_0`, `:UD-Q4_K_XL`, `:BF16`, or an exact `.gguf` filename). When omitted for a multi-file GGUF repository, `go-huggingface` automatically picks a default quantization (preferring `Q4_K_M`) while ignoring vision-projector `mmproj*` files unless explicitly requested. Programmatic equivalent: `repo.WithVariant(variant)`.

Examples:

* `Qwen/Qwen3.5-4B` — default `main` revision, SafeTensors weights.
* `unsloth/Qwen3.5-4B-GGUF:Q4_0` — `Q4_0` quantization from the GGUF repo (`Qwen3.5-4B-Q4_0.gguf`).
* `unsloth/Qwen3.5-4B-GGUF@main:UD-Q4_K_XL` — explicit `main` revision and `UD-Q4_K_XL` quantization.
* `google/gemma-4-E4B-it@<commit-sha>` — pinned to an exact commit hash (skips the Hub revision-info lookup when cached).


---
Expand Down
6 changes: 6 additions & 0 deletions cmd/hubinfo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ func main() {
})

metaTable.Row("Model ID", repo.ID)
if rev := repo.Revision(); rev != "" && rev != "main" {
metaTable.Row("Revision", rev)
}
if variant := repo.Variant(); variant != "" {
metaTable.Row("Variant", variant)
}
metaTable.Row("Tags", strings.Join(info.Tags, ", "))
metaTable.Row("Downloads / Likes", fmt.Sprintf("%s / %s", humanize.Count(info.Downloads), humanize.Count(info.Likes)))
metaTable.Row("Latest Update", info.LastModified.Local().Format(time.RFC1123))
Expand Down
25 changes: 25 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,31 @@

## Unreleased

- 2026/12/03:
- `modeltests`, `docs/ModelTests.md`, `README.md`:
- Extended `modeltests/internal/generators/yzma` with `-task=generate` (using `llama.Decode` + `llama.GetLogitsIth`, clearing SSM/KV memory between prompts, and filtering special tokens against GGUF header metadata) to generate golden reference specs for GGUF generative LLMs.
- Added `qwen3.5-4b-gguf` (`unsloth/Qwen3.5-4B-GGUF`, `Q4_0` variant) to `modeltests/testdata/qwen3.5-4b-gguf/spec.json` and `docs/ModelTests.md`.
- Updated `README.md` Overview section: replaced per-model example links with a **Models Known to Work** list and added a **How To Specify A Model** sub-section documenting `<owner>/<repo>[@<revision>][:<variant>]`.
- `examples/dolly/benchmark_generate`:
- Renamed `examples/dolly/browse` to `examples/dolly/benchmark_generate` and updated documentation references.
- `examples/msmarco/benchmark_embed`:
- Disabled printing the metrics table for the warmup run (printing only duration and unique shape count instead), since warmup skips duplicate shapes and its counts/speeds are not comparable to the benchmark run.
- `models/transformer`, `tokenizers/hftokenizer`:
- Added full Qwen3.5 (`general.architecture = "qwen35"`) GGUF model support in `models/transformer`:
- Extracted `attention.key_length` (`HeadDim`), `rope.dimension_count` (partial RoPE `PartialRotaryFactor`), `full_attention_interval`, and `ssm.*` (`conv_kernel`, `state_size`, `group_count`, `time_step_rank`, `inner_size`) metadata in `applyGGUFMetadata`, and recognized `"qwen35"` in `CreateGoMLXModel` and `detectCausalMask`.
- Kept `blk.{N}.attn_qkv.{weight,bias}` fused as `linear_attn/in_proj_qkv` on Gated DeltaNet layers (instead of splitting 3-ways as BERT QKV), mapped `attn_gate`, `ssm_alpha`, `ssm_beta`, `ssm_out`, `ssm_conv1d`, `ssm_a`, `ssm_dt.bias`, and `ssm_norm`, reshaped 2D `ssm_conv1d.weight` (`[convDim, K]`) to `[convDim, 1, K]`, and converted llama.cpp's `ssm_a` (`-exp(A_log)`) back to `A_log` (`log(-ssm_a)`).
- Configured `RMSNormOffset(0.0)` (since llama.cpp bakes the `+1.0` zero-centered RMSNorm offset into GGUF norm weights) and `WithLinearTiledKVHeads(true)` (matching llama.cpp's tiled V-head layout without dequantizing weights) for GGUF Qwen3.5 models.
- Added `qwen35` and `qwen2` pre-tokenizer (`Split` + `ByteLevel(use_regex=false)` + `NFC` normalizer) handling in `hftokenizer.NewFromGGUF` for `tokenizer.ggml.pre`, matching HuggingFace `tokenizer.json` identically.
- Added unit tests (`TestGGUFQwen35EndToEnd`, `TestGGUFQwen35RealParity`, `TestNewFromGGUF_Qwen35PreTokenizer`).
- `hub`, `models/gguf`, `models/transformer`, `cmd/hubinfo`, `examples/msmarco/benchmark_embed`:
- Added inline `<owner>/<repo>[@<revision>][:<variant>]` repository spec parsing via `hub.ParseRepoSpec` and `hub.New` (e.g., `unsloth/Qwen3.5-4B-GGUF:Q4_K_M` or `unsloth/Qwen3.5-4B-GGUF@main:UD-Q4_K_XL`), exposing `Repo.Revision()`, `Repo.Variant()`, and `Repo.WithVariant(...)` while keeping `Repo.ID` and cache layout unchanged.
- Added `gguf.SelectGGUFFileForVariant` (matching exact path, basename, parent directory, or delimited quantization tag while excluding `mmproj*` unless explicitly requested, with actionable errors on missing/ambiguous matches) and wired `gguf.Model.Load` and `transformer.LoadModel` to honor `repo.Variant()`.
- Updated `cmd/hubinfo` to display `Revision` (when non-`main`) and `Variant` (when set).
- Removed `-gguf_file` from `examples/msmarco/benchmark_embed` in favor of passing `:<variant>` inline in `-model`.
- `examples/dolly/browse`:
- Added `-save=<file>` flag to save generated responses, per-example timings/speeds (indexed by 1-based example number), warm summary stats, and CLI flags to a JSON file.
- Added `-teacher_forced=<saved_file>` flag to force GoMLX KV-cache generation to follow saved reference tokens for apples-to-apples performance benchmarking across backends while tracking exact sentence and token match counts, displaying saved baseline stats in the summary, and emitting warnings on `-prompt_tokens`/`-gen_tokens` mismatches or uncovered `-n`/`-ex` examples.

- 2026/12/01:
- `modeltests`, `docs/ModelTests.md`:
- Added optional `-warmup` / `-warmup=N` flag to run `N` untimed warmup passes (default `1` when `-warmup` is passed without a value) before each timed inference execution (embeddings, prefill logits, teacher-forced KV generation, and time-series) and display a `Warmup` column alongside warmed-up `Infer` timings in the summary table for fair cross-backend comparisons (e.g., `xla:cuda` vs. `cuda`).
Expand Down
7 changes: 5 additions & 2 deletions docs/ModelTests.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ modeltests/
│ │ └── embeddings.f32
│ ├── qwen3.5-4b/ # Hybrid Gated DeltaNet + full attention generative LLM
│ │ └── spec.json
│ ├── qwen3.5-4b-gguf/ # Qwen3.5-4B GGUF quantized generative LLM (Q4_0)
│ │ └── spec.json
│ ├── gemma4-e4b/ # Gemma 4 generative LLM
│ │ └── spec.json
│ └── timestral/
Expand Down Expand Up @@ -341,7 +343,7 @@ All golden files **must** be produced by an independent reference runtime (never
- Built on the battle-tested `llama.cpp` loader, pooling, and GGUF resolution logic from `../benchmarks/yzma_embedder/main.go`.
- **Key difference from `yzma_embedder`**: Uses `llama.cpp`'s own `llama.Tokenize` and `llama.Detokenize` (via `llama.ModelGetVocab`) to produce the reference token IDs and decoded strings—ensuring `go-huggingface`'s embedded GGUF tokenizer is tested against true `llama.cpp` output!
- Supports `-all_quants` to iterate over every `.gguf` file in a multi-quantization HuggingFace repo and emit all variants + `.f32` files into one `testdata/<model>/` directory in a single run.
- Extensible to GGUF generative LLMs (`-task=generate`) using `llama.Decode` + `llama.GetLogitsIth` for top-K logits and greedy generation.
- Supports `-task=generate` for GGUF generative LLMs using `llama.Decode` + `llama.GetLogitsIth` for prefill top-K logits and greedy generation (clearing recurrent/SSM state via `llama.MemoryClear(mem, true)` between prompts).

---

Expand All @@ -357,6 +359,7 @@ All golden files **must** be produced by an independent reference runtime (never
| `minilm-l6-v2-gguf` | `second-state/All-MiniLM-L6-v2-Embedding-GGUF` | GGUF | Transformer / Tokenize + Embed | **All 13 supported quants**: `Q2_K`, `Q3_K_S`, `Q3_K_M`, `Q3_K_L`, `Q4_0`, `Q4_K_S`, `Q4_K_M`, `Q5_0`, `Q5_K_S`, `Q5_K_M`, `Q6_K`, `Q8_0`, `F16` | `small` | Go `yzma` (`llama.cpp`) |
| `kalm-gemma3-12b` | `tencent/KaLM-Embedding-Gemma3-12B-2511` | SafeTensors | Transformer / Tokenize + Embed | Default (BF16) | `large` | Python (`sentence-transformers`) |
| `qwen3.5-4b` | `Qwen/Qwen3.5-4B` | SafeTensors | Transformer / Tokenize + Generate | Default (BF16) | `medium` | Python (`transformers`) |
| `qwen3.5-4b-gguf` | `unsloth/Qwen3.5-4B-GGUF` | GGUF | Transformer / Tokenize + Generate | `Q4_0` | `medium` | Go `yzma` (`llama.cpp`) |
| `gemma4-e4b` | `google/gemma-4-E4B-it` | SafeTensors | Transformer / Tokenize + Generate | Default (BF16, gated) | `medium` | Python (`transformers`) |
| `timestral` | `mistralai/Timestral-28M` & `123M` | SafeTensors | TimeSeries / Forecast | `28m`, `123m` | `small` | Python (PyTorch) |

Expand Down Expand Up @@ -446,7 +449,7 @@ go test -v -p=1 ./modeltests -modeltests \
3. **Phase 3 — Populate Initial Model Roster (Done)**:
- Generated specs & golden `.f32` files for `baai-bge-small-en-v1.5`, `sentence-transformers-all-minilm-l6-v2`, `bge-base-en-v1.5-gguf`, `minilm-l6-v2-gguf` (all 13 quantizations), `kalm-gemma3-12b`, `qwen3.5-4b`, `gemma4-e4b`, and `timestral` (28M & 123M).
4. **Phase 4 — Clean Up Redundant Example Tests (Done)**:
- Removed redundant parity tests and golden `.txt`/`.f32` test files from `examples/BAAI-bge-small-en-v1.5`, `examples/minilm-l6-v2-gguf`, `examples/kalmgemma3`, and `examples/timestral` while preserving helper packages and runnable demos (`gemma4-e4bit/demo`, `dolly/browse`, `msmarco/benchmark_embed`, `timestral/main.go`).
- Removed redundant parity tests and golden `.txt`/`.f32` test files from `examples/BAAI-bge-small-en-v1.5`, `examples/minilm-l6-v2-gguf`, `examples/kalmgemma3`, and `examples/timestral` while preserving helper packages and runnable demos (`gemma4-e4bit/demo`, `dolly/benchmark_generate`, `msmarco/benchmark_embed`, `timestral/main.go`).
- Removed superseded `internal/testing/` and legacy `internal/py/{embed_sentence,tokenize_bge}.py`.
5. **Phase 5 — Parallel `onnx-gomlx/modeltests/` (Next)**:
- Create a matching `modeltests/` suite inside `onnx-gomlx` (using the same `-modeltests`, `-backends`, `spec.json`, and `.f32` conventions), starting with `KnightsAnalytics/all-MiniLM-L6-v2` and other ONNX models.
20 changes: 13 additions & 7 deletions examples/dolly/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,27 @@ For more information see:
* https://pkg.go.dev/github.com/gomlx/go-huggingface/datasets : The `datasets` package documentation.
* https://huggingface.co/datasets/databricks/databricks-dolly-15k : The dataset page on HuggingFace Hub.

## `browse`
## `benchmark_generate`

A small CLI in [`browse/`](./browse) that downloads (and caches) the dataset, prints sample records, and optionally
generates responses with a HuggingFace model using GoMLX's `ml/zoo/transformer/generate`:
A CLI in [`benchmark_generate/`](./benchmark_generate) that downloads (and caches) the dataset, prints sample records, and optionally
generates and benchmarks responses with a HuggingFace model using GoMLX's `ml/zoo/transformer/generate` and/or a local Ollama server:

```bash
# Browse example #3 (default -n=1):
go run ./examples/dolly/browse -ex=3
go run ./examples/dolly/benchmark_generate -ex=3

# Generate responses for 3 examples using a GoMLX model:
go run ./examples/dolly/browse -n=3 -model=google/gemma-4-E2B-it -prompt_tokens=1024 -gen_tokens=128
go run ./examples/dolly/benchmark_generate -n=3 -model=google/gemma-4-E2B-it -prompt_tokens=1024 -gen_tokens=128

# Generate responses using a local Ollama server:
go run ./examples/dolly/browse -n=3 -ollama=gemma4:e2b-it-bf16
go run ./examples/dolly/benchmark_generate -n=3 -ollama=gemma4:e2b-it-bf16

# Run both and compare generated outputs side-by-side:
go run ./examples/dolly/browse -n=3 -model=google/gemma-4-E2B-it -ollama=gemma4:e2b-it-bf16
go run ./examples/dolly/benchmark_generate -n=3 -model=google/gemma-4-E2B-it -ollama=gemma4:e2b-it-bf16

# Run Ollama once and save outputs, timings, speeds, and flags to a JSON file:
go run ./examples/dolly/benchmark_generate -n=50 -prompt_tokens=1024 -gen_tokens=512 -ollama=qwen3.5:4b --quiet -save=qwen3.5-4b-Q4_K_M

# Benchmark a GoMLX backend with teacher forcing against the saved reference (exact same sequence length, tracking exact matches):
GOMLX_BACKEND=cuda go run ./examples/dolly/benchmark_generate -n=50 -prompt_tokens=1024 -gen_tokens=512 -model=Qwen/Qwen3.5-4B -teacher_forced=qwen3.5-4b-Q4_K_M --quiet
```
Loading
Loading
0