The 80B Qwen3-Coder-Next on a 16 GB Mac, about 13 tok/s, fully offline. A mixture-of-experts inference engine for Apple silicon.
Rust
Coachwhip v0.1.0: an 80B model, running comfortably on a 16 GB Mac
1picassoai8bfefc21b539
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..d0d6371--- /dev/null+++ b/.gitattributes@@ -0,0 +1,2 @@+* text=auto eol=lf+*.png binarydiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..35c2539--- /dev/null+++ b/.gitignore@@ -0,0 +1,10 @@+/target+*.gguf+tokenizer.json+tokenizer-*.json+build.log+.DS_Store+/learned+gate-out/+/data+/scriptsdiff --git a/Cargo.lock b/Cargo.locknew file mode 100644index 0000000..5629def--- /dev/null+++ b/Cargo.lock@@ -0,0 +1,1713 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "getrandom 0.3.4",+ "once_cell",+ "serde",+ "version_check",+ "zerocopy",+]++[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]++[[package]]+name = "allocator-api2"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"++[[package]]+name = "anstream"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"+dependencies = [+ "anstyle",+ "anstyle-parse",+ "anstyle-query",+ "anstyle-wincon",+ "colorchoice",+ "is_terminal_polyfill",+ "utf8parse",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anstyle-parse"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"+dependencies = [+ "utf8parse",+]++[[package]]+name = "anstyle-query"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"+dependencies = [+ "windows-sys",+]++[[package]]+name = "anstyle-wincon"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"+dependencies = [+ "anstyle",+ "once_cell_polyfill",+ "windows-sys",+]++[[package]]+name = "anyhow"+version = "1.0.104"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "base64"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "block2"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"+dependencies = [+ "objc2",+]++[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"++[[package]]+name = "candle-core"+version = "0.11.0"+source = "git+https://github.com/huggingface/candle?rev=5ba5d5b468b5b1df40e82dd3d556987bedeea041#5ba5d5b468b5b1df40e82dd3d556987bedeea041"+dependencies = [+ "byteorder",+ "candle-metal-kernels",+ "float8",+ "gemm",+ "half",+ "libc",+ "libm",+ "memmap2",+ "num-traits",+ "num_cpus",+ "objc2-foundation",+ "objc2-metal",+ "parking_lot",+ "rand",+ "rand_distr",+ "rayon",+ "safetensors",+ "thiserror 2.0.21",+ "tokenizers",+ "yoke",+ "zerocopy",+ "zip",+]++[[package]]+name = "candle-metal-kernels"+version = "0.11.0"+source = "git+https://github.com/huggingface/candle?rev=5ba5d5b468b5b1df40e82dd3d556987bedeea041#5ba5d5b468b5b1df40e82dd3d556987bedeea041"+dependencies = [+ "block2",+ "half",+ "objc2",+ "objc2-foundation",+ "objc2-metal",+ "once_cell",+ "thiserror 2.0.21",+ "tracing",+]++[[package]]+name = "candle-nn"+version = "0.11.0"+source = "git+https://github.com/huggingface/candle?rev=5ba5d5b468b5b1df40e82dd3d556987bedeea041#5ba5d5b468b5b1df40e82dd3d556987bedeea041"+dependencies = [+ "candle-core",+ "candle-metal-kernels",+ "half",+ "libc",+ "num-traits",+ "objc2-metal",+ "rayon",+ "safetensors",+ "serde",+ "thiserror 2.0.21",+]++[[package]]+name = "candle-transformers"+version = "0.11.0"+source = "git+https://github.com/huggingface/candle?rev=5ba5d5b468b5b1df40e82dd3d556987bedeea041#5ba5d5b468b5b1df40e82dd3d556987bedeea041"+dependencies = [+ "byteorder",+ "candle-core",+ "candle-nn",+ "fancy-regex 0.19.2",+ "num-traits",+ "rand",+ "rayon",+ "serde",+ "serde_json",+ "serde_plain",+ "tracing",+]++[[package]]+name = "castaway"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"+dependencies = [+ "rustversion",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "clap"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"+dependencies = [+ "clap_builder",+ "clap_derive",+]++[[package]]+name = "clap_builder"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"+dependencies = [+ "anstream",+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_derive"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "clap_lex"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"++[[package]]+name = "coachwhip"+version = "0.1.0"+dependencies = [+ "anyhow",+ "candle-core",+ "candle-metal-kernels",+ "candle-nn",+ "candle-transformers",+ "clap",+ "objc2-metal",+ "rayon",+ "serde_json",+ "tokenizers",+]++[[package]]+name = "colorchoice"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"++[[package]]+name = "compact_str"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"+dependencies = [+ "castaway",+ "cfg-if",+ "itoa",+ "rustversion",+ "ryu",+ "serde",+ "static_assertions",+]++[[package]]+name = "crc32fast"+version = "1.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"++[[package]]+name = "daachorse"+version = "3.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d"++[[package]]+name = "darling"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"+dependencies = [+ "fnv",+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 2.0.119",+]++[[package]]+name = "darling_macro"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"+dependencies = [+ "darling_core",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "dary_heap"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe"+dependencies = [+ "serde",+]++[[package]]+name = "derive_builder"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"+dependencies = [+ "derive_builder_macro",+]++[[package]]+name = "derive_builder_core"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "derive_builder_macro"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"+dependencies = [+ "derive_builder_core",+ "syn 2.0.119",+]++[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags",+ "objc2",+]++[[package]]+name = "dyn-stack"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c4713e43e2886ba72b8271aa66c93d722116acf7a75555cce11dcde84388fe8"+dependencies = [+ "bytemuck",+ "dyn-stack-macros",+]++[[package]]+name = "dyn-stack-macros"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9"++[[package]]+name = "either"+version = "1.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"++[[package]]+name = "enum-as-inner"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys",+]++[[package]]+name = "esaxx-rs"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6"++[[package]]+name = "fancy-regex"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8"+dependencies = [+ "bit-set",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "fancy-regex"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912"+dependencies = [+ "bit-set",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"++[[package]]+name = "float8"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc"+dependencies = [+ "half",+ "num-traits",+ "rand",+ "rand_distr",+]++[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "gemm"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa0673db364b12263d103b68337a68fbecc541d6f6b61ba72fe438654709eacb"+dependencies = [+ "dyn-stack",+ "gemm-c32",+ "gemm-c64",+ "gemm-common",+ "gemm-f16",+ "gemm-f32",+ "gemm-f64",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-c32"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "086936dbdcb99e37aad81d320f98f670e53c1e55a98bee70573e83f95beb128c"+dependencies = [+ "dyn-stack",+ "gemm-common",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-c64"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20c8aeeeec425959bda4d9827664029ba1501a90a0d1e6228e48bef741db3a3f"+dependencies = [+ "dyn-stack",+ "gemm-common",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-common"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88027625910cc9b1085aaaa1c4bc46bb3a36aad323452b33c25b5e4e7c8e2a3e"+dependencies = [+ "bytemuck",+ "dyn-stack",+ "half",+ "libm",+ "num-complex",+ "num-traits",+ "once_cell",+ "paste",+ "pulp",+ "raw-cpuid",+ "rayon",+ "seq-macro",+ "sysctl",+]++[[package]]+name = "gemm-f16"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3df7a55202e6cd6739d82ae3399c8e0c7e1402859b30e4cb780e61525d9486e"+dependencies = [+ "dyn-stack",+ "gemm-common",+ "gemm-f32",+ "half",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "rayon",+ "seq-macro",+]++[[package]]+name = "gemm-f32"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02e0b8c9da1fbec6e3e3ab2ce6bc259ef18eb5f6f0d3e4edf54b75f9fd41a81c"+dependencies = [+ "dyn-stack",+ "gemm-common",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-f64"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "056131e8f2a521bfab322f804ccd652520c79700d81209e9d9275bbdecaadc6a"+dependencies = [+ "dyn-stack",+ "gemm-common",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 5.3.0",+ "wasip2",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 6.0.0",+]++[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "bytemuck",+ "cfg-if",+ "crunchy",+ "num-traits",+ "rand",+ "rand_distr",+ "zerocopy",+]++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash",+ "serde",+ "serde_core",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "hermit-abi"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"++[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+]++[[package]]+name = "is_terminal_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"++[[package]]+name = "itertools"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+dependencies = [+ "either",+]++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "libc"+version = "0.2.189"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"++[[package]]+name = "macro_rules_attribute"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c"+dependencies = [+ "macro_rules_attribute-proc_macro",+ "pastey",+]++[[package]]+name = "macro_rules_attribute-proc_macro"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memmap2"+version = "0.9.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"+dependencies = [+ "libc",+ "stable_deref_trait",+]++[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"++[[package]]+name = "monostate"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67"+dependencies = [+ "monostate-impl",+ "serde",+ "serde_core",+]++[[package]]+name = "monostate-impl"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]++[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "bytemuck",+ "num-traits",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+ "libm",+]++[[package]]+name = "num_cpus"+version = "1.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"+dependencies = [+ "hermit-abi",+ "libc",+]++[[package]]+name = "objc2"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags",+ "dispatch2",+ "objc2",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags",+ "block2",+ "libc",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-metal"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"+dependencies = [+ "bitflags",+ "block2",+ "dispatch2",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "once_cell_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "pastey"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "pulp"+version = "0.22.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a"+dependencies = [+ "bytemuck",+ "cfg-if",+ "libm",+ "num-complex",+ "paste",+ "pulp-wasm-simd-flag",+ "raw-cpuid",+ "reborrow",+ "version_check",+]++[[package]]+name = "pulp-wasm-simd-flag"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740"++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rand"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"+dependencies = [+ "rand_chacha",+ "rand_core",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core",+]++[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",+]++[[package]]+name = "rand_distr"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463"+dependencies = [+ "num-traits",+ "rand",+]++[[package]]+name = "raw-cpuid"+version = "11.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"+dependencies = [+ "bitflags",+]++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-cond"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f"+dependencies = [+ "either",+ "itertools",+ "rayon",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "reborrow"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags",+]++[[package]]+name = "regex"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "rustix"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"+dependencies = [+ "bitflags",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"++[[package]]+name = "safetensors"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846"+dependencies = [+ "hashbrown 0.16.1",+ "libc",+ "serde",+ "serde_json",+ "tempfile",+]++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "seq-macro"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "serde_json"+version = "1.0.151"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_plain"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50"+dependencies = [+ "serde",+]++[[package]]+name = "smallvec"+version = "1.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"++[[package]]+name = "spm_precompiled"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326"+dependencies = [+ "base64",+ "nom",+ "serde",+ "unicode-segmentation",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "synstructure"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "sysctl"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc"+dependencies = [+ "bitflags",+ "byteorder",+ "enum-as-inner",+ "libc",+ "thiserror 1.0.69",+ "walkdir",+]++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom 0.4.3",+ "once_cell",+ "rustix",+ "windows-sys",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "tokenizers"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc"+dependencies = [+ "ahash",+ "compact_str",+ "daachorse",+ "dary_heap",+ "derive_builder",+ "esaxx-rs",+ "fancy-regex 0.17.0",+ "getrandom 0.3.4",+ "itertools",+ "log",+ "macro_rules_attribute",+ "monostate",+ "paste",+ "rand",+ "rayon",+ "rayon-cond",+ "regex",+ "regex-syntax",+ "serde",+ "serde_json",+ "spm_precompiled",+ "thiserror 2.0.21",+ "unicode-normalization-alignments",+ "unicode-segmentation",+ "unicode_categories",+]++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-attributes",+ "tracing-core",+]++[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]++[[package]]+name = "typed-path"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"++[[package]]+name = "unicode-ident"+version = "1.0.26"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"++[[package]]+name = "unicode-normalization-alignments"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de"+dependencies = [+ "smallvec",+]++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "unicode_categories"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"++[[package]]+name = "utf8parse"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "yoke"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "synstructure 0.13.2",+]++[[package]]+name = "zerocopy"+version = "0.8.59"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.59"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "synstructure 0.14.0",+]++[[package]]+name = "zip"+version = "8.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"+dependencies = [+ "crc32fast",+ "indexmap",+ "memchr",+ "typed-path",+]++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"diff --git a/Cargo.toml b/Cargo.tomlnew file mode 100644index 0000000..3dd4dc1--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,22 @@+[package]+name = "coachwhip"+version = "0.1.0"+edition = "2021"+description = "Run mixture-of-experts models bigger than your memory on a Mac: an 80B model on 16 GB. The experts stream from the SSD into a small GPU bank."+license = "Apache-2.0"+publish = false++[dependencies]+candle = { package = "candle-core", git = "https://github.com/huggingface/candle", rev = "5ba5d5b468b5b1df40e82dd3d556987bedeea041", features = ["metal"] }+candle-nn = { git = "https://github.com/huggingface/candle", rev = "5ba5d5b468b5b1df40e82dd3d556987bedeea041", features = ["metal"] }+candle-transformers = { git = "https://github.com/huggingface/candle", rev = "5ba5d5b468b5b1df40e82dd3d556987bedeea041", features = ["metal"] }+candle-metal-kernels = { git = "https://github.com/huggingface/candle", rev = "5ba5d5b468b5b1df40e82dd3d556987bedeea041" }+objc2-metal = "0.3.1"+tokenizers = { version = "0.23.1", default-features = false, features = ["fancy-regex"] }+clap = { version = "4.2.4", features = ["derive"] }+anyhow = "1"+serde_json = "1.0.99"+rayon = "1"++[profile.release]+debug = falsediff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..261eeb9--- /dev/null+++ b/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..e20e739--- /dev/null+++ b/README.md@@ -0,0 +1,143 @@+<p align="center"><img src="docs/coachwhip.png" alt="A coachwhip snake on sand" width="720"></p>++# Coachwhip++**Run mixture-of-experts models that are bigger than your memory.**++An 80B model, running comfortably on a 16 GB Mac. Coachwhip never needs the whole model in memory, because a mixture-of-experts model never needs the whole model for one word.++One Rust binary. Everything on the GPU. Nothing leaves your machine.++<p align="center"><img src="docs/coachwhip-demo.gif" alt="Qwen3-Coder-Next (80B) writing TypeScript in the Coachwhip chat on a 16 GB Mac" width="720"></p>++## Why it works++A mixture-of-experts (MoE) model is made of many small experts, and a router picks only a few of them for each word. Qwen3-Coder-Next has 80 billion parameters, but each word wakes up only about 3 billion of them.++Coachwhip is built around that fact:++- **Streams experts, not files.** The small, always-used part of the model lives on the GPU. The experts stay on the SSD, and for each word Coachwhip reads exactly the experts the router picked.+- **An expert bank on the GPU.** Recently used experts stay in a bank in the GPU's memory and are reused, so the SSD is only touched for experts the bank does not hold.+- **The hot path.** While the GPU works on one layer, Coachwhip predicts which experts the next layer will want and fetches them in parallel. The predictions are learned from the routes the model has taken before, and every chat teaches it more.+- **One GPU dispatch per layer.** All the experts a layer picked run together in a single fused kernel.+- **Reads while it computes.** When a prompt needs more experts than the bank holds, the GPU starts on each expert the moment its bytes land, while the rest are still being read.+- **Unified memory, used properly.** On Apple silicon the CPU and GPU share one memory, so an expert read from the SSD lands straight where the GPU reads it. No copies.++## Numbers++Mac mini M4, 16 GB, both models at Q4_K_M.++| | Qwen3-Coder-30B-A3B | Qwen3-Coder-Next (80B) |+|---|---|---|+| Model file | 18.6 GB | 48.4 GB |+| Follow-up in a chat | reads only your new words | reads only your new words |++While it reads your prompt, the page shows the layer it is on, from the first second.++## What it does to your Mac++Honest numbers, so you can decide.++| | 30B on 16 GB (bank 44) | 80B on 16 GB (bank 56) |+|---|---|---|+| Held by Coachwhip while the model is hot | about 11 GB | about 7.5 GB |+| Left for everything else | about 3 GB | about 7 GB |++The 30B's experts are bigger than the 80B's, so it holds more. If memory runs short, macOS squeezes your other apps, not Coachwhip. If the GPU runs out of room, Coachwhip says so on the page and stops; close some apps, or start it again with a smaller `--bank`.++With 24 GB or more the 80B runs with room to spare. `--bank` trades GPU memory for speed in either direction; on 16 GB, 56 is the most the 80B should use.++## Models++Coachwhip is an engine for MoE models, in GGUF format.++| Model | Architecture | Status |+|---|---|---|+| [Qwen3-Coder-30B-A3B-Instruct](https://huggingface.co/Qwen/Qwen3-Coder-30B-A3B-Instruct) | qwen3moe | Tested. |+| [Qwen3-Coder-Next](https://huggingface.co/Qwen/Qwen3-Coder-Next) (80B) | qwen3next | Tested. See below for the file to use. |+| [Qwen3-Next-80B-A3B-Instruct](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Instruct) | qwen3next | Tested. |+| Qwen3-30B-A3B, other Qwen3 MoE | qwen3moe | Supported. |+| Mixtral, Qwen2-MoE, OLMoE, DeepSeek, gpt-oss, GLM | | Coming next. |++Try other MoE models and tell us what happens. If a model's architecture is not supported yet, Coachwhip says so, and an issue is the fastest way to move it up the list.++**Which GGUF file.** Coachwhip reads the standard GGUF quantisations (Q4_K, Q5_K, Q6_K, Q8_0, F16). Some newer conversions store a few tensors in MXFP4 or fuse the attention weights into one tensor; Coachwhip does not read those yet. For Qwen3-Coder-Next, [MaziyarPanahi's Q4_K_M](https://huggingface.co/MaziyarPanahi/Qwen3-Coder-Next-GGUF) loads as is.++## What you need++| | 30B | 80B |+|---|---|---|+| Mac | Apple silicon (M1 or later). Tested on a Mac mini M4. | the same |+| Memory | 16 GB | 16 GB; 24 GB has room to spare |+| Disk | 19 GB for the model, 3 GB for the build | 49 GB for the model, 3 GB for the build |+| macOS | Tested on macOS 26 | the same |++## Install++One line in Terminal:++```sh+curl -fsSL https://raw.githubusercontent.com/1picassoai/coachwhip/main/install.sh | bash+```++It checks your Mac, installs what is missing (Apple's command line tools, Rust) and builds Coachwhip into `~/coachwhip`, in about 10 minutes. Run it again at any time: it skips whatever is already done.++If a window asks to install Apple's command line tools, finish it and run the line again.++## Bring a model++Coachwhip is the engine; the model is yours. Any GGUF of a supported model works (see Models).++**Recommended: Qwen3-Coder-Next, the 80B coder.** Download its [Q4_K_M GGUF](https://huggingface.co/MaziyarPanahi/Qwen3-Coder-Next-GGUF) (48 GB) and its [tokenizer.json](https://huggingface.co/Qwen/Qwen3-Coder-Next), then start it with a bank of 56:++```sh+~/coachwhip/coachwhip.sh ~/Downloads/Qwen3-Coder-Next.Q4_K_M.gguf ~/Downloads/tokenizer.json 56+```++| Model | GGUF file | Tokenizer | Bank on 16 GB |+|---|---|---|---|+| Qwen3-Coder-Next (80B), recommended | [MaziyarPanahi Q4_K_M](https://huggingface.co/MaziyarPanahi/Qwen3-Coder-Next-GGUF) | [tokenizer.json](https://huggingface.co/Qwen/Qwen3-Coder-Next) | 56 |+| Qwen3-Coder-30B-A3B, a smaller download | [unsloth Q4_K_M](https://huggingface.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF) | [tokenizer.json](https://huggingface.co/Qwen/Qwen3-Coder-30B-A3B-Instruct) | 44 |++## Use++**Chat in your browser:**++```sh+~/coachwhip/coachwhip.sh /path/to/model.gguf /path/to/tokenizer.json 56+```++The last number is the bank (44 if you leave it out). The chat opens in your browser. Type, press Send, and the answer streams as it is written. Follow-up questions read only your new words; press **New chat** to start again. Stop Coachwhip with Ctrl+C.++**One answer in the terminal:**++```sh+cd ~/coachwhip+./target/release/coachwhip --model /path/to/model.gguf --tokenizer /path/to/tokenizer.json --prompt "Write a Rust function that reverses a linked list."+```++**Useful options:**++| Option | What it does |+|---|---|+| `--chat 8090` | Serve the chat page on that port, on this machine only |+| `--max-tokens 4000` | Longest answer |+| `--temperature 0` | Always pick the likeliest word (same answer every time) |+| `--bank 44` | Expert slots kept on the GPU per layer (56 for the 80B) |+| `--profile` | Print where the time went after each answer |+| `--help` | Everything else |++## Roadmap++- More MoE families: Mixtral, Qwen2-MoE, OLMoE, DeepSeek, gpt-oss, GLM.+- MXFP4 and fused-attention GGUF files.+- An adapter that reads your own repository, on your own machine.+- More platforms.++## Credits++Built on [Candle](https://github.com/huggingface/candle). `src/model.rs` is derived from Candle's Qwen3 model, and the fused expert kernel is ggml's `mul_mv_id`, which ships inside Candle. The block-at-a-time linear attention follows [Gated Delta Networks](https://arxiv.org/abs/2412.06464) (Yang, Kautz and Hatamizadeh, ICLR 2025).++## Licence++Apache-2.0. See [LICENSE](LICENSE).diff --git a/coachwhip.sh b/coachwhip.shnew file mode 100755index 0000000..1b64c3c--- /dev/null+++ b/coachwhip.sh@@ -0,0 +1,21 @@+#!/bin/bash+# Start the Coachwhip chat and open it in the browser.+# ./coachwhip.sh <model.gguf> <tokenizer.json> [bank] [port]+set -euo pipefail+[ $# -ge 2 ] || { echo "usage: $0 <model.gguf> <tokenizer.json> [bank] [port]" >&2; exit 1; }+# Paths are made absolute before moving to the Coachwhip folder, so relative ones work too.+abs() { [ -f "$1" ] || { echo "no such file: $1" >&2; exit 1; }; echo "$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"; }+MODEL="$(abs "$1")"+TOKENIZER="$(abs "$2")"+BANK="${3:-44}"+PORT="${4:-8090}"+cd "$(dirname "$0")"+./target/release/coachwhip --model "$MODEL" --tokenizer "$TOKENIZER" --bank "$BANK" --chat "$PORT" &+pid=$!+trap 'kill $pid 2>/dev/null' INT TERM EXIT+until curl -s -o /dev/null "http://127.0.0.1:$PORT/"; do+ kill -0 $pid 2>/dev/null || exit 1+ sleep 1+done+open "http://127.0.0.1:$PORT/"+wait $piddiff --git a/docs/coachwhip-demo.gif b/docs/coachwhip-demo.gifnew file mode 100644index 0000000..eaf43b3Binary files /dev/null and b/docs/coachwhip-demo.gif differdiff --git a/docs/coachwhip.png b/docs/coachwhip.pngnew file mode 100644index 0000000..aa950cfBinary files /dev/null and b/docs/coachwhip.png differdiff --git a/install.sh b/install.shnew file mode 100755index 0000000..69e4e42--- /dev/null+++ b/install.sh@@ -0,0 +1,76 @@+#!/bin/bash+# Coachwhip installer: checks this Mac, installs what is missing and builds Coachwhip. Bring your+# own model. Run it again at any time; it skips whatever is already done.+#+# curl -fsSL https://raw.githubusercontent.com/1picassoai/coachwhip/main/install.sh | bash+#+# COACHWHIP_DIR picks the install folder (default ~/coachwhip).+set -euo pipefail++# Everything runs inside main, so a download cut off half way through runs nothing.+main() {+DIR="${COACHWHIP_DIR:-$HOME/coachwhip}"+REPO="${COACHWHIP_REPO:-https://github.com/1picassoai/coachwhip}"++say() { printf "\033[1;32m==>\033[0m %s\n" "$*"; }+die() { printf "\033[1;31merror:\033[0m %s\n" "$*" >&2; exit 1; }++# 1. This Mac+[ "$(uname -s)" = Darwin ] || die "Coachwhip runs on macOS only."+[ "$(uname -m)" = arm64 ] || die "Coachwhip needs an Apple silicon Mac (M1 or later)."+mem_gb=$(( $(sysctl -n hw.memsize) / 1073741824 ))+[ "$mem_gb" -ge 16 ] || die "Coachwhip needs 16 GB of memory; this Mac has $mem_gb GB."+need_gb=4+mkdir -p "$DIR"+free_gb=$(df -g "$DIR" | awk 'NR==2 {print $4}')+[ "$free_gb" -ge "$need_gb" ] || die "Coachwhip needs $need_gb GB of free disk; there are $free_gb GB."+say "Apple silicon, $mem_gb GB of memory, $free_gb GB free: good."++# 2. Apple's command line tools+if ! xcode-select -p >/dev/null 2>&1; then+ say "Installing Apple's command line tools. A window opens: finish it, then run this installer again."+ xcode-select --install || true+ exit 1+fi++# 3. Rust+export PATH="$HOME/.cargo/bin:$PATH"+if ! command -v cargo >/dev/null 2>&1; then+ say "Installing Rust"+ curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal+fi++# 4. Coachwhip+if [ -d "$DIR/.git" ]; then+ say "Updating Coachwhip"+ git -C "$DIR" pull --ff-only+elif [ -f "$DIR/Cargo.toml" ]; then+ say "Using the Coachwhip source already in $DIR"+else+ say "Downloading Coachwhip"+ tmp="$(mktemp -d)"+ git clone --depth 1 "$REPO" "$tmp/coachwhip"+ cp -R "$tmp/coachwhip/." "$DIR/"+ rm -rf "$tmp"+fi+cd "$DIR"+say "Building Coachwhip (the first build takes about 10 minutes)"+if ! cargo build --release 2> build.log; then+ # Some Command Line Tools ship a beta SDK the linker cannot read; build against the one that+ # matches this macOS instead.+ major="$(sw_vers -productVersion | cut -d. -f1)"+ sdk="$(ls -d /Library/Developer/CommandLineTools/SDKs/MacOSX"$major".*.sdk 2>/dev/null | sort -t. -k2,2n | tail -1 || true)"+ [ -n "$sdk" ] || sdk="/Library/Developer/CommandLineTools/SDKs/MacOSX$major.sdk"+ if grep -q "unknown architecture" build.log && [ -d "$sdk" ]; then+ say "Building again against $(basename "$sdk")"+ SDKROOT="$sdk" cargo build --release 2> build.log || die "The build failed; see $DIR/build.log"+ else+ die "The build failed; see $DIR/build.log"+ fi+fi++say "Done. Start Coachwhip with your model and its tokenizer:"+printf "\n %s/coachwhip.sh /path/to/model.gguf /path/to/tokenizer.json\n\nIt opens the chat in your browser. Stop it with Ctrl+C.\n\n" "$DIR"+}++main "$@"diff --git a/src/chat.rs b/src/chat.rsnew file mode 100644index 0000000..da9fa97--- /dev/null+++ b/src/chat.rs@@ -0,0 +1,455 @@+//! The chat: the model loads once and stays hot; a page on loopback sends each prompt in.+//!+//! One thread, no framework - `std::net::TcpListener` and a string of HTML. Nothing leaves the+//! machine: the page is served on 127.0.0.1 only. The answer streams: each word goes out as an+//! HTTP chunk the moment it is written.+//!+//! A chat is one long conversation the model has already read: a follow-up reads only its own new+//! words, then the model carries on from where it stopped.++use anyhow::Result;+use std::cell::RefCell;+use std::io::{BufRead, BufReader, Read, Write};+use std::net::{TcpListener, TcpStream};+use std::rc::Rc;++use candle::{Device, Tensor};+use candle_transformers::generation::{LogitsProcessor, Sampling};+use crate::model::{Model, Progress, Step};+use tokenizers::Tokenizer;++/// Largest request body accepted: a prompt of a few hundred pages.+const MAX_BODY: usize = 1 << 20;++/// Longest piece of a prompt read in one forward pass.+const PROMPT_CHUNK: usize = 512;++/// When a chat would grow past this many words, it is summarised first to make room.+const CONTEXT_LIMIT: usize = 16384;++/// Longest summary written when making room.+const SUMMARY_TOKENS: usize = 500;++const SUMMARY_ASK: &str = "Summarise our conversation so far in at most 300 words, for someone who will continue it: what was asked, what was decided, and every name, file, function or fact the next answer will need. Plain text, no preamble.";++/// Separates the streamed text from the closing stats line.+pub(crate) const STATS_MARK: &str = "\u{1}STATS:";++/// A progress line sent while the prompt is read, before any text: `\u{1}PROG:<json>\n`.+pub(crate) const PROG_MARK: &str = "\u{1}PROG:";++/// Ends the stream when the answer could not be finished; the page shows what follows it.+pub(crate) const ERROR_MARK: &str = "\u{1}ERROR:";++/// After the GPU has run out of memory once, Metal does not recover in this process.+fn gpu_out_of_memory(e: &anyhow::Error) -> bool {+ let m = format!("{e:#}");+ m.contains("OutOfMemory") || m.contains("Insufficient Memory")+}++pub fn serve(port: u16, model: &mut Model, model_name: &str, tokenizer: Tokenizer, device: &Device, max_new: usize, sampling: Sampling) -> Result<()> {+ let listener = TcpListener::bind(("127.0.0.1", port))?;+ println!("\n coachwhip chat on http://127.0.0.1:{port} (model hot, loopback only)\n");+ let mut session = Session::default();+ for stream in listener.incoming() {+ let Ok(stream) = stream else { continue };+ if let Err(e) = handle(stream, model, model_name, &tokenizer, device, max_new, &sampling, &mut session) {+ eprintln!(" request failed: {e}");+ }+ }+ Ok(())+}++/// Where the model is in the current chat.+#[derive(Default)]+pub struct Session {+ /// Words the model has read so far, its own answers included.+ pos: usize,+ /// The last word of an answer cut off at the length limit: written, but not yet read back.+ pending: Option<u32>,+}++pub struct Answer {+ /// New words read for this question; the earlier chat was not read again.+ pub prompt_tokens: usize,+ /// Words in the chat after this answer.+ pub context: usize,+ pub fresh: bool,+ /// The chat was summarised to make room before this answer.+ pub compacted: bool,+ pub written: usize,+ pub read_tps: f64,+ pub write_tps: f64,+}++/// Runs the model and hands every new piece of text to `emit` as soon as it exists.+#[allow(clippy::too_many_arguments)]+pub fn generate(+ model: &mut Model,+ tokenizer: &Tokenizer,+ device: &Device,+ session: &mut Session,+ new_chat: bool,+ prompt: &str,+ think: bool,+ max_new: usize,+ sampling: &Sampling,+ progress: Option<Progress>,+ emit: &mut dyn FnMut(&str) -> Result<()>,+) -> Result<Answer> {+ let think = think && model.thinks();+ let no_think = if think || !model.thinks() { "" } else { " /no_think" };+ let encode = |text: String| -> Result<Vec<u32>> { Ok(tokenizer.encode(text, true).map_err(anyhow::Error::msg)?.get_ids().to_vec()) };+ let eos = *tokenizer.get_vocab(true).get("<|im_end|>").unwrap();+ let mut sampler = LogitsProcessor::from_sampling(42, sampling.clone());+ let tell = progress.map(|p| Rc::new(RefCell::new(p)));++ // A follow-up closes the last answer and adds the new question; nothing earlier is read again.+ let turn = format!("<|im_start|>user\n{prompt}{no_think}<|im_end|>\n<|im_start|>assistant\n");+ let mut tokens = Vec::new();+ let mut fresh = new_chat || session.pos == 0;+ let mut summary = None;+ if !fresh {+ tokens.extend(session.pending);+ tokens.extend(encode(format!("<|im_end|>\n{turn}"))?);+ // Too long to go on: the model summarises the chat, and the summary opens a new one.+ if session.pos + tokens.len() + max_new > CONTEXT_LIMIT {+ summary = Some(summarise(model, tokenizer, device, session, no_think, eos, &tell)?);+ fresh = true;+ }+ }+ if fresh {+ model.clear_kv_cache();+ *session = Session::default();+ tokens = encode(match &summary {+ Some(s) => format!("<|im_start|>user\nSummary of our conversation so far, for context:\n{s}\n\nNow: {prompt}{no_think}<|im_end|>\n<|im_start|>assistant\n"),+ None => turn,+ })?;+ }++ let t0 = std::time::Instant::now();+ let logits = read_prompt(model, device, session.pos, &tokens, &tell)?;+ let base = session.pos + tokens.len();+ let mut next = sampler.sample(&logits)?;+ let read = t0.elapsed().as_secs_f64();++ // The answer so far; an end-of-turn word is never part of it.+ let mut out = if next == eos { Vec::new() } else { vec![next] };+ let mut sent = 0usize;+ let mut stream_text = |out: &[u32], sent: &mut usize| -> Result<()> {+ let full = tokenizer.decode(out, true).map_err(anyhow::Error::msg)?;+ // A token can be half of a multi-byte character; wait until the text is whole.+ if full.ends_with('\u{FFFD}') {+ return Ok(());+ }+ // With thinking off the model still opens and closes an empty think block; skip it.+ let start = if !think && full.starts_with("<think>") {+ match full.find("</think>") {+ Some(i) => {+ let after = &full[i + "</think>".len()..];+ i + "</think>".len() + (after.len() - after.trim_start_matches('\n').len())+ }+ None => return Ok(()),+ }+ } else {+ 0+ };+ let from = start.max(*sent);+ // A later decode can re-space earlier text; wait for a clean place to carry on from.+ if !full.is_char_boundary(from) {+ return Ok(());+ }+ if full.len() > from {+ emit(&full[from..])?;+ *sent = full.len();+ }+ Ok(())+ };+ stream_text(&out, &mut sent)?;+ let t1 = std::time::Instant::now();+ while out.len() < max_new && next != eos {+ let logits = model.forward(&Tensor::new(&[next], device)?.unsqueeze(0)?, base + out.len() - 1)?.squeeze(0)?;+ next = sampler.sample(&logits)?;+ if next != eos {+ out.push(next);+ stream_text(&out, &mut sent)?;+ }+ }+ let write = t1.elapsed().as_secs_f64();+ let written = out.len();+ // Every word of the answer was read back, except the last one when the length limit cut it off.+ let finished = next == eos;+ session.pos = base + if finished { out.len() } else { out.len() - 1 };+ session.pending = if finished { None } else { out.last().copied() };+ Ok(Answer {+ prompt_tokens: tokens.len(),+ context: session.pos,+ fresh,+ compacted: summary.is_some(),+ written,+ read_tps: tokens.len() as f64 / read.max(1e-9),+ // The first word comes out of reading the prompt; the rate counts the ones written after it.+ write_tps: written.saturating_sub(1) as f64 / write.max(1e-9),+ })+}++/// Reads a prompt that continues the chat at `pos`, and returns the logits for the next word.+/// The chunker: a long prompt is read in pieces, so the memory a piece needs stays bounded.+/// While it reads, every finished layer is reported, counted across all the pieces, so the page+/// is never silent.+fn read_prompt(model: &mut Model, device: &Device, pos: usize, tokens: &[u32], tell: &Option<Rc<RefCell<Progress>>>) -> Result<Tensor> {+ let pieces = tokens.len().div_ceil(PROMPT_CHUNK);+ let read = (|| -> Result<Tensor> {+ let mut logits = None;+ for (i, piece) in tokens.chunks(PROMPT_CHUNK).enumerate() {+ model.set_progress(tell.clone().map(|t| -> Progress {+ Box::new(move |step| {+ if let Step::Layer(layer, of) = step {+ (t.borrow_mut())(Step::Layer(i * of + layer, pieces * of))+ }+ })+ }));+ logits = Some(model.forward(&Tensor::new(piece, device)?.unsqueeze(0)?, pos + i * PROMPT_CHUNK)?.squeeze(0)?);+ }+ logits.ok_or_else(|| anyhow::anyhow!("empty prompt"))+ })();+ // Taken back on every path: the hook holds the page's connection open.+ model.set_progress(None);+ read+}++/// Asks the model, in the chat as it stands, for a summary of the chat; the chat is then thrown+/// away and the summary opens the next one. Greedy, so it is the same every time.+fn summarise(model: &mut Model, tokenizer: &Tokenizer, device: &Device, session: &Session, no_think: &str, eos: u32, tell: &Option<Rc<RefCell<Progress>>>) -> Result<String> {+ let mut tokens: Vec<u32> = session.pending.into_iter().collect();+ let ask = format!("<|im_end|>\n<|im_start|>user\n{SUMMARY_ASK}{no_think}<|im_end|>\n<|im_start|>assistant\n");+ tokens.extend(tokenizer.encode(ask, true).map_err(anyhow::Error::msg)?.get_ids().to_vec());+ let mut sampler = LogitsProcessor::from_sampling(42, Sampling::ArgMax);+ let logits = read_prompt(model, device, session.pos, &tokens, tell)?;+ let mut next = sampler.sample(&logits)?;+ let base = session.pos + tokens.len();+ let mut out = Vec::new();+ while next != eos && out.len() < SUMMARY_TOKENS {+ out.push(next);+ if let Some(t) = tell {+ if out.len() % 8 == 0 {+ (t.borrow_mut())(Step::Summary(out.len()));+ }+ }+ let logits = model.forward(&Tensor::new(&[next], device)?.unsqueeze(0)?, base + out.len() - 1)?.squeeze(0)?;+ next = sampler.sample(&logits)?;+ }+ let text = tokenizer.decode(&out, true).map_err(anyhow::Error::msg)?;+ let text = match text.find("</think>") {+ Some(i) if text.starts_with("<think>") => text[i + "</think>".len()..].to_string(),+ _ => text,+ };+ let text = text.trim().to_string();+ println!(" made room: {} tokens of chat summarised into {} tokens", session.pos, out.len());+ Ok(text)+}++pub(crate) fn html_escape(t: &str) -> String {+ t.replace('&', "&").replace('<', "<").replace('>', ">")+}++pub(crate) fn chunk(s: &mut TcpStream, bytes: &[u8]) -> Result<()> {+ if bytes.is_empty() {+ return Ok(());+ }+ write!(s, "{:x}\r\n", bytes.len())?;+ s.write_all(bytes)?;+ s.write_all(b"\r\n")?;+ s.flush()?;+ Ok(())+}++fn handle(mut s: TcpStream, model: &mut Model, model_name: &str, tokenizer: &Tokenizer, device: &Device, max_new: usize, sampling: &Sampling, session: &mut Session) -> Result<()> {+ // A client that stops sending must not hold the one-at-a-time server forever.+ s.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;+ let mut r = BufReader::new(s.try_clone()?).take(64 * 1024 + MAX_BODY as u64);+ let mut line = String::new();+ r.read_line(&mut line)?;+ let path = line.split_whitespace().nth(1).unwrap_or("/").to_string();+ let mut len = 0usize;+ let mut host = String::new();+ let mut origin = String::new();+ loop {+ let mut h = String::new();+ if r.read_line(&mut h)? == 0 || h.trim().is_empty() {+ break;+ }+ let lower = h.to_lowercase();+ if let Some(v) = lower.strip_prefix("content-length:") {+ len = v.trim().parse().unwrap_or(0);+ } else if let Some(v) = lower.strip_prefix("host:") {+ host = v.trim().to_string();+ } else if let Some(v) = lower.strip_prefix("origin:") {+ origin = v.trim().to_string();+ }+ }+ // Only this machine's own page may talk to the model: another site open in the browser+ // could otherwise post prompts here.+ let port = s.local_addr()?.port();+ let local = |h: &str| h == format!("127.0.0.1:{port}") || h == format!("localhost:{port}");+ let own_page = local(&host) && (origin.is_empty() || origin.strip_prefix("http://").is_some_and(local));+ if path == "/ask" && (!own_page || len > MAX_BODY) {+ write!(s, "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")?;+ return Ok(());+ }+ if path == "/ask" {+ let mut body = vec![0u8; len];+ r.read_exact(&mut body)?;+ let Ok(q) = serde_json::from_slice::<serde_json::Value>(&body) else {+ write!(s, "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n")?;+ return Ok(());+ };+ let prompt = q["prompt"].as_str().unwrap_or("");+ let think = q["think"].as_bool().unwrap_or(false);+ let new_chat = q["new_chat"].as_bool().unwrap_or(false);+ let max_new = q["max_new"].as_u64().map(|m| (m as usize).min(max_new)).unwrap_or(max_new);+ println!(" prompt: {} chars, thinking {}", prompt.len(), if think { "on" } else { "off" });+ write!(+ s,+ "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nTransfer-Encoding: chunked\r\nCache-Control: no-cache\r\nX-Accel-Buffering: no\r\n\r\n"+ )?;+ s.flush()?;+ let mut out_s = s.try_clone()?;+ let mut emit = |t: &str| chunk(&mut out_s, t.as_bytes());+ let mut prog_s = s.try_clone()?;+ let progress: Progress = Box::new(move |step| {+ let line = match step {+ Step::Layer(layer, of) => format!("{PROG_MARK}{{\"layer\":{layer},\"of\":{of}}}\n"),+ Step::Summary(words) => format!("{PROG_MARK}{{\"summary\":{words}}}\n"),+ };+ let _ = chunk(&mut prog_s, line.as_bytes());+ });+ let a = match generate(model, tokenizer, device, session, new_chat, prompt, think, max_new, sampling, Some(progress), &mut emit) {+ Ok(a) => a,+ Err(e) => {+ // A broken answer leaves the model part-way through it, so the next question starts afresh.+ *session = Session::default();+ let oom = gpu_out_of_memory(&e);+ let msg = if oom {+ "The GPU ran out of memory. Coachwhip has stopped: close some apps, or start it again with a smaller --bank.".to_string()+ } else {+ format!("The answer could not be finished: {e}")+ };+ let _ = chunk(&mut s, format!("{ERROR_MARK}{msg}").as_bytes());+ let _ = s.write_all(b"0\r\n\r\n");+ let _ = s.flush();+ if oom {+ eprintln!("\n coachwhip: {msg}\n");+ std::process::exit(1);+ }+ return Err(e);+ }+ };+ println!(" read {} new tokens at {:.1} tok/s, wrote {} at {:.1} tok/s, chat now {} tokens", a.prompt_tokens, a.read_tps, a.written, a.write_tps, a.context);+ model.report();+ let stats = serde_json::json!({+ "prompt_tokens": a.prompt_tokens, "written": a.written, "context": a.context, "fresh": a.fresh, "compacted": a.compacted,+ "read_tps": a.read_tps, "write_tps": a.write_tps,+ });+ chunk(&mut s, format!("{STATS_MARK}{stats}").as_bytes())?;+ s.write_all(b"0\r\n\r\n")?;+ } else {+ let page = if model.thinks() { PAGE.to_string() } else { PAGE.replace(THINK_BOX, "") };+ let page = page.replace("MODEL_NAME", &html_escape(model_name));+ write!(s, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\n\r\n", page.len())?;+ s.write_all(page.as_bytes())?;+ }+ s.flush()?;+ Ok(())+}++/// The page's thinking switch, left out for a model that has no thinking mode.+pub(crate) const THINK_BOX: &str = r#"<label><input type="checkbox" id="think"> let it think first (slower)</label>"#;++pub(crate) const PAGE: &str = r##"<!doctype html>+<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Coachwhip</title><style>+ :root{--bg:#0d1117;--panel:#161b22;--line:#30363d;--text:#e6edf3;--dim:#8b949e;--on:#3fb950;--off:#6e7681}+ *{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--text);+ font:15px/1.55 ui-monospace,"Cascadia Code",Consolas,monospace}+ .wrap{max-width:900px;margin:0 auto;padding:28px 16px 60px}+ h1{font-size:22px;margin:0 0 4px} h1 b{color:var(--on)}+ .sub{color:var(--dim);font-size:13px;margin-bottom:22px}+ textarea{width:100%;height:160px;background:var(--panel);color:var(--text);border:1px solid var(--line);+ border-radius:8px;padding:14px;font:14px/1.5 ui-monospace,Consolas,monospace;resize:vertical}+ .row{display:flex;gap:14px;align-items:center;flex-wrap:wrap;margin:12px 0 22px}+ button{background:var(--on);color:#08130b;border:0;border-radius:7px;padding:10px 22px;font-weight:700;+ font-size:14px;cursor:pointer} button:disabled{background:var(--off);color:#0d1117;cursor:default}+ label{color:var(--dim);font-size:13px;display:flex;gap:7px;align-items:center;cursor:pointer}+ .card{background:var(--panel);border:1px solid var(--line);border-radius:8px;overflow:hidden}+ .card h2{margin:0;padding:11px 15px;font-size:12px;letter-spacing:.09em;text-transform:uppercase;+ border-bottom:1px solid var(--line);color:var(--on)}+ pre{margin:0;padding:15px;white-space:pre-wrap;word-break:break-word;min-height:40px;font-size:14px}+ .you{color:var(--dim);white-space:pre-wrap;word-break:break-word;margin:18px 0 8px;font-size:14px}+ .you b{color:var(--on)} #log .card{margin-bottom:6px} button.ghost{background:transparent;color:var(--dim);border:1px solid var(--line)}+ .ms{color:var(--dim);font-size:13px;padding:0 15px 12px} .ms b{color:var(--text)}+</style></head><body><div class="wrap">+ <h1>coachwhip <b>·</b> MODEL_NAME</h1>+ <div class="sub">the experts stream from the SSD; everything runs on this machine</div>+ <div id="log"></div>+ <textarea id="p" spellcheck="false">Write a JavaScript function debounce(fn, ms) and explain in two sentences how it works.</textarea>+ <div class="row">+ <button id="go">Send</button>+ <button id="new" class="ghost">New chat</button>+ <label><input type="checkbox" id="think"> let it think first (slower)</label>+ </div>+</div><script>+const $=i=>document.getElementById(i);+const MARK = '\u0001STATS:';+const ERR = '\u0001ERROR:';+const PROG = /\u0001PROG:(\{[^\n]*\})\n/g;+let newChat = true;+const add = (tag, cls, html) => { const e = document.createElement(tag); if (cls) e.className = cls; e.innerHTML = html; $('log').appendChild(e); return e; };+$('new').onclick = () => { newChat = true; $('log').innerHTML = ''; $('p').focus(); };+$('go').onclick = async () => {+ const prompt = $('p').value.trim();+ if (!prompt) return;+ $('go').disabled = true; $('new').disabled = true;+ add('div', 'you', '<b>you ›</b> ').appendChild(document.createTextNode(prompt));+ const card = add('div', 'card', '<pre></pre><div class="ms"></div>');+ const A = card.querySelector('pre'), T = card.querySelector('.ms');+ T.textContent = 'reading…'; $('p').value = '';+ const t0 = performance.now();+ let text = '', first = 0;+ try{+ const r = await fetch('/ask',{method:'POST',headers:{'content-type':'application/json'},+ body:JSON.stringify({prompt, new_chat:newChat, think:!!($('think')&&$('think').checked)})});+ newChat = false;+ const reader = r.body.getReader(), dec = new TextDecoder();+ while (true) {+ const {value, done} = await reader.read();+ if (done) break;+ text += dec.decode(value, {stream:true});+ let p = null;+ text = text.replace(PROG, (m, j) => { p = JSON.parse(j); return ''; });+ const x = text.indexOf(ERR);+ if (x >= 0) { A.textContent = text.slice(0, x); T.textContent = text.slice(x + ERR.length); newChat = true; break; }+ if (p && !first) {+ const secs = ((performance.now()-t0)/1000).toFixed(1) + ' s';+ T.textContent = p.summary !== undefined+ ? 'making room: summarising the chat so far · ' + p.summary + ' tokens · ' + secs+ : 'reading your prompt · layer ' + p.layer + ' of ' + p.of + ' · ' + secs;+ continue;+ }+ if (!text) continue;+ if (!first) { first = performance.now(); T.textContent = 'writing…'; }+ const k = text.indexOf(MARK);+ A.textContent = k < 0 ? text : text.slice(0, k);+ }+ const k = text.indexOf(MARK);+ if (k >= 0 && text.indexOf(ERR) < 0) {+ const j = JSON.parse(text.slice(k + MARK.length));+ T.innerHTML = 'writing <b>' + j.write_tps.toFixed(1) + ' tok/s</b> (' + j.written + ' tokens) · read <b>' ++ j.prompt_tokens + ' new tokens</b> at ' + j.read_tps.toFixed(1) + ' tok/s · first word after <b>' ++ ((first - t0)/1000).toFixed(1) + ' s</b> · chat so far ' + j.context + ' tokens' ++ (j.compacted ? ' · the chat was summarised to make room' : '');+ }+ }catch(e){ A.textContent = 'failed: ' + e; newChat = true; }+ $('go').disabled = false; $('new').disabled = false;+ card.scrollIntoView({block:'end'});+};+</script></body></html>"##;diff --git a/src/experts.rs b/src/experts.rsnew file mode 100644index 0000000..c3aed55--- /dev/null+++ b/src/experts.rs@@ -0,0 +1,811 @@+//! The expert store: run a mixture-of-experts model whose experts do not fit in memory.+//!+//! Apple silicon has one memory for the CPU and the GPU. Every expert is a slice of bytes inside+//! the GGUF file, and the OS page cache is the shelf. Each layer owns a bank: for gate, up and+//! down one shared Metal buffer holding `bank` expert slots side by side, allocated once and+//! overwritten in place, so a load is one read from the file straight into the memory the GPU+//! uses. A layer's maths is three dispatches of ggml's `mul_mv_id` kernel (every selected expert+//! of every token at once) plus the activation and the weighted sum.+//!+//! While the GPU works on one layer, reader threads fetch the experts the next layer will+//! probably need, predicted from a table of routes the model took before (the hot path). The+//! table keeps learning: every answer's routes are added to it at once and saved, so the+//! predictions follow what this machine is actually asked.++use candle::quantized::metal::QMetalStorage;+use candle::quantized::{ggml_file::qtensor_from_ggml, gguf_file, GgmlDType, QMatMul, QTensor};+use candle::{CustomOp2, DType, Device, Layout, MetalDevice, MetalStorage, Module, Result, Shape, Tensor, D};+use candle::backend::BackendStorage;+use candle_nn::Linear;+use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};+use std::os::unix::fs::FileExt;+use rayon::prelude::*;+use std::path::Path;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{mpsc, Arc, Mutex, Weak};+use std::time::Instant;++/// Where one matrix of one expert lives in the file.+#[derive(Clone)]+struct Slice {+ dtype: GgmlDType,+ offset: u64,+ bytes: usize,+ dims: Vec<usize>,+}++/// One matrix of a layer's bank: `per_layer` expert slots in one shared buffer.+struct BankMat {+ storage: Arc<QMetalStorage>,+ base: usize,+ bytes: usize,+ dtype: GgmlDType,+ n: usize,+ k: usize,+}++struct Bank {+ mats: [BankMat; 3],+ holder: Vec<Option<u32>>,+ slot_of: HashMap<u32, usize>,+ lru: VecDeque<usize>,+ /// False while the prefetch thread is still reading an expert into the slot.+ ready: Vec<Arc<AtomicBool>>,+ /// Experts the prefetch thread brought in that no token has asked for yet.+ prefetched: HashSet<u32>,+}++type Key = (usize, u32);++/// How the store behaves. `Default` is what the Mac mini M4 with 16 GB was tuned on.+#[derive(Clone, Debug)]+pub struct Settings {+ /// Expert slots kept per layer (one expert each: about 3 MB for the 30B, 2 MB for the 80B, at Q4_K_M).+ pub bank: usize,+ /// Experts predicted and fetched ahead for the next layer; 0 turns prefetch off.+ pub prefetch: usize,+ /// How many layers ahead to predict.+ pub ahead: usize,+ /// Reader threads that fetch predicted experts.+ pub readers: usize,+ /// Folder of route logs the predictions start from.+ pub routes: Option<std::path::PathBuf>,+ /// Folder where the routes of every answer are saved, and read back at the next start.+ pub learned: Option<std::path::PathBuf>,+ /// Print where each word's time went after every answer.+ pub profile: bool,+}++impl Default for Settings {+ fn default() -> Self {+ Self { bank: 44, prefetch: 2, ahead: 1, readers: 3, routes: None, learned: None, profile: false }+ }+}++/// Route table: for each (layer, expert), how often each expert of the next layer followed it.+pub(crate) type Counts = HashMap<Key, HashMap<u32, u64>>;++/// Adds one layer-to-layer step to the table: every expert picked now, for every expert picked+/// in the layer before, token by token.+pub(crate) fn count_step(counts: &mut Counts, layer: usize, before: &[Vec<u32>], now: &[Vec<u32>]) {+ for (a_row, b_row) in before.iter().zip(now.iter()) {+ // Nothing followed (a broken log line): leave no empty row behind to look like knowledge.+ if b_row.is_empty() {+ continue;+ }+ for &a in a_row {+ let row = counts.entry((layer, a)).or_default();+ for &b in b_row {+ *row.entry(b).or_insert(0) += 1;+ }+ }+ }+}++/// Reads route logs from folders. A log is a "T ..." line followed by one line per layer:+/// comma-separated tokens, each the space-separated experts the router picked for it.+pub(crate) fn load_routes(dirs: &[&Path], layers: usize) -> Counts {+ let mut counts = Counts::new();+ for dir in dirs {+ let Ok(entries) = std::fs::read_dir(dir) else { continue };+ read_logs(&mut counts, entries, layers);+ }+ counts+}++fn read_logs(counts: &mut Counts, entries: std::fs::ReadDir, layers: usize) {+ for entry in entries.flatten() {+ if entry.path().extension().and_then(|x| x.to_str()) != Some("log") {+ continue;+ }+ let Ok(text) = std::fs::read_to_string(entry.path()) else { continue };+ let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();+ let mut i = 0;+ while i + layers < lines.len() {+ if !lines[i].starts_with("T ") {+ i += 1;+ continue;+ }+ let per_layer: Vec<Vec<Vec<u32>>> = (0..layers)+ .map(|l| lines[i + 1 + l].split(',').map(|t| t.split_whitespace().filter_map(|e| e.parse().ok()).collect()).collect())+ .collect();+ for l in 0..layers - 1 {+ count_step(counts, l, &per_layer[l], &per_layer[l + 1]);+ }+ i += 1 + layers;+ }+ }+}++/// What the current forward pass has picked so far, for learning and for the log.+#[derive(Default)]+struct Trail {+ /// The layer before, and the experts each token picked there.+ before: Option<(usize, Vec<Vec<u32>>)>,+ /// One line per layer of the forward pass in progress.+ lines: Vec<String>,+ /// Finished forward passes, waiting to be saved.+ blocks: Vec<String>,+}++#[derive(Default)]+struct Stats {+ hits: u64,+ loads: u64,+ load_seconds: f64,+ bytes_loaded: u64,+ fresh: u64,+ fresh_read_seconds: f64,+ fresh_build_seconds: f64,+ prefetch_copies: u64,+ prefetch_hits: u64,+ words: u64,+ word_started: Option<Instant>,+ word_seconds: f64,+ expert_seconds: f64,+ load_phase_seconds: f64,+ maths_seconds: f64,+}++static PROFILE: AtomicBool = AtomicBool::new(false);++fn profiling() -> bool {+ PROFILE.load(Ordering::Relaxed)+}++pub struct ExpertStore {+ file: std::fs::File,+ device: Device,+ metal: MetalDevice,+ per_layer: usize,+ ahead: usize,+ slices: Vec<Vec<[Slice; 3]>>,+ banks: Mutex<HashMap<usize, Bank>>,+ stats: Mutex<Stats>,+ layers: usize,+ routes: Mutex<Counts>,+ trail: Mutex<Trail>,+ learned: Option<std::path::PathBuf>,+ learned_file: String,+ prefetch_tx: Mutex<Option<mpsc::Sender<(usize, Vec<u32>)>>>,+}++impl ExpertStore {+ /// Reads the file's table of contents only; experts are read when a token first asks for them.+ pub fn new(ct: &gguf_file::Content, device: &Device, layers: usize, path: &Path, settings: &Settings) -> Result<Arc<Self>> {+ let Device::Metal(metal) = device else {+ candle::bail!("Coachwhip needs a Metal device (Apple silicon)")+ };+ PROFILE.store(settings.profile, Ordering::Relaxed);+ let per_layer = settings.bank.max(1);++ let mut slices = Vec::with_capacity(layers);+ for layer in 0..layers {+ let parts = ["gate", "up", "down"].map(|m| {+ let info = &ct.tensor_infos[&format!("blk.{layer}.ffn_{m}_exps.weight")];+ let dims = info.shape.dims().to_vec();+ let per_expert_elems: usize = dims[1..].iter().product();+ let bytes = per_expert_elems / info.ggml_dtype.block_size() * info.ggml_dtype.type_size();+ (info.ggml_dtype, ct.tensor_data_offset + info.offset, bytes, dims[1..].to_vec(), dims[0])+ });+ let experts = parts[0].4;+ let per_expert: Vec<[Slice; 3]> = (0..experts)+ .map(|e| {+ parts.clone().map(|(dtype, base, bytes, dims, _)| Slice {+ dtype,+ offset: base + (e * bytes) as u64,+ bytes,+ dims,+ })+ })+ .collect();+ slices.push(per_expert);+ }+ let file = std::fs::File::open(path)?;+ let experts = slices[0].len();+ let per_expert_mb = slices[0][0].iter().map(|s| s.bytes).sum::<usize>() as f64 / 1e6;+ eprintln!(+ "coachwhip: {layers} layers x {experts} experts, {per_expert_mb:.1} MB each; bank {per_layer} slots per layer ({:.2} GB)",+ per_layer as f64 * layers as f64 * per_expert_mb / 1e3+ );+ let dirs: Vec<&Path> = settings.routes.iter().chain(settings.learned.iter()).map(|p| p.as_path()).collect();+ let routes = load_routes(&dirs, layers);+ eprintln!("coachwhip: route table for {} (layer, expert) pairs", routes.len());+ let started = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);+ let store = Arc::new(Self {+ file,+ device: device.clone(),+ metal: metal.clone(),+ per_layer,+ ahead: settings.ahead,+ slices,+ banks: Mutex::new(HashMap::new()),+ stats: Mutex::new(Stats::default()),+ layers,+ routes: Mutex::new(routes),+ trail: Mutex::new(Trail::default()),+ learned: settings.learned.clone(),+ learned_file: format!("{started}.log"),+ prefetch_tx: Mutex::new(None),+ });+ // The prefetch thread reads predicted experts into free slots while the GPU works on the+ // current layer. It holds only a weak handle, so the store still shuts down when the model does.+ let (tx, rx) = mpsc::channel::<(usize, Vec<u32>)>();+ *store.prefetch_tx.lock().unwrap() = Some(tx);+ let rx = Arc::new(Mutex::new(rx));+ for _ in 0..settings.readers {+ let weak: Weak<Self> = Arc::downgrade(&store);+ let rx = rx.clone();+ std::thread::spawn(move || loop {+ let job = rx.lock().unwrap().recv();+ let Ok((layer, experts)) = job else { break };+ let Some(st) = weak.upgrade() else { break };+ if let Err(e) = st.prefetch(layer, &experts) {+ eprintln!("coachwhip: prefetch failed: {e}");+ }+ });+ }+ Ok(store)+ }++ /// Scores for the next layer's experts given this layer's picks, from the route table.+ fn next_scores(&self, layer: usize, now: &[(u32, f32)]) -> Vec<(u32, f32)> {+ let mut score: HashMap<u32, f32> = HashMap::new();+ let routes = self.routes.lock().unwrap();+ for &(a, w) in now {+ if let Some(row) = routes.get(&(layer, a)) {+ let total = row.values().sum::<u64>().max(1) as f32;+ for (&b, &n) in row {+ *score.entry(b).or_insert(0.0) += w * n as f32 / total;+ }+ }+ }+ let mut v: Vec<(u32, f32)> = score.into_iter().collect();+ v.sort_by(|x, y| y.1.partial_cmp(&x.1).unwrap());+ v+ }++ /// The `k` likeliest experts of `layer` that are not in its bank yet, one layer ahead of `now`+ /// (`ahead` = 1) or two (`ahead` = 2, composing the table twice).+ fn predict_missing(&self, layer: usize, now: &[u32], ahead: usize, k: usize) -> Vec<u32> {+ let mut scores: Vec<(u32, f32)> = now.iter().map(|&e| (e, 1.0)).collect();+ for step in 0..ahead {+ scores = self.next_scores(layer + step, &scores);+ scores.truncate(32);+ }+ let banks = self.banks.lock().unwrap();+ let present = banks.get(&(layer + ahead));+ scores+ .into_iter()+ .map(|(e, _)| e)+ .filter(|e| present.map_or(true, |b| !b.slot_of.contains_key(e)))+ .take(k)+ .collect()+ }++ /// Hand the next layer's predicted experts to the prefetch thread.+ fn request_prefetch(&self, layer: usize, predicted: Vec<u32>) {+ if predicted.is_empty() {+ return;+ }+ if let Some(tx) = self.prefetch_tx.lock().unwrap().as_ref() {+ let _ = tx.send((layer, predicted));+ }+ }++ /// Prefetch thread: reserve free slots for the predicted experts, then read them in with the+ /// bank unlocked, so the main thread is never held up by a read it did not ask for.+ fn prefetch(&self, layer: usize, predicted: &[u32]) -> Result<()> {+ let mut jobs: Vec<(u32, [(usize, usize); 3], Arc<AtomicBool>)> = Vec::new();+ {+ let mut banks = self.banks.lock().unwrap();+ let Some(bank) = banks.get_mut(&layer) else { return Ok(()) };+ for &e in predicted {+ if bank.slot_of.contains_key(&e) {+ continue;+ }+ let Some(pos) = bank+ .lru+ .iter()+ .position(|&slot| bank.ready[slot].load(Ordering::Acquire) && bank.holder[slot].map_or(true, |h| !predicted.contains(&h)))+ else {+ continue;+ };+ let slot = bank.lru.remove(pos).unwrap();+ if let Some(old) = bank.holder[slot] {+ bank.slot_of.remove(&old);+ bank.prefetched.remove(&old);+ }+ bank.ready[slot].store(false, Ordering::Release);+ bank.holder[slot] = Some(e);+ bank.slot_of.insert(e, slot);+ bank.prefetched.insert(e);+ bank.lru.push_back(slot);+ let ptrs = [0, 1, 2].map(|i| (bank.mats[i].base + slot * bank.mats[i].bytes, bank.mats[i].bytes));+ jobs.push((e, ptrs, bank.ready[slot].clone()));+ }+ }+ for (e, ptrs, ready) in jobs {+ for (i, s) in self.slices[layer][e as usize].iter().enumerate() {+ let dst = unsafe { std::slice::from_raw_parts_mut(ptrs[i].0 as *mut u8, s.bytes) };+ self.file.read_exact_at(dst, s.offset)?;+ }+ ready.store(true, Ordering::Release);+ self.stats.lock().unwrap().prefetch_copies += 1;+ }+ Ok(())+ }++ /// A layer's bank: three shared buffers, each `per_layer` expert slots of one matrix.+ fn make_bank(&self, layer: usize) -> Result<Bank> {+ let mut mats = Vec::with_capacity(3);+ for s in self.slices[layer][0].iter() {+ let elems: usize = s.dims.iter().product();+ let storage = QMetalStorage::zeros(&self.metal, elems * self.per_layer, s.dtype)?;+ let base = storage.buffer().contents() as usize;+ if base == 0 {+ candle::bail!("Metal gave a buffer the CPU cannot write to");+ }+ mats.push(BankMat {+ storage: Arc::new(storage),+ base,+ bytes: s.bytes,+ dtype: s.dtype,+ n: s.dims[0],+ k: s.dims[1],+ });+ }+ let mats: [BankMat; 3] = match mats.try_into() {+ Ok(m) => m,+ Err(_) => candle::bail!("a bank has three matrices"),+ };+ // `zeros` queues a GPU fill; let it run now, or it would wipe the experts written in afterwards.+ self.device.synchronize()?;+ Ok(Bank {+ mats,+ holder: vec![None; self.per_layer],+ slot_of: HashMap::new(),+ lru: (0..self.per_layer).collect(),+ ready: (0..self.per_layer).map(|_| Arc::new(AtomicBool::new(true))).collect(),+ prefetched: HashSet::new(),+ })+ }++ /// Many fresh experts outside the bank, for a forward that needs more experts than a bank+ /// holds (reading a prompt touches most of them). All the reads go to the SSD at once, and+ /// `each` gets every expert the moment its bytes land, so the GPU computes while the rest of+ /// the layer is still being read. `each` is called on this thread, in arrival order.+ fn fresh_stream(&self, layer: usize, experts: &[u32], mut each: impl FnMut(usize, [Arc<QTensor>; 3]) -> Result<()>) -> Result<()> {+ let started = Instant::now();+ let (tx, rx) = std::sync::mpsc::channel::<(usize, Result<[Vec<u8>; 3]>)>();+ let mut build_seconds = 0.0;+ let mut waited = 0.0;+ std::thread::scope(|scope| -> Result<()> {+ scope.spawn(move || {+ experts.par_iter().enumerate().for_each_with(tx, |tx, (j, &e)| {+ let read = |i: usize| -> Result<Vec<u8>> {+ let s = &self.slices[layer][e as usize][i];+ let mut b = vec![0u8; s.bytes];+ self.file.read_exact_at(&mut b, s.offset)?;+ Ok(b)+ };+ let bytes = (|| Ok([read(0)?, read(1)?, read(2)?]))();+ let _ = tx.send((j, bytes));+ });+ });+ for _ in 0..experts.len() {+ let wait = Instant::now();+ let (j, bytes) = rx.recv().map_err(|e| candle::Error::Msg(format!("expert reader stopped: {e}")))?;+ waited += wait.elapsed().as_secs_f64();+ let bytes = bytes?;+ let build = Instant::now();+ let sl = &self.slices[layer][experts[j] as usize];+ let [a, b, c] = [0, 1, 2].map(|i| qtensor_from_ggml(sl[i].dtype, &bytes[i], sl[i].dims.clone(), &self.device).map(Arc::new));+ let mats = [a?, b?, c?];+ build_seconds += build.elapsed().as_secs_f64();+ each(j, mats)?;+ }+ Ok(())+ })?;+ let mut st = self.stats.lock().unwrap();+ st.fresh += experts.len() as u64;+ st.fresh_read_seconds += waited;+ st.fresh_build_seconds += build_seconds;+ st.load_seconds += started.elapsed().as_secs_f64();+ Ok(())+ }++ /// Makes sure every needed expert of one layer sits in the bank; returns expert -> slot.+ /// None when the bank is too small for this forward.+ fn ensure(&self, layer: usize, needed: &[u32]) -> Result<Option<HashMap<u32, usize>>> {+ if needed.len() > self.per_layer {+ return Ok(None);+ }+ let mut banks = self.banks.lock().unwrap();+ if !banks.contains_key(&layer) {+ banks.insert(layer, self.make_bank(layer)?);+ }+ let bank = banks.get_mut(&layer).unwrap();+ // A slot still being filled by a prefetch cannot be taken; if too few are free for this+ // layer's misses, read them fresh instead, before the bank is touched.+ let missing = needed.iter().filter(|e| !bank.slot_of.contains_key(e)).count();+ let free = bank.lru.iter().filter(|&&slot| bank.ready[slot].load(Ordering::Acquire) && bank.holder[slot].map_or(true, |h| !needed.contains(&h))).count();+ if free < missing {+ return Ok(None);+ }+ let mut misses: Vec<(u32, usize)> = Vec::new();+ for &e in needed {+ if let Some(&slot) = bank.slot_of.get(&e) {+ // A prefetch may still be reading this one in; wait for it rather than read it twice.+ while !bank.ready[slot].load(Ordering::Acquire) {+ std::thread::yield_now();+ }+ bank.lru.retain(|&x| x != slot);+ bank.lru.push_back(slot);+ let mut st = self.stats.lock().unwrap();+ st.hits += 1;+ if bank.prefetched.remove(&e) {+ st.prefetch_hits += 1;+ }+ continue;+ }+ let pos = bank+ .lru+ .iter()+ .position(|&slot| bank.ready[slot].load(Ordering::Acquire) && bank.holder[slot].map_or(true, |h| !needed.contains(&h)))+ .expect("a bank always has a slot that this forward does not need");+ let slot = bank.lru.remove(pos).unwrap();+ if let Some(old) = bank.holder[slot] {+ bank.slot_of.remove(&old);+ bank.prefetched.remove(&old);+ }+ bank.holder[slot] = Some(e);+ bank.slot_of.insert(e, slot);+ bank.lru.push_back(slot);+ misses.push((e, slot));+ }+ if !misses.is_empty() {+ // All of this layer's misses go to the SSD at once: it serves several requests in+ // parallel far faster than one after another. Each matrix of each expert is one read.+ let places: [(usize, usize); 3] = [0, 1, 2].map(|i| (bank.mats[i].base, bank.mats[i].bytes));+ let reads: Vec<(usize, usize, u64)> = misses+ .iter()+ .flat_map(|&(e, slot)| {+ self.slices[layer][e as usize]+ .iter()+ .enumerate()+ .map(move |(i, s)| (places[i].0 + slot * places[i].1, s.bytes, s.offset))+ .collect::<Vec<_>>()+ })+ .collect();+ let started = Instant::now();+ reads.par_iter().try_for_each(|&(dst, len, offset)| {+ // Each read fills its own slot of a shared buffer that no GPU work in flight uses.+ let dst = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, len) };+ self.file.read_exact_at(dst, offset)+ })?;+ let mut st = self.stats.lock().unwrap();+ st.loads += misses.len() as u64;+ st.bytes_loaded += reads.iter().map(|r| r.1 as u64).sum::<u64>();+ st.load_seconds += started.elapsed().as_secs_f64();+ }+ Ok(Some(bank.slot_of.clone()))+ }++ /// One `mul_mv_id` dispatch over a bank matrix.+ fn bank_op(&self, layer: usize, which: usize, nei0: usize, rows_per_expert: bool) -> MoeMatvec {+ let banks = self.banks.lock().unwrap();+ let m = &banks[&layer].mats[which];+ MoeMatvec {+ bank: m.storage.clone(),+ dtype: m.dtype,+ n: m.n,+ k: m.k,+ slots: self.per_layer,+ bytes: m.bytes,+ nei0,+ rows_per_expert,+ }+ }++ /// Learn from one layer's picks: add the step from the layer before to the route table at once,+ /// and keep the line for the log.+ fn learn(&self, layer: usize, ids: &[Vec<u32>]) {+ let mut trail = self.trail.lock().unwrap();+ if layer == 0 {+ trail.lines.clear();+ } else if let Some((before_layer, before)) = trail.before.take() {+ if before_layer + 1 == layer && before.len() == ids.len() {+ count_step(&mut self.routes.lock().unwrap(), before_layer, &before, ids);+ }+ }+ let line = ids.iter().map(|t| t.iter().map(|e| e.to_string()).collect::<Vec<_>>().join(" ")).collect::<Vec<_>>().join(",");+ trail.lines.push(line);+ if layer + 1 == self.layers {+ let block = format!("T -\n{}\n", trail.lines.join("\n"));+ trail.blocks.push(block);+ trail.lines.clear();+ } else {+ trail.before = Some((layer, ids.to_vec()));+ }+ }++ /// Append the routes learned since the last save to this session's log file.+ fn save_learned(&self) {+ let Some(dir) = &self.learned else { return };+ let blocks: Vec<String> = std::mem::take(&mut self.trail.lock().unwrap().blocks);+ if blocks.is_empty() {+ return;+ }+ let saved = std::fs::create_dir_all(dir).and_then(|_| {+ use std::io::Write;+ let mut f = std::fs::OpenOptions::new().create(true).append(true).open(dir.join(&self.learned_file))?;+ f.write_all(blocks.concat().as_bytes())+ });+ if let Err(e) = saved {+ eprintln!("coachwhip: could not save learned routes: {e}");+ }+ }++ /// Print the profile so far, save what was learned, and start counting afresh; the chat calls+ /// this after each answer.+ pub fn report_and_reset(&self) {+ self.print_report();+ self.save_learned();+ *self.stats.lock().unwrap() = Stats::default();+ }++ fn print_report(&self) {+ let s = self.stats.lock().unwrap();+ if s.hits + s.loads == 0 {+ return;+ }+ let requests = (s.hits + s.loads).max(1) as f64;+ eprintln!(+ "coachwhip: {} expert requests: bank {:.1}%, file {:.1}% ({} outside the bank); {:.2} GB read; {:.2} s loading; {:.2} ms per load; prefetched {} of which used {}",+ requests as u64,+ 100.0 * s.hits as f64 / requests,+ 100.0 * s.loads as f64 / requests,+ s.fresh,+ s.bytes_loaded as f64 / 1e9,+ s.load_seconds,+ 1000.0 * s.load_seconds / s.loads.max(1) as f64,+ s.prefetch_copies,+ s.prefetch_hits+ );+ if s.fresh > 0 {+ eprintln!(+ "coachwhip: prompt experts: {} read outside the bank, {:.2} s reading, {:.2} s copying to the GPU",+ s.fresh, s.fresh_read_seconds, s.fresh_build_seconds+ );+ }+ if profiling() && s.words > 2 {+ let words = (s.words - 1) as f64;+ eprintln!(+ "coachwhip profile: {} written words after the first, {:.1} ms per word in total, {:.1} ms in the expert layers: router+loads {:.1} (of which file reads {:.1}), expert maths {:.1}",+ s.words - 1,+ 1000.0 * s.word_seconds / words,+ 1000.0 * s.expert_seconds / words,+ 1000.0 * s.load_phase_seconds / words,+ 1000.0 * s.load_seconds / words,+ 1000.0 * s.maths_seconds / words+ );+ }+ }+}++impl Drop for ExpertStore {+ fn drop(&mut self) {+ self.print_report();+ self.save_learned();+ }+}++/// `x (rows, k) , ids (tokens, nei0)` -> `(tokens, nei0, n)`: for each token and each of its+/// selected slots, one row of x times that slot's quantised matrix from the bank.+/// With `rows_per_expert`, x has one row per (token, slot) instead of one per token.+struct MoeMatvec {+ bank: Arc<QMetalStorage>,+ dtype: GgmlDType,+ n: usize,+ k: usize,+ slots: usize,+ bytes: usize,+ nei0: usize,+ rows_per_expert: bool,+}++impl CustomOp2 for MoeMatvec {+ fn name(&self) -> &'static str {+ "coachwhip-moe-matvec"+ }++ fn cpu_fwd(&self, _: &candle::CpuStorage, _: &Layout, _: &candle::CpuStorage, _: &Layout) -> Result<(candle::CpuStorage, Shape)> {+ candle::bail!("coachwhip-moe-matvec runs on Metal only")+ }++ fn metal_fwd(&self, x: &MetalStorage, xl: &Layout, ids: &MetalStorage, il: &Layout) -> Result<(MetalStorage, Shape)> {+ if !xl.is_contiguous() || !il.is_contiguous() {+ candle::bail!("coachwhip-moe-matvec needs contiguous inputs")+ }+ if x.dtype() != DType::F32 || ids.dtype() != DType::U32 {+ candle::bail!("coachwhip-moe-matvec: x must be f32 and ids u32")+ }+ let (tokens, nei0) = il.shape().dims2()?;+ if nei0 != self.nei0 {+ candle::bail!("coachwhip-moe-matvec: {} ids per token, expected {}", nei0, self.nei0)+ }+ let (rows, k) = xl.shape().dims2()?;+ if k != self.k || rows != if self.rows_per_expert { tokens * nei0 } else { tokens } {+ candle::bail!("coachwhip-moe-matvec: x is {rows}x{k}, expected k={} for {tokens} tokens", self.k)+ }+ let (ne11, nb11, nb12) = if self.rows_per_expert { (nei0, k * 4, nei0 * k * 4) } else { (1, 0, k * 4) };+ let device = x.device().clone();+ let elems = tokens * nei0 * self.n;+ let dst = device.new_buffer_builder().with_size_for(elems, DType::F32).with_label("moe_mv_id").build()?;+ {+ let encoder = device.command_encoder()?;+ crate::mv_id::matvec_id(+ device.device(),+ &encoder,+ device.kernels(),+ self.dtype.into(),+ (self.n, self.k, self.slots, self.bytes),+ self.bank.buffer(),+ x.buffer(),+ xl.start_offset() * 4,+ (ne11, nb11, nb12),+ ids.buffer(),+ il.start_offset() * 4,+ (nei0, tokens),+ &dst,+ )+ .map_err(candle::MetalError::from)?;+ }+ Ok((MetalStorage::new(dst, device.clone(), elems, DType::F32), Shape::from((tokens, nei0, self.n))))+ }+}++/// A MoE layer whose experts live in the ExpertStore instead of on the device.+pub struct StreamedMoe {+ pub layer: usize,+ pub gate: Linear,+ pub store: Arc<ExpertStore>,+ pub top_k: usize,+ pub norm_topk_prob: bool,+ pub prefetch_k: usize,+}++impl StreamedMoe {+ /// The plain path: one quantised matmul per expert, experts read fresh from the file.+ fn reference(&self, xs: &Tensor, ids: &[Vec<u32>], top_w: &Tensor) -> Result<Tensor> {+ let device = xs.device();+ let weights: Vec<Vec<f32>> = top_w.to_vec2()?;+ let mut tokens_per_expert: BTreeMap<u32, (Vec<u32>, Vec<f32>)> = BTreeMap::new();+ for (t, (row_ids, row_w)) in ids.iter().zip(weights.iter()).enumerate() {+ for (e, w) in row_ids.iter().zip(row_w.iter()) {+ let entry = tokens_per_expert.entry(*e).or_default();+ entry.0.push(t as u32);+ entry.1.push(*w);+ }+ }+ let experts: Vec<u32> = tokens_per_expert.keys().copied().collect();+ let work: Vec<(Vec<u32>, Vec<f32>)> = tokens_per_expert.into_values().collect();+ // Each expert's result is kept and summed in expert order at the end, so the answer does+ // not depend on the order the reads happened to land in.+ let mut parts: Vec<Option<(Tensor, Tensor)>> = (0..experts.len()).map(|_| None).collect();+ self.store.fresh_stream(self.layer, &experts, |j, [g, u, d]| {+ let (tokens, w) = &work[j];+ let (gate, up, down) = (QMatMul::from_arc(g)?, QMatMul::from_arc(u)?, QMatMul::from_arc(d)?);+ let idx = Tensor::new(tokens.as_slice(), device)?;+ let x = xs.index_select(&idx, 0)?;+ let hidden = (candle_nn::ops::silu(&gate.forward(&x)?)? * up.forward(&x)?)?;+ let y = down.forward(&hidden)?;+ let w = Tensor::new(w.as_slice(), device)?.unsqueeze(1)?;+ parts[j] = Some((idx, y.broadcast_mul(&w)?));+ Ok(())+ })?;+ // One add for the whole layer: adding expert by expert would build a full copy of the+ // output for every expert, a gigabyte of short-lived GPU memory on a long prompt.+ let (idx, ys): (Vec<Tensor>, Vec<Tensor>) = parts.into_iter().flatten().unzip();+ if idx.is_empty() {+ return xs.zeros_like();+ }+ xs.zeros_like()?.index_add(&Tensor::cat(&idx, 0)?, &Tensor::cat(&ys, 0)?, 0)+ }++ pub fn forward(&self, xs: &Tensor) -> Result<Tensor> {+ let (b, s, h) = xs.dims3()?;+ let prof = profiling() && b * s == 1;+ if prof && self.layer == 0 {+ self.store.device.synchronize()?;+ let mut st = self.store.stats.lock().unwrap();+ if let Some(t) = st.word_started {+ if st.words >= 2 {+ st.word_seconds += t.elapsed().as_secs_f64();+ }+ }+ st.word_started = Some(Instant::now());+ st.words += 1;+ }+ let started = Instant::now();+ let dtype = xs.dtype();+ let n = b * s;+ let xs = xs.reshape((n, h))?.to_dtype(DType::F32)?.contiguous()?;++ let probs = candle_nn::ops::softmax_last_dim(&self.gate.forward(&xs)?)?;+ let top_ids = probs.arg_sort_last_dim(false)?.narrow(D::Minus1, 0, self.top_k)?.contiguous()?;+ let mut top_w = probs.gather(&top_ids, D::Minus1)?;+ if self.norm_topk_prob {+ top_w = top_w.broadcast_div(&top_w.sum_keepdim(D::Minus1)?)?;+ }+ // Reading the picks back waits for the GPU to finish everything queued so far, so no+ // kernel is still reading a bank slot when `ensure` and the prefetchers overwrite it.+ // Keep this wait if this code ever changes.+ let ids: Vec<Vec<u32>> = top_ids.to_vec2()?;+ self.store.learn(self.layer, &ids);+ let mut needed: Vec<u32> = ids.iter().flatten().copied().collect();+ needed.sort_unstable();+ needed.dedup();+ let slot_of = self.store.ensure(self.layer, &needed)?;+ if n == 1 && self.prefetch_k > 0 {+ for ahead in 1..=self.store.ahead {+ if self.layer + ahead < self.store.slices.len() {+ let predicted = self.store.predict_missing(self.layer, &needed, ahead, self.prefetch_k);+ self.store.request_prefetch(self.layer + ahead, predicted);+ }+ }+ }+ if prof {+ self.store.device.synchronize()?;+ let mut st = self.store.stats.lock().unwrap();+ if st.words > 1 {+ st.load_phase_seconds += started.elapsed().as_secs_f64();+ }+ }+ let maths_started = Instant::now();+ let device = xs.device();++ let out = if let Some(slot_of) = slot_of {+ let slots: Vec<u32> = ids.iter().flatten().map(|e| slot_of[e] as u32).collect();+ let slots = Tensor::from_vec(slots, (n, self.top_k), device)?;+ let gate = xs.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 0, self.top_k, false))?; // (n, k, inter)+ let up = xs.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 1, self.top_k, false))?;+ let inter = gate.dim(2)?;+ let hidden = (candle_nn::ops::silu(&gate)? * &up)?.reshape((n * self.top_k, inter))?;+ let down = hidden.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 2, self.top_k, true))?; // (n, k, h)+ down.broadcast_mul(&top_w.unsqueeze(2)?)?.sum(1)?+ } else {+ self.reference(&xs, &ids, &top_w)?+ };+ if prof {+ self.store.device.synchronize()?;+ let mut st = self.store.stats.lock().unwrap();+ if st.words > 1 {+ st.expert_seconds += started.elapsed().as_secs_f64();+ st.maths_seconds += maths_started.elapsed().as_secs_f64();+ }+ }+ out.reshape((b, s, h))?.to_dtype(dtype)+ }+}diff --git a/src/main.rs b/src/main.rsnew file mode 100644index 0000000..475e720--- /dev/null+++ b/src/main.rs@@ -0,0 +1,130 @@+//! Coachwhip: run mixture-of-experts models that are bigger than the memory, on a Mac. An 80B+//! model runs on 16 GB: the experts stream from the SSD into a small bank on the GPU, and the+//! ones the next layer will probably need are fetched while the current layer computes.++mod chat;+mod experts;+mod model;+mod model_next;+mod mv_id;+#[cfg(test)]+mod tests;++use anyhow::Result;+use candle::Device;+use candle_transformers::generation::Sampling;+use clap::Parser;+use std::io::Write;+use std::path::PathBuf;+use tokenizers::Tokenizer;++#[derive(Parser, Debug)]+#[command(version, about = "Run mixture-of-experts models bigger than your memory on a Mac: an 80B model on 16 GB")]+struct Args {+ /// The model, as a GGUF file: Qwen3 MoE or Qwen3-Next (Q4_K_M tested).+ #[arg(long)]+ model: PathBuf,++ /// The model's tokenizer.json.+ #[arg(long)]+ tokenizer: PathBuf,++ /// Serve the chat page on 127.0.0.1 at this port.+ #[arg(long, conflicts_with = "prompt")]+ chat: Option<u16>,++ /// Answer one prompt and exit.+ #[arg(long)]+ prompt: Option<String>,++ /// Let the model think before it answers (slower).+ #[arg(long)]+ think: bool,++ /// Longest answer, in tokens.+ #[arg(long, default_value_t = 4000)]+ max_tokens: usize,++ /// Sampling temperature; 0 always picks the likeliest token.+ #[arg(long, default_value_t = 0.7)]+ temperature: f64,++ /// Nucleus sampling: keep the likeliest tokens up to this probability mass.+ #[arg(long, default_value_t = 0.8)]+ top_p: f64,++ /// Expert slots kept on the GPU per layer.+ #[arg(long, default_value_t = 44)]+ bank: usize,++ /// Experts fetched ahead for the next layer; 0 turns prefetch off.+ #[arg(long, default_value_t = 2)]+ prefetch: usize,++ /// Reader threads for the prefetch.+ #[arg(long, default_value_t = 3)]+ readers: usize,++ /// Folder of starting route logs, one sub-folder per model, named after the model file.+ #[arg(long, default_value = "data/routes")]+ routes: PathBuf,++ /// Folder where the routes of every answer are saved, one sub-folder per model, named after+ /// the model file, so each model's hot path keeps learning on its own.+ #[arg(long, default_value = "learned")]+ learned: PathBuf,++ /// Print where each word's time went after every answer.+ #[arg(long)]+ profile: bool,+}++fn main() -> Result<()> {+ let args = Args::parse();+ let device = Device::new_metal(0)?;+ // A hot path belongs to one model: its routes live in a folder named after the model file.+ let model_name = args.model.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "model".into());+ let routes = args.routes.join(&model_name);+ let learned = args.learned.join(&model_name);+ std::fs::create_dir_all(&learned)?;+ let settings = experts::Settings {+ bank: args.bank,+ prefetch: args.prefetch,+ ahead: 1,+ readers: args.readers,+ routes: routes.is_dir().then_some(routes),+ learned: Some(learned.clone()),+ profile: args.profile,+ };+ eprintln!("coachwhip: hot path for {model_name} learns in {}", learned.display());++ let started = std::time::Instant::now();+ let mut model = model::Model::load(&args.model, &device, &settings)?;+ eprintln!("coachwhip: model ready in {:.1} s", started.elapsed().as_secs_f64());+ let tokenizer = Tokenizer::from_file(&args.tokenizer).map_err(anyhow::Error::msg)?;+ let sampling = if args.temperature <= 0.0 {+ Sampling::ArgMax+ } else {+ Sampling::TopP { p: args.top_p, temperature: args.temperature }+ };++ if let Some(port) = args.chat {+ return chat::serve(port, &mut model, &model_name, tokenizer, &device, args.max_tokens, sampling);+ }+ let Some(prompt) = args.prompt else {+ anyhow::bail!("give --chat <port> or --prompt <text>")+ };+ let mut out = std::io::stdout();+ let mut emit = |t: &str| -> Result<()> {+ out.write_all(t.as_bytes())?;+ out.flush()?;+ Ok(())+ };+ let a = chat::generate(&mut model, &tokenizer, &device, &mut chat::Session::default(), true, &prompt, args.think, args.max_tokens, &sampling, None, &mut emit)?;+ eprintln!(+ "\n\ncoachwhip: read {} tokens at {:.1} tok/s, wrote {} at {:.1} tok/s",+ a.prompt_tokens, a.read_tps, a.written, a.write_tps+ );+ model.report();+ Ok(())+}diff --git a/src/model.rs b/src/model.rsnew file mode 100644index 0000000..9b68b2e--- /dev/null+++ b/src/model.rs@@ -0,0 +1,274 @@+//! Qwen3 mixture-of-experts, read from a GGUF file. Everything except the experts is loaded onto+//! the GPU at start-up; the experts stay in the file and stream through the ExpertStore.+//!+//! Derived from Candle's `quantized_qwen3_moe.rs` (Apache-2.0 / MIT). Changes: the experts are+//! streamed; the KV cache is one preallocated buffer per layer; grouped-query attention runs+//! without copying K and V per head; the token embedding table lives on the CPU.++use crate::experts::{ExpertStore, Settings, StreamedMoe};+use candle::quantized::gguf_file;+use candle::{DType, Device, Module, Result, Tensor};+use candle_nn::kv_cache::KvCache;+use candle_nn::{Embedding, Linear};+use candle_transformers::models::quantized_qwen3::{Gguf, RotaryEmbedding};+use candle_transformers::models::with_tracing::QMatMul;+use candle_transformers::quantized_nn::RmsNorm;+use std::path::Path;+use std::sync::Arc;++struct Attention {+ wq: QMatMul,+ wk: QMatMul,+ wv: QMatMul,+ wo: QMatMul,+ q_norm: RmsNorm,+ k_norm: RmsNorm,+ n_head: usize,+ n_kv_head: usize,+ head_dim: usize,+ rotary_emb: Arc<RotaryEmbedding>,+ dtype: DType,+ kv_cache: KvCache,+}++impl Attention {+ fn forward(&mut self, x: &Tensor, mask: Option<&Tensor>, input_pos: usize) -> Result<Tensor> {+ let (b, seq_len, _) = x.dims3()?;+ let in_dtype = x.dtype();+ let heads = |t: Tensor, n: usize| -> Result<Tensor> { t.reshape((1, seq_len, n, self.head_dim))?.transpose(1, 2)?.contiguous() };+ let q = heads(self.wq.forward(x)?, self.n_head)?;+ let k = heads(self.wk.forward(x)?, self.n_kv_head)?;+ let v = heads(self.wv.forward(x)?, self.n_kv_head)?;++ // Per-head RMSNorm, as Qwen3 does it.+ let q = self.q_norm.forward(&q.flatten(0, 2)?)?.reshape((1, self.n_head, seq_len, self.head_dim))?;+ let k = self.k_norm.forward(&k.flatten(0, 2)?)?.reshape((1, self.n_kv_head, seq_len, self.head_dim))?;++ let (q, k, v) = (q.to_dtype(self.dtype)?, k.to_dtype(self.dtype)?, v.to_dtype(self.dtype)?);+ let (q, k) = self.rotary_emb.apply(&q, &k, input_pos)?;++ // One preallocated buffer per layer: append writes the new rows in place and hands back+ // views, so nothing is copied per word.+ let (k, v) = self.kv_cache.append(&k, &v)?;+ let s_len = k.dim(2)?;++ // Grouped-query attention without repeating K and V: the G query heads that share one kv+ // head are stacked as G*L rows of one batched matmul.+ let g = self.n_head / self.n_kv_head;+ let q = q.contiguous()?.reshape((1, self.n_kv_head, g * seq_len, self.head_dim))?;+ let scale = 1.0 / (self.head_dim as f64).sqrt();+ let mut scores = (q.matmul(&k.transpose(2, 3)?)? * scale)?; // (1, KVH, G*L, S)+ if let Some(m) = mask {+ let mask = m.to_dtype(scores.dtype())?.unsqueeze(1)?; // (1, 1, 1, L, S)+ scores = scores+ .reshape((1, self.n_kv_head, g, seq_len, s_len))?+ .broadcast_add(&mask)?+ .reshape((1, self.n_kv_head, g * seq_len, s_len))?;+ }+ let probs = candle_nn::ops::softmax_last_dim(&scores)?;+ let ctx = probs.matmul(&v)?.reshape((1, self.n_head, seq_len, self.head_dim))?;+ let ctx = ctx.transpose(1, 2)?.reshape((b, seq_len, self.n_head * self.head_dim))?;+ self.wo.forward(&ctx.to_dtype(in_dtype)?)+ }+}++struct Layer {+ attn: Attention,+ attn_norm: RmsNorm,+ moe: StreamedMoe,+ ffn_norm: RmsNorm,+}++pub struct Qwen3Moe {+ embeddings: Embedding,+ layers: Vec<Layer>,+ norm: RmsNorm,+ output: QMatMul,+ store: Arc<ExpertStore>,+ dtype: DType,+ device: Device,+ /// Whether the model has a thinking mode (Qwen3) or answers straight away (Qwen3-Coder).+ pub thinks: bool,+ pub progress: Option<Progress>,+}++/// Told what the model is doing while the page would otherwise be silent.+pub type Progress = Box<dyn FnMut(Step)>;++pub enum Step {+ /// (layers done, layers in all) while a prompt is being read.+ Layer(usize, usize),+ /// Words written so far of a summary that makes room in a long chat.+ Summary(usize),+}++impl Qwen3Moe {+ pub fn load(path: &Path, device: &Device, dtype: DType, settings: &Settings) -> Result<Self> {+ let mut file = std::fs::File::open(path)?;+ let ct = gguf_file::Content::read(&mut file).map_err(|e| e.with_path(path))?;+ let md = |s: &str| match ct.metadata.get(s) {+ None => candle::bail!("cannot find {s} in the GGUF metadata"),+ Some(v) => Ok(v.clone()),+ };+ let arch = md("general.architecture")?.to_string()?.clone();+ let md_u = |s: &str| -> Result<usize> { Ok(md(&format!("{arch}.{s}"))?.to_u32()? as usize) };+ let head_count = md_u("attention.head_count")?;+ let head_count_kv = md_u("attention.head_count_kv")?;+ let embedding_length = md_u("embedding_length")?;+ let head_dim = md_u("attention.key_length").unwrap_or(embedding_length / head_count);+ let context_length = md_u("context_length")?;+ let block_count = md_u("block_count")?;+ let top_k = md_u("expert_used_count")?;+ let rms_norm_eps = md(&format!("{arch}.attention.layer_norm_rms_epsilon"))?.to_f32()? as f64;+ let rope_freq_base = md(&format!("{arch}.rope.freq_base")).and_then(|m| m.to_f32()).unwrap_or(10000f32);+ let shared = md_u("expert_shared_feed_forward_length").unwrap_or(0);+ let norm_topk_prob = shared == 0;+ // A model with a thinking mode says so in its chat template.+ let thinks = md("tokenizer.chat_template").and_then(|t| t.to_string().cloned()).map_or(false, |t| t.contains("enable_thinking"));++ let store = ExpertStore::new(&ct, device, block_count, path, settings)?;+ let mut gg = Gguf::new(ct, &mut file, device.clone());++ let embeddings = gg.tensor("token_embd.weight")?.dequantize(device)?.to_dtype(DType::F16)?.to_device(&Device::Cpu)?;+ let norm = gg.rms_norm("output_norm.weight", rms_norm_eps)?;+ let output = match gg.qmatmul("output.weight") {+ Ok(v) => v,+ _ => gg.qmatmul("token_embd.weight")?,+ };+ let rotary_emb = Arc::new(RotaryEmbedding::new(dtype, head_dim, context_length, rope_freq_base as f64, device)?);++ let mut layers = Vec::with_capacity(block_count);+ for layer in 0..block_count {+ let p = format!("blk.{layer}");+ let gate = gg.tensor(&format!("{p}.ffn_gate_inp.weight"))?.dequantize(device)?.to_dtype(DType::F32)?;+ let moe = StreamedMoe {+ layer,+ gate: Linear::new(gate, None),+ store: store.clone(),+ top_k,+ norm_topk_prob,+ prefetch_k: settings.prefetch,+ };+ let attn = Attention {+ wq: gg.qmatmul(&format!("{p}.attn_q.weight"))?,+ wk: gg.qmatmul(&format!("{p}.attn_k.weight"))?,+ wv: gg.qmatmul(&format!("{p}.attn_v.weight"))?,+ wo: gg.qmatmul(&format!("{p}.attn_output.weight"))?,+ q_norm: gg.rms_norm(&format!("{p}.attn_q_norm.weight"), rms_norm_eps)?,+ k_norm: gg.rms_norm(&format!("{p}.attn_k_norm.weight"), rms_norm_eps)?,+ n_head: head_count,+ n_kv_head: head_count_kv,+ head_dim,+ rotary_emb: rotary_emb.clone(),+ dtype,+ kv_cache: KvCache::new(2, 4096),+ };+ layers.push(Layer {+ attn,+ attn_norm: gg.rms_norm(&format!("{p}.attn_norm.weight"), rms_norm_eps)?,+ moe,+ ffn_norm: gg.rms_norm(&format!("{p}.ffn_norm.weight"), rms_norm_eps)?,+ });+ }+ Ok(Self { embeddings: Embedding::new(embeddings, embedding_length), layers, norm, output, store, dtype, device: device.clone(), thinks, progress: None })+ }++ /// Print where each written word's time went since the last call, then reset the counters.+ pub fn report(&self) {+ self.store.report_and_reset();+ }++ /// Forget the conversation so the next prompt starts at position 0.+ pub fn clear_kv_cache(&mut self) {+ for layer in self.layers.iter_mut() {+ layer.attn.kv_cache.reset();+ }+ }++ pub fn forward(&mut self, x: &Tensor, offset: usize) -> Result<Tensor> {+ let mut xs = self.embeddings.forward(&x.to_device(&Device::Cpu)?)?.to_device(&self.device)?.to_dtype(DType::F32)?;+ let (_b, l) = x.dims2()?;+ let mask = if l == 1 {+ None+ } else {+ Some(candle_transformers::utils::build_additive_causal_mask(l, offset, None, &self.device, self.dtype)?)+ };+ let n = self.layers.len();+ for (i, layer) in self.layers.iter_mut().enumerate() {+ let residual = &xs;+ let h = (layer.attn.forward(&layer.attn_norm.forward(residual)?, mask.as_ref(), offset)? + residual)?;+ let out = (layer.moe.forward(&layer.ffn_norm.forward(&h)?)? + &h)?;+ xs = out;+ if l > 1 {+ if let Some(p) = &mut self.progress {+ p(Step::Layer(i + 1, n));+ }+ }+ }+ let xs = self.norm.forward(&xs.narrow(1, l - 1, 1)?)?;+ self.output.forward(&xs)?.to_dtype(DType::F32)?.squeeze(1)+ }+}++/// Every model family Coachwhip runs, picked from the GGUF file's architecture.+pub enum Model {+ Qwen3Moe(Qwen3Moe),+ Qwen3Next(crate::model_next::Qwen3Next),+}++impl Model {+ pub fn load(path: &Path, device: &Device, settings: &Settings) -> Result<Self> {+ let mut file = std::fs::File::open(path)?;+ let ct = gguf_file::Content::read(&mut file).map_err(|e| e.with_path(path))?;+ let arch = match ct.metadata.get("general.architecture") {+ Some(v) => v.to_string()?.clone(),+ None => candle::bail!("cannot find general.architecture in the GGUF metadata"),+ };+ drop(ct);+ match arch.as_str() {+ // f16 for attention: bf16 garbles long answers in this model.+ "qwen3moe" => Ok(Self::Qwen3Moe(Qwen3Moe::load(path, device, DType::F16, settings)?)),+ "qwen3next" => Ok(Self::Qwen3Next(crate::model_next::Qwen3Next::load(path, device, settings)?)),+ other => candle::bail!(+ "this model's architecture is \"{other}\", which Coachwhip does not support yet (today: qwen3moe, qwen3next). \+ Open an issue at https://github.com/1picassoai/coachwhip/issues so it moves up the list."+ ),+ }+ }++ pub fn forward(&mut self, x: &Tensor, offset: usize) -> Result<Tensor> {+ match self {+ Self::Qwen3Moe(m) => m.forward(x, offset),+ Self::Qwen3Next(m) => m.forward(x, offset),+ }+ }++ pub fn clear_kv_cache(&mut self) {+ match self {+ Self::Qwen3Moe(m) => m.clear_kv_cache(),+ Self::Qwen3Next(m) => m.clear_kv_cache(),+ }+ }++ pub fn report(&self) {+ match self {+ Self::Qwen3Moe(m) => m.report(),+ Self::Qwen3Next(m) => m.report(),+ }+ }++ pub fn thinks(&self) -> bool {+ match self {+ Self::Qwen3Moe(m) => m.thinks,+ Self::Qwen3Next(m) => m.thinks,+ }+ }++ /// Who to tell, layer by layer, while a prompt is being read; `None` to stop telling.+ pub fn set_progress(&mut self, progress: Option<Progress>) {+ match self {+ Self::Qwen3Moe(m) => m.progress = progress,+ Self::Qwen3Next(m) => m.progress = progress,+ }+ }+}diff --git a/src/model_next.rs b/src/model_next.rsnew file mode 100644index 0000000..f79242a--- /dev/null+++ b/src/model_next.rs@@ -0,0 +1,451 @@+//! Qwen3-Next, read from a GGUF file. The same expert streaming as Qwen3 MoE; what is new is the+//! attention. Three layers in four keep a fixed-size running memory per head (Gated DeltaNet)+//! instead of a cache that grows with every word; every fourth layer is classic attention with a+//! gate on its output. Each layer also has a shared expert that every word uses.+//!+//! Follows llama.cpp's qwen3next graph for the tensor layout and the maths.++use crate::experts::{ExpertStore, Settings, StreamedMoe};+use candle::quantized::gguf_file;+use candle::{DType, Device, Module, Result, Tensor, D};+use candle_nn::kv_cache::KvCache;+use candle_nn::{Embedding, Linear};+use candle_transformers::models::quantized_qwen3::Gguf;+use candle_transformers::models::with_tracing::QMatMul;+use candle_transformers::quantized_nn::RmsNorm;+use std::path::Path;+use std::sync::Arc;++/// x / sqrt(sum(x^2) + eps) over the last dimension.+fn l2_norm(x: &Tensor, eps: f64) -> Result<Tensor> {+ let n = (x.sqr()?.sum_keepdim(D::Minus1)? + eps)?.sqrt()?;+ x.broadcast_div(&n)+}++fn softplus(x: &Tensor) -> Result<Tensor> {+ (x.exp()? + 1.0)?.log()+}++/// Words per block when a running-memory layer reads a prompt.+pub(crate) const DELTA_CHUNK: usize = 64;++/// The delta rule over a whole prompt, a block of words at a time (Gated DeltaNet, Yang, Kautz and+/// Hatamizadeh, ICLR 2025, section 3). Gives the same answer as stepping word by word, but each+/// block is a few large matrix products instead of a dozen small GPU jobs per word. Inside a block,+/// every word's correction depends on the corrections before it; that chain is a small triangular+/// system, solved once per block on the CPU. Decays are kept as logarithms so long blocks never+/// divide by a vanishing number.+/// q, k: (l, n_v, dk); v: (l, n_v, dv); beta, log_decay: (l, n_v); s: (n_v, dk, dv).+pub(crate) fn delta_chunked(q: &Tensor, k: &Tensor, v: &Tensor, beta: &Tensor, log_decay: &Tensor, mut s: Tensor) -> Result<(Tensor, Tensor)> {+ let (l, n_v, dk) = q.dims3()?;+ let dv = v.dim(2)?;+ let c = DELTA_CHUNK;+ let nc = l.div_ceil(c);+ let pad = nc * c - l;+ let device = q.device();+ // Padding words have no key, no value, no write strength and no decay, so they change nothing.+ let blocks = |t: &Tensor, width: usize| -> Result<Tensor> {+ let t = if pad > 0 { t.pad_with_zeros(0, 0, pad)? } else { t.clone() };+ t.reshape((nc, c, n_v, width))?.permute((2, 0, 1, 3))?.contiguous()?.reshape((n_v * nc, c, width))+ };+ let (q, k, v) = (blocks(q, dk)?, blocks(k, dk)?, blocks(v, dv)?);+ let beta = blocks(&beta.unsqueeze(2)?, 1)?; // (n, c, 1)+ let cum = blocks(&log_decay.unsqueeze(2)?, 1)?.squeeze(2)?.cumsum(1)?; // (n, c): decay since block start, inclusive++ let mask = |strict: bool| -> Result<Tensor> {+ let m: Vec<f32> = (0..c * c).map(|x| if x % c < x / c || (!strict && x % c == x / c) { 0.0 } else { -1e30 }).collect();+ Tensor::from_vec(m, (c, c), device)+ };+ let diff = cum.unsqueeze(2)?.broadcast_sub(&cum.unsqueeze(1)?)?; // [t, i] = decay from i to t+ let fade_strict = diff.broadcast_add(&mask(true)?)?.exp()?;+ let fade_incl = diff.broadcast_add(&mask(false)?)?.exp()?;+ let kt = k.transpose(1, 2)?.contiguous()?;+ let a = (k.matmul(&kt)? * fade_strict)?.broadcast_mul(&beta)?;+ let p = (q.matmul(&kt)? * fade_incl)?;+ let gam = cum.exp()?.unsqueeze(2)?; // (n, c, 1)+ let last = cum.narrow(1, c - 1, 1)?; // (n, 1)+ let gam_last = last.exp()?.unsqueeze(2)?; // (n, 1, 1)+ let k_to_end = k.broadcast_mul(&last.broadcast_sub(&cum)?.exp()?.unsqueeze(2)?)?;+ let q_gam = q.broadcast_mul(&gam)?;++ // T = (I + A)^-1, A strictly lower triangular: forward substitution, one small matrix per block and head.+ let a_rows = a.to_device(&Device::Cpu)?.flatten_all()?.to_vec1::<f32>()?;+ let mut t_rows = vec![0f32; a_rows.len()];+ use rayon::prelude::*;+ t_rows.par_chunks_mut(c * c).zip(a_rows.par_chunks(c * c)).for_each(|(t, a)| {+ for r in 0..c {+ t[r * c + r] = 1.0;+ for i in 0..r {+ let air = a[r * c + i];+ if air != 0.0 {+ for j in 0..=i {+ t[r * c + j] -= air * t[i * c + j];+ }+ }+ }+ }+ });+ let tri = Tensor::from_vec(t_rows, (n_v * nc, c, c), device)?;+ let w = tri.matmul(&k.broadcast_mul(&(beta.broadcast_mul(&gam))?)?)?; // (n, c, dk)+ let u = tri.matmul(&v.broadcast_mul(&beta)?)?; // (n, c, dv)++ let per_block = |t: Tensor, width: usize| t.reshape((n_v, nc, c, width));+ let (w, u, p, q_gam) = (per_block(w, dk)?, per_block(u, dv)?, per_block(p, c)?, per_block(q_gam, dk)?);+ let k_to_end_t = per_block(k_to_end, dk)?.transpose(2, 3)?.contiguous()?; // (n_v, nc, dk, c)+ let gam_last = gam_last.reshape((n_v, nc, 1, 1))?;+ let mut outs = Vec::with_capacity(nc);+ for b in 0..nc {+ let at = |t: &Tensor| t.narrow(1, b, 1)?.squeeze(1);+ let d = (at(&u)? - at(&w)?.matmul(&s)?)?; // (n_v, c, dv): each word's correction+ outs.push((at(&q_gam)?.matmul(&s)? + at(&p)?.contiguous()?.matmul(&d)?)?);+ s = (s.broadcast_mul(&at(&gam_last)?)? + at(&k_to_end_t)?.matmul(&d)?)?;+ }+ let o = Tensor::cat(&outs, 1)?.narrow(1, 0, l)?.transpose(0, 1)?.contiguous()?; // (l, n_v, dv)+ Ok((o, s))+}++/// A running-memory layer: per value head a 128 x 128 matrix that decays, is corrected by each+/// new key and value (the delta rule), and is read out with the query.+struct LinearAttn {+ in_proj: QMatMul,+ ba: QMatMul,+ conv_w: Tensor,+ dt_bias: Tensor,+ a: Tensor,+ norm: RmsNorm,+ out: QMatMul,+ n_k: usize,+ n_v: usize,+ dk: usize,+ dv: usize,+ eps: f64,+ conv_state: Option<Tensor>,+ state: Option<Tensor>,+}++impl LinearAttn {+ fn reset(&mut self) {+ self.conv_state = None;+ self.state = None;+ }++ fn forward(&mut self, x: &Tensor) -> Result<Tensor> {+ let (b, l, h) = x.dims3()?;+ let device = x.device();+ let (n_k, n_v, dk, dv) = (self.n_k, self.n_v, self.dk, self.dv);+ let per_group = n_v / n_k;+ let x2 = x.reshape((l, h))?;++ // One projection holds, per key head: q, k, then the values and gates of its value heads.+ let mixed = self.in_proj.forward(&x2)?.reshape((l, n_k, 2 * dk + 2 * dv * per_group))?;+ let q = mixed.narrow(2, 0, dk)?.reshape((l, n_k * dk))?;+ let k = mixed.narrow(2, dk, dk)?.reshape((l, n_k * dk))?;+ let v = mixed.narrow(2, 2 * dk, dv * per_group)?.reshape((l, n_v * dv))?;+ let z = mixed.narrow(2, 2 * dk + dv * per_group, dv * per_group)?.reshape((l, n_v, dv))?;+ let qkv = Tensor::cat(&[&q, &k, &v], 1)?; // (l, channels)+ let channels = qkv.dim(1)?;++ let ba = self.ba.forward(&x2)?.reshape((l, n_k, 2 * per_group))?;+ let beta = candle_nn::ops::sigmoid(&ba.narrow(2, 0, per_group)?.reshape((l, n_v))?)?;+ let alpha = ba.narrow(2, per_group, per_group)?.reshape((l, n_v))?;+ let log_decay = softplus(&alpha.broadcast_add(&self.dt_bias)?)?.broadcast_mul(&self.a)?; // (l, n_v)++ // Causal depthwise convolution over the last `taps` inputs, carried across calls.+ let taps = self.conv_w.dim(1)?;+ let past = match &self.conv_state {+ Some(s) => s.clone(),+ None => Tensor::zeros((taps - 1, channels), DType::F32, device)?,+ };+ let padded = Tensor::cat(&[&past, &qkv], 0)?; // (taps - 1 + l, channels)+ let mut conv = padded.narrow(0, 0, l)?.broadcast_mul(&self.conv_w.narrow(1, 0, 1)?.t()?)?;+ for w in 1..taps {+ conv = (conv + padded.narrow(0, w, l)?.broadcast_mul(&self.conv_w.narrow(1, w, 1)?.t()?)?)?;+ }+ self.conv_state = Some(padded.narrow(0, l, taps - 1)?.contiguous()?);+ let conv = candle_nn::ops::silu(&conv)?;++ let qc = l2_norm(&conv.narrow(1, 0, n_k * dk)?.reshape((l, n_k, dk))?, self.eps)?;+ let kc = l2_norm(&conv.narrow(1, n_k * dk, n_k * dk)?.reshape((l, n_k, dk))?, self.eps)?;+ let vc = conv.narrow(1, 2 * n_k * dk, n_v * dv)?.reshape((l, n_v, dv))?;+ // Each key head serves `per_group` value heads, side by side.+ let widen = |t: Tensor| -> Result<Tensor> { t.unsqueeze(2)?.broadcast_as((l, n_k, per_group, dk))?.reshape((l, n_v, dk)) };+ let qc = (widen(qc)? * (1.0 / (dk as f64).sqrt()))?;+ let kc = widen(kc)?;++ let mut s = match &self.state {+ Some(s) => s.clone(),+ None => Tensor::zeros((n_v, dk, dv), DType::F32, device)?,+ };+ let (o, s) = if l > 1 {+ delta_chunked(&qc, &kc, &vc, &beta, &log_decay, s)?+ } else {+ let decay = log_decay.exp()?;+ let mut outs = Vec::with_capacity(l);+ for t in 0..l {+ let kt = kc.get(t)?.unsqueeze(1)?.contiguous()?; // (n_v, 1, dk)+ let qt = qc.get(t)?.unsqueeze(1)?.contiguous()?;+ let vt = vc.get(t)?.unsqueeze(1)?; // (n_v, 1, dv)+ let bt = beta.get(t)?.reshape((n_v, 1, 1))?;+ let gt = decay.get(t)?.reshape((n_v, 1, 1))?;+ s = s.broadcast_mul(>)?;+ let sk = kt.matmul(&s)?; // (n_v, 1, dv)+ let d = (vt - sk)?.broadcast_mul(&bt)?;+ s = (s + kt.transpose(1, 2)?.contiguous()?.matmul(&d)?)?;+ outs.push(qt.matmul(&s)?.squeeze(1)?); // (n_v, dv)+ }+ (Tensor::stack(&outs, 0)?, s) // (l, n_v, dv)+ };+ self.state = Some(s);++ let o = (self.norm.forward(&o)? * candle_nn::ops::silu(&z)?)?;+ self.out.forward(&o.reshape((l, n_v * dv))?)?.reshape((b, l, h))+ }+}++/// Classic attention with a sigmoid gate on its output and rotary position on a quarter of each head.+struct FullAttn {+ wq: QMatMul,+ wk: QMatMul,+ wv: QMatMul,+ wo: QMatMul,+ q_norm: RmsNorm,+ k_norm: RmsNorm,+ n_head: usize,+ n_kv: usize,+ hd: usize,+ rot: usize,+ freq_base: f64,+ kv_cache: KvCache,+}++impl FullAttn {+ fn rope(&self, x: &Tensor, offset: usize) -> Result<Tensor> {+ let (_b, _h, l, _d) = x.dims4()?;+ let half = self.rot / 2;+ let inv: Vec<f32> = (0..half).map(|i| (1.0 / self.freq_base.powf(2.0 * i as f64 / self.rot as f64)) as f32).collect();+ let pos: Vec<f32> = (offset..offset + l).map(|p| p as f32).collect();+ let inv = Tensor::from_vec(inv, (1, half), x.device())?;+ let pos = Tensor::from_vec(pos, (l, 1), x.device())?;+ let freqs = pos.broadcast_mul(&inv)?; // (l, half)+ let (cos, sin) = (freqs.cos()?, freqs.sin()?);+ let rotated = candle_nn::rotary_emb::rope(&x.narrow(3, 0, self.rot)?.contiguous()?, &cos, &sin)?;+ Tensor::cat(&[&rotated, &x.narrow(3, self.rot, self.hd - self.rot)?], 3)+ }++ fn forward(&mut self, x: &Tensor, mask: Option<&Tensor>, offset: usize) -> Result<Tensor> {+ let (b, l, _) = x.dims3()?;+ let full = self.wq.forward(x)?.reshape((l, self.n_head, 2 * self.hd))?;+ let q = self.q_norm.forward(&full.narrow(2, 0, self.hd)?.contiguous()?)?;+ let gate = full.narrow(2, self.hd, self.hd)?.reshape((l, self.n_head * self.hd))?;+ let k = self.k_norm.forward(&self.wk.forward(x)?.reshape((l, self.n_kv, self.hd))?)?;+ let v = self.wv.forward(x)?.reshape((l, self.n_kv, self.hd))?;++ let heads = |t: Tensor| -> Result<Tensor> { t.transpose(0, 1)?.unsqueeze(0)?.contiguous() }; // (1, H, l, D)+ let q = self.rope(&heads(q)?, offset)?;+ let k = self.rope(&heads(k)?, offset)?;+ let v = heads(v)?;+ let (k, v) = self.kv_cache.append(&k.contiguous()?, &v)?;+ let s_len = k.dim(2)?;++ let g = self.n_head / self.n_kv;+ let q = q.contiguous()?.reshape((1, self.n_kv, g * l, self.hd))?;+ let mut scores = (q.matmul(&k.transpose(2, 3)?)? * (1.0 / (self.hd as f64).sqrt()))?;+ if let Some(m) = mask {+ scores = scores+ .reshape((1, self.n_kv, g, l, s_len))?+ .broadcast_add(&m.to_dtype(scores.dtype())?.unsqueeze(1)?)?+ .reshape((1, self.n_kv, g * l, s_len))?;+ }+ let probs = candle_nn::ops::softmax_last_dim(&scores)?;+ let ctx = probs.matmul(&v)?.reshape((1, self.n_head, l, self.hd))?;+ let ctx = ctx.transpose(1, 2)?.reshape((l, self.n_head * self.hd))?;+ let ctx = (ctx * candle_nn::ops::sigmoid(&gate)?)?;+ self.wo.forward(&ctx)?.reshape((b, l, ()))+ }+}++enum Mixer {+ Linear(LinearAttn),+ Full(FullAttn),+}++/// The expert every word uses, with its own sigmoid gate.+struct SharedExpert {+ gate_inp: Tensor,+ gate: QMatMul,+ up: QMatMul,+ down: QMatMul,+}++impl SharedExpert {+ fn forward(&self, x: &Tensor) -> Result<Tensor> {+ let hidden = (candle_nn::ops::silu(&self.gate.forward(x)?)? * self.up.forward(x)?)?;+ let y = self.down.forward(&hidden)?;+ let g = candle_nn::ops::sigmoid(&x.broadcast_mul(&self.gate_inp)?.sum_keepdim(D::Minus1)?)?;+ y.broadcast_mul(&g)+ }+}++struct Layer {+ mixer: Mixer,+ attn_norm: RmsNorm,+ post_norm: RmsNorm,+ moe: StreamedMoe,+ shared: SharedExpert,+}++pub struct Qwen3Next {+ embeddings: Embedding,+ layers: Vec<Layer>,+ norm: RmsNorm,+ output: QMatMul,+ store: Arc<ExpertStore>,+ device: Device,+ pub thinks: bool,+ pub progress: Option<crate::model::Progress>,+}++impl Qwen3Next {+ pub fn load(path: &Path, device: &Device, settings: &Settings) -> Result<Self> {+ let mut file = std::fs::File::open(path)?;+ let ct = gguf_file::Content::read(&mut file).map_err(|e| e.with_path(path))?;+ let md = |s: &str| match ct.metadata.get(s) {+ None => candle::bail!("cannot find {s} in the GGUF metadata"),+ Some(v) => Ok(v.clone()),+ };+ let md_u = |s: &str| -> Result<usize> { Ok(md(&format!("qwen3next.{s}"))?.to_u32()? as usize) };+ let n_head = md_u("attention.head_count")?;+ let n_kv = md_u("attention.head_count_kv")?;+ let hd = md_u("attention.key_length")?;+ let rot = md_u("rope.dimension_count")?;+ let block_count = md_u("block_count")?;+ let top_k = md_u("expert_used_count")?;+ let embedding_length = md_u("embedding_length")?;+ let d_state = md_u("ssm.state_size")?;+ let n_group = md_u("ssm.group_count")?;+ let dt_rank = md_u("ssm.time_step_rank")?;+ let inner = md_u("ssm.inner_size")?;+ let interval = md_u("full_attention_interval").unwrap_or(4);+ let eps = md("qwen3next.attention.layer_norm_rms_epsilon")?.to_f32()? as f64;+ // Some conversions leave the rope base out; Qwen3-Next's is ten million.+ let freq_base = md("qwen3next.rope.freq_base").ok().and_then(|v| v.to_f32().ok()).map_or(1e7, |f| f as f64);+ let thinks = md("tokenizer.chat_template").and_then(|t| t.to_string().cloned()).map_or(false, |t| t.contains("enable_thinking"));++ let store = ExpertStore::new(&ct, device, block_count, path, settings)?;+ let mut gg = Gguf::new(ct, &mut file, device.clone());+ let dense = |gg: &mut Gguf<&mut std::fs::File>, name: &str| -> Result<Tensor> { gg.tensor(name)?.dequantize(device)?.to_dtype(DType::F32) };++ let embeddings = gg.tensor("token_embd.weight")?.dequantize(device)?.to_dtype(DType::F16)?.to_device(&Device::Cpu)?;+ let norm = gg.rms_norm("output_norm.weight", eps)?;+ let output = match gg.qmatmul("output.weight") {+ Ok(v) => v,+ _ => gg.qmatmul("token_embd.weight")?,+ };++ let mut layers = Vec::with_capacity(block_count);+ for layer in 0..block_count {+ let p = format!("blk.{layer}");+ let mixer = if (layer + 1) % interval == 0 {+ Mixer::Full(FullAttn {+ wq: gg.qmatmul(&format!("{p}.attn_q.weight"))?,+ wk: gg.qmatmul(&format!("{p}.attn_k.weight"))?,+ wv: gg.qmatmul(&format!("{p}.attn_v.weight"))?,+ wo: gg.qmatmul(&format!("{p}.attn_output.weight"))?,+ q_norm: gg.rms_norm(&format!("{p}.attn_q_norm.weight"), eps)?,+ k_norm: gg.rms_norm(&format!("{p}.attn_k_norm.weight"), eps)?,+ n_head,+ n_kv,+ hd,+ rot,+ freq_base,+ kv_cache: KvCache::new(2, 4096),+ })+ } else {+ let conv_w = dense(&mut gg, &format!("{p}.ssm_conv1d.weight"))?; // (channels, taps)+ Mixer::Linear(LinearAttn {+ in_proj: gg.qmatmul(&format!("{p}.ssm_in.weight"))?,+ ba: gg.qmatmul(&format!("{p}.ssm_ba.weight"))?,+ conv_w,+ dt_bias: dense(&mut gg, &format!("{p}.ssm_dt.bias"))?,+ a: dense(&mut gg, &format!("{p}.ssm_a"))?,+ norm: gg.rms_norm(&format!("{p}.ssm_norm.weight"), eps)?,+ out: gg.qmatmul(&format!("{p}.ssm_out.weight"))?,+ n_k: n_group,+ n_v: dt_rank,+ dk: d_state,+ dv: inner / dt_rank,+ eps,+ conv_state: None,+ state: None,+ })+ };+ let gate = dense(&mut gg, &format!("{p}.ffn_gate_inp.weight"))?;+ let moe = StreamedMoe {+ layer,+ gate: Linear::new(gate, None),+ store: store.clone(),+ top_k,+ norm_topk_prob: true,+ prefetch_k: settings.prefetch,+ };+ let shared = SharedExpert {+ gate_inp: dense(&mut gg, &format!("{p}.ffn_gate_inp_shexp.weight"))?,+ gate: gg.qmatmul(&format!("{p}.ffn_gate_shexp.weight"))?,+ up: gg.qmatmul(&format!("{p}.ffn_up_shexp.weight"))?,+ down: gg.qmatmul(&format!("{p}.ffn_down_shexp.weight"))?,+ };+ layers.push(Layer {+ mixer,+ attn_norm: gg.rms_norm(&format!("{p}.attn_norm.weight"), eps)?,+ post_norm: gg.rms_norm(&format!("{p}.post_attention_norm.weight"), eps)?,+ moe,+ shared,+ });+ }+ Ok(Self { embeddings: Embedding::new(embeddings, embedding_length), layers, norm, output, store, device: device.clone(), thinks, progress: None })+ }++ pub fn report(&self) {+ self.store.report_and_reset();+ }++ /// Forget the conversation: the classic layers' caches and the running memories together.+ pub fn clear_kv_cache(&mut self) {+ for layer in self.layers.iter_mut() {+ match &mut layer.mixer {+ Mixer::Full(a) => a.kv_cache.reset(),+ Mixer::Linear(a) => a.reset(),+ }+ }+ }++ pub fn forward(&mut self, x: &Tensor, offset: usize) -> Result<Tensor> {+ let mut xs = self.embeddings.forward(&x.to_device(&Device::Cpu)?)?.to_device(&self.device)?.to_dtype(DType::F32)?;+ let (_b, l) = x.dims2()?;+ let mask = if l == 1 {+ None+ } else {+ Some(candle_transformers::utils::build_additive_causal_mask(l, offset, None, &self.device, DType::F32)?)+ };+ let n = self.layers.len();+ for (i, layer) in self.layers.iter_mut().enumerate() {+ let normed = layer.attn_norm.forward(&xs)?;+ let mixed = match &mut layer.mixer {+ Mixer::Linear(a) => a.forward(&normed)?,+ Mixer::Full(a) => a.forward(&normed, mask.as_ref(), offset)?,+ };+ let h = (mixed + &xs)?;+ let post = layer.post_norm.forward(&h)?;+ let routed = layer.moe.forward(&post)?;+ let shared = layer.shared.forward(&post)?;+ xs = ((routed + shared)? + h)?;+ if l > 1 {+ if let Some(p) = &mut self.progress {+ p(crate::model::Step::Layer(i + 1, n));+ }+ }+ }+ let xs = self.norm.forward(&xs.narrow(1, l - 1, 1)?)?;+ self.output.forward(&xs)?.to_dtype(DType::F32)?.squeeze(1)+ }+}diff --git a/src/mv_id.rs b/src/mv_id.rsnew file mode 100644index 0000000..0c6b19a--- /dev/null+++ b/src/mv_id.rs@@ -0,0 +1,112 @@+//! One Metal dispatch for every selected expert of every token: ggml's `kernel_mul_mv_id`,+//! which ships inside Candle's Metal kernel library but has no Rust entry point there.++use candle_metal_kernels::metal::{Buffer, Device};+use candle_metal_kernels::source::Source;+use candle_metal_kernels::utils::EncoderProvider;+use candle_metal_kernels::{set_params, GgmlDType, Kernels, MetalKernelError, Output};+use objc2_metal::MTLSize;++/// For every token and each of its `nei0` selected experts, multiplies one row of `src1` by that+/// expert's quantised matrix.+/// - `src0s` holds `ne02` expert matrices of `n` rows x `k` columns, `nb02` bytes apart.+/// - `ids` holds `nei1 x nei0` int32 expert indices into `src0s`.+/// - `src1` rows are f32; row `i11 = slot % ne11` of token `i12` sits at `i11*nb11 + i12*nb12` bytes.+/// - `dst` gets f32 `[nei1][nei0][n]`.+#[allow(clippy::too_many_arguments)]+pub fn matvec_id(+ device: &Device,+ ep: impl EncoderProvider,+ kernels: &Kernels,+ dtype: GgmlDType,+ (n, k, ne02, nb02): (usize, usize, usize, usize),+ src0s: &Buffer,+ src1: &Buffer,+ src1_offset: usize,+ (ne11, nb11, nb12): (usize, usize, usize),+ ids: &Buffer,+ ids_offset: usize,+ (nei0, nei1): (usize, usize),+ dst: &Buffer,+) -> Result<(), MetalKernelError> {+ let (nth0, nth1, align) = match dtype {+ GgmlDType::Q4_0 | GgmlDType::Q4_1 | GgmlDType::Q5_0 | GgmlDType::Q5_1 | GgmlDType::Q8_0 | GgmlDType::Q8_1 => (8, 8, 8),+ GgmlDType::Q2K => (2, 32, 4),+ GgmlDType::Q4K => (4, 8, 4),+ GgmlDType::Q3K | GgmlDType::Q5K => (2, 32, 4),+ GgmlDType::Q6K => (2, 32, 2),+ GgmlDType::F16 | GgmlDType::BF16 | GgmlDType::Q8K | GgmlDType::F32 => (32, 1, 8),+ };+ let name = match dtype {+ GgmlDType::Q4_0 => "kernel_mul_mv_id_q4_0_f32",+ GgmlDType::Q4_1 => "kernel_mul_mv_id_q4_1_f32",+ GgmlDType::Q5_0 => "kernel_mul_mv_id_q5_0_f32",+ GgmlDType::Q5_1 => "kernel_mul_mv_id_q5_1_f32",+ GgmlDType::Q8_0 => "kernel_mul_mv_id_q8_0_f32",+ GgmlDType::Q2K => "kernel_mul_mv_id_q2_K_f32",+ GgmlDType::Q3K => "kernel_mul_mv_id_q3_K_f32",+ GgmlDType::Q4K => "kernel_mul_mv_id_q4_K_f32",+ GgmlDType::Q5K => "kernel_mul_mv_id_q5_K_f32",+ GgmlDType::Q6K => "kernel_mul_mv_id_q6_K_f32",+ GgmlDType::F16 => "kernel_mul_mv_id_f16_f32",+ GgmlDType::F32 => "kernel_mul_mv_id_f32_f32",+ other => return Err(MetalKernelError::LoadLibraryError(format!("no mul_mv_id kernel for {other:?}"))),+ };+ let pipeline = kernels.load_pipeline(device, Source::Quantized, name)?;+ let encoder = ep.encoder();+ let encoder = encoder.as_ref();+ encoder.set_compute_pipeline_state(&pipeline);++ let ne00 = k as i64;+ let ne01 = n as i64;+ let ne02 = ne02 as i64;+ let nb00 = 0u64;+ let nb01 = 0u64;+ let nb02 = nb02 as u64;+ let ne10 = k as i64;+ let ne11 = ne11 as i64;+ let ne12 = nei1 as i64;+ let ne13 = 1i64;+ let nb10 = 4u64;+ let nb11 = nb11 as u64;+ let nb12 = nb12 as u64;+ let ne0 = n as i64;+ let ne1 = nei0 as i64;+ let nb1 = (n * 4) as u64;+ let nei0 = nei0 as i64;+ let nei1 = nei1 as i64;+ let nbi1 = (nei0 * 4) as u64;++ set_params!(+ encoder,+ (+ src0s,+ (src1, src1_offset),+ Output::with_offset(dst, 0),+ (ids, ids_offset),+ nei0,+ nei1,+ nbi1,+ ne00,+ ne01,+ ne02,+ nb00,+ nb01,+ nb02,+ ne10,+ ne11,+ ne12,+ ne13,+ nb10,+ nb11,+ nb12,+ ne0,+ ne1,+ nb1+ )+ );+ let thread_groups_count = MTLSize { width: n.div_ceil(align), height: 1, depth: (nei0 * nei1) as usize };+ let threads_per_threadgroup = MTLSize { width: nth0, height: nth1, depth: 1 };+ encoder.dispatch_thread_groups(thread_groups_count, threads_per_threadgroup);+ Ok(())+}diff --git a/src/tests.rs b/src/tests.rsnew file mode 100644index 0000000..02d6508--- /dev/null+++ b/src/tests.rs@@ -0,0 +1,301 @@+//! Unit tests. No GPU, no model file: only the pure helpers and the CPU maths.+//! Run with `cargo test --release` (debug builds of candle are slow).++use std::io::{Read, Write};+use std::net::{TcpListener, TcpStream};++// ---------------------------------------------------------------- chat.rs helpers++#[test]+fn html_escape_escapes_the_three_that_matter() {+ assert_eq!(crate::chat::html_escape("a&b<c>d"), "a&b<c>d");+ assert_eq!(crate::chat::html_escape("plain"), "plain");+ assert_eq!(crate::chat::html_escape(""), "");+ // Escaping is applied once: an already-escaped amp is escaped again, as it must be.+ assert_eq!(crate::chat::html_escape("&"), "&amp;");+}++#[test]+fn markers_are_the_control_one_prefix_the_page_strips() {+ // The page's JS: MARK = '\u0001STATS:' and PROG = /\u0001PROG:(\{[^\n]*\})\n/+ assert_eq!(crate::chat::STATS_MARK, "\u{1}STATS:");+ assert_eq!(crate::chat::PROG_MARK, "\u{1}PROG:");+ assert!(crate::chat::PAGE.contains("const MARK = '\\u0001STATS:'"));+ assert!(crate::chat::PAGE.contains("const PROG = /\\u0001PROG:(\\{[^\\n]*\\})\\n/g"));+}++#[test]+fn progress_lines_match_the_page_regex() {+ // Same format strings as chat.rs builds in `handle`.+ let layer = format!("{}{{\"layer\":{},\"of\":{}}}\n", crate::chat::PROG_MARK, 3, 48);+ let summary = format!("{}{{\"summary\":{}}}\n", crate::chat::PROG_MARK, 16);+ for line in [&layer, &summary] {+ assert!(line.starts_with("\u{1}PROG:{"));+ assert!(line.ends_with("}\n"));+ let json = &line["\u{1}PROG:".len()..line.len() - 1];+ let v: serde_json::Value = serde_json::from_str(json).expect("progress line is JSON");+ assert!(v.is_object());+ assert!(!json.contains('\n'));+ }+}++#[test]+fn think_box_is_a_verbatim_substring_of_the_page() {+ // `PAGE.replace(THINK_BOX, "")` is a silent no-op if the two ever drift apart.+ assert!(crate::chat::PAGE.contains(crate::chat::THINK_BOX), "THINK_BOX no longer matches the page");+ assert_eq!(crate::chat::PAGE.matches(crate::chat::THINK_BOX).count(), 1);+ let without = crate::chat::PAGE.replace(crate::chat::THINK_BOX, "");+ assert!(!without.contains("id=\"think\""));+ // The JS still guards the missing element.+ assert!(without.contains("$('think')&&$('think').checked"));+}++#[test]+fn page_has_the_model_name_placeholder_once() {+ assert_eq!(crate::chat::PAGE.matches("MODEL_NAME").count(), 1);+}++/// Sends `bytes` through `chunk` over a loopback socket and returns what the other end saw.+fn framed(bytes: &[u8]) -> Vec<u8> {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ let mut client = TcpStream::connect(addr).unwrap();+ let (mut server, _) = listener.accept().unwrap();+ crate::chat::chunk(&mut server, bytes).unwrap();+ drop(server);+ let mut got = Vec::new();+ client.read_to_end(&mut got).unwrap();+ got+}++#[test]+fn chunk_frames_as_hex_length_crlf_body_crlf() {+ assert_eq!(framed(b"hello"), b"5\r\nhello\r\n");+ assert_eq!(framed(&[b'x'; 255]), [b"ff\r\n".as_slice(), &[b'x'; 255], b"\r\n"].concat());+ assert_eq!(framed("é".as_bytes()), b"2\r\n\xc3\xa9\r\n");+}++#[test]+fn chunk_sends_nothing_for_empty_bytes() {+ // An empty chunk ("0\r\n\r\n") would end the HTTP response early.+ assert_eq!(framed(b""), b"");+}++#[test]+fn chunk_to_a_closed_socket_is_an_error_not_a_panic() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ let client = TcpStream::connect(addr).unwrap();+ let (mut server, _) = listener.accept().unwrap();+ drop(client);+ // The first write may still succeed into the kernel buffer; keep writing until it fails.+ let mut failed = false;+ for _ in 0..64 {+ if crate::chat::chunk(&mut server, &[b'x'; 65536]).is_err() {+ failed = true;+ break;+ }+ }+ assert!(failed, "writing to a closed socket never reported an error");+}++// ---------------------------------------------------------------- experts.rs route table++#[test]+fn count_step_counts_every_pair_token_by_token() {+ let mut counts = crate::experts::Counts::new();+ let before = vec![vec![1, 2], vec![1]];+ let now = vec![vec![7], vec![7, 9]];+ crate::experts::count_step(&mut counts, 4, &before, &now);+ assert_eq!(counts[&(4, 1)][&7], 2);+ assert_eq!(counts[&(4, 1)][&9], 1);+ assert_eq!(counts[&(4, 2)][&7], 1);+ assert!(counts.get(&(4, 2)).map_or(true, |r| !r.contains_key(&9)));+ assert!(!counts.contains_key(&(5, 1)));+}++#[test]+fn count_step_ignores_a_token_count_mismatch_beyond_the_shorter_side() {+ let mut counts = crate::experts::Counts::new();+ crate::experts::count_step(&mut counts, 0, &[vec![1]], &[vec![2], vec![3]]);+ assert_eq!(counts[&(0, 1)][&2], 1);+ assert_eq!(counts.len(), 1);+}++#[test]+fn load_routes_reads_the_log_shape_and_skips_junk() {+ let dir = std::env::temp_dir().join(format!("coachwhip-routes-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ // layers = 3: a "T" line then 3 layer lines; a stray header line and a short block are skipped.+ let log = "T -\n1 2,3\n4,5 6\n7,7\nT 1 2 3\n9\n9\nnot-a-number\nT -\n1\n2\n";+ std::fs::write(dir.join("a.log"), log).unwrap();+ std::fs::write(dir.join("ignored.txt"), "T -\n1\n2\n3\n").unwrap();+ let counts = crate::experts::load_routes(&[dir.as_path()], 3);+ std::fs::remove_dir_all(&dir).unwrap();+ // block 1, layer 0 -> 1: token0 (1,2)->(4), token1 (3)->(5,6)+ assert_eq!(counts[&(0, 1)][&4], 1);+ assert_eq!(counts[&(0, 2)][&4], 1);+ assert_eq!(counts[&(0, 3)][&5], 1);+ assert_eq!(counts[&(0, 3)][&6], 1);+ // block 1, layer 1 -> 2: (4)->(7), (5,6)->(7)+ assert_eq!(counts[&(1, 4)][&7], 1);+ assert_eq!(counts[&(1, 5)][&7], 1);+ // block 2: "not-a-number" parses to no experts, so (9)->(9) counted once and nothing from layer 2+ assert_eq!(counts[&(0, 9)][&9], 1);+ assert!(!counts.contains_key(&(1, 9)));+ // the last block is too short and must not be read+ assert!(!counts.contains_key(&(0, 1)) || counts[&(0, 1)].get(&2).is_none());+}++#[test]+fn load_routes_with_a_missing_folder_is_empty_not_an_error() {+ let counts = crate::experts::load_routes(&[std::path::Path::new("/nonexistent/coachwhip")], 4);+ assert!(counts.is_empty());+}++// ---------------------------------------------------------------- model_next.rs delta rule (CPU)++use candle::{Device, Tensor};++/// A tiny deterministic generator so the test needs no `rand` crate.+struct Lcg(u64);+impl Lcg {+ fn next(&mut self) -> f32 {+ self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);+ ((self.0 >> 33) as f32 / (1u64 << 31) as f32) * 2.0 - 1.0+ }+ fn tensor(&mut self, shape: &[usize], scale: f32) -> Tensor {+ let n: usize = shape.iter().product();+ let v: Vec<f32> = (0..n).map(|_| self.next() * scale).collect();+ Tensor::from_vec(v, shape, &Device::Cpu).unwrap()+ }+}++/// The word-by-word delta rule exactly as model_next.rs steps it for one word (its `l == 1` path).+fn delta_word_by_word(q: &Tensor, k: &Tensor, v: &Tensor, beta: &Tensor, log_decay: &Tensor, mut s: Tensor) -> (Tensor, Tensor) {+ let (l, n_v, _dk) = q.dims3().unwrap();+ let decay = log_decay.exp().unwrap();+ let mut outs = Vec::with_capacity(l);+ for t in 0..l {+ let kt = k.get(t).unwrap().unsqueeze(1).unwrap().contiguous().unwrap();+ let qt = q.get(t).unwrap().unsqueeze(1).unwrap().contiguous().unwrap();+ let vt = v.get(t).unwrap().unsqueeze(1).unwrap();+ let bt = beta.get(t).unwrap().reshape((n_v, 1, 1)).unwrap();+ let gt = decay.get(t).unwrap().reshape((n_v, 1, 1)).unwrap();+ s = s.broadcast_mul(>).unwrap();+ let sk = kt.matmul(&s).unwrap();+ let d = (vt - sk).unwrap().broadcast_mul(&bt).unwrap();+ s = (s + kt.transpose(1, 2).unwrap().contiguous().unwrap().matmul(&d).unwrap()).unwrap();+ outs.push(qt.matmul(&s).unwrap().squeeze(1).unwrap());+ }+ (Tensor::stack(&outs, 0).unwrap(), s)+}++fn max_abs_diff(a: &Tensor, b: &Tensor) -> f32 {+ (a - b).unwrap().abs().unwrap().flatten_all().unwrap().max(0).unwrap().to_scalar::<f32>().unwrap()+}++fn inputs(seed: u64, l: usize, n_v: usize, dk: usize, dv: usize) -> (Tensor, Tensor, Tensor, Tensor, Tensor) {+ let mut g = Lcg(seed);+ let unit = |t: Tensor| -> Tensor {+ let n = t.sqr().unwrap().sum_keepdim(2).unwrap().sqrt().unwrap();+ t.broadcast_div(&n).unwrap()+ };+ let q = unit(g.tensor(&[l, n_v, dk], 1.0));+ let k = unit(g.tensor(&[l, n_v, dk], 1.0));+ let v = g.tensor(&[l, n_v, dv], 1.0);+ // beta in (0, 1); log decay in about (-0.6, 0): what sigmoid and softplus * A produce.+ let beta = candle_nn::ops::sigmoid(&g.tensor(&[l, n_v], 2.0)).unwrap();+ let log_decay = (g.tensor(&[l, n_v], 0.3).abs().unwrap() * -1.0).unwrap();+ (q, k, v, beta, log_decay)+}++fn check_chunked_against_word_by_word(l: usize, seed: u64) {+ let (n_v, dk, dv) = (3, 8, 6);+ let (q, k, v, beta, log_decay) = inputs(seed, l, n_v, dk, dv);+ let s0 = Tensor::zeros((n_v, dk, dv), candle::DType::F32, &Device::Cpu).unwrap();+ let (o_ref, s_ref) = delta_word_by_word(&q, &k, &v, &beta, &log_decay, s0.clone());+ let (o, s) = crate::model_next::delta_chunked(&q, &k, &v, &beta, &log_decay, s0).unwrap();+ assert_eq!(o.dims(), &[l, n_v, dv], "output shape for l = {l}");+ assert_eq!(s.dims(), &[n_v, dk, dv]);+ let od = max_abs_diff(&o, &o_ref);+ let sd = max_abs_diff(&s, &s_ref);+ assert!(od < 1e-4, "l = {l}: output differs from word-by-word by {od}");+ assert!(sd < 1e-4, "l = {l}: state differs from word-by-word by {sd}");+}++#[test]+fn delta_chunked_matches_word_by_word_when_l_is_a_whole_number_of_blocks() {+ let c = crate::model_next::DELTA_CHUNK;+ check_chunked_against_word_by_word(c, 1);+ check_chunked_against_word_by_word(2 * c, 2);+}++#[test]+fn delta_chunked_matches_word_by_word_with_padding() {+ let c = crate::model_next::DELTA_CHUNK;+ for l in [2, 5, c - 1, c + 1, 2 * c + 17] {+ check_chunked_against_word_by_word(l, 10 + l as u64);+ }+}++#[test]+fn delta_chunked_carries_state_across_calls() {+ // One call over 70 words must equal two calls, 70 = 45 + 25, with the state handed on.+ let (l, n_v, dk, dv) = (70, 3, 8, 6);+ let (q, k, v, beta, log_decay) = inputs(99, l, n_v, dk, dv);+ let s0 = Tensor::zeros((n_v, dk, dv), candle::DType::F32, &Device::Cpu).unwrap();+ let (o_all, s_all) = crate::model_next::delta_chunked(&q, &k, &v, &beta, &log_decay, s0.clone()).unwrap();+ let cut = 45;+ let part = |t: &Tensor, from: usize, len: usize| t.narrow(0, from, len).unwrap().contiguous().unwrap();+ let (o1, s1) = crate::model_next::delta_chunked(&part(&q, 0, cut), &part(&k, 0, cut), &part(&v, 0, cut), &part(&beta, 0, cut), &part(&log_decay, 0, cut), s0).unwrap();+ let (o2, s2) = crate::model_next::delta_chunked(&part(&q, cut, l - cut), &part(&k, cut, l - cut), &part(&v, cut, l - cut), &part(&beta, cut, l - cut), &part(&log_decay, cut, l - cut), s1).unwrap();+ let o_split = Tensor::cat(&[&o1, &o2], 0).unwrap();+ assert!(max_abs_diff(&o_all, &o_split) < 1e-4);+ assert!(max_abs_diff(&s_all, &s2) < 1e-4);+}++#[test]+fn delta_chunked_with_a_nonzero_starting_state() {+ let (l, n_v, dk, dv) = (37, 2, 8, 6);+ let (q, k, v, beta, log_decay) = inputs(7, l, n_v, dk, dv);+ let s0 = Lcg(123).tensor(&[n_v, dk, dv], 0.5);+ let (o_ref, s_ref) = delta_word_by_word(&q, &k, &v, &beta, &log_decay, s0.clone());+ let (o, s) = crate::model_next::delta_chunked(&q, &k, &v, &beta, &log_decay, s0).unwrap();+ assert!(max_abs_diff(&o, &o_ref) < 1e-4);+ assert!(max_abs_diff(&s, &s_ref) < 1e-4);+}++// ---------------------------------------------------------------- loopback HTTP, no model++#[test]+fn chunk_output_is_valid_for_a_chunked_http_client() {+ // What the page receives per chunk: hex length, CRLF, body, CRLF. A zero-length chunk is never+ // produced by `chunk`; `handle` writes the terminator itself.+ let mut server_side: Vec<u8> = Vec::new();+ for piece in ["Here", "'s", " a", "\u{1}STATS:{\"written\":2}"] {+ server_side.extend(framed(piece.as_bytes()));+ }+ server_side.extend(b"0\r\n\r\n");+ // Decode by hand.+ let mut i = 0;+ let mut body = Vec::new();+ loop {+ let nl = server_side[i..].windows(2).position(|w| w == b"\r\n").unwrap() + i;+ let n = usize::from_str_radix(std::str::from_utf8(&server_side[i..nl]).unwrap(), 16).unwrap();+ if n == 0 {+ break;+ }+ body.extend_from_slice(&server_side[nl + 2..nl + 2 + n]);+ assert_eq!(&server_side[nl + 2 + n..nl + 4 + n], b"\r\n");+ i = nl + 4 + n;+ }+ let text = String::from_utf8(body).unwrap();+ let k = text.find(crate::chat::STATS_MARK).unwrap();+ assert_eq!(&text[..k], "Here's a");+ let stats: serde_json::Value = serde_json::from_str(&text[k + crate::chat::STATS_MARK.len()..]).unwrap();+ assert_eq!(stats["written"], 2);+}++#[allow(dead_code)]+fn _unused(_: &mut dyn Write) {}