From 292505e39636dcdeb2a25f140a9a24569efc3f13 Mon Sep 17 00:00:00 2001 From: Yudhanjaya Wijeratne Date: Sat, 21 Nov 2026 16:46:41 +0530 Subject: [PATCH] poly: Ling 3.0 Flash and Tiny (bailingmoe3) A new strata-poly engine, src/poly/ling3.cpp, from llama.cpp's bailingmoe3 graph. Some layers' attention is MLA over cached latents (512 latent + 64 rotary values a row, a sigmoid gate on each head's output; Tiny's query is low rank) on the existing attend()/attend_batch() kernels; the others are KDA with full-rank gates, on GLM 5.3 Flash's kernels. Dense first layers, then routed experts picked from the best 4 of 8 groups (sigmoid gates + bias, normalised, x2.5) and one shared expert. Flash's draft block (blk.42.nextn) runs as the engine's MTP block. - setup: family "ling3", Ling 3.0 Flash from bloomer010's GGUFs (Q4_K_M, Q3_K_M, UD-Q2_K_XL), pinned and checksummed; its configs pass --no-draft (no faster here, slower deep in a long context). Tiny runs on the engine but is not offered: its experts fit in most cards' VRAM. - tools/strata_tokenizer.py: llama.cpp's bailingmoe pre-tokenizer pattern; serve/models.py and tools/strata_inspect.py know the architecture; metal/CMakeLists.txt builds the engine (not compiled on a Mac). - docs/models/ling3.md, docs/BACKENDS.md (what runs, the parity table and how it was checked), README. - tools/test_setup_ling3.py; tools/test_setup_menu.py's family order. Checked against llama.cpp on one Linux PC (RTX 4080 SUPER + RTX 3080), five chat prompts of 35 to 8,036 tokens, 64 tokens each: Flash Q4_K_M within 0.28 (8 of its 12 departures at a near tie, the other four explained in BACKENDS.md), Tiny Q4_K_M within 0.19 (all six at a near tie). A prompt read in one call and in two gives the same tokens with every expert on the CPU. CUDA only; HIP and Metal not built. --- CMakeLists.txt | 6 +- README.md | 5 +- docs/BACKENDS.md | 21 ++- docs/models/ling3.md | 76 ++++++++ metal/CMakeLists.txt | 2 +- serve/models.py | 1 + setup.py | 35 +++- src/poly/engine.cpp | 2 + src/poly/ling3.cpp | 388 ++++++++++++++++++++++++++++++++++++++ src/poly/ling3.hpp | 80 ++++++++ tools/strata_inspect.py | 3 +- tools/strata_tokenizer.py | 15 +- tools/test_setup_ling3.py | 84 +++++++++ tools/test_setup_menu.py | 5 +- 14 files changed, 711 insertions(+), 12 deletions(-) create mode 100644 docs/models/ling3.md create mode 100644 src/poly/ling3.cpp create mode 100644 src/poly/ling3.hpp create mode 100644 tools/test_setup_ling3.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 763e1d70cf..a62976f66a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2140,7 +2140,7 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S add_test(NAME poly_gdn_mma_test COMMAND poly_gdn_mma_test) set_tests_properties(poly_gdn_mma_test PROPERTIES SKIP_RETURN_CODE 77) # Optional model/state check; run by hand with an MTP GGUF and frozen prompt IDs. - add_executable(poly_gdn_mma_state_test src/poly/gdn_mma_state_test.cpp src/poly/engine.cpp src/poly/glm5next.cpp + add_executable(poly_gdn_mma_state_test src/poly/gdn_mma_state_test.cpp src/poly/engine.cpp src/poly/glm5next.cpp src/poly/ling3.cpp src/poly/qwen35.cpp src/poly/gemma4.cpp src/poly/deepseek4.cpp src/poly/lfm2moe.cpp src/poly/flint.cpp src/poly/kolibri1.cpp src/poly/cpu_experts.cpp src/poly/kernels.cu src/poly/kernels_dsv4.cu src/core/conversation_memory.cpp) @@ -2149,7 +2149,7 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target} CUDA::cuda_driver Threads::Threads) endif() - add_executable(strata-poly src/poly/main.cpp src/poly/engine.cpp src/poly/glm5next.cpp src/poly/qwen35.cpp + add_executable(strata-poly src/poly/main.cpp src/poly/engine.cpp src/poly/glm5next.cpp src/poly/ling3.cpp src/poly/qwen35.cpp src/poly/gemma4.cpp src/poly/deepseek4.cpp src/poly/lfm2moe.cpp src/poly/flint.cpp src/poly/kolibri1.cpp src/poly/cpu_experts.cpp src/poly/kernels.cu src/poly/kernels_dsv4.cu src/poly/spill.cpp src/core/conversation_memory.cpp src/core/conversation_file.cpp) @@ -2174,7 +2174,7 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S Threads::Threads) # a read with the draft block repeats bit for bit; needs the model file, so it is run by hand: # poly_draft_race_test MODEL.gguf [RUNS] [LAYER_SPLIT] - add_executable(poly_draft_race_test src/poly/draft_race_test.cpp src/poly/engine.cpp src/poly/glm5next.cpp + add_executable(poly_draft_race_test src/poly/draft_race_test.cpp src/poly/engine.cpp src/poly/glm5next.cpp src/poly/ling3.cpp src/poly/qwen35.cpp src/poly/gemma4.cpp src/poly/deepseek4.cpp src/poly/lfm2moe.cpp src/poly/flint.cpp src/poly/kolibri1.cpp src/poly/cpu_experts.cpp src/poly/kernels.cu src/poly/kernels_dsv4.cu diff --git a/README.md b/README.md index 6bca7f6b5e..cd0aa2d050 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ **English** · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · [Português](README.pt-BR.md) · [Türkçe](README.tr.md)

Run large AI models on your own PC
-Qwen3.8-Flash-Next, GLM 5.3 Flash, DeepSeek V4 Flash, LFM2.5, Flint, Qwen3.6, Clover, Ornith 1.5, Gemma 4, Tiel Coder, MiniCPM-V and Kolibri 1 · free and open source

+Qwen3.8-Flash-Next, GLM 5.3 Flash, DeepSeek V4 Flash, LFM2.5, Flint, Qwen3.6, Clover, Ornith 1.5, Gemma 4, Tiel Coder, MiniCPM-V, Kolibri 1 and Ling 3.0 Flash · free and open source

Used by Linger

@@ -48,6 +48,8 @@ with an 8 GB card as well. own, made to read pictures: a file of 16 to 29 GB. - **[Kolibri 1](docs/models/kolibri.md)** by Aleph Alpha, which writes German as well as English: a file of 29 to 48 GB, most of which stays in RAM beside a small card. +- **[Ling 3.0 Flash](docs/models/ling3.md)** by inclusionAI (124B, 5.1B active): a file of 43 to 78 GB, most of which + stays in RAM. Every sixth layer keeps a compressed attention cache, so a 128K context takes 0.9 GB more VRAM than 32K. The server can change between installed models while it runs ([how](docs/BACKENDS.md#changing-the-model)). @@ -158,6 +160,7 @@ How it works and how it was measured: [docs/BACKENDS.md](docs/BACKENDS.md#less-o | [Tiel Coder 35B-A3B](docs/models/tiel.md) | same as above; AMD as a beta | about 21 GB beside an 8 GB card | 14 to 23 GB | Windows, Linux | | [MiniCPM-V 4.7 35B-A3B](docs/models/minicpmv.md) | same as above; AMD as a beta | about 25 GB beside an 8 GB card | 16 to 29 GB | Windows, Linux | | [Kolibri 1](docs/models/kolibri.md) | NVIDIA RTX 20 series or newer, 8 GB or more | about 33 GB beside an 8 GB card | 29 to 48 GB | Windows, Linux | +| [Ling 3.0 Flash](docs/models/ling3.md) | NVIDIA RTX 20 series or newer; run on a 16 GB card | about 72 GB beside a 16 GB card | 43 to 78 GB, on an SSD | Linux | RAM is the installer's estimate; a larger card needs less. The installer sets up everything else: on Windows it downloads the engine ready-made, and compiles it on your PC only on a processor without AVX2 or when your copy's engine is newer than the latest release, offering to install the tools. Two or three cards can share a model ([multi-GPU](docs/MULTI_GPU.md)). Older graphics cards, Intel Arc, Apple Silicon Macs (Qwen3.8-Flash-Next, and Qwen3.6 and LFM2.5 as a beta), Strix Halo and older processors without AVX2: [the full list](docs/INSTALL.md#what-you-need). Each model's card, RAM and sizes in detail are on its page. diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index 08ac8436c5..9c07eaf1df 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -25,9 +25,10 @@ a second machine, a Windows laptop whose card has 8 GB. | Flint 40B-A2.5B | `flint` | `strata-poly` | Unsloth UD-Q4_K_XL, UD-Q3_K_XL, UD-Q6_K_XL and Q8_0, 18.5 to 42.3 GB | repeats only: there is no draft model | | Kolibri 1 | `kolibri1` | `strata-poly` | Hob-forge Q4_K_M, Q2_K and Q3_K_M, 28.6 to 47.5 GB | repeats only: there is no draft model | | Clover-35B-A3B-Preview | `clover_moe` | `strata-poly` | maternion Q3_K_M and Q4_K_M, IsValorum APEX-I-NanoPlus, 12.6 to 21.2 GB | repeats only: its own block guesses are off ([below](#clover-35b-a3b-preview)) | +| Ling 3.0 Flash and Tiny | `bailingmoe3` | `strata-poly` | bloomer010 Q4_K_M (Flash, 78.3 GB), inclusionAI Q4_K_M (Tiny, 4.8 GB) | Flash: draft block in the file, off in setup's configs ([models/ling3.md](models/ling3.md)); Tiny: repeats only | `strata` is the first engine and runs Qwen3.8 only; nothing in it changed. `strata-poly` is the engine that reads a -GGUF in place, and it now has eight architectures. It was called `strata-glm`, after its first model; an install +GGUF in place, and it now has nine architectures. It was called `strata-glm`, after its first model; an install from then keeps its engine and moves to the new name the next time setup updates it. The optional CUDA [GDN prefill adapter](DETAILS.md#strata-poly-chunked-gdn-prefill) uses @@ -1080,6 +1081,11 @@ token ids compared and the probabilities of the reference's five likeliest token | Ornith 1.5 APEX-I-Quality | 61 of 61, 7, 21, 22, 34 | 0.16 | | Gemma 4 26B-A4B UD-Q2_K_XL | 64, 53, 22, 50, 33 | 0.09 | | Gemma 4 26B-A4B UD-Q4_K_M | 64, 26, 52, 25, 64 | 0.15 | +| Ling 3.0 Flash Q4_K_M | 9, 18, 0, 33, 3 | 0.28 | +| Ling 3.0 Flash Q4_K_M, draft block on | 17, 51, 0, 33, 64 | 0.26 | +| Ling 3.0 Flash Q4_K_M, every expert on the CPU | 17, 64, 14, 33, 64 | 0.21 | +| Ling 3.0 Tiny Q4_K_M | 14, 64, 64, 55, 14 | 0.19 | +| Ling 3.0 Tiny Q4_K_M, every expert on the CPU | 14, 10, 64, 10, 64 | 0.11 | The first three rows are the sizes setup takes first, UD-Q3_K_M and APEX-I-Compact. With the build of 2026-10-10 they were 64, 64, 40, 29 and 64 within 0.12, 60 of 60, 7, 56, 2 and 64 within 0.29, and five times @@ -1090,6 +1096,19 @@ states after a read and after the same calls one by one are equal byte for byte, tokens and with the whole model on the card after 30,000. Their answers to pictures are in the table further down. +The five Ling rows were compared on one Linux PC (RTX 4080 SUPER and RTX 3080, Flash on a layer split, Tiny on the +4080 SUPER alone), against llama.cpp built from PR #32517 at 0a054d0, with five chat prompts of 35 to 8,036 +tokens. llama.cpp gives a token that ends inside a character no probabilities of its own: they come with the next +token's, so the comparison matches its steps to the tokens by id. Eight of Flash's 12 departures and all six of +Tiny's are at a near tie as above. The other four are Flash's: its fourth prompt (4,034 tokens) at the 34th token in +all three rows (llama.cpp 0.57 and 0.43 for its two likeliest, this engine 0.60 to 0.69 for the second), and its +fifth (8,036 tokens) at the 4th without the draft block (llama.cpp 0.42 and 0.27, this engine 0.54 for a third +token). As a control, llama.cpp against itself with 512-token batches instead of 4,096 left its own tokens at the 3rd +to 18th token of four prompts, the fifth at that same 4th token, by up to 0.09, and wrote the fourth prompt's 64 the +same. A prompt read in one call and in two (4,096 tokens reused from the conversation cache, then 10,563 read) gave +the same 64 tokens with every expert on the CPU; with experts in VRAM the two runs held different experts there, and +their answers parted after a dozen words. + Two correct implementations do not write the same tokens for long. Activations are quantized to 8 bits at every quantized matrix, in a layout that depends on the kernel, so the two differ in the last bits and a near tie between two tokens goes either way. Ornith's file has 3-bit experts and 4-bit attention and is the most sensitive: diff --git a/docs/models/ling3.md b/docs/models/ling3.md new file mode 100644 index 0000000000..1fb9bfcfe9 --- /dev/null +++ b/docs/models/ling3.md @@ -0,0 +1,76 @@ +# Ling 3.0 Flash + +Back to [README.md](../../README.md) + +**Ling 3.0 Flash** by inclusionAI: 124B parameters, 5.1B of them active a token, llama.cpp's architecture +`bailingmoe3`, read from bloomer010's GGUF files. A file of 43 to 78 GB, most of which stays in RAM. Seven of its 42 +layers keep an attention cache, and that cache is compressed (a 512-value latent and 64 rotary values a token), so +a 128K context takes 0.9 GB more VRAM than 32K. The others are KDA layers, GLM 5.3 Flash's gated delta rule, with a +state of fixed size. Its license is MIT. + +It is new here and experimental. It has run on one Linux PC only: an RTX 4080 SUPER (16 GB) and an RTX 3080 (10 GB), +a Ryzen 7 5800X3D and 62 GB of DDR4. Not on Windows, AMD or a Mac. + +## The sizes + +| Size | From | Download | Experts | RAM beside a 16 GB card (setup's estimate) | +| --- | --- | ---: | ---: | ---: | +| **Q4_K_M** | [bloomer010](https://huggingface.co/bloomer010/Ling-3.0-flash-GGUF): 4-bit experts, 6- and 8-bit where they write | 78.3 GB | 75.8 GB | about 72 GB | +| **Q3_K_M** | bloomer010: 3- and 4-bit experts | 62.6 GB | 60.5 GB | about 57 GB | +| **UD-Q2_K_XL** | bloomer010: 2- and 3-bit i-quant experts | 43.4 GB | 40.5 GB | about 37 GB | + +Only Q4_K_M has been run; the other two are the same model at less RAM. UD-Q2_K_XL's experts are i-quants, whose +CPU kernels are slower per weight than the K-quants' (a token's experts the card does not hold are computed on the +CPU). Setup takes the first size whose estimate the PC meets: on the PC above (62 GB) that is Q3_K_M, and Q4_K_M, +named with `--model Q4_K_M`, ran there with part of its file read from the SSD. Every file is pinned to the +repository's commit of 2026-11-17 and checked against its SHA-256. + +The file carries a draft block (`blk.42.nextn`). Setup's configs leave it out (`--no-draft`): on this PC it made +answers no faster and writing deep in a long context slower, 14.9 against 20.0 tokens/s after an 88K prompt. + +## How fast is it? + +### One card: the RTX 4080 SUPER (16 GB) + +PolyStrata's own benchmark, `polystrata.py benchmark --prompt-tokens 24000` (a short chat, then a prompt built from +this repository's documents, 256 tokens written after each), Q4_K_M, a 32K context, `--no-draft`, three runs; each +starts the server, so the short chat is the first answer it writes. + +| Run | Writes a short chat | Reads the prompt (32,318 to 32,368 tokens) | Writes after it | Experts in VRAM | +| --- | ---: | ---: | ---: | ---: | +| 1 (`--vram-reserve-mib 1100`) | 11.9 tokens/s | 948 tokens/s | 6.6 tokens/s | 2,691 of 20,480 | +| 2 (`--vram-reserve-mib 1900`) | 11.6 tokens/s | 835 tokens/s | 11.8 tokens/s | 2,517 | +| 3 (`--vram-reserve-mib 1900`) | 8.6 tokens/s | 1,048 tokens/s | 13.0 tokens/s | 2,517 | + +The card drives the display. During the long prompt the staging buffer took VRAM past `--vram-reserve-mib`: the card +had 0.2 GB free with a reserve of 1,100 MiB and 0.8 GB with 1,900. + +### Two cards: RTX 4080 SUPER + RTX 3080, a layer split + +A 128K context, `--prompt-batch 512 --no-draft`, every other setting the engine's default; 4,030 of 20,480 experts in +VRAM. Each answer is 500 tokens with thinking off; "new prompts" are two the server had not seen, asked after it had +answered two others twice (a prompt asked again is written faster, from experts the cache has just taken for it). +The long prompt is 88,621 tokens of this repository's documents with one planted sentence, 200 tokens written after +it. llama.cpp (PR #32517 at 0a054d0, `--fit`, 4,096-token batches) on the same PC and file for comparison: + +| | Writes new prompts | Reads the long prompt | Writes after it | Found the sentence | +| --- | ---: | ---: | ---: | --- | +| PolyStrata | 30.9 (code), 35.5 (prose) tokens/s | 733 tokens/s | 20.0 tokens/s | yes | +| llama.cpp, no draft | 22.7 tokens/s (three prompts) | 463 tokens/s | 22.4 tokens/s | yes | +| llama.cpp, its draft block 2 ahead | 24.8 tokens/s | | | | + +`--prompt-batch 512` leaves room for experts on a layer split; with `--prompt-batch 2048` (and the draft block on) +the long prompt was read at 812 tokens/s, but 3,134 experts were in VRAM and writing after it fell to 11.0. Changing `--stage-mib` from its +default turns off the staging buffer's growth for a long read (`--stage-read-mib`), and the long prompt was then read +at 110 tokens/s. + +## Ling 3.0 Tiny + +The same engine runs Ling 3.0 Tiny (24 layers, 128 experts, a low-rank query; [inclusionAI's Q4_K_M](https://huggingface.co/inclusionAI/Ling-3.0-tiny-GGUF), +4.8 GB), with `strata-poly --model Ling-3.0-tiny-Q4_K_M.gguf` or a run config written by hand. Setup does not offer it: its +experts (3.9 GiB) fit in most cards' VRAM, where llama.cpp does as well. On the 4080 SUPER it wrote 246 tokens/s. + +## How it was checked + +Against llama.cpp on the same files, five chat prompts of 35 to 8,036 tokens, 64 tokens each: see +[BACKENDS.md](../BACKENDS.md#how-each-backend-was-checked). diff --git a/metal/CMakeLists.txt b/metal/CMakeLists.txt index 915d4bd024..fd4dd1fa6a 100644 --- a/metal/CMakeLists.txt +++ b/metal/CMakeLists.txt @@ -206,7 +206,7 @@ if(STRATA_METAL_POLY) STRATA_POLY_MM_SOURCE="${CMAKE_CURRENT_SOURCE_DIR}/src/poly/mm.metal") target_link_libraries(strata_poly_metal_kernels PUBLIC ggml-base) add_executable(strata-poly ${S}/poly/main.cpp ${S}/poly/engine.cpp ${S}/poly/qwen35.cpp - ${S}/poly/gemma4.cpp ${S}/poly/lfm2moe.cpp ${S}/poly/glm5next.cpp ${S}/poly/deepseek4.cpp ${S}/poly/flint.cpp + ${S}/poly/gemma4.cpp ${S}/poly/lfm2moe.cpp ${S}/poly/glm5next.cpp ${S}/poly/ling3.cpp ${S}/poly/deepseek4.cpp ${S}/poly/flint.cpp ${S}/poly/kolibri1.cpp ${S}/poly/cpu_experts.cpp ${S}/poly/spill.cpp ${S}/platform/memory.cpp ${S}/core/conversation_memory.cpp ${S}/core/conversation_file.cpp ${S}/spec/draft_policy.cpp ${S}/spec/suffix_drafter.cpp) diff --git a/serve/models.py b/serve/models.py index a8421234d0..3629035daa 100644 --- a/serve/models.py +++ b/serve/models.py @@ -29,6 +29,7 @@ "lfm2moe": "lfm2moe", "flint": "flint", "kolibri1": "kolibri1", + "bailingmoe3": "bailingmoe3", } # a routed expert's tensors: they stay in the file and are held in VRAM as far as it has room EXPERT = re.compile(r"\.ffn_(gate|up|down|gate_up)_exps\.weight$") diff --git a/setup.py b/setup.py index 76979e07a0..c545b60ec5 100644 --- a/setup.py +++ b/setup.py @@ -95,6 +95,7 @@ "Diffuspace/Clover-35B-A3B-Preview": "4b0402b65e523d0183a14c431955438714cb16ff", # 2026-10-28 "unsloth/Ornith-1.5-122B-GGUF": "3842d003341507c216295c6f28dfcd30349925c6", # 2026-10-20 "ornith-ai/Ornith-1.5-122B": "dfa07bab90e90746ffbfc0b0cba3126eb9265de2", # 2026-10-20 + "bloomer010/Ling-3.0-flash-GGUF": "3797301def2eb8e6b91bccb0ee59c377bc7e4416", # 2026-11-17 } @@ -863,6 +864,32 @@ def ms_meta(repo: str, path: str): (32785752352, "43bdc1b0cb764b5531d320816fb6004245256a414bfd55f1fdb69e3db42eaa57"), "mmproj-F16.gguf": (908724544, "39db176176a904b101f5173a4f03e785990f9279f94ab373c4fd629ae7011817")}}, + # Ling 3.0 Flash (llama.cpp's bailingmoe3, docs/LING.md): 124B, 5.1B active, 512 experts in 41 layers, from + # bloomer010's single-file GGUFs. Measured on one Linux PC only (RTX 4080 SUPER 16 GB + RTX 3080 10 GB, 62 GB of + # RAM): "vram_beside_gb" on the 4080 SUPER alone at 32K, every expert on the CPU (Q4_K_M; the other two sizes' + # attention and dense weights are within 0.5 GB of it); "arena_gb" from each file's header. "no_draft": the file's + # draft block made answers no faster there and writing deep in a long context slower (20.0 against 14.9 tokens/s + # at 88K), so setup's configs start without it. Ling 3.0 Tiny runs on the same engine but is not offered here: + # its 3.9 GiB of experts fit beside most cards' VRAM, where llama.cpp does as well. + "ling3": {"title": "Ling 3.0 Flash", "by": "inclusionAI; quantized by bloomer010", + "about": "on the strata-poly engine: NVIDIA, Linux; a 78 GB file, ~72 GB of RAM beside a 16 GB card; two " + "smaller sizes too, no images", + "hf": hf("bloomer010/Ling-3.0-flash-GGUF"), "file": "Ling-3.0-flash-{q}.gguf", "shards": 1, + "tag": "ling3-", "name": "ling-3.0-flash", "engine": "poly", "vision": False, "experimental": True, + "ran_on_gb": 16, "row_bytes": 9216, "no_draft": True, + "models": {"Q4_K_M": {"about": "4-bit experts, 6- and 8-bit where they write", + "download_gb": 78.3, "ram_gb": 81, "arena_gb": 75.8, "vram_beside_gb": 3.6}, + "Q3_K_M": {"about": "3- and 4-bit experts: less RAM (not measured here)", + "download_gb": 62.6, "ram_gb": 66, "arena_gb": 60.5, "vram_beside_gb": 3.6}, + "UD-Q2_K_XL": {"about": "2- and 3-bit i-quant experts: the least RAM, slow on the CPU " + "(not measured here)", + "download_gb": 43.4, "ram_gb": 46, "arena_gb": 40.5, "vram_beside_gb": 3.6}}, + "sha256": {"Ling-3.0-flash-Q4_K_M.gguf": + (78285288128, "1454b08b0490ecdfa8109379962fdf421eedaa89a7f26fb37ee5adabd9f66e65"), + "Ling-3.0-flash-Q3_K_M.gguf": + (62563876544, "87c3cb923db78e54bfafb1ed5b91ac6c8029497ffef3a2eb211f089bd687b28a"), + "Ling-3.0-flash-UD-Q2_K_XL.gguf": + (43444807104, "a0de4c344781e841f5ec7926c8a50ca720375c15cd6e5b2f83cd07ed6480f06b")}}, } MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" # Qwen3.6-35B-A3B (GGUF architecture qwen35moe), Unsloth's GGUFs with the MTP block: a family with an engine path of its @@ -2390,7 +2417,8 @@ def verify_sha256(s: Path, size: int, sha: str, own: bool = False) -> None: # general.architecture of each strata-poly family's GGUFs, the name Engine::open() (src/poly/engine.cpp) picks its # code by; the families not listed are qwen35moe POLY_GGUF_ARCHS = {"glm": ("glm5-next", "glm5next"), "deepseek": ("deepseek4",), "lfm25": ("lfm2moe",), - "gemma4": ("gemma4",), "flint": ("flint",), "kolibri": ("kolibri1",), "clover": ("clover_moe",)} + "gemma4": ("gemma4",), "flint": ("flint",), "kolibri": ("kolibri1",), "clover": ("clover_moe",), + "ling3": ("bailingmoe3",)} def gguf_arch(s: Path) -> str: @@ -7197,6 +7225,9 @@ def _skip_or_verify(path, sha_key): args = ["--model", str(gguf), "--max-context", str(ctx), "--expert-profile", str(profile)] if draft: args += ["--draft-model", str(draft)] + elif fam.get("no_draft"): + args += ["--no-draft"] + ok("the file's draft block is left out (--no-draft in the config): on this family it made answers no faster") if conv: args += ["--conversation-cache-mib", str(conv)] if a.vram_reserve_mib is not None: @@ -7850,7 +7881,7 @@ def main() -> int: "DeepSeek V4 Flash, lfm25 = LFM2.5-24B-A2B, flint = Flint 40B-A2.5B, qwen36 = " "Qwen3.6-35B-A3B on strata-poly, clover = Clover-35B-A3B-Preview, ornith = " "Ornith 1.5, gemma4 = Gemma 4 26B-A4B, tiel = Tiel Coder 35B-A3B, minicpmv = MiniCPM-V 4.7 " - "35B-A3B, ornith122 = Ornith 1.5 122B (docs/BACKENDS.md), qwen36-strata = Qwen3.6-35B-A3B on the Strata project's " + "35B-A3B, ornith122 = Ornith 1.5 122B (docs/BACKENDS.md), ling3 = Ling 3.0 Flash (docs/LING.md), qwen36-strata = Qwen3.6-35B-A3B on the Strata project's " "own engine (UD-Q4_K_XL and up, 32 GB of RAM or more; pictures with --vision, several " "requests at once with --parallel; docs/QWEN36.md)") ap.add_argument("--model", choices=list(dict.fromkeys( diff --git a/src/poly/engine.cpp b/src/poly/engine.cpp index 92da58f019..ca8b146967 100644 --- a/src/poly/engine.cpp +++ b/src/poly/engine.cpp @@ -6,6 +6,7 @@ #include "deepseek4.hpp" #include "gemma4.hpp" #include "glm5next.hpp" +#include "ling3.hpp" #include "kolibri1.hpp" #include "lfm2moe.hpp" #include "flint.hpp" @@ -1662,6 +1663,7 @@ std::unique_ptr Engine::open(const Options& o) { throw std::runtime_error("--cache-bias is supported for qwen35moe models; this is a '" + name + "' model"); const auto make = [&]() -> std::unique_ptr { if (name == "glm5-next" || name == "glm5next") return std::make_unique(); // Unsloth: no hyphen + if (name == "bailingmoe3") return std::make_unique(); if (qwen35) return std::make_unique(); if (name == "gemma4") return std::make_unique(); if (name == "deepseek4") return std::make_unique(); diff --git a/src/poly/ling3.cpp b/src/poly/ling3.cpp new file mode 100644 index 0000000000..6be74fe2d4 --- /dev/null +++ b/src/poly/ling3.cpp @@ -0,0 +1,388 @@ +// src/poly/ling3.cpp - Ling 3.0 Flash's layers. The reference for the math is llama.cpp's bailingmoe3 graph +// (src/models/bailingmoe3.cpp); the KDA layers are GLM 5.3 Flash's (glm5next.cpp) with full-rank gates. +// +// MLA, as llama.cpp runs it: a row of the cache is the latent, RMS-normed (kv_rank values), then the key's rotary +// part turned by the position (n_rot values), and it is the key and the value both. A head's query is its +// non-rotary part through attn_k_b (to kv_rank values) then its rotary part turned; the attention's output for a +// head is a latent, whose first kv_rank values go through attn_v_b. One key head, so attend() reads a row once +// for the 32 heads. +#include "ling3.hpp" + +#include "runtime.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include +#include +#include +#include +#include + +namespace strata::poly { +namespace { + +constexpr int kConv = 4; +constexpr size_t kScoreFloats = size_t(16) << 20; // the attention's scores of the tokens it takes at a time +constexpr float kMinWeightSum = 6.103515625e-5f; // the floor ggml's MoE graph puts under the gate sum + +constexpr Names kTensorNames[] = { + {"nextn.shared_head_norm.weight", {"layer_output_norm.weight"}}, +}; + +// rows x width floats from src (src_stride apart) to dst (dst_stride apart), on the stream +void copy_rows(float* dst, size_t dst_stride, const float* src, size_t src_stride, size_t width, size_t rows, + void* stream) { + ck(cudaMemcpy2DAsync(dst, dst_stride * sizeof(float), src, src_stride * sizeof(float), width * sizeof(float), rows, + cudaMemcpyDeviceToDevice, cs(stream)), + "ling3 copy"); +} + +} // namespace + +const Names* Ling3::tensor_alias(const char* name) const { return names_of(kTensorNames, name); } + +void Ling3::begin_pass() { + blocks_.assign(layers_.size(), Block{}); + n_mla_ = n_kda_ = 0; +} + +void Ling3::check_draft_block() { + if (!blocks_[(size_t) n_layer_].mla || !layers_[(size_t) n_layer_].moe) + throw std::runtime_error("the block that guesses ahead is not one this engine runs; --no-draft loads " + "the model without it"); +} + +void Ling3::load_geometry() { + load_shape(); + auto find = [&](const char* key) { return meta_in(*gg_, key); }; + n_ff_ = shape_i("feed_forward_length"); + n_head_ = shape_i("attention.head_count"); + w_scale_ = shape_f("expert_weights_scale"); + w_norm_ = shape_i("expert_weights_norm") != 0; + kda_dim_ = shape_i("kda.head_dim"); + kda_lb_ = shape_f("kda.gate_lower_bound"); + kv_rank_ = shape_i("attention.kv_lora_rank"); + mla_k_ = shape_i("attention.key_length_mla"); + mla_v_ = shape_i("attention.value_length_mla"); + n_rot_ = shape_i("rope.dimension_count"); + nope_ = mla_k_ - n_rot_; + row_ = kv_rank_ + n_rot_; + d_inner_ = n_head_ * kda_dim_; + if (const MetaValue* g = find("expert_group_count")) n_group_ = (int) g->u; + if (const MetaValue* g = find("expert_group_used_count")) group_used_ = (int) g->u; + rope_.theta_scale = std::pow(shape_f("rope.freq_base"), -2.0f / (float) n_rot_); + + auto need = [](bool ok, const char* what) { + if (!ok) throw std::runtime_error(std::string("unsupported model: ") + what); + }; + need(shape_i("ssm.conv_kernel") == kConv, "ssm.conv_kernel is not 4"); + if (const MetaValue* q = find("attention.q_lora_rank")) q_lora_ = (int) q->u; + need(!find("rope.dimension_sections"), "rope sections (a vision file)"); + const MetaValue* gating = find("expert_gating_func"); + need(!gating || gating->u == 2, "the expert gate is not a sigmoid"); + need(shape_i("expert_shared_count") == 1, "expert_shared_count is not 1"); + need(kda_dim_ > 0 && kda_dim_ % 32 == 0 && kda_dim_ <= 256, "kda.head_dim is not a multiple of 32 up to 256"); + need(nope_ > 0 && n_rot_ % 2 == 0 && row_ % 4 == 0, "bad key_length_mla or rope.dimension_count"); + need(n_group_ >= 1 && n_expert_ % n_group_ == 0 && group_used_ >= 1 && group_used_ <= n_group_ && + n_expert_ / n_group_ >= 2, + "bad expert_group_count"); + need(opt_.kv_format != KvFmt::kQ8_0, "--kv q8_0 (this engine keeps its MLA cache in fp16)"); + clamp_exp_ = clamp_limits(find("swiglu_clamp_exp"), n_layer_ + 1); + clamp_shexp_ = clamp_limits(find("swiglu_clamp_shexp"), n_layer_ + 1); +} + +void Ling3::load_layer(int il) { + Layer& L = layers_[(size_t) il]; + Block& B = blocks_[(size_t) il]; + auto f32 = [&](const char* n, int64_t a, int64_t b = 1) { return upload(tensor(il, n), blk(il, n), a, b, kF32); }; + auto mat = [&](const char* n, int64_t a, int64_t b, Want w = kAnyMat) { + return upload(tensor(il, n), blk(il, n), a, b, w); + }; + auto has = [&](const char* n) { return tensor(il, n) != nullptr; }; + + L.attn_norm = f32("attn_norm.weight", n_embd_); + L.ffn_norm = f32("ffn_norm.weight", n_embd_); + B.mla = has("attn_kv_a_mqa.weight"); + L.fixed = !B.mla; // the attention's launches take the position + if (B.mla) { + if (q_lora_ > 0) { + B.q_a = mat("attn_q_a.weight", n_embd_, q_lora_); + B.q_a_norm = f32("attn_q_a_norm.weight", q_lora_); + B.q_b = mat("attn_q_b.weight", q_lora_, (int64_t) n_head_ * mla_k_); + } else { + B.q = mat("attn_q.weight", n_embd_, (int64_t) n_head_ * mla_k_); + } + B.kv_a = mat("attn_kv_a_mqa.weight", n_embd_, row_); + B.kv_a_norm = f32("attn_kv_a_norm.weight", kv_rank_); + B.k_b = mat("attn_k_b.weight", nope_, (int64_t) kv_rank_ * n_head_, kFloatMat); + B.v_b = mat("attn_v_b.weight", kv_rank_, (int64_t) mla_v_ * n_head_, kFloatMat); + B.gate = mat("attn_gate.weight", n_embd_, n_head_); + B.wo = mat("attn_output.weight", (int64_t) n_head_ * mla_v_, n_embd_); + ++n_mla_; + } else { + B.wq = mat("attn_q.weight", n_embd_, d_inner_); + B.wk = mat("attn_k.weight", n_embd_, d_inner_); + B.wv = mat("attn_v.weight", n_embd_, d_inner_); + B.wo = mat("attn_output.weight", d_inner_, n_embd_); + B.conv_q = f32("ssm_conv1d_q.weight", kConv, d_inner_); + B.conv_k = f32("ssm_conv1d_k.weight", kConv, d_inner_); + B.conv_v = f32("ssm_conv1d_v.weight", kConv, d_inner_); + B.f_a = mat("ssm_f_a.weight", n_embd_, d_inner_); + B.dt_b = f32("ssm_dt.bias", d_inner_); + B.beta = mat("ssm_beta.weight", n_embd_, n_head_); + // llama.cpp: decay = lower_bound * sigmoid((f_a x + dt_b) * ssm_a); kda_step() makes it of + // sigmoid(-(g1 * a)), so a goes up negated + B.a = upload(tensor(il, "ssm_a"), blk(il, "ssm_a"), 1, n_head_, kF32, [](float v) { return -v; }); + B.g_a = mat("ssm_g_a.weight", n_embd_, d_inner_); + B.o_norm = f32("ssm_norm.weight", kda_dim_); + ++n_kda_; + } + + if (!has("ffn_gate_inp.weight")) { + B.ffn_gate = mat("ffn_gate.weight", n_embd_, n_ff_); + B.ffn_up = mat("ffn_up.weight", n_embd_, n_ff_); + B.ffn_down = mat("ffn_down.weight", n_ff_, n_embd_); + return; + } + load_moe(il); + B.probs_b.assign((size_t) n_expert_, 0.f); + if (const TensorInfo* b = tensor(il, "exp_probs_b.bias")) { + if (b->type != kTypeF32 || (int64_t) b->elements() != n_expert_) + throw std::runtime_error(b->name + " is " + shape_of(*b) + ", expected F32 [" + + std::to_string(n_expert_) + "]"); + home(*b).payload(*b); + std::memcpy(B.probs_b.data(), home(*b).data(*b), (size_t) n_expert_ * sizeof(float)); + } +} + +void Ling3::assign_scratch() { + const size_t n = (size_t) rows_, d = n * d_inner_, h = n * n_head_; + proj_ = fbuf(3 * d); + qkv_ = fbuf(3 * d); + g1_ = fbuf(d); + g2_ = fbuf(d); + beta_ = fbuf(h); + gated_ = fbuf(d); + q_ = fbuf(h * mla_k_); + if (q_lora_ > 0) qa_ = fbuf(n * q_lora_), qan_ = fbuf(n * q_lora_); + qn_ = fbuf(h * nope_); + kva_ = fbuf(n * row_); + lat_ = fbuf(n * kv_rank_); + qabs_ = fbuf(h * kv_rank_); + qf_ = fbuf(h * row_); + att_ = fbuf(h * row_); + kqv_ = fbuf(h * kv_rank_); + vout_ = fbuf(h * mla_v_); + agate_ = fbuf(h); + score_ = fbuf((size_t) chunk_ * n_head_ * opt_.max_context); + if (rows_ >= kStageRows) awork_ = fbuf(h * (row_ + row_ / 2 + 3) + 1); +} + +int Ling3::widest() const { return std::max({d_inner_, n_head_ * mla_v_, n_head_ * mla_k_, row_, kv_rank_, q_lora_}); } + +size_t Ling3::recurrent_floats() const { + return size_t(n_kda_) * (size_t(3) * d_inner_ * (kConv - 1) + size_t(n_head_) * kda_dim_ * kda_dim_); +} + +void Ling3::alloc_caches() { + const size_t conv_n = size_t(3) * d_inner_ * (kConv - 1), s_n = size_t(n_head_) * kda_dim_ * kda_dim_; + float* st = state_; + for (int il = 0; il < (int) blocks_.size(); ++il) { + Block& B = blocks_[(size_t) il]; + if (!runs(il)) continue; + if (B.mla) { + B.kv = (uint16_t*) kv_alloc((size_t) row_ * sizeof(uint16_t), 1); + } else { + B.conv = st; + st += conv_n; + B.s = st; + st += s_n; + } + } + chunk_ = (int) std::clamp(kScoreFloats / ((size_t) n_head_ * opt_.max_context), 1, (size_t) rows_); +} + +void Ling3::save_layer(int il, int64_t, uint8_t* dst) { + const Block& B = blocks_[(size_t) il]; + if (B.mla) return; + const size_t n = size_t(3) * d_inner_ * (kConv - 1) + size_t(n_head_) * kda_dim_ * kda_dim_; + ck(cudaMemcpy(dst + (size_t) (B.conv - state_) * sizeof(float), B.conv, n * sizeof(float), + cudaMemcpyDeviceToHost), + "save state"); +} + +size_t Ling3::card_row_bytes() const { return (size_t) n_mla_ * row_ * sizeof(uint16_t); } + +void Ling3::save_card_rows(int64_t first, int64_t n, uint8_t* dst) { + if (first < 0 || n < 0 || first + n > opt_.max_context) + throw std::logic_error("save_rows: the rows are outside the context"); + ck(cudaStreamSynchronize(cs(st_)), "save rows"); + const size_t row = (size_t) row_ * sizeof(uint16_t); + for (const Block& B : blocks_) { + if (!B.mla || !B.kv || n == 0) continue; + ck(cudaMemcpy(dst, (const uint8_t*) B.kv + (size_t) first * row, (size_t) n * row, cudaMemcpyDeviceToHost), + "save rows"); + dst += (size_t) n * row; + } +} + +void Ling3::load_card_rows(const uint8_t* src, int64_t from, int64_t count, int64_t first, int64_t n) { + if (from < 0 || first < from || n < 0 || first + n > from + count || first + n > opt_.max_context) + throw std::logic_error("load_rows: the rows are outside what was saved"); + cover(first + n); + ck(cudaStreamSynchronize(cs(st_)), "load rows"); + const size_t row = (size_t) row_ * sizeof(uint16_t); + for (const Block& B : blocks_) { + if (!B.mla || !B.kv || n == 0) continue; + ck(cudaMemcpy((uint8_t*) B.kv + (size_t) first * row, src + (size_t) (first - from) * row, (size_t) n * row, + cudaMemcpyHostToDevice), + "load rows"); + src += (size_t) count * row; + } +} + +void Ling3::kda(Block& B, int n) { + const size_t d = (size_t) n * d_inner_; + lin(B.wq, xn_, proj_, n, xq_); + lin(B.wk, xn_, proj_ + d, n, xq_); + lin(B.wv, xn_, proj_ + 2 * d, n, xq_); + kda_conv(proj_, B.conv, fp(B.conv_q), fp(B.conv_k), fp(B.conv_v), qkv_, d_inner_, n, st_, + snap_bits_ ? snap_at_ + (B.conv - state_) : nullptr, rec_n_, std::popcount(snap_bits_)); + lin(B.f_a, xn_, g1_, n, xq_); + add_bias(fp(B.dt_b), g1_, d_inner_, n, st_); + lin(B.beta, xn_, beta_, n, xq_); + lin(B.g_a, xn_, g2_, n, xq_); + kda_step(qkv_, g1_, fp(B.a), beta_, B.s, g2_, fp(B.o_norm), gated_, kda_dim_, n_head_, n, kda_lb_, rms_eps_, + st_, snap_bits_ ? snap_at_ + (B.s - state_) : nullptr, rec_n_, std::popcount(snap_bits_)); + lin(B.wo, gated_, ao_, n); +} + +// The rows n tokens from `pos` leave in an MLA layer's cache. xn_ and xq_ hold the layer's input. +void Ling3::mla_store(Block& B, int64_t pos, int n) { + lin(B.kv_a, xn_, kva_, n, xq_); + copy_rows(lat_, kv_rank_, kva_, row_, kv_rank_, n, st_); + rms_norm(lat_, fp(B.kv_a_norm), kva_, kv_rank_, n, rms_eps_, st_, row_); + dsv4_rope(kva_, kva_, row_, 1, kv_rank_, n_rot_, rope_, pos, 1, n, false, 0.f, false, st_); + store_f16(kva_, B.kv, row_, pos, n, st_); +} + +void Ling3::mla(Block& B, int64_t pos, int n) { + const size_t h = (size_t) n * n_head_; + if (q_lora_ > 0) { // llama.cpp: q_b(rms_norm(q_a x) * q_a_norm) + lin(B.q_a, xn_, qa_, n, xq_); + rms_norm(qa_, fp(B.q_a_norm), qan_, q_lora_, n, rms_eps_, st_); + lin(B.q_b, qan_, q_, n); + } else { + lin(B.q, xn_, q_, n, xq_); + } + dsv4_rope(q_, q_, mla_k_, n_head_, nope_, n_rot_, rope_, pos, 1, n, false, 0.f, false, st_); + copy_rows(qn_, nope_, q_, mla_k_, nope_, h, st_); + lin(B.k_b, qn_, qabs_, n, nullptr, kv_rank_); // the key's projection, absorbed into the query: per head + copy_rows(qf_, row_, qabs_, kv_rank_, kv_rank_, h, st_); + copy_rows(qf_ + kv_rank_, row_, q_ + nope_, mla_k_, n_rot_, h, st_); + mla_store(B, pos, n); + const float scale = 1.f / std::sqrt((float) mla_k_); + if (n >= kStageRows) + attend_batch(blas_, qf_, B.kv, B.kv, pos, n, score_, (size_t) chunk_ * n_head_ * opt_.max_context, awork_, + att_, row_, n_head_, 1, scale, st_); + else + attend(qf_, B.kv, B.kv, pos, n, score_, chunk_, att_, row_, n_head_, 1, scale, st_); + copy_rows(kqv_, kv_rank_, att_, row_, kv_rank_, h, st_); + lin(B.v_b, kqv_, vout_, n, nullptr, mla_v_); + lin(B.gate, xn_, agate_, n, xq_); + mul_sigmoid(vout_, agate_, mla_v_, (int) h, 1, true, st_); + lin(B.wo, vout_, ao_, n); +} + +void Ling3::dense_ffn(Block& B, int il, int n) { + lin(B.ffn_gate, xn_, g_, n, xq_); + lin(B.ffn_up, xn_, u_, n, xq_); + swiglu_clamp(g_, u_, h_, n * n_ff_, clamp_shexp_[(size_t) il], st_); + lin(B.ffn_down, h_, fo_, n); +} + +void Ling3::layer_head(Layer& L, int il, int n) { + Block& B = blocks_[(size_t) il]; + rms_norm(r_, fp(L.attn_norm), xn_, n_embd_, n, rms_eps_, st_); + kernels::native_quantize_q8_1(xn_, xq_, n_embd_ * n, 1, st_); + dbg("attn_in", il, xn_, n_embd_); + if (B.mla) mla(B, pos_, n); + else kda(B, n); + dbg("attn", il, ao_, n_embd_); + axpy(ao_, 1.f, r_, n * n_embd_, true, st_); + rms_norm(r_, fp(L.ffn_norm), xn_, n_embd_, n, rms_eps_, st_); + kernels::native_quantize_q8_1(xn_, xq_, n_embd_ * n, 1, st_); + dbg("ffn_in", il, xn_, n_embd_); + if (!L.moe) { + dense_ffn(B, il, n); + dbg("ffn", il, fo_, n_embd_); + axpy(fo_, 1.f, r_, n * n_embd_, true, st_); + } else if (!batched(L, n)) { + moe_router(L, n); + } +} + +void Ling3::layer_tail(Layer&, int, int n) { axpy(fo_, 1.f, r_, n * n_embd_, true, st_); } + +void Ling3::output_rows(int first, int rows, float* h) { + rms_norm(r_ + (size_t) first * n_embd_, fp(out_norm_), h, n_embd_, rows, rms_eps_, st_); +} + +// What ggml's MoE graph does for this model: sigmoid gates; gate + bias summed over each group's best two picks the +// groups, the best group_used of them; the n_used largest of gate + bias in those; weights from the bare gates, +// made to sum to one, times the scale. +void Ling3::route(int il, const float* logits, int32_t, int* ids, float* w, float* probs) const { + const std::vector& bias = blocks_[(size_t) il].probs_b; + float* pick = probs + n_expert_; + for (int e = 0; e < n_expert_; ++e) { + probs[e] = 1.f / (1.f + std::exp(-logits[e])); + pick[e] = probs[e] + bias[(size_t) e]; + } + if (n_group_ > 1 && group_used_ < n_group_) { + const int per = n_expert_ / n_group_; + float gs[64]; + bool keep[64] = {}; + for (int g = 0; g < n_group_; ++g) { + float a = -INFINITY, b = -INFINITY; + for (int e = g * per; e < (g + 1) * per; ++e) { + if (pick[e] > a) b = a, a = pick[e]; + else if (pick[e] > b) b = pick[e]; + } + gs[g] = a + b; + } + for (int k = 0; k < group_used_; ++k) { + int best = -1; + for (int g = 0; g < n_group_; ++g) + if (!keep[g] && (best < 0 || gs[g] > gs[best])) best = g; + keep[best] = true; + } + for (int g = 0; g < n_group_; ++g) + if (!keep[g]) std::fill(pick + g * per, pick + (g + 1) * per, -INFINITY); + } + float sum = 0.f; + for (int k = 0; k < n_used_; ++k) { + int best = 0; + for (int e = 1; e < n_expert_; ++e) + if (pick[e] > pick[best]) best = e; + pick[best] = -INFINITY; + ids[k] = best; + w[k] = probs[best]; + sum += w[k]; + } + const float denom = w_norm_ ? std::max(sum, kMinWeightSum) : 1.f; + for (int k = 0; k < n_used_; ++k) { + w[k] /= denom; + if (w_scale_ != 0.f) w[k] *= w_scale_; + } +} + +void Ling3::moe_shared(const Layer& L, int il, int n) { + lin(L.sh_gate, xn_, g_, n, xq_); + lin(L.sh_up, xn_, u_, n, xq_); + swiglu_clamp(g_, u_, h_, n * n_ff_shexp_, clamp_shexp_[(size_t) il], st_); + lin(L.sh_down, h_, fo_, n); +} + +void Ling3::block_attend(int64_t pos, int n) { mla(blocks_[(size_t) n_layer_], pos, n); } +void Ling3::block_rows(int64_t pos, int n) { mla_store(blocks_[(size_t) n_layer_], pos, n); } + +} // namespace strata::poly diff --git a/src/poly/ling3.hpp b/src/poly/ling3.hpp new file mode 100644 index 0000000000..0f2fe97e7b --- /dev/null +++ b/src/poly/ling3.hpp @@ -0,0 +1,80 @@ +// src/poly/ling3.hpp - Ling 3.0 Flash and Tiny (llama.cpp architecture "bailingmoe3"). +// +// Flash: 42 layers and one block that guesses a token ahead; Tiny: 24 layers, no such block. Some layers' attention +// is MLA over cached latents (a 512-value latent and 64 rotary values a row, every key attended; Tiny's query is +// low rank); the others are KDA, GLM 5.3 Flash's gated delta rule with its gates full rank. One residual stream. +// The FFN is dense in the first layers (two in Flash, one in Tiny), then routed experts (Flash 512, Tiny 128; 8 used, +// from the best 4 of 8 groups) with a shared one after them. +#pragma once + +#include "engine.hpp" +#include "strata/poly/kernels.hpp" + +namespace strata::poly { + +class Ling3 final : public Engine { +public: + size_t card_row_bytes() const override; + void save_card_rows(int64_t first, int64_t n, uint8_t* dst) override; + void load_card_rows(const uint8_t* src, int64_t from, int64_t count, int64_t first, int64_t n) override; + +protected: + void load_geometry() override; + void load_layer(int il) override; + void begin_pass() override; + void check_draft_block() override; + size_t recurrent_floats() const override; + void save_layer(int il, int64_t pos, uint8_t* dst) override; + void alloc_caches() override; + void assign_scratch() override; + int widest() const override; + int streams() const override { return 1; } + void layer_head(Layer& L, int il, int n) override; + void layer_tail(Layer& L, int il, int n) override; + void output_rows(int first, int rows, float* h) override; + void route(int il, const float* logits, int32_t token, int* ids, float* w, float* tmp) const override; + void moe_shared(const Layer& L, int il, int n) override; + void block_attend(int64_t pos, int n) override; + void block_rows(int64_t pos, int n) override; + const Names* tensor_alias(const char* name) const override; + +private: + struct Block { + bool mla = false; + Dev wo; + // KDA + Dev wq, wk, wv, conv_q, conv_k, conv_v, f_a, dt_b, beta, a, g_a, o_norm; + float* conv = nullptr; ///< 3 * d_inner * (d_conv - 1) + float* s = nullptr; ///< n_head * head_dim * head_dim + // MLA + Dev q, kv_a, kv_a_norm, k_b, v_b, gate; + Dev q_a, q_a_norm, q_b; ///< a low-rank query (Ling 3.0 tiny): q_b(rms_norm(q_a x)) in place of q + uint16_t* kv = nullptr; ///< max_context * (kv_rank + n_rot), fp16: the normed latent, then the turned key + // dense FFN + Dev ffn_gate, ffn_up, ffn_down; + std::vector probs_b; ///< what the routing adds to each expert's gate before it picks + }; + + void kda(Block& B, int n); + void mla(Block& B, int64_t pos, int n); + void mla_store(Block& B, int64_t pos, int n); + void dense_ffn(Block& B, int il, int n); + + std::vector blocks_; + + int n_head_ = 0, kda_dim_ = 0, d_inner_ = 0, n_kda_ = 0, n_mla_ = 0; + int kv_rank_ = 0, mla_k_ = 0, mla_v_ = 0, n_rot_ = 0, nope_ = 0, row_ = 0; ///< row_: kv_rank + n_rot + int n_group_ = 1, group_used_ = 1; + int q_lora_ = 0; ///< attention.q_lora_rank, 0 for a full-rank query + int chunk_ = 1; + float kda_lb_ = 0, w_scale_ = 1; + bool w_norm_ = false; + Rope rope_; + + // device scratch + float *proj_ = nullptr, *qkv_ = nullptr, *g1_ = nullptr, *g2_ = nullptr, *beta_ = nullptr, *gated_ = nullptr; + float *q_ = nullptr, *qa_ = nullptr, *qan_ = nullptr, *qn_ = nullptr, *kva_ = nullptr, *lat_ = nullptr, *qabs_ = nullptr, *qf_ = nullptr, + *att_ = nullptr, *kqv_ = nullptr, *vout_ = nullptr, *agate_ = nullptr, *score_ = nullptr, *awork_ = nullptr; +}; + +} // namespace strata::poly diff --git a/tools/strata_inspect.py b/tools/strata_inspect.py index 8c8ce1c398..36ff9a3bc0 100644 --- a/tools/strata_inspect.py +++ b/tools/strata_inspect.py @@ -34,7 +34,8 @@ # (setup.py's POLY_GGUF_ARCHS lists the arch set; keep these values byte-identical to those titles so # resolve_custom_gguf can map a "family" verdict back to --family/--model) POLY_ARCHS = {"gemma4": "Gemma 4 26B-A4B", "glm5-next": "GLM 5.3 Flash", "glm5next": "GLM 5.3 Flash", - "deepseek4": "DeepSeek V4 Flash", "lfm2moe": "LFM2.5-24B-A2B", "flint": "Flint 40B-A2.5B"} + "deepseek4": "DeepSeek V4 Flash", "lfm2moe": "LFM2.5-24B-A2B", "flint": "Flint 40B-A2.5B", + "bailingmoe3": "Ling 3.0 Flash"} # the files setup installs: (family, model, ModelScope repository, file name prefix) - for --fingerprints KNOWN = [ diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py index 4417d7595d..8278e970e3 100644 --- a/tools/strata_tokenizer.py +++ b/tools/strata_tokenizer.py @@ -130,8 +130,21 @@ def bytes_to_unicode() -> dict[int, str]: r"|\s+" ) +# The `bailingmoe2` pre-tokenizer (Ling 3.0 Flash), llama.cpp's LLAMA_VOCAB_PRE_TYPE_BAILINGMOE (its active version, +# greedy where tokenizer.json's is possessive): single digits, no `\p{M}`. +BAILINGMOE_PATTERN = ( + r"'(?:[sSdDmMtT]|[lL][lL]|[vV][eE]|[rR][eE])" + r"|[^\r\n\p{L}\p{N}]?\p{L}+" + r"|\p{N}" + r"| ?[^\s\p{L}\p{N}]+[\r\n]*" + r"|\s*[\r\n]" + r"|\s+(?!\S)" + r"|\s+" +) + PRE_PATTERNS = {"glm4": GLM4_PATTERN, "glm5": GLM4_PATTERN, # every other name: QWEN35_PATTERN, as before - "gemma4": GEMMA4_PATTERN, "lfm2": GLM4_PATTERN, "kolibri1": QWEN2_PATTERN} + "gemma4": GEMMA4_PATTERN, "lfm2": GLM4_PATTERN, "kolibri1": QWEN2_PATTERN, + "bailingmoe": BAILINGMOE_PATTERN, "bailingmoe2": BAILINGMOE_PATTERN, "llada-moe": BAILINGMOE_PATTERN} PRE_SEQUENCES = {"joyai-llm": DEEPSEEK3_SEQUENCE, "deepseek-v3": DEEPSEEK3_SEQUENCE, "flint": FLINT_SEQUENCE} IGNORE_MERGES = ("glm4", "glm5", "lfm2") RAW = ("gemma4",) # vocabularies of UTF-8 pieces diff --git a/tools/test_setup_ling3.py b/tools/test_setup_ling3.py new file mode 100644 index 0000000000..b25b8a98cc --- /dev/null +++ b/tools/test_setup_ling3.py @@ -0,0 +1,84 @@ +"""Tests for setup.py's Ling 3.0 Flash (docs/LING.md): its three pinned files, the estimates, and the install by +GLM's steps with the file's draft block left out (--no-draft). Mocked like tools/test_setup_glm.py, whose harness +this uses. + + python -m unittest tools.test_setup_ling3 +""" +from __future__ import annotations + +import json +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 +from tools import test_setup_glm as glm_tests # noqa: E402 + +FAM = setup.FAMILIES["ling3"] +# setup's order: the size taken with the RAM for it, the one with the least RAM, then the other +SIZES = [("Q4_K_M", 78285288128), ("Q3_K_M", 62563876544), ("UD-Q2_K_XL", 43444807104)] + + +class Pins(unittest.TestCase): + def test_the_files(self): + self.assertEqual(list(setup.family_models("ling3")), [m for m, _ in SIZES]) + self.assertRegex(FAM["hf"], r"^https://huggingface.co/bloomer010/Ling-3.0-flash-GGUF/resolve/[0-9a-f]{40}/$") + self.assertEqual(list(FAM["sha256"]), [f"Ling-3.0-flash-{m}.gguf" for m, _ in SIZES]) + for size, n in SIZES: + file = f"Ling-3.0-flash-{size}.gguf" + d = FAM["models"][size] + self.assertEqual((setup.model_file(FAM, size, 1), setup.model_shards(FAM, size)), (file, 1)) + self.assertEqual(FAM["sha256"][file][0], n) + self.assertRegex(FAM["sha256"][file][1], r"^[0-9a-f]{64}$") + self.assertAlmostEqual(n / 1e9, d["download_gb"], delta=0.05) + self.assertLess(d["arena_gb"], d["download_gb"]) + self.assertEqual(d["ram_gb"], round(setup.poly_ram_need(d, 8.0)), size) + + def test_the_about_line_says_the_first_size(self): + n = setup.poly_ram_need(FAM["models"]["Q4_K_M"], 16.0) + self.assertIn(f"~{n:.0f} GB of RAM beside a 16 GB card", FAM["about"]) + + def test_the_architecture(self): + self.assertEqual(setup.POLY_GGUF_ARCHS["ling3"], ("bailingmoe3",)) + sys.path.insert(0, str(ROOT / "tools")) + import strata_inspect + self.assertEqual(strata_inspect.POLY_ARCHS["bailingmoe3"], FAM["title"]) # resolve_custom_gguf's mapping + + +class Main(unittest.TestCase): + setUp, tearDown, main = glm_tests.Main.setUp, glm_tests.Main.tearDown, glm_tests.Main.main + + def test_install_each_size(self): + for size, _n in SIZES: + with self.subTest(size): + self.downloads, self.runs, self.verified = [], [], [] + code, out, _ = self.main(family="ling3", model=size, ram=96.0, vram=16376 / 1024) + self.assertEqual(code, 0, out) + cfg = json.loads((self.t / f"strata-ling3-{size.lower()}.json").read_text()) # one config a size + file = f"Ling-3.0-flash-{size}.gguf" + self.assertEqual(self.downloads, [FAM["hf"] + file]) + self.assertEqual(self.verified, [(file, *FAM["sha256"][file])]) + tag = "ling3-" + size + pack = self.t / "data" / "packs" / tag.lower() + self.assertEqual([Path(r[1]).name for r in self.runs], ["strata_tokenizer.py"]) + args = cfg["args"] + self.assertEqual(Path(args[args.index("--model") + 1]), self.t / "models" / tag / file) + self.assertEqual(Path(args[args.index("--expert-profile") + 1]), pack / "expert-profile.txt") + self.assertIn("--no-draft", args) # the file's own block is left out + self.assertNotIn("--draft-model", args) + self.assertEqual(cfg["model_name"], f"ling-3.0-flash-{size.lower()}") + self.assertNotIn("vision", cfg) + + def test_the_size_taken_without_a_name(self): + # on a 16 GB card: Q4_K_M wants ~72 GB of RAM, Q3_K_M ~57 and UD-Q2_K_XL ~37 (4 GB of slack each) + for ram, size in ((96.0, "Q4_K_M"), (62.0, "Q3_K_M"), (48.0, "UD-Q2_K_XL")): + with self.subTest(ram=ram): + code, out, _ = self.main(family="ling3", ram=ram, vram=16.0) + self.assertEqual(code, 0, out) + self.assertTrue((self.t / f"strata-ling3-{size.lower()}.json").exists(), out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_menu.py b/tools/test_setup_menu.py index 0817a7ff29..1cb17b3188 100644 --- a/tools/test_setup_menu.py +++ b/tools/test_setup_menu.py @@ -22,7 +22,7 @@ def test_the_menu_order_on_nvidia(self): fams = setup.menu_families(False) + list(setup.OWN_PATH_FAMILIES) self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth", "nvfp4", "glm", "deepseek", "lfm25", "flint", "kolibri", "qwen36", "clover", "ornith", "gemma4", "tiel", "minicpmv", "ornith122", - "qwen36-strata"]) + "ling3", "qwen36-strata"]) def test_the_default_stays_the_first_family(self): self.assertEqual(setup.menu_families(False)[0], "qwen") @@ -32,7 +32,8 @@ def test_nvfp4_is_not_listed_on_amd_and_intel(self): fams = setup.menu_families(True) self.assertNotIn("nvfp4", fams) self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth", "glm", "deepseek", "lfm25", "flint", "kolibri", - "qwen36", "clover", "ornith", "gemma4", "tiel", "minicpmv", "ornith122"]) + "qwen36", "clover", "ornith", "gemma4", "tiel", "minicpmv", "ornith122", + "ling3"]) self.assertIn("nvfp4", setup.FAMILIES) # --family nvfp4 still exists, and says why not def test_the_unsloth_line_names_the_alternative_on_amd_and_intel(self):