Elffuss BraidHub

kikocis/coco public

coco: initial public release

Architecture-agnostic LLM inference + quantization engine in Rust.
4 architectures (Qwen2/3/MoE, DeepSeek-MLA), turboquant data-free 3-bit,
GatedDeltaNet validated to 1.8e-7. Honest about WIP (Qwen3.5 not yet runnable).
Changeset4c721ca078a4e757c80833e850ab47175e1ab06cf1d8b11d10518d335d4a7289
AuthorKikoCis <kikocisneros@gmail.com> · 2026-07-09 20:16 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-07-09 20:16 +02:00
ParentsNone: the first changeset

Browse the files at this changeset

23 files changed

added .gitignore +7 −0
@@ -0,0 +1,7 @@
1+/target
2+**/*.rs.bak*
3+*.gguf
4+*.safetensors
5+model/
6+model-*/
7+*.DS_Store
added Cargo.lock +2518 −0
@@ -0,0 +1,2518 @@
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 4
4+
5+[[package]]
6+name = "ahash"
7+version = "0.8.12"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
10+dependencies = [
11+ "cfg-if",
12+ "getrandom 0.3.4",
13+ "once_cell",
14+ "serde",
15+ "version_check",
16+ "zerocopy",
17+]
18+
19+[[package]]
20+name = "aho-corasick"
21+version = "1.1.4"
22+source = "registry+https://github.com/rust-lang/crates.io-index"
23+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
24+dependencies = [
25+ "memchr",
26+]
27+
28+[[package]]
29+name = "allocator-api2"
30+version = "0.2.21"
31+source = "registry+https://github.com/rust-lang/crates.io-index"
32+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
33+
34+[[package]]
35+name = "anstream"
36+version = "1.0.0"
37+source = "registry+https://github.com/rust-lang/crates.io-index"
38+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
39+dependencies = [
40+ "anstyle",
41+ "anstyle-parse",
42+ "anstyle-query",
43+ "anstyle-wincon",
44+ "colorchoice",
45+ "is_terminal_polyfill",
46+ "utf8parse",
47+]
48+
49+[[package]]
50+name = "anstyle"
51+version = "1.0.14"
52+source = "registry+https://github.com/rust-lang/crates.io-index"
53+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
54+
55+[[package]]
56+name = "anstyle-parse"
57+version = "1.0.0"
58+source = "registry+https://github.com/rust-lang/crates.io-index"
59+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
60+dependencies = [
61+ "utf8parse",
62+]
63+
64+[[package]]
65+name = "anstyle-query"
66+version = "1.1.5"
67+source = "registry+https://github.com/rust-lang/crates.io-index"
68+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
69+dependencies = [
70+ "windows-sys 0.61.2",
71+]
72+
73+[[package]]
74+name = "anstyle-wincon"
75+version = "3.0.11"
76+source = "registry+https://github.com/rust-lang/crates.io-index"
77+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
78+dependencies = [
79+ "anstyle",
80+ "once_cell_polyfill",
81+ "windows-sys 0.61.2",
82+]
83+
84+[[package]]
85+name = "anyhow"
86+version = "1.0.103"
87+source = "registry+https://github.com/rust-lang/crates.io-index"
88+checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
89+
90+[[package]]
91+name = "autocfg"
92+version = "1.5.1"
93+source = "registry+https://github.com/rust-lang/crates.io-index"
94+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
95+
96+[[package]]
97+name = "base64"
98+version = "0.13.1"
99+source = "registry+https://github.com/rust-lang/crates.io-index"
100+checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
101+
102+[[package]]
103+name = "bit-set"
104+version = "0.8.0"
105+source = "registry+https://github.com/rust-lang/crates.io-index"
106+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
107+dependencies = [
108+ "bit-vec",
109+]
110+
111+[[package]]
112+name = "bit-vec"
113+version = "0.8.0"
114+source = "registry+https://github.com/rust-lang/crates.io-index"
115+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
116+
117+[[package]]
118+name = "bitflags"
119+version = "1.3.2"
120+source = "registry+https://github.com/rust-lang/crates.io-index"
121+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
122+
123+[[package]]
124+name = "bitflags"
125+version = "2.13.0"
126+source = "registry+https://github.com/rust-lang/crates.io-index"
127+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
128+
129+[[package]]
130+name = "block"
131+version = "0.1.6"
132+source = "registry+https://github.com/rust-lang/crates.io-index"
133+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
134+
135+[[package]]
136+name = "block-buffer"
137+version = "0.10.4"
138+source = "registry+https://github.com/rust-lang/crates.io-index"
139+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
140+dependencies = [
141+ "generic-array",
142+]
143+
144+[[package]]
145+name = "block2"
146+version = "0.6.2"
147+source = "registry+https://github.com/rust-lang/crates.io-index"
148+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
149+dependencies = [
150+ "objc2",
151+]
152+
153+[[package]]
154+name = "bumpalo"
155+version = "3.20.3"
156+source = "registry+https://github.com/rust-lang/crates.io-index"
157+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
158+
159+[[package]]
160+name = "bytemuck"
161+version = "1.25.0"
162+source = "registry+https://github.com/rust-lang/crates.io-index"
163+checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"
164+dependencies = [
165+ "bytemuck_derive",
166+]
167+
168+[[package]]
169+name = "bytemuck_derive"
170+version = "1.10.2"
171+source = "registry+https://github.com/rust-lang/crates.io-index"
172+checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"
173+dependencies = [
174+ "proc-macro2",
175+ "quote",
176+ "syn",
177+]
178+
179+[[package]]
180+name = "byteorder"
181+version = "1.5.0"
182+source = "registry+https://github.com/rust-lang/crates.io-index"
183+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
184+
185+[[package]]
186+name = "candle-core"
187+version = "0.11.0"
188+source = "registry+https://github.com/rust-lang/crates.io-index"
189+checksum = "5ecb245093b0f791b89d3420c3df9c6d49c60ab63ba54db896bf8a3baf486706"
190+dependencies = [
191+ "byteorder",
192+ "candle-kernels",
193+ "candle-metal-kernels",
194+ "candle-ug",
195+ "cudarc 0.19.8",
196+ "float8",
197+ "gemm 0.19.0",
198+ "half",
199+ "libc",
200+ "libm",
201+ "memmap2",
202+ "num-traits",
203+ "num_cpus",
204+ "objc2-foundation",
205+ "objc2-metal",
206+ "rand",
207+ "rand_distr",
208+ "rayon",
209+ "safetensors 0.8.0",
210+ "thiserror 2.0.18",
211+ "tokenizers 0.22.2",
212+ "yoke 0.8.3",
213+ "zerocopy",
214+ "zip",
215+]
216+
217+[[package]]
218+name = "candle-kernels"
219+version = "0.11.0"
220+source = "registry+https://github.com/rust-lang/crates.io-index"
221+checksum = "67450168a281bbb195a14cc85cf164c7a12023a54a03409a3324f476346e0789"
222+dependencies = [
223+ "cudaforge",
224+]
225+
226+[[package]]
227+name = "candle-metal-kernels"
228+version = "0.11.0"
229+source = "registry+https://github.com/rust-lang/crates.io-index"
230+checksum = "242e83c6acf639bb273c929d73c67a882bb4dd08a140f121096e19ba2f213d3e"
231+dependencies = [
232+ "block2",
233+ "half",
234+ "objc2",
235+ "objc2-foundation",
236+ "objc2-metal",
237+ "once_cell",
238+ "thiserror 2.0.18",
239+ "tracing",
240+]
241+
242+[[package]]
243+name = "candle-nn"
244+version = "0.11.0"
245+source = "registry+https://github.com/rust-lang/crates.io-index"
246+checksum = "eaa10b6ccc365b33210ce404fbf45e60d3e0bdac1004463cf1052e6ee1c1739a"
247+dependencies = [
248+ "candle-core",
249+ "candle-metal-kernels",
250+ "half",
251+ "libc",
252+ "num-traits",
253+ "objc2-metal",
254+ "rayon",
255+ "safetensors 0.8.0",
256+ "serde",
257+ "thiserror 2.0.18",
258+]
259+
260+[[package]]
261+name = "candle-transformers"
262+version = "0.11.0"
263+source = "registry+https://github.com/rust-lang/crates.io-index"
264+checksum = "3bcbbf7ff00ff6fe2af22b93600195917fe90e90ff48424a140d1a926c44b1c1"
265+dependencies = [
266+ "byteorder",
267+ "candle-core",
268+ "candle-nn",
269+ "fancy-regex",
270+ "num-traits",
271+ "rand",
272+ "rayon",
273+ "serde",
274+ "serde_json",
275+ "serde_plain",
276+ "tracing",
277+]
278+
279+[[package]]
280+name = "candle-ug"
281+version = "0.11.0"
282+source = "registry+https://github.com/rust-lang/crates.io-index"
283+checksum = "257411c33abf7d898a31ac20d80813dfe96ff09e23a73039e22ab293aea9b871"
284+dependencies = [
285+ "ug",
286+ "ug-cuda",
287+ "ug-metal",
288+]
289+
290+[[package]]
291+name = "castaway"
292+version = "0.2.4"
293+source = "registry+https://github.com/rust-lang/crates.io-index"
294+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
295+dependencies = [
296+ "rustversion",
297+]
298+
299+[[package]]
300+name = "cc"
301+version = "1.2.65"
302+source = "registry+https://github.com/rust-lang/crates.io-index"
303+checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96"
304+dependencies = [
305+ "find-msvc-tools",
306+ "shlex",
307+]
308+
309+[[package]]
310+name = "cfg-if"
311+version = "1.0.4"
312+source = "registry+https://github.com/rust-lang/crates.io-index"
313+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
314+
315+[[package]]
316+name = "clap"
317+version = "4.6.1"
318+source = "registry+https://github.com/rust-lang/crates.io-index"
319+checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
320+dependencies = [
321+ "clap_builder",
322+ "clap_derive",
323+]
324+
325+[[package]]
326+name = "clap_builder"
327+version = "4.6.0"
328+source = "registry+https://github.com/rust-lang/crates.io-index"
329+checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
330+dependencies = [
331+ "anstream",
332+ "anstyle",
333+ "clap_lex",
334+ "strsim",
335+]
336+
337+[[package]]
338+name = "clap_derive"
339+version = "4.6.1"
340+source = "registry+https://github.com/rust-lang/crates.io-index"
341+checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
342+dependencies = [
343+ "heck",
344+ "proc-macro2",
345+ "quote",
346+ "syn",
347+]
348+
349+[[package]]
350+name = "clap_lex"
351+version = "1.1.0"
352+source = "registry+https://github.com/rust-lang/crates.io-index"
353+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
354+
355+[[package]]
356+name = "coco-engine"
357+version = "0.1.0"
358+dependencies = [
359+ "anyhow",
360+ "candle-core",
361+ "candle-metal-kernels",
362+ "candle-nn",
363+ "candle-transformers",
364+ "clap",
365+ "half",
366+ "objc2",
367+ "objc2-metal",
368+ "regex",
369+ "serde",
370+ "serde_json",
371+ "tokenizers 0.21.4",
372+]
373+
374+[[package]]
375+name = "colorchoice"
376+version = "1.0.5"
377+source = "registry+https://github.com/rust-lang/crates.io-index"
378+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
379+
380+[[package]]
381+name = "compact_str"
382+version = "0.9.1"
383+source = "registry+https://github.com/rust-lang/crates.io-index"
384+checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"
385+dependencies = [
386+ "castaway",
387+ "cfg-if",
388+ "itoa",
389+ "rustversion",
390+ "ryu",
391+ "serde",
392+ "static_assertions",
393+]
394+
395+[[package]]
396+name = "console"
397+version = "0.15.11"
398+source = "registry+https://github.com/rust-lang/crates.io-index"
399+checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8"
400+dependencies = [
401+ "encode_unicode",
402+ "libc",
403+ "once_cell",
404+ "unicode-width",
405+ "windows-sys 0.59.0",
406+]
407+
408+[[package]]
409+name = "core-foundation"
410+version = "0.9.4"
411+source = "registry+https://github.com/rust-lang/crates.io-index"
412+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
413+dependencies = [
414+ "core-foundation-sys",
415+ "libc",
416+]
417+
418+[[package]]
419+name = "core-foundation-sys"
420+version = "0.8.7"
421+source = "registry+https://github.com/rust-lang/crates.io-index"
422+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
423+
424+[[package]]
425+name = "core-graphics-types"
426+version = "0.1.3"
427+source = "registry+https://github.com/rust-lang/crates.io-index"
428+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
429+dependencies = [
430+ "bitflags 1.3.2",
431+ "core-foundation",
432+ "libc",
433+]
434+
435+[[package]]
436+name = "cpufeatures"
437+version = "0.2.17"
438+source = "registry+https://github.com/rust-lang/crates.io-index"
439+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
440+dependencies = [
441+ "libc",
442+]
443+
444+[[package]]
445+name = "crc32fast"
446+version = "1.5.0"
447+source = "registry+https://github.com/rust-lang/crates.io-index"
448+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
449+dependencies = [
450+ "cfg-if",
451+]
452+
453+[[package]]
454+name = "crossbeam-deque"
455+version = "0.8.6"
456+source = "registry+https://github.com/rust-lang/crates.io-index"
457+checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
458+dependencies = [
459+ "crossbeam-epoch",
460+ "crossbeam-utils",
461+]
462+
463+[[package]]
464+name = "crossbeam-epoch"
465+version = "0.9.18"
466+source = "registry+https://github.com/rust-lang/crates.io-index"
467+checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
468+dependencies = [
469+ "crossbeam-utils",
470+]
471+
472+[[package]]
473+name = "crossbeam-utils"
474+version = "0.8.21"
475+source = "registry+https://github.com/rust-lang/crates.io-index"
476+checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
477+
478+[[package]]
479+name = "crunchy"
480+version = "0.2.4"
481+source = "registry+https://github.com/rust-lang/crates.io-index"
482+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
483+
484+[[package]]
485+name = "crypto-common"
486+version = "0.1.7"
487+source = "registry+https://github.com/rust-lang/crates.io-index"
488+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
489+dependencies = [
490+ "generic-array",
491+ "typenum",
492+]
493+
494+[[package]]
495+name = "cudaforge"
496+version = "0.1.6"
497+source = "registry+https://github.com/rust-lang/crates.io-index"
498+checksum = "8d475ff95b9e4096878f47fe0ca5dbad0e23849a79fc225305ea06c2f25771cd"
499+dependencies = [
500+ "anyhow",
501+ "fs2",
502+ "glob",
503+ "num_cpus",
504+ "rayon",
505+ "serde",
506+ "serde_json",
507+ "sha2",
508+ "thiserror 2.0.18",
509+ "walkdir",
510+ "which",
511+]
512+
513+[[package]]
514+name = "cudarc"
515+version = "0.17.8"
516+source = "registry+https://github.com/rust-lang/crates.io-index"
517+checksum = "0bf99ab37ee7072d64d906aa2dada9a3422f1d975cdf8c8055a573bc84897ed8"
518+dependencies = [
519+ "half",
520+ "libloading 0.8.9",
521+]
522+
523+[[package]]
524+name = "cudarc"
525+version = "0.19.8"
526+source = "registry+https://github.com/rust-lang/crates.io-index"
527+checksum = "42310153e06cf4cd532901f7096beb27504d681736a29ee90728ae4e2d93b2a8"
528+dependencies = [
529+ "float8",
530+ "half",
531+ "libloading 0.9.0",
532+]
533+
534+[[package]]
535+name = "darling"
536+version = "0.20.11"
537+source = "registry+https://github.com/rust-lang/crates.io-index"
538+checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
539+dependencies = [
540+ "darling_core",
541+ "darling_macro",
542+]
543+
544+[[package]]
545+name = "darling_core"
546+version = "0.20.11"
547+source = "registry+https://github.com/rust-lang/crates.io-index"
548+checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"
549+dependencies = [
550+ "fnv",
551+ "ident_case",
552+ "proc-macro2",
553+ "quote",
554+ "strsim",
555+ "syn",
556+]
557+
558+[[package]]
559+name = "darling_macro"
560+version = "0.20.11"
561+source = "registry+https://github.com/rust-lang/crates.io-index"
562+checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
563+dependencies = [
564+ "darling_core",
565+ "quote",
566+ "syn",
567+]
568+
569+[[package]]
570+name = "dary_heap"
571+version = "0.3.9"
572+source = "registry+https://github.com/rust-lang/crates.io-index"
573+checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe"
574+dependencies = [
575+ "serde",
576+]
577+
578+[[package]]
579+name = "derive_builder"
580+version = "0.20.2"
581+source = "registry+https://github.com/rust-lang/crates.io-index"
582+checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"
583+dependencies = [
584+ "derive_builder_macro",
585+]
586+
587+[[package]]
588+name = "derive_builder_core"
589+version = "0.20.2"
590+source = "registry+https://github.com/rust-lang/crates.io-index"
591+checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
592+dependencies = [
593+ "darling",
594+ "proc-macro2",
595+ "quote",
596+ "syn",
597+]
598+
599+[[package]]
600+name = "derive_builder_macro"
601+version = "0.20.2"
602+source = "registry+https://github.com/rust-lang/crates.io-index"
603+checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
604+dependencies = [
605+ "derive_builder_core",
606+ "syn",
607+]
608+
609+[[package]]
610+name = "digest"
611+version = "0.10.7"
612+source = "registry+https://github.com/rust-lang/crates.io-index"
613+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
614+dependencies = [
615+ "block-buffer",
616+ "crypto-common",
617+]
618+
619+[[package]]
620+name = "dispatch2"
621+version = "0.3.1"
622+source = "registry+https://github.com/rust-lang/crates.io-index"
623+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
624+dependencies = [
625+ "bitflags 2.13.0",
626+ "objc2",
627+]
628+
629+[[package]]
630+name = "dyn-stack"
631+version = "0.13.2"
632+source = "registry+https://github.com/rust-lang/crates.io-index"
633+checksum = "1c4713e43e2886ba72b8271aa66c93d722116acf7a75555cce11dcde84388fe8"
634+dependencies = [
635+ "bytemuck",
636+ "dyn-stack-macros",
637+]
638+
639+[[package]]
640+name = "dyn-stack-macros"
641+version = "0.1.3"
642+source = "registry+https://github.com/rust-lang/crates.io-index"
643+checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9"
644+
645+[[package]]
646+name = "either"
647+version = "1.16.0"
648+source = "registry+https://github.com/rust-lang/crates.io-index"
649+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
650+
651+[[package]]
652+name = "encode_unicode"
653+version = "1.0.0"
654+source = "registry+https://github.com/rust-lang/crates.io-index"
655+checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
656+
657+[[package]]
658+name = "enum-as-inner"
659+version = "0.6.1"
660+source = "registry+https://github.com/rust-lang/crates.io-index"
661+checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
662+dependencies = [
663+ "heck",
664+ "proc-macro2",
665+ "quote",
666+ "syn",
667+]
668+
669+[[package]]
670+name = "env_home"
671+version = "0.1.0"
672+source = "registry+https://github.com/rust-lang/crates.io-index"
673+checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
674+
675+[[package]]
676+name = "equivalent"
677+version = "1.0.2"
678+source = "registry+https://github.com/rust-lang/crates.io-index"
679+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
680+
681+[[package]]
682+name = "errno"
683+version = "0.3.14"
684+source = "registry+https://github.com/rust-lang/crates.io-index"
685+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
686+dependencies = [
687+ "libc",
688+ "windows-sys 0.61.2",
689+]
690+
691+[[package]]
692+name = "esaxx-rs"
693+version = "0.1.10"
694+source = "registry+https://github.com/rust-lang/crates.io-index"
695+checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6"
696+dependencies = [
697+ "cc",
698+]
699+
700+[[package]]
701+name = "fancy-regex"
702+version = "0.18.0"
703+source = "registry+https://github.com/rust-lang/crates.io-index"
704+checksum = "e1e1dacd0d2082dfcf1351c4bdd566bbe89a2b263235a2b50058f1e130a47277"
705+dependencies = [
706+ "bit-set",
707+ "regex-automata",
708+ "regex-syntax",
709+]
710+
711+[[package]]
712+name = "fastrand"
713+version = "2.4.1"
714+source = "registry+https://github.com/rust-lang/crates.io-index"
715+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
716+
717+[[package]]
718+name = "find-msvc-tools"
719+version = "0.1.9"
720+source = "registry+https://github.com/rust-lang/crates.io-index"
721+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
722+
723+[[package]]
724+name = "float8"
725+version = "0.7.0"
726+source = "registry+https://github.com/rust-lang/crates.io-index"
727+checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc"
728+dependencies = [
729+ "half",
730+ "num-traits",
731+ "rand",
732+ "rand_distr",
733+]
734+
735+[[package]]
736+name = "fnv"
737+version = "1.0.7"
738+source = "registry+https://github.com/rust-lang/crates.io-index"
739+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
740+
741+[[package]]
742+name = "foldhash"
743+version = "0.2.0"
744+source = "registry+https://github.com/rust-lang/crates.io-index"
745+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
746+
747+[[package]]
748+name = "foreign-types"
749+version = "0.5.0"
750+source = "registry+https://github.com/rust-lang/crates.io-index"
751+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
752+dependencies = [
753+ "foreign-types-macros",
754+ "foreign-types-shared",
755+]
756+
757+[[package]]
758+name = "foreign-types-macros"
759+version = "0.2.3"
760+source = "registry+https://github.com/rust-lang/crates.io-index"
761+checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742"
762+dependencies = [
763+ "proc-macro2",
764+ "quote",
765+ "syn",
766+]
767+
768+[[package]]
769+name = "foreign-types-shared"
770+version = "0.3.1"
771+source = "registry+https://github.com/rust-lang/crates.io-index"
772+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
773+
774+[[package]]
775+name = "fs2"
776+version = "0.4.3"
777+source = "registry+https://github.com/rust-lang/crates.io-index"
778+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
779+dependencies = [
780+ "libc",
781+ "winapi",
782+]
783+
784+[[package]]
785+name = "futures-core"
786+version = "0.3.32"
787+source = "registry+https://github.com/rust-lang/crates.io-index"
788+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
789+
790+[[package]]
791+name = "futures-task"
792+version = "0.3.32"
793+source = "registry+https://github.com/rust-lang/crates.io-index"
794+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
795+
796+[[package]]
797+name = "futures-util"
798+version = "0.3.32"
799+source = "registry+https://github.com/rust-lang/crates.io-index"
800+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
801+dependencies = [
802+ "futures-core",
803+ "futures-task",
804+ "pin-project-lite",
805+ "slab",
806+]
807+
808+[[package]]
809+name = "gemm"
810+version = "0.18.2"
811+source = "registry+https://github.com/rust-lang/crates.io-index"
812+checksum = "ab96b703d31950f1aeddded248bc95543c9efc7ac9c4a21fda8703a83ee35451"
813+dependencies = [
814+ "dyn-stack",
815+ "gemm-c32 0.18.2",
816+ "gemm-c64 0.18.2",
817+ "gemm-common 0.18.2",
818+ "gemm-f16 0.18.2",
819+ "gemm-f32 0.18.2",
820+ "gemm-f64 0.18.2",
821+ "num-complex",
822+ "num-traits",
823+ "paste",
824+ "raw-cpuid",
825+ "seq-macro",
826+]
827+
828+[[package]]
829+name = "gemm"
830+version = "0.19.0"
831+source = "registry+https://github.com/rust-lang/crates.io-index"
832+checksum = "aa0673db364b12263d103b68337a68fbecc541d6f6b61ba72fe438654709eacb"
833+dependencies = [
834+ "dyn-stack",
835+ "gemm-c32 0.19.0",
836+ "gemm-c64 0.19.0",
837+ "gemm-common 0.19.0",
838+ "gemm-f16 0.19.0",
839+ "gemm-f32 0.19.0",
840+ "gemm-f64 0.19.0",
841+ "num-complex",
842+ "num-traits",
843+ "paste",
844+ "raw-cpuid",
845+ "seq-macro",
846+]
847+
848+[[package]]
849+name = "gemm-c32"
850+version = "0.18.2"
851+source = "registry+https://github.com/rust-lang/crates.io-index"
852+checksum = "f6db9fd9f40421d00eea9dd0770045a5603b8d684654816637732463f4073847"
853+dependencies = [
854+ "dyn-stack",
855+ "gemm-common 0.18.2",
856+ "num-complex",
857+ "num-traits",
858+ "paste",
859+ "raw-cpuid",
860+ "seq-macro",
861+]
862+
863+[[package]]
864+name = "gemm-c32"
865+version = "0.19.0"
866+source = "registry+https://github.com/rust-lang/crates.io-index"
867+checksum = "086936dbdcb99e37aad81d320f98f670e53c1e55a98bee70573e83f95beb128c"
868+dependencies = [
869+ "dyn-stack",
870+ "gemm-common 0.19.0",
871+ "num-complex",
872+ "num-traits",
873+ "paste",
874+ "raw-cpuid",
875+ "seq-macro",
876+]
877+
878+[[package]]
879+name = "gemm-c64"
880+version = "0.18.2"
881+source = "registry+https://github.com/rust-lang/crates.io-index"
882+checksum = "dfcad8a3d35a43758330b635d02edad980c1e143dc2f21e6fd25f9e4eada8edf"
883+dependencies = [
884+ "dyn-stack",
885+ "gemm-common 0.18.2",
886+ "num-complex",
887+ "num-traits",
888+ "paste",
889+ "raw-cpuid",
890+ "seq-macro",
891+]
892+
893+[[package]]
894+name = "gemm-c64"
895+version = "0.19.0"
896+source = "registry+https://github.com/rust-lang/crates.io-index"
897+checksum = "20c8aeeeec425959bda4d9827664029ba1501a90a0d1e6228e48bef741db3a3f"
898+dependencies = [
899+ "dyn-stack",
900+ "gemm-common 0.19.0",
901+ "num-complex",
902+ "num-traits",
903+ "paste",
904+ "raw-cpuid",
905+ "seq-macro",
906+]
907+
908+[[package]]
909+name = "gemm-common"
910+version = "0.18.2"
911+source = "registry+https://github.com/rust-lang/crates.io-index"
912+checksum = "a352d4a69cbe938b9e2a9cb7a3a63b7e72f9349174a2752a558a8a563510d0f3"
913+dependencies = [
914+ "bytemuck",
915+ "dyn-stack",
916+ "half",
917+ "libm",
918+ "num-complex",
919+ "num-traits",
920+ "once_cell",
921+ "paste",
922+ "pulp 0.21.5",
923+ "raw-cpuid",
924+ "rayon",
925+ "seq-macro",
926+ "sysctl",
927+]
928+
929+[[package]]
930+name = "gemm-common"
931+version = "0.19.0"
932+source = "registry+https://github.com/rust-lang/crates.io-index"
933+checksum = "88027625910cc9b1085aaaa1c4bc46bb3a36aad323452b33c25b5e4e7c8e2a3e"
934+dependencies = [
935+ "bytemuck",
936+ "dyn-stack",
937+ "half",
938+ "libm",
939+ "num-complex",
940+ "num-traits",
941+ "once_cell",
942+ "paste",
943+ "pulp 0.22.3",
944+ "raw-cpuid",
945+ "rayon",
946+ "seq-macro",
947+ "sysctl",
948+]
949+
950+[[package]]
951+name = "gemm-f16"
952+version = "0.18.2"
953+source = "registry+https://github.com/rust-lang/crates.io-index"
954+checksum = "cff95ae3259432f3c3410eaa919033cd03791d81cebd18018393dc147952e109"
955+dependencies = [
956+ "dyn-stack",
957+ "gemm-common 0.18.2",
958+ "gemm-f32 0.18.2",
959+ "half",
960+ "num-complex",
961+ "num-traits",
962+ "paste",
963+ "raw-cpuid",
964+ "rayon",
965+ "seq-macro",
966+]
967+
968+[[package]]
969+name = "gemm-f16"
970+version = "0.19.0"
971+source = "registry+https://github.com/rust-lang/crates.io-index"
972+checksum = "e3df7a55202e6cd6739d82ae3399c8e0c7e1402859b30e4cb780e61525d9486e"
973+dependencies = [
974+ "dyn-stack",
975+ "gemm-common 0.19.0",
976+ "gemm-f32 0.19.0",
977+ "half",
978+ "num-complex",
979+ "num-traits",
980+ "paste",
981+ "raw-cpuid",
982+ "rayon",
983+ "seq-macro",
984+]
985+
986+[[package]]
987+name = "gemm-f32"
988+version = "0.18.2"
989+source = "registry+https://github.com/rust-lang/crates.io-index"
990+checksum = "bc8d3d4385393304f407392f754cd2dc4b315d05063f62cf09f47b58de276864"
991+dependencies = [
992+ "dyn-stack",
993+ "gemm-common 0.18.2",
994+ "num-complex",
995+ "num-traits",
996+ "paste",
997+ "raw-cpuid",
998+ "seq-macro",
999+]
1000+
1001+[[package]]
1002+name = "gemm-f32"
1003+version = "0.19.0"
1004+source = "registry+https://github.com/rust-lang/crates.io-index"
1005+checksum = "02e0b8c9da1fbec6e3e3ab2ce6bc259ef18eb5f6f0d3e4edf54b75f9fd41a81c"
1006+dependencies = [
1007+ "dyn-stack",
1008+ "gemm-common 0.19.0",
1009+ "num-complex",
1010+ "num-traits",
1011+ "paste",
1012+ "raw-cpuid",
1013+ "seq-macro",
1014+]
1015+
1016+[[package]]
1017+name = "gemm-f64"
1018+version = "0.18.2"
1019+source = "registry+https://github.com/rust-lang/crates.io-index"
1020+checksum = "35b2a4f76ce4b8b16eadc11ccf2e083252d8237c1b589558a49b0183545015bd"
1021+dependencies = [
1022+ "dyn-stack",
1023+ "gemm-common 0.18.2",
1024+ "num-complex",
1025+ "num-traits",
1026+ "paste",
1027+ "raw-cpuid",
1028+ "seq-macro",
1029+]
1030+
1031+[[package]]
1032+name = "gemm-f64"
1033+version = "0.19.0"
1034+source = "registry+https://github.com/rust-lang/crates.io-index"
1035+checksum = "056131e8f2a521bfab322f804ccd652520c79700d81209e9d9275bbdecaadc6a"
1036+dependencies = [
1037+ "dyn-stack",
1038+ "gemm-common 0.19.0",
1039+ "num-complex",
1040+ "num-traits",
1041+ "paste",
1042+ "raw-cpuid",
1043+ "seq-macro",
1044+]
1045+
1046+[[package]]
1047+name = "generic-array"
1048+version = "0.14.7"
1049+source = "registry+https://github.com/rust-lang/crates.io-index"
1050+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
1051+dependencies = [
1052+ "typenum",
1053+ "version_check",
1054+]
1055+
1056+[[package]]
1057+name = "getrandom"
1058+version = "0.3.4"
1059+source = "registry+https://github.com/rust-lang/crates.io-index"
1060+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
1061+dependencies = [
1062+ "cfg-if",
1063+ "libc",
1064+ "r-efi 5.3.0",
1065+ "wasip2",
1066+]
1067+
1068+[[package]]
1069+name = "getrandom"
1070+version = "0.4.3"
1071+source = "registry+https://github.com/rust-lang/crates.io-index"
1072+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
1073+dependencies = [
1074+ "cfg-if",
1075+ "libc",
1076+ "r-efi 6.0.0",
1077+]
1078+
1079+[[package]]
1080+name = "glob"
1081+version = "0.3.3"
1082+source = "registry+https://github.com/rust-lang/crates.io-index"
1083+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
1084+
1085+[[package]]
1086+name = "half"
1087+version = "2.7.1"
1088+source = "registry+https://github.com/rust-lang/crates.io-index"
1089+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
1090+dependencies = [
1091+ "bytemuck",
1092+ "cfg-if",
1093+ "crunchy",
1094+ "num-traits",
1095+ "rand",
1096+ "rand_distr",
1097+ "zerocopy",
1098+]
1099+
1100+[[package]]
1101+name = "hashbrown"
1102+version = "0.16.1"
1103+source = "registry+https://github.com/rust-lang/crates.io-index"
1104+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
1105+dependencies = [
1106+ "allocator-api2",
1107+ "equivalent",
1108+ "foldhash",
1109+ "serde",
1110+ "serde_core",
1111+]
1112+
1113+[[package]]
1114+name = "hashbrown"
1115+version = "0.17.1"
1116+source = "registry+https://github.com/rust-lang/crates.io-index"
1117+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
1118+
1119+[[package]]
1120+name = "heck"
1121+version = "0.5.0"
1122+source = "registry+https://github.com/rust-lang/crates.io-index"
1123+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
1124+
1125+[[package]]
1126+name = "hermit-abi"
1127+version = "0.5.2"
1128+source = "registry+https://github.com/rust-lang/crates.io-index"
1129+checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
1130+
1131+[[package]]
1132+name = "ident_case"
1133+version = "1.0.1"
1134+source = "registry+https://github.com/rust-lang/crates.io-index"
1135+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
1136+
1137+[[package]]
1138+name = "indexmap"
1139+version = "2.14.0"
1140+source = "registry+https://github.com/rust-lang/crates.io-index"
1141+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
1142+dependencies = [
1143+ "equivalent",
1144+ "hashbrown 0.17.1",
1145+]
1146+
1147+[[package]]
1148+name = "indicatif"
1149+version = "0.17.11"
1150+source = "registry+https://github.com/rust-lang/crates.io-index"
1151+checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235"
1152+dependencies = [
1153+ "console",
1154+ "number_prefix",
1155+ "portable-atomic",
1156+ "unicode-width",
1157+ "web-time",
1158+]
1159+
1160+[[package]]
1161+name = "is_terminal_polyfill"
1162+version = "1.70.2"
1163+source = "registry+https://github.com/rust-lang/crates.io-index"
1164+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
1165+
1166+[[package]]
1167+name = "itertools"
1168+version = "0.14.0"
1169+source = "registry+https://github.com/rust-lang/crates.io-index"
1170+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
1171+dependencies = [
1172+ "either",
1173+]
1174+
1175+[[package]]
1176+name = "itoa"
1177+version = "1.0.18"
1178+source = "registry+https://github.com/rust-lang/crates.io-index"
1179+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
1180+
1181+[[package]]
1182+name = "js-sys"
1183+version = "0.3.103"
1184+source = "registry+https://github.com/rust-lang/crates.io-index"
1185+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"
1186+dependencies = [
1187+ "cfg-if",
1188+ "futures-util",
1189+ "wasm-bindgen",
1190+]
1191+
1192+[[package]]
1193+name = "libc"
1194+version = "0.2.186"
1195+source = "registry+https://github.com/rust-lang/crates.io-index"
1196+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
1197+
1198+[[package]]
1199+name = "libloading"
1200+version = "0.8.9"
1201+source = "registry+https://github.com/rust-lang/crates.io-index"
1202+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
1203+dependencies = [
1204+ "cfg-if",
1205+ "windows-link",
1206+]
1207+
1208+[[package]]
1209+name = "libloading"
1210+version = "0.9.0"
1211+source = "registry+https://github.com/rust-lang/crates.io-index"
1212+checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60"
1213+dependencies = [
1214+ "cfg-if",
1215+ "windows-link",
1216+]
1217+
1218+[[package]]
1219+name = "libm"
1220+version = "0.2.16"
1221+source = "registry+https://github.com/rust-lang/crates.io-index"
1222+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
1223+
1224+[[package]]
1225+name = "linux-raw-sys"
1226+version = "0.12.1"
1227+source = "registry+https://github.com/rust-lang/crates.io-index"
1228+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
1229+
1230+[[package]]
1231+name = "log"
1232+version = "0.4.33"
1233+source = "registry+https://github.com/rust-lang/crates.io-index"
1234+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
1235+
1236+[[package]]
1237+name = "macro_rules_attribute"
1238+version = "0.2.2"
1239+source = "registry+https://github.com/rust-lang/crates.io-index"
1240+checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520"
1241+dependencies = [
1242+ "macro_rules_attribute-proc_macro",
1243+ "paste",
1244+]
1245+
1246+[[package]]
1247+name = "macro_rules_attribute-proc_macro"
1248+version = "0.2.2"
1249+source = "registry+https://github.com/rust-lang/crates.io-index"
1250+checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30"
1251+
1252+[[package]]
1253+name = "malloc_buf"
1254+version = "0.0.6"
1255+source = "registry+https://github.com/rust-lang/crates.io-index"
1256+checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
1257+dependencies = [
1258+ "libc",
1259+]
1260+
1261+[[package]]
1262+name = "memchr"
1263+version = "2.8.2"
1264+source = "registry+https://github.com/rust-lang/crates.io-index"
1265+checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"
1266+
1267+[[package]]
1268+name = "memmap2"
1269+version = "0.9.11"
1270+source = "registry+https://github.com/rust-lang/crates.io-index"
1271+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
1272+dependencies = [
1273+ "libc",
1274+ "stable_deref_trait",
1275+]
1276+
1277+[[package]]
1278+name = "metal"
1279+version = "0.29.0"
1280+source = "registry+https://github.com/rust-lang/crates.io-index"
1281+checksum = "7ecfd3296f8c56b7c1f6fbac3c71cefa9d78ce009850c45000015f206dc7fa21"
1282+dependencies = [
1283+ "bitflags 2.13.0",
1284+ "block",
1285+ "core-graphics-types",
1286+ "foreign-types",
1287+ "log",
1288+ "objc",
1289+ "paste",
1290+]
1291+
1292+[[package]]
1293+name = "minimal-lexical"
1294+version = "0.2.1"
1295+source = "registry+https://github.com/rust-lang/crates.io-index"
1296+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
1297+
1298+[[package]]
1299+name = "monostate"
1300+version = "0.1.18"
1301+source = "registry+https://github.com/rust-lang/crates.io-index"
1302+checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67"
1303+dependencies = [
1304+ "monostate-impl",
1305+ "serde",
1306+ "serde_core",
1307+]
1308+
1309+[[package]]
1310+name = "monostate-impl"
1311+version = "0.1.18"
1312+source = "registry+https://github.com/rust-lang/crates.io-index"
1313+checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9"
1314+dependencies = [
1315+ "proc-macro2",
1316+ "quote",
1317+ "syn",
1318+]
1319+
1320+[[package]]
1321+name = "nom"
1322+version = "7.1.3"
1323+source = "registry+https://github.com/rust-lang/crates.io-index"
1324+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
1325+dependencies = [
1326+ "memchr",
1327+ "minimal-lexical",
1328+]
1329+
1330+[[package]]
1331+name = "num"
1332+version = "0.4.3"
1333+source = "registry+https://github.com/rust-lang/crates.io-index"
1334+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
1335+dependencies = [
1336+ "num-bigint",
1337+ "num-complex",
1338+ "num-integer",
1339+ "num-iter",
1340+ "num-rational",
1341+ "num-traits",
1342+]
1343+
1344+[[package]]
1345+name = "num-bigint"
1346+version = "0.4.6"
1347+source = "registry+https://github.com/rust-lang/crates.io-index"
1348+checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
1349+dependencies = [
1350+ "num-integer",
1351+ "num-traits",
1352+]
1353+
1354+[[package]]
1355+name = "num-complex"
1356+version = "0.4.6"
1357+source = "registry+https://github.com/rust-lang/crates.io-index"
1358+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
1359+dependencies = [
1360+ "bytemuck",
1361+ "num-traits",
1362+]
1363+
1364+[[package]]
1365+name = "num-integer"
1366+version = "0.1.46"
1367+source = "registry+https://github.com/rust-lang/crates.io-index"
1368+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
1369+dependencies = [
1370+ "num-traits",
1371+]
1372+
1373+[[package]]
1374+name = "num-iter"
1375+version = "0.1.45"
1376+source = "registry+https://github.com/rust-lang/crates.io-index"
1377+checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
1378+dependencies = [
1379+ "autocfg",
1380+ "num-integer",
1381+ "num-traits",
1382+]
1383+
1384+[[package]]
1385+name = "num-rational"
1386+version = "0.4.2"
1387+source = "registry+https://github.com/rust-lang/crates.io-index"
1388+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
1389+dependencies = [
1390+ "num-bigint",
1391+ "num-integer",
1392+ "num-traits",
1393+]
1394+
1395+[[package]]
1396+name = "num-traits"
1397+version = "0.2.19"
1398+source = "registry+https://github.com/rust-lang/crates.io-index"
1399+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
1400+dependencies = [
1401+ "autocfg",
1402+ "libm",
1403+]
1404+
1405+[[package]]
1406+name = "num_cpus"
1407+version = "1.17.0"
1408+source = "registry+https://github.com/rust-lang/crates.io-index"
1409+checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
1410+dependencies = [
1411+ "hermit-abi",
1412+ "libc",
1413+]
1414+
1415+[[package]]
1416+name = "number_prefix"
1417+version = "0.4.0"
1418+source = "registry+https://github.com/rust-lang/crates.io-index"
1419+checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
1420+
1421+[[package]]
1422+name = "objc"
1423+version = "0.2.7"
1424+source = "registry+https://github.com/rust-lang/crates.io-index"
1425+checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
1426+dependencies = [
1427+ "malloc_buf",
1428+]
1429+
1430+[[package]]
1431+name = "objc2"
1432+version = "0.6.4"
1433+source = "registry+https://github.com/rust-lang/crates.io-index"
1434+checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
1435+dependencies = [
1436+ "objc2-encode",
1437+]
1438+
1439+[[package]]
1440+name = "objc2-core-foundation"
1441+version = "0.3.2"
1442+source = "registry+https://github.com/rust-lang/crates.io-index"
1443+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
1444+dependencies = [
1445+ "bitflags 2.13.0",
1446+ "dispatch2",
1447+ "objc2",
1448+]
1449+
1450+[[package]]
1451+name = "objc2-encode"
1452+version = "4.1.0"
1453+source = "registry+https://github.com/rust-lang/crates.io-index"
1454+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
1455+
1456+[[package]]
1457+name = "objc2-foundation"
1458+version = "0.3.2"
1459+source = "registry+https://github.com/rust-lang/crates.io-index"
1460+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
1461+dependencies = [
1462+ "bitflags 2.13.0",
1463+ "block2",
1464+ "libc",
1465+ "objc2",
1466+ "objc2-core-foundation",
1467+]
1468+
1469+[[package]]
1470+name = "objc2-metal"
1471+version = "0.3.2"
1472+source = "registry+https://github.com/rust-lang/crates.io-index"
1473+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
1474+dependencies = [
1475+ "bitflags 2.13.0",
1476+ "block2",
1477+ "dispatch2",
1478+ "objc2",
1479+ "objc2-core-foundation",
1480+ "objc2-foundation",
1481+]
1482+
1483+[[package]]
1484+name = "once_cell"
1485+version = "1.21.4"
1486+source = "registry+https://github.com/rust-lang/crates.io-index"
1487+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
1488+
1489+[[package]]
1490+name = "once_cell_polyfill"
1491+version = "1.70.2"
1492+source = "registry+https://github.com/rust-lang/crates.io-index"
1493+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
1494+
1495+[[package]]
1496+name = "onig"
1497+version = "6.5.3"
1498+source = "registry+https://github.com/rust-lang/crates.io-index"
1499+checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2"
1500+dependencies = [
1501+ "bitflags 2.13.0",
1502+ "libc",
1503+ "once_cell",
1504+ "onig_sys",
1505+]
1506+
1507+[[package]]
1508+name = "onig_sys"
1509+version = "69.9.3"
1510+source = "registry+https://github.com/rust-lang/crates.io-index"
1511+checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7"
1512+dependencies = [
1513+ "cc",
1514+ "pkg-config",
1515+]
1516+
1517+[[package]]
1518+name = "paste"
1519+version = "1.0.15"
1520+source = "registry+https://github.com/rust-lang/crates.io-index"
1521+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
1522+
1523+[[package]]
1524+name = "pin-project-lite"
1525+version = "0.2.17"
1526+source = "registry+https://github.com/rust-lang/crates.io-index"
1527+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
1528+
1529+[[package]]
1530+name = "pkg-config"
1531+version = "0.3.33"
1532+source = "registry+https://github.com/rust-lang/crates.io-index"
1533+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
1534+
1535+[[package]]
1536+name = "portable-atomic"
1537+version = "1.13.1"
1538+source = "registry+https://github.com/rust-lang/crates.io-index"
1539+checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
1540+
1541+[[package]]
1542+name = "ppv-lite86"
1543+version = "0.2.21"
1544+source = "registry+https://github.com/rust-lang/crates.io-index"
1545+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
1546+dependencies = [
1547+ "zerocopy",
1548+]
1549+
1550+[[package]]
1551+name = "proc-macro2"
1552+version = "1.0.106"
1553+source = "registry+https://github.com/rust-lang/crates.io-index"
1554+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
1555+dependencies = [
1556+ "unicode-ident",
1557+]
1558+
1559+[[package]]
1560+name = "pulp"
1561+version = "0.21.5"
1562+source = "registry+https://github.com/rust-lang/crates.io-index"
1563+checksum = "96b86df24f0a7ddd5e4b95c94fc9ed8a98f1ca94d3b01bdce2824097e7835907"
1564+dependencies = [
1565+ "bytemuck",
1566+ "cfg-if",
1567+ "libm",
1568+ "num-complex",
1569+ "reborrow",
1570+ "version_check",
1571+]
1572+
1573+[[package]]
1574+name = "pulp"
1575+version = "0.22.3"
1576+source = "registry+https://github.com/rust-lang/crates.io-index"
1577+checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a"
1578+dependencies = [
1579+ "bytemuck",
1580+ "cfg-if",
1581+ "libm",
1582+ "num-complex",
1583+ "paste",
1584+ "pulp-wasm-simd-flag",
1585+ "raw-cpuid",
1586+ "reborrow",
1587+ "version_check",
1588+]
1589+
1590+[[package]]
1591+name = "pulp-wasm-simd-flag"
1592+version = "0.1.1"
1593+source = "registry+https://github.com/rust-lang/crates.io-index"
1594+checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740"
1595+
1596+[[package]]
1597+name = "quote"
1598+version = "1.0.46"
1599+source = "registry+https://github.com/rust-lang/crates.io-index"
1600+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
1601+dependencies = [
1602+ "proc-macro2",
1603+]
1604+
1605+[[package]]
1606+name = "r-efi"
1607+version = "5.3.0"
1608+source = "registry+https://github.com/rust-lang/crates.io-index"
1609+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
1610+
1611+[[package]]
1612+name = "r-efi"
1613+version = "6.0.0"
1614+source = "registry+https://github.com/rust-lang/crates.io-index"
1615+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
1616+
1617+[[package]]
1618+name = "rand"
1619+version = "0.9.4"
1620+source = "registry+https://github.com/rust-lang/crates.io-index"
1621+checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
1622+dependencies = [
1623+ "rand_chacha",
1624+ "rand_core",
1625+]
1626+
1627+[[package]]
1628+name = "rand_chacha"
1629+version = "0.9.0"
1630+source = "registry+https://github.com/rust-lang/crates.io-index"
1631+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
1632+dependencies = [
1633+ "ppv-lite86",
1634+ "rand_core",
1635+]
1636+
1637+[[package]]
1638+name = "rand_core"
1639+version = "0.9.5"
1640+source = "registry+https://github.com/rust-lang/crates.io-index"
1641+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
1642+dependencies = [
1643+ "getrandom 0.3.4",
1644+]
1645+
1646+[[package]]
1647+name = "rand_distr"
1648+version = "0.5.1"
1649+source = "registry+https://github.com/rust-lang/crates.io-index"
1650+checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463"
1651+dependencies = [
1652+ "num-traits",
1653+ "rand",
1654+]
1655+
1656+[[package]]
1657+name = "raw-cpuid"
1658+version = "11.6.0"
1659+source = "registry+https://github.com/rust-lang/crates.io-index"
1660+checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"
1661+dependencies = [
1662+ "bitflags 2.13.0",
1663+]
1664+
1665+[[package]]
1666+name = "rayon"
1667+version = "1.12.0"
1668+source = "registry+https://github.com/rust-lang/crates.io-index"
1669+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
1670+dependencies = [
1671+ "either",
1672+ "rayon-core",
1673+]
1674+
1675+[[package]]
1676+name = "rayon-cond"
1677+version = "0.4.0"
1678+source = "registry+https://github.com/rust-lang/crates.io-index"
1679+checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f"
1680+dependencies = [
1681+ "either",
1682+ "itertools",
1683+ "rayon",
1684+]
1685+
1686+[[package]]
1687+name = "rayon-core"
1688+version = "1.13.0"
1689+source = "registry+https://github.com/rust-lang/crates.io-index"
1690+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
1691+dependencies = [
1692+ "crossbeam-deque",
1693+ "crossbeam-utils",
1694+]
1695+
1696+[[package]]
1697+name = "reborrow"
1698+version = "0.5.5"
1699+source = "registry+https://github.com/rust-lang/crates.io-index"
1700+checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"
1701+
1702+[[package]]
1703+name = "regex"
1704+version = "1.12.4"
1705+source = "registry+https://github.com/rust-lang/crates.io-index"
1706+checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba"
1707+dependencies = [
1708+ "aho-corasick",
1709+ "memchr",
1710+ "regex-automata",
1711+ "regex-syntax",
1712+]
1713+
1714+[[package]]
1715+name = "regex-automata"
1716+version = "0.4.14"
1717+source = "registry+https://github.com/rust-lang/crates.io-index"
1718+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
1719+dependencies = [
1720+ "aho-corasick",
1721+ "memchr",
1722+ "regex-syntax",
1723+]
1724+
1725+[[package]]
1726+name = "regex-syntax"
1727+version = "0.8.11"
1728+source = "registry+https://github.com/rust-lang/crates.io-index"
1729+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
1730+
1731+[[package]]
1732+name = "rustix"
1733+version = "1.1.4"
1734+source = "registry+https://github.com/rust-lang/crates.io-index"
1735+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
1736+dependencies = [
1737+ "bitflags 2.13.0",
1738+ "errno",
1739+ "libc",
1740+ "linux-raw-sys",
1741+ "windows-sys 0.61.2",
1742+]
1743+
1744+[[package]]
1745+name = "rustversion"
1746+version = "1.0.22"
1747+source = "registry+https://github.com/rust-lang/crates.io-index"
1748+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
1749+
1750+[[package]]
1751+name = "ryu"
1752+version = "1.0.23"
1753+source = "registry+https://github.com/rust-lang/crates.io-index"
1754+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
1755+
1756+[[package]]
1757+name = "safetensors"
1758+version = "0.4.5"
1759+source = "registry+https://github.com/rust-lang/crates.io-index"
1760+checksum = "44560c11236a6130a46ce36c836a62936dc81ebf8c36a37947423571be0e55b6"
1761+dependencies = [
1762+ "serde",
1763+ "serde_json",
1764+]
1765+
1766+[[package]]
1767+name = "safetensors"
1768+version = "0.8.0"
1769+source = "registry+https://github.com/rust-lang/crates.io-index"
1770+checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846"
1771+dependencies = [
1772+ "hashbrown 0.16.1",
1773+ "libc",
1774+ "serde",
1775+ "serde_json",
1776+ "tempfile",
1777+]
1778+
1779+[[package]]
1780+name = "same-file"
1781+version = "1.0.6"
1782+source = "registry+https://github.com/rust-lang/crates.io-index"
1783+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
1784+dependencies = [
1785+ "winapi-util",
1786+]
1787+
1788+[[package]]
1789+name = "seq-macro"
1790+version = "0.3.6"
1791+source = "registry+https://github.com/rust-lang/crates.io-index"
1792+checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
1793+
1794+[[package]]
1795+name = "serde"
1796+version = "1.0.228"
1797+source = "registry+https://github.com/rust-lang/crates.io-index"
1798+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
1799+dependencies = [
1800+ "serde_core",
1801+ "serde_derive",
1802+]
1803+
1804+[[package]]
1805+name = "serde_core"
1806+version = "1.0.228"
1807+source = "registry+https://github.com/rust-lang/crates.io-index"
1808+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
1809+dependencies = [
1810+ "serde_derive",
1811+]
1812+
1813+[[package]]
1814+name = "serde_derive"
1815+version = "1.0.228"
1816+source = "registry+https://github.com/rust-lang/crates.io-index"
1817+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
1818+dependencies = [
1819+ "proc-macro2",
1820+ "quote",
1821+ "syn",
1822+]
1823+
1824+[[package]]
1825+name = "serde_json"
1826+version = "1.0.150"
1827+source = "registry+https://github.com/rust-lang/crates.io-index"
1828+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
1829+dependencies = [
1830+ "itoa",
1831+ "memchr",
1832+ "serde",
1833+ "serde_core",
1834+ "zmij",
1835+]
1836+
1837+[[package]]
1838+name = "serde_plain"
1839+version = "1.0.2"
1840+source = "registry+https://github.com/rust-lang/crates.io-index"
1841+checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50"
1842+dependencies = [
1843+ "serde",
1844+]
1845+
1846+[[package]]
1847+name = "sha2"
1848+version = "0.10.9"
1849+source = "registry+https://github.com/rust-lang/crates.io-index"
1850+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
1851+dependencies = [
1852+ "cfg-if",
1853+ "cpufeatures",
1854+ "digest",
1855+]
1856+
1857+[[package]]
1858+name = "shlex"
1859+version = "2.0.1"
1860+source = "registry+https://github.com/rust-lang/crates.io-index"
1861+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
1862+
1863+[[package]]
1864+name = "slab"
1865+version = "0.4.12"
1866+source = "registry+https://github.com/rust-lang/crates.io-index"
1867+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
1868+
1869+[[package]]
1870+name = "smallvec"
1871+version = "1.15.2"
1872+source = "registry+https://github.com/rust-lang/crates.io-index"
1873+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
1874+
1875+[[package]]
1876+name = "spm_precompiled"
1877+version = "0.1.4"
1878+source = "registry+https://github.com/rust-lang/crates.io-index"
1879+checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326"
1880+dependencies = [
1881+ "base64",
1882+ "nom",
1883+ "serde",
1884+ "unicode-segmentation",
1885+]
1886+
1887+[[package]]
1888+name = "stable_deref_trait"
1889+version = "1.2.1"
1890+source = "registry+https://github.com/rust-lang/crates.io-index"
1891+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
1892+
1893+[[package]]
1894+name = "static_assertions"
1895+version = "1.1.0"
1896+source = "registry+https://github.com/rust-lang/crates.io-index"
1897+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
1898+
1899+[[package]]
1900+name = "strsim"
1901+version = "0.11.1"
1902+source = "registry+https://github.com/rust-lang/crates.io-index"
1903+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
1904+
1905+[[package]]
1906+name = "syn"
1907+version = "2.0.118"
1908+source = "registry+https://github.com/rust-lang/crates.io-index"
1909+checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
1910+dependencies = [
1911+ "proc-macro2",
1912+ "quote",
1913+ "unicode-ident",
1914+]
1915+
1916+[[package]]
1917+name = "synstructure"
1918+version = "0.13.2"
1919+source = "registry+https://github.com/rust-lang/crates.io-index"
1920+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
1921+dependencies = [
1922+ "proc-macro2",
1923+ "quote",
1924+ "syn",
1925+]
1926+
1927+[[package]]
1928+name = "sysctl"
1929+version = "0.6.0"
1930+source = "registry+https://github.com/rust-lang/crates.io-index"
1931+checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc"
1932+dependencies = [
1933+ "bitflags 2.13.0",
1934+ "byteorder",
1935+ "enum-as-inner",
1936+ "libc",
1937+ "thiserror 1.0.69",
1938+ "walkdir",
1939+]
1940+
1941+[[package]]
1942+name = "tempfile"
1943+version = "3.27.0"
1944+source = "registry+https://github.com/rust-lang/crates.io-index"
1945+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
1946+dependencies = [
1947+ "fastrand",
1948+ "getrandom 0.4.3",
1949+ "once_cell",
1950+ "rustix",
1951+ "windows-sys 0.61.2",
1952+]
1953+
1954+[[package]]
1955+name = "thiserror"
1956+version = "1.0.69"
1957+source = "registry+https://github.com/rust-lang/crates.io-index"
1958+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
1959+dependencies = [
1960+ "thiserror-impl 1.0.69",
1961+]
1962+
1963+[[package]]
1964+name = "thiserror"
1965+version = "2.0.18"
1966+source = "registry+https://github.com/rust-lang/crates.io-index"
1967+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
1968+dependencies = [
1969+ "thiserror-impl 2.0.18",
1970+]
1971+
1972+[[package]]
1973+name = "thiserror-impl"
1974+version = "1.0.69"
1975+source = "registry+https://github.com/rust-lang/crates.io-index"
1976+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
1977+dependencies = [
1978+ "proc-macro2",
1979+ "quote",
1980+ "syn",
1981+]
1982+
1983+[[package]]
1984+name = "thiserror-impl"
1985+version = "2.0.18"
1986+source = "registry+https://github.com/rust-lang/crates.io-index"
1987+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
1988+dependencies = [
1989+ "proc-macro2",
1990+ "quote",
1991+ "syn",
1992+]
1993+
1994+[[package]]
1995+name = "tokenizers"
1996+version = "0.21.4"
1997+source = "registry+https://github.com/rust-lang/crates.io-index"
1998+checksum = "a620b996116a59e184c2fa2dfd8251ea34a36d0a514758c6f966386bd2e03476"
1999+dependencies = [
2000+ "ahash",
2001+ "aho-corasick",
2002+ "compact_str",
2003+ "dary_heap",
2004+ "derive_builder",
2005+ "esaxx-rs",
2006+ "getrandom 0.3.4",
2007+ "indicatif",
2008+ "itertools",
2009+ "log",
2010+ "macro_rules_attribute",
2011+ "monostate",
2012+ "onig",
2013+ "paste",
2014+ "rand",
2015+ "rayon",
2016+ "rayon-cond",
2017+ "regex",
2018+ "regex-syntax",
2019+ "serde",
2020+ "serde_json",
2021+ "spm_precompiled",
2022+ "thiserror 2.0.18",
2023+ "unicode-normalization-alignments",
2024+ "unicode-segmentation",
2025+ "unicode_categories",
2026+]
2027+
2028+[[package]]
2029+name = "tokenizers"
2030+version = "0.22.2"
2031+source = "registry+https://github.com/rust-lang/crates.io-index"
2032+checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223"
2033+dependencies = [
2034+ "ahash",
2035+ "aho-corasick",
2036+ "compact_str",
2037+ "dary_heap",
2038+ "derive_builder",
2039+ "esaxx-rs",
2040+ "getrandom 0.3.4",
2041+ "itertools",
2042+ "log",
2043+ "macro_rules_attribute",
2044+ "monostate",
2045+ "onig",
2046+ "paste",
2047+ "rand",
2048+ "rayon",
2049+ "rayon-cond",
2050+ "regex",
2051+ "regex-syntax",
2052+ "serde",
2053+ "serde_json",
2054+ "spm_precompiled",
2055+ "thiserror 2.0.18",
2056+ "unicode-normalization-alignments",
2057+ "unicode-segmentation",
2058+ "unicode_categories",
2059+]
2060+
2061+[[package]]
2062+name = "tracing"
2063+version = "0.1.44"
2064+source = "registry+https://github.com/rust-lang/crates.io-index"
2065+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
2066+dependencies = [
2067+ "pin-project-lite",
2068+ "tracing-attributes",
2069+ "tracing-core",
2070+]
2071+
2072+[[package]]
2073+name = "tracing-attributes"
2074+version = "0.1.31"
2075+source = "registry+https://github.com/rust-lang/crates.io-index"
2076+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
2077+dependencies = [
2078+ "proc-macro2",
2079+ "quote",
2080+ "syn",
2081+]
2082+
2083+[[package]]
2084+name = "tracing-core"
2085+version = "0.1.36"
2086+source = "registry+https://github.com/rust-lang/crates.io-index"
2087+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
2088+dependencies = [
2089+ "once_cell",
2090+]
2091+
2092+[[package]]
2093+name = "typed-path"
2094+version = "0.12.3"
2095+source = "registry+https://github.com/rust-lang/crates.io-index"
2096+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
2097+
2098+[[package]]
2099+name = "typenum"
2100+version = "1.20.1"
2101+source = "registry+https://github.com/rust-lang/crates.io-index"
2102+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
2103+
2104+[[package]]
2105+name = "ug"
2106+version = "0.5.0"
2107+source = "registry+https://github.com/rust-lang/crates.io-index"
2108+checksum = "76b761acf8af3494640d826a8609e2265e19778fb43306c7f15379c78c9b05b0"
2109+dependencies = [
2110+ "gemm 0.18.2",
2111+ "half",
2112+ "libloading 0.8.9",
2113+ "memmap2",
2114+ "num",
2115+ "num-traits",
2116+ "num_cpus",
2117+ "rayon",
2118+ "safetensors 0.4.5",
2119+ "serde",
2120+ "thiserror 1.0.69",
2121+ "tracing",
2122+ "yoke 0.7.5",
2123+]
2124+
2125+[[package]]
2126+name = "ug-cuda"
2127+version = "0.5.0"
2128+source = "registry+https://github.com/rust-lang/crates.io-index"
2129+checksum = "9f0a1fa748f26166778c33b8498255ebb7c6bffb472bcc0a72839e07ebb1d9b5"
2130+dependencies = [
2131+ "cudarc 0.17.8",
2132+ "half",
2133+ "serde",
2134+ "thiserror 1.0.69",
2135+ "ug",
2136+]
2137+
2138+[[package]]
2139+name = "ug-metal"
2140+version = "0.5.0"
2141+source = "registry+https://github.com/rust-lang/crates.io-index"
2142+checksum = "9f7adf545a99a086d362efc739e7cf4317c18cbeda22706000fd434d70ea3d95"
2143+dependencies = [
2144+ "half",
2145+ "metal",
2146+ "objc",
2147+ "serde",
2148+ "thiserror 1.0.69",
2149+ "ug",
2150+]
2151+
2152+[[package]]
2153+name = "unicode-ident"
2154+version = "1.0.24"
2155+source = "registry+https://github.com/rust-lang/crates.io-index"
2156+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
2157+
2158+[[package]]
2159+name = "unicode-normalization-alignments"
2160+version = "0.1.12"
2161+source = "registry+https://github.com/rust-lang/crates.io-index"
2162+checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de"
2163+dependencies = [
2164+ "smallvec",
2165+]
2166+
2167+[[package]]
2168+name = "unicode-segmentation"
2169+version = "1.13.3"
2170+source = "registry+https://github.com/rust-lang/crates.io-index"
2171+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
2172+
2173+[[package]]
2174+name = "unicode-width"
2175+version = "0.2.2"
2176+source = "registry+https://github.com/rust-lang/crates.io-index"
2177+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
2178+
2179+[[package]]
2180+name = "unicode_categories"
2181+version = "0.1.1"
2182+source = "registry+https://github.com/rust-lang/crates.io-index"
2183+checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
2184+
2185+[[package]]
2186+name = "utf8parse"
2187+version = "0.2.2"
2188+source = "registry+https://github.com/rust-lang/crates.io-index"
2189+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
2190+
2191+[[package]]
2192+name = "version_check"
2193+version = "0.9.5"
2194+source = "registry+https://github.com/rust-lang/crates.io-index"
2195+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
2196+
2197+[[package]]
2198+name = "walkdir"
2199+version = "2.5.0"
2200+source = "registry+https://github.com/rust-lang/crates.io-index"
2201+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
2202+dependencies = [
2203+ "same-file",
2204+ "winapi-util",
2205+]
2206+
2207+[[package]]
2208+name = "wasip2"
2209+version = "1.0.4+wasi-0.2.12"
2210+source = "registry+https://github.com/rust-lang/crates.io-index"
2211+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
2212+dependencies = [
2213+ "wit-bindgen",
2214+]
2215+
2216+[[package]]
2217+name = "wasm-bindgen"
2218+version = "0.2.126"
2219+source = "registry+https://github.com/rust-lang/crates.io-index"
2220+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"
2221+dependencies = [
2222+ "cfg-if",
2223+ "once_cell",
2224+ "rustversion",
2225+ "wasm-bindgen-macro",
2226+ "wasm-bindgen-shared",
2227+]
2228+
2229+[[package]]
2230+name = "wasm-bindgen-macro"
2231+version = "0.2.126"
2232+source = "registry+https://github.com/rust-lang/crates.io-index"
2233+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"
2234+dependencies = [
2235+ "quote",
2236+ "wasm-bindgen-macro-support",
2237+]
2238+
2239+[[package]]
2240+name = "wasm-bindgen-macro-support"
2241+version = "0.2.126"
2242+source = "registry+https://github.com/rust-lang/crates.io-index"
2243+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"
2244+dependencies = [
2245+ "bumpalo",
2246+ "proc-macro2",
2247+ "quote",
2248+ "syn",
2249+ "wasm-bindgen-shared",
2250+]
2251+
2252+[[package]]
2253+name = "wasm-bindgen-shared"
2254+version = "0.2.126"
2255+source = "registry+https://github.com/rust-lang/crates.io-index"
2256+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"
2257+dependencies = [
2258+ "unicode-ident",
2259+]
2260+
2261+[[package]]
2262+name = "web-time"
2263+version = "1.1.0"
2264+source = "registry+https://github.com/rust-lang/crates.io-index"
2265+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
2266+dependencies = [
2267+ "js-sys",
2268+ "wasm-bindgen",
2269+]
2270+
2271+[[package]]
2272+name = "which"
2273+version = "7.0.3"
2274+source = "registry+https://github.com/rust-lang/crates.io-index"
2275+checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
2276+dependencies = [
2277+ "either",
2278+ "env_home",
2279+ "rustix",
2280+ "winsafe",
2281+]
2282+
2283+[[package]]
2284+name = "winapi"
2285+version = "0.3.9"
2286+source = "registry+https://github.com/rust-lang/crates.io-index"
2287+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
2288+dependencies = [
2289+ "winapi-i686-pc-windows-gnu",
2290+ "winapi-x86_64-pc-windows-gnu",
2291+]
2292+
2293+[[package]]
2294+name = "winapi-i686-pc-windows-gnu"
2295+version = "0.4.0"
2296+source = "registry+https://github.com/rust-lang/crates.io-index"
2297+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
2298+
2299+[[package]]
2300+name = "winapi-util"
2301+version = "0.1.11"
2302+source = "registry+https://github.com/rust-lang/crates.io-index"
2303+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
2304+dependencies = [
2305+ "windows-sys 0.61.2",
2306+]
2307+
2308+[[package]]
2309+name = "winapi-x86_64-pc-windows-gnu"
2310+version = "0.4.0"
2311+source = "registry+https://github.com/rust-lang/crates.io-index"
2312+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
2313+
2314+[[package]]
2315+name = "windows-link"
2316+version = "0.2.1"
2317+source = "registry+https://github.com/rust-lang/crates.io-index"
2318+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
2319+
2320+[[package]]
2321+name = "windows-sys"
2322+version = "0.59.0"
2323+source = "registry+https://github.com/rust-lang/crates.io-index"
2324+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
2325+dependencies = [
2326+ "windows-targets",
2327+]
2328+
2329+[[package]]
2330+name = "windows-sys"
2331+version = "0.61.2"
2332+source = "registry+https://github.com/rust-lang/crates.io-index"
2333+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
2334+dependencies = [
2335+ "windows-link",
2336+]
2337+
2338+[[package]]
2339+name = "windows-targets"
2340+version = "0.52.6"
2341+source = "registry+https://github.com/rust-lang/crates.io-index"
2342+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
2343+dependencies = [
2344+ "windows_aarch64_gnullvm",
2345+ "windows_aarch64_msvc",
2346+ "windows_i686_gnu",
2347+ "windows_i686_gnullvm",
2348+ "windows_i686_msvc",
2349+ "windows_x86_64_gnu",
2350+ "windows_x86_64_gnullvm",
2351+ "windows_x86_64_msvc",
2352+]
2353+
2354+[[package]]
2355+name = "windows_aarch64_gnullvm"
2356+version = "0.52.6"
2357+source = "registry+https://github.com/rust-lang/crates.io-index"
2358+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
2359+
2360+[[package]]
2361+name = "windows_aarch64_msvc"
2362+version = "0.52.6"
2363+source = "registry+https://github.com/rust-lang/crates.io-index"
2364+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
2365+
2366+[[package]]
2367+name = "windows_i686_gnu"
2368+version = "0.52.6"
2369+source = "registry+https://github.com/rust-lang/crates.io-index"
2370+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
2371+
2372+[[package]]
2373+name = "windows_i686_gnullvm"
2374+version = "0.52.6"
2375+source = "registry+https://github.com/rust-lang/crates.io-index"
2376+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
2377+
2378+[[package]]
2379+name = "windows_i686_msvc"
2380+version = "0.52.6"
2381+source = "registry+https://github.com/rust-lang/crates.io-index"
2382+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
2383+
2384+[[package]]
2385+name = "windows_x86_64_gnu"
2386+version = "0.52.6"
2387+source = "registry+https://github.com/rust-lang/crates.io-index"
2388+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
2389+
2390+[[package]]
2391+name = "windows_x86_64_gnullvm"
2392+version = "0.52.6"
2393+source = "registry+https://github.com/rust-lang/crates.io-index"
2394+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
2395+
2396+[[package]]
2397+name = "windows_x86_64_msvc"
2398+version = "0.52.6"
2399+source = "registry+https://github.com/rust-lang/crates.io-index"
2400+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
2401+
2402+[[package]]
2403+name = "winsafe"
2404+version = "0.0.19"
2405+source = "registry+https://github.com/rust-lang/crates.io-index"
2406+checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
2407+
2408+[[package]]
2409+name = "wit-bindgen"
2410+version = "0.57.1"
2411+source = "registry+https://github.com/rust-lang/crates.io-index"
2412+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
2413+
2414+[[package]]
2415+name = "yoke"
2416+version = "0.7.5"
2417+source = "registry+https://github.com/rust-lang/crates.io-index"
2418+checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40"
2419+dependencies = [
2420+ "serde",
2421+ "stable_deref_trait",
2422+ "yoke-derive 0.7.5",
2423+ "zerofrom",
2424+]
2425+
2426+[[package]]
2427+name = "yoke"
2428+version = "0.8.3"
2429+source = "registry+https://github.com/rust-lang/crates.io-index"
2430+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
2431+dependencies = [
2432+ "stable_deref_trait",
2433+ "yoke-derive 0.8.2",
2434+ "zerofrom",
2435+]
2436+
2437+[[package]]
2438+name = "yoke-derive"
2439+version = "0.7.5"
2440+source = "registry+https://github.com/rust-lang/crates.io-index"
2441+checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154"
2442+dependencies = [
2443+ "proc-macro2",
2444+ "quote",
2445+ "syn",
2446+ "synstructure",
2447+]
2448+
2449+[[package]]
2450+name = "yoke-derive"
2451+version = "0.8.2"
2452+source = "registry+https://github.com/rust-lang/crates.io-index"
2453+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
2454+dependencies = [
2455+ "proc-macro2",
2456+ "quote",
2457+ "syn",
2458+ "synstructure",
2459+]
2460+
2461+[[package]]
2462+name = "zerocopy"
2463+version = "0.8.52"
2464+source = "registry+https://github.com/rust-lang/crates.io-index"
2465+checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f"
2466+dependencies = [
2467+ "zerocopy-derive",
2468+]
2469+
2470+[[package]]
2471+name = "zerocopy-derive"
2472+version = "0.8.52"
2473+source = "registry+https://github.com/rust-lang/crates.io-index"
2474+checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930"
2475+dependencies = [
2476+ "proc-macro2",
2477+ "quote",
2478+ "syn",
2479+]
2480+
2481+[[package]]
2482+name = "zerofrom"
2483+version = "0.1.8"
2484+source = "registry+https://github.com/rust-lang/crates.io-index"
2485+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
2486+dependencies = [
2487+ "zerofrom-derive",
2488+]
2489+
2490+[[package]]
2491+name = "zerofrom-derive"
2492+version = "0.1.7"
2493+source = "registry+https://github.com/rust-lang/crates.io-index"
2494+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
2495+dependencies = [
2496+ "proc-macro2",
2497+ "quote",
2498+ "syn",
2499+ "synstructure",
2500+]
2501+
2502+[[package]]
2503+name = "zip"
2504+version = "8.6.0"
2505+source = "registry+https://github.com/rust-lang/crates.io-index"
2506+checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
2507+dependencies = [
2508+ "crc32fast",
2509+ "indexmap",
2510+ "memchr",
2511+ "typed-path",
2512+]
2513+
2514+[[package]]
2515+name = "zmij"
2516+version = "1.0.21"
2517+source = "registry+https://github.com/rust-lang/crates.io-index"
2518+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
added Cargo.toml +48 −0
@@ -0,0 +1,48 @@
1+[package]
2+name = "coco-engine"
3+version = "0.1.0"
4+edition = "2021"
5+description = "coco v0 — a minimal but real Rust LLM inference engine (Qwen2.5-1.5B on Metal/CPU via candle)"
6+license = "MIT"
7+
8+[lib]
9+name = "coco_engine"
10+path = "src/lib.rs"
11+
12+[[bin]]
13+name = "coco"
14+path = "src/main.rs"
15+
16+# Step-1 evolutionary-merge driver (reuses the engine via the lib seam).
17+[[bin]]
18+name = "coco-evomerge"
19+path = "src/bin/evomerge.rs"
20+
21+[features]
22+# Default to Metal (Apple Silicon GPU). Use --no-default-features for CPU-only.
23+default = ["metal"]
24+metal = ["candle-core/metal", "candle-nn/metal", "candle-transformers/metal", "dep:candle-metal-kernels", "dep:objc2-metal", "dep:objc2"]
25+cuda = ["candle-core/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
26+
27+[dependencies]
28+candle-core = "0.11.0"
29+candle-nn = "0.11.0"
30+candle-transformers = "0.11.0"
31+# Re-exported Metal bindings (Buffer/ComputePipeline/encoder) for the
32+# turboquant-fast custom Metal kernels. Only pulled in with the `metal` feature.
33+candle-metal-kernels = { version = "0.11.0", optional = true }
34+# MTLSize for the kernel dispatch grid (same version candle uses internally).
35+objc2-metal = { version = "0.3.2", optional = true }
36+objc2 = { version = "0.6", optional = true }
37+tokenizers = "0.21"
38+half = "2"
39+serde = { version = "1", features = ["derive"] }
40+serde_json = "1"
41+anyhow = "1"
42+clap = { version = "4", features = ["derive"] }
43+# Step-1 eval harness: GSM8K answer extraction (_extract_int port).
44+regex = "1"
45+
46+[profile.release]
47+opt-level = 3
48+lto = true
added LICENSE +202 −0
@@ -0,0 +1,202 @@
1+
2+ Apache License
3+ Version 2.0, January 2004
4+ http://www.apache.org/licenses/
5+
6+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7+
8+ 1. Definitions.
9+
10+ "License" shall mean the terms and conditions for use, reproduction,
11+ and distribution as defined by Sections 1 through 9 of this document.
12+
13+ "Licensor" shall mean the copyright owner or entity authorized by
14+ the copyright owner that is granting the License.
15+
16+ "Legal Entity" shall mean the union of the acting entity and all
17+ other entities that control, are controlled by, or are under common
18+ control with that entity. For the purposes of this definition,
19+ "control" means (i) the power, direct or indirect, to cause the
20+ direction or management of such entity, whether by contract or
21+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22+ outstanding shares, or (iii) beneficial ownership of such entity.
23+
24+ "You" (or "Your") shall mean an individual or Legal Entity
25+ exercising permissions granted by this License.
26+
27+ "Source" form shall mean the preferred form for making modifications,
28+ including but not limited to software source code, documentation
29+ source, and configuration files.
30+
31+ "Object" form shall mean any form resulting from mechanical
32+ transformation or translation of a Source form, including but
33+ not limited to compiled object code, generated documentation,
34+ and conversions to other media types.
35+
36+ "Work" shall mean the work of authorship, whether in Source or
37+ Object form, made available under the License, as indicated by a
38+ copyright notice that is included in or attached to the work
39+ (an example is provided in the Appendix below).
40+
41+ "Derivative Works" shall mean any work, whether in Source or Object
42+ form, that is based on (or derived from) the Work and for which the
43+ editorial revisions, annotations, elaborations, or other modifications
44+ represent, as a whole, an original work of authorship. For the purposes
45+ of this License, Derivative Works shall not include works that remain
46+ separable from, or merely link (or bind by name) to the interfaces of,
47+ the Work and Derivative Works thereof.
48+
49+ "Contribution" shall mean any work of authorship, including
50+ the original version of the Work and any modifications or additions
51+ to that Work or Derivative Works thereof, that is intentionally
52+ submitted to Licensor for inclusion in the Work by the copyright owner
53+ or by an individual or Legal Entity authorized to submit on behalf of
54+ the copyright owner. For the purposes of this definition, "submitted"
55+ means any form of electronic, verbal, or written communication sent
56+ to the Licensor or its representatives, including but not limited to
57+ communication on electronic mailing lists, source code control systems,
58+ and issue tracking systems that are managed by, or on behalf of, the
59+ Licensor for the purpose of discussing and improving the Work, but
60+ excluding communication that is conspicuously marked or otherwise
61+ designated in writing by the copyright owner as "Not a Contribution."
62+
63+ "Contributor" shall mean Licensor and any individual or Legal Entity
64+ on behalf of whom a Contribution has been received by Licensor and
65+ subsequently incorporated within the Work.
66+
67+ 2. Grant of Copyright License. Subject to the terms and conditions of
68+ this License, each Contributor hereby grants to You a perpetual,
69+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70+ copyright license to reproduce, prepare Derivative Works of,
71+ publicly display, publicly perform, sublicense, and distribute the
72+ Work and such Derivative Works in Source or Object form.
73+
74+ 3. Grant of Patent License. Subject to the terms and conditions of
75+ this License, each Contributor hereby grants to You a perpetual,
76+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77+ (except as stated in this section) patent license to make, have made,
78+ use, offer to sell, sell, import, and otherwise transfer the Work,
79+ where such license applies only to those patent claims licensable
80+ by such Contributor that are necessarily infringed by their
81+ Contribution(s) alone or by combination of their Contribution(s)
82+ with the Work to which such Contribution(s) was submitted. If You
83+ institute patent litigation against any entity (including a
84+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85+ or a Contribution incorporated within the Work constitutes direct
86+ or contributory patent infringement, then any patent licenses
87+ granted to You under this License for that Work shall terminate
88+ as of the date such litigation is filed.
89+
90+ 4. Redistribution. You may reproduce and distribute copies of the
91+ Work or Derivative Works thereof in any medium, with or without
92+ modifications, and in Source or Object form, provided that You
93+ meet the following conditions:
94+
95+ (a) You must give any other recipients of the Work or
96+ Derivative Works a copy of this License; and
97+
98+ (b) You must cause any modified files to carry prominent notices
99+ stating that You changed the files; and
100+
101+ (c) You must retain, in the Source form of any Derivative Works
102+ that You distribute, all copyright, patent, trademark, and
103+ attribution notices from the Source form of the Work,
104+ excluding those notices that do not pertain to any part of
105+ the Derivative Works; and
106+
107+ (d) If the Work includes a "NOTICE" text file as part of its
108+ distribution, then any Derivative Works that You distribute must
109+ include a readable copy of the attribution notices contained
110+ within such NOTICE file, excluding those notices that do not
111+ pertain to any part of the Derivative Works, in at least one
112+ of the following places: within a NOTICE text file distributed
113+ as part of the Derivative Works; within the Source form or
114+ documentation, if provided along with the Derivative Works; or,
115+ within a display generated by the Derivative Works, if and
116+ wherever such third-party notices normally appear. The contents
117+ of the NOTICE file are for informational purposes only and
118+ do not modify the License. You may add Your own attribution
119+ notices within Derivative Works that You distribute, alongside
120+ or as an addendum to the NOTICE text from the Work, provided
121+ that such additional attribution notices cannot be construed
122+ as modifying the License.
123+
124+ You may add Your own copyright statement to Your modifications and
125+ may provide additional or different license terms and conditions
126+ for use, reproduction, or distribution of Your modifications, or
127+ for any such Derivative Works as a whole, provided Your use,
128+ reproduction, and distribution of the Work otherwise complies with
129+ the conditions stated in this License.
130+
131+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132+ any Contribution intentionally submitted for inclusion in the Work
133+ by You to the Licensor shall be under the terms and conditions of
134+ this License, without any additional terms or conditions.
135+ Notwithstanding the above, nothing herein shall supersede or modify
136+ the terms of any separate license agreement you may have executed
137+ with Licensor regarding such Contributions.
138+
139+ 6. Trademarks. This License does not grant permission to use the trade
140+ names, trademarks, service marks, or product names of the Licensor,
141+ except as required for reasonable and customary use in describing the
142+ origin of the Work and reproducing the content of the NOTICE file.
143+
144+ 7. Disclaimer of Warranty. Unless required by applicable law or
145+ agreed to in writing, Licensor provides the Work (and each
146+ Contributor provides its Contributions) on an "AS IS" BASIS,
147+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148+ implied, including, without limitation, any warranties or conditions
149+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150+ PARTICULAR PURPOSE. You are solely responsible for determining the
151+ appropriateness of using or redistributing the Work and assume any
152+ risks associated with Your exercise of permissions under this License.
153+
154+ 8. Limitation of Liability. In no event and under no legal theory,
155+ whether in tort (including negligence), contract, or otherwise,
156+ unless required by applicable law (such as deliberate and grossly
157+ negligent acts) or agreed to in writing, shall any Contributor be
158+ liable to You for damages, including any direct, indirect, special,
159+ incidental, or consequential damages of any character arising as a
160+ result of this License or out of the use or inability to use the
161+ Work (including but not limited to damages for loss of goodwill,
162+ work stoppage, computer failure or malfunction, or any and all
163+ other commercial damages or losses), even if such Contributor
164+ has been advised of the possibility of such damages.
165+
166+ 9. Accepting Warranty or Additional Liability. While redistributing
167+ the Work or Derivative Works thereof, You may choose to offer,
168+ and charge a fee for, acceptance of support, warranty, indemnity,
169+ or other liability obligations and/or rights consistent with this
170+ License. However, in accepting such obligations, You may act only
171+ on Your own behalf and on Your sole responsibility, not on behalf
172+ of any other Contributor, and only if You agree to indemnify,
173+ defend, and hold each Contributor harmless for any liability
174+ incurred by, or claims asserted against, such Contributor by reason
175+ of your accepting any such warranty or additional liability.
176+
177+ END OF TERMS AND CONDITIONS
178+
179+ APPENDIX: How to apply the Apache License to your work.
180+
181+ To apply the Apache License to your work, attach the following
182+ boilerplate notice, with the fields enclosed by brackets "[]"
183+ replaced with your own identifying information. (Don't include
184+ the brackets!) The text should be enclosed in the appropriate
185+ comment syntax for the file format. We also recommend that a
186+ file or class name and description of purpose be included on the
187+ same "printed page" as the copyright notice for easier
188+ identification within third-party archives.
189+
190+ Copyright [yyyy] [name of copyright owner]
191+
192+ Licensed under the Apache License, Version 2.0 (the "License");
193+ you may not use this file except in compliance with the License.
194+ You may obtain a copy of the License at
195+
196+ http://www.apache.org/licenses/LICENSE-2.0
197+
198+ Unless required by applicable law or agreed to in writing, software
199+ distributed under the License is distributed on an "AS IS" BASIS,
200+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201+ See the License for the specific language governing permissions and
202+ limitations under the License.
added README.md +65 −0
@@ -0,0 +1,65 @@
1+# coco
2+
3+**An architecture-agnostic LLM inference + quantization engine, in Rust.** Built on [candle](https://github.com/huggingface/candle) + Metal.
4+
5+> One engine, not one-file-per-architecture. Every model reduces to a config row plus a single pluggable per-layer seam — so supporting a new architecture is an afternoon, not a rewrite.
6+
7+Status: **early but real.** Builds clean, `cargo test` is green (12/12), and the headline pieces are validated against oracles. It is honest about what it can't do yet (see *Limitations*). This is a working research engine, not a drop-in llama.cpp replacement.
8+
9+---
10+
11+## What works today
12+
13+- **Four architectures**, all wired end-to-end through one generic `DenseDecoder`:
14+ - **Qwen2**, **Qwen3** (QK-norm), **Qwen3-MoE** (per-layer dense/MoE routing), **DeepSeek V2/V3** (MLA latent attention + shared-expert MoE + YaRN RoPE).
15+- **One pluggable seam** — the `SequenceMixer` trait. Three mixers implement it and dispatch per layer:
16+ `GqaAttention` (full GQA + flash-decode + persistent KV cache), `MlaAttention` (DeepSeek latent), `GatedDeltaNet` (linear recurrent).
17+- **turboquant** — a pure-Rust, **data-free** 3-bit quantizer (FWHT incoherence rotation + Lloyd-Max codebook + per-block fp16 radius). No Python, no calibration set, no external quant libs.
18+ - Measured on Qwen2.5-1.5B: whole model **2944 → 934 MB (3.15×)**, projections **5.12×**, ~3.125 bpw, relFro 0.184.
19+ - Weights stay **GPU-resident and compressed**, decompressed on-the-fly inside fused Metal kernels — never materialized back to fp16.
20+ - Output is **byte-for-byte identical** to the fp16 baseline on the checked cases.
21+- **Fused Metal kernel suite** (`qlinear.rs`): on-GPU rotation, quantized matvec that reads compressed codes directly (register-blocked variants), fused RMSNorm, and split-K flash-decode with in-kernel KV append.
22+
23+## Validated (reproducible)
24+
25+- **GatedDeltaNet** forward matches its reference oracle at **max abs err 1.825e-7** (mean 3.5e-8), threshold 1e-4 — `cargo run --release --bin gdn_ref`, fixtures in `tests/fixtures/gdn_oracle/`.
26+- `cargo test --release` → **12 passed / 0 failed** (FWHT self-inverse, rotated-fast-path == dense matmul, 3-bit roundtrip, …).
27+- `cargo build --release` → 0 errors.
28+
29+## Limitations (honest)
30+
31+- **Qwen3.5 is recognized but does not run yet.** Its config is parsed and the `GatedDeltaNet` mixer is validated in isolation, but the per-layer linear/full-attention dispatch isn't wired into `DecoderLayer` yet — `build_model` returns a **diagnostic error on purpose** rather than building a half-working model.
32+- **MLA** runs the candle fallback (no fused kernel yet); its parity-vs-reference is not re-verified in this release (needs an external checkpoint).
33+- **Speed wins are short-context only.** Decode is bandwidth-bound, so reading fewer weight bytes wins at ctx 0–128; the advantage inverts by ~2K–8K because prefill is still O(seq²).
34+- The integrated binary ships the 4.x-bpw nibble format by default; the true-3-bit (934 MB) path is self-checked but not yet CLI-default.
35+- No checkpoint persistence / GGUF interop — models are quantized at load.
36+
37+## Quick start
38+
39+```bash
40+cargo build --release
41+# run generation (point --model at a HF model dir with config.json, tokenizer.json, *.safetensors)
42+cargo run --release --bin coco -- --model ./model --prompt "The capital of France is"
43+# validate the GatedDeltaNet port against its oracle
44+cargo run --release --bin gdn_ref
45+cargo test --release
46+```
47+
48+## Layout
49+
50+| file | what |
51+|---|---|
52+| `src/config.rs` | arch registry + config parsing (`ARCH_REGISTRY`, `resolve_arch`, `build_model` dispatch) |
53+| `src/model.rs` | `DenseDecoder`, `DecoderLayer`, the `SequenceMixer` trait + its 3 impls, `MoeFfn` |
54+| `src/turboquant.rs` | the data-free quantizer (rotation + codebook + radius) |
55+| `src/qlinear.rs` | fused Metal kernels (quantized matvec, flash-decode, rmsnorm) |
56+| `src/eval.rs` / `src/merge.rs` | eval harness + evolutionary merge |
57+| `tests/fixtures/` | golden oracles for validation |
58+
59+## The story
60+
61+The design decisions here are written up, for humans, at **[bitacora.utopiaia.com](https://bitacora.utopiaia.com)** — the SequenceMixer seam, oracle-first validation, turboquant, the bandwidth thesis, and an honest engineering war story about a GPU kernel that came out 20× slower.
62+
63+## License
64+
65+Apache-2.0. See [LICENSE](LICENSE).
added src/bin/ds2_ref.rs +134 −0
@@ -0,0 +1,134 @@
1+// ds2_ref — ORACLE reference runner for the MLA port validation.
2+//
3+// Loads DeepSeek-V2-Lite with candle-transformers 0.11's OWN deepseek2.rs
4+// (DeepSeekV2 + DeepSeekV2Config), greedy-generates N tokens for a fixed prompt,
5+// and prints the exact generated token ids as `TOKENS id,id,...` — the same
6+// format coco's COCO_DUMP_TOKENS uses. This is the ground truth the coco MLA
7+// port is compared against at matched precision (fp16/bf16).
8+
9+use anyhow::{anyhow, Result};
10+use candle_core::{DType, Device, Tensor};
11+use candle_nn::VarBuilder;
12+use candle_transformers::models::deepseek2::{DeepSeekV2, DeepSeekV2Config};
13+use clap::Parser;
14+use std::path::PathBuf;
15+use tokenizers::Tokenizer;
16+
17+#[derive(Parser, Debug)]
18+struct Args {
19+ #[arg(long, default_value = "The capital of France is")]
20+ prompt: String,
21+ #[arg(long)]
22+ model: PathBuf,
23+ #[arg(long, default_value_t = 20)]
24+ max_tokens: usize,
25+ #[arg(long)]
26+ cpu: bool,
27+}
28+
29+fn pick_device(force_cpu: bool) -> Result<Device> {
30+ if force_cpu {
31+ return Ok(Device::Cpu);
32+ }
33+ if candle_core::utils::metal_is_available() {
34+ match Device::new_metal(0) {
35+ Ok(d) => return Ok(d),
36+ Err(e) => eprintln!("warning: Metal failed ({e}); CPU"),
37+ }
38+ }
39+ Ok(Device::Cpu)
40+}
41+
42+fn safetensors_files(dir: &PathBuf) -> Result<Vec<PathBuf>> {
43+ let mut files = Vec::new();
44+ for entry in std::fs::read_dir(dir)? {
45+ let path = entry?.path();
46+ if path.extension().map(|e| e == "safetensors").unwrap_or(false) {
47+ files.push(path);
48+ }
49+ }
50+ if files.is_empty() {
51+ return Err(anyhow!("no *.safetensors in {}", dir.display()));
52+ }
53+ files.sort();
54+ Ok(files)
55+}
56+
57+fn main() -> Result<()> {
58+ let args = Args::parse();
59+ let device = pick_device(args.cpu)?;
60+ // Match coco: BF16 on GPU (Metal), F32 on CPU. DeepSeek weights are bf16.
61+ let dtype = if device.is_cpu() { DType::F32 } else { DType::BF16 };
62+ eprintln!("ds2_ref | device: {device:?} | dtype: {dtype:?}");
63+
64+ let tokenizer = Tokenizer::from_file(args.model.join("tokenizer.json"))
65+ .map_err(|e| anyhow!("tokenizer: {e}"))?;
66+
67+ let cfg: DeepSeekV2Config =
68+ serde_json::from_slice(&std::fs::read(args.model.join("config.json"))?)?;
69+
70+ let weight_files = safetensors_files(&args.model)?;
71+ let vb = unsafe { VarBuilder::from_mmaped_safetensors(&weight_files, dtype, &device)? };
72+ let mut model = DeepSeekV2::new(&cfg, vb)?;
73+ eprintln!("ds2_ref | model loaded ({} layers)", cfg_num_layers(&args.model)?);
74+
75+ let encoding = tokenizer
76+ .encode(args.prompt.as_str(), true)
77+ .map_err(|e| anyhow!("encode: {e}"))?;
78+ let mut tokens: Vec<u32> = encoding.get_ids().to_vec();
79+ if tokens.is_empty() {
80+ return Err(anyhow!("empty prompt"));
81+ }
82+ let prompt_len = tokens.len();
83+
84+ for index in 0..args.max_tokens {
85+ let (context, offset) = if index == 0 {
86+ (tokens.as_slice(), 0)
87+ } else {
88+ (&tokens[tokens.len() - 1..], tokens.len() - 1)
89+ };
90+ let input = Tensor::new(context, &device)?.unsqueeze(0)?;
91+ let logits = model.forward(&input, offset)?; // [1, seq, vocab] or [1, vocab]
92+ // deepseek2.rs returns [b, vocab] (last-token) already; be robust either way.
93+ let logits = logits.to_dtype(DType::F32)?;
94+ let logits = match logits.dims().len() {
95+ 3 => logits.i((0, logits.dim(1)? - 1))?, // [vocab]
96+ 2 => logits.i(0)?, // [vocab]
97+ 1 => logits,
98+ _ => return Err(anyhow!("unexpected logits shape {:?}", logits.dims())),
99+ };
100+ // At the first step (identical prompt), dump the top-8 (id: logit) pairs —
101+ // the matched-input probe compared against coco's LOGITS0.
102+ if index == 0 {
103+ let v: Vec<f32> = logits.to_vec1::<f32>()?;
104+ let mut ix: Vec<usize> = (0..v.len()).collect();
105+ ix.sort_by(|&a, &b| v[b].partial_cmp(&v[a]).unwrap());
106+ let top: Vec<String> =
107+ ix.iter().take(8).map(|&i| format!("{}:{:.4}", i, v[i])).collect();
108+ println!("LOGITS0 {}", top.join(","));
109+ }
110+ // Greedy argmax.
111+ let next = logits.argmax(candle_core::D::Minus1)?.to_scalar::<u32>()?;
112+ tokens.push(next);
113+ }
114+
115+ let gen_ids = &tokens[prompt_len..];
116+ let ids: Vec<String> = gen_ids.iter().map(|t| t.to_string()).collect();
117+ println!("TOKENS {}", ids.join(","));
118+ // Also print the decoded text for a human sanity read.
119+ if let Ok(text) = tokenizer.decode(gen_ids, true) {
120+ eprintln!("TEXT: {}{}", args.prompt, text);
121+ }
122+ Ok(())
123+}
124+
125+use candle_core::IndexOp;
126+
127+fn cfg_num_layers(dir: &PathBuf) -> Result<usize> {
128+ #[derive(serde::Deserialize)]
129+ struct P {
130+ num_hidden_layers: usize,
131+ }
132+ let p: P = serde_json::from_slice(&std::fs::read(dir.join("config.json"))?)?;
133+ Ok(p.num_hidden_layers)
134+}
added src/bin/enc_proto.rs +925 −0
@@ -0,0 +1,925 @@
1+//! enc_proto — de-risk prototype for the SINGLE-ENCODER decode path.
2+//!
3+//! Measures ONE decoder layer (Qwen2.5-1.5B, real layer-0 weights, turboquant-fast
4+//! kernels) two ways, 200 iterations each:
5+//! (a) CURRENT path : the exact per-op candle route the engine uses today
6+//! (apply_op1 / shared-encoder guard / hazard tracker / buffer pool).
7+//! (b) RAW path : the SAME 16 kernels with the SAME grids encoded into ONE
8+//! raw MTLComputeCommandEncoder on our own MTLCommandQueue, with manual
9+//! memoryBarrier(scope=buffers) between dependent dispatches, pre-bound
10+//! reused buffers, ONE commit + waitUntilCompleted for the whole run.
11+//!
12+//! The headline is the ratio (a)/(b): ≥1.25x ⇒ the encoder/glue overhead theory
13+//! is confirmed and a single-encoder integration is worth doing.
14+//!
15+//! Per-iteration kernel sequence (default engine config: FUSED_ATTN on, bf16 KV,
16+//! nibble pack, QROWS=4, FUSE_SWIGLU on, FUSE_RESID off, ROTATE_IN off):
17+//! 1. tq_rmsnorm_bf16 (input_layernorm)
18+//! 2. tq_rotate_bf16 (qkv shared rotate)
19+//! 3. tq_qmatvec_bf16_r (fused q/k/v, out=2048, bias epilogue)
20+//! 4. tq_rope_bf16 (q, strided view)
21+//! 5. tq_rope_bf16 (k, strided view) [no barrier 4→5]
22+//! 6. tq_attn_partial (flash-decode split-K, in-kernel append)
23+//! 7. tq_attn_combine
24+//! 8. cast f32→bf16 (candle native cast in (a))
25+//! 9. tq_rotate_bf16 (o_proj rotate)
26+//! 10. tq_qmatvec_bf16_r (o_proj)
27+//! 11. tq_add_rmsnorm_bf16 (residual add + post-attn norm, 2 outputs)
28+//! 12. tq_rotate_bf16 (gate/up shared rotate)
29+//! 13. tq_qmatvec_swiglu_r (fused gate/up → silu(g)·u, out=8960)
30+//! 14. tq_rotate_bf16 (down rotate, inn=8960)
31+//! 15. tq_qmatvec_bf16_r (down_proj)
32+//! 16. add bf16 (h + mlp_out; candle native add in (a))
33+//!
34+//! Run (defaults): cargo run --release --bin enc_proto
35+//! Notes: run with NO COCO_* env vars set (defaults asserted above).
36+
37+#![allow(dead_code)]
38+#![allow(clippy::too_many_arguments)]
39+
40+#[path = "../turboquant.rs"]
41+mod turboquant;
42+#[path = "../qlinear.rs"]
43+mod qlinear;
44+
45+use anyhow::{anyhow, Context, Result};
46+use candle_core::{DType, Device, Tensor};
47+use candle_metal_kernels::metal::{Buffer as KBuffer, ComputePipeline};
48+use clap::Parser;
49+use half::bf16;
50+use objc2::rc::Retained;
51+use objc2::runtime::ProtocolObject;
52+use objc2_metal::{
53+ MTLBarrierScope, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue,
54+ MTLComputeCommandEncoder, MTLDevice, MTLDispatchType, MTLResourceOptions, MTLSize,
55+};
56+use std::ffi::c_void;
57+use std::path::PathBuf;
58+use std::ptr::NonNull;
59+use std::sync::Arc;
60+
61+use qlinear::{rope_apply, KvCache, QGroup, QWeight, RmsNormFused};
62+use turboquant::{encode, TqConfig, LLOYD_MAX_3BIT};
63+
64+// ───────────────────────────── CLI ─────────────────────────────
65+
66+#[derive(Parser, Debug)]
67+#[command(name = "enc_proto", about = "single-encoder decode-path prototype (ONE layer)")]
68+struct Args {
69+ /// Model dir (config.json + model.safetensors).
70+ #[arg(long, default_value = "./model")]
71+ model: PathBuf,
72+ /// Timed iterations per rep.
73+ #[arg(long, default_value_t = 200)]
74+ iters: usize,
75+ /// KV-cache depth the decode step attends over (fixed every iteration).
76+ #[arg(long, default_value_t = 512)]
77+ ctx: usize,
78+ /// Timing repetitions (best wall time kept).
79+ #[arg(long, default_value_t = 3)]
80+ reps: usize,
81+ /// Warmup iterations (per path).
82+ #[arg(long, default_value_t = 20)]
83+ warmup: usize,
84+}
85+
86+// ─────────────────────── small helpers ───────────────────────
87+
88+/// Metal buffer + BYTE offset backing a candle tensor.
89+fn tbuf(t: &Tensor) -> Result<(KBuffer, usize)> {
90+ let (s, l) = t.storage_and_layout();
91+ match &*s {
92+ candle_core::Storage::Metal(ms) => Ok((
93+ ms.buffer().clone(),
94+ l.start_offset() * t.dtype().size_in_bytes(),
95+ )),
96+ _ => Err(anyhow!("tensor not on Metal")),
97+ }
98+}
99+
100+type RawEnc = ProtocolObject<dyn MTLComputeCommandEncoder>;
101+
102+fn set_buf(enc: &RawEnc, idx: usize, buf: &KBuffer, off: usize) {
103+ unsafe { enc.setBuffer_offset_atIndex(Some(buf.as_ref()), off, idx) }
104+}
105+
106+fn set_bytes<T>(enc: &RawEnc, idx: usize, v: &T) {
107+ let ptr = NonNull::new(v as *const T as *mut c_void).unwrap();
108+ unsafe { enc.setBytes_length_atIndex(ptr, std::mem::size_of::<T>(), idx) }
109+}
110+
111+fn barrier(enc: &RawEnc) {
112+ enc.memoryBarrierWithScope(MTLBarrierScope::Buffers);
113+}
114+
115+fn sz(w: usize, h: usize, d: usize) -> MTLSize {
116+ MTLSize { width: w, height: h, depth: d }
117+}
118+
119+// ─────────────────────── model pieces (layer 0) ───────────────────────
120+
121+struct Dims {
122+ hidden: usize,
123+ inter: usize,
124+ heads: usize,
125+ kv: usize,
126+ hd: usize,
127+ d: usize, // turboquant block width (128)
128+ eps: f32,
129+ theta: f32,
130+}
131+
132+struct Layer0 {
133+ qkv: QGroup,
134+ o: QWeight,
135+ gate_up: QGroup,
136+ down: QWeight,
137+ ln1: RmsNormFused,
138+ ln2: RmsNormFused,
139+}
140+
141+fn load_layer0(model: &PathBuf, dims: &Dims, dev: &Device) -> Result<Layer0> {
142+ let st = unsafe {
143+ candle_core::safetensors::MmapedSafetensors::new(model.join("model.safetensors"))?
144+ };
145+ let cpu = Device::Cpu;
146+ let f32v = |name: &str| -> Result<(Vec<f32>, usize, usize)> {
147+ let t = st.load(&format!("model.layers.0.{name}"), &cpu)?;
148+ let dd = t.dims().to_vec();
149+ Ok((t.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?, dd[0], dd[1]))
150+ };
151+ let bias = |name: &str| -> Result<Tensor> {
152+ Ok(st
153+ .load(&format!("model.layers.0.{name}"), &cpu)?
154+ .to_dtype(DType::BF16)?
155+ .to_device(dev)?)
156+ };
157+ let cfg = TqConfig { d: dims.d, bits: 3, outlier_frac: 0.0, seed: 0, block_hadamard: true };
158+
159+ let enc1 = |name: &str| -> Result<turboquant::TqWeight> {
160+ let (w, o, i) = f32v(name)?;
161+ Ok(encode(&w, o, i, &cfg, &LLOYD_MAX_3BIT))
162+ };
163+
164+ let t0 = std::time::Instant::now();
165+ let q = enc1("self_attn.q_proj.weight")?;
166+ let k = enc1("self_attn.k_proj.weight")?;
167+ let v = enc1("self_attn.v_proj.weight")?;
168+ let qkv = QGroup::from_tqs(
169+ &[&q, &k, &v],
170+ vec![
171+ Some(bias("self_attn.q_proj.bias")?),
172+ Some(bias("self_attn.k_proj.bias")?),
173+ Some(bias("self_attn.v_proj.bias")?),
174+ ],
175+ dev,
176+ )?;
177+ let o = QWeight::from_tq(&enc1("self_attn.o_proj.weight")?, None, dev)?;
178+ let g = enc1("mlp.gate_proj.weight")?;
179+ let u = enc1("mlp.up_proj.weight")?;
180+ let gate_up = QGroup::from_tqs(&[&g, &u], vec![None, None], dev)?;
181+ let down = QWeight::from_tq(&enc1("mlp.down_proj.weight")?, None, dev)?;
182+
183+ let lnw = |name: &str| -> Result<Tensor> {
184+ Ok(st
185+ .load(&format!("model.layers.0.{name}.weight"), &cpu)?
186+ .to_dtype(DType::BF16)?
187+ .to_device(dev)?)
188+ };
189+ let ln1 = RmsNormFused::new(lnw("input_layernorm")?, dims.eps as f64)?;
190+ let ln2 = RmsNormFused::new(lnw("post_attention_layernorm")?, dims.eps as f64)?;
191+ eprintln!("[setup] layer0 encoded+resident in {:.2}s", t0.elapsed().as_secs_f64());
192+ Ok(Layer0 { qkv, o, gate_up, down, ln1, ln2 })
193+}
194+
195+// ─────────────────────── (a) the CURRENT candle path ───────────────────────
196+
197+/// Exact replica of DecoderLayer::forward on the default decode path
198+/// (qwen2_q.rs: FUSE_RESID off → forward_add branch; fused flash-decode attn).
199+fn candle_layer_forward(
200+ xs: &Tensor,
201+ l: &Layer0,
202+ kc: &mut KvCache,
203+ cos: &Tensor,
204+ sin: &Tensor,
205+ dims: &Dims,
206+) -> Result<Tensor> {
207+ let residual = xs;
208+ let x = l.ln1.forward(xs)?; // 1: rmsnorm
209+ let mut qkv = l.qkv.forward(&x)?; // 2+3: rotate + fused qmatvec
210+ let v = qkv.pop().unwrap();
211+ let k = qkv.pop().unwrap();
212+ let q = qkv.pop().unwrap();
213+ let q = q.reshape((1, 1, dims.heads, dims.hd))?.transpose(1, 2)?;
214+ let k = k.reshape((1, 1, dims.kv, dims.hd))?.transpose(1, 2)?;
215+ let v = v.reshape((1, 1, dims.kv, dims.hd))?.transpose(1, 2)?;
216+ let q = rope_apply(&q, cos, sin)?; // 4
217+ let k = rope_apply(&k, cos, sin)?; // 5
218+ let k_f = k.squeeze(0)?.contiguous()?;
219+ let v_f = v.squeeze(0)?.contiguous()?;
220+ let k1 = k_f.squeeze(1)?;
221+ let v1 = v_f.squeeze(1)?;
222+ let q_f = q.squeeze(0)?.squeeze(1)?.contiguous()?;
223+ let attn = kc.decode(&q_f, &k1, &v1)?; // 6+7: partial + combine
224+ let attn = attn.to_dtype(DType::BF16)?; // 8: candle cast
225+ let attn_out = l.o.forward(&attn)?; // 9+10: rotate + qmatvec
226+ let (h, normed) = l.ln2.forward_add(residual, &attn_out)?; // 11
227+ let act = l
228+ .gate_up
229+ .forward_swiglu(&normed)?
230+ .ok_or_else(|| anyhow!("swiglu path not eligible?"))?; // 12+13
231+ let mlp_out = l.down.forward(&act)?; // 14+15
232+ Ok((&h + mlp_out)?) // 16: candle add
233+}
234+
235+// ─────────────────────── (b) the RAW single-encoder path ───────────────────────
236+
237+/// Tiny MSL twins of the two candle-native elementwise ops in the sequence.
238+const EXTRA_SRC: &str = r#"
239+#include <metal_stdlib>
240+using namespace metal;
241+kernel void ep_cast_f32_bf16(device const float *x [[buffer(0)]],
242+ device bfloat *y [[buffer(1)]],
243+ uint i [[thread_position_in_grid]]) { y[i] = (bfloat)x[i]; }
244+kernel void ep_add_bf16(device const bfloat *a [[buffer(0)]],
245+ device const bfloat *b [[buffer(1)]],
246+ device bfloat *y [[buffer(2)]],
247+ uint i [[thread_position_in_grid]]) { y[i] = a[i] + b[i]; }
248+"#;
249+
250+/// Everything pre-resolved: pipelines, weight/cache buffers, reused intermediates,
251+/// grids. `encode_iter` appends the 16 dispatches (+15 barriers) to a raw encoder.
252+struct RawLayer {
253+ // pipelines (identical objects to the ones the candle path uses)
254+ p_rms: ComputePipeline,
255+ p_rot: ComputePipeline,
256+ p_qmv: ComputePipeline,
257+ p_rope: ComputePipeline,
258+ p_part: ComputePipeline,
259+ p_comb: ComputePipeline,
260+ p_addnorm: ComputePipeline,
261+ p_swiglu: ComputePipeline,
262+ p_cast: ComputePipeline,
263+ p_add: ComputePipeline,
264+ // weights / params
265+ qkv_codes: KBuffer,
266+ qkv_rad: KBuffer,
267+ qkv_bias: KBuffer,
268+ o_codes: KBuffer,
269+ o_rad: KBuffer,
270+ gu_codes: KBuffer,
271+ gu_rad: KBuffer,
272+ dn_codes: KBuffer,
273+ dn_rad: KBuffer,
274+ codebook: [f32; 8],
275+ sign_h: (KBuffer, usize), // hidden-width ±1 (qkv/o/gate_up share seed+inn)
276+ sign_i: (KBuffer, usize), // intermediate-width ±1 (down)
277+ ln1_w: (KBuffer, usize),
278+ ln2_w: (KBuffer, usize),
279+ cos: (KBuffer, usize),
280+ sin: (KBuffer, usize),
281+ x_in: (KBuffer, usize),
282+ // kv cache
283+ k_cache: KBuffer,
284+ v_cache: KBuffer,
285+ pacc: KBuffer,
286+ pm: KBuffer,
287+ pl: KBuffer,
288+ // reused intermediates (shared storage → CPU-checkable)
289+ normed1: KBuffer,
290+ xr1: KBuffer,
291+ qkv_out: KBuffer,
292+ ropeq: KBuffer,
293+ ropek: KBuffer,
294+ attn_f32: KBuffer,
295+ attn_bf16: KBuffer,
296+ xr2: KBuffer,
297+ o_out: KBuffer,
298+ h_buf: KBuffer,
299+ normed2: KBuffer,
300+ xr3: KBuffer,
301+ act: KBuffer,
302+ xr4: KBuffer,
303+ dn_out: KBuffer,
304+ final_out: KBuffer,
305+ // dims / scalars
306+ hidden: u32,
307+ inter: u32,
308+ heads: u32,
309+ kvh: u32,
310+ hd: u32,
311+ d: u32,
312+ eps: f32,
313+ scale: f32,
314+ max_ctx: u32,
315+ total: u32, // ctx + 1 (positions attended after in-kernel append)
316+ pos_ctx: u32, // unused by bf16 partial (append slot == total-1), kept for clarity
317+ n_splits: u32,
318+ // grid tg widths (derived from each pipeline's max, same formulas as the ops)
319+ tgw_rms: usize,
320+ tgw_qmv: usize,
321+ tgw_addnorm: usize,
322+}
323+
324+impl RawLayer {
325+ fn encode_iter(&self, enc: &RawEnc, first: bool) {
326+ let hidden = self.hidden as usize;
327+ let inter = self.inter as usize;
328+ let heads = self.heads as usize;
329+ let kvh = self.kvh as usize;
330+ let hd = self.hd as usize;
331+ let d = self.d as usize;
332+ let one: u32 = 1;
333+ let zero: u32 = 0;
334+
335+ if !first {
336+ // Cross-iteration WAR/RAW on the reused buffers (incl. KV slot rewrite).
337+ barrier(enc);
338+ }
339+
340+ // 1 ── rmsnorm: x_in → normed1
341+ enc.setComputePipelineState(self.p_rms.as_ref());
342+ set_buf(enc, 0, &self.x_in.0, self.x_in.1);
343+ set_buf(enc, 1, &self.normed1, 0);
344+ set_buf(enc, 2, &self.ln1_w.0, self.ln1_w.1);
345+ set_bytes(enc, 3, &self.hidden);
346+ set_bytes(enc, 4, &self.eps);
347+ enc.dispatchThreads_threadsPerThreadgroup(sz(self.tgw_rms, 1, 1), sz(self.tgw_rms, 1, 1));
348+ barrier(enc);
349+
350+ // 2 ── rotate (bf16 in): normed1 → xr1
351+ enc.setComputePipelineState(self.p_rot.as_ref());
352+ set_buf(enc, 0, &self.normed1, 0);
353+ set_buf(enc, 1, &self.xr1, 0);
354+ set_buf(enc, 2, &self.sign_h.0, self.sign_h.1);
355+ set_bytes(enc, 3, &self.hidden);
356+ set_bytes(enc, 4, &self.d);
357+ enc.dispatchThreadgroups_threadsPerThreadgroup(sz(1, hidden / d, 1), sz(d, 1, 1));
358+ barrier(enc);
359+
360+ // 3 ── fused q/k/v qmatvec (QROWS=4, bias epilogue): xr1 → qkv_out
361+ let out_qkv: u32 = (hidden + 2 * kvh * hd) as u32; // 2048
362+ enc.setComputePipelineState(self.p_qmv.as_ref());
363+ set_buf(enc, 0, &self.xr1, 0);
364+ set_buf(enc, 1, &self.qkv_codes, 0);
365+ set_buf(enc, 2, &self.qkv_rad, 0);
366+ unsafe {
367+ enc.setBytes_length_atIndex(
368+ NonNull::new(self.codebook.as_ptr() as *mut c_void).unwrap(),
369+ 32,
370+ 3,
371+ )
372+ };
373+ set_buf(enc, 4, &self.qkv_out, 0);
374+ set_bytes(enc, 5, &self.hidden);
375+ set_bytes(enc, 6, &out_qkv);
376+ set_bytes(enc, 7, &self.d);
377+ set_bytes(enc, 8, &one);
378+ set_buf(enc, 9, &self.qkv_bias, 0);
379+ set_bytes(enc, 10, &one); // has_bias
380+ set_buf(enc, 11, &self.qkv_codes, 0); // resid placeholder
381+ set_bytes(enc, 12, &zero); // has_resid
382+ let n_groups = (out_qkv as usize).div_ceil(4);
383+ enc.dispatchThreads_threadsPerThreadgroup(
384+ sz(n_groups * 32, 1, 1),
385+ sz(self.tgw_qmv, 1, 1),
386+ );
387+ barrier(enc);
388+
389+ // 4+5 ── RoPE on the strided q and k views of qkv_out (independent)
390+ let strides_q: [i32; 4] = [hidden as i32, hd as i32, hidden as i32, 1];
391+ let strides_k: [i32; 4] = [(kvh * hd) as i32, hd as i32, (kvh * hd) as i32, 1];
392+ let t_u: u32 = 1;
393+ for (h_u, strides, in_off, out_buf) in [
394+ (self.heads, strides_q, 0usize, &self.ropeq),
395+ (self.kvh, strides_k, hidden * 2, &self.ropek),
396+ ] {
397+ enc.setComputePipelineState(self.p_rope.as_ref());
398+ set_buf(enc, 0, &self.qkv_out, in_off);
399+ set_buf(enc, 1, out_buf, 0);
400+ set_buf(enc, 2, &self.cos.0, self.cos.1);
401+ set_buf(enc, 3, &self.sin.0, self.sin.1);
402+ set_bytes(enc, 4, &h_u);
403+ set_bytes(enc, 5, &t_u);
404+ set_bytes(enc, 6, &self.hd);
405+ unsafe {
406+ enc.setBytes_length_atIndex(
407+ NonNull::new(strides.as_ptr() as *mut c_void).unwrap(),
408+ 16,
409+ 7,
410+ )
411+ };
412+ enc.dispatchThreads_threadsPerThreadgroup(
413+ sz(hd / 2, 1, h_u as usize),
414+ sz(hd / 2, 1, 1),
415+ );
416+ }
417+ barrier(enc);
418+
419+ // 6 ── flash-decode partials (appends k/v at slot total-1 in-kernel)
420+ enc.setComputePipelineState(self.p_part.as_ref());
421+ set_buf(enc, 0, &self.ropeq, 0);
422+ set_buf(enc, 1, &self.k_cache, 0);
423+ set_buf(enc, 2, &self.v_cache, 0);
424+ set_buf(enc, 3, &self.pacc, 0);
425+ set_buf(enc, 4, &self.pm, 0);
426+ set_buf(enc, 5, &self.pl, 0);
427+ set_bytes(enc, 6, &self.heads);
428+ set_bytes(enc, 7, &self.kvh);
429+ set_bytes(enc, 8, &self.hd);
430+ set_bytes(enc, 9, &self.max_ctx);
431+ set_bytes(enc, 10, &self.total);
432+ set_bytes(enc, 11, &self.scale);
433+ set_bytes(enc, 12, &self.n_splits);
434+ set_buf(enc, 13, &self.ropek, 0);
435+ set_buf(enc, 14, &self.qkv_out, (hidden + kvh * hd) * 2); // v slice
436+ enc.dispatchThreadgroups_threadsPerThreadgroup(
437+ sz(heads, self.n_splits as usize, 1),
438+ sz(32, 1, 1),
439+ );
440+ barrier(enc);
441+
442+ // 7 ── combine partials → attn_f32
443+ enc.setComputePipelineState(self.p_comb.as_ref());
444+ set_buf(enc, 0, &self.pacc, 0);
445+ set_buf(enc, 1, &self.pm, 0);
446+ set_buf(enc, 2, &self.pl, 0);
447+ set_buf(enc, 3, &self.attn_f32, 0);
448+ set_bytes(enc, 4, &self.heads);
449+ set_bytes(enc, 5, &self.hd);
450+ set_bytes(enc, 6, &self.n_splits);
451+ enc.dispatchThreadgroups_threadsPerThreadgroup(sz(heads, 1, 1), sz(32, 1, 1));
452+ barrier(enc);
453+
454+ // 8 ── cast f32→bf16
455+ enc.setComputePipelineState(self.p_cast.as_ref());
456+ set_buf(enc, 0, &self.attn_f32, 0);
457+ set_buf(enc, 1, &self.attn_bf16, 0);
458+ enc.dispatchThreads_threadsPerThreadgroup(sz(hidden, 1, 1), sz(256, 1, 1));
459+ barrier(enc);
460+
461+ // 9 ── o_proj rotate
462+ enc.setComputePipelineState(self.p_rot.as_ref());
463+ set_buf(enc, 0, &self.attn_bf16, 0);
464+ set_buf(enc, 1, &self.xr2, 0);
465+ set_buf(enc, 2, &self.sign_h.0, self.sign_h.1);
466+ set_bytes(enc, 3, &self.hidden);
467+ set_bytes(enc, 4, &self.d);
468+ enc.dispatchThreadgroups_threadsPerThreadgroup(sz(1, hidden / d, 1), sz(d, 1, 1));
469+ barrier(enc);
470+
471+ // 10 ── o_proj qmatvec
472+ enc.setComputePipelineState(self.p_qmv.as_ref());
473+ set_buf(enc, 0, &self.xr2, 0);
474+ set_buf(enc, 1, &self.o_codes, 0);
475+ set_buf(enc, 2, &self.o_rad, 0);
476+ unsafe {
477+ enc.setBytes_length_atIndex(
478+ NonNull::new(self.codebook.as_ptr() as *mut c_void).unwrap(),
479+ 32,
480+ 3,
481+ )
482+ };
483+ set_buf(enc, 4, &self.o_out, 0);
484+ set_bytes(enc, 5, &self.hidden);
485+ set_bytes(enc, 6, &self.hidden);
486+ set_bytes(enc, 7, &self.d);
487+ set_bytes(enc, 8, &one);
488+ set_buf(enc, 9, &self.o_codes, 0); // bias placeholder
489+ set_bytes(enc, 10, &zero);
490+ set_buf(enc, 11, &self.o_codes, 0); // resid placeholder
491+ set_bytes(enc, 12, &zero);
492+ enc.dispatchThreads_threadsPerThreadgroup(
493+ sz(hidden.div_ceil(4) * 32, 1, 1),
494+ sz(self.tgw_qmv, 1, 1),
495+ );
496+ barrier(enc);
497+
498+ // 11 ── fused residual-add + RMSNorm: (x_in, o_out) → (h_buf, normed2)
499+ enc.setComputePipelineState(self.p_addnorm.as_ref());
500+ set_buf(enc, 0, &self.x_in.0, self.x_in.1);
501+ set_buf(enc, 1, &self.o_out, 0);
502+ set_buf(enc, 2, &self.h_buf, 0);
503+ set_buf(enc, 3, &self.normed2, 0);
504+ set_buf(enc, 4, &self.ln2_w.0, self.ln2_w.1);
505+ set_bytes(enc, 5, &self.hidden);
506+ set_bytes(enc, 6, &self.eps);
507+ enc.dispatchThreads_threadsPerThreadgroup(
508+ sz(self.tgw_addnorm, 1, 1),
509+ sz(self.tgw_addnorm, 1, 1),
510+ );
511+ barrier(enc);
512+
513+ // 12 ── gate/up rotate
514+ enc.setComputePipelineState(self.p_rot.as_ref());
515+ set_buf(enc, 0, &self.normed2, 0);
516+ set_buf(enc, 1, &self.xr3, 0);
517+ set_buf(enc, 2, &self.sign_h.0, self.sign_h.1);
518+ set_bytes(enc, 3, &self.hidden);
519+ set_bytes(enc, 4, &self.d);
520+ enc.dispatchThreadgroups_threadsPerThreadgroup(sz(1, hidden / d, 1), sz(d, 1, 1));
521+ barrier(enc);
522+
523+ // 13 ── fused SwiGLU qmatvec: xr3 → act (silu(gate)·up, width I)
524+ enc.setComputePipelineState(self.p_swiglu.as_ref());
525+ set_buf(enc, 0, &self.xr3, 0);
526+ set_buf(enc, 1, &self.gu_codes, 0);
527+ set_buf(enc, 2, &self.gu_rad, 0);
528+ unsafe {
529+ enc.setBytes_length_atIndex(
530+ NonNull::new(self.codebook.as_ptr() as *mut c_void).unwrap(),
531+ 32,
532+ 3,
533+ )
534+ };
535+ set_buf(enc, 4, &self.act, 0);
536+ set_bytes(enc, 5, &self.hidden);
537+ set_bytes(enc, 6, &self.inter);
538+ set_bytes(enc, 7, &self.d);
539+ set_bytes(enc, 8, &one);
540+ enc.dispatchThreads_threadsPerThreadgroup(
541+ sz(inter.div_ceil(4) * 32, 1, 1),
542+ sz(self.tgw_qmv, 1, 1),
543+ );
544+ barrier(enc);
545+
546+ // 14 ── down rotate (inn = I)
547+ enc.setComputePipelineState(self.p_rot.as_ref());
548+ set_buf(enc, 0, &self.act, 0);
549+ set_buf(enc, 1, &self.xr4, 0);
550+ set_buf(enc, 2, &self.sign_i.0, self.sign_i.1);
551+ set_bytes(enc, 3, &self.inter);
552+ set_bytes(enc, 4, &self.d);
553+ enc.dispatchThreadgroups_threadsPerThreadgroup(sz(1, inter / d, 1), sz(d, 1, 1));
554+ barrier(enc);
555+
556+ // 15 ── down qmatvec: xr4 → dn_out
557+ enc.setComputePipelineState(self.p_qmv.as_ref());
558+ set_buf(enc, 0, &self.xr4, 0);
559+ set_buf(enc, 1, &self.dn_codes, 0);
560+ set_buf(enc, 2, &self.dn_rad, 0);
561+ unsafe {
562+ enc.setBytes_length_atIndex(
563+ NonNull::new(self.codebook.as_ptr() as *mut c_void).unwrap(),
564+ 32,
565+ 3,
566+ )
567+ };
568+ set_buf(enc, 4, &self.dn_out, 0);
569+ set_bytes(enc, 5, &self.inter);
570+ set_bytes(enc, 6, &self.hidden);
571+ set_bytes(enc, 7, &self.d);
572+ set_bytes(enc, 8, &one);
573+ set_buf(enc, 9, &self.dn_codes, 0);
574+ set_bytes(enc, 10, &zero);
575+ set_buf(enc, 11, &self.dn_codes, 0);
576+ set_bytes(enc, 12, &zero);
577+ enc.dispatchThreads_threadsPerThreadgroup(
578+ sz(hidden.div_ceil(4) * 32, 1, 1),
579+ sz(self.tgw_qmv, 1, 1),
580+ );
581+ barrier(enc);
582+
583+ // 16 ── final residual add: h_buf + dn_out → final_out
584+ enc.setComputePipelineState(self.p_add.as_ref());
585+ set_buf(enc, 0, &self.h_buf, 0);
586+ set_buf(enc, 1, &self.dn_out, 0);
587+ set_buf(enc, 2, &self.final_out, 0);
588+ enc.dispatchThreads_threadsPerThreadgroup(sz(hidden, 1, 1), sz(256, 1, 1));
589+ }
590+}
591+
592+// ───────────────────────────── main ─────────────────────────────
593+
594+fn main() -> Result<()> {
595+ let args = Args::parse();
596+
597+ // Guard: this prototype asserts the DEFAULT engine config.
598+ for v in [
599+ "COCO_FUSE_RESID", "COCO_FUSE_ROTATE_IN", "COCO_NO_FUSE", "COCO_NO_FUSE_NORM",
600+ "COCO_NO_FUSE_ADDNORM", "COCO_NO_FUSE_ROPE", "COCO_QROWS", "COCO_QW2", "COCO_QOCC",
601+ "COCO_PACK_BITS", "COCO_KV_BITS", "COCO_FUSE_SWIGLU", "COCO_FFN_MEGA",
602+ "COCO_SPLIT_TARGET", "COCO_SKIP_ROTATE", "COCO_FUSED_ATTN", "COCO_FUSED_MIN_CTX",
603+ ] {
604+ if std::env::var(v).is_ok() {
605+ return Err(anyhow!("unset {v} — enc_proto requires default engine config"));
606+ }
607+ }
608+
609+ let device = Device::new_metal(0).context("Metal device")?;
610+ let mdev = match &device {
611+ Device::Metal(m) => m.clone(),
612+ _ => unreachable!(),
613+ };
614+
615+ // config.json → dims
616+ let cfgj: serde_json::Value =
617+ serde_json::from_slice(&std::fs::read(args.model.join("config.json"))?)?;
618+ let gi = |k: &str| cfgj[k].as_u64().unwrap() as usize;
619+ let dims = Dims {
620+ hidden: gi("hidden_size"),
621+ inter: gi("intermediate_size"),
622+ heads: gi("num_attention_heads"),
623+ kv: gi("num_key_value_heads"),
624+ hd: gi("hidden_size") / gi("num_attention_heads"),
625+ d: 128,
626+ eps: cfgj["rms_norm_eps"].as_f64().unwrap() as f32,
627+ theta: cfgj["rope_theta"].as_f64().unwrap() as f32,
628+ };
629+ eprintln!(
630+ "[setup] dims: hidden={} I={} heads={} kv={} hd={} | ctx={} iters={}",
631+ dims.hidden, dims.inter, dims.heads, dims.kv, dims.hd, args.ctx, args.iters
632+ );
633+
634+ let layer = load_layer0(&args.model, &dims, &device)?;
635+
636+ // KV cache prefilled to depth ctx with bounded pseudo-random values.
637+ let max_ctx = args.ctx + 8;
638+ let mut kc = KvCache::new(dims.heads, dims.kv, dims.hd, max_ctx, &device)?;
639+ if args.ctx > 0 {
640+ let n = dims.kv * args.ctx * dims.hd;
641+ let mk = |ph: f32| -> Vec<bf16> {
642+ (0..n)
643+ .map(|i| bf16::from_f32(0.3 * ((i as f32) * 0.11 + ph).sin()))
644+ .collect()
645+ };
646+ let k = Tensor::from_vec(mk(0.0), (dims.kv, args.ctx, dims.hd), &device)?;
647+ let v = Tensor::from_vec(mk(1.7), (dims.kv, args.ctx, dims.hd), &device)?;
648+ kc.append_prefill(&k, &v)?;
649+ }
650+
651+ // Fixed input hidden state + this position's RoPE cos/sin slice.
652+ let xs_v: Vec<bf16> = (0..dims.hidden)
653+ .map(|i| bf16::from_f32(0.05 * ((i as f32) * 0.37).sin()))
654+ .collect();
655+ let xs = Tensor::from_vec(xs_v, (1, 1, dims.hidden), &device)?;
656+ let hd2 = dims.hd / 2;
657+ let npos = args.ctx + 4;
658+ let mut cos_v = Vec::with_capacity(npos * hd2);
659+ let mut sin_v = Vec::with_capacity(npos * hd2);
660+ for pos in 0..npos {
661+ for i in 0..hd2 {
662+ let f = pos as f32 / dims.theta.powf((2 * i) as f32 / dims.hd as f32);
663+ cos_v.push(bf16::from_f32(f.cos()));
664+ sin_v.push(bf16::from_f32(f.sin()));
665+ }
666+ }
667+ let cos_t = Tensor::from_vec(cos_v, (npos, hd2), &device)?;
668+ let sin_t = Tensor::from_vec(sin_v, (npos, hd2), &device)?;
669+ let cos = cos_t.narrow(0, args.ctx, 1)?;
670+ let sin = sin_t.narrow(0, args.ctx, 1)?;
671+
672+ // ── build the RAW context ────────────────────────────────────────────────
673+ let kdev = mdev.metal_device().clone();
674+ let pipes = qlinear::get_pipelines(&kdev)?;
675+ let extra_lib = kdev
676+ .new_library_with_source(EXTRA_SRC, None)
677+ .map_err(|e| anyhow!("extra MSL: {e}"))?;
678+ let extra_pipe = |name: &str| -> Result<ComputePipeline> {
679+ let f = extra_lib.get_function(name, None).map_err(|e| anyhow!("{name}: {e}"))?;
680+ kdev.new_compute_pipeline_state_with_function(&f)
681+ .map_err(|e| anyhow!("pipeline {name}: {e}"))
682+ };
683+
684+ let opts = MTLResourceOptions(
685+ MTLResourceOptions::StorageModeShared.0 | MTLResourceOptions::HazardTrackingModeUntracked.0,
686+ );
687+ let mkbuf = |elems: usize, esz: usize, label: &str| -> Result<KBuffer> {
688+ let b = kdev
689+ .new_buffer((elems * esz).max(16), opts)
690+ .map_err(|e| anyhow!("alloc {label}: {e}"))?;
691+ b.set_label(label);
692+ Ok(b)
693+ };
694+
695+ let total = (args.ctx + 1) as u32;
696+ let n_splits = 128usize.min(((args.ctx + 1) / 16).max(1)).clamp(1, 256) as u32;
697+ let tgw_of = |p: &ComputePipeline, cap_inn: Option<usize>| -> usize {
698+ let mut w = (8 * 32).min(p.max_total_threads_per_threadgroup());
699+ if let Some(inn) = cap_inn {
700+ w = w.min(inn);
701+ }
702+ (w / 32).max(1) * 32
703+ };
704+
705+ let raw = RawLayer {
706+ p_rms: pipes.rmsnorm.clone(),
707+ p_rot: pipes.rotate_bf16.clone(),
708+ p_qmv: pipes.qmatvec_bf16_r.clone(),
709+ p_rope: pipes.rope_bf16.clone(),
710+ p_part: pipes.attn_partial.clone(),
711+ p_comb: pipes.attn_combine.clone(),
712+ p_addnorm: pipes.add_rmsnorm.clone(),
713+ p_swiglu: pipes.qmatvec_swiglu_r.clone(),
714+ p_cast: extra_pipe("ep_cast_f32_bf16")?,
715+ p_add: extra_pipe("ep_add_bf16")?,
716+ qkv_codes: (*layer.qkv.codes).clone(),
717+ qkv_rad: (*layer.qkv.radius).clone(),
718+ qkv_bias: (**layer.qkv.bias_bf16.as_ref().unwrap()).clone(),
719+ o_codes: (*layer.o.codes).clone(),
720+ o_rad: (*layer.o.radius).clone(),
721+ gu_codes: (*layer.gate_up.codes).clone(),
722+ gu_rad: (*layer.gate_up.radius).clone(),
723+ dn_codes: (*layer.down.codes).clone(),
724+ dn_rad: (*layer.down.radius).clone(),
725+ codebook: {
726+ let mut cb = [0f32; 8];
727+ cb.copy_from_slice(&layer.qkv.codebook);
728+ cb
729+ },
730+ sign_h: tbuf(&layer.qkv.sign)?,
731+ sign_i: tbuf(&layer.down.sign)?,
732+ ln1_w: tbuf(&layer.ln1.weight)?,
733+ ln2_w: tbuf(&layer.ln2.weight)?,
734+ cos: tbuf(&cos)?,
735+ sin: tbuf(&sin)?,
736+ x_in: tbuf(&xs)?,
737+ k_cache: (*kc.k_cache).clone(),
738+ v_cache: (*kc.v_cache).clone(),
739+ pacc: (*kc.pacc).clone(),
740+ pm: (*kc.pm).clone(),
741+ pl: (*kc.pl).clone(),
742+ normed1: mkbuf(dims.hidden, 2, "ep_normed1")?,
743+ xr1: mkbuf(dims.hidden, 4, "ep_xr1")?,
744+ qkv_out: mkbuf(dims.hidden + 2 * dims.kv * dims.hd, 2, "ep_qkv_out")?,
745+ ropeq: mkbuf(dims.heads * dims.hd, 2, "ep_ropeq")?,
746+ ropek: mkbuf(dims.kv * dims.hd, 2, "ep_ropek")?,
747+ attn_f32: mkbuf(dims.hidden, 4, "ep_attn_f32")?,
748+ attn_bf16: mkbuf(dims.hidden, 2, "ep_attn_bf16")?,
749+ xr2: mkbuf(dims.hidden, 4, "ep_xr2")?,
750+ o_out: mkbuf(dims.hidden, 2, "ep_o_out")?,
751+ h_buf: mkbuf(dims.hidden, 2, "ep_h")?,
752+ normed2: mkbuf(dims.hidden, 2, "ep_normed2")?,
753+ xr3: mkbuf(dims.hidden, 4, "ep_xr3")?,
754+ act: mkbuf(dims.inter, 2, "ep_act")?,
755+ xr4: mkbuf(dims.inter, 4, "ep_xr4")?,
756+ dn_out: mkbuf(dims.hidden, 2, "ep_dn_out")?,
757+ final_out: mkbuf(dims.hidden, 2, "ep_final")?,
758+ hidden: dims.hidden as u32,
759+ inter: dims.inter as u32,
760+ heads: dims.heads as u32,
761+ kvh: dims.kv as u32,
762+ hd: dims.hd as u32,
763+ d: dims.d as u32,
764+ eps: dims.eps,
765+ scale: 1.0 / (dims.hd as f32).sqrt(),
766+ max_ctx: max_ctx as u32,
767+ total,
768+ pos_ctx: args.ctx as u32,
769+ n_splits,
770+ tgw_rms: tgw_of(&pipes.rmsnorm, Some(dims.hidden)),
771+ tgw_qmv: tgw_of(&pipes.qmatvec_bf16_r, None),
772+ tgw_addnorm: tgw_of(&pipes.add_rmsnorm, Some(dims.hidden)),
773+ };
774+ eprintln!(
775+ "[setup] raw ctx ready | n_splits={} total={} tgw(rms/qmv/addnorm)={}/{}/{}",
776+ n_splits, total, raw.tgw_rms, raw.tgw_qmv, raw.tgw_addnorm
777+ );
778+
779+ // Own queue on the same MTLDevice (candle 0.11 hides its CommandQueue; the
780+ // raw MTLDevice is reachable via MetalDevice::metal_device()).
781+ let queue: Retained<ProtocolObject<dyn MTLCommandQueue>> = kdev
782+ .as_ref()
783+ .newCommandQueue()
784+ .ok_or_else(|| anyhow!("newCommandQueue failed"))?;
785+
786+ // ── numerical check ──────────────────────────────────────────────────────
787+ device.synchronize()?;
788+ kc.len = args.ctx;
789+ let out_a = candle_layer_forward(&xs, &layer, &mut kc, &cos, &sin, &dims)?;
790+ let a_v: Vec<f32> = out_a.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
791+ device.synchronize()?; // drain candle's queue before touching ours
792+
793+ let cb = queue.commandBuffer().ok_or_else(|| anyhow!("cb"))?;
794+ let enc = cb
795+ .computeCommandEncoderWithDispatchType(MTLDispatchType::Concurrent)
796+ .ok_or_else(|| anyhow!("encoder"))?;
797+ raw.encode_iter(&enc, true);
798+ enc.endEncoding();
799+ cb.commit();
800+ cb.waitUntilCompleted();
801+ let b_v: Vec<f32> = unsafe {
802+ let p = raw.final_out.contents() as *const u16;
803+ (0..dims.hidden)
804+ .map(|i| bf16::from_bits(*p.add(i)).to_f32())
805+ .collect()
806+ };
807+ let mut max_diff = 0f32;
808+ let mut argmax = 0usize;
809+ for i in 0..dims.hidden {
810+ let dv = (a_v[i] - b_v[i]).abs();
811+ if dv > max_diff {
812+ max_diff = dv;
813+ argmax = i;
814+ }
815+ }
816+ println!(
817+ "NUMCHECK max|candle-raw| = {:.6} at {} (a={:.5} b={:.5})",
818+ max_diff, argmax, a_v[argmax], b_v[argmax]
819+ );
820+
821+ // ── (a) candle path, pipelined ───────────────────────────────────────────
822+ for _ in 0..args.warmup {
823+ kc.len = args.ctx;
824+ let _ = candle_layer_forward(&xs, &layer, &mut kc, &cos, &sin, &dims)?;
825+ }
826+ device.synchronize()?;
827+ let mut a_best = f64::MAX;
828+ for _ in 0..args.reps {
829+ let t0 = std::time::Instant::now();
830+ for _ in 0..args.iters {
831+ kc.len = args.ctx;
832+ let _ = candle_layer_forward(&xs, &layer, &mut kc, &cos, &sin, &dims)?;
833+ }
834+ device.synchronize()?;
835+ a_best = a_best.min(t0.elapsed().as_secs_f64());
836+ }
837+ let a_ms = a_best / args.iters as f64 * 1e3;
838+
839+ // ── (a2) candle path, sync every iteration (latency bound) ──────────────
840+ let a2_iters = (args.iters / 4).max(20);
841+ let t0 = std::time::Instant::now();
842+ for _ in 0..a2_iters {
843+ kc.len = args.ctx;
844+ let _ = candle_layer_forward(&xs, &layer, &mut kc, &cos, &sin, &dims)?;
845+ device.synchronize()?;
846+ }
847+ let a2_ms = t0.elapsed().as_secs_f64() / a2_iters as f64 * 1e3;
848+
849+ device.synchronize()?;
850+
851+ // ── (b) raw single encoder: all iters in ONE encoder/commit ─────────────
852+ // warmup
853+ {
854+ let cb = queue.commandBuffer().ok_or_else(|| anyhow!("cb"))?;
855+ let enc = cb
856+ .computeCommandEncoderWithDispatchType(MTLDispatchType::Concurrent)
857+ .ok_or_else(|| anyhow!("encoder"))?;
858+ for i in 0..args.warmup {
859+ raw.encode_iter(&enc, i == 0);
860+ }
861+ enc.endEncoding();
862+ cb.commit();
863+ cb.waitUntilCompleted();
864+ }
865+ let mut b_best = f64::MAX;
866+ let mut b_encode_ms = 0f64;
867+ for _ in 0..args.reps {
868+ let t0 = std::time::Instant::now();
869+ let cb = queue.commandBuffer().ok_or_else(|| anyhow!("cb"))?;
870+ let enc = cb
871+ .computeCommandEncoderWithDispatchType(MTLDispatchType::Concurrent)
872+ .ok_or_else(|| anyhow!("encoder"))?;
873+ for i in 0..args.iters {
874+ raw.encode_iter(&enc, i == 0);
875+ }
876+ enc.endEncoding();
877+ let t_enc = t0.elapsed().as_secs_f64();
878+ cb.commit();
879+ cb.waitUntilCompleted();
880+ let wall = t0.elapsed().as_secs_f64();
881+ if wall < b_best {
882+ b_best = wall;
883+ b_encode_ms = t_enc / args.iters as f64 * 1e3;
884+ }
885+ }
886+ let b_ms = b_best / args.iters as f64 * 1e3;
887+
888+ // ── (b2) raw, one command buffer + wait per iteration (worst case) ──────
889+ let b2_iters = (args.iters / 4).max(20);
890+ let t0 = std::time::Instant::now();
891+ for _ in 0..b2_iters {
892+ let cb = queue.commandBuffer().ok_or_else(|| anyhow!("cb"))?;
893+ let enc = cb
894+ .computeCommandEncoderWithDispatchType(MTLDispatchType::Concurrent)
895+ .ok_or_else(|| anyhow!("encoder"))?;
896+ raw.encode_iter(&enc, true);
897+ enc.endEncoding();
898+ cb.commit();
899+ cb.waitUntilCompleted();
900+ }
901+ let b2_ms = t0.elapsed().as_secs_f64() / b2_iters as f64 * 1e3;
902+
903+ println!();
904+ println!(
905+ "ENC_PROTO layer0 Qwen2.5-1.5B | ctx={} iters={} reps={} | 16 dispatches/iter (14 custom + cast + add), 15 raw barriers/iter",
906+ args.ctx, args.iters, args.reps
907+ );
908+ println!(" (a) candle path, pipelined : {:.4} ms/layer-step", a_ms);
909+ println!(
910+ " (b) RAW one-encoder, one commit : {:.4} ms/layer-step (CPU encode {:.4} ms/iter)",
911+ b_ms, b_encode_ms
912+ );
913+ println!(" RATIO (a)/(b) = {:.2}x", a_ms / b_ms);
914+ println!(
915+ " (a2) candle, sync each iter : {:.4} ms/layer-step [latency bound]",
916+ a2_ms
917+ );
918+ println!(
919+ " (b2) RAW, commit+wait each iter : {:.4} ms/layer-step [worst-case commit cost]",
920+ b2_ms
921+ );
922+ println!(" NUMCHECK max|a-b| = {:.6}", max_diff);
923+
924+ Ok(())
925+}
added src/bin/evomerge.rs +259 −0
@@ -0,0 +1,259 @@
1+// coco-evomerge — Step 1 of the evolutionary-merge capability.
2+//
3+// Loads both parents CPU-resident (f32, once), merges by a num_layers+2 genome into
4+// ONE in-memory child, builds a runnable coco Model on Metal, and runs the fixed
5+// 16 GSM8K + 16 ARC-Easy eval. Step-1 mode: score the two PURE parents
6+// (genome all-0 = parentA, all-1 = parentB) + the midpoint (all-0.5) + optionally an
7+// arbitrary genome, printing math/general/combined for each. --repeat N re-evals to
8+// measure RSS stability. The GA loop is Step 2 (not here).
9+//
10+// GPU note: cargo build is CPU-only. RUNNING this touches Metal → the shared-Mac GPU
11+// lock is required (this bin does NOT acquire it; the caller/next phase does — this
12+// Step-1 handoff builds clean and is run under the lock in the GPU gate).
13+
14+use std::collections::HashMap;
15+use std::path::PathBuf;
16+
17+use anyhow::{anyhow, Result};
18+use candle_core::{DType, Device};
19+use clap::Parser;
20+use tokenizers::Tokenizer;
21+
22+use coco_engine::config::CocoConfig;
23+use coco_engine::eval::{fitness, EvalItems, Fitness};
24+use coco_engine::merge::{
25+ build_child_dense, build_child_quant, dense_config_from_dir, load_parent_f32,
26+ merge_full,
27+};
28+
29+#[derive(Parser, Debug)]
30+#[command(name = "coco-evomerge", about = "Step 1 — merge + eval one genome, baselines vs Python")]
31+struct Args {
32+ /// Parent A (general): Qwen2.5-1.5B-Instruct. genome all-0 = this.
33+ #[arg(long, default_value = "./model-instruct")]
34+ parent_a: PathBuf,
35+
36+ /// Parent B (math): Qwen2.5-Math-1.5B-Instruct. genome all-1 = this.
37+ #[arg(long, default_value = "./model-math")]
38+ parent_b: PathBuf,
39+
40+ /// eval_items.json (baked 16 GSM8K + 16 ARC-Easy).
41+ #[arg(long, default_value = "./eval_items.json")]
42+ eval_items: PathBuf,
43+
44+ /// Number of GSM8K math items to score (<= baked 16).
45+ #[arg(long, default_value_t = 16)]
46+ n_math: usize,
47+
48+ /// Number of ARC-Easy items to score (<= baked 16).
49+ #[arg(long, default_value_t = 16)]
50+ n_general: usize,
51+
52+ /// Dense fp16/bf16 build (NO turboquant) — the numeric-parity gate vs Python.
53+ /// Without this flag, the 3-bit turboquant search representation is used.
54+ #[arg(long)]
55+ no_quant: bool,
56+
57+ /// Force CPU (bit-faithful f32 eval; slow). Default = Metal (bf16).
58+ #[arg(long)]
59+ cpu: bool,
60+
61+ /// Also eval this arbitrary genome (JSON array of num_layers+2 floats in [0,1]).
62+ #[arg(long)]
63+ eval_genome: Option<PathBuf>,
64+
65+ /// Re-eval every genome this many times to measure RSS stability (default 1).
66+ #[arg(long, default_value_t = 1)]
67+ repeat: usize,
68+
69+ /// Write the baseline results here (JSON).
70+ #[arg(long)]
71+ out: Option<PathBuf>,
72+}
73+
74+fn pick_device(force_cpu: bool) -> Result<Device> {
75+ if force_cpu {
76+ return Ok(Device::Cpu);
77+ }
78+ if candle_core::utils::metal_is_available() {
79+ match Device::new_metal(0) {
80+ Ok(d) => return Ok(d),
81+ Err(e) => eprintln!("warning: Metal failed ({e}); CPU fallback"),
82+ }
83+ }
84+ Ok(Device::Cpu)
85+}
86+
87+/// Coarse RSS (MB) of this process — the memory-stability signal for Step 1.
88+fn rss_mb() -> u64 {
89+ #[cfg(target_os = "macos")]
90+ {
91+ let pid = std::process::id();
92+ if let Ok(out) = std::process::Command::new("ps")
93+ .args(["-o", "rss=", "-p", &pid.to_string()])
94+ .output()
95+ {
96+ if let Ok(s) = String::from_utf8(out.stdout) {
97+ if let Ok(kb) = s.trim().parse::<u64>() {
98+ return kb / 1024;
99+ }
100+ }
101+ }
102+ }
103+ 0
104+}
105+
106+fn eval_genome(
107+ label: &str,
108+ genome: &[f32],
109+ a_map: &HashMap<String, candle_core::Tensor>,
110+ b_map: &HashMap<String, candle_core::Tensor>,
111+ coco_cfg: &CocoConfig,
112+ dense_cfg: &candle_transformers::models::qwen2::Config,
113+ tok: &Tokenizer,
114+ dev: &Device,
115+ dtype: DType,
116+ no_quant: bool,
117+ items: &EvalItems,
118+ repeat: usize,
119+) -> Result<Fitness> {
120+ let mut last = Fitness { math: 0.0, general: 0.0, combined: 0.0 };
121+ for r in 0..repeat.max(1) {
122+ let rss0 = rss_mb();
123+ // Blend on CPU (transient f32 temporaries drop at end of scope).
124+ let full = merge_full(genome, a_map, b_map)?;
125+ // Build ONE child on Metal.
126+ let mut model = if no_quant {
127+ build_child_dense(&full, dense_cfg, dev, dtype)?
128+ } else {
129+ build_child_quant(full, coco_cfg, dev, dtype)?
130+ };
131+ let f = fitness(&mut *model, tok, dev, items)?;
132+ // Deterministic drop BEFORE the next candidate + drain barrier.
133+ drop(model);
134+ dev.synchronize()?;
135+ let rss1 = rss_mb();
136+ println!(
137+ " [{label}] rep {}/{}: math={:.3} general={:.3} combined={:.3} | rss {}→{} MB",
138+ r + 1,
139+ repeat.max(1),
140+ f.math,
141+ f.general,
142+ f.combined,
143+ rss0,
144+ rss1
145+ );
146+ last = f;
147+ }
148+ Ok(last)
149+}
150+
151+fn main() -> Result<()> {
152+ let args = Args::parse();
153+
154+ let dev = pick_device(args.cpu)?;
155+ let dtype = if dev.is_cpu() { DType::F32 } else { DType::BF16 };
156+ println!(
157+ "coco-evomerge | device: {} | dtype: {:?} | build: {}",
158+ if dev.is_cpu() { "CPU" } else { "Metal" },
159+ dtype,
160+ if args.no_quant { "dense fp16 (parity gate)" } else { "turboquant 3-bit" }
161+ );
162+
163+ // Compatibility guard (Step-3 requirement, cheap to run now): identical arch + vocab.
164+ let cfg_a = CocoConfig::from_dir(&args.parent_a)?;
165+ let cfg_b = CocoConfig::from_dir(&args.parent_b)?;
166+ if cfg_a.num_hidden_layers != cfg_b.num_hidden_layers
167+ || cfg_a.hidden_size != cfg_b.hidden_size
168+ || cfg_a.vocab_size != cfg_b.vocab_size
169+ {
170+ return Err(anyhow!(
171+ "parent shape mismatch: A(layers={},hidden={},vocab={}) vs B(layers={},hidden={},vocab={})",
172+ cfg_a.num_hidden_layers, cfg_a.hidden_size, cfg_a.vocab_size,
173+ cfg_b.num_hidden_layers, cfg_b.hidden_size, cfg_b.vocab_size,
174+ ));
175+ }
176+ let genome_len = cfg_a.num_hidden_layers + 2;
177+ println!(
178+ "parents: {} layers, hidden {}, vocab {} → genome_len {}",
179+ cfg_a.num_hidden_layers, cfg_a.hidden_size, cfg_a.vocab_size, genome_len
180+ );
181+
182+ // Tokenizer (identical across both parents — verified byte-identical).
183+ let tok = Tokenizer::from_file(args.parent_a.join("tokenizer.json"))
184+ .map_err(|e| anyhow!("loading tokenizer: {e}"))?;
185+
186+ // candle-qwen2 Config for the --no-quant dense path (built from parent A; parents
187+ // share identical shape/config).
188+ let dense_cfg = dense_config_from_dir(&args.parent_a)?;
189+
190+ // Fixed eval items (baked 16+16), truncated to requested counts.
191+ let items = EvalItems::load(&args.eval_items)?.take(args.n_math, args.n_general);
192+ println!(
193+ "eval items: {} math + {} general",
194+ items.math.len(),
195+ items.general.len()
196+ );
197+
198+ // Parents CPU-resident, f32, loaded ONCE. CPU RAM never fragments the Metal heap.
199+ println!("loading parent A (f32, CPU): {}", args.parent_a.display());
200+ let a_map = load_parent_f32(&args.parent_a)?;
201+ println!("loading parent B (f32, CPU): {}", args.parent_b.display());
202+ let b_map = load_parent_f32(&args.parent_b)?;
203+ println!("parents resident: {} tensors each", a_map.len());
204+
205+ let g0 = vec![0.0f32; genome_len]; // all-0 → pure parent A (general)
206+ let g1 = vec![1.0f32; genome_len]; // all-1 → pure parent B (math)
207+ let ghalf = vec![0.5f32; genome_len]; // midpoint
208+
209+ println!("\n=== Step-1 baselines ({} reps each) ===", args.repeat.max(1));
210+ let f_a = eval_genome("all-0 = parentA", &g0, &a_map, &b_map, &cfg_a, &dense_cfg, &tok, &dev, dtype, args.no_quant, &items, args.repeat)?;
211+ let f_b = eval_genome("all-1 = parentB", &g1, &a_map, &b_map, &cfg_a, &dense_cfg, &tok, &dev, dtype, args.no_quant, &items, args.repeat)?;
212+ let f_h = eval_genome("all-0.5 = midpoint", &ghalf, &a_map, &b_map, &cfg_a, &dense_cfg, &tok, &dev, dtype, args.no_quant, &items, args.repeat)?;
213+
214+ // Optional arbitrary genome.
215+ let f_x = if let Some(path) = &args.eval_genome {
216+ let raw = std::fs::read(path)?;
217+ let genome: Vec<f32> = serde_json::from_slice(&raw)?;
218+ if genome.len() != genome_len {
219+ return Err(anyhow!(
220+ "eval-genome length {} != genome_len {}",
221+ genome.len(),
222+ genome_len
223+ ));
224+ }
225+ Some(eval_genome("arbitrary", &genome, &a_map, &b_map, &cfg_a, &dense_cfg, &tok, &dev, dtype, args.no_quant, &items, args.repeat)?)
226+ } else {
227+ None
228+ };
229+
230+ println!("\n=== summary ===");
231+ let show = |name: &str, f: &Fitness| {
232+ println!(" {name:<22} math={:.3} general={:.3} combined={:.3}", f.math, f.general, f.combined);
233+ };
234+ show("parentA (all-0)", &f_a);
235+ show("parentB (all-1)", &f_b);
236+ show("midpoint (all-0.5)", &f_h);
237+ if let Some(f) = &f_x {
238+ show("arbitrary", f);
239+ }
240+
241+ if let Some(out) = &args.out {
242+ let mut obj = serde_json::json!({
243+ "build": if args.no_quant { "dense_fp16" } else { "turboquant_3bit" },
244+ "n_math": items.math.len(),
245+ "n_general": items.general.len(),
246+ "genome_len": genome_len,
247+ "parentA": {"math": f_a.math, "general": f_a.general, "combined": f_a.combined},
248+ "parentB": {"math": f_b.math, "general": f_b.general, "combined": f_b.combined},
249+ "midpoint": {"math": f_h.math, "general": f_h.general, "combined": f_h.combined},
250+ });
251+ if let Some(f) = &f_x {
252+ obj["arbitrary"] = serde_json::json!({"math": f.math, "general": f.general, "combined": f.combined});
253+ }
254+ std::fs::write(out, serde_json::to_string_pretty(&obj)?)?;
255+ println!("wrote {}", out.display());
256+ }
257+
258+ Ok(())
259+}
added src/bin/gdn_ref.rs +140 −0
@@ -0,0 +1,140 @@
1+// gdn_ref — ORACLE validation for the GatedDeltaNet port (candle 0.11).
2+//
3+// Loads the golden fixture (tests/fixtures/gdn_oracle/oracle.safetensors: input + the 7
4+// weights + the reference output from HF Qwen3NextGatedDeltaNet) and re-computes the layer
5+// forward with candle Tensor ops, following the numpy-verified BLUEPRINT.md (matched the HF
6+// oracle to 4e-7). Prints `max abs err` vs golden — the port is correct when this is < 1e-4.
7+//
8+// cargo run --release --bin gdn_ref
9+use anyhow::{anyhow, Result};
10+use candle_core::{DType, Device, IndexOp, Tensor, D};
11+
12+fn silu(x: &Tensor) -> Result<Tensor> {
13+ Ok((x * candle_nn::ops::sigmoid(x)?)?)
14+}
15+fn softplus(x: &Tensor) -> Result<Tensor> {
16+ // ln(1 + exp(x)); oracle magnitudes are small, the naive form is fine here.
17+ Ok(((x.exp()? + 1.0)?).log()?)
18+}
19+fn l2norm(x: &Tensor, eps: f64) -> Result<Tensor> {
20+ let denom = (x.sqr()?.sum_keepdim(D::Minus1)? + eps)?.sqrt()?;
21+ Ok(x.broadcast_div(&denom)?)
22+}
23+
24+fn main() -> Result<()> {
25+ let dev = Device::Cpu; // validate in f32 on CPU (the oracle is f32)
26+ let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/gdn_oracle");
27+ let t = candle_core::safetensors::load(format!("{dir}/oracle.safetensors"), &dev)?;
28+ let g = |k: &str| -> Result<Tensor> {
29+ Ok(t.get(k).ok_or_else(|| anyhow!("missing {k}"))?.to_dtype(DType::F32)?)
30+ };
31+ let x = g("input")?.squeeze(0)?; // [s,256]
32+ let w_qkvz = g("in_proj_qkvz__weight")?; // [768,256]
33+ let w_ba = g("in_proj_ba__weight")?; // [16,256]
34+ let conv_w = g("conv1d__weight")?; // [512,1,4]
35+ let a_log = g("A_log")?; // [nv]
36+ let dt = g("dt_bias")?; // [nv]
37+ let norm_w = g("norm__weight")?; // [hv]
38+ let w_out = g("out_proj__weight")?; // [256,256]
39+ let gold = g("output")?.squeeze(0)?; // [s,256]
40+
41+ let (s, nk, nv, hk, hv, ck) = (x.dim(0)?, 4usize, 8usize, 32usize, 32usize, 4usize);
42+ let (kd, vd, rep) = (nk * hk, nv * hv, nv / nk);
43+
44+ // 1. projections
45+ let qkvz = x.matmul(&w_qkvz.t()?)?; // [s,768]
46+ let ba = x.matmul(&w_ba.t()?)?; // [s,16]
47+
48+ // 2. fix_query_key_value_ordering
49+ let qkvz = qkvz.reshape((s, nk, 2 * hk + 2 * hv * rep))?;
50+ let q = qkvz.narrow(2, 0, hk)?.contiguous()?; // [s,nk,hk]
51+ let k = qkvz.narrow(2, hk, hk)?.contiguous()?;
52+ let v = qkvz.narrow(2, 2 * hk, rep * hv)?.reshape((s, nv, hv))?;
53+ let z = qkvz.narrow(2, 2 * hk + rep * hv, rep * hv)?.reshape((s, nv, hv))?;
54+ let ba = ba.reshape((s, nk, 2 * rep))?;
55+ let b = ba.narrow(2, 0, rep)?.reshape((s, nv))?;
56+ let a = ba.narrow(2, rep, rep)?.reshape((s, nv))?;
57+
58+ // 3. q,k,v -> [s,-1]; 4. conv (causal depthwise k=4) + silu
59+ let q = q.reshape((s, kd))?;
60+ let k = k.reshape((s, kd))?;
61+ let v3 = v.reshape((s, vd))?;
62+ let mixed = Tensor::cat(&[&q, &k, &v3], 1)?; // [s,512]
63+ let conv_dim = kd + kd + vd; // 512
64+ let mixed_t = mixed.t()?.unsqueeze(0)?.contiguous()?; // [1,512,s]
65+ // depthwise causal: pad left (ck-1), conv1d groups=conv_dim, take first s, silu
66+ let convd = mixed_t.conv1d(&conv_w, ck - 1, 1, 1, conv_dim)?; // [1,512,s+ck-1]
67+ let convd = convd.narrow(2, 0, s)?; // causal: first s
68+ let convd = silu(&convd)?;
69+ let mixed = convd.squeeze(0)?.t()?.contiguous()?; // [s,512]
70+
71+ // 5. split -> q,k [s,nk,hk], v [s,nv,hv]
72+ let q = mixed.narrow(1, 0, kd)?.reshape((s, nk, hk))?;
73+ let k = mixed.narrow(1, kd, kd)?.reshape((s, nk, hk))?;
74+ let v = mixed.narrow(1, 2 * kd, vd)?.reshape((s, nv, hv))?;
75+
76+ // 6. beta = sigmoid(b); g = -exp(A_log) * softplus(a + dt)
77+ let beta = candle_nn::ops::sigmoid(&b)?; // [s,nv]
78+ let gate = a.broadcast_add(&dt)?;
79+ let gate = softplus(&gate)?;
80+ let neg_exp_alog = a_log.exp()?.neg()?; // [nv]
81+ let gdecay = gate.broadcast_mul(&neg_exp_alog)?; // [s,nv]
82+
83+ // 7. repeat_interleave q,k by rep along head dim -> [s,nv,hk]
84+ let ri = |x: &Tensor| -> Result<Tensor> {
85+ Ok(x.reshape((s, nk, 1, hk))?
86+ .broadcast_as((s, nk, rep, hk))?
87+ .reshape((s, nv, hk))?)
88+ };
89+ let q = ri(&q)?;
90+ let k = ri(&k)?;
91+
92+ // 8. recurrence (f32): l2norm q,k; q *= 1/sqrt(hk); S[nv,hk,hv]
93+ let q = (l2norm(&q, 1e-6)? * (1.0 / (hk as f64).sqrt()))?;
94+ let k = l2norm(&k, 1e-6)?;
95+ let mut sstate = Tensor::zeros((nv, hk, hv), DType::F32, &dev)?;
96+ let mut outs: Vec<Tensor> = Vec::with_capacity(s);
97+ for i in 0..s {
98+ let q_t = q.i(i)?; // [nv,hk]
99+ let k_t = k.i(i)?;
100+ let v_t = v.i(i)?; // [nv,hv]
101+ let g_t = gdecay.i(i)?.exp()?.reshape((nv, 1, 1))?;
102+ let beta_t = beta.i(i)?.reshape((nv, 1))?;
103+ sstate = sstate.broadcast_mul(&g_t)?;
104+ let k_col = k_t.reshape((nv, hk, 1))?;
105+ let kv = sstate.broadcast_mul(&k_col)?.sum(1)?; // [nv,hv]
106+ let delta = (v_t - kv)?.broadcast_mul(&beta_t)?; // [nv,hv]
107+ let upd = k_col.broadcast_mul(&delta.reshape((nv, 1, hv))?)?; // [nv,hk,hv]
108+ sstate = (sstate + upd)?;
109+ let out_t = sstate.broadcast_mul(&q_t.reshape((nv, hk, 1))?)?.sum(1)?; // [nv,hv]
110+ outs.push(out_t.unsqueeze(0)?);
111+ }
112+ let out = Tensor::cat(&outs, 0)?; // [s,nv,hv]
113+
114+ // 9. RMSNormGated(out, z)
115+ let oc = out.reshape((s * nv, hv))?;
116+ let zc = z.reshape((s * nv, hv))?;
117+ let var = oc.sqr()?.mean_keepdim(D::Minus1)?;
118+ let oc = oc.broadcast_div(&(var + 1e-6)?.sqrt()?)?;
119+ let oc = oc.broadcast_mul(&norm_w)?;
120+ let oc = (oc * silu(&zc)?)?;
121+ let oc = oc.reshape((s, vd))?;
122+
123+ // 10. out_proj
124+ let y = oc.matmul(&w_out.t()?)?; // [s,256]
125+
126+ let err = (&y - &gold)?.abs()?;
127+ let maxerr = err.max(D::Minus1)?.max(D::Minus1)?.to_scalar::<f32>()?;
128+ let meanerr = err.mean_all()?.to_scalar::<f32>()?;
129+ println!("GDN candle port vs oracle: max_abs_err = {maxerr:.3e} mean_abs_err = {meanerr:.3e}");
130+ let y0: Vec<f32> = y.i(0)?.narrow(0, 0, 5)?.to_vec1()?;
131+ let g0: Vec<f32> = gold.i(0)?.narrow(0, 0, 5)?.to_vec1()?;
132+ println!(" y[0,:5] = {y0:?}");
133+ println!(" gold[0,:5] = {g0:?}");
134+ if maxerr < 1e-4 {
135+ println!(" ✅ PASS (< 1e-4) — GatedDeltaNet forward matches the HF oracle.");
136+ } else {
137+ println!(" ❌ mismatch — debug the port.");
138+ }
139+ Ok(())
140+}
added src/config.rs +433 −0
@@ -0,0 +1,433 @@
1+// coco-owned config: the config.json → architectures[0] → Arch registry.
2+//
3+// This replaces the hard dependency on candle's `qwen2::Config` type. `CocoConfig`
4+// is a serde superset of the fields every mainstream decoder-only LM exposes; flag
5+// fields are defaulted so future archs (qwen3, llama, mistral, gemma3, …) drop in
6+// as field-mapping + a registry arm, with no kernel changes. Step 0 registers ONLY
7+// qwen2 — the flags below are the qwen2 wiring.
8+
9+use anyhow::{anyhow, Context, Result};
10+use candle_nn::Activation;
11+use serde::Deserialize;
12+use std::path::Path;
13+
14+/// The architecture tag resolved from config.json's `architectures[0]`. Step 0 has
15+/// exactly one entry; every later step adds an arm here + a registry-table row.
16+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17+pub enum Arch {
18+ Qwen2,
19+ Qwen3,
20+ Qwen3Moe,
21+ DeepSeekV2,
22+ /// Qwen3.5 hybrid: 3:1 interleave of GatedDeltaNet (linear-attn recurrent) +
23+ /// periodic full GQA attention. Config lives under a multimodal `text_config`.
24+ Qwen35,
25+}
26+
27+/// The registry: HF `architectures[0]` string → coco `Arch`. This table IS the moat
28+/// candle lacks (candle's `models/mod.rs` is a flat `pub mod` list with no dispatch).
29+/// Adding an arch = adding a row here + a `build_model` match arm.
30+pub const ARCH_REGISTRY: &[(&str, Arch)] = &[
31+ ("Qwen2ForCausalLM", Arch::Qwen2),
32+ ("Qwen3ForCausalLM", Arch::Qwen3),
33+ ("Qwen3MoeForCausalLM", Arch::Qwen3Moe),
34+ ("DeepseekV2ForCausalLM", Arch::DeepSeekV2),
35+ ("Qwen3_5ForConditionalGeneration", Arch::Qwen35),
36+ ("Qwen3_5ForCausalLM", Arch::Qwen35),
37+];
38+
39+fn default_true() -> bool {
40+ true
41+}
42+fn default_false() -> bool {
43+ false
44+}
45+fn default_rope_theta() -> f64 {
46+ 10000.0
47+}
48+fn default_hidden_act() -> Activation {
49+ Activation::Silu
50+}
51+fn default_max_pos() -> usize {
52+ 32768
53+}
54+fn default_decoder_sparse_step() -> usize {
55+ 1
56+}
57+fn default_moe_layer_freq() -> usize {
58+ 1
59+}
60+fn default_routed_scaling_factor() -> f64 {
61+ 1.0
62+}
63+fn default_partial_rotary() -> f32 {
64+ 1.0
65+}
66+fn default_sliding_window() -> usize {
67+ // qwen2 config.json carries a huge sliding_window; the mask code treats it as
68+ // effectively "no window" for these models. Default matches that when absent.
69+ 4096
70+}
71+
72+/// Deserialize `sliding_window`, tolerating an explicit JSON `null` (qwen3) as well
73+/// as an absent key — both collapse to `default_sliding_window()`.
74+fn de_opt_sliding_window<'de, D>(de: D) -> std::result::Result<usize, D::Error>
75+where
76+ D: serde::Deserializer<'de>,
77+{
78+ let v: Option<usize> = Option::deserialize(de)?;
79+ Ok(v.unwrap_or_else(default_sliding_window))
80+}
81+
82+/// coco-owned union config. A `#[derive(Deserialize)]` superset of qwen2's
83+/// config.json fields, plus flag fields defaulted for future archs. The quant/fast
84+/// path reads ONLY this — never candle's `qwen2::Config`. Several fields
85+/// (intermediate_size, qk_norm, attn_bias, tie_word_embeddings, …) are part of the
86+/// union for future arch wirings and are not all read in Step 0's qwen2 path.
87+#[derive(Debug, Clone, Deserialize)]
88+#[allow(dead_code)]
89+pub struct CocoConfig {
90+ pub hidden_size: usize,
91+ pub num_hidden_layers: usize,
92+ pub num_attention_heads: usize,
93+ pub num_key_value_heads: usize,
94+ pub intermediate_size: usize,
95+ pub vocab_size: usize,
96+ pub rms_norm_eps: f64,
97+
98+ #[serde(default = "default_rope_theta")]
99+ pub rope_theta: f64,
100+
101+ #[serde(default = "default_max_pos")]
102+ pub max_position_embeddings: usize,
103+
104+ /// qwen2 carries a huge sliding_window (mask treats it as "no window"); qwen3
105+ /// sets it to `null`. serde's `default` only fires on an ABSENT key — an explicit
106+ /// `null` would error into `usize` — so deserialize via `Option` then unwrap to
107+ /// the default. Either way the mask code sees a large "no window" value.
108+ #[serde(default, deserialize_with = "de_opt_sliding_window")]
109+ pub sliding_window: usize,
110+
111+ #[serde(default = "default_hidden_act")]
112+ pub hidden_act: Activation,
113+
114+ /// Explicit head_dim (qwen3/gemma3 set it; qwen2 derives hidden/n_heads). When
115+ /// absent, `head_dim()` derives it. Kept `Option` so the derive path is faithful.
116+ #[serde(default)]
117+ pub head_dim: Option<usize>,
118+
119+ // ── flag fields, defaulted for the qwen2 wiring (future archs override) ──────
120+ /// QK-norm on head_dim q&k pre-rope (qwen3). qwen2 = false.
121+ #[serde(default = "default_false")]
122+ pub qk_norm: bool,
123+
124+ /// q/k/v projection biases. qwen2 = true; qwen3/llama/mistral = false.
125+ #[serde(default = "default_true")]
126+ pub attn_bias: bool,
127+
128+ /// Tie lm_head to the embedding matrix (Qwen2.5-1.5B = true).
129+ #[serde(default = "default_false")]
130+ pub tie_word_embeddings: bool,
131+
132+ // ── MoE fields (qwen3_moe / mixtral / glm4_moe). Defaulted to a dense wiring
133+ // (num_experts=0) so non-MoE config.json blobs parse unchanged. ──────────
134+ /// Number of experts in each MoE FFN (0 = dense arch, no MoE).
135+ #[serde(default)]
136+ pub num_experts: usize,
137+ /// top-k experts activated per token.
138+ #[serde(default)]
139+ pub num_experts_per_tok: usize,
140+ /// Per-expert SwiGLU intermediate width (distinct from the dense
141+ /// intermediate_size; qwen3_moe = 768).
142+ #[serde(default)]
143+ pub moe_intermediate_size: usize,
144+ /// Renormalize the top-k router weights to sum to 1 (qwen3_moe = true).
145+ #[serde(default = "default_true")]
146+ pub norm_topk_prob: bool,
147+ /// Layer indices that stay DENSE even in a MoE arch (qwen3_moe = []).
148+ #[serde(default)]
149+ pub mlp_only_layers: Vec<usize>,
150+ /// Sparse-layer stride: a MoE layer only every `decoder_sparse_step` layers
151+ /// (qwen3_moe = 1 → every layer is MoE).
152+ #[serde(default = "default_decoder_sparse_step")]
153+ pub decoder_sparse_step: usize,
154+
155+ // ── DeepSeek-V2/V3 MLA fields (Arch::DeepSeekV2). All serde-defaulted so every
156+ // other arch's config.json still parses unchanged. On V2-Lite: kv_lora_rank=512,
157+ // q_lora_rank=null, qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128. ──
158+ /// Rank of the compressed KV latent `c_kv` (the MQA-shared cache row width).
159+ #[serde(default)]
160+ pub kv_lora_rank: usize,
161+ /// Rank of the optional compressed Q latent (full V2/V3). `None` on V2-Lite →
162+ /// direct `q_proj` (QProj::Plain fork).
163+ #[serde(default)]
164+ pub q_lora_rank: Option<usize>,
165+ /// Content (no-rope) part of the per-head Q/K dim.
166+ #[serde(default)]
167+ pub qk_nope_head_dim: usize,
168+ /// Decoupled-rope part of the per-head Q dim + the single shared K rope dim.
169+ #[serde(default)]
170+ pub qk_rope_head_dim: usize,
171+ /// Per-head V width (asymmetric: K is qk_nope+qk_rope, V is v_head_dim).
172+ #[serde(default)]
173+ pub v_head_dim: usize,
174+ /// q/k/v/o projection biases for MLA (attention_bias in HF config; V2-Lite = false).
175+ #[serde(default = "default_false")]
176+ pub attention_bias: bool,
177+
178+ // ── DeepSeek-MoE FFN fields. Distinct from the qwen3_moe MoE fields above:
179+ // DeepSeek adds always-on shared experts + a dense-layer prefix + a routed
180+ // scaling factor. All defaulted to a no-op so qwen3_moe behavior is unchanged. ──
181+ /// Number of routed experts (DeepSeek names it `n_routed_experts`; 0 = not a
182+ /// DeepSeek-MoE arch).
183+ #[serde(default)]
184+ pub n_routed_experts: usize,
185+ /// Number of always-on shared experts whose output is ADDED (ungated) to the
186+ /// routed sum. `None`/0 = no shared experts.
187+ #[serde(default)]
188+ pub n_shared_experts: Option<usize>,
189+ /// The first K decoder layers use a plain dense SwiGLU (not MoE). V2-Lite = 1.
190+ #[serde(default)]
191+ pub first_k_dense_replace: usize,
192+ /// A MoE layer only every `moe_layer_freq` layers past `first_k_dense_replace`
193+ /// (V2-Lite = 1 → every layer past the dense prefix is MoE).
194+ #[serde(default = "default_moe_layer_freq")]
195+ pub moe_layer_freq: usize,
196+ /// Scalar multiplied into the routed-expert sum (DeepSeek routed_scaling_factor).
197+ #[serde(default = "default_routed_scaling_factor")]
198+ pub routed_scaling_factor: f64,
199+ /// Grouped-topk config (full V2/V3). V2-Lite = 1/1 → degenerates to plain top-k,
200+ /// which the existing top-k path already covers.
201+ #[serde(default)]
202+ pub n_group: usize,
203+ #[serde(default)]
204+ pub topk_group: usize,
205+
206+ /// YaRN (or linear/dynamic) rope scaling. `None` = plain rope. When present with
207+ /// `type: yarn`, MLA applies the mscale sin/cos correction + squared-mscale
208+ /// softmax scale, exactly per candle deepseek2.rs.
209+ #[serde(default)]
210+ pub rope_scaling: Option<RopeScaling>,
211+
212+ // ── Qwen3.5 hybrid (Arch::Qwen35) fields. All serde-defaulted so every other arch's
213+ // config.json parses unchanged. Per-layer mixer type comes from `layer_types` (a
214+ // per-layer "linear_attention"/"full_attention" list) or `full_attention_interval`. ──
215+ /// Per-layer mixer selector: "linear_attention" (GatedDeltaNet) or "full_attention" (GQA).
216+ #[serde(default)]
217+ pub layer_types: Vec<String>,
218+ /// When `layer_types` is absent: every `full_attention_interval`-th layer is full-attn.
219+ #[serde(default)]
220+ pub full_attention_interval: usize,
221+ /// GatedDeltaNet per-head key/value dims and head counts.
222+ #[serde(default)]
223+ pub linear_key_head_dim: usize,
224+ #[serde(default)]
225+ pub linear_value_head_dim: usize,
226+ #[serde(default)]
227+ pub linear_num_key_heads: usize,
228+ #[serde(default)]
229+ pub linear_num_value_heads: usize,
230+ /// Depthwise causal conv kernel width on the GatedDeltaNet q/k/v stream.
231+ #[serde(default)]
232+ pub linear_conv_kernel_dim: usize,
233+ /// Full-attn layers apply rope to only the first `partial_rotary_factor * head_dim`
234+ /// dims (rest NoPE). Absent → 1.0 (full rope, the qwen3 behavior).
235+ #[serde(default = "default_partial_rotary")]
236+ pub partial_rotary_factor: f32,
237+ /// Full-attn layers carry a post-attention sigmoid output gate (qwen3.5 = true).
238+ #[serde(default = "default_false")]
239+ pub attn_output_gate: bool,
240+
241+ /// Resolved at load from `architectures[0]`; not in config.json's fields itself.
242+ #[serde(skip, default = "default_arch")]
243+ pub arch: Arch,
244+}
245+
246+/// DeepSeek rope scaling. `#[serde(untagged)]` matches candle's `DeepSeekV2RopeScaling`:
247+/// the YaRN variant carries the correction params; the linear/dynamic variant only a
248+/// factor. Fields not present default so V2-Lite's yarn blob parses.
249+#[derive(Debug, Clone, Deserialize)]
250+#[serde(untagged)]
251+pub enum RopeScaling {
252+ Yarn {
253+ original_max_position_embeddings: usize,
254+ beta_fast: f32,
255+ beta_slow: f32,
256+ mscale: f32,
257+ mscale_all_dim: f32,
258+ factor: f32,
259+ #[serde(rename = "type")]
260+ scaling_type: String,
261+ },
262+ LinearOrDynamic {
263+ #[serde(rename = "type")]
264+ scaling_type: String,
265+ factor: f64,
266+ },
267+}
268+
269+impl CocoConfig {
270+ /// Is decoder layer `idx` a MoE FFN (vs a dense SwiGLU)? A layer is DENSE if it
271+ /// is listed in `mlp_only_layers` OR (decoder_sparse_step > 1 and it is not a
272+ /// multiple-stride sparse layer). All other layers of a MoE arch are MoE. Dense
273+ /// archs (num_experts == 0) are never MoE. Matches HF qwen3_moe layer selection.
274+ pub fn layer_is_moe(&self, idx: usize) -> bool {
275+ if self.arch != Arch::Qwen3Moe || self.num_experts == 0 {
276+ return false;
277+ }
278+ if self.mlp_only_layers.contains(&idx) {
279+ return false;
280+ }
281+ if self.decoder_sparse_step > 1 && (idx + 1) % self.decoder_sparse_step != 0 {
282+ return false;
283+ }
284+ true
285+ }
286+}
287+
288+fn default_arch() -> Arch {
289+ Arch::Qwen2
290+}
291+
292+/// YaRN mscale, ported verbatim from deepseek2.rs `yarn_get_mscale`:
293+/// `0.1 * mscale * ln(scale) + 1` for scale > 1, else 1. Used both for the sin/cos
294+/// magnitude in MLA rope and (squared) in the softmax scale.
295+pub fn yarn_get_mscale(scale: f32, mscale: f32) -> f32 {
296+ if scale <= 1.0 {
297+ return 1.0;
298+ }
299+ 0.1 * mscale * scale.ln() + 1.0
300+}
301+
302+impl CocoConfig {
303+ /// head_dim: explicit if present, else hidden_size / num_attention_heads (qwen2).
304+ pub fn head_dim(&self) -> usize {
305+ self.head_dim
306+ .unwrap_or(self.hidden_size / self.num_attention_heads)
307+ }
308+
309+ /// MLA per-head Q/K dim = qk_nope_head_dim + qk_rope_head_dim (192 on V2-Lite).
310+ pub fn mla_q_head_dim(&self) -> usize {
311+ self.qk_nope_head_dim + self.qk_rope_head_dim
312+ }
313+
314+ /// MLA softmax scale = 1/sqrt(q_head_dim), with the YaRN squared-mscale correction
315+ /// when `rope_scaling` is a yarn variant — ported verbatim from deepseek2.rs
316+ /// `softmax_scale()` (mismatched mscale silently degrades). `mscale_all_dim` here,
317+ /// applied twice (squared).
318+ pub fn mla_softmax_scale(&self) -> f64 {
319+ let mut s = 1.0_f64 / (self.mla_q_head_dim() as f64).sqrt();
320+ if let Some(RopeScaling::Yarn {
321+ mscale_all_dim,
322+ factor,
323+ ..
324+ }) = &self.rope_scaling
325+ {
326+ let m = yarn_get_mscale(*factor, *mscale_all_dim) as f64;
327+ s = s * m * m;
328+ }
329+ s
330+ }
331+
332+ /// DeepSeek-MoE per-layer dense-vs-MoE selection: the first `first_k_dense_replace`
333+ /// layers are plain dense SwiGLU; the rest are MoE (subject to `moe_layer_freq`).
334+ /// Matches deepseek2.rs `DecoderLayer::new`. Dense archs / non-DeepSeek return false.
335+ pub fn deepseek_layer_is_moe(&self, idx: usize) -> bool {
336+ if self.arch != Arch::DeepSeekV2 || self.n_routed_experts == 0 {
337+ return false;
338+ }
339+ idx >= self.first_k_dense_replace && idx % self.moe_layer_freq == 0
340+ }
341+
342+ /// Qwen3.5 per-layer mixer: true = GatedDeltaNet (linear attn), false = full GQA.
343+ /// Prefers the explicit `layer_types` list; falls back to `full_attention_interval`
344+ /// (every Nth layer full-attn, the rest linear). Non-qwen3.5 archs return false.
345+ pub fn layer_is_linear_attn(&self, idx: usize) -> bool {
346+ if self.arch != Arch::Qwen35 {
347+ return false;
348+ }
349+ if let Some(t) = self.layer_types.get(idx) {
350+ return t == "linear_attention";
351+ }
352+ let n = self.full_attention_interval.max(1);
353+ (idx + 1) % n != 0
354+ }
355+
356+ /// Load config.json, resolve `architectures[0]` (or `model_type`) against the
357+ /// registry, and parse the union config. This is the config.json → Arch step.
358+ pub fn from_dir(dir: &Path) -> Result<Self> {
359+ let path = dir.join("config.json");
360+ let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
361+ Self::from_json_bytes(&bytes)
362+ .with_context(|| format!("parsing {}", path.display()))
363+ }
364+
365+ /// Parse a config.json byte blob and resolve its architecture tag.
366+ pub fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
367+ // First pull architectures[0] / model_type to resolve the Arch.
368+ // Parse the whole config as a Value. Resolve arch from the top-level
369+ // architectures/model_type; take the LM fields from `text_config` when this is a
370+ // multimodal wrapper (qwen3_5, with a `vision_config` sibling we ignore), else from
371+ // the top-level object itself (qwen2/qwen3/deepseek).
372+ let root: serde_json::Value = serde_json::from_slice(bytes)?;
373+ let architectures: Vec<String> = root
374+ .get("architectures")
375+ .and_then(|v| serde_json::from_value(v.clone()).ok())
376+ .unwrap_or_default();
377+ let model_type = root
378+ .get("model_type")
379+ .and_then(|v| v.as_str())
380+ .map(str::to_string);
381+ let arch = resolve_arch(&architectures, model_type.as_deref())?;
382+
383+ let text_config = root.get("text_config").cloned();
384+ let lm_val = text_config.unwrap_or(root);
385+ let mut cfg: CocoConfig = serde_json::from_value(lm_val)?;
386+ cfg.arch = arch;
387+
388+ // Arch-implied flags. qwen3's config.json has NO `qk_norm` field and NO
389+ // q/k/v bias — those are architecture facts, not config values — so we force
390+ // them here rather than trusting/expecting config keys. (qwen3 DOES carry
391+ // `attention_bias: false`, but forcing keeps us robust to its absence.)
392+ // qwen3_moe shares qwen3's attention: QK-norm on, no q/k/v bias. The ONLY
393+ // delta vs qwen3 dense is the FFN (MoE vs SwiGLU) — read from the MoE fields.
394+ if arch == Arch::Qwen3 || arch == Arch::Qwen3Moe {
395+ cfg.qk_norm = true;
396+ cfg.attn_bias = false;
397+ }
398+ // DeepSeek V2/V3 is full causal (no sliding window). Its config.json omits
399+ // `sliding_window`, so the default (4096) would wrongly window contexts > 4096.
400+ // Force it to the full range. MLA has its own head-dim split (not the GQA
401+ // qk_norm), so leave qk_norm/attn_bias to the MLA-specific fields.
402+ if arch == Arch::DeepSeekV2 {
403+ cfg.sliding_window = cfg.max_position_embeddings;
404+ }
405+ Ok(cfg)
406+ }
407+}
408+
409+/// Resolve `architectures[0]` (preferred) or `model_type` against ARCH_REGISTRY.
410+fn resolve_arch(architectures: &[String], model_type: Option<&str>) -> Result<Arch> {
411+ if let Some(first) = architectures.first() {
412+ if let Some((_, arch)) = ARCH_REGISTRY.iter().find(|(name, _)| name == first) {
413+ return Ok(*arch);
414+ }
415+ }
416+ // Fallback: model_type string (qwen2 → Qwen2, qwen3 → Qwen3).
417+ if let Some(mt) = model_type {
418+ match mt {
419+ "qwen2" => return Ok(Arch::Qwen2),
420+ "qwen3" => return Ok(Arch::Qwen3),
421+ "qwen3_moe" => return Ok(Arch::Qwen3Moe),
422+ "deepseek_v2" | "deepseek_v3" => return Ok(Arch::DeepSeekV2),
423+ "qwen3_5" | "qwen3_5_text" | "qwen3_5_moe" => return Ok(Arch::Qwen35),
424+ _ => {}
425+ }
426+ }
427+ Err(anyhow!(
428+ "unregistered architecture: architectures={:?} model_type={:?} (registered: {:?})",
429+ architectures,
430+ model_type,
431+ ARCH_REGISTRY.iter().map(|(n, _)| *n).collect::<Vec<_>>()
432+ ))
433+}
added src/eval.rs +319 −0
@@ -0,0 +1,319 @@
1+// Step-1 eval harness — deterministic port of lab/evo_merge/eval_fitness.py (FIXED
2+// 16 GSM8K + 16 ARC-Easy). fitness = math_acc + general_acc ∈ [0,2].
3+//
4+// * GSM8K: Qwen2.5 ChatML template, GREEDY up to 640 new tokens, extract the LAST
5+// \boxed{...} number (else '#### N' else 'answer is N' else last number), exact
6+// match vs gold.
7+// * ARC-Easy MCQ: argmax next-token logprob over ' A'/' B'/' C'/' D' via logits_last.
8+//
9+// Deterministic (greedy, temp 0, no repeat penalty, fixed items) ⇒ a given weight-set
10+// always yields the same fitness — a stable GA signal.
11+
12+use anyhow::{anyhow, Result};
13+use candle_core::{DType, Device, Tensor};
14+use candle_transformers::generation::LogitsProcessor;
15+use regex::Regex;
16+use serde::Deserialize;
17+use std::collections::HashMap;
18+use tokenizers::Tokenizer;
19+
20+use crate::model::Model;
21+
22+// Qwen2.5 special-token ids (verified against both parents' tokenizer.json).
23+const IM_END: u32 = 151645; // <|im_end|> — turn end for Instruct/Math
24+const EOS: u32 = 151643; // <|endoftext|>
25+
26+// ARC letter token ids: (bare, leading-space). Verified: A 32/362, B 33/425,
27+// C 34/356, D 35/422.
28+const LETTER_IDS: [(char, u32, u32); 4] =
29+ [('A', 32, 362), ('B', 33, 425), ('C', 34, 356), ('D', 35, 422)];
30+
31+// ─────────────────────────── items ───────────────────────────
32+
33+#[derive(Debug, Clone, Deserialize)]
34+pub struct MathItem {
35+ pub q: String,
36+ pub gold: String,
37+}
38+
39+#[derive(Debug, Clone, Deserialize)]
40+pub struct GenItem {
41+ pub q: String,
42+ pub choices: HashMap<String, String>,
43+ pub gold: String,
44+}
45+
46+#[derive(Debug, Clone, Deserialize)]
47+pub struct EvalItems {
48+ pub math: Vec<MathItem>,
49+ pub general: Vec<GenItem>,
50+}
51+
52+impl EvalItems {
53+ /// Load the baked 16+16 items from eval_items.json (dumped once from the Python
54+ /// loader — byte-identical to the reference).
55+ pub fn load(path: &std::path::Path) -> Result<Self> {
56+ let raw = std::fs::read(path)
57+ .map_err(|e| anyhow!("reading eval items {}: {e}", path.display()))?;
58+ let items: EvalItems = serde_json::from_slice(&raw)
59+ .map_err(|e| anyhow!("parsing eval items {}: {e}", path.display()))?;
60+ Ok(items)
61+ }
62+
63+ /// Truncate to the first `n_math` / `n_general` items (for --n-math/--n-general).
64+ pub fn take(mut self, n_math: usize, n_general: usize) -> Self {
65+ self.math.truncate(n_math);
66+ self.general.truncate(n_general);
67+ self
68+ }
69+}
70+
71+#[derive(Debug, Clone, Copy)]
72+pub struct Fitness {
73+ pub math: f32,
74+ pub general: f32,
75+ pub combined: f32,
76+}
77+
78+// ─────────────────────────── prompting ───────────────────────────
79+
80+/// Qwen2.5 ChatML with the explicit system line (suppresses the Math model's default
81+/// \boxed{} system injection so both parents get identical prompts). Verbatim of the
82+/// template `apply_chat_template` produces for the fixed system+user pair.
83+pub fn qwen_chat(user: &str) -> String {
84+ format!(
85+ "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n\
86+ <|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n"
87+ )
88+}
89+
90+const MATH_INSTR: &str = "Solve the problem. Show brief reasoning, then give the final \
91+ answer on a new line as '#### <number>'.\n\nProblem: ";
92+
93+fn encode(tok: &Tokenizer, prompt: &str) -> Result<Vec<u32>> {
94+ // add_special_tokens=false — the ChatML template already carries the specials.
95+ let enc = tok
96+ .encode(prompt, false)
97+ .map_err(|e| anyhow!("encoding prompt: {e}"))?;
98+ Ok(enc.get_ids().to_vec())
99+}
100+
101+// ─────────────────────────── coco eval primitives ───────────────────────────
102+
103+/// The MCQ primitive: run a single forward over `ids`, return the last-position
104+/// logits as an F32 vocab vector. `.to_dtype(F32)` BEFORE softmax (matches Python
105+/// `.float()`). coco's forward already narrows to the last position → [1,1,vocab].
106+pub fn logits_last(m: &mut dyn Model, dev: &Device, ids: &[u32]) -> Result<Vec<f32>> {
107+ m.clear_kv_cache();
108+ let input = Tensor::new(ids, dev)?.unsqueeze(0)?; // [1, seq]
109+ let logits = m.forward(&input, 0)?; // [1,1,vocab]
110+ let v = logits
111+ .squeeze(0)?
112+ .squeeze(0)?
113+ .to_dtype(DType::F32)?
114+ .to_vec1::<f32>()?;
115+ Ok(v)
116+}
117+
118+/// Greedy generation lifted from main.rs's loop. temp=None ⇒ argmax; repeat_penalty
119+/// 1.0 (Python `do_sample=False, num_beams=1`). Stops on any id in `stops` (pass
120+/// [IM_END, EOS] or math runs to the 640-token cap). Returns the decoded new text
121+/// (skip_special_tokens=true, matching the Python decode).
122+pub fn generate_greedy(
123+ m: &mut dyn Model,
124+ tok: &Tokenizer,
125+ dev: &Device,
126+ ids: &[u32],
127+ max_new: usize,
128+ stops: &[u32],
129+) -> Result<String> {
130+ m.clear_kv_cache();
131+ let mut tokens: Vec<u32> = ids.to_vec();
132+ let prompt_len = tokens.len();
133+ let mut lp = LogitsProcessor::new(0, None, None); // temp None ⇒ argmax (greedy)
134+
135+ for index in 0..max_new {
136+ let (context, offset) = if index == 0 {
137+ (&tokens[..], 0)
138+ } else {
139+ (&tokens[tokens.len() - 1..], tokens.len() - 1)
140+ };
141+ let input = Tensor::new(context, dev)?.unsqueeze(0)?;
142+ let logits = m.forward(&input, offset)?; // [1,1,vocab]
143+ let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?;
144+ let next = lp.sample(&logits)?;
145+ if stops.contains(&next) {
146+ break;
147+ }
148+ tokens.push(next);
149+ }
150+
151+ let gen = &tokens[prompt_len..];
152+ let text = tok
153+ .decode(gen, true)
154+ .map_err(|e| anyhow!("decoding generation: {e}"))?;
155+ Ok(text)
156+}
157+
158+// ─────────────────────────── answer extraction (port of _extract_int) ───────────────────────────
159+
160+/// Pull the last plain number out of a string (handles $, commas, decimals).
161+/// Port of `_num_in`.
162+fn num_in(s: &str) -> Option<String> {
163+ let cleaned = s.replace('$', "");
164+ let re = Regex::new(r"[-]?\d[\d,]*(?:\.\d+)?").unwrap();
165+ re.find_iter(&cleaned).last().map(|m| m.as_str().to_string())
166+}
167+
168+/// Normalize a number string: strip $/commas, `.0`→int. Port of `_norm_num`.
169+pub fn norm_num(s: &str) -> String {
170+ let t = s.replace('$', "").replace(',', "");
171+ let t = t.trim();
172+ if let Ok(f) = t.parse::<f64>() {
173+ if f == f.trunc() && f.is_finite() {
174+ return (f as i64).to_string();
175+ }
176+ return f.to_string();
177+ }
178+ t.to_string()
179+}
180+
181+/// Extract the predicted answer, in the SAME priority order as `_extract_int`:
182+/// (1) LAST \boxed{...} inner number, (2) last '#### N', (3) 'answer (is|:|=) N',
183+/// (4) last standalone number.
184+pub fn extract_int(text: &str) -> Option<String> {
185+ // 1) LAST \boxed{...} — inner has no nested braces.
186+ let boxed = Regex::new(r"\\boxed\{([^{}]*)\}").unwrap();
187+ let boxed_hits: Vec<String> = boxed
188+ .captures_iter(text)
189+ .map(|c| c[1].to_string())
190+ .collect();
191+ if let Some(last) = boxed_hits.last() {
192+ if let Some(n) = num_in(last) {
193+ return Some(norm_num(&n));
194+ }
195+ }
196+ // 2) '#### N'
197+ let hashes = Regex::new(r"####\s*([-\$]?[0-9][0-9,\.]*)").unwrap();
198+ let hash_hits: Vec<String> = hashes.captures_iter(text).map(|c| c[1].to_string()).collect();
199+ if let Some(last) = hash_hits.last() {
200+ return Some(norm_num(last));
201+ }
202+ // 3) 'answer is|:|= N' (case-insensitive)
203+ let ans = Regex::new(r"(?i)answer\s*(?:is|:|=)?\s*\$?([-]?[0-9][0-9,\.]*)").unwrap();
204+ let ans_hits: Vec<String> = ans.captures_iter(text).map(|c| c[1].to_string()).collect();
205+ if let Some(last) = ans_hits.last() {
206+ return Some(norm_num(last));
207+ }
208+ // 4) fallback: last standalone number
209+ let any = Regex::new(r"([-\$]?\d[\d,]*(?:\.\d+)?)").unwrap();
210+ let any_hits: Vec<String> = any.captures_iter(text).map(|c| c[1].to_string()).collect();
211+ if let Some(last) = any_hits.last() {
212+ return Some(norm_num(last));
213+ }
214+ None
215+}
216+
217+// ─────────────────────────── the two evals ───────────────────────────
218+
219+/// GSM8K greedy exact-match. math_acc = correct / n.
220+pub fn score_math(
221+ m: &mut dyn Model,
222+ tok: &Tokenizer,
223+ dev: &Device,
224+ items: &[MathItem],
225+) -> Result<f32> {
226+ if items.is_empty() {
227+ return Ok(0.0);
228+ }
229+ let stops = [IM_END, EOS];
230+ let mut correct = 0usize;
231+ for it in items {
232+ let prompt = qwen_chat(&format!("{MATH_INSTR}{}", it.q));
233+ let ids = encode(tok, &prompt)?;
234+ let gen = generate_greedy(m, tok, dev, &ids, 640, &stops)?;
235+ let pred = extract_int(&gen);
236+ let gold = norm_num(&it.gold);
237+ if std::env::var("COCO_DEBUG_GEN").is_ok() {
238+ eprintln!("--- GEN (gold={gold} pred={:?}) ---\n{}\n--- END (len={}) ---", pred, gen, gen.len());
239+ }
240+ if pred.as_deref() == Some(gold.as_str()) {
241+ correct += 1;
242+ }
243+ }
244+ Ok(correct as f32 / items.len() as f32)
245+}
246+
247+/// log_softmax over an F32 vocab vector (subtract max, exp, log-normalize).
248+fn log_softmax(logits: &[f32]) -> Vec<f32> {
249+ let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
250+ let mut sum = 0f64;
251+ for &x in logits {
252+ sum += ((x - max) as f64).exp();
253+ }
254+ let log_sum = sum.ln() as f32;
255+ logits.iter().map(|&x| (x - max) - log_sum).collect()
256+}
257+
258+/// ARC-Easy MCQ by next-token letter logprob. general_acc = correct / n.
259+pub fn score_arc(
260+ m: &mut dyn Model,
261+ tok: &Tokenizer,
262+ dev: &Device,
263+ items: &[GenItem],
264+) -> Result<f32> {
265+ if items.is_empty() {
266+ return Ok(0.0);
267+ }
268+ let mut correct = 0usize;
269+ for it in items {
270+ // Options in fixed A,B,C,D order.
271+ let mut opts = String::new();
272+ for (letter, _, _) in LETTER_IDS.iter() {
273+ let key = letter.to_string();
274+ if let Some(v) = it.choices.get(&key) {
275+ if !opts.is_empty() {
276+ opts.push('\n');
277+ }
278+ opts.push_str(&format!("{letter}. {v}"));
279+ }
280+ }
281+ let user = format!(
282+ "Answer the multiple choice question.\n\nQuestion: {}\n{}\n\nRespond with just the letter of the correct answer.",
283+ it.q, opts
284+ );
285+ let prompt = qwen_chat(&user);
286+ let ids = encode(tok, &prompt)?;
287+ let lp = logits_last(m, dev, &ids)?;
288+ let logprobs = log_softmax(&lp);
289+ let mut best_letter = 'A';
290+ let mut best_score = f32::NEG_INFINITY;
291+ for (letter, bare, space) in LETTER_IDS.iter() {
292+ let s = logprobs[*bare as usize].max(logprobs[*space as usize]);
293+ if s > best_score {
294+ best_score = s;
295+ best_letter = *letter;
296+ }
297+ }
298+ if best_letter.to_string() == it.gold {
299+ correct += 1;
300+ }
301+ }
302+ Ok(correct as f32 / items.len() as f32)
303+}
304+
305+/// fitness = math_acc + general_acc.
306+pub fn fitness(
307+ m: &mut dyn Model,
308+ tok: &Tokenizer,
309+ dev: &Device,
310+ items: &EvalItems,
311+) -> Result<Fitness> {
312+ let math = score_math(m, tok, dev, &items.math)?;
313+ let general = score_arc(m, tok, dev, &items.general)?;
314+ Ok(Fitness {
315+ math,
316+ general,
317+ combined: math + general,
318+ })
319+}
added src/lib.rs +24 −0
@@ -0,0 +1,24 @@
1+// coco-engine library seam.
2+//
3+// `main.rs` is the `coco` generate/bench bin (unchanged). This `lib.rs` exposes the
4+// engine's internals so sibling bins (e.g. `coco-evomerge`) can reuse coco's model
5+// loading + generation without duplicating the forward. The modules below are the
6+// SAME sources compiled by the bin; nothing here changes their behavior.
7+//
8+// Step-1 evolutionary-merge additions: `merge` (CPU f32 parent lerp → runnable Model)
9+// and `eval` (GSM8K + ARC-Easy fitness harness). Both are library-only — the `coco`
10+// bin never touches them.
11+
12+pub mod config;
13+pub mod eval;
14+pub mod merge;
15+pub mod model;
16+pub mod qlinear;
17+pub mod qwen2_legacy;
18+pub mod qwen2_q;
19+pub mod turboquant;
20+
21+// The stable surface the merge/eval lanes (and the evomerge bin) build on.
22+pub use config::{Arch, CocoConfig};
23+pub use model::{build_model, Model};
24+pub use qwen2_q::{WeightSource, WeightStats};
added src/main.rs +731 −0
@@ -0,0 +1,731 @@
1+// coco v0 — minimal but real Rust LLM inference engine.
2+//
3+// Loads Qwen2.5-1.5B (standard qwen2 architecture) and generates coherent text
4+// on Metal (Apple Silicon GPU) with a CPU fallback. fp16/bf16 inference only —
5+// NO quantization (that is the next step: turboquant / a custom QuantizedLinear).
6+//
7+// Structure mirrors the official candle qwen example:
8+// candle-examples/examples/qwen/main.rs
9+// (model construction + KV cache + LogitsProcessor sampling loop).
10+
11+mod config;
12+mod model;
13+mod qlinear;
14+mod qwen2_legacy;
15+mod qwen2_q;
16+mod turboquant;
17+
18+use anyhow::{anyhow, Context, Result};
19+use candle_core::{DType, Device, Tensor};
20+use candle_nn::VarBuilder;
21+use candle_transformers::generation::LogitsProcessor;
22+// candle's qwen2 Config/ModelForCausalLM are used ONLY for the dense (non-turboquant)
23+// fallback path. The quant/fast path goes entirely through coco's own CocoConfig +
24+// build_model registry — no candle qwen2 type on the moat.
25+use candle_transformers::models::qwen2::{Config, ModelForCausalLM};
26+use clap::Parser;
27+
28+use crate::config::CocoConfig;
29+use crate::model::Model as CocoModel;
30+use std::collections::HashMap;
31+use std::io::Write;
32+use std::path::PathBuf;
33+use tokenizers::Tokenizer;
34+
35+#[derive(Parser, Debug)]
36+#[command(name = "coco", about = "coco v0 — real Rust LLM inference (Qwen2.5-1.5B)")]
37+struct Args {
38+ /// Prompt to continue.
39+ #[arg(long, default_value = "Write a haiku about the sea:")]
40+ prompt: String,
41+
42+ /// Path to the model directory (must contain config.json, tokenizer.json, *.safetensors).
43+ #[arg(long, default_value = "./model")]
44+ model: PathBuf,
45+
46+ /// Max new tokens to generate.
47+ #[arg(long, default_value_t = 256)]
48+ max_tokens: usize,
49+
50+ /// Sampling temperature. 0.0 = greedy (argmax).
51+ #[arg(long, default_value_t = 0.7)]
52+ temperature: f64,
53+
54+ /// Nucleus sampling top-p. Only used when temperature > 0.
55+ #[arg(long)]
56+ top_p: Option<f64>,
57+
58+ /// RNG seed.
59+ #[arg(long, default_value_t = 299792458)]
60+ seed: u64,
61+
62+ /// Repeat penalty (>1.0 discourages repetition). 1.0 = off.
63+ #[arg(long, default_value_t = 1.1)]
64+ repeat_penalty: f32,
65+
66+ /// How many of the last tokens the repeat penalty considers.
67+ #[arg(long, default_value_t = 64)]
68+ repeat_last_n: usize,
69+
70+ /// Force CPU even if a GPU is available.
71+ #[arg(long)]
72+ cpu: bool,
73+
74+ /// Weight quantization mode. "none" (default) = v0 fp16/bf16. "turboquant" =
75+ /// data-free turboquant-v2 quantize-then-dequant-at-load (3-bit codebook +
76+ /// FWHT incoherence rotation). Quantized weights are reconstructed to
77+ /// fp16/bf16 before inference (dequant-at-load), proving the Rust quant is
78+ /// correct without a fused kernel yet.
79+ #[arg(long, default_value = "none")]
80+ quant: String,
81+
82+ /// turboquant: keep the top this-fraction of |rotated| values in fp16
83+ /// (outlier split). 0.0 disables the split. Default 0.005 (~0.5%).
84+ #[arg(long, default_value_t = 0.005)]
85+ outlier_frac: f32,
86+
87+ /// Benchmark mode: prefill `--bench-ctx` synthetic tokens (warm the KV cache),
88+ /// then measure PURE decode tok/s over `--bench-decode` steps (median of
89+ /// per-token latencies). Mirrors `llama-bench -d <ctx> -n <decode>`. Prints a
90+ /// one-line machine-readable result. Skips the prompt/streaming path.
91+ #[arg(long)]
92+ bench: bool,
93+
94+ /// Context depth (already-cached tokens) for `--bench`. The decode is measured
95+ /// with this many tokens in the KV cache (long ctx = bandwidth/cache heavy).
96+ #[arg(long, default_value_t = 0)]
97+ bench_ctx: usize,
98+
99+ /// How many decode steps to time in `--bench` (after a few warmup steps).
100+ #[arg(long, default_value_t = 64)]
101+ bench_decode: usize,
102+}
103+
104+/// Pick Metal (Apple Silicon GPU) if available, else CPU.
105+fn pick_device(force_cpu: bool) -> Result<Device> {
106+ if force_cpu {
107+ return Ok(Device::Cpu);
108+ }
109+ if candle_core::utils::metal_is_available() {
110+ // device ordinal 0
111+ match Device::new_metal(0) {
112+ Ok(d) => return Ok(d),
113+ Err(e) => eprintln!("warning: Metal requested but failed ({e}); falling back to CPU"),
114+ }
115+ } else if candle_core::utils::cuda_is_available() {
116+ match Device::new_cuda(0) {
117+ Ok(d) => return Ok(d),
118+ Err(e) => eprintln!("warning: CUDA requested but failed ({e}); falling back to CPU"),
119+ }
120+ }
121+ Ok(Device::Cpu)
122+}
123+
124+fn device_label(dev: &Device) -> &'static str {
125+ match dev {
126+ Device::Cpu => "CPU",
127+ Device::Metal(_) => "Metal (Apple Silicon GPU)",
128+ Device::Cuda(_) => "CUDA (NVIDIA GPU)",
129+ }
130+}
131+
132+/// Collect every *.safetensors file in the model directory.
133+fn safetensors_files(dir: &PathBuf) -> Result<Vec<PathBuf>> {
134+ let mut files = Vec::new();
135+ for entry in std::fs::read_dir(dir)
136+ .with_context(|| format!("reading model dir {}", dir.display()))?
137+ {
138+ let path = entry?.path();
139+ // Skip macOS AppleDouble sidecars (`._model-*.safetensors`) — 4 KB resource-fork
140+ // junk created when a model dir is copied to exFAT/FAT (e.g. the Lexar drive).
141+ // Reading their first 8 bytes as a safetensors header length → "header too large".
142+ let is_appledouble = path
143+ .file_name()
144+ .and_then(|n| n.to_str())
145+ .map(|n| n.starts_with("._"))
146+ .unwrap_or(false);
147+ if is_appledouble {
148+ continue;
149+ }
150+ if path.extension().map(|e| e == "safetensors").unwrap_or(false) {
151+ files.push(path);
152+ }
153+ }
154+ if files.is_empty() {
155+ return Err(anyhow!("no *.safetensors files in {}", dir.display()));
156+ }
157+ files.sort();
158+ Ok(files)
159+}
160+
161+/// Is this a Linear projection weight we should turboquant?
162+/// (attention q/k/v/o and MLP gate/up/down — the bulk of the parameters — plus the
163+/// DeepSeek-V2/V3 MLA latent projections kv_a_proj_with_mqa/kv_b_proj and, for the
164+/// q-LoRA MLA variant, q_a_proj/q_b_proj). We deliberately skip embeddings, norms,
165+/// biases, routers, and anything not 2-D.
166+fn is_quant_target(name: &str) -> bool {
167+ const PROJ: [&str; 11] = [
168+ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj",
169+ // DeepSeek MLA (Arch::DeepSeekV2): compressed KV / query latent projections.
170+ "kv_a_proj_with_mqa", "kv_b_proj", "q_a_proj", "q_b_proj",
171+ ];
172+ name.ends_with(".weight") && PROJ.iter().any(|p| name.contains(&format!(".{p}.")))
173+}
174+
175+/// Is this a projection bias (q/k/v_proj carry biases in Qwen2) we must keep for
176+/// the fast path's QuantizedLinear?
177+fn is_proj_bias(name: &str) -> bool {
178+ const PROJ: [&str; 7] = [
179+ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj",
180+ ];
181+ name.ends_with(".bias") && PROJ.iter().any(|p| name.contains(&format!(".{p}.")))
182+}
183+
184+/// Load every weight from the safetensors files on CPU, turboquant-v2 each Linear
185+/// projection weight (data-free), reconstruct it (dequant-at-load), and return a
186+/// HashMap of tensors on `device` at `dtype` ready for `VarBuilder::from_tensors`.
187+///
188+/// Prints the storage win: total compressed bytes vs the fp16 baseline, the
189+/// effective bpw, and how many matrices were quantized.
190+///
191+/// NOTE (next milestone hook): to keep weights compressed in RAM and fuse a
192+/// FWHT-dequant Metal kernel, you'd store the `TqWeight`s here instead of
193+/// decoding, and hand them to a custom QuantizedLinear at model-build time. For
194+/// v1 we reconstruct fp16 right here — see decode() below.
195+fn quantize_weights(
196+ weight_files: &[PathBuf],
197+ outlier_frac: f32,
198+ block_hadamard: bool,
199+ dtype: DType,
200+ device: &Device,
201+) -> Result<HashMap<String, Tensor>> {
202+ use turboquant::{decode, encode, TqConfig, LLOYD_MAX_3BIT};
203+
204+ let cpu = Device::Cpu;
205+ let cfg = TqConfig { outlier_frac, block_hadamard, ..TqConfig::default() };
206+ let codebook = LLOYD_MAX_3BIT;
207+
208+ let mut out: HashMap<String, Tensor> = HashMap::new();
209+ let mut quantized = 0usize;
210+ let mut q_orig_fp16_bytes = 0usize; // fp16 baseline of the quantized matrices
211+ let mut q_comp_bytes = 0usize; // compressed bytes of those matrices
212+ let mut passthrough_bytes = 0usize; // fp16 baseline of everything left alone
213+ let mut total_relfro = 0f64;
214+
215+ let t0 = std::time::Instant::now();
216+ for file in weight_files {
217+ // Load this shard's tensors on CPU (so we can pull raw f32 data out).
218+ let shard = candle_core::safetensors::load(file, &cpu)
219+ .with_context(|| format!("loading {}", file.display()))?;
220+ for (name, tensor) in shard.into_iter() {
221+ let dims = tensor.dims().to_vec();
222+ if is_quant_target(&name) && dims.len() == 2 {
223+ let (rows, cols) = (dims[0], dims[1]);
224+ let w: Vec<f32> = tensor.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
225+
226+ let q = encode(&w, rows, cols, &cfg, &codebook);
227+ let wq = decode(&q);
228+
229+ total_relfro += turboquant::relative_fro(&w, &wq);
230+ q_orig_fp16_bytes += rows * cols * 2;
231+ q_comp_bytes += q.compressed_bytes();
232+ quantized += 1;
233+
234+ let recon = Tensor::from_vec(wq, (rows, cols), &cpu)?
235+ .to_dtype(dtype)?
236+ .to_device(device)?;
237+ out.insert(name, recon);
238+ } else {
239+ // Pass through untouched (embeddings, norms, biases, lm_head).
240+ let n: usize = dims.iter().product();
241+ passthrough_bytes += n * 2;
242+ out.insert(name, tensor.to_dtype(dtype)?.to_device(device)?);
243+ }
244+ }
245+ }
246+
247+ let total_fp16 = q_orig_fp16_bytes + passthrough_bytes;
248+ let total_comp = q_comp_bytes + passthrough_bytes;
249+ let mb = |b: usize| b as f64 / (1024.0 * 1024.0);
250+ let avg_relfro = if quantized > 0 { total_relfro / quantized as f64 } else { 0.0 };
251+ // Effective bpw over the quantized weights only.
252+ let q_weights: usize = q_orig_fp16_bytes / 2;
253+ let eff_bpw = if q_weights > 0 {
254+ (q_comp_bytes * 8) as f64 / q_weights as f64
255+ } else {
256+ 0.0
257+ };
258+
259+ let mode = if block_hadamard { "block-diagonal FWHT (no pad)" } else { "v2 full-row FWHT (pad-to-pow2)" };
260+ println!(
261+ "turboquant | rotation: {} | quantized {} Linear matrices, outlier_frac={} in {:.2}s",
262+ mode,
263+ quantized,
264+ outlier_frac,
265+ t0.elapsed().as_secs_f64()
266+ );
267+ println!(
268+ " quantized-weight storage : {:.1} MB fp16 -> {:.1} MB compressed ({:.2}x, {:.3} bpw)",
269+ mb(q_orig_fp16_bytes),
270+ mb(q_comp_bytes),
271+ q_orig_fp16_bytes as f64 / q_comp_bytes.max(1) as f64,
272+ eff_bpw,
273+ );
274+ println!(
275+ " whole-model artifact : {:.1} MB fp16 -> {:.1} MB compressed ({:.2}x) | avg relFro {:.4}",
276+ mb(total_fp16),
277+ mb(total_comp),
278+ total_fp16 as f64 / total_comp.max(1) as f64,
279+ avg_relfro,
280+ );
281+
282+ Ok(out)
283+}
284+
285+/// Either the upstream dense/dequant-at-load model, or the turboquant-fast model
286+/// that keeps weights compressed. The fast path is now a `Box<dyn Model>` from the
287+/// config-driven registry (qwen2 is registry entry #1); the dense fallback stays
288+/// candle-qwen2-typed. Both expose `forward(input, offset) -> logits`.
289+enum Engine {
290+ Dense(ModelForCausalLM),
291+ Fast(Box<dyn CocoModel>),
292+}
293+
294+impl Engine {
295+ fn forward(&mut self, input: &Tensor, offset: usize) -> Result<Tensor> {
296+ match self {
297+ Engine::Dense(m) => Ok(m.forward(input, offset)?),
298+ Engine::Fast(m) => m.forward(input, offset),
299+ }
300+ }
301+
302+ fn clear_kv_cache(&mut self) {
303+ match self {
304+ Engine::Dense(m) => m.clear_kv_cache(),
305+ Engine::Fast(m) => m.clear_kv_cache(),
306+ }
307+ }
308+}
309+
310+/// Pure-decode benchmark: prefill `ctx` synthetic tokens (one forward over the
311+/// whole synthetic prompt, like a real prompt — warms the KV cache to depth
312+/// `ctx`), then time `decode` single-token decode steps and report the MEDIAN
313+/// per-step latency → tok/s. Mirrors `llama-bench -d <ctx> -n <decode>`. We use a
314+/// fixed, valid token id so the KV cache content is realistic; greedy argmax is
315+/// irrelevant to decode cost so we skip sampling and just feed a constant token.
316+fn run_bench(
317+ model: &mut Engine,
318+ device: &Device,
319+ ctx: usize,
320+ decode: usize,
321+ label: &str,
322+) -> Result<()> {
323+ model.clear_kv_cache();
324+ let tok: u32 = 100; // any valid, non-special token id
325+ // Prefill to depth `ctx` in CHUNKS so the non-flash attention never builds a
326+ // [seq, seq] weight matrix bigger than chunk×ctx (a single 32K forward would
327+ // need a [1,heads,32K,32K] tensor → tens of GB → OOM). Real engines chunk
328+ // prefill too; this just warms the KV cache to depth `ctx`. ctx==0 → depth 0.
329+ let mut offset = 0usize;
330+ if ctx > 0 {
331+ let chunk = 512usize;
332+ while offset < ctx {
333+ let n = chunk.min(ctx - offset);
334+ let piece: Vec<u32> = vec![tok; n];
335+ let input = Tensor::new(piece.as_slice(), device)?.unsqueeze(0)?;
336+ let _ = model.forward(&input, offset)?;
337+ offset += n;
338+ }
339+ device_sync(device)?;
340+ }
341+
342+ // A few warmup decode steps (shader caches, clocks) — not timed. Sync once
343+ // at the end of warmup so the GPU is settled before timing.
344+ let warmup = 8usize.min(decode.max(1));
345+ for _ in 0..warmup {
346+ let input = Tensor::new(&[tok], device)?.unsqueeze(0)?;
347+ let _ = model.forward(&input, offset)?;
348+ offset += 1;
349+ }
350+ device_sync(device)?;
351+
352+ // Steady-state, PIPELINED decode throughput: enqueue all `decode` single-token
353+ // steps back-to-back (Metal pipelines them like a real generation loop / like
354+ // llama-bench's tg), then ONE sync drains the queue. tok/s = decode / wall.
355+ // (Per-step sync would serialize the GPU and report cold-start latency, not
356+ // steady throughput — that's not what we or llama-bench measure.) We also run
357+ // a few repeats and keep the best (lowest-noise) wall time.
358+ let reps = 3usize;
359+ let mut best_tok_s = 0f64;
360+ for _ in 0..reps {
361+ let t0 = std::time::Instant::now();
362+ for _ in 0..decode {
363+ let input = Tensor::new(&[tok], device)?.unsqueeze(0)?;
364+ let _ = model.forward(&input, offset)?;
365+ offset += 1;
366+ }
367+ device_sync(device)?;
368+ let wall = t0.elapsed().as_secs_f64();
369+ let tok_s = decode as f64 / wall.max(1e-9);
370+ if tok_s > best_tok_s {
371+ best_tok_s = tok_s;
372+ }
373+ }
374+ println!(
375+ "BENCH {label} | ctx={ctx} decode={decode} | {:.2} tok/s (best of {reps})",
376+ best_tok_s
377+ );
378+ // If COCO_PROFILE was set, run one extra UNPIPELINED (sync-per-token) decode
379+ // pass so the per-phase timers see real wall time, then report the breakdown.
380+ if std::env::var("COCO_PROFILE").is_ok() {
381+ for _ in 0..decode {
382+ let input = Tensor::new(&[tok], device)?.unsqueeze(0)?;
383+ let _ = model.forward(&input, offset)?;
384+ offset += 1;
385+ }
386+ if let Engine::Fast(_) = model {
387+ model::profile_report();
388+ }
389+ }
390+ Ok(())
391+}
392+
393+/// Force the device to finish all queued work so timings are real (Metal is async).
394+fn device_sync(device: &Device) -> Result<()> {
395+ // Synchronize the whole device (drains the command queue). On Metal this maps
396+ // to wait_until_completed for the in-flight command buffer.
397+ device.synchronize()?;
398+ Ok(())
399+}
400+
401+/// Load every weight on CPU (f32), build the turboquant-fast `qwen2_q::Model`
402+/// (encodes target weights data-free, keeps them compressed on the GPU), and
403+/// report the compressed-vs-fp16 storage of the quantized matrices.
404+fn build_fast_engine(
405+ weight_files: &[std::path::PathBuf],
406+ config: &CocoConfig,
407+ dense_cfg: Option<&Config>,
408+ dtype: DType,
409+ device: &Device,
410+ model_label: std::path::Display<'_>,
411+) -> Result<Engine> {
412+ use turboquant::TqConfig;
413+
414+ let t0 = std::time::Instant::now();
415+ let cpu = Device::Cpu;
416+
417+ // Load ONLY the quant-target tensors (the 7 projections' weights+biases) on
418+ // CPU as f32 so `encode` can pull raw values. Everything else (embeddings,
419+ // norms, lm_head) is read on demand from the mmap'd VarBuilder below — we do
420+ // NOT pull it into this f32 map, keeping the build-time RAM peak bounded.
421+ let mut tensors: HashMap<String, Tensor> = HashMap::new();
422+ for file in weight_files {
423+ let shard = candle_core::safetensors::load(file, &cpu)
424+ .with_context(|| format!("loading {}", file.display()))?;
425+ for (name, tensor) in shard.into_iter() {
426+ if is_quant_target(&name) || (name.ends_with(".bias") && is_proj_bias(&name)) {
427+ tensors.insert(name, tensor.to_dtype(DType::F32)?);
428+ }
429+ }
430+ }
431+
432+ // A dense mmap'd VarBuilder for the small passthrough tensors (embeddings,
433+ // norms, lm_head) — read straight from disk in the target dtype.
434+ let vb = unsafe { VarBuilder::from_mmaped_safetensors(weight_files, dtype, device)? };
435+
436+ // turboquant-fast requires the clean 3-bit block recipe (no padding, no
437+ // sparse outliers) so the kernel can read fixed-width packed codes.
438+ let cfg = TqConfig {
439+ outlier_frac: 0.0,
440+ block_hadamard: true,
441+ ..TqConfig::default()
442+ };
443+
444+ let src = qwen2_q::WeightSource {
445+ tensors,
446+ device: device.clone(),
447+ dtype,
448+ cfg,
449+ total_compressed_bytes: 0,
450+ total_fp16_bytes: 0,
451+ n_quant: 0,
452+ };
453+
454+ // COCO_REGISTRY gate (the Step-0 A/B seam). UNSET (default) = the ORIGINAL
455+ // inlined qwen2 forward (qwen2_legacy::Model, candle Config). SET = the NEW
456+ // config-driven registry path (model::build_model, CocoConfig). Both produce a
457+ // `Box<dyn Model>`; the two paths share the SAME load-time turboquant machinery
458+ // (WeightSource) so only the forward wiring differs.
459+ let use_registry = matches!(std::env::var("COCO_REGISTRY").as_deref(), Ok(v) if v != "0");
460+ let (model, stats): (Box<dyn CocoModel>, qwen2_q::WeightStats) = if use_registry {
461+ eprintln!("COCO_REGISTRY=1 — using the config-driven registry forward (model.rs)");
462+ model::build_model(config, src, vb)?
463+ } else {
464+ let dense_cfg = dense_cfg.ok_or_else(|| {
465+ anyhow!("legacy fast path (COCO_REGISTRY unset) requires the candle qwen2 Config")
466+ })?;
467+ let (m, stats) = qwen2_legacy::Model::new(dense_cfg, src, vb)?;
468+ (Box::new(m), stats)
469+ };
470+
471+ let mb = |b: usize| b as f64 / (1024.0 * 1024.0);
472+ let eff_bpw = (stats.compressed_bytes * 8) as f64 / (stats.fp16_bytes / 2).max(1) as f64;
473+ println!(
474+ "turboquant-fast | compressed {} Linear matrices in {:.2}s (weights stay packed on GPU)",
475+ stats.n_quant,
476+ t0.elapsed().as_secs_f64()
477+ );
478+ println!(
479+ " quantized-weight storage : {:.1} MB fp16 -> {:.1} MB compressed (resident) ({:.2}x, {:.3} bpw)",
480+ mb(stats.fp16_bytes),
481+ mb(stats.compressed_bytes),
482+ stats.fp16_bytes as f64 / stats.compressed_bytes.max(1) as f64,
483+ eff_bpw,
484+ );
485+ println!(
486+ "loaded {} ({} layers, hidden {}) in {:.2}s",
487+ model_label,
488+ config.num_hidden_layers,
489+ config.hidden_size,
490+ t0.elapsed().as_secs_f64()
491+ );
492+
493+ Ok(Engine::Fast(model))
494+}
495+
496+/// A tiny candle-qwen2 Config used ONLY by the dense (non-turboquant) fallback path.
497+/// The quant/fast path never touches this — it goes through CocoConfig + build_model.
498+fn dense_config_from_dir(dir: &std::path::Path) -> Result<Config> {
499+ let cfg_path = dir.join("config.json");
500+ let config: Config = serde_json::from_slice(
501+ &std::fs::read(&cfg_path).with_context(|| format!("reading {}", cfg_path.display()))?,
502+ )
503+ .with_context(|| format!("parsing {}", cfg_path.display()))?;
504+ Ok(config)
505+}
506+
507+fn main() -> Result<()> {
508+ let args = Args::parse();
509+
510+ let device = pick_device(args.cpu)?;
511+ // Qwen2.5 weights are bf16. Metal supports bf16; on CPU bf16 also works in candle.
512+ let dtype = if device.is_cpu() { DType::F32 } else { DType::BF16 };
513+ println!(
514+ "coco v0 | device: {} | dtype: {:?}",
515+ device_label(&device),
516+ dtype
517+ );
518+
519+ // ── Tokenizer ────────────────────────────────────────────────────────────
520+ let tok_path = args.model.join("tokenizer.json");
521+ let tokenizer = Tokenizer::from_file(&tok_path)
522+ .map_err(|e| anyhow!("loading tokenizer {}: {e}", tok_path.display()))?;
523+
524+ // ── Config: coco-owned CocoConfig (config.json → architectures[0] → Arch).
525+ // This drives the quant/fast path (the moat). The candle qwen2 Config is loaded
526+ // lazily below ONLY for the dense (non-turboquant) fallback.
527+ let coco_cfg = CocoConfig::from_dir(&args.model)?;
528+
529+ // ── Weights → VarBuilder → ModelForCausalLM ──────────────────────────────
530+ let weight_files = safetensors_files(&args.model)?;
531+ let load_start = std::time::Instant::now();
532+
533+ // (turbo_on, block_hadamard)
534+ let (turbo, block_hadamard) = match args.quant.as_str() {
535+ "none" | "off" | "fp16" => (false, false),
536+ // v2: full-row pad-to-power-of-two FWHT (max quality, padding-bpw cost).
537+ "turboquant" | "turboquant-v2" | "tq" => (true, false),
538+ // block: block-diagonal d-wide Hadamard, no padding (clean ~3.125 bpw).
539+ "turboquant-block" | "tq-block" | "block" => (true, true),
540+ // fast: keep weights COMPRESSED in RAM, fused rotate+quant-matmul kernel.
541+ "turboquant-fast" | "tq-fast" | "fast" => (false, false), // handled below
542+ other => {
543+ return Err(anyhow!(
544+ "unknown --quant mode {other:?} (use none | turboquant | turboquant-block | turboquant-fast)"
545+ ))
546+ }
547+ };
548+ let fast = matches!(args.quant.as_str(), "turboquant-fast" | "tq-fast" | "fast");
549+
550+ let mut model = if fast {
551+ // turboquant-fast: encode every target weight data-free and keep it
552+ // COMPRESSED on the GPU (packed 3-bit codes + fp16 radius). The matmul
553+ // reads the codes directly via a fused rotate-activation + quant-matmul
554+ // Metal kernel — W is NEVER dequantized to fp16.
555+ // The legacy (default) fast path needs candle's qwen2 Config; the registry
556+ // path needs only CocoConfig. Load the candle Config here so build_fast_engine
557+ // can pick either forward based on COCO_REGISTRY. It is OPTIONAL: a qwen3
558+ // config.json does NOT parse into candle's qwen2 Config (no head_dim field,
559+ // `sliding_window: null`), and the registry path never uses it — so only load
560+ // it when the legacy path will actually consume it (COCO_REGISTRY unset).
561+ let use_registry = matches!(std::env::var("COCO_REGISTRY").as_deref(), Ok(v) if v != "0");
562+ let dense_cfg = if use_registry {
563+ None
564+ } else {
565+ Some(dense_config_from_dir(&args.model)?)
566+ };
567+ build_fast_engine(
568+ &weight_files,
569+ &coco_cfg,
570+ dense_cfg.as_ref(),
571+ dtype,
572+ &device,
573+ args.model.display(),
574+ )?
575+ } else {
576+ // Dense/dequant fallback: candle's qwen2 Config + ModelForCausalLM.
577+ let config = dense_config_from_dir(&args.model)?;
578+ let vb = if turbo {
579+ // turboquant: quantize every Linear weight data-free, then reconstruct
580+ // (dequant-at-load). Owns the tensors in a HashMap.
581+ let tensors =
582+ quantize_weights(&weight_files, args.outlier_frac, block_hadamard, dtype, &device)?;
583+ VarBuilder::from_tensors(tensors, dtype, &device)
584+ } else {
585+ unsafe { VarBuilder::from_mmaped_safetensors(&weight_files, dtype, &device)? }
586+ };
587+ let m = ModelForCausalLM::new(&config, vb)?;
588+ println!(
589+ "loaded {} ({} layers, hidden {}) in {:.2}s",
590+ args.model.display(),
591+ config.num_hidden_layers,
592+ config.hidden_size,
593+ load_start.elapsed().as_secs_f64()
594+ );
595+ Engine::Dense(m)
596+ };
597+
598+ // ── Benchmark mode (pure decode tok/s at a given ctx depth) ──────────────
599+ if args.bench {
600+ let label = format!(
601+ "{} {}",
602+ args.model.file_name().and_then(|s| s.to_str()).unwrap_or("model"),
603+ args.quant
604+ );
605+ run_bench(&mut model, &device, args.bench_ctx, args.bench_decode, &label)?;
606+ return Ok(());
607+ }
608+
609+ // ── Encode prompt ────────────────────────────────────────────────────────
610+ let encoding = tokenizer
611+ .encode(args.prompt.as_str(), true)
612+ .map_err(|e| anyhow!("encoding prompt: {e}"))?;
613+ let mut tokens: Vec<u32> = encoding.get_ids().to_vec();
614+ if tokens.is_empty() {
615+ return Err(anyhow!("prompt encoded to zero tokens"));
616+ }
617+
618+ // eos: Qwen2.5 uses <|endoftext|> (151643) and <|im_end|> (151645).
619+ let eos_token = config_eos(&tokenizer).unwrap_or(151643);
620+
621+ let mut logits_processor = {
622+ let temp = if args.temperature <= 0.0 { None } else { Some(args.temperature) };
623+ LogitsProcessor::new(args.seed, temp, args.top_p)
624+ };
625+
626+ print!("\n{}", args.prompt);
627+ std::io::stdout().flush().ok();
628+
629+ // ── Generation loop (mirrors candle qwen example) ────────────────────────
630+ let mut generated = 0usize;
631+ let start_gen = std::time::Instant::now();
632+ let prompt_len = tokens.len();
633+
634+ for index in 0..args.max_tokens {
635+ // First pass feeds the whole prompt (offset 0); subsequent passes feed
636+ // only the last token, with seqlen_offset = number of cached tokens.
637+ let (context, offset) = if index == 0 {
638+ (tokens.as_slice(), 0)
639+ } else {
640+ (&tokens[tokens.len() - 1..], tokens.len() - 1)
641+ };
642+
643+ let input = Tensor::new(context, &device)?.unsqueeze(0)?; // [1, seq]
644+ let logits = model.forward(&input, offset)?; // [1, 1, vocab]
645+ let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?; // [vocab]
646+
647+ // COCO_DUMP_LOGITS: at the FIRST step (offset 0, identical prompt to any
648+ // reference), print the top-8 (id: logit) pairs. This is the matched-input
649+ // probe used to isolate the MLA math port from sampling drift: the argmax
650+ // and top-k ordering here reflect the full forward, before any greedy fork.
651+ if index == 0 && std::env::var("COCO_DUMP_LOGITS").is_ok() {
652+ let v: Vec<f32> = logits.to_vec1::<f32>()?;
653+ let mut idx: Vec<usize> = (0..v.len()).collect();
654+ idx.sort_by(|&a, &b| v[b].partial_cmp(&v[a]).unwrap());
655+ let top: Vec<String> =
656+ idx.iter().take(8).map(|&i| format!("{}:{:.4}", i, v[i])).collect();
657+ println!("LOGITS0 {}", top.join(","));
658+ }
659+
660+ // Repeat penalty over the recent window.
661+ let logits = if args.repeat_penalty == 1.0 {
662+ logits
663+ } else {
664+ let start = tokens.len().saturating_sub(args.repeat_last_n);
665+ candle_transformers::utils::apply_repeat_penalty(
666+ &logits,
667+ args.repeat_penalty,
668+ &tokens[start..],
669+ )?
670+ };
671+
672+ let next = logits_processor.sample(&logits)?;
673+ tokens.push(next);
674+ generated += 1;
675+
676+ if next == eos_token {
677+ break;
678+ }
679+
680+ // Stream decode: decode the growing tail and print the delta.
681+ if let Some(text) = decode_delta(&tokenizer, &tokens, prompt_len) {
682+ print!("{text}");
683+ std::io::stdout().flush().ok();
684+ }
685+ }
686+
687+ let elapsed = start_gen.elapsed().as_secs_f64();
688+ let tok_s = generated as f64 / elapsed.max(1e-9);
689+ // COCO_DUMP_TOKENS: print the exact generated token ids (behavior-neutral,
690+ // used by the Step-0 refactor gate to prove token-for-token identity).
691+ if std::env::var("COCO_DUMP_TOKENS").is_ok() {
692+ let gen_ids = &tokens[prompt_len..];
693+ let ids: Vec<String> = gen_ids.iter().map(|t| t.to_string()).collect();
694+ println!("TOKENS {}", ids.join(","));
695+ }
696+ println!(
697+ "\n\n── {} tokens in {:.2}s = {:.2} tok/s ({}) ──",
698+ generated,
699+ elapsed,
700+ tok_s,
701+ device_label(&device)
702+ );
703+
704+ Ok(())
705+}
706+
707+/// Best-effort eos lookup from the tokenizer's added tokens.
708+fn config_eos(tokenizer: &Tokenizer) -> Option<u32> {
709+ tokenizer.token_to_id("<|endoftext|>")
710+}
711+
712+/// Decode the full token stream and return only the new suffix appended since
713+/// the previous call (simple, robust streaming that handles multi-byte pieces).
714+fn decode_delta(tokenizer: &Tokenizer, tokens: &[u32], prompt_len: usize) -> Option<String> {
715+ use std::cell::RefCell;
716+ thread_local! {
717+ static PRINTED: RefCell<usize> = const { RefCell::new(0) };
718+ }
719+ let gen = &tokens[prompt_len..];
720+ let full = tokenizer.decode(gen, true).ok()?;
721+ PRINTED.with(|p| {
722+ let mut printed = p.borrow_mut();
723+ if full.len() > *printed {
724+ let delta = full[*printed..].to_string();
725+ *printed = full.len();
726+ Some(delta)
727+ } else {
728+ None
729+ }
730+ })
731+}
added src/merge.rs +233 −0
@@ -0,0 +1,233 @@
1+// Step-1 merge primitive: data-free evolutionary merge of two same-arch parents.
2+//
3+// Both parents are loaded ONCE as CPU-resident f32 tensor maps. Per candidate a
4+// `num_layers+2` genome lerps every tensor (child = (1-a)*A + a*B) into ONE
5+// in-memory HashMap<String,Tensor>, which is handed straight to a runnable coco
6+// Model on Metal — no temp safetensors, no disk round-trip. Deterministic `drop`
7+// between candidates makes the Python Metal-fragmentation crash structurally
8+// impossible (constant-shape children ⇒ candle Metal pool reuse).
9+//
10+// Two build paths:
11+// * build_child_dense — candle ModelForCausalLM (fp16/bf16, NO turboquant). The
12+// numeric-parity gate vs the Python reference.
13+// * build_child_quant — coco build_model (3-bit turboquant, the GA search rep).
14+
15+use std::collections::HashMap;
16+
17+use anyhow::{anyhow, Context, Result};
18+use candle_core::{DType, Device, Tensor};
19+use candle_nn::VarBuilder;
20+use candle_transformers::models::qwen2::{Config as DenseConfig, ModelForCausalLM};
21+
22+use crate::config::CocoConfig;
23+use crate::model::{build_model, Model};
24+use crate::qwen2_q::WeightSource;
25+use crate::turboquant::TqConfig;
26+
27+// ─────────────────────────── genome grouping (port of merge.py) ───────────────────────────
28+
29+/// Map a state_dict key → genome group index. Order: `[L0..L(n-1), embed, norm]`,
30+/// so `embed = genome_len-2`, `norm = genome_len-1`. Verbatim semantics of
31+/// `merge.py::tensor_group`: `model.layers.<L>.` → L, `embed_tokens`/`lm_head.weight`
32+/// → embed, `model.norm.weight` (or any stray key) → norm.
33+pub fn group_index(key: &str, genome_len: usize) -> usize {
34+ let embed = genome_len - 2;
35+ let norm = genome_len - 1;
36+ // model.layers.<n>. → n
37+ if let Some(rest) = key.strip_prefix("model.layers.") {
38+ if let Some(dot) = rest.find('.') {
39+ if let Ok(n) = rest[..dot].parse::<usize>() {
40+ return n;
41+ }
42+ }
43+ }
44+ if key.contains("embed_tokens") || key == "lm_head.weight" {
45+ return embed;
46+ }
47+ // model.norm.weight and any stray key → norm group (matches merge.py fallback).
48+ norm
49+}
50+
51+/// Is this a Linear projection weight coco turboquants? (attention q/k/v/o + MLP
52+/// gate/up/down.) Mirrors `main.rs::is_quant_target` for the qwen2/qwen3 path.
53+pub fn is_quant_target(name: &str) -> bool {
54+ const PROJ: [&str; 11] = [
55+ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj",
56+ "kv_a_proj_with_mqa", "kv_b_proj", "q_a_proj", "q_b_proj",
57+ ];
58+ name.ends_with(".weight") && PROJ.iter().any(|p| name.contains(&format!(".{p}.")))
59+}
60+
61+/// Is this a projection bias (q/k/v_proj carry biases in Qwen2)? Mirrors
62+/// `main.rs::is_proj_bias`.
63+pub fn is_proj_bias(name: &str) -> bool {
64+ const PROJ: [&str; 7] = [
65+ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj",
66+ ];
67+ name.ends_with(".bias") && PROJ.iter().any(|p| name.contains(&format!(".{p}.")))
68+}
69+
70+// ─────────────────────────── parent loading ───────────────────────────
71+
72+/// Load one parent's FULL safetensors as a CPU-resident f32 tensor map (loaded ONCE,
73+/// held for the whole search). CPU RAM never fragments the Metal heap.
74+pub fn load_parent_f32(dir: &std::path::Path) -> Result<HashMap<String, Tensor>> {
75+ let files = safetensors_files(dir)?;
76+ let cpu = Device::Cpu;
77+ let mut out: HashMap<String, Tensor> = HashMap::new();
78+ for file in &files {
79+ let shard = candle_core::safetensors::load(file, &cpu)
80+ .with_context(|| format!("loading {}", file.display()))?;
81+ for (name, tensor) in shard.into_iter() {
82+ out.insert(name, tensor.to_dtype(DType::F32)?);
83+ }
84+ }
85+ if out.is_empty() {
86+ return Err(anyhow!("no tensors loaded from {}", dir.display()));
87+ }
88+ Ok(out)
89+}
90+
91+/// Collect every *.safetensors file in a model directory (sorted).
92+pub fn safetensors_files(dir: &std::path::Path) -> Result<Vec<std::path::PathBuf>> {
93+ let mut files = Vec::new();
94+ for entry in std::fs::read_dir(dir)
95+ .with_context(|| format!("reading model dir {}", dir.display()))?
96+ {
97+ let path = entry?.path();
98+ if path.extension().map(|e| e == "safetensors").unwrap_or(false) {
99+ files.push(path);
100+ }
101+ }
102+ if files.is_empty() {
103+ return Err(anyhow!("no *.safetensors files in {}", dir.display()));
104+ }
105+ files.sort();
106+ Ok(files)
107+}
108+
109+/// candle-qwen2 `Config` for the dense (--no-quant) parity path.
110+pub fn dense_config_from_dir(dir: &std::path::Path) -> Result<DenseConfig> {
111+ let cfg_path = dir.join("config.json");
112+ let cfg: DenseConfig = serde_json::from_slice(
113+ &std::fs::read(&cfg_path).with_context(|| format!("reading {}", cfg_path.display()))?,
114+ )
115+ .with_context(|| format!("parsing {}", cfg_path.display()))?;
116+ Ok(cfg)
117+}
118+
119+// ─────────────────────────── the blend ───────────────────────────
120+
121+/// Union over both parents' keys (identical shapes; every key present in both). Blend
122+/// each tensor in f32: `child = (1-a)*A + a*B`, `a = genome[group_index(key)]`. Bit-
123+/// faithful to the validated `torch.lerp(...float())`; cast to eval dtype at build.
124+///
125+/// Fast paths: `a<=0` → clone A, `a>=1` → clone B (no blend), matching `merge.py`.
126+pub fn merge_full(
127+ genome: &[f32],
128+ a_map: &HashMap<String, Tensor>,
129+ b_map: &HashMap<String, Tensor>,
130+) -> Result<HashMap<String, Tensor>> {
131+ let mut out = HashMap::with_capacity(a_map.len());
132+ for (k, ta) in a_map {
133+ let tb = b_map
134+ .get(k)
135+ .ok_or_else(|| anyhow!("key {k} present in parent A but missing in parent B"))?;
136+ let a = genome[group_index(k, genome.len())] as f64;
137+ let blended = if a <= 0.0 {
138+ ta.clone()
139+ } else if a >= 1.0 {
140+ tb.clone()
141+ } else {
142+ // f32 lerp: (1-a)*ta + a*tb
143+ ((ta * (1.0 - a))? + (tb * a)?)?
144+ };
145+ out.insert(k.clone(), blended);
146+ }
147+ Ok(out)
148+}
149+
150+// ─────────────────────────── build path 1: dense fp16 (parity gate) ───────────────────────────
151+
152+/// A candle `ModelForCausalLM` wrapped in coco's `Model` trait so the SAME
153+/// `eval::fitness` drives either build path via `&mut dyn Model`. Both expose the
154+/// identical `forward(ids, offset) -> [1,1,vocab]` last-position contract.
155+pub struct DenseChild(pub ModelForCausalLM);
156+
157+impl Model for DenseChild {
158+ fn forward(&mut self, ids: &Tensor, offset: usize) -> Result<Tensor> {
159+ Ok(self.0.forward(ids, offset)?)
160+ }
161+ fn clear_kv_cache(&mut self) {
162+ self.0.clear_kv_cache();
163+ }
164+}
165+
166+/// `--no-quant` dense fp16 build: feed the FULL blended map to candle's dense path.
167+/// Zero turboquant, fp16-faithful, apples-to-apples with the Python reference. Tied
168+/// lm_head handled by candle when `lm_head.weight` is absent (Qwen2.5-1.5B ties).
169+pub fn build_child_dense(
170+ full: &HashMap<String, Tensor>,
171+ cfg: &DenseConfig,
172+ dev: &Device,
173+ dtype: DType,
174+) -> Result<Box<dyn Model>> {
175+ let vb = VarBuilder::from_tensors(full.clone(), dtype, dev);
176+ let m = ModelForCausalLM::new(cfg, vb)?;
177+ Ok(Box::new(DenseChild(m)))
178+}
179+
180+// ─────────────────────────── build path 2: turboquant (GA search rep) ───────────────────────────
181+
182+/// Split a full blended map into (a) quant-target weights+biases → `WeightSource.tensors`
183+/// (CPU f32); (b) everything else (embeds, norms) → `VarBuilder::from_tensors` on device.
184+/// Mirrors `main.rs::build_fast_engine` (410-441) but sourced from the blended map.
185+pub fn split_weightsource(
186+ full: HashMap<String, Tensor>,
187+ dev: &Device,
188+ dtype: DType,
189+) -> Result<(WeightSource, VarBuilder<'static>)> {
190+ let mut quant: HashMap<String, Tensor> = HashMap::new();
191+ let mut rest: HashMap<String, Tensor> = HashMap::new();
192+ for (name, t) in full.into_iter() {
193+ if is_quant_target(&name) || is_proj_bias(&name) {
194+ // quant targets stay CPU f32 (encode() pulls raw values).
195+ quant.insert(name, t);
196+ } else {
197+ // embeds/norms go straight to device in the model dtype.
198+ rest.insert(name, t.to_dtype(dtype)?.to_device(dev)?);
199+ }
200+ }
201+ let vb = VarBuilder::from_tensors(rest, dtype, dev);
202+ // Clean 3-bit block recipe (no padding, no sparse outliers) — the fast kernel's contract.
203+ let cfg = TqConfig {
204+ outlier_frac: 0.0,
205+ block_hadamard: true,
206+ ..TqConfig::default()
207+ };
208+ let src = WeightSource {
209+ tensors: quant,
210+ device: dev.clone(),
211+ dtype,
212+ cfg,
213+ total_compressed_bytes: 0,
214+ total_fp16_bytes: 0,
215+ n_quant: 0,
216+ };
217+ Ok((src, vb))
218+}
219+
220+/// turboquant build: blended map → `build_model` (3-bit turboquant + Metal wiring).
221+/// Uses the config-driven registry path (Arch::Qwen2 → DenseDecoder), same as the
222+/// `coco` bin under COCO_REGISTRY=1. Baselines here differ slightly from Python fp16
223+/// (turboquant offset) — that's expected; the parity gate uses `build_child_dense`.
224+pub fn build_child_quant(
225+ full: HashMap<String, Tensor>,
226+ cfg: &CocoConfig,
227+ dev: &Device,
228+ dtype: DType,
229+) -> Result<Box<dyn Model>> {
230+ let (src, vb) = split_weightsource(full, dev, dtype)?;
231+ let (model, _stats) = build_model(cfg, src, vb)?;
232+ Ok(model)
233+}
added src/model.rs +1511 −0
@@ -0,0 +1,1511 @@
1+// coco config-driven decoder: the fixed primitive set + Model/SequenceMixer traits
2+// + build_model dispatcher.
3+//
4+// STEP 0 (pure refactor, no behavior change): the inlined qwen2 forward from
5+// qwen2_q.rs is lifted VERBATIM into named primitives that WRAP the existing
6+// qlinear.rs machinery:
7+// RmsNorm → wraps RmsNormFused
8+// Rope → wraps RotaryEmbedding + rope_apply
9+// GqaAttention → the flash-decode block (incl. COCO_FUSED_ATTN candle fallback +
10+// persistent KvCache); the first (and only) SequenceMixer impl
11+// SwiGlu → the fused MLP
12+// A DecoderLayer holds input_norm, mixer: Box<dyn SequenceMixer>, pre_ffn_norm, and
13+// ffn: Ffn::Dense(SwiGlu). Optional post-attn / post-ffn norms are None for qwen2.
14+//
15+// The trait-object dispatch is once per layer per token — proven negligible by the
16+// Step-0 tok/s gate (design §5 risk 4).
17+
18+use anyhow::Result;
19+use candle_core::{DType, Device, Module, Tensor, D};
20+use candle_nn::{Activation, VarBuilder};
21+use std::sync::Arc;
22+
23+use crate::config::{yarn_get_mscale, Arch, CocoConfig, RopeScaling};
24+use crate::qlinear::{fuse_resid_enabled, rope_apply, KvCache, QGroup, RmsNormFused};
25+use crate::qwen2_q::{Proj, WeightSource, WeightStats};
26+
27+// ── env-flag helpers (identical semantics to the originals in qwen2_q.rs) ──────────
28+
29+fn fused_max_ctx() -> usize {
30+ std::env::var("COCO_MAX_CTX")
31+ .ok()
32+ .and_then(|s| s.parse().ok())
33+ .unwrap_or(8192)
34+}
35+
36+fn fused_attn_enabled() -> bool {
37+ !matches!(std::env::var("COCO_FUSED_ATTN").as_deref(), Ok("0"))
38+}
39+
40+fn fused_min_ctx() -> usize {
41+ std::env::var("COCO_FUSED_MIN_CTX")
42+ .ok()
43+ .and_then(|s| s.parse().ok())
44+ .unwrap_or(0)
45+}
46+
47+/// Debug switch: when COCO_NO_QK_NORM is set, SKIP the qwen3 q_norm/k_norm even
48+/// though they were loaded. Lets the Prove phase show that turning qk_norm off
49+/// garbles a qwen3 model — proving the primitive is real and on the live path.
50+/// Default OFF (unset) → qk_norm applies normally.
51+fn qk_norm_disabled() -> bool {
52+ std::env::var("COCO_NO_QK_NORM").is_ok()
53+}
54+
55+/// Gate for the (future) fused MLA Metal kernel. Default = the candle fallback (always
56+/// correct). Mirrors `COCO_FUSED_ATTN`. A fused latent-cache flash-decode kernel would
57+/// switch on when `COCO_FUSED_MLA=1`; today only the fallback exists, so this is read
58+/// but the fused branch is not yet wired (the fallback is unconditionally taken).
59+fn fused_mla_enabled() -> bool {
60+ matches!(std::env::var("COCO_FUSED_MLA").as_deref(), Ok("1"))
61+}
62+
63+// ─────────────────────────── the shared model contract ───────────────────────────
64+
65+/// The model contract every arch wiring implements (candle has NO such trait).
66+pub trait Model {
67+ fn forward(&mut self, ids: &Tensor, offset: usize) -> Result<Tensor>;
68+ fn clear_kv_cache(&mut self);
69+}
70+
71+/// The ONE pluggable per-layer seam. GqaAttention is the first/only impl in Step 0;
72+/// Mla / SparseSelect / GatedDeltaNet / ShortConv land in later steps.
73+pub trait SequenceMixer {
74+ /// `xs` is already input-normed upstream. `resid` (COCO_FUSE_RESID) is the layer
75+ /// input folded into the o_proj store epilogue. Returns the mixed hidden state.
76+ fn forward(
77+ &mut self,
78+ xs: &Tensor,
79+ attention_mask: Option<&Tensor>,
80+ seqlen_offset: usize,
81+ resid: Option<&Tensor>,
82+ ) -> Result<Tensor>;
83+ fn clear_cache(&mut self);
84+}
85+
86+// ─────────────────────────── primitive: RmsNorm ───────────────────────────
87+
88+/// Fused RMSNorm primitive — thin wrapper over the existing `RmsNormFused` kernel.
89+pub struct RmsNorm(RmsNormFused);
90+
91+impl RmsNorm {
92+ pub fn new(weight: Tensor, eps: f64) -> Result<Self> {
93+ Ok(Self(RmsNormFused::new(weight, eps)?))
94+ }
95+ pub fn forward(&self, x: &Tensor) -> Result<Tensor> {
96+ self.0.forward(x)
97+ }
98+ /// Fused residual-add + RMSNorm in one dispatch → (h = a+b, normed = norm(h)).
99+ pub fn forward_add(&self, a: &Tensor, b: &Tensor) -> Result<(Tensor, Tensor)> {
100+ self.0.forward_add(a, b)
101+ }
102+}
103+
104+// ─────────────────────────── primitive: Rope ───────────────────────────
105+
106+/// RoPE primitive — wraps the fused `rope_apply` kernel + the cos/sin tables, with
107+/// the per-token thread-local slice cache. Verbatim behavior from qwen2_q.rs.
108+pub struct Rope {
109+ sin: Tensor,
110+ cos: Tensor,
111+}
112+
113+thread_local! {
114+ /// Per-token cached RoPE cos/sin slice: (seqlen_offset, seq_len, cos, sin).
115+ static ROPE_SLICE_CACHE: std::cell::RefCell<Option<(usize, usize, Tensor, Tensor)>> =
116+ const { std::cell::RefCell::new(None) };
117+
118+ /// (layers_secs, head_secs, count) accumulated across profiled decode steps.
119+ static PROFILE_ACC: std::cell::RefCell<(f64, f64, usize)> =
120+ const { std::cell::RefCell::new((0.0, 0.0, 0)) };
121+}
122+
123+/// Print + reset the COCO_PROFILE accumulator (called from the bench harness).
124+pub fn profile_report() {
125+ PROFILE_ACC.with(|a| {
126+ let (l, h, n) = *a.borrow();
127+ if n > 0 {
128+ eprintln!(
129+ "PROFILE n={} | layers {:.3} ms/tok | norm+lm_head {:.3} ms/tok | total {:.3} ms/tok",
130+ n,
131+ l / n as f64 * 1e3,
132+ h / n as f64 * 1e3,
133+ (l + h) / n as f64 * 1e3,
134+ );
135+ }
136+ });
137+}
138+
139+impl Rope {
140+ pub fn new(dtype: DType, cfg: &CocoConfig, dev: &Device) -> Result<Self> {
141+ let dim = cfg.head_dim();
142+ let max_seq_len = cfg.max_position_embeddings;
143+ let inv_freq: Vec<_> = (0..dim)
144+ .step_by(2)
145+ .map(|i| 1f32 / cfg.rope_theta.powf(i as f64 / dim as f64) as f32)
146+ .collect();
147+ let inv_freq_len = inv_freq.len();
148+ let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?.to_dtype(dtype)?;
149+ let t = Tensor::arange(0u32, max_seq_len as u32, dev)?
150+ .to_dtype(dtype)?
151+ .reshape((max_seq_len, 1))?;
152+ let freqs = t.matmul(&inv_freq)?;
153+ Ok(Self {
154+ sin: freqs.sin()?,
155+ cos: freqs.cos()?,
156+ })
157+ }
158+
159+ pub fn apply(&self, q: &Tensor, k: &Tensor, seqlen_offset: usize) -> Result<(Tensor, Tensor)> {
160+ let (_b_sz, _h, seq_len, _n_embd) = q.dims4()?;
161+ let (cos, sin) = ROPE_SLICE_CACHE.with(|c| -> Result<(Tensor, Tensor)> {
162+ let mut c = c.borrow_mut();
163+ if let Some((off, len, cos, sin)) = c.as_ref() {
164+ if *off == seqlen_offset && *len == seq_len {
165+ return Ok((cos.clone(), sin.clone()));
166+ }
167+ }
168+ let cos = self.cos.narrow(0, seqlen_offset, seq_len)?;
169+ let sin = self.sin.narrow(0, seqlen_offset, seq_len)?;
170+ *c = Some((seqlen_offset, seq_len, cos.clone(), sin.clone()));
171+ Ok((cos, sin))
172+ })?;
173+ if std::env::var("COCO_NO_FUSE_ROPE").is_err()
174+ && matches!(q.device(), Device::Metal(_))
175+ && q.dtype() == DType::BF16
176+ {
177+ let q_embed = rope_apply(q, &cos, &sin)?;
178+ let k_embed = rope_apply(k, &cos, &sin)?;
179+ return Ok((q_embed, k_embed));
180+ }
181+ let q_embed = candle_nn::rotary_emb::rope(&q.contiguous()?, &cos, &sin)?;
182+ let k_embed = candle_nn::rotary_emb::rope(&k.contiguous()?, &cos, &sin)?;
183+ Ok((q_embed, k_embed))
184+ }
185+}
186+
187+// ─────────────────────────── primitive: SwiGlu (dense FFN) ───────────────────────────
188+
189+/// SwiGLU dense FFN primitive — gate/up fused as one QGroup, down as one Proj. The
190+/// fused-swiglu / ffn-mega / fallback paths are byte-identical to qwen2_q.rs's MLP.
191+pub struct SwiGlu {
192+ gate_up: QGroup,
193+ down_proj: Proj,
194+ act_fn: Activation,
195+}
196+
197+impl SwiGlu {
198+ pub fn new(src: &mut WeightSource, prefix: &str, cfg: &CocoConfig) -> Result<Self> {
199+ Ok(Self {
200+ gate_up: src.quant_group(&[
201+ (&format!("{prefix}.gate_proj"), false),
202+ (&format!("{prefix}.up_proj"), false),
203+ ])?,
204+ down_proj: src.proj(&format!("{prefix}.down_proj"), false)?,
205+ act_fn: cfg.hidden_act,
206+ })
207+ }
208+
209+ pub fn forward(&self, xs: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> {
210+ if let Proj::Quant(down) = &self.down_proj {
211+ if let Some(out) = self.gate_up.forward_ffn_mega(xs, down)? {
212+ return match resid {
213+ Some(r) => Ok((out + r)?),
214+ None => Ok(out),
215+ };
216+ }
217+ }
218+ let fuse = std::env::var("COCO_FUSE_SWIGLU").as_deref() != Ok("0");
219+ if fuse {
220+ if let Some(act) = self.gate_up.forward_swiglu(xs)? {
221+ return match resid {
222+ Some(r) => self.down_proj.forward_resid(&act, r),
223+ None => self.down_proj.forward(&act),
224+ };
225+ }
226+ }
227+ let mut gu = self.gate_up.forward(xs)?;
228+ let rhs = gu.pop().unwrap();
229+ let lhs = gu.pop().unwrap().apply(&self.act_fn)?;
230+ let act = (lhs * rhs)?;
231+ match resid {
232+ Some(r) => self.down_proj.forward_resid(&act, r),
233+ None => self.down_proj.forward(&act),
234+ }
235+ }
236+}
237+
238+// ─────────────────────────── primitive: MoeFfn (top-k MoE FFN) ───────────────────────────
239+
240+/// Top-k Mixture-of-Experts FFN (qwen3_moe / mixtral / glm4_moe). A DENSE fp16 router
241+/// `gate` [hidden, num_experts] (tiny — kept dense, not turboquant'd) selects the
242+/// top-`k` experts per token; each expert is a `SwiGlu` (per-expert gate/up = a QGroup,
243+/// down = a Proj, turboquant-compressed exactly like the dense FFN).
244+///
245+/// Forward matches candle `qwen3_moe.rs::Qwen3SparseMoeBlock` exactly:
246+/// logits = gate(x) [T, num_experts]
247+/// probs = softmax(logits, dim=experts)
248+/// idx = argsort(probs, desc)[..k] top-k expert ids [T, k]
249+/// weights = gather(probs, idx) [T, k]
250+/// if norm_topk_prob: weights /= sum_k(weights) renormalize the k
251+/// out[t] = Σ_{e in idx[t]} weights[t,e] · expert_e(x[t])
252+/// implemented via the same per-expert gather/scatter (index_select rows for each
253+/// expert, forward once, broadcast_mul the weight, index_add back).
254+pub struct MoeFfn {
255+ gate: candle_nn::Linear, // router — DENSE fp16, [hidden, num_experts], no bias
256+ experts: Vec<SwiGlu>,
257+ num_experts_per_tok: usize,
258+ norm_topk_prob: bool,
259+ /// DeepSeek-MoE: always-on shared experts summed (ungated) with the routed output.
260+ /// Empty for qwen3_moe (n_shared_experts absent) → behavior unchanged.
261+ shared_experts: Vec<SwiGlu>,
262+ /// DeepSeek-MoE: scalar applied to the routed-expert sum. 1.0 for qwen3_moe (and,
263+ /// per the oracle, only applied when `!norm_topk_prob`).
264+ routed_scaling_factor: f64,
265+}
266+
267+impl MoeFfn {
268+ pub fn new(
269+ src: &mut WeightSource,
270+ prefix: &str,
271+ cfg: &CocoConfig,
272+ norm_vb: &VarBuilder,
273+ ) -> Result<Self> {
274+ // Routed-expert count: qwen3_moe uses `num_experts`; DeepSeek-MoE uses
275+ // `n_routed_experts`. Exactly one is nonzero for a given arch.
276+ let n_routed = if cfg.arch == Arch::DeepSeekV2 {
277+ cfg.n_routed_experts
278+ } else {
279+ cfg.num_experts
280+ };
281+ // Router stays a dense fp16 linear read straight from the mmap'd VarBuilder.
282+ // Tensor name: model.layers.{L}.mlp.gate.weight (no bias).
283+ let gate = candle_nn::linear_no_bias(
284+ cfg.hidden_size,
285+ n_routed,
286+ norm_vb.pp(format!("{prefix}.gate")),
287+ )?;
288+ // Per-expert SwiGLU. gate_proj/up_proj = a QGroup, down_proj = a Proj — the
289+ // expert intermediate width is moe_intermediate_size (768 for Qwen3-30B-A3B,
290+ // 1408 for DeepSeek-V2-Lite), read from config by SwiGlu::new via the weight
291+ // shapes. Turboquant divisibility (inn % 128 == 0) is checked at encode time.
292+ let mut experts = Vec::with_capacity(n_routed);
293+ for i in 0..n_routed {
294+ experts.push(SwiGlu::new(src, &format!("{prefix}.experts.{i}"), cfg)?);
295+ }
296+
297+ // DeepSeek-MoE shared experts: a SINGLE always-on SwiGLU of intermediate width
298+ // `moe_intermediate_size * n_shared_experts` (per deepseek2.rs `Moe::new`),
299+ // summed ungated with the routed output. `SwiGlu::new` derives the (wide)
300+ // intermediate from the `{prefix}.shared_experts` weight shapes. Absent for
301+ // qwen3_moe → empty vec, behavior unchanged.
302+ let mut shared_experts = Vec::new();
303+ if cfg.arch == Arch::DeepSeekV2 && cfg.n_shared_experts.unwrap_or(0) > 0 {
304+ shared_experts.push(SwiGlu::new(src, &format!("{prefix}.shared_experts"), cfg)?);
305+ }
306+
307+ // routed_scaling_factor is a DeepSeek concept; qwen3_moe keeps 1.0.
308+ let routed_scaling_factor = if cfg.arch == Arch::DeepSeekV2 {
309+ cfg.routed_scaling_factor
310+ } else {
311+ 1.0
312+ };
313+
314+ Ok(Self {
315+ gate,
316+ experts,
317+ num_experts_per_tok: cfg.num_experts_per_tok,
318+ norm_topk_prob: cfg.norm_topk_prob,
319+ shared_experts,
320+ routed_scaling_factor,
321+ })
322+ }
323+
324+ fn forward(&self, xs: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> {
325+ let (b_size, seq_len, hidden_dim) = xs.dims3()?;
326+ let xs2d = xs.reshape(((), hidden_dim))?;
327+
328+ // Router: logits → softmax over experts. The router Linear weight is the model
329+ // dtype (BF16 on Metal); matmul it in that dtype, then cast to f32 for a stable
330+ // softmax/argsort/gather (candle's reference softmaxes then works in f32).
331+ let router_logits = self.gate.forward(&xs2d)?.to_dtype(DType::F32)?;
332+ let routing_weights = candle_nn::ops::softmax_last_dim(&router_logits)?;
333+
334+ // top-k: argsort descending, take the first k expert ids, gather their probs.
335+ let experts_per_tok = routing_weights
336+ .arg_sort_last_dim(false)?
337+ .narrow(D::Minus1, 0, self.num_experts_per_tok)?
338+ .contiguous()?;
339+ let topk_weights = routing_weights.gather(&experts_per_tok, D::Minus1)?;
340+
341+ let topk_weights = topk_weights.to_dtype(DType::F32)?.to_vec2::<f32>()?;
342+ let experts_per_tok = experts_per_tok.to_vec2::<u32>()?;
343+
344+ // Invert token→experts into expert→(rows, weights) for a single batched
345+ // forward per expert (matches candle's scatter loop exactly).
346+ let mut top_x = vec![vec![]; self.experts.len()];
347+ let mut selected_weights = vec![vec![]; self.experts.len()];
348+ for (row_idx, (rw, expert_idxs)) in
349+ topk_weights.iter().zip(experts_per_tok.iter()).enumerate()
350+ {
351+ let sum_rw = rw.iter().sum::<f32>();
352+ for (&w, &expert_idx) in rw.iter().zip(expert_idxs.iter()) {
353+ top_x[expert_idx as usize].push(row_idx as u32);
354+ // Oracle (deepseek2.rs MoeGate): renormalize when norm_topk_prob (and
355+ // top_k>1), else scale by routed_scaling_factor. Mutually exclusive.
356+ let w = if self.norm_topk_prob && self.num_experts_per_tok > 1 {
357+ w / sum_rw
358+ } else {
359+ w * self.routed_scaling_factor as f32
360+ };
361+ selected_weights[expert_idx as usize].push(w);
362+ }
363+ }
364+
365+ let mut ys = xs2d.zeros_like()?;
366+ for (expert_idx, expert) in self.experts.iter().enumerate() {
367+ let rows = &top_x[expert_idx];
368+ if rows.is_empty() {
369+ continue;
370+ }
371+ let rows_t = Tensor::new(rows.as_slice(), xs2d.device())?;
372+ let w_t = Tensor::new(selected_weights[expert_idx].as_slice(), xs2d.device())?
373+ .reshape(((), 1))?
374+ .to_dtype(xs2d.dtype())?;
375+ let cur = xs2d.index_select(&rows_t, 0)?;
376+ // Expert SwiGLU (no residual — the MoE weighted sum is accumulated below).
377+ let cur = expert.forward(&cur, None)?;
378+ let cur = cur.broadcast_mul(&w_t)?;
379+ ys = ys.index_add(&rows_t, &cur, 0)?;
380+ }
381+
382+ // DeepSeek-MoE: add the always-on shared experts (ungated) to the routed sum.
383+ // Runs on the ORIGINAL activation xs2d (the routed weighting is already folded
384+ // into `ys`). No-op for qwen3_moe (shared_experts empty).
385+ for shared in &self.shared_experts {
386+ ys = (ys + shared.forward(&xs2d, None)?)?;
387+ }
388+
389+ let out = ys.reshape((b_size, seq_len, hidden_dim))?;
390+ match resid {
391+ Some(r) => Ok((out + r)?),
392+ None => Ok(out),
393+ }
394+ }
395+}
396+
397+/// Feed-forward: dense SwiGLU or top-k MoE. Config-selected fixed primitive.
398+pub enum Ffn {
399+ Dense(SwiGlu),
400+ Moe(MoeFfn),
401+}
402+
403+impl Ffn {
404+ fn forward(&self, xs: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> {
405+ match self {
406+ Ffn::Dense(m) => m.forward(xs, resid),
407+ Ffn::Moe(m) => m.forward(xs, resid),
408+ }
409+ }
410+}
411+
412+// ─────────────────────────── mixer: GqaAttention ───────────────────────────
413+
414+/// GQA causal flash-decode attention (the first/only SequenceMixer). Contains the
415+/// persistent KvCache + the candle fallback, byte-identical to qwen2_q.rs's Attention.
416+pub struct GqaAttention {
417+ qkv: QGroup,
418+ o_proj: Proj,
419+ num_heads: usize,
420+ num_kv_heads: usize,
421+ num_kv_groups: usize,
422+ head_dim: usize,
423+ hidden_size: usize,
424+ rotary_emb: Arc<Rope>,
425+ /// qwen3 QK-norm: RmsNorm over head_dim applied to reshaped per-head q/k BEFORE
426+ /// rope. `None` for qwen2 (cfg.qk_norm == false) so that path is byte-identical.
427+ q_norm: Option<RmsNorm>,
428+ k_norm: Option<RmsNorm>,
429+ kv_cache: Option<(Tensor, Tensor)>,
430+ kv_fast: Option<KvCache>,
431+ fused: bool,
432+}
433+
434+impl GqaAttention {
435+ pub fn new(
436+ src: &mut WeightSource,
437+ prefix: &str,
438+ rotary_emb: Arc<Rope>,
439+ cfg: &CocoConfig,
440+ norm_vb: &VarBuilder,
441+ ) -> Result<Self> {
442+ let hidden_sz = cfg.hidden_size;
443+ let num_heads = cfg.num_attention_heads;
444+ let num_kv_heads = cfg.num_key_value_heads;
445+ let num_kv_groups = num_heads / num_kv_heads;
446+ let head_dim = cfg.head_dim();
447+ let bias = cfg.attn_bias;
448+
449+ // qwen3 QK-norm: an RmsNorm over head_dim on the reshaped per-head q & k,
450+ // applied BEFORE rope. Gated by cfg.qk_norm (false for qwen2 → None). Weights
451+ // are small fp16 norm vectors read from the mmap'd VarBuilder, not quantized.
452+ let (q_norm, k_norm) = if cfg.qk_norm {
453+ let q_w = norm_vb.pp(format!("{prefix}.q_norm")).get(head_dim, "weight")?;
454+ let k_w = norm_vb.pp(format!("{prefix}.k_norm")).get(head_dim, "weight")?;
455+ (
456+ Some(RmsNorm::new(q_w, cfg.rms_norm_eps)?),
457+ Some(RmsNorm::new(k_w, cfg.rms_norm_eps)?),
458+ )
459+ } else {
460+ (None, None)
461+ };
462+
463+ Ok(Self {
464+ qkv: src.quant_group(&[
465+ (&format!("{prefix}.q_proj"), bias),
466+ (&format!("{prefix}.k_proj"), bias),
467+ (&format!("{prefix}.v_proj"), bias),
468+ ])?,
469+ o_proj: src.proj(&format!("{prefix}.o_proj"), false)?,
470+ num_heads,
471+ num_kv_heads,
472+ num_kv_groups,
473+ head_dim,
474+ hidden_size: hidden_sz,
475+ rotary_emb,
476+ q_norm,
477+ k_norm,
478+ kv_cache: None,
479+ kv_fast: None,
480+ fused: fused_attn_enabled(),
481+ })
482+ }
483+
484+ #[allow(clippy::too_many_arguments)]
485+ fn candle_attention(
486+ &mut self,
487+ query_states: &Tensor,
488+ key_states: &Tensor,
489+ value_states: &Tensor,
490+ attention_mask: Option<&Tensor>,
491+ b_sz: usize,
492+ q_len: usize,
493+ resid: Option<&Tensor>,
494+ ) -> Result<Tensor> {
495+ let (key_states, value_states) = match &self.kv_cache {
496+ None => (key_states.clone(), value_states.clone()),
497+ Some((prev_k, prev_v)) => {
498+ let key_states = Tensor::cat(&[prev_k, key_states], 2)?;
499+ let value_states = Tensor::cat(&[prev_v, value_states], 2)?;
500+ (key_states, value_states)
501+ }
502+ };
503+ self.kv_cache = Some((key_states.clone(), value_states.clone()));
504+
505+ let key_states =
506+ candle_transformers::utils::repeat_kv(key_states, self.num_kv_groups)?.contiguous()?;
507+ let value_states =
508+ candle_transformers::utils::repeat_kv(value_states, self.num_kv_groups)?.contiguous()?;
509+
510+ let attn_output = {
511+ let scale = 1f64 / f64::sqrt(self.head_dim as f64);
512+ let attn_weights = (query_states.matmul(&key_states.transpose(2, 3)?)? * scale)?;
513+
514+ let attn_weights = match attention_mask {
515+ None => attn_weights,
516+ Some(mask) => attn_weights.broadcast_add(mask)?,
517+ };
518+ let attn_weights = candle_nn::ops::softmax_last_dim(&attn_weights)?;
519+ attn_weights.matmul(&value_states)?
520+ };
521+ // o_proj input width is n_heads*head_dim, which for qwen3 (16*128=2048) is NOT
522+ // hidden_size (1024) — reshape to the attention output width, not hidden_size.
523+ let attn_output = attn_output
524+ .transpose(1, 2)?
525+ .reshape((b_sz, q_len, self.num_heads * self.head_dim))?;
526+ match resid {
527+ Some(r) => self.o_proj.forward_resid(&attn_output, r),
528+ None => self.o_proj.forward(&attn_output),
529+ }
530+ }
531+}
532+
533+impl SequenceMixer for GqaAttention {
534+ fn forward(
535+ &mut self,
536+ xs: &Tensor,
537+ attention_mask: Option<&Tensor>,
538+ seqlen_offset: usize,
539+ resid: Option<&Tensor>,
540+ ) -> Result<Tensor> {
541+ let (b_sz, q_len, _) = xs.dims3()?;
542+
543+ let mut qkv = self.qkv.forward(xs)?;
544+ let value_states = qkv.pop().unwrap();
545+ let key_states = qkv.pop().unwrap();
546+ let query_states = qkv.pop().unwrap();
547+
548+ let query_states = query_states
549+ .reshape((b_sz, q_len, self.num_heads, self.head_dim))?
550+ .transpose(1, 2)?;
551+ let key_states = key_states
552+ .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))?
553+ .transpose(1, 2)?;
554+ let value_states = value_states
555+ .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))?
556+ .transpose(1, 2)?;
557+
558+ // qwen3 QK-norm: RmsNorm over head_dim on the per-head q & k, BEFORE rope.
559+ // No-op for qwen2 (q_norm/k_norm are None). COCO_NO_QK_NORM skips it (debug:
560+ // proves the primitive is live — a qwen3 model garbles without it).
561+ let (query_states, key_states) = if qk_norm_disabled() {
562+ (query_states, key_states)
563+ } else {
564+ // The reshaped q/k are non-contiguous (post-transpose); the RmsNorm reshape
565+ // needs contiguous input, so contiguify only when a norm actually applies.
566+ let query_states = match &self.q_norm {
567+ Some(qn) => qn.forward(&query_states.contiguous()?)?,
568+ None => query_states,
569+ };
570+ let key_states = match &self.k_norm {
571+ Some(kn) => kn.forward(&key_states.contiguous()?)?,
572+ None => key_states,
573+ };
574+ (query_states, key_states)
575+ };
576+
577+ let (query_states, key_states) =
578+ self.rotary_emb.apply(&query_states, &key_states, seqlen_offset)?;
579+
580+ if self.fused && b_sz == 1 {
581+ if self.kv_fast.is_none() {
582+ self.kv_fast = Some(KvCache::new(
583+ self.num_heads,
584+ self.num_kv_heads,
585+ self.head_dim,
586+ fused_max_ctx(),
587+ query_states.device(),
588+ )?);
589+ }
590+ let k_f = key_states.squeeze(0)?.contiguous()?;
591+ let v_f = value_states.squeeze(0)?.contiguous()?;
592+
593+ if q_len == 1 {
594+ let ctx_now = self.kv_fast.as_ref().unwrap().len();
595+ let k1 = k_f.squeeze(1)?;
596+ let v1 = v_f.squeeze(1)?;
597+ if ctx_now >= fused_min_ctx() {
598+ let kc = self.kv_fast.as_mut().unwrap();
599+ let q_f = query_states.squeeze(0)?.squeeze(1)?.contiguous()?;
600+ let attn = kc.decode(&q_f, &k1, &v1)?;
601+ let attn = attn.to_dtype(xs.dtype())?;
602+ return match resid {
603+ Some(r) => self.o_proj.forward_resid(&attn, r),
604+ None => self.o_proj.forward(&attn),
605+ };
606+ } else {
607+ self.kv_fast
608+ .as_mut()
609+ .unwrap()
610+ .append_prefill(&k1.unsqueeze(1)?, &v1.unsqueeze(1)?)?;
611+ return self.candle_attention(
612+ &query_states,
613+ &key_states,
614+ &value_states,
615+ attention_mask,
616+ b_sz,
617+ q_len,
618+ resid,
619+ );
620+ }
621+ } else {
622+ self.kv_fast.as_mut().unwrap().append_prefill(&k_f, &v_f)?;
623+ return self.candle_attention(
624+ &query_states,
625+ &key_states,
626+ &value_states,
627+ attention_mask,
628+ b_sz,
629+ q_len,
630+ resid,
631+ );
632+ }
633+ }
634+
635+ self.candle_attention(
636+ &query_states,
637+ &key_states,
638+ &value_states,
639+ attention_mask,
640+ b_sz,
641+ q_len,
642+ resid,
643+ )
644+ }
645+
646+ fn clear_cache(&mut self) {
647+ self.kv_cache = None;
648+ if let Some(kc) = self.kv_fast.as_mut() {
649+ kc.clear();
650+ }
651+ }
652+}
653+
654+// ─────────────────────────── mixer: MlaAttention (DeepSeek V2/V3) ───────────────────────────
655+
656+/// Decoupled-RoPE tables for MLA. Sized `qk_rope_head_dim` (64 on V2-Lite), applied
657+/// ONLY to the rope slices q_pe/k_pe. Ported verbatim from deepseek2.rs
658+/// `DeepSeekV2RotaryEmbedding`: plain freqs when no scaling, YaRN interpolation +
659+/// mscale sin/cos magnitude when `rope_scaling: yarn`. Uses candle `rope_i`
660+/// (interleaved) exactly like the oracle — NOT coco's NeoX `rope`.
661+pub struct MlaRope {
662+ sin: Tensor,
663+ cos: Tensor,
664+}
665+
666+impl MlaRope {
667+ pub fn new(dtype: DType, cfg: &CocoConfig, dev: &Device) -> Result<Self> {
668+ let dim = cfg.qk_rope_head_dim;
669+ let theta = cfg.rope_theta as f32;
670+ match &cfg.rope_scaling {
671+ Some(RopeScaling::Yarn {
672+ original_max_position_embeddings,
673+ beta_fast,
674+ beta_slow,
675+ mscale,
676+ mscale_all_dim,
677+ factor,
678+ ..
679+ }) => Self::new_yarn(
680+ dtype,
681+ dev,
682+ dim,
683+ theta,
684+ cfg.max_position_embeddings,
685+ *original_max_position_embeddings,
686+ *beta_fast,
687+ *beta_slow,
688+ *factor,
689+ *mscale,
690+ *mscale_all_dim,
691+ ),
692+ Some(RopeScaling::LinearOrDynamic { .. }) => {
693+ anyhow::bail!("MLA linear/dynamic rope scaling not implemented (only yarn)")
694+ }
695+ None => Self::new_unscaled(dtype, dev, dim, theta, cfg.max_position_embeddings),
696+ }
697+ }
698+
699+ fn new_unscaled(
700+ dtype: DType,
701+ dev: &Device,
702+ dim: usize,
703+ theta: f32,
704+ max_seq_len: usize,
705+ ) -> Result<Self> {
706+ let inv_freq: Vec<f32> = (0..dim)
707+ .step_by(2)
708+ .map(|i| 1f32 / theta.powf(i as f32 / dim as f32))
709+ .collect();
710+ let inv_freq_len = inv_freq.len();
711+ let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?;
712+ let t = Tensor::arange(0u32, max_seq_len as u32, dev)?
713+ .to_dtype(DType::F32)?
714+ .reshape((max_seq_len, 1))?;
715+ let freqs = t.matmul(&inv_freq)?;
716+ Ok(Self {
717+ sin: freqs.sin()?.to_dtype(dtype)?,
718+ cos: freqs.cos()?.to_dtype(dtype)?,
719+ })
720+ }
721+
722+ #[allow(clippy::too_many_arguments)]
723+ fn new_yarn(
724+ dtype: DType,
725+ dev: &Device,
726+ dim: usize,
727+ theta: f32,
728+ max_position_embeddings: usize,
729+ original_max_position_embeddings: usize,
730+ beta_fast: f32,
731+ beta_slow: f32,
732+ factor: f32,
733+ mscale: f32,
734+ mscale_all_dim: f32,
735+ ) -> Result<Self> {
736+ // freq_extra = un-interpolated (extrapolation) freqs; freq_inter = /factor.
737+ let freq_extra: Vec<f32> = (0..dim)
738+ .step_by(2)
739+ .map(|i| 1f32 / theta.powf(i as f32 / dim as f32))
740+ .collect();
741+ let freq_extra_len = freq_extra.len();
742+ let freq_extra = Tensor::from_vec(freq_extra, freq_extra_len, dev)?;
743+ let freq_inter: Vec<f32> = (0..dim)
744+ .step_by(2)
745+ .map(|i| 1f32 / (factor * theta.powf(i as f32 / dim as f32)))
746+ .collect();
747+ let freq_inter_len = freq_inter.len();
748+ let freq_inter = Tensor::from_vec(freq_inter, (1, freq_inter_len), dev)?;
749+
750+ let (low, high) = yarn_find_correction_range(
751+ beta_fast,
752+ beta_slow,
753+ dim,
754+ theta,
755+ original_max_position_embeddings,
756+ );
757+ let inv_freq_mask = (1.0 - yarn_linear_ramp_mask(low, high, dim / 2, dev)?)?;
758+ let inv_freq = freq_inter
759+ .broadcast_mul(&(1.0 - &inv_freq_mask)?)?
760+ .broadcast_add(&freq_extra.broadcast_mul(&inv_freq_mask)?)?;
761+
762+ let t = Tensor::arange(0u32, max_position_embeddings as u32, dev)?
763+ .to_dtype(DType::F32)?
764+ .reshape((max_position_embeddings, 1))?;
765+ let freqs = t.matmul(&inv_freq)?;
766+
767+ // sin/cos magnitude correction. On V2-Lite mscale==mscale_all_dim → 1.0.
768+ let mscale =
769+ yarn_get_mscale(factor, mscale) / yarn_get_mscale(factor, mscale_all_dim);
770+ let sin = (freqs.sin()? * mscale as f64)?.to_dtype(dtype)?;
771+ let cos = (freqs.cos()? * mscale as f64)?.to_dtype(dtype)?;
772+ Ok(Self { sin, cos })
773+ }
774+
775+ /// Apply interleaved rope to q_pe and k_pe (each `[b, heads_or_1, seq, rope_dim]`).
776+ /// Uses candle `rope_i` to match the oracle byte-for-byte.
777+ fn apply(&self, q: &Tensor, k: &Tensor, seqlen_offset: usize) -> Result<(Tensor, Tensor)> {
778+ let (_b, _h, seq_len, _d) = q.dims4()?;
779+ let cos = self.cos.narrow(0, seqlen_offset, seq_len)?;
780+ let sin = self.sin.narrow(0, seqlen_offset, seq_len)?;
781+ let q_embed = candle_nn::rotary_emb::rope_i(&q.contiguous()?, &cos, &sin)?;
782+ let k_embed = candle_nn::rotary_emb::rope_i(&k.contiguous()?, &cos, &sin)?;
783+ Ok((q_embed, k_embed))
784+ }
785+}
786+
787+// YaRN helpers — ported verbatim from deepseek2.rs.
788+fn yarn_find_correction_dim(num_rot: f32, dim: usize, base: f32, max_pos: usize) -> f32 {
789+ (dim as f32 * (max_pos as f32 / (num_rot * 2.0 * std::f32::consts::PI)).ln())
790+ / (2.0 * base.ln())
791+}
792+
793+fn yarn_find_correction_range(
794+ low_rot: f32,
795+ high_rot: f32,
796+ dim: usize,
797+ base: f32,
798+ max_pos: usize,
799+) -> (f32, f32) {
800+ let low = yarn_find_correction_dim(low_rot, dim, base, max_pos).floor();
801+ let high = yarn_find_correction_dim(high_rot, dim, base, max_pos).ceil();
802+ (low.max(0.0), high.min(dim as f32 - 1.0))
803+}
804+
805+fn yarn_linear_ramp_mask(min: f32, mut max: f32, dim: usize, dev: &Device) -> Result<Tensor> {
806+ if min == max {
807+ max += 0.001;
808+ }
809+ let linear_func =
810+ ((Tensor::arange(0f32, dim as f32, dev)? - min as f64)? / (max as f64 - min as f64))?;
811+ Ok(linear_func.clamp(0.0, 1.0)?)
812+}
813+
814+/// The optional compressed-Q latent path. `Plain` = direct q_proj (V2-Lite,
815+/// q_lora_rank=null); `Lora` = q_a_proj → q_a_layernorm → q_b_proj (full V2/V3).
816+/// Mirrors deepseek2.rs `QProj`.
817+enum QProj {
818+ Plain(Proj),
819+ Lora {
820+ a: Proj,
821+ norm: RmsNorm,
822+ b: Proj,
823+ },
824+}
825+
826+impl QProj {
827+ fn forward(&self, xs: &Tensor) -> Result<Tensor> {
828+ match self {
829+ QProj::Plain(lin) => lin.forward(xs),
830+ QProj::Lora { a, norm, b } => b.forward(&norm.forward(&a.forward(xs)?)?),
831+ }
832+ }
833+}
834+
835+/// Multi-head Latent Attention (DeepSeek V2/V3). Candle-fallback-first: ports
836+/// deepseek2.rs `Attention::forward` line-for-line onto coco's QLinear primitives.
837+///
838+/// Genuinely-new vs GqaAttention: asymmetric K(192)/V(128); a nope+rope head split
839+/// with rope on only a 64-dim slice; a single shared k_pe broadcast across all query
840+/// heads (MQA-style latent). The cache is a PEER `LatentKvCache` (candle
841+/// `Option<(Tensor,Tensor)>` cat-cache of the reconstructed per-head k[192]/v[128]);
842+/// the fused GQA `KvCache` is NOT allocated for this arch.
843+pub struct MlaAttention {
844+ q: QProj,
845+ kv_a_proj_with_mqa: Proj,
846+ kv_a_layernorm: RmsNorm,
847+ kv_b_proj: Proj,
848+ o_proj: Proj,
849+ rotary_emb: Arc<MlaRope>,
850+ num_heads: usize,
851+ q_head_dim: usize, // qk_nope + qk_rope (192)
852+ qk_nope_head_dim: usize, // 128
853+ qk_rope_head_dim: usize, // 64
854+ v_head_dim: usize, // 128
855+ kv_lora_rank: usize, // 512 (c_kv width == kv_a_layernorm length)
856+ softmax_scale: f64,
857+ /// Peer LatentKvCache (fallback form): reconstructed per-head k[192]/v[128], grown
858+ /// by Tensor::cat along seq — exactly GqaAttention::candle_attention's path. This
859+ /// is intentionally NOT the fused KvCache (asymmetric K/V, latent layout).
860+ kv_cache: Option<(Tensor, Tensor)>,
861+}
862+
863+impl MlaAttention {
864+ pub fn new(
865+ src: &mut WeightSource,
866+ prefix: &str,
867+ rotary_emb: Arc<MlaRope>,
868+ cfg: &CocoConfig,
869+ norm_vb: &VarBuilder,
870+ ) -> Result<Self> {
871+ let num_heads = cfg.num_attention_heads;
872+ let q_head_dim = cfg.mla_q_head_dim();
873+ let bias = cfg.attention_bias;
874+
875+ // Q path: Plain (q_proj) or Lora (q_a_proj → q_a_layernorm → q_b_proj).
876+ let q = match cfg.q_lora_rank {
877+ None => QProj::Plain(src.proj(&format!("{prefix}.q_proj"), bias)?),
878+ Some(lora_rank) => {
879+ let a = src.proj(&format!("{prefix}.q_a_proj"), bias)?;
880+ let norm_w = norm_vb
881+ .pp(format!("{prefix}.q_a_layernorm"))
882+ .get(lora_rank, "weight")?;
883+ let norm = RmsNorm::new(norm_w, cfg.rms_norm_eps)?;
884+ let b = src.proj(&format!("{prefix}.q_b_proj"), false)?;
885+ QProj::Lora { a, norm, b }
886+ }
887+ };
888+
889+ // kv_a_proj_with_mqa: hidden → kv_lora_rank + qk_rope_head_dim (576 on V2-Lite).
890+ let kv_a_proj_with_mqa = src.proj(&format!("{prefix}.kv_a_proj_with_mqa"), bias)?;
891+ let kv_a_norm_w = norm_vb
892+ .pp(format!("{prefix}.kv_a_layernorm"))
893+ .get(cfg.kv_lora_rank, "weight")?;
894+ let kv_a_layernorm = RmsNorm::new(kv_a_norm_w, cfg.rms_norm_eps)?;
895+ // kv_b_proj: kv_lora_rank → heads * (qk_nope + v_head_dim). No bias (oracle).
896+ let kv_b_proj = src.proj(&format!("{prefix}.kv_b_proj"), false)?;
897+ let o_proj = src.proj(&format!("{prefix}.o_proj"), bias)?;
898+
899+ Ok(Self {
900+ q,
901+ kv_a_proj_with_mqa,
902+ kv_a_layernorm,
903+ kv_b_proj,
904+ o_proj,
905+ rotary_emb,
906+ num_heads,
907+ q_head_dim,
908+ qk_nope_head_dim: cfg.qk_nope_head_dim,
909+ qk_rope_head_dim: cfg.qk_rope_head_dim,
910+ v_head_dim: cfg.v_head_dim,
911+ kv_lora_rank: cfg.kv_lora_rank,
912+ softmax_scale: cfg.mla_softmax_scale(),
913+ kv_cache: None,
914+ })
915+ }
916+}
917+
918+impl SequenceMixer for MlaAttention {
919+ fn forward(
920+ &mut self,
921+ xs: &Tensor,
922+ attention_mask: Option<&Tensor>,
923+ seqlen_offset: usize,
924+ resid: Option<&Tensor>,
925+ ) -> Result<Tensor> {
926+ let _ = fused_mla_enabled(); // fused Metal MLA is a later step; fallback always.
927+ let (bs, seq_len, _) = xs.dims3()?;
928+
929+ // 1. Q path → [bs, heads, seq, q_head_dim]; split nope[128] + pe[64].
930+ let q = self.q.forward(xs)?;
931+ let q = q
932+ .reshape((bs, seq_len, self.num_heads, self.q_head_dim))?
933+ .transpose(1, 2)?;
934+ let q_nope = q.narrow(D::Minus1, 0, self.qk_nope_head_dim)?;
935+ let q_pe = q.narrow(D::Minus1, self.qk_nope_head_dim, self.qk_rope_head_dim)?;
936+
937+ // 2. KV compression: compressed = kv_a_proj_with_mqa(x) → c_kv[512] + k_pe[64].
938+ let compressed_kv = self.kv_a_proj_with_mqa.forward(xs)?;
939+ let c_kv = compressed_kv.narrow(D::Minus1, 0, self.kv_lora_rank)?;
940+ let k_pe = compressed_kv.narrow(D::Minus1, self.kv_lora_rank, self.qk_rope_head_dim)?;
941+ // k_pe: one shared rope key → [bs, 1, seq, rope_dim].
942+ let k_pe = k_pe
943+ .reshape((bs, seq_len, 1, self.qk_rope_head_dim))?
944+ .transpose(1, 2)?;
945+
946+ // 3. Reconstruct: kv = kv_b_proj(kv_a_layernorm(c_kv)) → [bs, heads, seq, 256];
947+ // split k_nope[128] + v[128].
948+ let kv = self.kv_b_proj.forward(&self.kv_a_layernorm.forward(&c_kv)?)?;
949+ let kv = kv
950+ .reshape((
951+ bs,
952+ seq_len,
953+ self.num_heads,
954+ self.qk_nope_head_dim + self.v_head_dim,
955+ ))?
956+ .transpose(1, 2)?;
957+ let k_nope = kv.narrow(D::Minus1, 0, self.qk_nope_head_dim)?;
958+ let v = kv.narrow(D::Minus1, self.qk_nope_head_dim, self.v_head_dim)?;
959+
960+ // 4. Decoupled RoPE on q_pe and k_pe (64-dim slices only).
961+ let (q_pe, k_pe) = self.rotary_emb.apply(&q_pe, &k_pe, seqlen_offset)?;
962+
963+ // 5. Assemble q=cat(q_nope,q_pe)→192; k=cat(k_nope, broadcast(k_pe over heads))→192.
964+ let q = Tensor::cat(&[&q_nope.contiguous()?, &q_pe.contiguous()?], D::Minus1)?;
965+ let k_pe_b = k_pe.broadcast_as((bs, self.num_heads, seq_len, self.qk_rope_head_dim))?;
966+ let k = Tensor::cat(&[&k_nope.contiguous()?, &k_pe_b.contiguous()?], D::Minus1)?;
967+
968+ // 6. Grow the peer latent cache (reconstructed k[192]/v[128]) along seq.
969+ let (k, v) = match &self.kv_cache {
970+ None => (k, v),
971+ Some((prev_k, prev_v)) => {
972+ let k = Tensor::cat(&[prev_k, &k], 2)?;
973+ let v = Tensor::cat(&[prev_v, &v], 2)?;
974+ (k, v)
975+ }
976+ };
977+ self.kv_cache = Some((k.clone(), v.clone()));
978+
979+ // 7. Attend: softmax(q·kᵀ·scale + mask)·v → v_head_dim wide → o_proj.
980+ let att = (q.contiguous()?.matmul(&k.t()?.contiguous()?)? * self.softmax_scale)?;
981+ let att = match attention_mask {
982+ Some(mask) => att.broadcast_add(mask)?,
983+ None => att,
984+ };
985+ let att = candle_nn::ops::softmax_last_dim(&att)?;
986+ let ctx = att.matmul(&v.contiguous()?)?; // [bs, heads, seq, v_head_dim]
987+ let ctx = ctx
988+ .transpose(1, 2)?
989+ .reshape((bs, seq_len, self.num_heads * self.v_head_dim))?;
990+
991+ match resid {
992+ Some(r) => self.o_proj.forward_resid(&ctx, r),
993+ None => self.o_proj.forward(&ctx),
994+ }
995+ }
996+
997+ fn clear_cache(&mut self) {
998+ self.kv_cache = None;
999+ }
1000+}
1001+
1002+// ─────────────────────────── mixer: GatedDeltaNet (qwen3_5 linear-attn) ───────────────────────────
1003+
1004+/// GatedDeltaNet linear-attention mixer (qwen3_next / qwen3_5). Matrix-valued recurrent
1005+/// state (NOT masked softmax), validated bit-exact against the HF oracle in `bin/gdn_ref.rs`
1006+/// (max_abs_err 1.8e-7). Incremental: the per-layer `state` (S[nv,hk,hv] f32) + `conv_state`
1007+/// [conv_dim, k-1] carry across forward calls → constant memory regardless of context.
1008+pub struct GatedDeltaNet {
1009+ in_proj_qkvz: Proj,
1010+ in_proj_ba: Proj,
1011+ out_proj: Proj,
1012+ conv1d_w: Tensor, // [conv_dim, 1, k]
1013+ a_log: Tensor, // [nv]
1014+ dt_bias: Tensor, // [nv]
1015+ norm_w: Tensor, // [hv] (RMSNormGated)
1016+ hidden: usize,
1017+ nk: usize,
1018+ nv: usize,
1019+ hk: usize,
1020+ hv: usize,
1021+ ck: usize,
1022+ eps: f64,
1023+ state: Option<Tensor>, // S[nv,hk,hv] f32
1024+ conv_state: Option<Tensor>, // [conv_dim, ck-1] f32
1025+}
1026+
1027+impl GatedDeltaNet {
1028+ pub fn new(
1029+ src: &mut WeightSource,
1030+ prefix: &str,
1031+ cfg: &CocoConfig,
1032+ norm_vb: &VarBuilder,
1033+ ) -> Result<Self> {
1034+ let nk = cfg.linear_num_key_heads;
1035+ let nv = cfg.linear_num_value_heads;
1036+ let hk = cfg.linear_key_head_dim;
1037+ let hv = cfg.linear_value_head_dim;
1038+ let ck = cfg.linear_conv_kernel_dim;
1039+ let conv_dim = nk * hk * 2 + nv * hv; // key_dim*2 + value_dim
1040+ Ok(Self {
1041+ in_proj_qkvz: src.proj(&format!("{prefix}.in_proj_qkvz"), false)?,
1042+ in_proj_ba: src.proj(&format!("{prefix}.in_proj_ba"), false)?,
1043+ out_proj: src.proj(&format!("{prefix}.out_proj"), false)?,
1044+ conv1d_w: norm_vb.pp(format!("{prefix}.conv1d")).get((conv_dim, 1, ck), "weight")?,
1045+ a_log: norm_vb.pp(prefix).get(nv, "A_log")?,
1046+ dt_bias: norm_vb.pp(prefix).get(nv, "dt_bias")?,
1047+ norm_w: norm_vb.pp(format!("{prefix}.norm")).get(hv, "weight")?,
1048+ hidden: cfg.hidden_size,
1049+ nk,
1050+ nv,
1051+ hk,
1052+ hv,
1053+ ck,
1054+ eps: cfg.rms_norm_eps,
1055+ state: None,
1056+ conv_state: None,
1057+ })
1058+ }
1059+}
1060+
1061+fn gdn_silu(x: &Tensor) -> Result<Tensor> {
1062+ Ok((x * candle_nn::ops::sigmoid(x)?)?)
1063+}
1064+fn gdn_l2norm(x: &Tensor, eps: f64) -> Result<Tensor> {
1065+ let denom = (x.sqr()?.sum_keepdim(candle_core::D::Minus1)? + eps)?.sqrt()?;
1066+ Ok(x.broadcast_div(&denom)?)
1067+}
1068+
1069+impl SequenceMixer for GatedDeltaNet {
1070+ fn forward(
1071+ &mut self,
1072+ xs: &Tensor,
1073+ _attention_mask: Option<&Tensor>,
1074+ _seqlen_offset: usize,
1075+ resid: Option<&Tensor>,
1076+ ) -> Result<Tensor> {
1077+ use candle_core::{DType, IndexOp, D};
1078+ let (b_sz, q_len, _) = xs.dims3()?;
1079+ let dev = xs.device().clone();
1080+ let (nk, nv, hk, hv, ck) = (self.nk, self.nv, self.hk, self.hv, self.ck);
1081+ let (kd, vd, rep) = (nk * hk, nv * hv, nv / nk);
1082+ let conv_dim = kd + kd + vd;
1083+ let s = b_sz * q_len;
1084+
1085+ // 1. projections (f32 for the recurrence numerics)
1086+ let x = xs.reshape((s, self.hidden))?.to_dtype(DType::F32)?;
1087+ let qkvz = self.in_proj_qkvz.forward(&x)?.to_dtype(DType::F32)?;
1088+ let ba = self.in_proj_ba.forward(&x)?.to_dtype(DType::F32)?;
1089+
1090+ // 2. fix ordering
1091+ let qkvz = qkvz.reshape((s, nk, 2 * hk + 2 * hv * rep))?;
1092+ let q = qkvz.narrow(2, 0, hk)?.contiguous()?.reshape((s, kd))?;
1093+ let k = qkvz.narrow(2, hk, hk)?.contiguous()?.reshape((s, kd))?;
1094+ let v3 = qkvz.narrow(2, 2 * hk, rep * hv)?.reshape((s, vd))?;
1095+ let z = qkvz.narrow(2, 2 * hk + rep * hv, rep * hv)?.reshape((s, nv, hv))?;
1096+ let ba = ba.reshape((s, nk, 2 * rep))?;
1097+ let b = ba.narrow(2, 0, rep)?.reshape((s, nv))?;
1098+ let a = ba.narrow(2, rep, rep)?.reshape((s, nv))?;
1099+
1100+ // 3+4. conv (causal depthwise, k=4) continuing from cached conv_state, + silu
1101+ let mixed_t = Tensor::cat(&[&q, &k, &v3], 1)?.t()?.contiguous()?; // [conv_dim, s]
1102+ let prev = match &self.conv_state {
1103+ Some(cs) => cs.clone(),
1104+ None => Tensor::zeros((conv_dim, ck - 1), DType::F32, &dev)?,
1105+ };
1106+ let padded = Tensor::cat(&[&prev, &mixed_t], 1)?; // [conv_dim, ck-1+s]
1107+ let convd = padded
1108+ .unsqueeze(0)?
1109+ .conv1d(&self.conv1d_w, 0, 1, 1, conv_dim)?
1110+ .squeeze(0)?; // [conv_dim, s]
1111+ self.conv_state = Some(padded.narrow(1, padded.dim(1)? - (ck - 1), ck - 1)?.contiguous()?);
1112+ let mixed = gdn_silu(&convd)?.t()?.contiguous()?; // [s, conv_dim]
1113+
1114+ // 5. split; 6. beta,g; 7. repeat_interleave q,k
1115+ let q = mixed.narrow(1, 0, kd)?.reshape((s, nk, hk))?;
1116+ let k = mixed.narrow(1, kd, kd)?.reshape((s, nk, hk))?;
1117+ let v = mixed.narrow(1, 2 * kd, vd)?.reshape((s, nv, hv))?;
1118+ let beta = candle_nn::ops::sigmoid(&b)?;
1119+ let gate = softplus_pos(&a.broadcast_add(&self.dt_bias)?)?;
1120+ let gdecay = gate.broadcast_mul(&self.a_log.exp()?.neg()?)?; // [s,nv]
1121+ let ri = |t: &Tensor| -> Result<Tensor> {
1122+ Ok(t.reshape((s, nk, 1, hk))?
1123+ .broadcast_as((s, nk, rep, hk))?
1124+ .reshape((s, nv, hk))?)
1125+ };
1126+ let q = (gdn_l2norm(&ri(&q)?, 1e-6)? * (1.0 / (hk as f64).sqrt()))?;
1127+ let k = gdn_l2norm(&ri(&k)?, 1e-6)?;
1128+
1129+ // 8. recurrence continuing from cached S
1130+ let mut sstate = match &self.state {
1131+ Some(st) => st.clone(),
1132+ None => Tensor::zeros((nv, hk, hv), DType::F32, &dev)?,
1133+ };
1134+ let mut outs: Vec<Tensor> = Vec::with_capacity(s);
1135+ for i in 0..s {
1136+ let q_t = q.i(i)?;
1137+ let k_t = k.i(i)?;
1138+ let v_t = v.i(i)?;
1139+ let g_t = gdecay.i(i)?.exp()?.reshape((nv, 1, 1))?;
1140+ let beta_t = beta.i(i)?.reshape((nv, 1))?;
1141+ sstate = sstate.broadcast_mul(&g_t)?;
1142+ let k_col = k_t.reshape((nv, hk, 1))?;
1143+ let kv = sstate.broadcast_mul(&k_col)?.sum(1)?;
1144+ let delta = (v_t - kv)?.broadcast_mul(&beta_t)?;
1145+ sstate = (sstate + k_col.broadcast_mul(&delta.reshape((nv, 1, hv))?)?)?;
1146+ outs.push(sstate.broadcast_mul(&q_t.reshape((nv, hk, 1))?)?.sum(1)?.unsqueeze(0)?);
1147+ }
1148+ self.state = Some(sstate);
1149+ let out = Tensor::cat(&outs, 0)?; // [s,nv,hv]
1150+
1151+ // 9. RMSNormGated; 10. out_proj (+ resid)
1152+ let oc = out.reshape((s * nv, hv))?;
1153+ let zc = z.reshape((s * nv, hv))?;
1154+ let var = oc.sqr()?.mean_keepdim(D::Minus1)?;
1155+ let oc = oc.broadcast_div(&(var + self.eps)?.sqrt()?)?;
1156+ let oc = oc.broadcast_mul(&self.norm_w)?;
1157+ let oc = (oc * gdn_silu(&zc)?)?.reshape((b_sz, q_len, vd))?;
1158+ let oc = oc.to_dtype(xs.dtype())?;
1159+ match resid {
1160+ Some(r) => self.out_proj.forward_resid(&oc, r),
1161+ None => self.out_proj.forward(&oc),
1162+ }
1163+ }
1164+
1165+ fn clear_cache(&mut self) {
1166+ self.state = None;
1167+ self.conv_state = None;
1168+ }
1169+}
1170+
1171+fn softplus_pos(x: &Tensor) -> Result<Tensor> {
1172+ Ok(((x.exp()? + 1.0)?).log()?)
1173+}
1174+
1175+// ─────────────────────────── DecoderLayer (config-driven op-list) ───────────────────────────
1176+
1177+/// One decoder layer = the ordered op-list, driven by config not hard-coded. For
1178+/// qwen2 the optional sandwich norms are None and the ffn is Ffn::Dense(SwiGlu).
1179+pub struct DecoderLayer {
1180+ input_norm: RmsNorm,
1181+ mixer: Box<dyn SequenceMixer>,
1182+ post_attn_norm: Option<RmsNorm>,
1183+ pre_ffn_norm: RmsNorm,
1184+ ffn: Ffn,
1185+ post_ffn_norm: Option<RmsNorm>,
1186+}
1187+
1188+impl DecoderLayer {
1189+ fn new(
1190+ src: &mut WeightSource,
1191+ idx: usize,
1192+ rotary_emb: Arc<Rope>,
1193+ mla_rotary_emb: Option<&Arc<MlaRope>>,
1194+ cfg: &CocoConfig,
1195+ norm_vb: &VarBuilder,
1196+ ) -> Result<Self> {
1197+ let prefix = format!("model.layers.{idx}");
1198+ // Mixer: MLA for DeepSeek V2/V3, GQA (qwen2/qwen3/qwen3_moe) otherwise. Both
1199+ // implement the SAME SequenceMixer trait → no op-list change, cache stays
1200+ // hidden inside the mixer (MLA owns a peer LatentKvCache, not the fused KvCache).
1201+ let mixer: Box<dyn SequenceMixer> = if cfg.arch == Arch::DeepSeekV2 {
1202+ let mla_rope = mla_rotary_emb
1203+ .expect("MlaRope must be built for Arch::DeepSeekV2")
1204+ .clone();
1205+ Box::new(MlaAttention::new(
1206+ src,
1207+ &format!("{prefix}.self_attn"),
1208+ mla_rope,
1209+ cfg,
1210+ norm_vb,
1211+ )?)
1212+ } else {
1213+ Box::new(GqaAttention::new(
1214+ src,
1215+ &format!("{prefix}.self_attn"),
1216+ rotary_emb,
1217+ cfg,
1218+ norm_vb,
1219+ )?)
1220+ };
1221+ // Per-layer dense-vs-MoE. qwen3_moe: layers not in mlp_only_layers / not skipped
1222+ // by decoder_sparse_step. DeepSeek-MoE: first_k_dense_replace layers are dense,
1223+ // the rest MoE (deepseek_layer_is_moe). Dense archs always take SwiGLU. Same
1224+ // op-list, only the Ffn variant differs — the registry moat (design §1.2).
1225+ let is_moe = if cfg.arch == Arch::DeepSeekV2 {
1226+ cfg.deepseek_layer_is_moe(idx)
1227+ } else {
1228+ cfg.layer_is_moe(idx)
1229+ };
1230+ let ffn = if is_moe {
1231+ Ffn::Moe(MoeFfn::new(src, &format!("{prefix}.mlp"), cfg, norm_vb)?)
1232+ } else {
1233+ Ffn::Dense(SwiGlu::new(src, &format!("{prefix}.mlp"), cfg)?)
1234+ };
1235+ let input_norm = RmsNorm::new(
1236+ norm_vb
1237+ .pp(format!("model.layers.{idx}.input_layernorm"))
1238+ .get(cfg.hidden_size, "weight")?,
1239+ cfg.rms_norm_eps,
1240+ )?;
1241+ let pre_ffn_norm = RmsNorm::new(
1242+ norm_vb
1243+ .pp(format!("model.layers.{idx}.post_attention_layernorm"))
1244+ .get(cfg.hidden_size, "weight")?,
1245+ cfg.rms_norm_eps,
1246+ )?;
1247+ Ok(Self {
1248+ input_norm,
1249+ mixer,
1250+ post_attn_norm: None, // gemma3 sandwich norms land later
1251+ pre_ffn_norm,
1252+ ffn,
1253+ post_ffn_norm: None,
1254+ })
1255+ }
1256+
1257+ fn forward(
1258+ &mut self,
1259+ xs: &Tensor,
1260+ attention_mask: Option<&Tensor>,
1261+ seqlen_offset: usize,
1262+ ) -> Result<Tensor> {
1263+ let residual = xs;
1264+ let xs = self.input_norm.forward(xs)?;
1265+ if fuse_resid_enabled() {
1266+ let h = self
1267+ .mixer
1268+ .forward(&xs, attention_mask, seqlen_offset, Some(residual))?;
1269+ // post_attn_norm (sandwich) would go here for gemma3; None for qwen2.
1270+ let normed = self.pre_ffn_norm.forward(&h)?;
1271+ let out = self.ffn.forward(&normed, Some(&h))?;
1272+ // post_ffn_norm (sandwich) would go here for gemma3; None for qwen2.
1273+ return Ok(out);
1274+ }
1275+ let attn_out = self
1276+ .mixer
1277+ .forward(&xs, attention_mask, seqlen_offset, None)?;
1278+ let (h, normed) = self.pre_ffn_norm.forward_add(residual, &attn_out)?;
1279+ let xs2 = self.ffn.forward(&normed, None)?;
1280+ Ok((&h + xs2)?)
1281+ }
1282+
1283+ fn clear_kv_cache(&mut self) {
1284+ self.mixer.clear_cache();
1285+ let _ = &self.post_attn_norm;
1286+ let _ = &self.post_ffn_norm;
1287+ }
1288+}
1289+
1290+// ─────────────────────────── DenseDecoder (the qwen2/qwen3/llama/… wiring) ───────────────────────────
1291+
1292+/// The generic dense-FFN decoder wiring. qwen2/qwen3/llama/mistral/gemma3 all use
1293+/// this same op-list; only config flags differ. Step 0 registers qwen2 only.
1294+pub struct DenseDecoder {
1295+ embed_tokens: candle_nn::Embedding,
1296+ layers: Vec<DecoderLayer>,
1297+ norm: RmsNorm,
1298+ lm_head: Proj,
1299+ sliding_window: usize,
1300+ device: Device,
1301+ dtype: DType,
1302+}
1303+
1304+impl DenseDecoder {
1305+ pub fn new(cfg: &CocoConfig, mut src: WeightSource, vb: VarBuilder) -> Result<(Self, WeightStats)> {
1306+ let device = src.device.clone();
1307+ let dtype = src.dtype;
1308+ let vb_m = vb.pp("model");
1309+ let embed_tokens =
1310+ candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embed_tokens"))?;
1311+ let rotary_emb = Arc::new(Rope::new(dtype, cfg, &device)?);
1312+ // MLA decoupled-rope table (sized qk_rope_head_dim, YaRN-scaled) — built only
1313+ // for DeepSeek so other archs pay nothing. Shared Arc across all layers.
1314+ let mla_rotary_emb = if cfg.arch == Arch::DeepSeekV2 {
1315+ Some(Arc::new(MlaRope::new(dtype, cfg, &device)?))
1316+ } else {
1317+ None
1318+ };
1319+ let mut layers = Vec::with_capacity(cfg.num_hidden_layers);
1320+ for idx in 0..cfg.num_hidden_layers {
1321+ layers.push(DecoderLayer::new(
1322+ &mut src,
1323+ idx,
1324+ rotary_emb.clone(),
1325+ mla_rotary_emb.as_ref(),
1326+ cfg,
1327+ &vb,
1328+ )?);
1329+ }
1330+ let norm = RmsNorm::new(vb_m.pp("norm").get(cfg.hidden_size, "weight")?, cfg.rms_norm_eps)?;
1331+
1332+ // lm_head — identical logic to qwen2_q.rs::Model::new. Tied embeddings stay
1333+ // fp16; a separate head is optionally turboquant'd via COCO_QUANT_HEAD.
1334+ let head_separate = vb.contains_tensor("lm_head.weight");
1335+ let quant_head = matches!(std::env::var("COCO_QUANT_HEAD").as_deref(), Ok(v) if v != "0");
1336+ let lm_head = if !head_separate {
1337+ if quant_head {
1338+ eprintln!(
1339+ "COCO_QUANT_HEAD set but this model TIES lm_head to the embeddings \
1340+ (no separate lm_head.weight) — keeping the head fp16 to avoid \
1341+ double-quantizing the shared embedding matrix."
1342+ );
1343+ }
1344+ Proj::Dense(candle_nn::Linear::new(embed_tokens.embeddings().clone(), None))
1345+ } else if quant_head {
1346+ if matches!(std::env::var("COCO_QUANT_HEAD").as_deref(), Ok("8")) {
1347+ eprintln!(
1348+ "COCO_QUANT_HEAD=8 requested but the qmatvec kernel is 3-bit (8-level) \
1349+ only — a Q8 head is not wired; using the standard turboquant 3-bit head."
1350+ );
1351+ }
1352+ let (qw, comp, fp16) = src.quant_lm_head(&vb, cfg.vocab_size, cfg.hidden_size)?;
1353+ eprintln!(
1354+ "COCO_QUANT_HEAD: lm_head compressed {:.1} MB fp16 -> {:.1} MB (3-bit)",
1355+ fp16 as f64 / (1024.0 * 1024.0),
1356+ comp as f64 / (1024.0 * 1024.0),
1357+ );
1358+ Proj::Quant(qw)
1359+ } else {
1360+ Proj::Dense(candle_nn::linear_no_bias(
1361+ cfg.hidden_size,
1362+ cfg.vocab_size,
1363+ vb.pp("lm_head"),
1364+ )?)
1365+ };
1366+
1367+ let stats = src.stats();
1368+ Ok((
1369+ Self {
1370+ embed_tokens,
1371+ layers,
1372+ norm,
1373+ lm_head,
1374+ sliding_window: cfg.sliding_window,
1375+ device,
1376+ dtype,
1377+ },
1378+ stats,
1379+ ))
1380+ }
1381+
1382+ fn prepare_causal_attention_mask(
1383+ &self,
1384+ b_size: usize,
1385+ tgt_len: usize,
1386+ seqlen_offset: usize,
1387+ ) -> Result<Tensor> {
1388+ let mask: Vec<_> = (0..tgt_len)
1389+ .flat_map(|i| {
1390+ (0..tgt_len).map(move |j| {
1391+ if i < j || j + self.sliding_window < i {
1392+ f32::NEG_INFINITY
1393+ } else {
1394+ 0.
1395+ }
1396+ })
1397+ })
1398+ .collect();
1399+ let mask = Tensor::from_slice(&mask, (tgt_len, tgt_len), &self.device)?;
1400+ let mask = if seqlen_offset > 0 {
1401+ let mask0 = Tensor::zeros((tgt_len, seqlen_offset), DType::F32, &self.device)?;
1402+ Tensor::cat(&[&mask0, &mask], D::Minus1)?
1403+ } else {
1404+ mask
1405+ };
1406+ Ok(mask
1407+ .expand((b_size, 1, tgt_len, tgt_len + seqlen_offset))?
1408+ .to_dtype(self.dtype)?)
1409+ }
1410+}
1411+
1412+impl Model for DenseDecoder {
1413+ fn forward(&mut self, input_ids: &Tensor, seqlen_offset: usize) -> Result<Tensor> {
1414+ let (b_size, seq_len) = input_ids.dims2()?;
1415+ let attention_mask: Option<Tensor> = if seq_len <= 1 {
1416+ None
1417+ } else {
1418+ Some(self.prepare_causal_attention_mask(b_size, seq_len, seqlen_offset)?)
1419+ };
1420+ // COCO_PROFILE: sync-and-time the layers vs norm+lm_head phases of a single-
1421+ // token decode. Off by default (the syncs serialize the pipeline; profiling
1422+ // only) — so the gate path (COCO_PROFILE unset) is byte-identical to below.
1423+ let profile = seq_len == 1 && std::env::var("COCO_PROFILE").is_ok();
1424+ let mut xs = self.embed_tokens.forward(input_ids)?;
1425+ if profile {
1426+ self.device.synchronize()?;
1427+ let t = std::time::Instant::now();
1428+ for layer in self.layers.iter_mut() {
1429+ xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)?;
1430+ }
1431+ self.device.synchronize()?;
1432+ let t_layers = t.elapsed().as_secs_f64();
1433+ let t = std::time::Instant::now();
1434+ let xn = xs.narrow(1, seq_len - 1, 1)?;
1435+ let xn = self.norm.forward(&xn)?;
1436+ let out = self.lm_head.forward(&xn)?;
1437+ self.device.synchronize()?;
1438+ let t_head = t.elapsed().as_secs_f64();
1439+ PROFILE_ACC.with(|a| {
1440+ let mut a = a.borrow_mut();
1441+ a.0 += t_layers;
1442+ a.1 += t_head;
1443+ a.2 += 1;
1444+ });
1445+ return Ok(out);
1446+ }
1447+ for layer in self.layers.iter_mut() {
1448+ xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)?;
1449+ }
1450+ let xs = xs.narrow(1, seq_len - 1, 1)?;
1451+ let xs = self.norm.forward(&xs)?;
1452+ self.lm_head.forward(&xs)
1453+ }
1454+
1455+ fn clear_kv_cache(&mut self) {
1456+ for layer in self.layers.iter_mut() {
1457+ layer.clear_kv_cache()
1458+ }
1459+ }
1460+}
1461+
1462+// ─────────────────────────── the dispatcher ───────────────────────────
1463+
1464+/// config.json → Arch → assembled forward. The `match cfg.arch` IS the registry.
1465+/// Returns the boxed model + load-time weight stats (for the storage report).
1466+pub fn build_model(
1467+ cfg: &CocoConfig,
1468+ src: WeightSource,
1469+ vb: VarBuilder,
1470+) -> Result<(Box<dyn Model>, WeightStats)> {
1471+ match cfg.arch {
1472+ // qwen2 and qwen3 dense share the SAME DenseDecoder wiring — only config flags
1473+ // differ (qwen3: qk_norm=true, attn_bias=false, explicit head_dim). This IS the
1474+ // registry moat: a second architecture through one op-list, no new forward.
1475+ Arch::Qwen2 | Arch::Qwen3 => {
1476+ let (m, stats) = DenseDecoder::new(cfg, src, vb)?;
1477+ Ok((Box::new(m), stats))
1478+ }
1479+ // qwen3_moe = qwen3 attention (qk_norm GqaAttention, reused unchanged) with an
1480+ // Ffn::Moe per sparse layer. The SAME DenseDecoder/DecoderLayer op-list — the
1481+ // ONLY delta is the FFN variant, selected per layer inside DecoderLayer::new via
1482+ // cfg.layer_is_moe. No forked attention, no new kernel (design §3 Step 2).
1483+ Arch::Qwen3Moe => {
1484+ let (m, stats) = DenseDecoder::new(cfg, src, vb)?;
1485+ Ok((Box::new(m), stats))
1486+ }
1487+ // DeepSeek V2/V3: the SAME DenseDecoder/DecoderLayer op-list, but each layer's
1488+ // SequenceMixer is MlaAttention (built when cfg.arch == DeepSeekV2 inside
1489+ // DecoderLayer::new) and the FFN is DeepSeek-MoE (shared experts + dense prefix
1490+ // + routed scaling). No forked decoder; the fused Metal MLA kernel is gated
1491+ // behind COCO_FUSED_MLA (default = the candle fallback, always correct).
1492+ Arch::DeepSeekV2 => {
1493+ let (m, stats) = DenseDecoder::new(cfg, src, vb)?;
1494+ Ok((Box::new(m), stats))
1495+ }
1496+ // Qwen3.5: config parses + arch resolves (registry moat done), but the
1497+ // GatedDeltaNet linear-attn SequenceMixer + recurrent-state cache are not yet
1498+ // implemented. Report the parsed layer plan so the config path is provably wired.
1499+ Arch::Qwen35 => {
1500+ let n = cfg.num_hidden_layers;
1501+ let lin = (0..n).filter(|&i| cfg.layer_is_linear_attn(i)).count();
1502+ anyhow::bail!(
1503+ "Qwen3.5 recognized + config parsed: {n} layers = {lin} GatedDeltaNet (linear-attn) \
1504+ + {} full-attn GQA; head_dim={}, linear_k_heads={} linear_v_heads={} conv_k={}, \
1505+ partial_rope={}. GatedDeltaNet SequenceMixer not yet implemented (TRENDING_ARCH_DESIGN.md §1.3).",
1506+ n - lin, cfg.head_dim(), cfg.linear_num_key_heads, cfg.linear_num_value_heads,
1507+ cfg.linear_conv_kernel_dim, cfg.partial_rotary_factor,
1508+ )
1509+ }
1510+ }
1511+}
added src/qlinear.rs +4102 −0
@@ -0,0 +1,4102 @@
1+// coco turboquant-fast — keep weights COMPRESSED in RAM, matmul reads them packed.
2+//
3+// The activation-rotation trick (this is what makes it fast):
4+// turboquant stores the ROTATED quantized weight Wr (3-bit codes + per-block
5+// fp16 radius + a seeded ±1 sign + per-d-block FWHT). The real weight is
6+// W = unrotate(Wr). For a linear y = x @ Wᵀ, because the rotation R is
7+// orthonormal and block-local:
8+// ⟨x, unrotate(w)⟩ = ⟨rotate(x), w_rotated⟩
9+// So we rotate the ACTIVATION x once per token (sign-flip + per-d-block FWHT,
10+// O(inn·log d), cheap) → xr, then matmul xr against the COMPRESSED rotated
11+// codes Wr directly. W is NEVER dequantized to fp16. The matmul reads ~4
12+// bits/weight (codes packed two-per-byte) instead of 16 → fewer bytes/token.
13+//
14+// Two Metal kernels, both written here as raw MSL and JIT-compiled via candle's
15+// objc2-metal device handle (candle 0.11 exposes it through MetalDevice):
16+// 1. tq_rotate_f32 — rotate the activation in place on the GPU (sign-flip +
17+// block-diagonal FWHT). x never leaves the GPU.
18+// 2. tq_qmatvec_f32 — quantized mat·vec/mat: for each output o (and token t),
19+// accumulate xr[t,k] * codebook[code(o,k)] * radius(o,k), reconstructing
20+// each weight on the fly from the packed nibble codes + fp16 radius.
21+//
22+// Activations stay f32 in this path (Qwen's hidden state is tiny; the win is in
23+// the weight bytes). Only block-Hadamard, outlier-frac 0 weights are supported
24+// (clean 3-bit codes, inn % d == 0, no sparse outlier side-list) — that is the
25+// `turboquant-block --outlier-frac 0` recipe, 3.125 bpw, validated coherent.
26+
27+use anyhow::{anyhow, Result};
28+use candle_core::backend::BackendStorage;
29+use candle_core::{CpuStorage, CustomOp1, DType, Device, Layout, Shape, Tensor};
30+use candle_metal_kernels::metal::{Buffer, ComputeCommandEncoder, ComputePipeline};
31+use std::sync::{Arc, Mutex, OnceLock};
32+
33+use crate::turboquant::{self, TqWeight};
34+
35+// ───────────────────────── Metal kernel source (MSL) ─────────────────────────
36+
37+const KERNEL_SRC: &str = r#"
38+#include <metal_stdlib>
39+using namespace metal;
40+
41+// Rotate the activation out-of-place: xr = blockFWHT(x ∘ sgn), per d-wide block.
42+// Reads x, writes xr — no separate blit copy needed. One threadgroup per
43+// (block, token); `d` threads cooperate via threadgroup memory.
44+// grid (threadgroups) = (1, nblocks, tokens) ; tgroup = (d, 1, 1)
45+kernel void tq_rotate_f32(
46+ device const float* x [[buffer(0)]], // [tokens, inn]
47+ device float* xr [[buffer(1)]], // [tokens, inn] (output)
48+ device const float* sgn [[buffer(2)]], // [inn] (±1), tiled over blocks
49+ constant uint& inn [[buffer(3)]],
50+ constant uint& d [[buffer(4)]],
51+ uint3 tg [[threadgroup_position_in_grid]],
52+ uint3 lt [[thread_position_in_threadgroup]])
53+{
54+ threadgroup float buf[1024]; // d <= 1024
55+ uint blk = tg.y; // which d-block
56+ uint tok = tg.z; // which token row
57+ uint j = lt.x; // coord within the block
58+ if (j >= d) return;
59+
60+ uint col = blk * d + j; // column within the row
61+ uint idx = tok * inn + col;
62+ // sign-flip on load, keep the working value in a register
63+ float v = x[idx] * sgn[col];
64+
65+ // Stages with stride h < 32 live entirely within a SIMD-group: use
66+ // simd_shuffle_xor (no threadgroup barrier). For d=128 that's h=1..16.
67+ for (uint h = 1; h < 32u && h < d; h <<= 1) {
68+ float partner = simd_shuffle_xor(v, h);
69+ v = ((j & h) == 0) ? (v + partner) : (partner - v);
70+ }
71+ // Stages with stride h >= 32 cross SIMD-groups: round-trip via threadgroup
72+ // memory with a barrier. For d=128 that's h=32 and h=64 (2 barriers).
73+ for (uint h = 32u; h < d; h <<= 1) {
74+ buf[j] = v;
75+ threadgroup_barrier(mem_flags::mem_threadgroup);
76+ float partner = buf[j ^ h];
77+ threadgroup_barrier(mem_flags::mem_threadgroup);
78+ v = ((j & h) == 0) ? (v + partner) : (partner - v);
79+ }
80+ // orthonormal scale 1/sqrt(d)
81+ xr[idx] = v * rsqrt((float)d);
82+}
83+
84+// BF16-INPUT rotate: identical to tq_rotate_f32 but reads the activation as
85+// `bfloat` (the model's hidden-state dtype) and converts to f32 on load. This
86+// lets the model feed the post-norm hidden DIRECTLY into the rotate, eliminating
87+// candle's separate `to_dtype(F32)` (a full elementwise dispatch) + the
88+// `contiguous` copy that preceded every rotate. Output stays f32 (xr feeds the
89+// qmatvec, which wants f32).
90+kernel void tq_rotate_bf16(
91+ device const bfloat* x [[buffer(0)]], // [tokens, inn] bf16
92+ device float* xr [[buffer(1)]], // [tokens, inn] f32 (output)
93+ device const float* sgn [[buffer(2)]], // [inn] (±1), tiled over blocks
94+ constant uint& inn [[buffer(3)]],
95+ constant uint& d [[buffer(4)]],
96+ uint3 tg [[threadgroup_position_in_grid]],
97+ uint3 lt [[thread_position_in_threadgroup]])
98+{
99+ threadgroup float buf[1024];
100+ uint blk = tg.y;
101+ uint tok = tg.z;
102+ uint j = lt.x;
103+ if (j >= d) return;
104+
105+ uint col = blk * d + j;
106+ uint idx = tok * inn + col;
107+ float v = (float)x[idx] * sgn[col];
108+
109+ for (uint h = 1; h < 32u && h < d; h <<= 1) {
110+ float partner = simd_shuffle_xor(v, h);
111+ v = ((j & h) == 0) ? (v + partner) : (partner - v);
112+ }
113+ for (uint h = 32u; h < d; h <<= 1) {
114+ buf[j] = v;
115+ threadgroup_barrier(mem_flags::mem_threadgroup);
116+ float partner = buf[j ^ h];
117+ threadgroup_barrier(mem_flags::mem_threadgroup);
118+ v = ((j & h) == 0) ? (v + partner) : (partner - v);
119+ }
120+ xr[idx] = v * rsqrt((float)d);
121+}
122+
123+// Fused RoPE (GPT-NeoX "rotate-half" convention, matching candle_nn::rotary_emb::rope).
124+// Reads q/k DIRECTLY from their transposed [b,h,t,d] VIEW (arbitrary strides) and
125+// writes a CONTIGUOUS [b,h,t,d] output — folding candle's `.contiguous()` blit copy
126+// AND the separate rope dispatch into ONE pass. The qkv projection produces
127+// [b,t,h*d] which is reshaped+transposed to [b,h,t,d] (non-contiguous); candle's
128+// rope rejects non-contiguous input, so the old path paid a full elementwise copy
129+// per q and per k every token. Here we index the source via its real strides.
130+//
131+// cos/sin are [t, d/2] contiguous (cos[i_t*(d/2)+i_d]). For each (b,h,t,i_d<d/2):
132+// o1 = src1*cos - src2*sin ; o2 = src1*sin + src2*cos
133+// where src1 = x[.., i_d], src2 = x[.., i_d + d/2]. Output is dense row-major.
134+// grid = (d/2, t, b*h) ; tgroup = (d/2,1,1) (d/2 <= 128 here)
135+kernel void tq_rope_bf16(
136+ device const bfloat* x [[buffer(0)]], // [b,h,t,d] strided view, bf16
137+ device bfloat* out [[buffer(1)]], // [b,h,t,d] CONTIGUOUS, bf16 (output)
138+ device const bfloat* cos [[buffer(2)]], // [t, d/2] contiguous, bf16
139+ device const bfloat* sin [[buffer(3)]], // [t, d/2] contiguous, bf16
140+ constant uint& h [[buffer(4)]], // n heads (this tensor's)
141+ constant uint& t_len [[buffer(5)]], // seq length
142+ constant uint& d [[buffer(6)]], // head_dim
143+ constant int4& strides [[buffer(7)]], // (sb, sh, st, sd) of the input view
144+ uint3 gid [[thread_position_in_grid]])
145+{
146+ uint i_d = gid.x; // coord within first half [0, d/2)
147+ uint i_t = gid.y; // position
148+ uint bh = gid.z; // batch*head flattened
149+ if (i_d >= (d >> 1) || i_t >= t_len) return;
150+ uint b_i = bh / h;
151+ uint h_i = bh % h;
152+
153+ // Source element offsets via the input view's strides (elements, not bytes).
154+ long base = (long)b_i * strides.x + (long)h_i * strides.y + (long)i_t * strides.z;
155+ long o1s = base + (long)i_d * strides.w;
156+ long o2s = base + (long)(i_d + (d >> 1)) * strides.w;
157+ float s1 = (float)x[o1s];
158+ float s2 = (float)x[o2s];
159+
160+ uint i_cs = i_t * (d >> 1) + i_d;
161+ float c = (float)cos[i_cs];
162+ float s = (float)sin[i_cs];
163+
164+ // Contiguous [b,h,t,d] output.
165+ ulong dbase = (((ulong)bh) * t_len + i_t) * d;
166+ out[dbase + i_d] = (bfloat)(s1 * c - s2 * s);
167+ out[dbase + i_d + (d>>1)] = (bfloat)(s1 * s + s2 * c);
168+}
169+
170+// Quantized mat·mat: y[t,o] = sum_k xr[t,k] * codebook[code(o,k)] * radius(o,k).
171+// One SIMD-group (32 lanes) cooperates on ONE output row: each lane strides over
172+// k in steps of 32, so the 32 lanes read 32 CONSECUTIVE packed bytes per step
173+// (coalesced), then a simd_sum reduces the partial dot products. Codes are
174+// packed two-per-byte (low nibble = even k); each lane consumes one byte = two
175+// adjacent k. radius is fp16, one per d coords of the row-major (out*inn) grid.
176+//
177+// dispatch: grid = (out*32, tokens), threadgroup width = SIMDW * rows_per_tg.
178+kernel void tq_qmatvec_f32(
179+ device const float* xr [[buffer(0)]], // [tokens, inn] (already rotated)
180+ device const uchar* codes [[buffer(1)]], // packed nibbles, len = out*inn/2
181+ device const half* radius [[buffer(2)]], // [out*inn/d]
182+ constant float* codebook [[buffer(3)]], // 8 levels
183+ device float* y [[buffer(4)]], // [tokens, out]
184+ constant uint& inn [[buffer(5)]],
185+ constant uint& out_dim [[buffer(6)]],
186+ constant uint& d [[buffer(7)]],
187+ constant uint& tokens [[buffer(8)]],
188+ uint2 gid [[thread_position_in_grid]])
189+{
190+ const uint SIMDW = 32;
191+ uint t = gid.y; // token
192+ uint o = gid.x / SIMDW; // output row this simd-group owns
193+ uint lane = gid.x % SIMDW;
194+ if (o >= out_dim || t >= tokens) return;
195+
196+ float cb[8];
197+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i];
198+
199+ device const float* xrow = xr + (ulong)t * inn;
200+ ulong base_pk = ((ulong)o * inn) >> 1; // packed-byte base (4-aligned)
201+ ulong rbase = ((ulong)o * inn) / d; // radius block base for this row
202+
203+ // Read 4 packed bytes (8 weights) per load as a uint → wide coalesced loads.
204+ // base_pk is a multiple of 4 for all rows (o*inn/2, inn%8==0), so the uint
205+ // view is aligned. nwords = npk/4 = inn/8 words per row.
206+ device const uint* codes32 = (device const uint*)(codes + base_pk);
207+ uint nwords = inn >> 3; // packed uints per row
208+
209+ // d (128) is a power of two; one radius block = d coords = d/8 uint-words.
210+ // wshift = log2(d/8). All 8 weights in a uint-word share a d-block when
211+ // d>=8 and inn%d==0 (true here), so ONE radius lookup per word.
212+ uint wshift = (uint)log2((float)(d >> 3)); // words per radius block
213+
214+ float acc = 0.0f;
215+ for (uint w = lane; w < nwords; w += SIMDW) {
216+ uint packed = codes32[w];
217+ uint k0 = w << 3; // first weight index of this word
218+ float r = (float)radius[rbase + (w >> wshift)];
219+ // 8 nibbles, low-to-high = k0..k0+7
220+ acc += xrow[k0 + 0] * cb[(packed >> 0) & 0xF] * r;
221+ acc += xrow[k0 + 1] * cb[(packed >> 4) & 0xF] * r;
222+ acc += xrow[k0 + 2] * cb[(packed >> 8) & 0xF] * r;
223+ acc += xrow[k0 + 3] * cb[(packed >> 12) & 0xF] * r;
224+ acc += xrow[k0 + 4] * cb[(packed >> 16) & 0xF] * r;
225+ acc += xrow[k0 + 5] * cb[(packed >> 20) & 0xF] * r;
226+ acc += xrow[k0 + 6] * cb[(packed >> 24) & 0xF] * r;
227+ acc += xrow[k0 + 7] * cb[(packed >> 28) & 0xF] * r;
228+ }
229+ // reduce the 32 partial sums across the simd-group
230+ acc = simd_sum(acc);
231+ if (lane == 0) {
232+ y[(ulong)t * out_dim + o] = acc;
233+ }
234+}
235+
236+// TRUE 3-bit variant: codes packed 8-per-3-bytes (24-bit little-endian octet,
237+// code j at bits 3j..3j+3). 3.125 bpw vs the nibble path's 4.125 → 488 MB vs
238+// 644 MB resident (24% less weight memory). Same SIMD-group-per-row structure as
239+// the nibble kernel: each lane owns octets at stride 32 (8 consecutive k), so the
240+// 32 lanes read 32 consecutive 3-byte octets per step. One radius lookup/octet.
241+//
242+// NOTE (measured): this variant is correct (≤1e-6 vs the nibble kernel) and
243+// halves-then-some the weight bytes, but at 1.5B it does NOT raise throughput —
244+// the qmatvec path is decode/dispatch-bound, not weight-bandwidth-bound, and the
245+// 3-byte (unaligned) reads + extra unpacking exactly offset the bandwidth saving.
246+// So 4-bit nibble is the default fast path; pick 3-bit (COCO_PACK_BITS=3) when
247+// resident RAM matters more than the last ~0 tok/s.
248+kernel void tq_qmatvec3_f32(
249+ device const float* xr [[buffer(0)]], // [tokens, inn] (already rotated)
250+ device const uchar* codes [[buffer(1)]], // 3-bit stream, len = out*inn/8*3
251+ device const half* radius [[buffer(2)]], // [out*inn/d]
252+ constant float* codebook [[buffer(3)]], // 8 levels
253+ device float* y [[buffer(4)]], // [tokens, out]
254+ constant uint& inn [[buffer(5)]],
255+ constant uint& out_dim [[buffer(6)]],
256+ constant uint& d [[buffer(7)]],
257+ constant uint& tokens [[buffer(8)]],
258+ uint2 gid [[thread_position_in_grid]])
259+{
260+ const uint SIMDW = 32;
261+ uint t = gid.y; // token
262+ uint o = gid.x / SIMDW; // output row this simd-group owns
263+ uint lane = gid.x % SIMDW;
264+ if (o >= out_dim || t >= tokens) return;
265+
266+ float cb[8];
267+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i];
268+
269+ device const float* xrow = xr + (ulong)t * inn;
270+ ulong base_b = ((ulong)o * inn / 8) * 3; // 3 bytes per 8-code octet
271+ device const uchar* crow = codes + base_b;
272+ ulong rbase = ((ulong)o * inn) / d;
273+ uint noctet = inn >> 3;
274+ uint gshift = (uint)log2((float)(d >> 3)); // octets per radius block
275+
276+ float acc = 0.0f;
277+ for (uint g = lane; g < noctet; g += SIMDW) {
278+ uint bb = g * 3;
279+ uint v = (uint)crow[bb] | ((uint)crow[bb + 1] << 8) | ((uint)crow[bb + 2] << 16);
280+ uint k0 = g << 3;
281+ float r = (float)radius[rbase + (g >> gshift)];
282+ acc += xrow[k0 + 0] * cb[(v >> 0) & 0x7] * r;
283+ acc += xrow[k0 + 1] * cb[(v >> 3) & 0x7] * r;
284+ acc += xrow[k0 + 2] * cb[(v >> 6) & 0x7] * r;
285+ acc += xrow[k0 + 3] * cb[(v >> 9) & 0x7] * r;
286+ acc += xrow[k0 + 4] * cb[(v >> 12) & 0x7] * r;
287+ acc += xrow[k0 + 5] * cb[(v >> 15) & 0x7] * r;
288+ acc += xrow[k0 + 6] * cb[(v >> 18) & 0x7] * r;
289+ acc += xrow[k0 + 7] * cb[(v >> 21) & 0x7] * r;
290+ }
291+ acc = simd_sum(acc);
292+ if (lane == 0) {
293+ y[(ulong)t * out_dim + o] = acc;
294+ }
295+}
296+
297+// ───────── FUSED EPILOGUE variants (bf16 out + in-kernel bias) ─────────
298+// Same dot-product core as the *_f32 kernels above, but the simd-leader writes the
299+// result DIRECTLY as the model dtype (bf16) and adds the per-row bias IN the
300+// kernel. This folds candle's separate `to_dtype(bf16)` dispatch + N
301+// `broadcast_add(bias)` dispatches into the qmatvec epilogue — one fewer full
302+// elementwise pass over the output per projection group (and the bias add is free,
303+// piggy-backing on the simd-leader's single store). `bias` is a real per-row
304+// buffer (length out_dim, zeros where a projection has none); `has_bias` gates it
305+// so a null/dummy bind is never dereferenced. We accumulate in f32 (full
306+// precision) and round once at the store.
307+//
308+// RESIDUAL epilogue (COCO_FUSE_RESID, default on): buffers 11/12 optionally add a
309+// per-element residual at the same leader store — y[t,o] = dot + bias + resid[t,o].
310+// This is the attention/MLP twin of the SwiGLU fuse: the o_proj and down_proj
311+// qmatvecs are each followed by a residual add on a hidden-width tensor; folding
312+// it into the store epilogue kills the standalone candle elementwise add dispatch
313+// (+ its barrier) after down_proj, and on the o_proj side replaces the two-output
314+// fused add+norm with (epilogue-add → plain norm). The add is done in f32 before
315+// the single bf16 rounding (the launch grid is untouched — epilogue-only fuse).
316+
317+kernel void tq_qmatvec3_bf16(
318+ device const float* xr [[buffer(0)]], // [tokens, inn] rotated f32
319+ device const uchar* codes [[buffer(1)]], // 3-bit stream
320+ device const half* radius [[buffer(2)]], // [out*inn/d]
321+ constant float* codebook [[buffer(3)]], // 8 levels
322+ device bfloat* y [[buffer(4)]], // [tokens, out] bf16 (output)
323+ constant uint& inn [[buffer(5)]],
324+ constant uint& out_dim [[buffer(6)]],
325+ constant uint& d [[buffer(7)]],
326+ constant uint& tokens [[buffer(8)]],
327+ device const ushort* bias [[buffer(9)]], // [out_dim] bf16 bits (per-row)
328+ constant uint& has_bias [[buffer(10)]],
329+ device const bfloat* resid [[buffer(11)]], // [tokens, out_dim] residual
330+ constant uint& has_resid [[buffer(12)]],
331+ uint2 gid [[thread_position_in_grid]])
332+{
333+ const uint SIMDW = 32;
334+ uint t = gid.y;
335+ uint o = gid.x / SIMDW;
336+ uint lane = gid.x % SIMDW;
337+ if (o >= out_dim || t >= tokens) return;
338+
339+ float cb[8];
340+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i];
341+
342+ device const float* xrow = xr + (ulong)t * inn;
343+ ulong base_b = ((ulong)o * inn / 8) * 3;
344+ device const uchar* crow = codes + base_b;
345+ ulong rbase = ((ulong)o * inn) / d;
346+ uint noctet = inn >> 3;
347+ uint gshift = (uint)log2((float)(d >> 3));
348+
349+ float acc = 0.0f;
350+ for (uint g = lane; g < noctet; g += SIMDW) {
351+ uint bb = g * 3;
352+ uint v = (uint)crow[bb] | ((uint)crow[bb + 1] << 8) | ((uint)crow[bb + 2] << 16);
353+ uint k0 = g << 3;
354+ float r = (float)radius[rbase + (g >> gshift)];
355+ float part = xrow[k0 + 0] * cb[(v >> 0) & 0x7];
356+ part += xrow[k0 + 1] * cb[(v >> 3) & 0x7];
357+ part += xrow[k0 + 2] * cb[(v >> 6) & 0x7];
358+ part += xrow[k0 + 3] * cb[(v >> 9) & 0x7];
359+ part += xrow[k0 + 4] * cb[(v >> 12) & 0x7];
360+ part += xrow[k0 + 5] * cb[(v >> 15) & 0x7];
361+ part += xrow[k0 + 6] * cb[(v >> 18) & 0x7];
362+ part += xrow[k0 + 7] * cb[(v >> 21) & 0x7];
363+ acc += part * r;
364+ }
365+ acc = simd_sum(acc);
366+ if (lane == 0) {
367+ if (has_bias) acc += (float)as_type<bfloat>(bias[o]);
368+ if (has_resid) acc += (float)resid[(ulong)t * out_dim + o];
369+ y[(ulong)t * out_dim + o] = (bfloat)acc;
370+ }
371+}
372+
373+kernel void tq_qmatvec_bf16(
374+ device const float* xr [[buffer(0)]], // [tokens, inn] rotated f32
375+ device const uchar* codes [[buffer(1)]], // packed nibbles
376+ device const half* radius [[buffer(2)]], // [out*inn/d]
377+ constant float* codebook [[buffer(3)]], // 8 levels
378+ device bfloat* y [[buffer(4)]], // [tokens, out] bf16 (output)
379+ constant uint& inn [[buffer(5)]],
380+ constant uint& out_dim [[buffer(6)]],
381+ constant uint& d [[buffer(7)]],
382+ constant uint& tokens [[buffer(8)]],
383+ device const ushort* bias [[buffer(9)]], // [out_dim] bf16 bits (per-row)
384+ constant uint& has_bias [[buffer(10)]],
385+ device const bfloat* resid [[buffer(11)]], // [tokens, out_dim] residual
386+ constant uint& has_resid [[buffer(12)]],
387+ uint2 gid [[thread_position_in_grid]])
388+{
389+ const uint SIMDW = 32;
390+ uint t = gid.y;
391+ uint o = gid.x / SIMDW;
392+ uint lane = gid.x % SIMDW;
393+ if (o >= out_dim || t >= tokens) return;
394+
395+ float cb[8];
396+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i];
397+
398+ device const float* xrow = xr + (ulong)t * inn;
399+ ulong base_pk = ((ulong)o * inn) >> 1;
400+ ulong rbase = ((ulong)o * inn) / d;
401+ device const uint* codes32 = (device const uint*)(codes + base_pk);
402+ uint nwords = inn >> 3;
403+ uint wshift = (uint)log2((float)(d >> 3));
404+
405+ float acc = 0.0f;
406+ for (uint w = lane; w < nwords; w += SIMDW) {
407+ uint packed = codes32[w];
408+ uint k0 = w << 3;
409+ float r = (float)radius[rbase + (w >> wshift)];
410+ acc += xrow[k0 + 0] * cb[(packed >> 0) & 0xF] * r;
411+ acc += xrow[k0 + 1] * cb[(packed >> 4) & 0xF] * r;
412+ acc += xrow[k0 + 2] * cb[(packed >> 8) & 0xF] * r;
413+ acc += xrow[k0 + 3] * cb[(packed >> 12) & 0xF] * r;
414+ acc += xrow[k0 + 4] * cb[(packed >> 16) & 0xF] * r;
415+ acc += xrow[k0 + 5] * cb[(packed >> 20) & 0xF] * r;
416+ acc += xrow[k0 + 6] * cb[(packed >> 24) & 0xF] * r;
417+ acc += xrow[k0 + 7] * cb[(packed >> 28) & 0xF] * r;
418+ }
419+ acc = simd_sum(acc);
420+ if (lane == 0) {
421+ if (has_bias) acc += (float)as_type<bfloat>(bias[o]);
422+ if (has_resid) acc += (float)resid[(ulong)t * out_dim + o];
423+ y[(ulong)t * out_dim + o] = (bfloat)acc;
424+ }
425+}
426+
427+// ───────── REGISTER-BLOCKED bf16 variant: QROWS output rows per simd-group ─────────
428+// The single-row kernel above re-reads the WHOLE activation row (xrow[k]) from
429+// device memory for every output row, so activation traffic is out*inn floats —
430+// the activation load dominates arithmetic intensity at decode (tokens=1, the flat
431+// path). Here ONE simd-group owns QROWS consecutive output rows: each lane loads
432+// the 8 activation coords of its word ONCE into registers and reuses them across
433+// all QROWS rows' codes, cutting activation traffic by QROWS* and lifting the
434+// FMA:load ratio toward ggml mul_mv's. Codes for row (o0+i) are at the same word
435+// index but row-strided by nwords uints (rows are contiguous out*inn/2 bytes,
436+// uint-aligned since inn%8==0); radius is row-strided by inn/d. One radius lookup
437+// per (row, word) — d>=8 so all 8 weights of a word share a d-block. Reductions
438+// are QROWS independent simd_sums; the simd-leader writes QROWS outputs.
439+// grid = (ceil(out/QROWS) * 32, tokens) ; tgroup width = multiple of 32.
440+//
441+// QROWS is a compile-time template (QR) so the per-row arrays (acc[QR], the
442+// unrolled inner loop) live entirely in registers and the compiler can fully
443+// unroll. We instantiate QR=4 (the round-1 default) and QR=8 (wider blocking:
444+// 8 output rows per activation load → 2x the arithmetic intensity, picked when
445+// COCO_QROWS=8). The Rust side selects the pipeline + matching grid divisor.
446+#define DEFINE_QMATVEC_R(NAME, QR) \
447+kernel void NAME( \
448+ device const float* xr [[buffer(0)]], \
449+ device const uchar* codes [[buffer(1)]], \
450+ device const half* radius [[buffer(2)]], \
451+ constant float* codebook [[buffer(3)]], \
452+ device bfloat* y [[buffer(4)]], \
453+ constant uint& inn [[buffer(5)]], \
454+ constant uint& out_dim [[buffer(6)]], \
455+ constant uint& d [[buffer(7)]], \
456+ constant uint& tokens [[buffer(8)]], \
457+ device const ushort* bias [[buffer(9)]], \
458+ constant uint& has_bias [[buffer(10)]], \
459+ device const bfloat* resid [[buffer(11)]], \
460+ constant uint& has_resid [[buffer(12)]], \
461+ uint2 gid [[thread_position_in_grid]]) \
462+{ \
463+ const uint SIMDW = 32; \
464+ const uint QROWS = (QR); \
465+ uint t = gid.y; \
466+ uint grp = gid.x / SIMDW; \
467+ uint lane = gid.x % SIMDW; \
468+ uint o0 = grp * QROWS; \
469+ if (o0 >= out_dim || t >= tokens) return; \
470+ \
471+ float cb[8]; \
472+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; \
473+ \
474+ device const float* xrow = xr + (ulong)t * inn; \
475+ uint nwords = inn >> 3; \
476+ uint wshift = (uint)log2((float)(d >> 3)); \
477+ uint rstride = inn / d; \
478+ \
479+ /* Row stride in uint-words == nwords (rows back-to-back, uint-aligned). */\
480+ device const uint* codes32 = \
481+ (device const uint*)(codes + (((ulong)o0 * inn) >> 1)); \
482+ /* Per-row code base pointers hoisted out of the word loop: the row index \
483+ multiply (i*nwords) is loop-invariant, so compute each row's base once. */\
484+ device const uint* crow[QR]; \
485+ _Pragma("unroll") \
486+ for (uint i = 0; i < QROWS; ++i) crow[i] = codes32 + (ulong)i * nwords; \
487+ \
488+ float acc[QR]; \
489+ for (uint i = 0; i < QROWS; ++i) acc[i] = 0.0f; \
490+ \
491+ /* Activation viewed as float4: k0 = w<<3 is 8-aligned, so two aligned \
492+ float4 loads per word (16-byte coalesced) instead of 8 scalar loads. */ \
493+ device const float4* xrow4 = (device const float4*)xrow; \
494+ for (uint w = lane; w < nwords; w += SIMDW) { \
495+ uint q = w << 1; \
496+ float4 xa = xrow4[q]; \
497+ float4 xb = xrow4[q + 1]; \
498+ uint rb = w >> wshift; \
499+ _Pragma("unroll") \
500+ for (uint i = 0; i < QROWS; ++i) { \
501+ uint o = o0 + i; \
502+ if (o >= out_dim) break; \
503+ uint packed = crow[i][w]; \
504+ float r = (float)radius[(ulong)o * rstride + rb]; \
505+ float4 wa = float4(cb[(packed >> 0) & 0xF], cb[(packed >> 4) & 0xF],\
506+ cb[(packed >> 8) & 0xF], cb[(packed >> 12) & 0xF]);\
507+ float4 wb = float4(cb[(packed >> 16) & 0xF], cb[(packed >> 20) & 0xF],\
508+ cb[(packed >> 24) & 0xF], cb[(packed >> 28) & 0xF]);\
509+ float part = dot(xa, wa) + dot(xb, wb); \
510+ acc[i] += part * r; \
511+ } \
512+ } \
513+ _Pragma("unroll") \
514+ for (uint i = 0; i < QROWS; ++i) { \
515+ uint o = o0 + i; \
516+ if (o >= out_dim) break; \
517+ float s = simd_sum(acc[i]); \
518+ if (lane == 0) { \
519+ if (has_bias) s += (float)as_type<bfloat>(bias[o]); \
520+ if (has_resid) s += (float)resid[(ulong)t * out_dim + o]; \
521+ y[(ulong)t * out_dim + o] = (bfloat)s; \
522+ } \
523+ } \
524+}
525+
526+DEFINE_QMATVEC_R(tq_qmatvec_bf16_r, 4)
527+DEFINE_QMATVEC_R(tq_qmatvec_bf16_r8, 8)
528+
529+// ───────── FUSED SwiGLU variant: silu(gate)·up computed in the qmatvec epilogue ─────────
530+// The MLP gate/up projections are stored as ONE QGroup whose concatenated codes are
531+// [gate(I rows); up(I rows)] back-to-back (out_total = 2*I, I = intermediate dim).
532+// The old path ran the register-blocked qmatvec over all 2*I rows → [gate; up], then
533+// candle issued TWO more whole-tensor passes — `silu(gate)` and `* up` — before
534+// down_proj. Those two elementwise dispatches (+ their GPU barriers + a 2*I→I
535+// round-trip of the intermediate) are pure dispatch overhead at decode (tokens=1).
536+//
537+// Here a simd-group owns QR *gate* rows (o0..o0+QR, o0 strided by QROWS over [0,I)).
538+// For each gate row `o` it ALSO computes the matching up row `o + I` (same activation
539+// row, same codebook; the up codes live `half_rows*nwords` uint-words further into the
540+// SAME codes buffer, the up radius `half_rows*rstride` further into the SAME radius).
541+// Carrying gate[o] AND up[o] in registers, the simd-leader stores silu(gate)·up
542+// directly to y[o] (output width I, NOT 2*I). The standalone silu+mul dispatches in
543+// MLP::forward are then dropped. `half_rows` (= I) is passed in buffer(6) as out_dim
544+// (the SwiGLU output width); the gate/up split is at row `out_dim`. No bias (gate/up
545+// never carry one) so the bias buffers are omitted from this variant.
546+// grid = (ceil(I/QROWS) * 32, tokens) ; same grid math as the register-blocked path
547+// with out_dim = I. silu(x) = x * sigmoid(x) = x / (1 + exp(-x)), accumulated/applied
548+// in f32 and rounded once at the bf16 store (matches candle's f32 silu then bf16 mul).
549+#define DEFINE_QMATVEC_SWIGLU(NAME, QR) \
550+kernel void NAME( \
551+ device const float* xr [[buffer(0)]], \
552+ device const uchar* codes [[buffer(1)]], \
553+ device const half* radius [[buffer(2)]], \
554+ constant float* codebook [[buffer(3)]], \
555+ device bfloat* y [[buffer(4)]], \
556+ constant uint& inn [[buffer(5)]], \
557+ constant uint& out_dim [[buffer(6)]], /* = I (SwiGLU width) */ \
558+ constant uint& d [[buffer(7)]], \
559+ constant uint& tokens [[buffer(8)]], \
560+ uint2 gid [[thread_position_in_grid]]) \
561+{ \
562+ const uint SIMDW = 32; \
563+ const uint QROWS = (QR); \
564+ uint t = gid.y; \
565+ uint grp = gid.x / SIMDW; \
566+ uint lane = gid.x % SIMDW; \
567+ uint o0 = grp * QROWS; \
568+ if (o0 >= out_dim || t >= tokens) return; \
569+ \
570+ float cb[8]; \
571+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; \
572+ \
573+ device const float* xrow = xr + (ulong)t * inn; \
574+ uint nwords = inn >> 3; \
575+ uint wshift = (uint)log2((float)(d >> 3)); \
576+ uint rstride = inn / d; \
577+ /* Up row (o) lives `out_dim` rows after gate row (o) in the SAME buffers. */\
578+ ulong up_word_off = (ulong)out_dim * nwords; /* code words to up codes */\
579+ ulong up_rad_off = (ulong)out_dim * rstride; /* radius entries to up rad */\
580+ \
581+ device const uint* gcodes32 = \
582+ (device const uint*)(codes + (((ulong)o0 * inn) >> 1)); \
583+ /* Per-row gate+up code base pointers, hoisted out of the word loop. */ \
584+ device const uint* gcrow[QR]; \
585+ device const uint* ucrow[QR]; \
586+ _Pragma("unroll") \
587+ for (uint i = 0; i < QROWS; ++i) { \
588+ gcrow[i] = gcodes32 + (ulong)i * nwords; \
589+ ucrow[i] = gcrow[i] + up_word_off; \
590+ } \
591+ \
592+ float gacc[QR]; \
593+ float uacc[QR]; \
594+ for (uint i = 0; i < QROWS; ++i) { gacc[i] = 0.0f; uacc[i] = 0.0f; } \
595+ \
596+ device const float4* xrow4 = (device const float4*)xrow; \
597+ for (uint w = lane; w < nwords; w += SIMDW) { \
598+ uint q = w << 1; \
599+ float4 xa = xrow4[q]; \
600+ float4 xb = xrow4[q + 1]; \
601+ uint rb = w >> wshift; \
602+ _Pragma("unroll") \
603+ for (uint i = 0; i < QROWS; ++i) { \
604+ uint o = o0 + i; \
605+ if (o >= out_dim) break; \
606+ /* gate row o */ \
607+ uint gp = gcrow[i][w]; \
608+ float gr = (float)radius[(ulong)o * rstride + rb]; \
609+ float4 gwa = float4(cb[(gp >> 0) & 0xF], cb[(gp >> 4) & 0xF], \
610+ cb[(gp >> 8) & 0xF], cb[(gp >> 12) & 0xF]); \
611+ float4 gwb = float4(cb[(gp >> 16) & 0xF], cb[(gp >> 20) & 0xF], \
612+ cb[(gp >> 24) & 0xF], cb[(gp >> 28) & 0xF]); \
613+ gacc[i] += (dot(xa, gwa) + dot(xb, gwb)) * gr; \
614+ /* up row o (= concatenated row o+out_dim) */ \
615+ uint up = ucrow[i][w]; \
616+ float ur = (float)radius[(ulong)o * rstride + rb + up_rad_off]; \
617+ float4 uwa = float4(cb[(up >> 0) & 0xF], cb[(up >> 4) & 0xF], \
618+ cb[(up >> 8) & 0xF], cb[(up >> 12) & 0xF]); \
619+ float4 uwb = float4(cb[(up >> 16) & 0xF], cb[(up >> 20) & 0xF], \
620+ cb[(up >> 24) & 0xF], cb[(up >> 28) & 0xF]); \
621+ uacc[i] += (dot(xa, uwa) + dot(xb, uwb)) * ur; \
622+ } \
623+ } \
624+ _Pragma("unroll") \
625+ for (uint i = 0; i < QROWS; ++i) { \
626+ uint o = o0 + i; \
627+ if (o >= out_dim) break; \
628+ float g = simd_sum(gacc[i]); \
629+ float u = simd_sum(uacc[i]); \
630+ if (lane == 0) { \
631+ float sg = g / (1.0f + exp(-g)); /* silu(gate) = x·σ(x) */ \
632+ y[(ulong)t * out_dim + o] = (bfloat)(sg * u); \
633+ } \
634+ } \
635+}
636+
637+DEFINE_QMATVEC_SWIGLU(tq_qmatvec_swiglu_r, 4)
638+DEFINE_QMATVEC_SWIGLU(tq_qmatvec_swiglu_r8, 8)
639+
640+// ───────── FFN MEGAKERNEL (1.5B, no tiling): swiglu → rotate → down, all on-chip ─────────
641+// ONE dispatch (one threadgroup per token) runs the WHOLE FFN with the I-wide
642+// SwiGLU intermediate `h` living in threadgroup memory — it never touches device
643+// memory, and the down-rotate + down-matmul stay fused behind a cheap in-group
644+// barrier (no device drain, no I→I round-trip dispatch). Engaged only when
645+// I (intermediate width) fits the 32KB threadgroup budget as bf16:
646+// I * sizeof(bfloat) = I*2 ; at the 1.5B I=8960 → 17.5KB (FITS). Larger models
647+// (7B I=18944 → 37KB) DON'T fit one tile and fall back automatically (Rust guard).
648+//
649+// Phases (all threads in the group cooperate; one threadgroup owns one token):
650+// 1. SwiGLU: like tq_qmatvec_swiglu but each simd-group owns a STRIDED set of I
651+// gate rows. For gate row o it also reads up row (o+I) from the SAME concat
652+// gate/up buffers, computes silu(gate·xr)·(up·xr), and STORES it as bf16 into
653+// threadgroup hbuf[o]. (xr = the gate/up-rotated input, buffer 0 — the gate/up
654+// rotate stays a separate cheap dispatch upstream, identical to the swiglu path.)
655+// 2. barrier(mem_threadgroup) — all of hbuf is now visible group-wide.
656+// 3. Rotate h for the down projection: per d-wide (d=128) block, h_rot =
657+// blockFWHT(h ∘ down_sign)·rsqrt(d) — the SAME transform tq_rotate applies,
658+// but reading/writing hbuf in place (bf16). Done with a 128-thread FWHT over
659+// each block; the group processes (tgsize/128) blocks per sweep. Cross-simd
660+// stages (stride 32,64) round-trip a small per-block threadgroup scratch.
661+// 4. barrier(mem_threadgroup) — rotated hbuf visible.
662+// 5. Down matmul: each simd-group owns ONE down output row o (hidden width),
663+// dot product over the I-wide rotated hbuf with down codes/radius/codebook,
664+// simd_sum, and the leader stores y[o] (bf16). y is hidden-wide.
665+//
666+// Numerics match swiglu(bf16 h) → tq_rotate(h) → down qmatvec exactly except h is
667+// rounded to bf16 ONCE in threadgroup (the separate path also stored h as bf16),
668+// and the FWHT/dot accumulate in f32 as before.
669+//
670+// Buffers: 0 xr(f32, gate/up-rotated) ; 1 gu_codes ; 2 gu_radius ; 3 codebook(8 f32)
671+// ; 4 y(bf16 out) ; 5 inn (=hidden, gate/up inn) ; 6 I (intermediate width)
672+// ; 7 d (=128) ; 8 down_codes ; 9 down_radius ; 10 down_sign(f32 [I]) ; 11 hidden(out)
673+// grid = (tgsize, tokens=1) threadgroups, threadgroup width = tgsize.
674+kernel void tq_ffn_mega(
675+ device const float* xr [[buffer(0)]], // [tokens, inn] gate/up-rotated
676+ device const uchar* gu_codes [[buffer(1)]], // concat [gate(I); up(I)] nibbles
677+ device const half* gu_radius [[buffer(2)]], // concat gate/up radii
678+ constant float* codebook [[buffer(3)]], // 8 levels (shared gate/up/down)
679+ device bfloat* y [[buffer(4)]], // [tokens, hidden] (output)
680+ constant uint& inn [[buffer(5)]], // gate/up inn (= hidden)
681+ constant uint& I [[buffer(6)]], // intermediate width
682+ constant uint& d [[buffer(7)]], // block size (128)
683+ device const uchar* dn_codes [[buffer(8)]], // down codes [hidden, I] nibbles
684+ device const half* dn_radius [[buffer(9)]], // down radii [hidden*I/d]
685+ device const float* dn_sign [[buffer(10)]], // down rotation sign [I] (±1)
686+ constant uint& hidden [[buffer(11)]], // down out (= hidden)
687+ uint3 tg [[threadgroup_position_in_grid]],
688+ uint3 lt [[thread_position_in_threadgroup]],
689+ uint3 tgsz3 [[threads_per_threadgroup]])
690+{
691+ const uint SIMDW = 32;
692+ // Threadgroup budget (32KB): hbuf 14336*2 = 28KB + scr 512*4 = 2KB = 30KB.
693+ // hbuf holds the whole I-wide SwiGLU intermediate on-chip; the Rust guard only
694+ // engages this kernel when I <= 14336 (the 1.5B I=8960 → 17.5KB used, FITS).
695+ // scr is the per-block FWHT cross-simd scratch (needs `tgsz` floats; tgsz<=512).
696+ threadgroup bfloat hbuf[14336];
697+ threadgroup float scr[512];
698+
699+ uint tgsz = tgsz3.x; // threads per threadgroup
700+ uint tok = tg.y; // one threadgroup per token
701+ uint tid = lt.x; // [0, tgsize)
702+ uint sg = tid / SIMDW; // this simd-group index
703+ uint lane = tid % SIMDW;
704+ uint nsg = tgsz / SIMDW; // simd-groups in the threadgroup
705+
706+ float cb[8];
707+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i];
708+
709+ device const float* xrow = xr + (ulong)tok * inn;
710+ uint nwords = inn >> 3; // packed uints per gate/up row
711+ uint wshift = (uint)log2((float)(d >> 3));
712+ uint rstride = inn / d; // radius entries per gate/up row
713+ ulong up_word_off = (ulong)I * nwords; // up codes live I rows after gate
714+ ulong up_rad_off = (ulong)I * rstride;
715+
716+ // ── Phase 1: SwiGLU → hbuf (each simd-group strides over I gate rows) ──
717+ device const float4* xrow4 = (device const float4*)xrow;
718+ for (uint o = sg; o < I; o += nsg) {
719+ device const uint* gcrow = (device const uint*)(gu_codes + (((ulong)o * inn) >> 1));
720+ device const uint* ucrow = gcrow + up_word_off;
721+ float gacc = 0.0f, uacc = 0.0f;
722+ for (uint w = lane; w < nwords; w += SIMDW) {
723+ uint q = w << 1;
724+ float4 xa = xrow4[q];
725+ float4 xb = xrow4[q + 1];
726+ uint rb = w >> wshift;
727+ uint gp = gcrow[w];
728+ float gr = (float)gu_radius[(ulong)o * rstride + rb];
729+ float4 gwa = float4(cb[(gp >> 0) & 0xF], cb[(gp >> 4) & 0xF],
730+ cb[(gp >> 8) & 0xF], cb[(gp >> 12) & 0xF]);
731+ float4 gwb = float4(cb[(gp >> 16) & 0xF], cb[(gp >> 20) & 0xF],
732+ cb[(gp >> 24) & 0xF], cb[(gp >> 28) & 0xF]);
733+ gacc += (dot(xa, gwa) + dot(xb, gwb)) * gr;
734+ uint up = ucrow[w];
735+ float ur = (float)gu_radius[(ulong)o * rstride + rb + up_rad_off];
736+ float4 uwa = float4(cb[(up >> 0) & 0xF], cb[(up >> 4) & 0xF],
737+ cb[(up >> 8) & 0xF], cb[(up >> 12) & 0xF]);
738+ float4 uwb = float4(cb[(up >> 16) & 0xF], cb[(up >> 20) & 0xF],
739+ cb[(up >> 24) & 0xF], cb[(up >> 28) & 0xF]);
740+ uacc += (dot(xa, uwa) + dot(xb, uwb)) * ur;
741+ }
742+ float g = simd_sum(gacc);
743+ float u = simd_sum(uacc);
744+ if (lane == 0) {
745+ float sg_act = g / (1.0f + exp(-g)); // silu(gate) = x·σ(x)
746+ hbuf[o] = (bfloat)(sg_act * u);
747+ }
748+ }
749+ threadgroup_barrier(mem_flags::mem_threadgroup);
750+
751+ // ── Phase 3: rotate h per d-block: h_rot = blockFWHT(h ∘ dn_sign)/sqrt(d) ──
752+ // Process `blocks_per_sweep = tgsz/d` blocks at once: thread tid owns coord
753+ // (tid % d) of the (tid / d)-th block in the current sweep. Each block's
754+ // cross-simd FWHT scratch is the `d`-slice of scr it maps to (scr is tgsz wide).
755+ uint nblk = I / d;
756+ uint bps = tgsz / d; // blocks rotated per sweep (>=1; d|tgsz)
757+ if (bps >= 1) {
758+ uint jb = tid % d; // coord within its block
759+ uint slot = tid / d; // which concurrent block this thread serves
760+ for (uint b0 = 0; b0 < nblk; b0 += bps) {
761+ uint blk = b0 + slot;
762+ if (blk < nblk) {
763+ uint col = blk * d + jb; // coord within the I-wide h
764+ float v = (float)hbuf[col] * dn_sign[col];
765+ // intra-simd stages (stride < 32): simd_shuffle_xor, no barrier
766+ for (uint h = 1; h < 32u && h < d; h <<= 1) {
767+ float partner = simd_shuffle_xor(v, h);
768+ v = ((jb & h) == 0) ? (v + partner) : (partner - v);
769+ }
770+ // cross-simd stages (stride >= 32): per-block scratch slice
771+ threadgroup float* sb = scr + slot * d;
772+ for (uint h = 32u; h < d; h <<= 1) {
773+ sb[jb] = v;
774+ threadgroup_barrier(mem_flags::mem_threadgroup);
775+ float partner = sb[jb ^ h];
776+ threadgroup_barrier(mem_flags::mem_threadgroup);
777+ v = ((jb & h) == 0) ? (v + partner) : (partner - v);
778+ }
779+ hbuf[col] = (bfloat)(v * rsqrt((float)d));
780+ } else {
781+ // threads with no block this sweep must still hit the barriers
782+ for (uint h = 32u; h < d; h <<= 1) {
783+ threadgroup_barrier(mem_flags::mem_threadgroup);
784+ threadgroup_barrier(mem_flags::mem_threadgroup);
785+ }
786+ }
787+ }
788+ }
789+ threadgroup_barrier(mem_flags::mem_threadgroup);
790+
791+ // ── Phase 5: down matmul y = down · h_rot (one simd-group per output row) ──
792+ uint dn_nwords = I >> 3; // packed uints per down row (inn = I)
793+ uint dn_wshift = (uint)log2((float)(d >> 3));
794+ uint dn_rstride = I / d;
795+ for (uint o = sg; o < hidden; o += nsg) {
796+ device const uint* drow = (device const uint*)(dn_codes + (((ulong)o * I) >> 1));
797+ float acc = 0.0f;
798+ for (uint w = lane; w < dn_nwords; w += SIMDW) {
799+ uint packed = drow[w];
800+ uint k0 = w << 3;
801+ float r = (float)dn_radius[(ulong)o * dn_rstride + (w >> dn_wshift)];
802+ acc += (float)hbuf[k0 + 0] * cb[(packed >> 0) & 0xF] * r;
803+ acc += (float)hbuf[k0 + 1] * cb[(packed >> 4) & 0xF] * r;
804+ acc += (float)hbuf[k0 + 2] * cb[(packed >> 8) & 0xF] * r;
805+ acc += (float)hbuf[k0 + 3] * cb[(packed >> 12) & 0xF] * r;
806+ acc += (float)hbuf[k0 + 4] * cb[(packed >> 16) & 0xF] * r;
807+ acc += (float)hbuf[k0 + 5] * cb[(packed >> 20) & 0xF] * r;
808+ acc += (float)hbuf[k0 + 6] * cb[(packed >> 24) & 0xF] * r;
809+ acc += (float)hbuf[k0 + 7] * cb[(packed >> 28) & 0xF] * r;
810+ }
811+ acc = simd_sum(acc);
812+ if (lane == 0) {
813+ y[(ulong)tok * hidden + o] = (bfloat)acc;
814+ }
815+ }
816+}
817+
818+// ── uint2 wide-unpack variant ──────────────────────────────────────────────
819+// Same register-blocking as above but each lane consumes TWO packed words per
820+// inner iteration: codes are read as a single uint2 (8-byte coalesced) and all
821+// 16 nibbles are unpacked in registers, and the 16 matching activation coords
822+// are loaded as four float4. This halves loop trip count + branch overhead and
823+// raises ILP (two independent dot-product chains per row). Coalescing holds:
824+// consecutive lanes read consecutive uint2 words across the simd-group.
825+// Requires nwords (=inn/8) even — true for every weight here (inn is a multiple
826+// of 16). A scalar tail handles an odd final word defensively. Gated by
827+// COCO_QW2=1 (with QROWS=4). Numerics match the per-word kernel exactly (same
828+// FMA grouping per word, only the loop is restructured).
829+#define DEFINE_QMATVEC_RW2(NAME, QR) \
830+kernel void NAME( \
831+ device const float* xr [[buffer(0)]], \
832+ device const uchar* codes [[buffer(1)]], \
833+ device const half* radius [[buffer(2)]], \
834+ constant float* codebook [[buffer(3)]], \
835+ device bfloat* y [[buffer(4)]], \
836+ constant uint& inn [[buffer(5)]], \
837+ constant uint& out_dim [[buffer(6)]], \
838+ constant uint& d [[buffer(7)]], \
839+ constant uint& tokens [[buffer(8)]], \
840+ device const ushort* bias [[buffer(9)]], \
841+ constant uint& has_bias [[buffer(10)]], \
842+ device const bfloat* resid [[buffer(11)]], \
843+ constant uint& has_resid [[buffer(12)]], \
844+ uint2 gid [[thread_position_in_grid]]) \
845+{ \
846+ const uint SIMDW = 32; \
847+ const uint QROWS = (QR); \
848+ uint t = gid.y; \
849+ uint grp = gid.x / SIMDW; \
850+ uint lane = gid.x % SIMDW; \
851+ uint o0 = grp * QROWS; \
852+ if (o0 >= out_dim || t >= tokens) return; \
853+ \
854+ float cb[8]; \
855+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; \
856+ \
857+ device const float* xrow = xr + (ulong)t * inn; \
858+ uint nwords = inn >> 3; \
859+ uint nw2 = nwords >> 1; /* number of uint2 pairs */ \
860+ uint wshift = (uint)log2((float)(d >> 3)); \
861+ uint rstride = inn / d; \
862+ \
863+ device const uint* codes32 = \
864+ (device const uint*)(codes + (((ulong)o0 * inn) >> 1)); \
865+ device const uint2* crow2[QR]; \
866+ _Pragma("unroll") \
867+ for (uint i = 0; i < QROWS; ++i) \
868+ crow2[i] = (device const uint2*)(codes32 + (ulong)i * nwords); \
869+ \
870+ float acc[QR]; \
871+ for (uint i = 0; i < QROWS; ++i) acc[i] = 0.0f; \
872+ \
873+ device const float4* xrow4 = (device const float4*)xrow; \
874+ for (uint p = lane; p < nw2; p += SIMDW) { \
875+ uint w0 = p << 1; /* low word index of this pair */ \
876+ uint q = w0 << 1; /* float4 index of word w0's low half */ \
877+ float4 x0 = xrow4[q]; \
878+ float4 x1 = xrow4[q + 1]; \
879+ float4 x2 = xrow4[q + 2]; \
880+ float4 x3 = xrow4[q + 3]; \
881+ uint rb0 = w0 >> wshift; \
882+ uint rb1 = (w0 + 1) >> wshift; \
883+ _Pragma("unroll") \
884+ for (uint i = 0; i < QROWS; ++i) { \
885+ uint o = o0 + i; \
886+ if (o >= out_dim) break; \
887+ uint2 pk = crow2[i][p]; \
888+ uint a = pk.x, b = pk.y; \
889+ float r0 = (float)radius[(ulong)o * rstride + rb0]; \
890+ float r1 = (float)radius[(ulong)o * rstride + rb1]; \
891+ float4 a0 = float4(cb[(a >> 0) & 0xF], cb[(a >> 4) & 0xF], \
892+ cb[(a >> 8) & 0xF], cb[(a >> 12) & 0xF]); \
893+ float4 a1 = float4(cb[(a >> 16) & 0xF], cb[(a >> 20) & 0xF], \
894+ cb[(a >> 24) & 0xF], cb[(a >> 28) & 0xF]); \
895+ float4 b0 = float4(cb[(b >> 0) & 0xF], cb[(b >> 4) & 0xF], \
896+ cb[(b >> 8) & 0xF], cb[(b >> 12) & 0xF]); \
897+ float4 b1 = float4(cb[(b >> 16) & 0xF], cb[(b >> 20) & 0xF], \
898+ cb[(b >> 24) & 0xF], cb[(b >> 28) & 0xF]); \
899+ acc[i] += (dot(x0, a0) + dot(x1, a1)) * r0; \
900+ acc[i] += (dot(x2, b0) + dot(x3, b1)) * r1; \
901+ } \
902+ } \
903+ /* Defensive scalar tail for an odd final word (nwords not a multiple of \
904+ 2). All current weights have even nwords, so this never executes, but \
905+ it keeps the kernel correct for any inn that is a multiple of 8. */ \
906+ if ((nwords & 1u) && lane == 0) { \
907+ uint w = nwords - 1; \
908+ uint q = w << 1; \
909+ float4 xa = xrow4[q]; \
910+ float4 xb = xrow4[q + 1]; \
911+ uint rb = w >> wshift; \
912+ _Pragma("unroll") \
913+ for (uint i = 0; i < QROWS; ++i) { \
914+ uint o = o0 + i; \
915+ if (o >= out_dim) break; \
916+ uint packed = codes32[(ulong)i * nwords + w]; \
917+ float r = (float)radius[(ulong)o * rstride + rb]; \
918+ float4 wa = float4(cb[(packed >> 0) & 0xF], cb[(packed >> 4) & 0xF],\
919+ cb[(packed >> 8) & 0xF], cb[(packed >> 12) & 0xF]);\
920+ float4 wb = float4(cb[(packed >> 16) & 0xF], cb[(packed >> 20) & 0xF],\
921+ cb[(packed >> 24) & 0xF], cb[(packed >> 28) & 0xF]);\
922+ acc[i] += (dot(xa, wa) + dot(xb, wb)) * r; \
923+ } \
924+ } \
925+ _Pragma("unroll") \
926+ for (uint i = 0; i < QROWS; ++i) { \
927+ uint o = o0 + i; \
928+ if (o >= out_dim) break; \
929+ float s = simd_sum(acc[i]); \
930+ if (lane == 0) { \
931+ if (has_bias) s += (float)as_type<bfloat>(bias[o]); \
932+ if (has_resid) s += (float)resid[(ulong)t * out_dim + o]; \
933+ y[(ulong)t * out_dim + o] = (bfloat)s; \
934+ } \
935+ } \
936+}
937+
938+DEFINE_QMATVEC_RW2(tq_qmatvec_bf16_rw2, 4)
939+
940+// ───────── ROTATE-IN-PROLOGUE variants (COCO_FUSE_ROTATE_IN, default OFF) ─────────
941+// Fold the standalone activation-rotate dispatch (blockwise FWHT `tq_rotate`) into
942+// the qmatvec itself: each THREADGROUP cooperatively recomputes the rotation of the
943+// token's activation row into threadgroup memory (`xbuf`, dynamic, inn f32 + tgsz
944+// f32 of FWHT scratch), barriers once, then runs the standard register-blocked
945+// QR=4 dot loop reading xbuf instead of a device xr. This trades REDUNDANT FLOPs
946+// (every threadgroup re-rotates the row; decode is memory-bound so they are nearly
947+// free) for one fewer dispatch+barrier per rotate it replaces (qkv, o_proj,
948+// gate/up — the down rotate stays: its row is I-wide, 8960/18944 f32 > 32KB).
949+// The launch grid is UNCHANGED vs the separate-rotate path (same threadgroup count
950+// / simd-group-per-QR-rows layout — parallelism-preserving), but each group now
951+// reserves (inn+tgsz)*4 B of threadgroup memory, which can trim resident-group
952+// occupancy — hence flag-OFF, A/B to decide.
953+//
954+// Numerics: the FWHT here is the SAME op order as tq_rotate_bf16 (bf16 load → f32
955+// sign-flip/butterflies → rsqrt(d) scale) staged as f32, so results match the
956+// separate-rotate path exactly (verified by the one-shot COCO_QCHECK compare).
957+//
958+// Dispatched with dispatch_thread_groups (uniform groups — barrier-safe): grid =
959+// (ceil(out/(nsg*4)), tokens), tgroup = (tgsz,1,1) with tgsz a multiple of d.
960+// buffer(0) is the UNROTATED bf16 activation [tokens, inn].
961+#define TQ_ROTIN_PROLOGUE \
962+ uint tgsz = tgsz3.x; \
963+ uint t = tg.y; \
964+ uint tid = lt.x; \
965+ { \
966+ uint nblk = inn / d; \
967+ uint jb = tid % d; /* coord within its d-block */ \
968+ uint slot = tid / d; /* which concurrent block it serves */ \
969+ uint bps = tgsz / d; /* blocks rotated per sweep (d|tgsz) */ \
970+ threadgroup float* scr = xbuf + inn; /* cross-simd FWHT scratch */ \
971+ device const bfloat* xrow_in = x + (ulong)t * inn; \
972+ for (uint b0 = 0; b0 < nblk; b0 += bps) { \
973+ uint blk = b0 + slot; \
974+ if (blk < nblk) { \
975+ uint col = blk * d + jb; \
976+ float v = (float)xrow_in[col] * sgn[col]; \
977+ for (uint h = 1; h < 32u && h < d; h <<= 1) { \
978+ float partner = simd_shuffle_xor(v, h); \
979+ v = ((jb & h) == 0) ? (v + partner) : (partner - v); \
980+ } \
981+ threadgroup float* sb = scr + slot * d; \
982+ for (uint h = 32u; h < d; h <<= 1) { \
983+ sb[jb] = v; \
984+ threadgroup_barrier(mem_flags::mem_threadgroup); \
985+ float partner = sb[jb ^ h]; \
986+ threadgroup_barrier(mem_flags::mem_threadgroup); \
987+ v = ((jb & h) == 0) ? (v + partner) : (partner - v); \
988+ } \
989+ xbuf[col] = v * rsqrt((float)d); \
990+ } else { \
991+ /* idle threads must still hit the FWHT barriers */ \
992+ for (uint h = 32u; h < d; h <<= 1) { \
993+ threadgroup_barrier(mem_flags::mem_threadgroup); \
994+ threadgroup_barrier(mem_flags::mem_threadgroup); \
995+ } \
996+ } \
997+ } \
998+ } \
999+ threadgroup_barrier(mem_flags::mem_threadgroup);
1000+
1001+// Rotate-in + register-blocked QR=4 dot + bias/resid epilogue (plain projections).
1002+kernel void tq_qmatvec_bf16_rot(
1003+ device const bfloat* x [[buffer(0)]], // [tokens, inn] UNROTATED bf16
1004+ device const uchar* codes [[buffer(1)]],
1005+ device const half* radius [[buffer(2)]],
1006+ constant float* codebook [[buffer(3)]],
1007+ device bfloat* y [[buffer(4)]],
1008+ constant uint& inn [[buffer(5)]],
1009+ constant uint& out_dim [[buffer(6)]],
1010+ constant uint& d [[buffer(7)]],
1011+ constant uint& tokens [[buffer(8)]],
1012+ device const ushort* bias [[buffer(9)]],
1013+ constant uint& has_bias [[buffer(10)]],
1014+ device const bfloat* resid [[buffer(11)]],
1015+ constant uint& has_resid [[buffer(12)]],
1016+ device const float* sgn [[buffer(13)]], // [inn] rotation sign (±1)
1017+ threadgroup float* xbuf [[threadgroup(0)]], // inn + tgsz floats
1018+ uint3 tg [[threadgroup_position_in_grid]],
1019+ uint3 lt [[thread_position_in_threadgroup]],
1020+ uint3 tgsz3 [[threads_per_threadgroup]])
1021+{
1022+ const uint SIMDW = 32;
1023+ const uint QROWS = 4;
1024+ TQ_ROTIN_PROLOGUE
1025+
1026+ uint sg = tid / SIMDW;
1027+ uint lane = tid % SIMDW;
1028+ uint nsg = tgsz / SIMDW;
1029+ uint o0 = (tg.x * nsg + sg) * QROWS;
1030+ if (o0 >= out_dim) return; // AFTER all barriers — safe
1031+
1032+ float cb[8];
1033+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i];
1034+
1035+ uint nwords = inn >> 3;
1036+ uint wshift = (uint)log2((float)(d >> 3));
1037+ uint rstride = inn / d;
1038+
1039+ device const uint* codes32 =
1040+ (device const uint*)(codes + (((ulong)o0 * inn) >> 1));
1041+ device const uint* crow[4];
1042+ _Pragma("unroll")
1043+ for (uint i = 0; i < QROWS; ++i) crow[i] = codes32 + (ulong)i * nwords;
1044+
1045+ float acc[4];
1046+ for (uint i = 0; i < QROWS; ++i) acc[i] = 0.0f;
1047+
1048+ threadgroup const float4* xrow4 = (threadgroup const float4*)xbuf;
1049+ for (uint w = lane; w < nwords; w += SIMDW) {
1050+ uint q = w << 1;
1051+ float4 xa = xrow4[q];
1052+ float4 xb = xrow4[q + 1];
1053+ uint rb = w >> wshift;
1054+ _Pragma("unroll")
1055+ for (uint i = 0; i < QROWS; ++i) {
1056+ uint o = o0 + i;
1057+ if (o >= out_dim) break;
1058+ uint packed = crow[i][w];
1059+ float r = (float)radius[(ulong)o * rstride + rb];
1060+ float4 wa = float4(cb[(packed >> 0) & 0xF], cb[(packed >> 4) & 0xF],
1061+ cb[(packed >> 8) & 0xF], cb[(packed >> 12) & 0xF]);
1062+ float4 wb = float4(cb[(packed >> 16) & 0xF], cb[(packed >> 20) & 0xF],
1063+ cb[(packed >> 24) & 0xF], cb[(packed >> 28) & 0xF]);
1064+ acc[i] += (dot(xa, wa) + dot(xb, wb)) * r;
1065+ }
1066+ }
1067+ _Pragma("unroll")
1068+ for (uint i = 0; i < QROWS; ++i) {
1069+ uint o = o0 + i;
1070+ if (o >= out_dim) break;
1071+ float s = simd_sum(acc[i]);
1072+ if (lane == 0) {
1073+ if (has_bias) s += (float)as_type<bfloat>(bias[o]);
1074+ if (has_resid) s += (float)resid[(ulong)t * out_dim + o];
1075+ y[(ulong)t * out_dim + o] = (bfloat)s;
1076+ }
1077+ }
1078+}
1079+
1080+// Rotate-in + fused SwiGLU (gate/up group): same prologue, then the swiglu QR=4
1081+// dot (gate row o + up row o+out_dim from the concatenated codes), silu(g)·u at
1082+// the leader store. No bias/resid (gate/up never carry either).
1083+kernel void tq_qmatvec_swiglu_rot(
1084+ device const bfloat* x [[buffer(0)]], // [tokens, inn] UNROTATED bf16
1085+ device const uchar* codes [[buffer(1)]],
1086+ device const half* radius [[buffer(2)]],
1087+ constant float* codebook [[buffer(3)]],
1088+ device bfloat* y [[buffer(4)]],
1089+ constant uint& inn [[buffer(5)]],
1090+ constant uint& out_dim [[buffer(6)]], // = I (SwiGLU width)
1091+ constant uint& d [[buffer(7)]],
1092+ constant uint& tokens [[buffer(8)]],
1093+ device const float* sgn [[buffer(9)]], // [inn] rotation sign (±1)
1094+ threadgroup float* xbuf [[threadgroup(0)]], // inn + tgsz floats
1095+ uint3 tg [[threadgroup_position_in_grid]],
1096+ uint3 lt [[thread_position_in_threadgroup]],
1097+ uint3 tgsz3 [[threads_per_threadgroup]])
1098+{
1099+ const uint SIMDW = 32;
1100+ const uint QROWS = 4;
1101+ TQ_ROTIN_PROLOGUE
1102+
1103+ uint sg = tid / SIMDW;
1104+ uint lane = tid % SIMDW;
1105+ uint nsg = tgsz / SIMDW;
1106+ uint o0 = (tg.x * nsg + sg) * QROWS;
1107+ if (o0 >= out_dim) return; // AFTER all barriers — safe
1108+
1109+ float cb[8];
1110+ for (uint i = 0; i < 8; ++i) cb[i] = codebook[i];
1111+
1112+ uint nwords = inn >> 3;
1113+ uint wshift = (uint)log2((float)(d >> 3));
1114+ uint rstride = inn / d;
1115+ ulong up_word_off = (ulong)out_dim * nwords;
1116+ ulong up_rad_off = (ulong)out_dim * rstride;
1117+
1118+ device const uint* gcodes32 =
1119+ (device const uint*)(codes + (((ulong)o0 * inn) >> 1));
1120+ device const uint* gcrow[4];
1121+ device const uint* ucrow[4];
1122+ _Pragma("unroll")
1123+ for (uint i = 0; i < QROWS; ++i) {
1124+ gcrow[i] = gcodes32 + (ulong)i * nwords;
1125+ ucrow[i] = gcrow[i] + up_word_off;
1126+ }
1127+
1128+ float gacc[4];
1129+ float uacc[4];
1130+ for (uint i = 0; i < QROWS; ++i) { gacc[i] = 0.0f; uacc[i] = 0.0f; }
1131+
1132+ threadgroup const float4* xrow4 = (threadgroup const float4*)xbuf;
1133+ for (uint w = lane; w < nwords; w += SIMDW) {
1134+ uint q = w << 1;
1135+ float4 xa = xrow4[q];
1136+ float4 xb = xrow4[q + 1];
1137+ uint rb = w >> wshift;
1138+ _Pragma("unroll")
1139+ for (uint i = 0; i < QROWS; ++i) {
1140+ uint o = o0 + i;
1141+ if (o >= out_dim) break;
1142+ uint gp = gcrow[i][w];
1143+ float gr = (float)radius[(ulong)o * rstride + rb];
1144+ float4 gwa = float4(cb[(gp >> 0) & 0xF], cb[(gp >> 4) & 0xF],
1145+ cb[(gp >> 8) & 0xF], cb[(gp >> 12) & 0xF]);
1146+ float4 gwb = float4(cb[(gp >> 16) & 0xF], cb[(gp >> 20) & 0xF],
1147+ cb[(gp >> 24) & 0xF], cb[(gp >> 28) & 0xF]);
1148+ gacc[i] += (dot(xa, gwa) + dot(xb, gwb)) * gr;
1149+ uint up = ucrow[i][w];
1150+ float ur = (float)radius[(ulong)o * rstride + rb + up_rad_off];
1151+ float4 uwa = float4(cb[(up >> 0) & 0xF], cb[(up >> 4) & 0xF],
1152+ cb[(up >> 8) & 0xF], cb[(up >> 12) & 0xF]);
1153+ float4 uwb = float4(cb[(up >> 16) & 0xF], cb[(up >> 20) & 0xF],
1154+ cb[(up >> 24) & 0xF], cb[(up >> 28) & 0xF]);
1155+ uacc[i] += (dot(xa, uwa) + dot(xb, uwb)) * ur;
1156+ }
1157+ }
1158+ _Pragma("unroll")
1159+ for (uint i = 0; i < QROWS; ++i) {
1160+ uint o = o0 + i;
1161+ if (o >= out_dim) break;
1162+ float g = simd_sum(gacc[i]);
1163+ float u = simd_sum(uacc[i]);
1164+ if (lane == 0) {
1165+ float sg_act = g / (1.0f + exp(-g)); /* silu(gate) = x·σ(x) */
1166+ y[(ulong)t * out_dim + o] = (bfloat)(sg_act * u);
1167+ }
1168+ }
1169+}
1170+
1171+// ───────── FUSED FLASH-DECODE ATTENTION (one token, GQA, persistent KV) ─────────
1172+// Replaces candle's per-token cat(kv) + repeat_kv().contiguous() + scores matmul
1173+// + softmax + AV matmul (each O(ctx), each a separate dispatch + huge copies)
1174+// with ONE dispatch over the persistent KV cache. This is THE long-context lever:
1175+// the candle path reallocates & copies the whole cache every token and materializes
1176+// the GQA-expanded K/V, so decode tok/s collapsed ~35x by 32K. Here the cache lives
1177+// in a pinned buffer; the new k/v is appended in-kernel; attention is online-softmax
1178+// (flash style) so nothing of size [heads,1,ctx] is ever materialized.
1179+//
1180+// Layout: q [n_heads, head_dim] f32 (RoPE'd). k_new/v_new [n_kv_heads, head_dim] f32
1181+// (RoPE'd, in f32). k_cache/v_cache [n_kv_heads, max_ctx, head_dim] f32, persistent.
1182+// `pos` = index where the new token is written; it then attends over [0..=pos].
1183+// GQA: query head h maps to kv head h / (n_heads/n_kv_heads).
1184+//
1185+// FLASH-DECODING (split-K) — the parallelism that matters. The naive "1
1186+// threadgroup per head, loop all positions" design serializes O(ctx) per head with
1187+// only n_heads threadgroups (12), leaving the GPU idle and 2 threadgroup-barriers
1188+// per position. Instead we split the KV range across `n_splits` threadgroups PER
1189+// head (grid = n_heads × n_splits) so up to n_heads·n_splits groups run in
1190+// parallel, each over ctx/n_splits positions. Each group is ONE simd-group (32
1191+// lanes): the per-position q·k dot is a `simd_sum` (no threadgroup barrier), and
1192+// each lane owns head_dim/32 value-accumulator coords. A second tiny kernel
1193+// (tq_attn_combine) merges the per-split partials per head via online-softmax.
1194+//
1195+// head_dim must be a multiple of 32 (128 here → 4 coords/lane). q/k/v f32.
1196+// partial dispatch: grid(threadgroups) = (n_heads, n_splits) ; tgroup = (32,1,1)
1197+// partial outputs : pacc [n_heads, n_splits, head_dim] f32
1198+// pm [n_heads, n_splits] f32 (running max)
1199+// pl [n_heads, n_splits] f32 (running denom)
1200+#define COCO_HD_MAX 256
1201+// 4-bit KV cache: coords-per-quant-block. Equals the simd width (32) so one block ==
1202+// one simd-group (block absmax = a single simd_max). head_dim must be a multiple of 32.
1203+#define Q4_BLK 32
1204+// k_new/v_new (the decode token's k/v, bf16) are appended IN-KERNEL by the single
1205+// split whose range includes pos=total-1 (the highest position). Because only that
1206+// one threadgroup both writes AND reads position `pos`, and every other split reads
1207+// only OLD positions (< pos, untouched this step), there is NO cross-threadgroup
1208+// hazard — so we fold the append into this dispatch (no separate kernel, no
1209+// MTLBarrierScope::Buffers between append→read that serialized the GPU per token).
1210+kernel void tq_attn_partial(
1211+ device const bfloat* q [[buffer(0)]], // [n_heads, head_dim] bf16, RoPE'd
1212+ device bfloat* k_cache [[buffer(1)]], // [n_kv, max_ctx, head_dim] BF16
1213+ device bfloat* v_cache [[buffer(2)]], // [n_kv, max_ctx, head_dim] BF16
1214+ device float* pacc [[buffer(3)]], // [n_heads, n_splits, head_dim]
1215+ device float* pm [[buffer(4)]], // [n_heads, n_splits]
1216+ device float* pl [[buffer(5)]], // [n_heads, n_splits]
1217+ constant uint& n_heads [[buffer(6)]],
1218+ constant uint& n_kv [[buffer(7)]],
1219+ constant uint& head_dim [[buffer(8)]],
1220+ constant uint& max_ctx [[buffer(9)]],
1221+ constant uint& total [[buffer(10)]], // number of valid positions (pos+1)
1222+ constant float& scale [[buffer(11)]],
1223+ constant uint& n_splits [[buffer(12)]],
1224+ device const bfloat* k_new [[buffer(13)]], // [n_kv, head_dim] bf16, RoPE'd
1225+ device const bfloat* v_new [[buffer(14)]], // [n_kv, head_dim] bf16
1226+ uint3 tg [[threadgroup_position_in_grid]],
1227+ uint3 lt [[thread_position_in_threadgroup]])
1228+{
1229+ const uint SIMDW = 32;
1230+ uint lane = lt.x;
1231+ uint h = tg.x; // query head
1232+ uint split = tg.y; // which position-slice
1233+ if (h >= n_heads || split >= n_splits) return;
1234+ uint grp = n_heads / n_kv;
1235+ uint kvh = h / grp;
1236+
1237+ // This split's position range [p0, p1).
1238+ uint per = (total + n_splits - 1) / n_splits;
1239+ uint p0 = split * per;
1240+ uint p1 = min(p0 + per, total);
1241+
1242+ uint cpl = head_dim / SIMDW; // coords per lane (4 for head_dim=128)
1243+
1244+ // In-kernel append: EVERY threadgroup whose range owns pos=total-1 writes the
1245+ // new k/v row for its OWN kv head, then reads it below. No h%grp==0 guard: heads
1246+ // sharing a kvh live in DIFFERENT threadgroups, so if only head 0 wrote, head 1
1247+ // would read a row written by another group (cross-group race). Letting each
1248+ // group write its own kvh row is redundant (identical data) but RACE-FREE: each
1249+ // group reads exactly what it itself wrote (intra-group, ordered by the barrier).
1250+ uint pos = total - 1;
1251+ bool owns_pos = (p0 <= pos && pos < p1);
1252+ if (owns_pos) {
1253+ for (uint c = 0; c < cpl; ++c) {
1254+ uint j = c * SIMDW + lane;
1255+ ulong dst = ((ulong)kvh * max_ctx + pos) * head_dim + j;
1256+ k_cache[dst] = k_new[kvh * head_dim + j]; // bf16 → bf16 cache
1257+ v_cache[dst] = v_new[kvh * head_dim + j];
1258+ }
1259+ // Make this group's own writes visible to its own reads below.
1260+ threadgroup_barrier(mem_flags::mem_device);
1261+ }
1262+
1263+ // Load this lane's q coords into registers (bf16 → f32 on load).
1264+ float qreg[COCO_HD_MAX / 32];
1265+ for (uint c = 0; c < cpl; ++c) qreg[c] = (float)q[h * head_dim + c * SIMDW + lane];
1266+
1267+ float m = -INFINITY, l = 0.0f;
1268+ float acc[COCO_HD_MAX / 32];
1269+ for (uint c = 0; c < cpl; ++c) acc[c] = 0.0f;
1270+
1271+ for (uint p = p0; p < p1; ++p) {
1272+ device const bfloat* krow = k_cache + ((ulong)kvh * max_ctx + p) * head_dim;
1273+ // q·k: each lane sums its coords (bf16 cache → f32 math), simd_sum reduces.
1274+ float partial = 0.0f;
1275+ for (uint c = 0; c < cpl; ++c) partial += qreg[c] * (float)krow[c * SIMDW + lane];
1276+ float score = simd_sum(partial) * scale; // broadcast to all lanes
1277+ float m_new = max(m, score);
1278+ float corr = exp(m - m_new);
1279+ float w = exp(score - m_new);
1280+ l = l * corr + w;
1281+ device const bfloat* vrow = v_cache + ((ulong)kvh * max_ctx + p) * head_dim;
1282+ for (uint c = 0; c < cpl; ++c) acc[c] = acc[c] * corr + w * (float)vrow[c * SIMDW + lane];
1283+ m = m_new;
1284+ }
1285+ // Write this split's partials. acc is the UN-normalized weighted-V (÷ l done in
1286+ // combine). Empty splits (p0>=p1) write m=-inf, l=0 → ignored in combine.
1287+ ulong pbase = ((ulong)h * n_splits + split) * head_dim;
1288+ for (uint c = 0; c < cpl; ++c) pacc[pbase + c * SIMDW + lane] = acc[c];
1289+ if (lane == 0) {
1290+ pm[h * n_splits + split] = m;
1291+ pl[h * n_splits + split] = l;
1292+ }
1293+}
1294+
1295+// Combine the per-split partials for each head into the final attention output.
1296+// online-softmax merge across splits: global m = max(m_i); each split contributes
1297+// exp(m_i - m) * (acc_i, l_i); out = Σ acc / Σ l.
1298+// dispatch: grid(threadgroups) = (n_heads,1,1) ; tgroup = (32,1,1)
1299+kernel void tq_attn_combine(
1300+ device const float* pacc [[buffer(0)]], // [n_heads, n_splits, head_dim]
1301+ device const float* pm [[buffer(1)]], // [n_heads, n_splits]
1302+ device const float* pl [[buffer(2)]], // [n_heads, n_splits]
1303+ device float* attn [[buffer(3)]], // [n_heads, head_dim] f32 out
1304+ constant uint& n_heads [[buffer(4)]],
1305+ constant uint& head_dim [[buffer(5)]],
1306+ constant uint& n_splits [[buffer(6)]],
1307+ uint3 tg [[threadgroup_position_in_grid]],
1308+ uint3 lt [[thread_position_in_threadgroup]])
1309+{
1310+ const uint SIMDW = 32;
1311+ uint h = tg.x;
1312+ uint lane = lt.x;
1313+ if (h >= n_heads) return;
1314+ uint cpl = head_dim / SIMDW;
1315+ // global max across splits
1316+ float gm = -INFINITY;
1317+ for (uint s = 0; s < n_splits; ++s) gm = max(gm, pm[h * n_splits + s]);
1318+ float gl = 0.0f;
1319+ float out[COCO_HD_MAX / 32];
1320+ for (uint c = 0; c < cpl; ++c) out[c] = 0.0f;
1321+ for (uint s = 0; s < n_splits; ++s) {
1322+ float m_s = pm[h * n_splits + s];
1323+ float l_s = pl[h * n_splits + s];
1324+ if (l_s <= 0.0f) continue; // empty split
1325+ float corr = exp(m_s - gm);
1326+ gl += l_s * corr;
1327+ ulong pbase = ((ulong)h * n_splits + s) * head_dim;
1328+ for (uint c = 0; c < cpl; ++c) out[c] += corr * pacc[pbase + c * SIMDW + lane];
1329+ }
1330+ float inv = (gl > 0.0f) ? (1.0f / gl) : 0.0f;
1331+ for (uint c = 0; c < cpl; ++c) attn[h * head_dim + c * SIMDW + lane] = out[c] * inv;
1332+}
1333+
1334+// Append a chunk's k/v into the persistent f32 cache, reading BF16 source (the
1335+// model's hidden dtype) and converting on store — no candle to_dtype(F32) before
1336+// the append. src contiguous [n_kv, seq, head_dim] (k already RoPE'd); dst cache
1337+// [n_kv, max_ctx, head_dim] at column offset `pos`. One thread per (kv, s, j).
1338+// grid = (head_dim, seq, n_kv) ; tgroup = (head_dim,1,1)
1339+kernel void tq_kv_append(
1340+ device const bfloat* k_src [[buffer(0)]], // [n_kv, seq, head_dim] bf16
1341+ device const bfloat* v_src [[buffer(1)]],
1342+ device bfloat* k_cache [[buffer(2)]], // [n_kv, max_ctx, head_dim] BF16
1343+ device bfloat* v_cache [[buffer(3)]],
1344+ constant uint& seq [[buffer(4)]],
1345+ constant uint& head_dim [[buffer(5)]],
1346+ constant uint& max_ctx [[buffer(6)]],
1347+ constant uint& pos [[buffer(7)]],
1348+ uint3 gid [[thread_position_in_grid]])
1349+{
1350+ uint j = gid.x; // coord
1351+ uint s = gid.y; // position within the chunk
1352+ uint kv = gid.z; // kv head
1353+ if (j >= head_dim || s >= seq) return;
1354+ ulong src = ((ulong)kv * seq + s) * head_dim + j;
1355+ ulong dst = ((ulong)kv * max_ctx + (pos + s)) * head_dim + j;
1356+ k_cache[dst] = k_src[src];
1357+ v_cache[dst] = v_src[src];
1358+}
1359+
1360+// ──────────────── 4-BIT KV-CACHE (q4_0-style, per-32-coord block scale) ───────────
1361+// The KV cache stored as 4-bit symmetric-quantized rows instead of bf16 to cut the
1362+// per-decode KV memory traffic ~4x at long context (the dominant cost there). One
1363+// row = the `head_dim` (128) coords for a single (kv_head, position). Each row is
1364+// split into Q4_BLK-coord (=32) BLOCKS, and each block is quantized INDEPENDENTLY:
1365+// scale = absmax(block)/7, code = round(val/scale) clamped to [-7,7], stored unsigned
1366+// as (code+8) in 4 bits (nibble), 2 coords per byte. Dequant: val = (nib - 8) * scale.
1367+//
1368+// IMPORTANT: a single scale per 128-coord ROW (the original design) was too coarse —
1369+// one large RoPE'd coordinate inflates the row absmax, quantizing every other coord to
1370+// near-zero, which collapses the attention scores across positions (the model repeats/
1371+// rambles after the first, recency-dominated token). Real llama.cpp `-ctk q4_0` uses a
1372+// scale PER 32-element block; we match that. With SIMDW==Q4_BLK==32, each block is
1373+// exactly one simd-group, so the block absmax is a single simd_max (no cross-simd
1374+// reduction). f32 softmax/accumulation in-kernel after dequant.
1375+// codes layout: [n_kv, max_ctx, head_dim/2] uchar (nibble-packed, coord j → byte
1376+// j/2, low nibble for even j, high nibble for odd j)
1377+// scale layout: [n_kv, max_ctx, head_dim/Q4_BLK] bfloat (one per 32-coord block)
1378+
1379+// Quantize + append a prefill chunk's k/v into the 4-bit cache. ONE threadgroup per
1380+// (kv, s): the head_dim threads find each 32-coord BLOCK's absmax (one simd_max per
1381+// simd-group, since SIMDW==Q4_BLK), derive that block's bf16 scale, then each thread
1382+// writes its nibble. Reads bf16 source, writes packed nibbles + per-block bf16 scales.
1383+// grid = (kv, seq) tgroup = (head_dim).
1384+kernel void tq_kv_append_q4(
1385+ device const bfloat* k_src [[buffer(0)]], // [n_kv, seq, head_dim] bf16
1386+ device const bfloat* v_src [[buffer(1)]],
1387+ device uchar* k_codes [[buffer(2)]], // [n_kv, max_ctx, head_dim/2]
1388+ device uchar* v_codes [[buffer(3)]],
1389+ device bfloat* k_scale [[buffer(4)]], // [n_kv, max_ctx, head_dim/Q4_BLK]
1390+ device bfloat* v_scale [[buffer(5)]],
1391+ constant uint& seq [[buffer(6)]],
1392+ constant uint& head_dim [[buffer(7)]],
1393+ constant uint& max_ctx [[buffer(8)]],
1394+ constant uint& pos [[buffer(9)]],
1395+ // NOTE: Metal requires the position stage-in attributes in one kernel to be
1396+ // either ALL scalar or ALL same-width vectors. The previous (uint2 tg, uint lt)
1397+ // pair mixed a width-2 vector with a scalar and failed MSL JIT compilation
1398+ // ("expecting input declarations with either all scalar types or all vector
1399+ // types with the same number of elements"). Use uint3 for both (matching the
1400+ // tq_attn_partial convention) and read the components we need.
1401+ uint3 tg [[threadgroup_position_in_grid]],
1402+ uint3 lt [[thread_position_in_threadgroup]],
1403+ uint sg_id [[simdgroup_index_in_threadgroup]],
1404+ uint n_sg [[simdgroups_per_threadgroup]])
1405+{
1406+ (void)n_sg; (void)sg_id; // block index derived from coord (j/Q4_BLK) below
1407+ uint kv = tg.x; // kv head
1408+ uint s = tg.y; // position within the chunk
1409+ uint j = lt.x; // coord
1410+ if (j >= head_dim) return;
1411+ ulong srow = ((ulong)kv * seq + s) * head_dim;
1412+ uint dpos = pos + s;
1413+ float kv_v = (float)k_src[srow + j];
1414+ float vv_v = (float)v_src[srow + j];
1415+
1416+ // ── per-32-coord BLOCK absmax. With SIMDW==Q4_BLK==32, coord j's block is its
1417+ // own simd-group (blk = j/Q4_BLK == sg_id); the block max is one simd_max. ──
1418+ uint blk = j / Q4_BLK; // == sg_id
1419+ uint n_blk = head_dim / Q4_BLK;
1420+ float k_sc = simd_max(fabs(kv_v)) / 7.0f;
1421+ if (k_sc == 0.0f) k_sc = 1.0f; // all-zero block → safe unit scale
1422+ float v_sc = simd_max(fabs(vv_v)) / 7.0f;
1423+ if (v_sc == 0.0f) v_sc = 1.0f;
1424+
1425+ // lane 0 of each simd-group (== block) writes that block's scale.
1426+ if (simd_is_first()) {
1427+ ulong sbase = ((ulong)kv * max_ctx + dpos) * n_blk + blk;
1428+ k_scale[sbase] = (bfloat)k_sc;
1429+ v_scale[sbase] = (bfloat)v_sc;
1430+ }
1431+ // encode this coord's nibble (signed code in [-7,7], stored as code+8 ∈ [1,15])
1432+ int kc = (int)round(kv_v / k_sc); kc = clamp(kc, -7, 7);
1433+ int vc = (int)round(vv_v / v_sc); vc = clamp(vc, -7, 7);
1434+ uint nk = (uint)(kc + 8);
1435+ uint nv = (uint)(vc + 8);
1436+ // nibble-pack: the OWNER of each byte is the even-coord thread (j%2==0); it reads
1437+ // its odd neighbour's nibble via threadgroup memory to avoid a read-modify-write
1438+ // race on the shared byte. (Two threads writing the same byte = data race.)
1439+ threadgroup uchar k_nib[256]; // head_dim <= 256
1440+ threadgroup uchar v_nib[256];
1441+ k_nib[j] = (uchar)nk;
1442+ v_nib[j] = (uchar)nv;
1443+ threadgroup_barrier(mem_flags::mem_threadgroup);
1444+ if ((j & 1u) == 0u) {
1445+ ulong byte = ((ulong)kv * max_ctx + dpos) * (head_dim / 2) + (j >> 1);
1446+ uchar lo_k = k_nib[j], hi_k = (j + 1 < head_dim) ? k_nib[j + 1] : 8;
1447+ uchar lo_v = v_nib[j], hi_v = (j + 1 < head_dim) ? v_nib[j + 1] : 8;
1448+ k_codes[byte] = (uchar)(lo_k | (hi_k << 4));
1449+ v_codes[byte] = (uchar)(lo_v | (hi_v << 4));
1450+ }
1451+}
1452+
1453+// Flash-decode split-K partials over the 4-BIT KV cache (q4 variant of
1454+// tq_attn_partial). Identical online-softmax math; the only difference is K/V are
1455+// read as packed nibbles + a per-row bf16 scale and DEQUANTIZED on the fly
1456+// (val = (nib-8)*scale) before the f32 dot / AV accumulation. The decode token's
1457+// k/v is quantized + appended IN-KERNEL by the split owning pos=total-1 (same
1458+// race-free design as the bf16 kernel: each group writes its own kv-head row).
1459+kernel void tq_attn_partial_q4(
1460+ device const bfloat* q [[buffer(0)]], // [n_heads, head_dim] bf16, RoPE'd
1461+ device uchar* k_codes [[buffer(1)]], // [n_kv, max_ctx, head_dim/2]
1462+ device uchar* v_codes [[buffer(2)]], // [n_kv, max_ctx, head_dim/2]
1463+ device float* pacc [[buffer(3)]], // [n_heads, n_splits, head_dim]
1464+ device float* pm [[buffer(4)]], // [n_heads, n_splits]
1465+ device float* pl [[buffer(5)]], // [n_heads, n_splits]
1466+ constant uint& n_heads [[buffer(6)]],
1467+ constant uint& n_kv [[buffer(7)]],
1468+ constant uint& head_dim [[buffer(8)]],
1469+ constant uint& max_ctx [[buffer(9)]],
1470+ constant uint& total [[buffer(10)]], // valid positions (pos+1)
1471+ constant float& scale [[buffer(11)]],
1472+ constant uint& n_splits [[buffer(12)]],
1473+ device const bfloat* k_new [[buffer(13)]], // [n_kv, head_dim] bf16, RoPE'd
1474+ device const bfloat* v_new [[buffer(14)]], // [n_kv, head_dim] bf16
1475+ device bfloat* k_scale [[buffer(15)]], // [n_kv, max_ctx, head_dim/Q4_BLK]
1476+ device bfloat* v_scale [[buffer(16)]], // [n_kv, max_ctx, head_dim/Q4_BLK]
1477+ constant uint& do_append [[buffer(17)]], // 1 = quantize+append pos in-kernel
1478+ uint3 tg [[threadgroup_position_in_grid]],
1479+ uint3 lt [[thread_position_in_threadgroup]])
1480+{
1481+ const uint SIMDW = 32;
1482+ uint lane = lt.x;
1483+ uint h = tg.x; // query head
1484+ uint split = tg.y; // which position-slice
1485+ if (h >= n_heads || split >= n_splits) return;
1486+ uint grp = n_heads / n_kv;
1487+ uint kvh = h / grp;
1488+ uint hd2 = head_dim / 2; // bytes per packed row
1489+
1490+ uint per = (total + n_splits - 1) / n_splits;
1491+ uint p0 = split * per;
1492+ uint p1 = min(p0 + per, total);
1493+ uint cpl = head_dim / SIMDW; // coords per lane (4 for head_dim=128)
1494+
1495+ // In-kernel quantize+append of the decode token (only the split owning pos).
1496+ uint pos = total - 1;
1497+ bool owns_pos = (do_append != 0u) && (p0 <= pos && pos < p1);
1498+ if (owns_pos) {
1499+ // Per-32-coord BLOCK absmax. Each lane holds one coord per block (coord
1500+ // c*SIMDW+lane is in block c), so simd_max over the 32 lanes for a fixed c is
1501+ // block c's absmax. ksc_b[c]/vsc_b[c] = that block's scale. (Matches the
1502+ // prefill kernel tq_kv_append_q4's per-block scaling.)
1503+ uint n_blk = head_dim / Q4_BLK; // == cpl here (SIMDW == Q4_BLK)
1504+ float ksc_b[COCO_HD_MAX / 32];
1505+ float vsc_b[COCO_HD_MAX / 32];
1506+ for (uint c = 0; c < cpl; ++c) {
1507+ uint j = c * SIMDW + lane;
1508+ float ks = simd_max(fabs((float)k_new[kvh * head_dim + j])) / 7.0f;
1509+ float vs = simd_max(fabs((float)v_new[kvh * head_dim + j])) / 7.0f;
1510+ if (ks == 0.0f) ks = 1.0f;
1511+ if (vs == 0.0f) vs = 1.0f;
1512+ ksc_b[c] = ks; vsc_b[c] = vs;
1513+ if (lane == 0) {
1514+ ulong sbase = ((ulong)kvh * max_ctx + pos) * n_blk + c;
1515+ k_scale[sbase] = (bfloat)ks;
1516+ v_scale[sbase] = (bfloat)vs;
1517+ }
1518+ }
1519+ // Each lane owns cpl coords (j = c*SIMDW + lane). Quantize every coord to a
1520+ // nibble, then nibble-pack via a threadgroup scratch buffer — the SAME race-
1521+ // free pattern as the prefill kernel tq_kv_append_q4 (each lane writes its own
1522+ // nibble to scratch; after a barrier, the even-coord owner assembles the byte
1523+ // from its own + the odd neighbour's scratch nibble). This avoids relying on
1524+ // simd_shuffle_down's cross-lane semantics for the packing (correctness over
1525+ // cleverness). scratch indexed by the absolute coord j (head_dim <= 256).
1526+ threadgroup uchar k_nib[COCO_HD_MAX];
1527+ threadgroup uchar v_nib[COCO_HD_MAX];
1528+ for (uint c = 0; c < cpl; ++c) {
1529+ uint j = c * SIMDW + lane;
1530+ int kc = clamp((int)round((float)k_new[kvh * head_dim + j] / ksc_b[c]), -7, 7);
1531+ int vc = clamp((int)round((float)v_new[kvh * head_dim + j] / vsc_b[c]), -7, 7);
1532+ k_nib[j] = (uchar)(kc + 8);
1533+ v_nib[j] = (uchar)(vc + 8);
1534+ }
1535+ simdgroup_barrier(mem_flags::mem_threadgroup);
1536+ for (uint c = 0; c < cpl; ++c) {
1537+ uint j = c * SIMDW + lane;
1538+ if ((j & 1u) == 0u) {
1539+ ulong byte = ((ulong)kvh * max_ctx + pos) * hd2 + (j >> 1);
1540+ uchar lo_k = k_nib[j], hi_k = (j + 1 < head_dim) ? k_nib[j + 1] : 8;
1541+ uchar lo_v = v_nib[j], hi_v = (j + 1 < head_dim) ? v_nib[j + 1] : 8;
1542+ k_codes[byte] = (uchar)(lo_k | (hi_k << 4));
1543+ v_codes[byte] = (uchar)(lo_v | (hi_v << 4));
1544+ }
1545+ }
1546+ simdgroup_barrier(mem_flags::mem_device);
1547+ }
1548+
1549+ // Load this lane's q coords (bf16 → f32).
1550+ float qreg[COCO_HD_MAX / 32];
1551+ for (uint c = 0; c < cpl; ++c) qreg[c] = (float)q[h * head_dim + c * SIMDW + lane];
1552+
1553+ float m = -INFINITY, l = 0.0f;
1554+ float acc[COCO_HD_MAX / 32];
1555+ for (uint c = 0; c < cpl; ++c) acc[c] = 0.0f;
1556+
1557+ uint n_blk = head_dim / Q4_BLK; // scale blocks per row
1558+ for (uint p = p0; p < p1; ++p) {
1559+ device const bfloat* krsc = k_scale + ((ulong)kvh * max_ctx + p) * n_blk;
1560+ device const uchar* krow = k_codes + ((ulong)kvh * max_ctx + p) * hd2;
1561+ float partial = 0.0f;
1562+ for (uint c = 0; c < cpl; ++c) {
1563+ uint j = c * SIMDW + lane;
1564+ uchar b = krow[j >> 1];
1565+ int nib = ((j & 1u) == 0u) ? (b & 0xF) : (b >> 4);
1566+ float kval = (float)(nib - 8) * (float)krsc[j / Q4_BLK];
1567+ partial += qreg[c] * kval;
1568+ }
1569+ float score = simd_sum(partial) * scale;
1570+ float m_new = max(m, score);
1571+ float corr = exp(m - m_new);
1572+ float w = exp(score - m_new);
1573+ l = l * corr + w;
1574+ device const bfloat* vrsc = v_scale + ((ulong)kvh * max_ctx + p) * n_blk;
1575+ device const uchar* vrow = v_codes + ((ulong)kvh * max_ctx + p) * hd2;
1576+ for (uint c = 0; c < cpl; ++c) {
1577+ uint j = c * SIMDW + lane;
1578+ uchar b = vrow[j >> 1];
1579+ int nib = ((j & 1u) == 0u) ? (b & 0xF) : (b >> 4);
1580+ float vval = (float)(nib - 8) * (float)vrsc[j / Q4_BLK];
1581+ acc[c] = acc[c] * corr + w * vval;
1582+ }
1583+ m = m_new;
1584+ }
1585+ ulong pbase = ((ulong)h * n_splits + split) * head_dim;
1586+ for (uint c = 0; c < cpl; ++c) pacc[pbase + c * SIMDW + lane] = acc[c];
1587+ if (lane == 0) {
1588+ pm[h * n_splits + split] = m;
1589+ pl[h * n_splits + split] = l;
1590+ }
1591+}
1592+
1593+// Fused RMSNorm: out = x * rsqrt(mean(x^2) + eps) * w, reading bf16 x + bf16 w and
1594+// writing bf16 — ONE dispatch replacing candle's RmsNorm chain (to_dtype(f32) +
1595+// sqr + mean + add(eps) + rsqrt + broadcast_mul + broadcast_mul + to_dtype(bf16),
1596+// ~7 elementwise dispatches per norm x ~57 norms/token). One threadgroup per token;
1597+// the threadgroup width (a multiple of 32, capped) strides over inn coords and
1598+// reduces the sum-of-squares cooperatively in f32, then each lane writes its
1599+// normalized coords. Reduction: per-lane partial -> simd_sum within each 32-lane
1600+// simd-group -> per-simd partials combined via threadgroup memory. Math in f32
1601+// (candle's RmsNorm also upcasts); output rounded to bf16.
1602+kernel void tq_rmsnorm_bf16(
1603+ device const bfloat* x [[buffer(0)]], // [tokens, inn] bf16
1604+ device bfloat* out [[buffer(1)]], // [tokens, inn] bf16 (output)
1605+ device const bfloat* w [[buffer(2)]], // [inn] bf16 (norm weight)
1606+ constant uint& inn [[buffer(3)]],
1607+ constant float& eps [[buffer(4)]],
1608+ uint tg [[threadgroup_position_in_grid]],
1609+ uint lt [[thread_position_in_threadgroup]],
1610+ uint tgw [[threads_per_threadgroup]],
1611+ uint sg_id [[simdgroup_index_in_threadgroup]],
1612+ uint n_sg [[simdgroups_per_threadgroup]])
1613+{
1614+ threadgroup float sg_part[32]; // one partial per simd-group (<=32)
1615+ uint tok = tg;
1616+ uint tid = lt; // thread index within the threadgroup
1617+ uint W = tgw; // threadgroup width (multiple of 32)
1618+ device const bfloat* xrow = x + (ulong)tok * inn;
1619+ device bfloat* orow = out + (ulong)tok * inn;
1620+
1621+ // Per-thread sum of squares over its strided coords.
1622+ float ss = 0.0f;
1623+ for (uint i = tid; i < inn; i += W) {
1624+ float v = (float)xrow[i];
1625+ ss += v * v;
1626+ }
1627+ ss = simd_sum(ss); // reduce within the simd-group
1628+ if (simd_is_first()) sg_part[sg_id] = ss;
1629+ threadgroup_barrier(mem_flags::mem_threadgroup);
1630+ // simd-group 0 reduces the per-simd partials, broadcasts via sg_part[0].
1631+ if (sg_id == 0) {
1632+ float p = (lt < n_sg) ? sg_part[lt] : 0.0f;
1633+ p = simd_sum(p);
1634+ if (simd_is_first()) sg_part[0] = p;
1635+ }
1636+ threadgroup_barrier(mem_flags::mem_threadgroup);
1637+ float total = sg_part[0];
1638+ float inv = rsqrt(total / (float)inn + eps);
1639+ for (uint i = tid; i < inn; i += W) {
1640+ orow[i] = (bfloat)(((float)xrow[i]) * inv * (float)w[i]);
1641+ }
1642+}
1643+
1644+// FUSED residual-add + RMSNorm: h = a + b ; out = RMSNorm(h) * w. Writes BOTH the
1645+// summed residual `h` (needed as the residual for the NEXT add) AND the normalized
1646+// output, in ONE dispatch. This folds the standalone candle elementwise residual
1647+// add (`(xs + residual)?` — a full [tokens,inn] pass, one per sublayer ×28 layers)
1648+// into the RMSNorm that immediately consumes it. The transformer block is
1649+// h = x + sublayer(...) ; h_norm = RMSNorm(h)
1650+// so the add result is always read straight by the next norm — we never need a
1651+// separate add dispatch. Math in f32 (matches candle's upcast); both outputs bf16.
1652+kernel void tq_add_rmsnorm_bf16(
1653+ device const bfloat* a [[buffer(0)]], // [tokens, inn] bf16 (residual)
1654+ device const bfloat* b [[buffer(1)]], // [tokens, inn] bf16 (sublayer out)
1655+ device bfloat* h [[buffer(2)]], // [tokens, inn] bf16 (a+b, output)
1656+ device bfloat* out [[buffer(3)]], // [tokens, inn] bf16 (RMSNorm(h)*w)
1657+ device const bfloat* w [[buffer(4)]], // [inn] bf16 (norm weight)
1658+ constant uint& inn [[buffer(5)]],
1659+ constant float& eps [[buffer(6)]],
1660+ uint tg [[threadgroup_position_in_grid]],
1661+ uint lt [[thread_position_in_threadgroup]],
1662+ uint tgw [[threads_per_threadgroup]],
1663+ uint sg_id [[simdgroup_index_in_threadgroup]],
1664+ uint n_sg [[simdgroups_per_threadgroup]])
1665+{
1666+ threadgroup float sg_part[32];
1667+ uint tok = tg;
1668+ uint tid = lt;
1669+ uint W = tgw;
1670+ device const bfloat* arow = a + (ulong)tok * inn;
1671+ device const bfloat* brow = b + (ulong)tok * inn;
1672+ device bfloat* hrow = h + (ulong)tok * inn;
1673+ device bfloat* orow = out + (ulong)tok * inn;
1674+
1675+ // Sum once, store h (rounded bf16 — same precision the standalone add produced),
1676+ // and accumulate the f32 sum-of-squares of the (bf16-rounded) h for the norm.
1677+ float ss = 0.0f;
1678+ for (uint i = tid; i < inn; i += W) {
1679+ bfloat hv = (bfloat)((float)arow[i] + (float)brow[i]);
1680+ hrow[i] = hv;
1681+ float f = (float)hv;
1682+ ss += f * f;
1683+ }
1684+ ss = simd_sum(ss);
1685+ if (simd_is_first()) sg_part[sg_id] = ss;
1686+ threadgroup_barrier(mem_flags::mem_threadgroup);
1687+ if (sg_id == 0) {
1688+ float p = (lt < n_sg) ? sg_part[lt] : 0.0f;
1689+ p = simd_sum(p);
1690+ if (simd_is_first()) sg_part[0] = p;
1691+ }
1692+ threadgroup_barrier(mem_flags::mem_threadgroup);
1693+ float total = sg_part[0];
1694+ float inv = rsqrt(total / (float)inn + eps);
1695+ for (uint i = tid; i < inn; i += W) {
1696+ orow[i] = (bfloat)(((float)hrow[i]) * inv * (float)w[i]);
1697+ }
1698+}
1699+"#;
1700+
1701+// ───────────────────────── compiled-pipeline cache ─────────────────────────
1702+
1703+// pub(crate) (fields too) so the enc_proto micro-bench bin (which #[path]-includes
1704+// this module) can raw-encode the exact same pipelines. No behavior change.
1705+pub(crate) struct Pipelines {
1706+ pub(crate) rotate: ComputePipeline, // f32-input activation rotate
1707+ pub(crate) rotate_bf16: ComputePipeline, // bf16-input rotate (skips candle to_dtype/contiguous)
1708+ pub(crate) qmatvec: ComputePipeline, // 4-bit nibble codes (legacy)
1709+ pub(crate) qmatvec3: ComputePipeline, // true 3-bit codes (opt-2, default)
1710+ pub(crate) qmatvec_bf16: ComputePipeline, // 4-bit nibble, fused bf16-out + bias epilogue
1711+ pub(crate) qmatvec3_bf16: ComputePipeline, // true 3-bit, fused bf16-out + bias epilogue
1712+ pub(crate) qmatvec_bf16_r: ComputePipeline, // 4-bit nibble, register-blocked (QROWS=4 rows/simd-group)
1713+ pub(crate) qmatvec_bf16_r8: ComputePipeline, // register-blocked QROWS=8 (wider blocking, COCO_QROWS=8)
1714+ pub(crate) qmatvec_bf16_rw2: ComputePipeline, // QROWS=4, uint2 wide-unpack (2 words/iter, COCO_QW2=1)
1715+ pub(crate) qmatvec_swiglu_r: ComputePipeline, // fused gate/up → silu(gate)·up (QROWS=4, COCO_FUSE_SWIGLU)
1716+ pub(crate) qmatvec_swiglu_r8: ComputePipeline, // fused gate/up → silu(gate)·up (QROWS=8)
1717+ pub(crate) qmatvec_bf16_rot: ComputePipeline, // rotate-in prologue + QR=4 dot (COCO_FUSE_ROTATE_IN)
1718+ pub(crate) qmatvec_swiglu_rot: ComputePipeline, // rotate-in prologue + fused SwiGLU (COCO_FUSE_ROTATE_IN)
1719+ pub(crate) ffn_mega: ComputePipeline, // whole FFN in one dispatch (1.5B, h in threadgroup; COCO_FFN_MEGA)
1720+ pub(crate) attn_partial: ComputePipeline, // flash-decoding split-K partials (GQA, persistent KV)
1721+ pub(crate) attn_partial_q4: ComputePipeline, // q4-KV flash-decoding partials (dequant on the fly)
1722+ pub(crate) attn_combine: ComputePipeline, // merge per-split partials per head
1723+ pub(crate) kv_append: ComputePipeline, // append a prefill chunk's k/v into the cache
1724+ pub(crate) kv_append_q4: ComputePipeline, // quantize+append a prefill chunk into the 4-bit cache
1725+ pub(crate) rmsnorm: ComputePipeline, // fused RMSNorm (x * rsqrt(mean(x^2)+eps) * w)
1726+ pub(crate) rope_bf16: ComputePipeline, // fused RoPE reading the transposed view (no .contiguous())
1727+ pub(crate) add_rmsnorm: ComputePipeline, // fused residual-add + RMSNorm (one dispatch, writes h + normed)
1728+}
1729+
1730+// Keyed by Metal device registry id so we compile the library exactly once.
1731+static PIPELINES: OnceLock<Mutex<Vec<(u64, Arc<Pipelines>)>>> = OnceLock::new();
1732+
1733+pub(crate) fn get_pipelines(mdev: &candle_metal_kernels::metal::Device) -> Result<Arc<Pipelines>> {
1734+ let cache = PIPELINES.get_or_init(|| Mutex::new(Vec::new()));
1735+ let id = mdev.registry_id();
1736+ {
1737+ let guard = cache.lock().unwrap();
1738+ if let Some((_, p)) = guard.iter().find(|(k, _)| *k == id) {
1739+ return Ok(p.clone());
1740+ }
1741+ }
1742+ let lib = mdev
1743+ .new_library_with_source(KERNEL_SRC, None)
1744+ .map_err(|e| anyhow!("compiling turboquant-fast MSL: {e}"))?;
1745+ let pipe = |name: &str| -> Result<ComputePipeline> {
1746+ let f = lib
1747+ .get_function(name, None)
1748+ .map_err(|e| anyhow!("{name}: {e}"))?;
1749+ mdev.new_compute_pipeline_state_with_function(&f)
1750+ .map_err(|e| anyhow!("pipeline {name}: {e}"))
1751+ };
1752+ let rotate = pipe("tq_rotate_f32")?;
1753+ let rotate_bf16 = pipe("tq_rotate_bf16")?;
1754+ let qmatvec = pipe("tq_qmatvec_f32")?;
1755+ let qmatvec3 = pipe("tq_qmatvec3_f32")?;
1756+ let qmatvec_bf16 = pipe("tq_qmatvec_bf16")?;
1757+ let qmatvec3_bf16 = pipe("tq_qmatvec3_bf16")?;
1758+ let qmatvec_bf16_r = pipe("tq_qmatvec_bf16_r")?;
1759+ let qmatvec_bf16_r8 = pipe("tq_qmatvec_bf16_r8")?;
1760+ let qmatvec_bf16_rw2 = pipe("tq_qmatvec_bf16_rw2")?;
1761+ let qmatvec_swiglu_r = pipe("tq_qmatvec_swiglu_r")?;
1762+ let qmatvec_swiglu_r8 = pipe("tq_qmatvec_swiglu_r8")?;
1763+ let qmatvec_bf16_rot = pipe("tq_qmatvec_bf16_rot")?;
1764+ let qmatvec_swiglu_rot = pipe("tq_qmatvec_swiglu_rot")?;
1765+ let ffn_mega = pipe("tq_ffn_mega")?;
1766+ let attn_partial = pipe("tq_attn_partial")?;
1767+ let attn_partial_q4 = pipe("tq_attn_partial_q4")?;
1768+ let attn_combine = pipe("tq_attn_combine")?;
1769+ let kv_append = pipe("tq_kv_append")?;
1770+ let kv_append_q4 = pipe("tq_kv_append_q4")?;
1771+ let rmsnorm = pipe("tq_rmsnorm_bf16")?;
1772+ let rope_bf16 = pipe("tq_rope_bf16")?;
1773+ let add_rmsnorm = pipe("tq_add_rmsnorm_bf16")?;
1774+ let p = Arc::new(Pipelines {
1775+ rotate,
1776+ rotate_bf16,
1777+ qmatvec,
1778+ qmatvec3,
1779+ qmatvec_bf16,
1780+ qmatvec3_bf16,
1781+ qmatvec_bf16_r,
1782+ qmatvec_bf16_r8,
1783+ qmatvec_bf16_rw2,
1784+ qmatvec_swiglu_r,
1785+ qmatvec_swiglu_r8,
1786+ qmatvec_bf16_rot,
1787+ qmatvec_swiglu_rot,
1788+ ffn_mega,
1789+ attn_partial,
1790+ attn_partial_q4,
1791+ attn_combine,
1792+ kv_append,
1793+ kv_append_q4,
1794+ rmsnorm,
1795+ rope_bf16,
1796+ add_rmsnorm,
1797+ });
1798+ cache.lock().unwrap().push((id, p.clone()));
1799+ Ok(p)
1800+}
1801+
1802+// ───────────────────────── GPU-resident compressed weight ─────────────────────────
1803+
1804+/// One turboquant weight, kept COMPRESSED on the GPU (packed codes + fp16 radius
1805+/// + 8-entry codebook + the ±1 sign vector). Plus an optional bias kept on
1806+/// the device. Nothing here is ever expanded to a dense fp16 weight.
1807+pub struct QWeight {
1808+ pub(crate) out: usize,
1809+ pub(crate) inn: usize,
1810+ pub(crate) d: usize,
1811+ pub(crate) sign: Tensor, // [inn] f32, on device (±1)
1812+ // codes/radius/bias are held as `Arc<Buffer>` (not bare `Buffer`) so candle's
1813+ // pool allocator never recycles or evicts-from-residency the resident weight
1814+ // memory: the pool reclaims a buffer only when its `Arc<Buffer>` strong count
1815+ // hits 1, and these clones keep it at ≥2 for the model's lifetime. (Storing a
1816+ // bare `Buffer` retains the MTLBuffer but lets the pool's own Arc drop to 1,
1817+ // so a later same-size allocation gets handed the same buffer and overwrites
1818+ // it — the root cause of the garbage we debugged once build-time readbacks
1819+ // started triggering `drop_unused_buffers`.)
1820+ pub(crate) codes: Arc<Buffer>, // packed codes on device (3-bit stream or 4-bit nibble)
1821+ pub(crate) radius: Arc<Buffer>, // f16, len = out*inn/d, on device
1822+ pub(crate) codebook: Vec<f32>, // 8 levels (tiny, passed as constant bytes)
1823+ pub(crate) bias: Option<Tensor>, // [out], on device, in the model dtype
1824+ /// Per-row bias as a raw BF16 device buffer, for the fused bf16 qmatvec
1825+ /// epilogue. Stored as `Arc<Buffer>` (NOT a bare `Buffer`) so candle's pool
1826+ /// allocator — which reclaims/recycles buffers whose `Arc<Buffer>` strong
1827+ /// count drops to 1 — never hands this MTLBuffer to a later same-size
1828+ /// allocation. (A bare `Buffer` retains the MTLBuffer but leaves the pool's
1829+ /// own Arc at count 1, so `find_available_buffer` reuses & overwrites it —
1830+ /// the cause of the fused-bias garbage we debugged.) `None` if no bias.
1831+ pub(crate) bias_bf16: Option<Arc<Buffer>>,
1832+ pub(crate) pack_bits: u8, // 3 = true 3-bit stream (default), 4 = nibble (legacy/A-B)
1833+ pub compressed_bytes: usize,
1834+}
1835+
1836+/// Build a dedicated, pinned BF16 device buffer (length `out`) holding the bias
1837+/// bits, for the fused qmatvec epilogue. Returns the `Arc<Buffer>` so the caller
1838+/// can keep candle's pool from recycling it (see `QWeight::bias_bf16`). We read
1839+/// the bias values to CPU and re-upload via `new_buffer_with_data` rather than
1840+/// aliasing a transient tensor's storage (whose pool-Arc would drop to 1 and be
1841+/// reused/overwritten).
1842+fn bias_to_bf16_buf(
1843+ bias: &Tensor,
1844+ cdev: &candle_core::MetalDevice,
1845+) -> Result<Arc<Buffer>> {
1846+ let vals: Vec<half::bf16> = bias.to_dtype(DType::BF16)?.flatten_all()?.to_vec1()?;
1847+ let bits: Vec<u16> = vals.iter().map(|v| v.to_bits()).collect();
1848+ Ok(cdev.new_buffer_with_data(&bits)?)
1849+}
1850+
1851+/// Code packing for the resident weights / matmul kernel.
1852+/// 4 = nibble (4.125 bpw, 644 MB) — DEFAULT: validated + fastest (aligned
1853+/// uint32 reads). The qmatvec path is decode/dispatch-bound at 1.5B, so
1854+/// this is the throughput choice.
1855+/// 3 = true 3-bit (3.125 bpw, 488 MB) — 24% less resident RAM at equal speed;
1856+/// pick it (`COCO_PACK_BITS=3`) when memory matters more than tok/s.
1857+fn pack_bits_from_env() -> u8 {
1858+ match std::env::var("COCO_PACK_BITS").as_deref() {
1859+ Ok("3") => 3,
1860+ _ => 4,
1861+ }
1862+}
1863+
1864+/// Fused residual epilogue (COCO_FUSE_RESID, default OFF — opt-in): the o_proj / down_proj
1865+/// qmatvec adds the layer residual at its leader store instead of a standalone
1866+/// candle elementwise add dispatch. Set COCO_FUSE_RESID=0 to restore the old
1867+/// add-after path (A/B).
1868+pub fn fuse_resid_enabled() -> bool {
1869+ // OPT-IN (COCO_FUSE_RESID=1). Measured A/B on the 7B: this fusion is ~2% slower at
1870+ // ctx0 and ~10% slower at 8K than the pre-existing path (whose attn-side add+RMSNorm
1871+ // was already fused via forward_add; the resid qmatvec variant misses the fastest
1872+ // kernel path). Numerically correct (QCHECK 1 ULP) but a measured LOSS — kept only
1873+ // as a documented experiment. Default = the faster separate path.
1874+ matches!(std::env::var("COCO_FUSE_RESID").as_deref(), Ok("1"))
1875+}
1876+
1877+/// Rotate-in-prologue (COCO_FUSE_ROTATE_IN=1, default OFF — experimental A/B):
1878+/// fold the activation-rotate dispatch into the qmatvec kernel prologue
1879+/// (threadgroup-memory FWHT recompute per threadgroup).
1880+fn fuse_rotate_in_enabled() -> bool {
1881+ matches!(std::env::var("COCO_FUSE_ROTATE_IN").as_deref(), Ok("1"))
1882+}
1883+
1884+/// Can the rotate-in kernel take this projection? Mirrors the dispatch-side tgw
1885+/// computation so the threadgroup-memory budget check ((inn + tgsz) f32 ≤ 32KB)
1886+/// is decided before choosing the path. Decode-only (tokens==1): at prefill the
1887+/// separate rotate is amortized over the whole grid, per-threadgroup recompute
1888+/// is not. The rot kernels are compiled at QROWS=4 without the QW2 restructure,
1889+/// so any non-default QROWS/QW2 selection falls back to the separate rotate.
1890+fn rotate_in_eligible(inn: usize, d: usize, pack_bits: u8, in_dtype: DType, tokens: usize) -> bool {
1891+ if !fuse_rotate_in_enabled() || tokens != 1 {
1892+ return false;
1893+ }
1894+ if in_dtype != DType::BF16 || pack_bits == 3 {
1895+ return false;
1896+ }
1897+ if std::env::var("COCO_NO_FUSE").is_ok() || std::env::var("COCO_SKIP_ROTATE").is_ok() {
1898+ return false;
1899+ }
1900+ if matches!(std::env::var("COCO_QROWS").ok().as_deref(), Some("0") | Some("8")) {
1901+ return false;
1902+ }
1903+ if std::env::var("COCO_QW2").as_deref() == Ok("1") {
1904+ return false;
1905+ }
1906+ if inn % d != 0 || inn % 8 != 0 {
1907+ return false;
1908+ }
1909+ // Worst-case threadgroup width the op will pick (qocc simd-groups, rounded to
1910+ // a multiple of d): the dynamic threadgroup buffer is (inn + tgw) f32 and must
1911+ // fit the 32KB budget. o_proj/qkv/gate-up (inn = hidden ≤ 3584) fit; the down
1912+ // rotate does NOT (inn = I = 8960/18944) and keeps its separate dispatch.
1913+ let qocc: usize = std::env::var("COCO_QOCC")
1914+ .ok()
1915+ .and_then(|v| v.parse::<usize>().ok())
1916+ .filter(|&v| v >= 1)
1917+ .unwrap_or(8);
1918+ let mut tgw = (qocc * 32).min(1024);
1919+ tgw = (tgw / d).max(1) * d;
1920+ (inn + tgw) * 4 <= 32 * 1024
1921+}
1922+
1923+impl QWeight {
1924+ /// Build a GPU-resident compressed weight from a `TqWeight` (must be
1925+ /// block-Hadamard with no outlier split — the clean 3-bit recipe).
1926+ /// `bias` (if any) is already on `device` in the model dtype.
1927+ pub fn from_tq(q: &TqWeight, bias: Option<Tensor>, device: &Device) -> Result<Self> {
1928+ if !q.block_hadamard {
1929+ return Err(anyhow!(
1930+ "turboquant-fast requires block-Hadamard mode (inn % d == 0)"
1931+ ));
1932+ }
1933+ if !q.outlier_idx.is_empty() {
1934+ return Err(anyhow!(
1935+ "turboquant-fast requires --outlier-frac 0 (no sparse side-list)"
1936+ ));
1937+ }
1938+ if q.bits != 3 {
1939+ return Err(anyhow!("turboquant-fast assumes 3-bit codes (8 levels)"));
1940+ }
1941+ let cdev = match device {
1942+ Device::Metal(m) => m,
1943+ _ => return Err(anyhow!("turboquant-fast requires the Metal device")),
1944+ };
1945+
1946+ let sign_v = turboquant::signs(q.p, q.seed); // length p == inn in block mode
1947+ let sign = Tensor::from_vec(sign_v, q.inn, device)?;
1948+
1949+ // Pack codes: 4-bit nibble (4.125 bpw, default, fastest) or true 3-bit
1950+ // (3.125 bpw, COCO_PACK_BITS=3, less RAM). The matmul kernel is chosen to
1951+ // match. 3-bit packing needs inn % 8 == 0 (true: 1536, 8960).
1952+ let pack_bits = pack_bits_from_env();
1953+ let packed = if pack_bits == 3 {
1954+ q.codes_packed_3bit()
1955+ } else {
1956+ q.codes_packed_nibble()
1957+ };
1958+ let codes = cdev.new_buffer_with_data(&packed)?; // Arc<Buffer>
1959+
1960+ // radius as raw f16 bits -> GPU buffer
1961+ let rad_bits: Vec<u16> = q.radius.iter().map(|r| r.to_bits()).collect();
1962+ let radius = cdev.new_buffer_with_data(&rad_bits)?;
1963+
1964+ let compressed_bytes = packed.len() + rad_bits.len() * 2 + q.codebook.len() * 4;
1965+
1966+ // One-shot self-check: build BOTH the 3-bit and 4-bit code buffers for
1967+ // this weight, run the matmul kernel each way on a fixed random rotated
1968+ // input, and print the max abs diff. They MUST match (same codes, same
1969+ // codebook). Triggered by COCO_QCHECK=1, first weight only.
1970+ if std::env::var("COCO_QCHECK").is_ok() {
1971+ // Check one weight per distinct (out, inn) shape.
1972+ static SEEN: OnceLock<Mutex<Vec<(usize, usize)>>> = OnceLock::new();
1973+ let seen = SEEN.get_or_init(|| Mutex::new(Vec::new()));
1974+ let key = (q.out, q.inn);
1975+ let do_check = {
1976+ let mut g = seen.lock().unwrap();
1977+ if g.contains(&key) {
1978+ false
1979+ } else {
1980+ g.push(key);
1981+ true
1982+ }
1983+ };
1984+ if do_check {
1985+ let nib = q.codes_packed_nibble();
1986+ let three = q.codes_packed_3bit();
1987+ let codes_nib = cdev.new_buffer_with_data(&nib)?;
1988+ let codes_3 = cdev.new_buffer_with_data(&three)?;
1989+ // fixed pseudo-random xr [1, inn]
1990+ let xr_v: Vec<f32> = (0..q.inn)
1991+ .map(|i| ((i as f32 * 0.123).sin()))
1992+ .collect();
1993+ let xr = Tensor::from_vec(xr_v, (1, q.inn), device)?;
1994+ let run = |buf: &Arc<Buffer>, pb: u8| -> Result<Vec<f32>> {
1995+ let y = xr.apply_op1(QMatVecOp {
1996+ qw: QMatVecRef {
1997+ out: q.out,
1998+ inn: q.inn,
1999+ d: q.d,
2000+ codes: buf.clone(),
2001+ radius: radius.clone(),
2002+ codebook: q.codebook.clone(),
2003+ pack_bits: pb,
2004+ bias_bf16: None,
2005+ out_dtype: DType::F32, // f32 path for the kernel A/B check
2006+ swiglu: false,
2007+ resid: None,
2008+ rot_sign: None,
2009+ },
2010+ tokens: 1,
2011+ })?;
2012+ Ok(y.flatten_all()?.to_vec1()?)
2013+ };
2014+ let y4 = run(&codes_nib, 4)?;
2015+ let y3 = run(&codes_3, 3)?;
2016+ let mut max_abs = 0f32;
2017+ let mut argmax_diff = 0usize;
2018+ for i in 0..y4.len() {
2019+ let dv = (y4[i] - y3[i]).abs();
2020+ if dv > max_abs {
2021+ max_abs = dv;
2022+ argmax_diff = i;
2023+ }
2024+ }
2025+ eprintln!(
2026+ "QCHECK out={} inn={} d={} : max|y4-y3|={:.6} at row {} (y4={:.4} y3={:.4})",
2027+ q.out, q.inn, q.d, max_abs, argmax_diff, y4[argmax_diff], y3[argmax_diff]
2028+ );
2029+ // Also check the FUSED bf16 kernel (no bias) vs the f32 3-bit
2030+ // kernel: rounded to bf16 they should match to ~1e-2.
2031+ let run_bf16 = |buf: &Arc<Buffer>, pb: u8| -> Result<Vec<f32>> {
2032+ let y = xr.apply_op1(QMatVecOp {
2033+ qw: QMatVecRef {
2034+ out: q.out,
2035+ inn: q.inn,
2036+ d: q.d,
2037+ codes: buf.clone(),
2038+ radius: radius.clone(),
2039+ codebook: q.codebook.clone(),
2040+ pack_bits: pb,
2041+ bias_bf16: None,
2042+ out_dtype: DType::BF16,
2043+ swiglu: false,
2044+ resid: None,
2045+ rot_sign: None,
2046+ },
2047+ tokens: 1,
2048+ })?;
2049+ Ok(y.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?)
2050+ };
2051+ let yb = run_bf16(&codes_3, 3)?;
2052+ // Bias check: feed a known all-1.0 bias; every output must gain +1.0.
2053+ let onebias: Vec<u16> = (0..q.out).map(|_| half::bf16::from_f32(1.0).to_bits()).collect();
2054+ let onebias_buf = cdev.new_buffer_with_data(&onebias)?;
2055+ let yb_bias = {
2056+ let y = xr.apply_op1(QMatVecOp {
2057+ qw: QMatVecRef {
2058+ out: q.out, inn: q.inn, d: q.d,
2059+ codes: codes_3.clone(), radius: radius.clone(),
2060+ codebook: q.codebook.clone(), pack_bits: 3,
2061+ bias_bf16: Some(onebias_buf), out_dtype: DType::BF16,
2062+ swiglu: false, resid: None, rot_sign: None,
2063+ }, tokens: 1,
2064+ })?;
2065+ y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?
2066+ };
2067+ let mut mbb = 0f32;
2068+ for i in 0..yb.len() {
2069+ let want = yb[i] + 1.0;
2070+ mbb = mbb.max((yb_bias[i] - want).abs());
2071+ }
2072+ eprintln!("QCHECK-BIAS out={} : max|(ybf16+1)-ybias|={:.6}", q.out, mbb);
2073+ // Residual-epilogue check on the DEFAULT runtime kernel (nibble,
2074+ // register-blocked QR=4): an all-1.0 residual must add exactly
2075+ // +1.0 to every output (the kernel adds resid in f32 before the
2076+ // single bf16 rounding — same structure as the bias check).
2077+ let yb4 = run_bf16(&codes_nib, 4)?;
2078+ let ones_resid = Tensor::ones((1, q.out), DType::BF16, device)?;
2079+ let yb_resid = {
2080+ let y = xr.apply_op1(QMatVecOp {
2081+ qw: QMatVecRef {
2082+ out: q.out, inn: q.inn, d: q.d,
2083+ codes: codes_nib.clone(), radius: radius.clone(),
2084+ codebook: q.codebook.clone(), pack_bits: 4,
2085+ bias_bf16: None, out_dtype: DType::BF16,
2086+ swiglu: false, resid: Some(ones_resid), rot_sign: None,
2087+ }, tokens: 1,
2088+ })?;
2089+ y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?
2090+ };
2091+ let mut mrr = 0f32;
2092+ for i in 0..yb4.len() {
2093+ let want = yb4[i] + 1.0;
2094+ mrr = mrr.max((yb_resid[i] - want).abs());
2095+ }
2096+ eprintln!("QCHECK-RESID out={} : max|(ybf16+1)-yresid|={:.6}", q.out, mrr);
2097+ let mut mb = 0f32;
2098+ let mut ab = 0usize;
2099+ for i in 0..y3.len() {
2100+ let dv = (y3[i] - yb[i]).abs();
2101+ if dv > mb { mb = dv; ab = i; }
2102+ }
2103+ eprintln!(
2104+ "QCHECK-BF16 out={} inn={} : max|y3-ybf16|={:.6} at row {} (y3={:.4} ybf16={:.4})",
2105+ q.out, q.inn, mb, ab, y3[ab], yb[ab]
2106+ );
2107+
2108+ // ── Fused-SwiGLU numerical self-test ──────────────────────────────
2109+ // Treat this weight's rows as a [gate(half); up(half)] pair and verify
2110+ // the fused kernel's silu(gate[i])·up[i] matches the reference computed
2111+ // from the plain nibble bf16 qmatvec (per-row dot products) + a CPU
2112+ // silu*mul. Requires an even row count.
2113+ if q.out % 2 == 0 && q.out >= 2 {
2114+ let half = q.out / 2;
2115+ // Reference: per-row dot products from the plain nibble bf16 kernel.
2116+ let yref = run_bf16(&codes_nib, 4)?; // length q.out
2117+ // Fused: swiglu kernel over the SAME nibble codes, out = half.
2118+ let yswi = {
2119+ let y = xr.apply_op1(QMatVecOp {
2120+ qw: QMatVecRef {
2121+ out: half,
2122+ inn: q.inn,
2123+ d: q.d,
2124+ codes: codes_nib.clone(),
2125+ radius: radius.clone(),
2126+ codebook: q.codebook.clone(),
2127+ pack_bits: 4,
2128+ bias_bf16: None,
2129+ out_dtype: DType::BF16,
2130+ swiglu: true,
2131+ resid: None,
2132+ rot_sign: None,
2133+ },
2134+ tokens: 1,
2135+ })?;
2136+ y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?
2137+ };
2138+ let mut msw = 0f32;
2139+ let mut asw = 0usize;
2140+ for i in 0..half {
2141+ let g = yref[i];
2142+ let u = yref[i + half];
2143+ let want = (g / (1.0 + (-g).exp())) * u; // silu(g)*u
2144+ let dv = (yswi[i] - want).abs();
2145+ if dv > msw { msw = dv; asw = i; }
2146+ }
2147+ eprintln!(
2148+ "QCHECK-SWIGLU out={} (half={}) inn={} : max|yfused-silu(g)*u|={:.6} at row {} (fused={:.4} ref={:.4})",
2149+ q.out, half, q.inn, msw, asw, yswi[asw],
2150+ { let g = yref[asw]; (g/(1.0+(-g).exp()))*yref[asw+half] }
2151+ );
2152+ }
2153+ }
2154+ }
2155+
2156+ let bias_bf16 = match &bias {
2157+ Some(b) => Some(bias_to_bf16_buf(b, cdev)?),
2158+ None => None,
2159+ };
2160+
2161+ Ok(Self {
2162+ out: q.out,
2163+ inn: q.inn,
2164+ d: q.d,
2165+ sign,
2166+ codes,
2167+ radius,
2168+ codebook: q.codebook.clone(),
2169+ bias,
2170+ bias_bf16,
2171+ pack_bits,
2172+ compressed_bytes,
2173+ })
2174+ }
2175+
2176+ /// Rotate an activation once: xr = blockFWHT(x ∘ sgn), per d-wide block.
2177+ /// `x` is [.., inn] on Metal; returns [tokens, inn] f32 (leading dims
2178+ /// flattened, contiguous). This is the launch-bound step we DEDUP: q/k/v all
2179+ /// consume the post-attn-norm hidden, gate/up both consume the post-mlp-norm
2180+ /// input — so the model rotates each shared input ONCE and feeds the result to
2181+ /// several `matmul_rotated` calls instead of re-rotating per projection
2182+ /// (~196 rotate dispatches/token → ~112).
2183+ ///
2184+ /// COCO_SKIP_ROTATE isolates the qmatvec cost (output becomes incoherent).
2185+ pub fn rotate(&self, x: &Tensor) -> Result<Tensor> {
2186+ let dims = x.dims().to_vec();
2187+ let inn = *dims.last().unwrap();
2188+ if inn != self.inn {
2189+ return Err(anyhow!(
2190+ "turboquant-fast: rotate input dim {inn} != weight inn {}",
2191+ self.inn
2192+ ));
2193+ }
2194+ let tokens: usize = dims[..dims.len() - 1].iter().product::<usize>().max(1);
2195+ // Feed the (bf16 or f32) hidden straight into the rotate kernel, which
2196+ // reads the input dtype directly — no candle `to_dtype(F32)` per rotate.
2197+ let xc = x.reshape((tokens, inn))?.contiguous()?;
2198+ if std::env::var("COCO_SKIP_ROTATE").is_ok() {
2199+ return Ok(xc.to_dtype(DType::F32)?); // profiling path; qmatvec wants f32
2200+ }
2201+ Ok(xc.apply_op1(RotateOp {
2202+ sign: self.sign.clone(),
2203+ d: self.d,
2204+ inn,
2205+ tokens,
2206+ })?)
2207+ }
2208+
2209+ /// Quantized matmul against the compressed codes, taking an ALREADY-ROTATED
2210+ /// input `xr` ([tokens, inn] f32 from `rotate`). Adds bias and restores the
2211+ /// requested leading shape. `lead_dims` are the leading dims of the original
2212+ /// (un-flattened) activation; `out_dtype` is the model dtype.
2213+ pub fn matmul_rotated(
2214+ &self,
2215+ xr: &Tensor,
2216+ lead_dims: &[usize],
2217+ out_dtype: DType,
2218+ ) -> Result<Tensor> {
2219+ self.matmul_rotated_resid(xr, lead_dims, out_dtype, None)
2220+ }
2221+
2222+ /// `matmul_rotated` + an optional fused residual: when `resid` is `Some` and
2223+ /// the fused bf16 path is active, the kernel's leader store adds
2224+ /// `resid[t,o]` (f32, before the single bf16 rounding) — no standalone candle
2225+ /// elementwise add dispatch. `resid` must be a contiguous bf16
2226+ /// [tokens, out]-shaped tensor (callers reshape/contiguous first).
2227+ fn matmul_rotated_resid(
2228+ &self,
2229+ xr: &Tensor,
2230+ lead_dims: &[usize],
2231+ out_dtype: DType,
2232+ resid: Option<&Tensor>,
2233+ ) -> Result<Tensor> {
2234+ let tokens: usize = lead_dims.iter().product::<usize>().max(1);
2235+ // BF16 model dtype → fused kernel writes bf16 + adds bias in-kernel; no
2236+ // candle to_dtype / broadcast_add. Other dtypes fall back to the f32
2237+ // kernel + candle epilogue (kept for completeness). COCO_NO_FUSE forces
2238+ // the f32 fallback (A/B + a safety escape hatch).
2239+ let fused = out_dtype == DType::BF16 && std::env::var("COCO_NO_FUSE").is_err();
2240+ let resid_t = match resid {
2241+ Some(r) if fused => Some(r.reshape((tokens, self.out))?.contiguous()?),
2242+ _ => None,
2243+ };
2244+ let mut y = xr.apply_op1(QMatVecOp {
2245+ qw: QMatVecRef {
2246+ out: self.out,
2247+ inn: self.inn,
2248+ d: self.d,
2249+ codes: self.codes.clone(),
2250+ radius: self.radius.clone(),
2251+ codebook: self.codebook.clone(),
2252+ pack_bits: self.pack_bits,
2253+ bias_bf16: if fused { self.bias_bf16.clone() } else { None },
2254+ out_dtype,
2255+ swiglu: false,
2256+ resid: resid_t,
2257+ rot_sign: None,
2258+ },
2259+ tokens,
2260+ })?; // [tokens, out] in out_dtype (fused) or f32 (fallback)
2261+
2262+ if !fused {
2263+ y = y.to_dtype(out_dtype)?;
2264+ if let Some(b) = &self.bias {
2265+ y = y.broadcast_add(b)?;
2266+ }
2267+ if let Some(r) = resid {
2268+ y = (y + r.reshape((tokens, self.out))?)?;
2269+ }
2270+ }
2271+ let mut out_dims = lead_dims.to_vec();
2272+ out_dims.push(self.out);
2273+ Ok(y.reshape(Shape::from_dims(&out_dims))?)
2274+ }
2275+
2276+ /// Expose the compressed parts needed by the FFN megakernel to do the
2277+ /// down-projection (its own rotation sign + codes/radius) reading the SwiGLU
2278+ /// intermediate straight from threadgroup memory. Only valid for the clean
2279+ /// nibble path (asserted by the caller's eligibility check).
2280+ pub fn ffn_down_parts(&self) -> (Arc<Buffer>, Arc<Buffer>, Tensor, usize, usize, usize, u8) {
2281+ (
2282+ self.codes.clone(),
2283+ self.radius.clone(),
2284+ self.sign.clone(),
2285+ self.d,
2286+ self.out,
2287+ self.inn,
2288+ self.pack_bits,
2289+ )
2290+ }
2291+
2292+ /// y = x @ Wᵀ (+ bias) with W kept compressed. x: [.., inn] on Metal.
2293+ /// Returns [.., out] in the same dtype as x. Standalone path (rotate + matmul)
2294+ /// kept for the o_proj / down_proj projections whose input is not shared; the
2295+ /// model dedups q/k/v and gate/up via the fused `QGroup` (one rotate + one
2296+ /// qmatvec over concatenated codes).
2297+ pub fn forward(&self, x: &Tensor) -> Result<Tensor> {
2298+ self.forward_opt(x, None)
2299+ }
2300+
2301+ /// y = x @ Wᵀ (+ bias) + resid — the residual folded into the qmatvec store
2302+ /// epilogue (COCO_FUSE_RESID, default ON). Falls back to `forward` + a candle
2303+ /// elementwise add when the fused epilogue can't engage (non-bf16 dtype,
2304+ /// COCO_NO_FUSE, or COCO_FUSE_RESID=0). `resid` must broadcast-match the
2305+ /// output shape [.., out] (it is the layer residual, same shape).
2306+ pub fn forward_resid(&self, x: &Tensor, resid: &Tensor) -> Result<Tensor> {
2307+ let fused = x.dtype() == DType::BF16
2308+ && std::env::var("COCO_NO_FUSE").is_err()
2309+ && fuse_resid_enabled();
2310+ if !fused {
2311+ return Ok((self.forward(x)? + resid)?);
2312+ }
2313+ self.forward_opt(x, Some(resid))
2314+ }
2315+
2316+ fn forward_opt(&self, x: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> {
2317+ let dims = x.dims().to_vec();
2318+ let in_dtype = x.dtype();
2319+ let lead = dims[..dims.len() - 1].to_vec();
2320+ let tokens: usize = lead.iter().product::<usize>().max(1);
2321+
2322+ // ROTATE-IN (COCO_FUSE_ROTATE_IN=1, experimental): skip the standalone
2323+ // rotate dispatch; the qmatvec kernel recomputes the FWHT of the input row
2324+ // in its threadgroup prologue. Engages for o_proj (inn = hidden fits the
2325+ // 32KB threadgroup budget); the down_proj row (inn = I) does NOT fit and
2326+ // keeps the separate rotate.
2327+ if rotate_in_eligible(self.inn, self.d, self.pack_bits, in_dtype, tokens) {
2328+ let xc = x.reshape((tokens, self.inn))?.contiguous()?;
2329+ let resid_t = match resid {
2330+ Some(r) => Some(r.reshape((tokens, self.out))?.contiguous()?),
2331+ None => None,
2332+ };
2333+ let y = xc.apply_op1(QMatVecOp {
2334+ qw: QMatVecRef {
2335+ out: self.out,
2336+ inn: self.inn,
2337+ d: self.d,
2338+ codes: self.codes.clone(),
2339+ radius: self.radius.clone(),
2340+ codebook: self.codebook.clone(),
2341+ pack_bits: self.pack_bits,
2342+ bias_bf16: self.bias_bf16.clone(),
2343+ out_dtype: in_dtype,
2344+ swiglu: false,
2345+ resid: resid_t,
2346+ rot_sign: Some(self.sign.clone()),
2347+ },
2348+ tokens,
2349+ })?;
2350+ // One-shot numerical self-test (COCO_QCHECK): rotate-in vs the
2351+ // separate rotate + qmatvec reference on the same live activation.
2352+ if std::env::var("COCO_QCHECK").is_ok() {
2353+ static ROTIN_QCHECK: OnceLock<()> = OnceLock::new();
2354+ if ROTIN_QCHECK.set(()).is_ok() {
2355+ let xr = self.rotate(x)?;
2356+ let yref =
2357+ self.matmul_rotated_resid(&xr, &[tokens], in_dtype, resid)?;
2358+ let a = y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?;
2359+ let b = yref.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?;
2360+ let mut m = 0f32;
2361+ for i in 0..a.len().min(b.len()) {
2362+ m = m.max((a[i] - b[i]).abs());
2363+ }
2364+ eprintln!(
2365+ "QCHECK-ROTIN out={} inn={} : max|yrot-yref|={:.6}",
2366+ self.out, self.inn, m
2367+ );
2368+ }
2369+ }
2370+ let mut out_dims = lead.clone();
2371+ out_dims.push(self.out);
2372+ return Ok(y.reshape(Shape::from_dims(&out_dims))?);
2373+ }
2374+
2375+ let xr = self.rotate(x)?;
2376+ self.matmul_rotated_resid(&xr, &lead, in_dtype, resid)
2377+ }
2378+}
2379+
2380+// ───────────────────────── fused group of shared-input projections ─────────────────────────
2381+
2382+/// One sub-projection inside a fused `QGroup`: its output width, the row offset
2383+/// into the concatenated output, and its (already-on-device) bias.
2384+pub(crate) struct QSub {
2385+ pub(crate) out: usize,
2386+ pub(crate) row_off: usize,
2387+ pub(crate) bias: Option<Tensor>,
2388+}
2389+
2390+/// A set of compressed projections that all consume the SAME input activation and
2391+/// share the SAME rotation (same `inn`, same sign) — q/k/v (post-attn-norm) and
2392+/// gate/up (post-mlp-norm). Their codes + radius are CONCATENATED row-wise into a
2393+/// single GPU buffer, so the whole group runs as ONE rotate + ONE qmatvec
2394+/// dispatch (out = Σ out_i) instead of N+N. This halves the qmatvec/rotate launch
2395+/// count for the attention and MLP input projections — the dominant remaining
2396+/// per-token overhead once activations stay on-GPU.
2397+pub struct QGroup {
2398+ pub(crate) inn: usize,
2399+ pub(crate) d: usize,
2400+ pub(crate) out_total: usize,
2401+ pub(crate) sign: Tensor,
2402+ // Held as `Arc<Buffer>` to pin against candle's pool recycler (see QWeight).
2403+ pub(crate) codes: Arc<Buffer>, // concatenated packed codes for all sub-projections
2404+ pub(crate) radius: Arc<Buffer>, // concatenated fp16 radii
2405+ pub(crate) codebook: Vec<f32>,
2406+ pub(crate) pack_bits: u8,
2407+ pub(crate) subs: Vec<QSub>,
2408+ /// Concatenated per-row bias (length `out_total`) as a BF16 device buffer for
2409+ /// the fused qmatvec epilogue: the single fused dispatch adds each row's bias
2410+ /// in-kernel. Zero-filled rows where a sub has no bias. `None` if NO sub in the
2411+ /// group has a bias (e.g. gate/up). Held as `Arc<Buffer>` to pin it against
2412+ /// candle's pool recycler (see `QWeight::bias_bf16`).
2413+ pub(crate) bias_bf16: Option<Arc<Buffer>>,
2414+ pub compressed_bytes: usize,
2415+}
2416+
2417+impl QGroup {
2418+ /// Build a fused group from several `TqWeight`s that share `inn`/seed/d (so
2419+ /// the rotation sign is identical). `biases[i]` is the bias for sub i (already
2420+ /// on `device`, model dtype). Concatenates the packed codes + radii into single
2421+ /// device buffers; the qmatvec then grids over the summed output rows.
2422+ pub fn from_tqs(
2423+ qs: &[&TqWeight],
2424+ biases: Vec<Option<Tensor>>,
2425+ device: &Device,
2426+ ) -> Result<Self> {
2427+ let cdev = match device {
2428+ Device::Metal(m) => m,
2429+ _ => return Err(anyhow!("turboquant-fast requires the Metal device")),
2430+ };
2431+ let first = qs[0];
2432+ let inn = first.inn;
2433+ let d = first.d;
2434+ let pack_bits = pack_bits_from_env();
2435+ for q in qs {
2436+ if !q.block_hadamard || !q.outlier_idx.is_empty() || q.bits != 3 {
2437+ return Err(anyhow!("QGroup requires the clean 3-bit block recipe"));
2438+ }
2439+ if q.inn != inn || q.d != d || q.seed != first.seed {
2440+ return Err(anyhow!(
2441+ "QGroup members must share inn/d/seed (same rotation)"
2442+ ));
2443+ }
2444+ }
2445+
2446+ let sign_v = turboquant::signs(first.p, first.seed);
2447+ let sign = Tensor::from_vec(sign_v, inn, device)?;
2448+
2449+ // Concatenate packed codes + radii row-wise (row-major [out_i, inn]).
2450+ let mut all_codes: Vec<u8> = Vec::new();
2451+ let mut all_rad: Vec<u16> = Vec::new();
2452+ let mut subs = Vec::with_capacity(qs.len());
2453+ let mut row_off = 0usize;
2454+ for (i, q) in qs.iter().enumerate() {
2455+ let packed = if pack_bits == 3 {
2456+ q.codes_packed_3bit()
2457+ } else {
2458+ q.codes_packed_nibble()
2459+ };
2460+ all_codes.extend_from_slice(&packed);
2461+ all_rad.extend(q.radius.iter().map(|r| r.to_bits()));
2462+ subs.push(QSub {
2463+ out: q.out,
2464+ row_off,
2465+ bias: biases[i].clone(),
2466+ });
2467+ row_off += q.out;
2468+ }
2469+ let out_total = row_off;
2470+ let compressed_bytes = all_codes.len() + all_rad.len() * 2 + first.codebook.len() * 4;
2471+ let codes = cdev.new_buffer_with_data(&all_codes)?;
2472+ let radius = cdev.new_buffer_with_data(&all_rad)?;
2473+
2474+ // Build ONE concatenated BF16 bias buffer (length out_total) so the single
2475+ // fused qmatvec adds every row's bias in its epilogue. Zero where a sub has
2476+ // no bias. Only allocate if at least one sub carries a bias.
2477+ let any_bias = subs.iter().any(|s| s.bias.is_some());
2478+ let bias_bf16 = if any_bias {
2479+ let mut bits = vec![0u16; out_total]; // bf16 0.0 == bit pattern 0
2480+ for sub in &subs {
2481+ if let Some(b) = &sub.bias {
2482+ let bb = b.to_dtype(DType::BF16)?.flatten_all()?;
2483+ let vals: Vec<half::bf16> = bb.to_vec1()?;
2484+ for (j, v) in vals.iter().enumerate() {
2485+ bits[sub.row_off + j] = v.to_bits();
2486+ }
2487+ }
2488+ }
2489+ Some(cdev.new_buffer_with_data(&bits)?)
2490+ } else {
2491+ None
2492+ };
2493+
2494+ Ok(Self {
2495+ inn,
2496+ d,
2497+ out_total,
2498+ sign,
2499+ codes,
2500+ radius,
2501+ codebook: first.codebook.clone(),
2502+ pack_bits,
2503+ subs,
2504+ bias_bf16,
2505+ compressed_bytes,
2506+ })
2507+ }
2508+
2509+ /// One rotate + one qmatvec over the whole group, then split the concatenated
2510+ /// output into per-projection tensors (+ bias, original leading shape).
2511+ pub fn forward(&self, x: &Tensor) -> Result<Vec<Tensor>> {
2512+ let dims = x.dims().to_vec();
2513+ let in_dtype = x.dtype();
2514+ let lead: Vec<usize> = dims[..dims.len() - 1].to_vec();
2515+ let inn = *dims.last().unwrap();
2516+ if inn != self.inn {
2517+ return Err(anyhow!("QGroup: input dim {inn} != {}", self.inn));
2518+ }
2519+ let tokens: usize = lead.iter().product::<usize>().max(1);
2520+
2521+ // Rotate once (shared sign). The bf16 hidden goes STRAIGHT into the rotate
2522+ // kernel (which converts on load) — no candle `to_dtype(F32)` + `contiguous`
2523+ // before every rotate. We only ensure contiguity (a no-op when already
2524+ // contiguous, e.g. decode's [1, inn]).
2525+ let xc = x.reshape((tokens, inn))?.contiguous()?;
2526+ let fused = in_dtype == DType::BF16 && std::env::var("COCO_NO_FUSE").is_err();
2527+ // ROTATE-IN (COCO_FUSE_ROTATE_IN=1): the qkv group's shared rotate folds
2528+ // into the qmatvec prologue — one dispatch for the whole group.
2529+ let rot_in =
2530+ fused && rotate_in_eligible(self.inn, self.d, self.pack_bits, in_dtype, tokens);
2531+ // Single fused qmatvec over the concatenated rows. When the model dtype is
2532+ // BF16 (always on Metal), the kernel writes bf16 directly AND adds each
2533+ // row's concatenated bias in its epilogue — so the whole group's dtype
2534+ // conversion + all per-sub bias-adds collapse into the one qmatvec. The
2535+ // f32 fallback (COCO_NO_FUSE) keeps candle's to_dtype + per-sub
2536+ // broadcast_add.
2537+ let y = if rot_in {
2538+ let y = xc.apply_op1(QMatVecOp {
2539+ qw: QMatVecRef {
2540+ out: self.out_total,
2541+ inn: self.inn,
2542+ d: self.d,
2543+ codes: self.codes.clone(),
2544+ radius: self.radius.clone(),
2545+ codebook: self.codebook.clone(),
2546+ pack_bits: self.pack_bits,
2547+ bias_bf16: self.bias_bf16.clone(),
2548+ out_dtype: in_dtype,
2549+ swiglu: false,
2550+ resid: None,
2551+ rot_sign: Some(self.sign.clone()),
2552+ },
2553+ tokens,
2554+ })?;
2555+ // One-shot self-test (COCO_QCHECK): rotate-in group vs the separate
2556+ // rotate + qmatvec reference on the same live activation.
2557+ if std::env::var("COCO_QCHECK").is_ok() {
2558+ static GROUP_ROTIN_QCHECK: OnceLock<()> = OnceLock::new();
2559+ if GROUP_ROTIN_QCHECK.set(()).is_ok() {
2560+ let xr = xc.apply_op1(RotateOp {
2561+ sign: self.sign.clone(),
2562+ d: self.d,
2563+ inn,
2564+ tokens,
2565+ })?;
2566+ let yref = xr.apply_op1(QMatVecOp {
2567+ qw: QMatVecRef {
2568+ out: self.out_total,
2569+ inn: self.inn,
2570+ d: self.d,
2571+ codes: self.codes.clone(),
2572+ radius: self.radius.clone(),
2573+ codebook: self.codebook.clone(),
2574+ pack_bits: self.pack_bits,
2575+ bias_bf16: self.bias_bf16.clone(),
2576+ out_dtype: in_dtype,
2577+ swiglu: false,
2578+ resid: None,
2579+ rot_sign: None,
2580+ },
2581+ tokens,
2582+ })?;
2583+ let a = y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?;
2584+ let b = yref.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?;
2585+ let mut m = 0f32;
2586+ for i in 0..a.len().min(b.len()) {
2587+ m = m.max((a[i] - b[i]).abs());
2588+ }
2589+ eprintln!(
2590+ "QCHECK-ROTIN-GROUP out={} inn={} : max|yrot-yref|={:.6}",
2591+ self.out_total, self.inn, m
2592+ );
2593+ }
2594+ }
2595+ y
2596+ } else {
2597+ let xr = if std::env::var("COCO_SKIP_ROTATE").is_ok() {
2598+ // Profiling-only path; qmatvec wants f32 xr, so convert here.
2599+ xc.to_dtype(DType::F32)?
2600+ } else {
2601+ xc.apply_op1(RotateOp {
2602+ sign: self.sign.clone(),
2603+ d: self.d,
2604+ inn,
2605+ tokens,
2606+ })?
2607+ };
2608+ xr.apply_op1(QMatVecOp {
2609+ qw: QMatVecRef {
2610+ out: self.out_total,
2611+ inn: self.inn,
2612+ d: self.d,
2613+ codes: self.codes.clone(),
2614+ radius: self.radius.clone(),
2615+ codebook: self.codebook.clone(),
2616+ pack_bits: self.pack_bits,
2617+ bias_bf16: if fused { self.bias_bf16.clone() } else { None },
2618+ out_dtype: in_dtype,
2619+ swiglu: false,
2620+ resid: None,
2621+ rot_sign: None,
2622+ },
2623+ tokens,
2624+ })?
2625+ };
2626+ let y = if fused { y } else { y.to_dtype(in_dtype)? };
2627+
2628+ // Split into per-projection slices (zero-copy narrow), restore leading
2629+ // shape. In the fused path the bias is already in `y`; only the f32
2630+ // fallback needs the per-sub broadcast_add here.
2631+ let mut outs = Vec::with_capacity(self.subs.len());
2632+ for sub in &self.subs {
2633+ let mut yi = y.narrow(1, sub.row_off, sub.out)?;
2634+ if !fused {
2635+ if let Some(b) = &sub.bias {
2636+ yi = yi.broadcast_add(b)?;
2637+ }
2638+ }
2639+ let mut out_dims = lead.clone();
2640+ out_dims.push(sub.out);
2641+ outs.push(yi.reshape(Shape::from_dims(&out_dims))?);
2642+ }
2643+ Ok(outs)
2644+ }
2645+
2646+ /// FUSED SwiGLU forward for a 2-sub gate/up group: one rotate + one qmatvec that
2647+ /// emits `silu(gate)·up` DIRECTLY (intermediate width I), collapsing the separate
2648+ /// candle `silu` + `mul` element-wise passes into the qmatvec store epilogue.
2649+ /// Requires exactly two subs of equal width (gate then up), no bias, the bf16 +
2650+ /// 4-bit nibble path. Falls back via `Ok(None)` when those preconditions don't
2651+ /// hold (caller then uses `forward` + candle silu*mul). Gated by COCO_FUSE_SWIGLU
2652+ /// (default ON) at the call site.
2653+ pub fn forward_swiglu(&self, x: &Tensor) -> Result<Option<Tensor>> {
2654+ // Preconditions: exactly [gate; up], equal width, biasless, bf16+nibble.
2655+ let in_dtype = x.dtype();
2656+ let eligible = self.subs.len() == 2
2657+ && self.subs[0].out == self.subs[1].out
2658+ && self.subs[0].row_off == 0
2659+ && self.subs[1].row_off == self.subs[0].out
2660+ && self.subs.iter().all(|s| s.bias.is_none())
2661+ && self.pack_bits != 3 // swiglu kernel is the 4-bit nibble variant
2662+ && in_dtype == DType::BF16
2663+ && std::env::var("COCO_NO_FUSE").is_err();
2664+ if !eligible {
2665+ return Ok(None);
2666+ }
2667+ let half = self.subs[0].out; // I (intermediate / SwiGLU output width)
2668+
2669+ let dims = x.dims().to_vec();
2670+ let lead: Vec<usize> = dims[..dims.len() - 1].to_vec();
2671+ let inn = *dims.last().unwrap();
2672+ if inn != self.inn {
2673+ return Err(anyhow!("QGroup(swiglu): input dim {inn} != {}", self.inn));
2674+ }
2675+ let tokens: usize = lead.iter().product::<usize>().max(1);
2676+
2677+ let xc = x.reshape((tokens, inn))?.contiguous()?;
2678+
2679+ // ROTATE-IN (COCO_FUSE_ROTATE_IN=1): the gate/up shared rotate folds into
2680+ // the swiglu qmatvec prologue (tq_qmatvec_swiglu_rot) — one dispatch.
2681+ if rotate_in_eligible(self.inn, self.d, self.pack_bits, in_dtype, tokens) {
2682+ let y = xc.apply_op1(QMatVecOp {
2683+ qw: QMatVecRef {
2684+ out: half,
2685+ inn: self.inn,
2686+ d: self.d,
2687+ codes: self.codes.clone(),
2688+ radius: self.radius.clone(),
2689+ codebook: self.codebook.clone(),
2690+ pack_bits: self.pack_bits,
2691+ bias_bf16: None,
2692+ out_dtype: in_dtype,
2693+ swiglu: true,
2694+ resid: None,
2695+ rot_sign: Some(self.sign.clone()),
2696+ },
2697+ tokens,
2698+ })?;
2699+ // One-shot self-test (COCO_QCHECK): rotate-in swiglu vs the separate
2700+ // rotate + swiglu-qmatvec reference on the same live activation.
2701+ if std::env::var("COCO_QCHECK").is_ok() {
2702+ static SWIGLU_ROTIN_QCHECK: OnceLock<()> = OnceLock::new();
2703+ if SWIGLU_ROTIN_QCHECK.set(()).is_ok() {
2704+ let xr = xc.apply_op1(RotateOp {
2705+ sign: self.sign.clone(),
2706+ d: self.d,
2707+ inn,
2708+ tokens,
2709+ })?;
2710+ let yref = xr.apply_op1(QMatVecOp {
2711+ qw: QMatVecRef {
2712+ out: half,
2713+ inn: self.inn,
2714+ d: self.d,
2715+ codes: self.codes.clone(),
2716+ radius: self.radius.clone(),
2717+ codebook: self.codebook.clone(),
2718+ pack_bits: self.pack_bits,
2719+ bias_bf16: None,
2720+ out_dtype: in_dtype,
2721+ swiglu: true,
2722+ resid: None,
2723+ rot_sign: None,
2724+ },
2725+ tokens,
2726+ })?;
2727+ let a = y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?;
2728+ let b = yref.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?;
2729+ let mut m = 0f32;
2730+ for i in 0..a.len().min(b.len()) {
2731+ m = m.max((a[i] - b[i]).abs());
2732+ }
2733+ eprintln!(
2734+ "QCHECK-ROTIN-SWIGLU I={half} inn={} : max|yrot-yref|={:.6}",
2735+ self.inn, m
2736+ );
2737+ }
2738+ }
2739+ let mut out_dims = lead.clone();
2740+ out_dims.push(half);
2741+ return Ok(Some(y.reshape(Shape::from_dims(&out_dims))?));
2742+ }
2743+
2744+ // Rotate once (shared sign), straight from the bf16 hidden (no candle
2745+ // to_dtype/contiguous beyond the cheap reshape-contiguous).
2746+ let xr = xc.apply_op1(RotateOp {
2747+ sign: self.sign.clone(),
2748+ d: self.d,
2749+ inn,
2750+ tokens,
2751+ })?;
2752+
2753+ // One fused SwiGLU qmatvec: codes/radius are the full [gate(I); up(I)]
2754+ // concatenation; `out = half` makes the kernel grid over I gate rows and pair
2755+ // each with up row (o + I), storing silu(gate)·up. Output is [tokens, I].
2756+ let y = xr.apply_op1(QMatVecOp {
2757+ qw: QMatVecRef {
2758+ out: half,
2759+ inn: self.inn,
2760+ d: self.d,
2761+ codes: self.codes.clone(),
2762+ radius: self.radius.clone(),
2763+ codebook: self.codebook.clone(),
2764+ pack_bits: self.pack_bits,
2765+ bias_bf16: None,
2766+ out_dtype: in_dtype,
2767+ swiglu: true,
2768+ resid: None,
2769+ rot_sign: None,
2770+ },
2771+ tokens,
2772+ })?;
2773+
2774+ let mut out_dims = lead.clone();
2775+ out_dims.push(half);
2776+ Ok(Some(y.reshape(Shape::from_dims(&out_dims))?))
2777+ }
2778+
2779+ /// FFN MEGAKERNEL (default-on, COCO_FFN_MEGA != "0"): run the WHOLE FFN
2780+ /// (gate/up SwiGLU → down-rotate → down-matmul) in ONE dispatch, keeping the
2781+ /// I-wide intermediate `h` in threadgroup memory the whole time. This removes
2782+ /// the I→I device round-trip of `h`, the separate down-rotate dispatch, and the
2783+ /// GPU barrier between the swiglu-qmatvec and the down path. `self` must be the
2784+ /// gate/up group; `down` is the down_proj weight. Returns `None` (→ caller uses
2785+ /// the swiglu + separate-down fallback) when ineligible:
2786+ /// * gate/up not swiglu-eligible (same checks as `forward_swiglu`), OR
2787+ /// * I > 14336 (h would not fit the 32KB threadgroup as bf16 — e.g. 7B
2788+ /// I=18944; those fall back automatically — tiling is out of scope), OR
2789+ /// * down is not the matching nibble/d recipe.
2790+ /// The gate/up rotate of the input stays a separate (cheap) dispatch — it is
2791+ /// the swiglu↔down fusion that this kernel buys.
2792+ pub fn forward_ffn_mega(&self, x: &Tensor, down: &QWeight) -> Result<Option<Tensor>> {
2793+ // OPT-IN ONLY (COCO_FFN_MEGA=1). The one-threadgroup-per-token megakernel is
2794+ // numerically correct (QCHECK 1 ULP) but ~20x SLOWER: collapsing the whole FFN
2795+ // onto a single threadgroup serializes it and starves the GPU of parallelism.
2796+ // The h round-trip it saves (~3.8% of traffic) is dwarfed by the lost occupancy.
2797+ // Kept behind a flag as a documented dead-end; the default is the parallel path.
2798+ if std::env::var("COCO_FFN_MEGA").as_deref() != Ok("1") {
2799+ return Ok(None);
2800+ }
2801+ let in_dtype = x.dtype();
2802+ let eligible = self.subs.len() == 2
2803+ && self.subs[0].out == self.subs[1].out
2804+ && self.subs[0].row_off == 0
2805+ && self.subs[1].row_off == self.subs[0].out
2806+ && self.subs.iter().all(|s| s.bias.is_none())
2807+ && self.pack_bits != 3
2808+ && in_dtype == DType::BF16
2809+ && std::env::var("COCO_NO_FUSE").is_err();
2810+ if !eligible {
2811+ return Ok(None);
2812+ }
2813+ let big_i = self.subs[0].out; // I (intermediate width)
2814+ // Guard: h must fit the 32KB threadgroup as bf16 (hbuf is [14336] bfloat).
2815+ if big_i > 14336 {
2816+ return Ok(None);
2817+ }
2818+
2819+ let (dn_codes, dn_radius, dn_sign, dn_d, dn_out, dn_inn, dn_pack) = down.ffn_down_parts();
2820+ // down must be the nibble recipe, consume the I-wide h, share the block size,
2821+ // and emit the hidden width (= gate/up inn here).
2822+ if dn_pack == 3 || dn_inn != big_i || dn_d != self.d || dn_out != self.inn {
2823+ return Ok(None);
2824+ }
2825+ // One-shot activation marker (COCO_FFN_MEGA_DBG=1): proves the megakernel
2826+ // is the path actually taken (vs a silent fallback), once per process.
2827+ if std::env::var("COCO_FFN_MEGA_DBG").is_ok() {
2828+ static MEGA_SEEN: OnceLock<()> = OnceLock::new();
2829+ if MEGA_SEEN.set(()).is_ok() {
2830+ eprintln!(
2831+ "FFN-MEGA active: I={big_i} hidden={dn_out} d={} (h threadgroup bytes = {})",
2832+ self.d,
2833+ big_i * 2
2834+ );
2835+ }
2836+ }
2837+
2838+ let dims = x.dims().to_vec();
2839+ let lead: Vec<usize> = dims[..dims.len() - 1].to_vec();
2840+ let inn = *dims.last().unwrap();
2841+ if inn != self.inn {
2842+ return Err(anyhow!("QGroup(ffn_mega): input dim {inn} != {}", self.inn));
2843+ }
2844+ let tokens: usize = lead.iter().product::<usize>().max(1);
2845+
2846+ // Rotate the post-mlp-norm input ONCE (gate/up sign), exactly as the swiglu
2847+ // path does — that rotate stays a separate, cheap dispatch.
2848+ let xc = x.reshape((tokens, inn))?.contiguous()?;
2849+ let xr = xc.apply_op1(RotateOp {
2850+ sign: self.sign.clone(),
2851+ d: self.d,
2852+ inn,
2853+ tokens,
2854+ })?;
2855+
2856+ // ONE megakernel dispatch: swiglu → rotate(h) → down, h on-chip. Output is
2857+ // [tokens, hidden] bf16.
2858+ let y = xr.apply_op1(FfnMegaOp {
2859+ inn: self.inn,
2860+ big_i,
2861+ d: self.d,
2862+ hidden: dn_out,
2863+ gu_codes: self.codes.clone(),
2864+ gu_radius: self.radius.clone(),
2865+ codebook: self.codebook.clone(),
2866+ dn_codes,
2867+ dn_radius,
2868+ dn_sign,
2869+ tokens,
2870+ })?;
2871+
2872+ // ── Megakernel numerical self-test (COCO_QCHECK, once per process) ──
2873+ // Compare the fused-FFN output against the reference path: swiglu (h) →
2874+ // down.forward(h) (separate rotate + qmatvec). They should match to bf16
2875+ // rounding of h (both round h to bf16 before down). Reports max abs diff.
2876+ if std::env::var("COCO_QCHECK").is_ok() {
2877+ static FFNMEGA_QCHECK: OnceLock<()> = OnceLock::new();
2878+ if FFNMEGA_QCHECK.set(()).is_ok() {
2879+ if let Some(h) = self.forward_swiglu(x)? {
2880+ let yref = down.forward(&h)?;
2881+ let a = y
2882+ .reshape((tokens, dn_out))?
2883+ .to_dtype(DType::F32)?
2884+ .flatten_all()?
2885+ .to_vec1::<f32>()?;
2886+ let b = yref
2887+ .reshape((tokens, dn_out))?
2888+ .to_dtype(DType::F32)?
2889+ .flatten_all()?
2890+ .to_vec1::<f32>()?;
2891+ let mut m = 0f32;
2892+ let mut ai = 0usize;
2893+ for i in 0..a.len().min(b.len()) {
2894+ let dv = (a[i] - b[i]).abs();
2895+ if dv > m {
2896+ m = dv;
2897+ ai = i;
2898+ }
2899+ }
2900+ eprintln!(
2901+ "QCHECK-FFNMEGA I={big_i} hidden={dn_out} : max|ymega-yref|={:.6} at {} (mega={:.4} ref={:.4})",
2902+ m, ai, a[ai], b[ai]
2903+ );
2904+ }
2905+ }
2906+ }
2907+
2908+ let mut out_dims = lead.clone();
2909+ out_dims.push(dn_out);
2910+ Ok(Some(y.reshape(Shape::from_dims(&out_dims))?))
2911+ }
2912+}
2913+
2914+// ───────────────────────── CustomOp1: rotate activation ─────────────────────────
2915+
2916+struct RotateOp {
2917+ sign: Tensor,
2918+ d: usize,
2919+ inn: usize,
2920+ tokens: usize,
2921+}
2922+
2923+impl CustomOp1 for RotateOp {
2924+ fn name(&self) -> &'static str {
2925+ "tq_rotate"
2926+ }
2927+
2928+ fn cpu_fwd(&self, _s: &CpuStorage, _l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> {
2929+ Err(candle_core::Error::Msg(
2930+ "tq_rotate has no CPU implementation (Metal only)".into(),
2931+ ))
2932+ }
2933+
2934+ fn metal_fwd(
2935+ &self,
2936+ storage: &candle_core::MetalStorage,
2937+ layout: &Layout,
2938+ ) -> candle_core::Result<(candle_core::MetalStorage, Shape)> {
2939+ use objc2_metal::MTLSize;
2940+ let dev = storage.device().clone();
2941+ let mdev = dev.metal_device();
2942+ let pipes = get_pipelines(mdev).map_err(wrap)?;
2943+
2944+ let inn = self.inn as u32;
2945+ let d = self.d as u32;
2946+ let nblocks = (self.inn / self.d) as u32;
2947+
2948+ // fresh output buffer; the kernel reads x and writes xr (no blit copy).
2949+ let elem = self.tokens * self.inn;
2950+ let out_buf = dev.new_buffer(elem, DType::F32, "tq_rotate")?;
2951+ let out_ref: &Buffer = &out_buf;
2952+
2953+ // Pick the kernel by INPUT dtype: bf16 input is read & converted in-kernel
2954+ // (no candle to_dtype/contiguous), f32 input uses the original path.
2955+ let in_dt = storage.dtype();
2956+ let (rot_pipe, in_off) = match in_dt {
2957+ DType::BF16 => (&pipes.rotate_bf16, layout.start_offset() * DType::BF16.size_in_bytes()),
2958+ DType::F32 => (&pipes.rotate, layout.start_offset() * DType::F32.size_in_bytes()),
2959+ other => {
2960+ return Err(candle_core::Error::Msg(format!(
2961+ "tq_rotate: unsupported input dtype {other:?}"
2962+ )))
2963+ }
2964+ };
2965+
2966+ let sign_storage = self.sign.storage_and_layout().0;
2967+ let sign_buf = match &*sign_storage {
2968+ candle_core::Storage::Metal(s) => s.buffer().clone(),
2969+ _ => return Err(candle_core::Error::Msg("sign not on metal".into())),
2970+ };
2971+
2972+ let enc = dev.command_encoder()?;
2973+ let ce: &ComputeCommandEncoder = enc.as_ref();
2974+ ce.set_compute_pipeline_state(rot_pipe);
2975+ ce.set_input_buffer(0, Some(storage.buffer()), in_off);
2976+ ce.set_output_buffer(1, Some(out_ref), 0);
2977+ ce.set_input_buffer(2, Some(&sign_buf), 0);
2978+ ce.set_bytes(3, &inn);
2979+ ce.set_bytes(4, &d);
2980+ // grid is in THREADGROUPS: one group per (block, token); kernel reads
2981+ // blk = tg.y, tok = tg.z. Each group has `d` threads (the d-block).
2982+ let grid = MTLSize {
2983+ width: 1,
2984+ height: nblocks as usize,
2985+ depth: self.tokens,
2986+ };
2987+ let tgroup = MTLSize { width: self.d, height: 1, depth: 1 };
2988+ ce.dispatch_thread_groups(grid, tgroup);
2989+ drop(enc);
2990+
2991+ let news = candle_core::MetalStorage::new(out_buf, dev.clone(), elem, DType::F32);
2992+ Ok((news, layout.shape().clone()))
2993+ }
2994+}
2995+
2996+// ───────────────────────── CustomOp1: quantized matmul ─────────────────────────
2997+
2998+#[derive(Clone)]
2999+struct QMatVecRef {
3000+ out: usize,
3001+ inn: usize,
3002+ d: usize,
3003+ codes: Arc<Buffer>,
3004+ radius: Arc<Buffer>,
3005+ codebook: Vec<f32>,
3006+ pack_bits: u8, // 3 = true 3-bit kernel, 4 = nibble kernel
3007+ /// Optional per-row bias kept on-device as BF16 (length `out`). When `Some`
3008+ /// AND the requested output dtype is BF16, the fused kernel writes bf16 and
3009+ /// adds this bias in its epilogue — no candle `to_dtype`/`broadcast_add`.
3010+ /// `Arc<Buffer>` so the pin (vs candle's recycling pool) is carried along.
3011+ bias_bf16: Option<Arc<Buffer>>,
3012+ /// Output dtype. BF16 → fused bf16 epilogue kernel; anything else (e.g. the
3013+ /// f32 QCHECK path) → the legacy f32 kernel (caller does to_dtype/bias).
3014+ out_dtype: DType,
3015+ /// Fused SwiGLU: `codes`/`radius` hold a [gate(I); up(I)] concatenation
3016+ /// (2*`out` rows) and the kernel emits `silu(gate)·up` of width `out` (= I).
3017+ /// Only valid for the bf16 + nibble path (gate/up never carry a bias).
3018+ swiglu: bool,
3019+ /// Optional residual added in the leader-store epilogue (fused bf16
3020+ /// non-swiglu kernels): y[t,o] = dot + bias + resid[t,o]. Must be a
3021+ /// CONTIGUOUS bf16 [tokens, out] tensor on the device (COCO_FUSE_RESID).
3022+ resid: Option<Tensor>,
3023+ /// When `Some(sign)`, the op INPUT is the UNROTATED bf16 activation and the
3024+ /// rotate-in kernel recomputes the blockwise FWHT in a threadgroup-memory
3025+ /// prologue (COCO_FUSE_ROTATE_IN). `sign` is the [inn] f32 ±1 vector.
3026+ rot_sign: Option<Tensor>,
3027+}
3028+
3029+struct QMatVecOp {
3030+ qw: QMatVecRef,
3031+ tokens: usize,
3032+}
3033+
3034+impl CustomOp1 for QMatVecOp {
3035+ fn name(&self) -> &'static str {
3036+ "tq_qmatvec"
3037+ }
3038+
3039+ fn cpu_fwd(&self, _s: &CpuStorage, _l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> {
3040+ Err(candle_core::Error::Msg(
3041+ "tq_qmatvec has no CPU implementation (Metal only)".into(),
3042+ ))
3043+ }
3044+
3045+ fn metal_fwd(
3046+ &self,
3047+ storage: &candle_core::MetalStorage,
3048+ layout: &Layout,
3049+ ) -> candle_core::Result<(candle_core::MetalStorage, Shape)> {
3050+ use objc2_metal::MTLSize;
3051+ let dev = storage.device().clone();
3052+ let mdev = dev.metal_device();
3053+ let pipes = get_pipelines(mdev).map_err(wrap)?;
3054+
3055+ let inn = self.qw.inn as u32;
3056+ let out_dim = self.qw.out as u32;
3057+ let d = self.qw.d as u32;
3058+ let tokens = self.tokens as u32;
3059+
3060+ let out_elems = self.tokens * self.qw.out;
3061+ // Input is the rotated f32 xr — or, on the rotate-in path, the UNROTATED
3062+ // bf16 activation (the kernel rotates it in its threadgroup prologue).
3063+ let xr_off = layout.start_offset() * storage.dtype().size_in_bytes();
3064+ let rot_on = self.qw.rot_sign.is_some();
3065+
3066+ // Fused epilogue path: output bf16 directly + add the per-row bias in the
3067+ // kernel (no candle to_dtype/broadcast_add). Used whenever the model dtype
3068+ // is BF16 (always true on Metal). The f32 path stays for the QCHECK self-
3069+ // test, which compares kernels in f32.
3070+ let fused_bf16 = self.qw.out_dtype == DType::BF16;
3071+ let out_dt = if fused_bf16 { DType::BF16 } else { DType::F32 };
3072+ let out_buf = dev.new_buffer(out_elems, out_dt, "tq_qmatvec")?;
3073+ let out_ref: &Buffer = &out_buf;
3074+
3075+ // Register-blocked nibble kernel (QROWS output rows per simd-group) is the
3076+ // throughput default for the fused bf16 + 4-bit path: it amortizes the
3077+ // activation load across rows. COCO_QROWS selects the width:
3078+ // "0" → single-row kernel (A/B baseline)
3079+ // "8" → wider register blocking (8 rows/group, tq_qmatvec_bf16_r8)
3080+ // else (default "4") → tq_qmatvec_bf16_r
3081+ let qrows_env = std::env::var("COCO_QROWS").ok();
3082+ let qrows_sel: usize = match qrows_env.as_deref() {
3083+ Some("0") => 0,
3084+ Some("8") => 8,
3085+ _ => 4,
3086+ };
3087+ let qrows_on = fused_bf16 && self.qw.pack_bits != 3 && qrows_sel != 0;
3088+ // COCO_QW2=1 swaps the QROWS=4 kernel for its uint2 wide-unpack twin
3089+ // (2 packed words per inner iteration). Only valid at QROWS=4.
3090+ let qw2 = qrows_sel == 4 && std::env::var("COCO_QW2").as_deref() == Ok("1");
3091+ // Fused SwiGLU is a register-blocked nibble kernel that also folds
3092+ // silu(gate)·up at store; it shares the QROWS width selection. Only set
3093+ // by the gate/up QGroup, only on the bf16 + 4-bit path (asserted at the
3094+ // call site), so qrows_on holds whenever swiglu does.
3095+ let swiglu_on = self.qw.swiglu;
3096+ let pipe = if rot_on {
3097+ // Rotate-in prologue kernels (QR=4; eligibility asserted by the caller
3098+ // via rotate_in_eligible: bf16 + nibble + default QROWS, tokens==1).
3099+ if swiglu_on {
3100+ &pipes.qmatvec_swiglu_rot
3101+ } else {
3102+ &pipes.qmatvec_bf16_rot
3103+ }
3104+ } else if swiglu_on {
3105+ if qrows_sel == 8 {
3106+ &pipes.qmatvec_swiglu_r8
3107+ } else {
3108+ &pipes.qmatvec_swiglu_r // QROWS=4 (also when COCO_QROWS=0/unset)
3109+ }
3110+ } else if qrows_on {
3111+ if qw2 {
3112+ &pipes.qmatvec_bf16_rw2
3113+ } else if qrows_sel == 8 {
3114+ &pipes.qmatvec_bf16_r8
3115+ } else {
3116+ &pipes.qmatvec_bf16_r
3117+ }
3118+ } else {
3119+ match (fused_bf16, self.qw.pack_bits == 3) {
3120+ (true, true) => &pipes.qmatvec3_bf16,
3121+ (true, false) => &pipes.qmatvec_bf16,
3122+ (false, true) => &pipes.qmatvec3,
3123+ (false, false) => &pipes.qmatvec,
3124+ }
3125+ };
3126+ // SwiGLU's QROWS divisor: the swiglu kernel uses QR=8 only when COCO_QROWS=8,
3127+ // else QR=4 (the swiglu_r kernel is compiled at QR=4 regardless of qrows_sel
3128+ // being 0/unset). Grid math below must match.
3129+ let swiglu_qr: usize = if qrows_sel == 8 { 8 } else { 4 };
3130+
3131+ let enc = dev.command_encoder()?;
3132+ let ce: &ComputeCommandEncoder = enc.as_ref();
3133+ ce.set_compute_pipeline_state(pipe);
3134+ ce.set_input_buffer(0, Some(storage.buffer()), xr_off);
3135+ ce.set_input_buffer(1, Some(self.qw.codes.as_ref()), 0);
3136+ ce.set_input_buffer(2, Some(self.qw.radius.as_ref()), 0);
3137+ // codebook (8 f32) as a constant pointer via set_bytes_directly
3138+ ce.set_bytes_directly(
3139+ 3,
3140+ std::mem::size_of_val(self.qw.codebook.as_slice()),
3141+ self.qw.codebook.as_ptr().cast(),
3142+ );
3143+ ce.set_output_buffer(4, Some(out_ref), 0);
3144+ ce.set_bytes(5, &inn);
3145+ ce.set_bytes(6, &out_dim);
3146+ ce.set_bytes(7, &d);
3147+ ce.set_bytes(8, &tokens);
3148+ // The SwiGLU kernels have no bias/resid buffers (gate/up never carry
3149+ // either); only the plain fused-bf16 kernels read buffers 9-12.
3150+ if fused_bf16 && !swiglu_on {
3151+ // bias (buffer 9) + has_bias flag (buffer 10). Bind the real bias when
3152+ // present; otherwise bind the codes buffer as a harmless non-null
3153+ // placeholder (has_bias=0 means the kernel never reads it).
3154+ let has_bias: u32 = if self.qw.bias_bf16.is_some() { 1 } else { 0 };
3155+ // Real bias buffer (Arc deref) when present; else the codes buffer as a
3156+ // harmless non-null placeholder (has_bias=0 ⇒ never read).
3157+ let bias_buf: &Buffer = match &self.qw.bias_bf16 {
3158+ Some(b) => b.as_ref(),
3159+ None => self.qw.codes.as_ref(),
3160+ };
3161+ ce.set_input_buffer(9, Some(bias_buf), 0);
3162+ ce.set_bytes(10, &has_bias);
3163+ // resid (buffer 11) + has_resid flag (buffer 12): the fused residual
3164+ // epilogue (COCO_FUSE_RESID). Same placeholder trick when absent.
3165+ let has_resid: u32 = if self.qw.resid.is_some() { 1 } else { 0 };
3166+ match &self.qw.resid {
3167+ Some(r) => {
3168+ if r.dtype() != DType::BF16 {
3169+ return Err(candle_core::Error::Msg(
3170+ "tq_qmatvec: resid must be bf16".into(),
3171+ ));
3172+ }
3173+ let (rst, rl) = r.storage_and_layout();
3174+ let rbuf = match &*rst {
3175+ candle_core::Storage::Metal(s) => s.buffer().clone(),
3176+ _ => {
3177+ return Err(candle_core::Error::Msg(
3178+ "tq_qmatvec: resid not on metal".into(),
3179+ ))
3180+ }
3181+ };
3182+ let roff = rl.start_offset() * DType::BF16.size_in_bytes();
3183+ ce.set_input_buffer(11, Some(&rbuf), roff);
3184+ }
3185+ None => ce.set_input_buffer(11, Some(self.qw.codes.as_ref()), 0),
3186+ }
3187+ ce.set_bytes(12, &has_resid);
3188+ }
3189+ // Rotate-in prologue: bind the ±1 rotation sign vector (buffer 13 for the
3190+ // plain kernel, buffer 9 for the swiglu variant — it has no bias/resid).
3191+ if rot_on {
3192+ let sign_t = self.qw.rot_sign.as_ref().unwrap();
3193+ let sign_storage = sign_t.storage_and_layout().0;
3194+ let sign_buf = match &*sign_storage {
3195+ candle_core::Storage::Metal(s) => s.buffer().clone(),
3196+ _ => {
3197+ return Err(candle_core::Error::Msg(
3198+ "tq_qmatvec: rot sign not on metal".into(),
3199+ ))
3200+ }
3201+ };
3202+ let sgn_idx = if swiglu_on { 9 } else { 13 };
3203+ ce.set_input_buffer(sgn_idx, Some(&sign_buf), 0);
3204+ }
3205+
3206+ // One SIMD-group (32 lanes) per output row (or per QROWS rows). The
3207+ // threadgroup packs `qocc` simd-groups so reductions stay within a
3208+ // simd-group; capped at the pipeline max. ggml tunes simds-per-threadgroup
3209+ // per quant for occupancy — expose it via COCO_QOCC (simd-groups per
3210+ // threadgroup; default 8) so the fastest config can be picked by A/B.
3211+ const SIMDW: usize = 32;
3212+ let max_w = pipe.max_total_threads_per_threadgroup();
3213+ let qocc: usize = std::env::var("COCO_QOCC")
3214+ .ok()
3215+ .and_then(|v| v.parse::<usize>().ok())
3216+ .filter(|&v| v >= 1)
3217+ .unwrap_or(8);
3218+ if rot_on {
3219+ // Rotate-in path: UNIFORM threadgroups (dispatch_thread_groups) — the
3220+ // FWHT prologue barriers require every thread of the group present.
3221+ // tgw must be a multiple of d so each sweep rotates whole d-blocks;
3222+ // the dynamic threadgroup buffer holds the rotated row (inn f32) plus
3223+ // the cross-simd FWHT scratch (tgw f32) — fit pre-checked by
3224+ // rotate_in_eligible. Grid: nsg simd-groups per threadgroup, each
3225+ // owning QR=4 rows → ceil(out / (nsg*4)) groups per token. Same
3226+ // simd-group-per-rows parallelism as the separate-rotate kernel.
3227+ let mut tgw = (qocc * SIMDW).min(max_w);
3228+ tgw = (tgw / self.qw.d).max(1) * self.qw.d;
3229+ tgw = tgw.min(max_w).max(self.qw.d);
3230+ ce.set_threadgroup_memory_length(
3231+ 0,
3232+ (self.qw.inn + tgw) * DType::F32.size_in_bytes(),
3233+ );
3234+ let rows_per_tg = (tgw / SIMDW) * 4; // QR = 4 (rot kernels)
3235+ let n_tg = (self.qw.out + rows_per_tg - 1) / rows_per_tg;
3236+ let grid = MTLSize { width: n_tg, height: self.tokens, depth: 1 };
3237+ let tgroup = MTLSize { width: tgw, height: 1, depth: 1 };
3238+ ce.dispatch_thread_groups(grid, tgroup);
3239+ drop(enc);
3240+
3241+ let news =
3242+ candle_core::MetalStorage::new(out_buf, dev.clone(), out_elems, out_dt);
3243+ return Ok((news, Shape::from_dims(&[self.tokens, self.qw.out])));
3244+ }
3245+ let mut tgw = (qocc * SIMDW).min(max_w);
3246+ tgw = (tgw / SIMDW) * SIMDW; // round down to a simd multiple
3247+ tgw = tgw.max(SIMDW);
3248+ // grid.x in THREADS: one simd-group (32 lanes) per output row, or per QROWS
3249+ // rows when the register-blocked kernel is active. The divisor MUST match the
3250+ // kernel's compile-time QROWS (qrows_sel) so each group owns the right rows.
3251+ // SwiGLU grids over `out` (= I) gate rows (each group also does the matching
3252+ // up rows internally); its divisor is swiglu_qr.
3253+ let n_groups = if swiglu_on {
3254+ (self.qw.out + swiglu_qr - 1) / swiglu_qr
3255+ } else if qrows_on {
3256+ (self.qw.out + qrows_sel - 1) / qrows_sel
3257+ } else {
3258+ self.qw.out
3259+ };
3260+ let grid = MTLSize {
3261+ width: n_groups * SIMDW,
3262+ height: self.tokens,
3263+ depth: 1,
3264+ };
3265+ let tgroup = MTLSize { width: tgw, height: 1, depth: 1 };
3266+ ce.dispatch_threads(grid, tgroup);
3267+ drop(enc);
3268+
3269+ let news = candle_core::MetalStorage::new(out_buf, dev.clone(), out_elems, out_dt);
3270+ Ok((news, Shape::from_dims(&[self.tokens, self.qw.out])))
3271+ }
3272+}
3273+
3274+// ───────────────────────── CustomOp1: FFN megakernel ─────────────────────────
3275+// Whole FFN (swiglu → rotate(h) → down) in one dispatch. Input is the
3276+// gate/up-ROTATED activation `xr` ([tokens, inn] f32). Output is [tokens, hidden]
3277+// bf16. `h` (I-wide SwiGLU intermediate) lives entirely in threadgroup memory; see
3278+// the `tq_ffn_mega` kernel. Eligibility (incl. I<=14336) is checked by the caller.
3279+struct FfnMegaOp {
3280+ inn: usize, // gate/up input width (= hidden)
3281+ big_i: usize, // intermediate width I
3282+ d: usize, // block size (128)
3283+ hidden: usize, // down out width (= hidden)
3284+ gu_codes: Arc<Buffer>,
3285+ gu_radius: Arc<Buffer>,
3286+ codebook: Vec<f32>,
3287+ dn_codes: Arc<Buffer>,
3288+ dn_radius: Arc<Buffer>,
3289+ dn_sign: Tensor, // [I] f32 (±1) on device
3290+ tokens: usize,
3291+}
3292+
3293+impl CustomOp1 for FfnMegaOp {
3294+ fn name(&self) -> &'static str {
3295+ "tq_ffn_mega"
3296+ }
3297+
3298+ fn cpu_fwd(&self, _s: &CpuStorage, _l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> {
3299+ Err(candle_core::Error::Msg(
3300+ "tq_ffn_mega has no CPU implementation (Metal only)".into(),
3301+ ))
3302+ }
3303+
3304+ fn metal_fwd(
3305+ &self,
3306+ storage: &candle_core::MetalStorage,
3307+ layout: &Layout,
3308+ ) -> candle_core::Result<(candle_core::MetalStorage, Shape)> {
3309+ use objc2_metal::MTLSize;
3310+ let dev = storage.device().clone();
3311+ let mdev = dev.metal_device();
3312+ let pipes = get_pipelines(mdev).map_err(wrap)?;
3313+
3314+ let inn = self.inn as u32;
3315+ let big_i = self.big_i as u32;
3316+ let d = self.d as u32;
3317+ let hidden = self.hidden as u32;
3318+
3319+ let out_elems = self.tokens * self.hidden;
3320+ let xr_off = layout.start_offset() * DType::F32.size_in_bytes();
3321+ let out_buf = dev.new_buffer(out_elems, DType::BF16, "tq_ffn_mega")?;
3322+ let out_ref: &Buffer = &out_buf;
3323+
3324+ // down rotation sign buffer (on device).
3325+ let sign_storage = self.dn_sign.storage_and_layout().0;
3326+ let sign_buf = match &*sign_storage {
3327+ candle_core::Storage::Metal(s) => s.buffer().clone(),
3328+ _ => return Err(candle_core::Error::Msg("ffn_mega: down sign not on metal".into())),
3329+ };
3330+
3331+ let pipe = &pipes.ffn_mega;
3332+ let enc = dev.command_encoder()?;
3333+ let ce: &ComputeCommandEncoder = enc.as_ref();
3334+ ce.set_compute_pipeline_state(pipe);
3335+ ce.set_input_buffer(0, Some(storage.buffer()), xr_off);
3336+ ce.set_input_buffer(1, Some(self.gu_codes.as_ref()), 0);
3337+ ce.set_input_buffer(2, Some(self.gu_radius.as_ref()), 0);
3338+ ce.set_bytes_directly(
3339+ 3,
3340+ std::mem::size_of_val(self.codebook.as_slice()),
3341+ self.codebook.as_ptr().cast(),
3342+ );
3343+ ce.set_output_buffer(4, Some(out_ref), 0);
3344+ ce.set_bytes(5, &inn);
3345+ ce.set_bytes(6, &big_i);
3346+ ce.set_bytes(7, &d);
3347+ ce.set_input_buffer(8, Some(self.dn_codes.as_ref()), 0);
3348+ ce.set_input_buffer(9, Some(self.dn_radius.as_ref()), 0);
3349+ ce.set_input_buffer(10, Some(&sign_buf), 0);
3350+ ce.set_bytes(11, &hidden);
3351+
3352+ // One threadgroup per token. Threadgroup width = qocc simd-groups, capped at
3353+ // the pipeline max AND at 512 (the FWHT scratch `scr[512]` bound), AND kept a
3354+ // multiple of `d` (=128) so the rotate phase tiles whole blocks per sweep.
3355+ const SIMDW: usize = 32;
3356+ let max_w = pipe.max_total_threads_per_threadgroup();
3357+ let qocc: usize = std::env::var("COCO_QOCC")
3358+ .ok()
3359+ .and_then(|v| v.parse::<usize>().ok())
3360+ .filter(|&v| v >= 1)
3361+ .unwrap_or(8);
3362+ let mut tgw = (qocc * SIMDW).min(max_w).min(512);
3363+ tgw = (tgw / SIMDW) * SIMDW; // simd multiple
3364+ // Make tgw a multiple of d (128) so tgsz/d blocks tile evenly each sweep;
3365+ // d=128 is 4 simd-groups, so round down to a multiple of 128 (>= 128).
3366+ tgw = (tgw / self.d).max(1) * self.d;
3367+ tgw = tgw.min(max_w).max(self.d);
3368+
3369+ // grid in THREADS: one threadgroup (tgw threads) per token along y.
3370+ let grid = MTLSize { width: tgw, height: self.tokens, depth: 1 };
3371+ let tgroup = MTLSize { width: tgw, height: 1, depth: 1 };
3372+ ce.dispatch_threads(grid, tgroup);
3373+ drop(enc);
3374+
3375+ let news = candle_core::MetalStorage::new(out_buf, dev.clone(), out_elems, DType::BF16);
3376+ Ok((news, Shape::from_dims(&[self.tokens, self.hidden])))
3377+ }
3378+}
3379+
3380+// ───────────────────────── fused flash-decode KV cache ─────────────────────────
3381+
3382+/// Persistent per-layer KV cache for the FUSED flash-decode attention path. K and
3383+/// V live in pinned device buffers `[n_kv, max_ctx, head_dim]` allocated ONCE and
3384+/// written in-kernel — no per-token `cat` realloc, no `repeat_kv` materialization.
3385+/// `len` is how many positions are currently stored.
3386+///
3387+/// Precision is selected by `kv_bits` (COCO_KV_BITS): 16 = bf16 cache; 4 = q4_0-style
3388+/// 4-bit nibble cache (per-(head,position) row scale) — ~4x less KV memory traffic per
3389+/// decode step at long context, the dominant cost there. The flash-decode kernel
3390+/// dequantizes K/V on the fly and accumulates the softmax in f32 either way.
3391+///
3392+/// Held buffers are `Arc<Buffer>` so candle's pool never recycles them out from
3393+/// under us (same pinning rationale as `QWeight`).
3394+pub struct KvCache {
3395+ pub(crate) n_heads: usize,
3396+ pub(crate) n_kv: usize,
3397+ pub(crate) head_dim: usize,
3398+ pub(crate) max_ctx: usize,
3399+ /// KV precision: 16 = bf16 cache (k_cache/v_cache used), 4 = 4-bit nibble cache
3400+ /// (k_codes/v_codes + k_scale/v_scale used). Default 4 (COCO_KV_BITS).
3401+ pub(crate) kv_bits: u8,
3402+ // ── bf16 path (kv_bits==16) ──
3403+ pub(crate) k_cache: Arc<Buffer>, // [n_kv, max_ctx, head_dim] bf16
3404+ pub(crate) v_cache: Arc<Buffer>,
3405+ // ── 4-bit path (kv_bits==4) ──
3406+ // Nibble-packed codes [n_kv, max_ctx, head_dim/2] (uchar) + a per-32-coord-block
3407+ // bf16 scale [n_kv, max_ctx, head_dim/32]. ~4x less KV traffic than the bf16 cache.
3408+ pub(crate) k_codes: Arc<Buffer>,
3409+ pub(crate) v_codes: Arc<Buffer>,
3410+ pub(crate) k_scale: Arc<Buffer>,
3411+ pub(crate) v_scale: Arc<Buffer>,
3412+ // Flash-decoding split-K scratch (persistent, sized for MAX_SPLITS). Reused
3413+ // every decode step so we don't allocate per token.
3414+ pub(crate) pacc: Arc<Buffer>, // [n_heads, MAX_SPLITS, head_dim]
3415+ pub(crate) pm: Arc<Buffer>, // [n_heads, MAX_SPLITS]
3416+ pub(crate) pl: Arc<Buffer>, // [n_heads, MAX_SPLITS]
3417+ pub(crate) len: usize,
3418+}
3419+
3420+/// KV-cache element bits. Default 4 (4-bit q4_0-style nibble cache, ~4x less KV
3421+/// memory traffic at long ctx). Set COCO_KV_BITS=16 for the old bf16 cache (A/B).
3422+fn kv_bits_from_env() -> u8 {
3423+ // DEFAULT = 16 (bf16, coherent). 4-bit KV DEGENERATES larger models (verified: breaks
3424+ // Qwen2.5-7B into a repetition loop) AND gives no real decode speedup at 8-32K — so it's
3425+ // opt-in only. (It was briefly the default, validated only on the 1.5B → shipped broken 7B.)
3426+ match std::env::var("COCO_KV_BITS").as_deref() {
3427+ Ok("4") => 4,
3428+ _ => 16,
3429+ }
3430+}
3431+
3432+/// Hard cap on position-splits per head for flash-decoding. The actual count per
3433+/// step targets ~128 splits (n_heads × 128 ≈ GPU simd-group occupancy); beyond
3434+/// that, finer splits add combine overhead without filling more GPU lanes.
3435+const MAX_SPLITS: usize = 256;
3436+
3437+impl KvCache {
3438+ /// Allocate the persistent K/V buffers for one attention layer.
3439+ pub fn new(
3440+ n_heads: usize,
3441+ n_kv: usize,
3442+ head_dim: usize,
3443+ max_ctx: usize,
3444+ device: &Device,
3445+ ) -> Result<Self> {
3446+ let cdev = match device {
3447+ Device::Metal(m) => m,
3448+ _ => return Err(anyhow!("flash-decode KV cache requires the Metal device")),
3449+ };
3450+ let elems = n_kv * max_ctx * head_dim;
3451+ let kv_bits = kv_bits_from_env();
3452+ // PRIVATE (unpooled) buffers: candle's pool never recycles them, and they
3453+ // don't need zeroing — the kernel only ever reads slots [0..=pos] it has
3454+ // itself written. Held as Arc<Buffer> for the model's lifetime. We allocate
3455+ // ONLY the path actually selected by kv_bits at full size; the unused path
3456+ // gets a 1-element placeholder (so the struct stays flat, no Option).
3457+ //
3458+ // bf16 (16-bit): halves attention bandwidth vs f32 — matches llama.cpp f16 KV.
3459+ // 4-bit (q4_0-style): ~4x less than bf16 — nibble codes [.., head_dim/2] +
3460+ // a per-32-coord-block bf16 scale [n_kv, max_ctx, head_dim/32]. The partial
3461+ // kernel dequantizes on the fly (val=(nib-8)*scale) and accumulates in f32.
3462+ let (k_cache, v_cache, k_codes, v_codes, k_scale, v_scale) = if kv_bits == 4 {
3463+ let code_elems = n_kv * max_ctx * (head_dim / 2); // uchar nibble bytes
3464+ // one bf16 scale per 32-coord block (Q4_BLK), not per row — a single
3465+ // per-row scale was too coarse and collapsed attention (see kernel notes).
3466+ let scale_elems = n_kv * max_ctx * (head_dim / 32);
3467+ (
3468+ cdev.new_private_buffer(1, DType::BF16, "kv_k_unused")?,
3469+ cdev.new_private_buffer(1, DType::BF16, "kv_v_unused")?,
3470+ cdev.new_private_buffer(code_elems, DType::U8, "kv_k_codes")?,
3471+ cdev.new_private_buffer(code_elems, DType::U8, "kv_v_codes")?,
3472+ cdev.new_private_buffer(scale_elems, DType::BF16, "kv_k_scale")?,
3473+ cdev.new_private_buffer(scale_elems, DType::BF16, "kv_v_scale")?,
3474+ )
3475+ } else {
3476+ (
3477+ cdev.new_private_buffer(elems, DType::BF16, "kv_k")?,
3478+ cdev.new_private_buffer(elems, DType::BF16, "kv_v")?,
3479+ cdev.new_private_buffer(1, DType::U8, "kv_k_codes_unused")?,
3480+ cdev.new_private_buffer(1, DType::U8, "kv_v_codes_unused")?,
3481+ cdev.new_private_buffer(1, DType::BF16, "kv_k_scale_unused")?,
3482+ cdev.new_private_buffer(1, DType::BF16, "kv_v_scale_unused")?,
3483+ )
3484+ };
3485+ let pacc = cdev.new_private_buffer(n_heads * MAX_SPLITS * head_dim, DType::F32, "pacc")?;
3486+ let pm = cdev.new_private_buffer(n_heads * MAX_SPLITS, DType::F32, "pm")?;
3487+ let pl = cdev.new_private_buffer(n_heads * MAX_SPLITS, DType::F32, "pl")?;
3488+ Ok(Self {
3489+ n_heads,
3490+ n_kv,
3491+ head_dim,
3492+ max_ctx,
3493+ kv_bits,
3494+ k_cache,
3495+ v_cache,
3496+ k_codes,
3497+ v_codes,
3498+ k_scale,
3499+ v_scale,
3500+ pacc,
3501+ pm,
3502+ pl,
3503+ len: 0,
3504+ })
3505+ }
3506+
3507+ pub fn clear(&mut self) {
3508+ self.len = 0;
3509+ }
3510+
3511+ pub fn len(&self) -> usize {
3512+ self.len
3513+ }
3514+
3515+ pub fn max_ctx(&self) -> usize {
3516+ self.max_ctx
3517+ }
3518+
3519+ /// Append a chunk's k/v into the persistent cache and advance `len`.
3520+ /// `k`/`v` must be contiguous BF16 `[n_kv, seq, head_dim]` (k already RoPE'd) —
3521+ /// the kernel converts to the f32 cache on store. One copy dispatch; no candle
3522+ /// cat/realloc and no candle to_dtype(F32) beforehand.
3523+ pub fn append_prefill(&mut self, k: &Tensor, v: &Tensor) -> Result<()> {
3524+ use objc2_metal::MTLSize;
3525+ let device = k.device().clone();
3526+ let cdev = match &device {
3527+ Device::Metal(m) => m.clone(),
3528+ _ => return Err(anyhow!("kv append requires the Metal device")),
3529+ };
3530+ let mdev = cdev.metal_device();
3531+ let pipes = get_pipelines(mdev)?;
3532+
3533+ let dims = k.dims().to_vec();
3534+ // accept [n_kv, seq, head_dim] or [1, n_kv, seq, head_dim]
3535+ let (n_kv, seq, hd) = match dims.len() {
3536+ 3 => (dims[0], dims[1], dims[2]),
3537+ 4 => (dims[1], dims[2], dims[3]),
3538+ _ => return Err(anyhow!("kv append expects 3 or 4 dims, got {dims:?}")),
3539+ };
3540+ if n_kv != self.n_kv || hd != self.head_dim {
3541+ return Err(anyhow!("kv append shape mismatch"));
3542+ }
3543+ if self.len + seq > self.max_ctx {
3544+ return Err(anyhow!(
3545+ "KV cache overflow on prefill: {} + {} > {}",
3546+ self.len, seq, self.max_ctx
3547+ ));
3548+ }
3549+
3550+ // bf16 inputs → 2-byte element offset.
3551+ let buf_of = |t: &Tensor| -> Result<(Buffer, usize)> {
3552+ let (s, l) = t.storage_and_layout();
3553+ match &*s {
3554+ candle_core::Storage::Metal(ms) => Ok((ms.buffer().clone(), l.start_offset() * 2)),
3555+ _ => Err(anyhow!("kv append inputs must be on Metal")),
3556+ }
3557+ };
3558+ let (k_buf, k_off) = buf_of(k)?;
3559+ let (v_buf, v_off) = buf_of(v)?;
3560+
3561+ let seq_u = seq as u32;
3562+ let hd_u = hd as u32;
3563+ let max_ctx = self.max_ctx as u32;
3564+ let pos = self.len as u32;
3565+ if self.kv_bits == 4 {
3566+ // Quantize + nibble-pack the chunk into the 4-bit cache. ONE threadgroup
3567+ // per (kv, position): head_dim threads cooperatively find each row's
3568+ // absmax → bf16 scale, then pack nibbles + write the scale.
3569+ let enc = cdev.command_encoder()?;
3570+ let ce: &ComputeCommandEncoder = enc.as_ref();
3571+ ce.set_compute_pipeline_state(&pipes.kv_append_q4);
3572+ ce.set_input_buffer(0, Some(&k_buf), k_off);
3573+ ce.set_input_buffer(1, Some(&v_buf), v_off);
3574+ ce.set_output_buffer(2, Some(self.k_codes.as_ref()), 0);
3575+ ce.set_output_buffer(3, Some(self.v_codes.as_ref()), 0);
3576+ ce.set_output_buffer(4, Some(self.k_scale.as_ref()), 0);
3577+ ce.set_output_buffer(5, Some(self.v_scale.as_ref()), 0);
3578+ ce.set_bytes(6, &seq_u);
3579+ ce.set_bytes(7, &hd_u);
3580+ ce.set_bytes(8, &max_ctx);
3581+ ce.set_bytes(9, &pos);
3582+ let grid = MTLSize { width: n_kv, height: seq, depth: 1 };
3583+ let tgroup = MTLSize { width: hd, height: 1, depth: 1 };
3584+ ce.dispatch_thread_groups(grid, tgroup);
3585+ drop(enc);
3586+ self.len += seq;
3587+ return Ok(());
3588+ }
3589+ {
3590+ let enc = cdev.command_encoder()?;
3591+ let ce: &ComputeCommandEncoder = enc.as_ref();
3592+ ce.set_compute_pipeline_state(&pipes.kv_append);
3593+ ce.set_input_buffer(0, Some(&k_buf), k_off);
3594+ ce.set_input_buffer(1, Some(&v_buf), v_off);
3595+ ce.set_input_buffer(2, Some(self.k_cache.as_ref()), 0);
3596+ ce.set_input_buffer(3, Some(self.v_cache.as_ref()), 0);
3597+ ce.set_bytes(4, &seq_u);
3598+ ce.set_bytes(5, &hd_u);
3599+ ce.set_bytes(6, &max_ctx);
3600+ ce.set_bytes(7, &pos);
3601+ let grid = MTLSize { width: hd, height: seq, depth: n_kv };
3602+ let tgroup = MTLSize { width: hd, height: 1, depth: 1 };
3603+ ce.dispatch_threads(grid, tgroup);
3604+ }
3605+ self.len += seq;
3606+ Ok(())
3607+ }
3608+
3609+ /// Append one token's k/v into the cache and run fused flash-decode attention
3610+ /// for the single new query. `q` [n_heads, head_dim] BF16 (RoPE'd), `k_new`/
3611+ /// `v_new` [n_kv, head_dim] BF16 (k_new RoPE'd) — all contiguous on Metal; the
3612+ /// kernels convert to f32 on load (no candle to_dtype). Returns the attention
3613+ /// output [n_heads*head_dim] f32 as a candle Tensor shaped [1,1,hidden]; the
3614+ /// caller feeds it straight into o_proj (o_proj's rotate handles f32 input).
3615+ ///
3616+ /// TWO Metal dispatches (partial + combine) replace candle's cat + repeat_kv +
3617+ /// scores + softmax + AV (each O(ctx), each a separate dispatch plus huge
3618+ /// copies). The new token's k/v is appended IN the partial kernel (by the split
3619+ /// owning the last position), so there's no separate append dispatch and no
3620+ /// append→read memory barrier serializing the GPU per token. f32 KV cache is
3621+ /// persistent (no per-token realloc).
3622+ pub fn decode(&mut self, q: &Tensor, k_new: &Tensor, v_new: &Tensor) -> Result<Tensor> {
3623+ use objc2_metal::MTLSize;
3624+ let device = q.device().clone();
3625+ let cdev = match &device {
3626+ Device::Metal(m) => m.clone(),
3627+ _ => return Err(anyhow!("flash-decode requires the Metal device")),
3628+ };
3629+ let mdev = cdev.metal_device();
3630+ let pipes = get_pipelines(mdev)?;
3631+
3632+ if self.len >= self.max_ctx {
3633+ return Err(anyhow!(
3634+ "KV cache overflow: len {} >= max_ctx {}",
3635+ self.len,
3636+ self.max_ctx
3637+ ));
3638+ }
3639+
3640+ // The new token will occupy slot `len`; after this step the valid range is
3641+ // [0..=len]. The partial kernel appends it (in-kernel) and attends. q/k_new/
3642+ // v_new are BF16 (read & converted in-kernel) → 2-byte element offsets.
3643+ let pos = self.len as u32;
3644+ let buf_of = |t: &Tensor| -> Result<(Buffer, usize)> {
3645+ let (s, l) = t.storage_and_layout();
3646+ match &*s {
3647+ candle_core::Storage::Metal(ms) => Ok((ms.buffer().clone(), l.start_offset() * 2)),
3648+ _ => Err(anyhow!("flash-decode inputs must be on Metal")),
3649+ }
3650+ };
3651+ let (q_buf, q_off) = buf_of(q)?;
3652+ let (k_buf, k_off) = buf_of(k_new)?;
3653+ let (v_buf, v_off) = buf_of(v_new)?;
3654+
3655+ let out_elems = self.n_heads * self.head_dim;
3656+ let out_buf = cdev.new_buffer(out_elems, DType::F32, "tq_attn_out")?;
3657+
3658+ // For the 4-bit cache, quantize+append the decode token's k/v via the SAME
3659+ // proven prefill kernel (tq_kv_append_q4) BEFORE attending, instead of the
3660+ // in-kernel append inside tq_attn_partial_q4. The in-kernel q4 append path
3661+ // corrupted later positions (token 1 ok, token 2+ garbage); the prefill
3662+ // append is verified-correct, so we reuse it here (correctness over the
3663+ // saved dispatch). After this, self.len == pos+1 and the attention kernel
3664+ // runs read-only (do_append=0). bf16 keeps its single-dispatch in-kernel
3665+ // append (that path is coherent).
3666+ let do_append: u32 = if self.kv_bits == 4 {
3667+ // append_prefill expects [n_kv, seq, head_dim]; k_new/v_new are
3668+ // [n_kv, head_dim] → add the seq=1 axis. This advances self.len by 1.
3669+ let k_app = k_new.unsqueeze(1)?;
3670+ let v_app = v_new.unsqueeze(1)?;
3671+ self.append_prefill(&k_app, &v_app)?;
3672+ 0
3673+ } else {
3674+ 1
3675+ };
3676+
3677+ let total = (pos + 1) as u32; // valid positions after the append
3678+ // Flash-decoding split count. The attention is PARALLELISM-bound, not
3679+ // bandwidth-bound: with too few splits the GPU sits idle (measured 27 tok/s
3680+ // at 8K with 16 splits → 65 tok/s with 128 splits). The sweet spot is when
3681+ // n_heads × n_splits ≈ GPU simd-group occupancy (~600-1000 on M4 Max), so we
3682+ // TARGET a fixed split count rather than a fixed positions-per-split. Each
3683+ // split still needs enough work, so we also cap at total/MIN_PER_SPLIT.
3684+ // COCO_SPLIT_TARGET overrides the target (profiling).
3685+ let target: usize = std::env::var("COCO_SPLIT_TARGET")
3686+ .ok()
3687+ .and_then(|s| s.parse().ok())
3688+ .unwrap_or(128);
3689+ const MIN_PER_SPLIT: usize = 16;
3690+ let by_work = ((total as usize) / MIN_PER_SPLIT).max(1);
3691+ // n_splits = min(target, total/MIN_PER_SPLIT), clamped to [1, MAX_SPLITS].
3692+ let n_splits = target.min(by_work).clamp(1, MAX_SPLITS) as u32;
3693+
3694+ let n_heads = self.n_heads as u32;
3695+ let n_kv = self.n_kv as u32;
3696+ let head_dim = self.head_dim as u32;
3697+ let max_ctx = self.max_ctx as u32;
3698+ let scale = 1.0f32 / (self.head_dim as f32).sqrt();
3699+
3700+ {
3701+ let enc = cdev.command_encoder()?;
3702+ let ce: &ComputeCommandEncoder = enc.as_ref();
3703+ let grid = MTLSize { width: self.n_heads, height: n_splits as usize, depth: 1 };
3704+ let tgroup = MTLSize { width: 32, height: 1, depth: 1 };
3705+ // ── partials (also appends the new token to the cache) ──
3706+ // k/v cache bound as OUTPUTS (the kernel appends the new row): this makes
3707+ // candle's hazard tracker insert the inter-token barrier so token N's
3708+ // write to slot N is visible to token N+1's read. (Binding read-only
3709+ // would skip that barrier → cross-token race.)
3710+ if self.kv_bits == 4 {
3711+ // 4-bit cache: quantize+append the decode token's k/v in-kernel and
3712+ // dequantize the cached K/V on the fly while attending (val=(nib-8)*sc).
3713+ ce.set_compute_pipeline_state(&pipes.attn_partial_q4);
3714+ ce.set_input_buffer(0, Some(&q_buf), q_off);
3715+ ce.set_output_buffer(1, Some(self.k_codes.as_ref()), 0);
3716+ ce.set_output_buffer(2, Some(self.v_codes.as_ref()), 0);
3717+ ce.set_output_buffer(3, Some(self.pacc.as_ref()), 0);
3718+ ce.set_output_buffer(4, Some(self.pm.as_ref()), 0);
3719+ ce.set_output_buffer(5, Some(self.pl.as_ref()), 0);
3720+ ce.set_bytes(6, &n_heads);
3721+ ce.set_bytes(7, &n_kv);
3722+ ce.set_bytes(8, &head_dim);
3723+ ce.set_bytes(9, &max_ctx);
3724+ ce.set_bytes(10, &total);
3725+ ce.set_bytes(11, &scale);
3726+ ce.set_bytes(12, &n_splits);
3727+ ce.set_input_buffer(13, Some(&k_buf), k_off);
3728+ ce.set_input_buffer(14, Some(&v_buf), v_off);
3729+ // scale buffers also bound as OUTPUTS (the owning split writes the new
3730+ // row's scale, all splits read prior rows' scales) → same barrier.
3731+ ce.set_output_buffer(15, Some(self.k_scale.as_ref()), 0);
3732+ ce.set_output_buffer(16, Some(self.v_scale.as_ref()), 0);
3733+ ce.set_bytes(17, &do_append); // 0 → token already appended above
3734+ ce.dispatch_thread_groups(grid, tgroup);
3735+ } else {
3736+ ce.set_compute_pipeline_state(&pipes.attn_partial);
3737+ ce.set_input_buffer(0, Some(&q_buf), q_off);
3738+ ce.set_output_buffer(1, Some(self.k_cache.as_ref()), 0);
3739+ ce.set_output_buffer(2, Some(self.v_cache.as_ref()), 0);
3740+ ce.set_output_buffer(3, Some(self.pacc.as_ref()), 0);
3741+ ce.set_output_buffer(4, Some(self.pm.as_ref()), 0);
3742+ ce.set_output_buffer(5, Some(self.pl.as_ref()), 0);
3743+ ce.set_bytes(6, &n_heads);
3744+ ce.set_bytes(7, &n_kv);
3745+ ce.set_bytes(8, &head_dim);
3746+ ce.set_bytes(9, &max_ctx);
3747+ ce.set_bytes(10, &total);
3748+ ce.set_bytes(11, &scale);
3749+ ce.set_bytes(12, &n_splits);
3750+ ce.set_input_buffer(13, Some(&k_buf), k_off);
3751+ ce.set_input_buffer(14, Some(&v_buf), v_off);
3752+ ce.dispatch_thread_groups(grid, tgroup);
3753+ }
3754+
3755+ // ── combine (reads pacc/pm/pl which were just written → auto barrier) ──
3756+ ce.set_compute_pipeline_state(&pipes.attn_combine);
3757+ ce.set_input_buffer(0, Some(self.pacc.as_ref()), 0);
3758+ ce.set_input_buffer(1, Some(self.pm.as_ref()), 0);
3759+ ce.set_input_buffer(2, Some(self.pl.as_ref()), 0);
3760+ ce.set_output_buffer(3, Some(out_buf.as_ref()), 0);
3761+ ce.set_bytes(4, &n_heads);
3762+ ce.set_bytes(5, &head_dim);
3763+ ce.set_bytes(6, &n_splits);
3764+ let grid2 = MTLSize { width: self.n_heads, height: 1, depth: 1 };
3765+ let tgroup2 = MTLSize { width: 32, height: 1, depth: 1 };
3766+ ce.dispatch_thread_groups(grid2, tgroup2);
3767+ }
3768+
3769+ // The new token is now in the cache. For kv_bits==4 it was already appended
3770+ // (and self.len advanced) by append_prefill above; only the bf16 in-kernel
3771+ // append path still needs to advance len here.
3772+ if self.kv_bits != 4 {
3773+ self.len += 1;
3774+ }
3775+
3776+ let storage =
3777+ candle_core::MetalStorage::new(out_buf, cdev.clone(), out_elems, DType::F32);
3778+ let attn = candle_core::Tensor::from_storage(
3779+ candle_core::Storage::Metal(storage),
3780+ Shape::from_dims(&[1, 1, out_elems]),
3781+ candle_core::op::BackpropOp::none(),
3782+ false,
3783+ );
3784+ Ok(attn)
3785+ }
3786+}
3787+
3788+fn wrap(e: anyhow::Error) -> candle_core::Error {
3789+ candle_core::Error::Msg(e.to_string())
3790+}
3791+
3792+// ───────────────────────── fused RMSNorm ─────────────────────────
3793+
3794+/// A fused RMSNorm that runs `out = x * rsqrt(mean(x^2)+eps) * weight` in ONE Metal
3795+/// dispatch (bf16 in/out, f32 math). Drop-in for `candle_nn::RmsNorm` on the decode
3796+/// path: candle's RmsNorm is a chain of ~7 elementwise dispatches (upcast, sqr,
3797+/// mean, +eps, rsqrt, ×, ×, downcast); there are ~57 norms/token, so collapsing each
3798+/// to one dispatch removes a big slice of the per-token candle op-tax.
3799+pub struct RmsNormFused {
3800+ pub(crate) weight: Tensor, // [inn] bf16 on device
3801+ pub(crate) eps: f32,
3802+ pub(crate) inn: usize,
3803+}
3804+
3805+impl RmsNormFused {
3806+ pub fn new(weight: Tensor, eps: f64) -> Result<Self> {
3807+ let inn = weight.dims1()?;
3808+ let weight = weight.to_dtype(DType::BF16)?.contiguous()?;
3809+ Ok(Self { weight, eps: eps as f32, inn })
3810+ }
3811+
3812+ /// out has the same shape/dtype as `x` (bf16). Flattens leading dims to tokens.
3813+ pub fn forward(&self, x: &Tensor) -> Result<Tensor> {
3814+ // Fallback to candle when disabled (A/B) or input isn't bf16.
3815+ if std::env::var("COCO_NO_FUSE_NORM").is_ok() || x.dtype() != DType::BF16 {
3816+ let xs = x.to_dtype(DType::F32)?;
3817+ let var = xs.sqr()?.mean_keepdim(D::Minus1)?;
3818+ let xn = xs.broadcast_div(&(var + self.eps as f64)?.sqrt()?)?;
3819+ let w = self.weight.to_dtype(DType::F32)?;
3820+ return Ok(xn.broadcast_mul(&w)?.to_dtype(x.dtype())?);
3821+ }
3822+ let dims = x.dims().to_vec();
3823+ let inn = *dims.last().unwrap();
3824+ if inn != self.inn {
3825+ return Err(anyhow!("RmsNormFused: input dim {inn} != weight {}", self.inn));
3826+ }
3827+ let tokens: usize = dims[..dims.len() - 1].iter().product::<usize>().max(1);
3828+ let xc = x.reshape((tokens, inn))?.contiguous()?;
3829+ let out = xc.apply_op1(RmsNormOp {
3830+ weight: self.weight.clone(),
3831+ eps: self.eps,
3832+ inn,
3833+ tokens,
3834+ })?;
3835+ Ok(out.reshape(Shape::from_dims(&dims))?)
3836+ }
3837+
3838+ /// FUSED residual-add + RMSNorm: returns `(h, normed)` where `h = a + b` and
3839+ /// `normed = RMSNorm(h) * weight`, computed in ONE Metal dispatch. `h` is the new
3840+ /// residual stream (fed to the next add); `normed` feeds the next sublayer. This
3841+ /// folds the standalone candle elementwise residual add into the norm that
3842+ /// immediately consumes it (one fewer full [tokens,inn] pass per sublayer). Falls
3843+ /// back to candle (`(a+b)` then `forward`) when disabled or off the bf16 path.
3844+ pub fn forward_add(&self, a: &Tensor, b: &Tensor) -> Result<(Tensor, Tensor)> {
3845+ if std::env::var("COCO_NO_FUSE_ADDNORM").is_ok()
3846+ || std::env::var("COCO_NO_FUSE_NORM").is_ok()
3847+ || a.dtype() != DType::BF16
3848+ || b.dtype() != DType::BF16
3849+ || !matches!(a.device(), Device::Metal(_))
3850+ {
3851+ let h = (a + b)?;
3852+ let normed = self.forward(&h)?;
3853+ return Ok((h, normed));
3854+ }
3855+ let dims = a.dims().to_vec();
3856+ let inn = *dims.last().unwrap();
3857+ if inn != self.inn {
3858+ return Err(anyhow!("RmsNormFused::forward_add: dim {inn} != weight {}", self.inn));
3859+ }
3860+ if b.dims() != a.dims() {
3861+ return Err(anyhow!("forward_add: shape mismatch {:?} vs {:?}", a.dims(), b.dims()));
3862+ }
3863+ let tokens: usize = dims[..dims.len() - 1].iter().product::<usize>().max(1);
3864+ let ac = a.reshape((tokens, inn))?.contiguous()?;
3865+ let bc = b.reshape((tokens, inn))?.contiguous()?;
3866+ let (h, normed) = add_rmsnorm_apply(&ac, &bc, &self.weight, self.eps, tokens, inn)?;
3867+ Ok((
3868+ h.reshape(Shape::from_dims(&dims))?,
3869+ normed.reshape(Shape::from_dims(&dims))?,
3870+ ))
3871+ }
3872+}
3873+
3874+/// Run the fused add+RMSNorm kernel over contiguous `[tokens, inn]` bf16 `a`/`b` and
3875+/// bf16 weight `w`, returning `(h=a+b, normed=RMSNorm(h)*w)` as two `[tokens,inn]`
3876+/// bf16 tensors. Builds the encoder directly (two source reads, two writes) so candle
3877+/// tracks the hazards; the leader-style one-threadgroup-per-token reduction mirrors
3878+/// `RmsNormOp`.
3879+fn add_rmsnorm_apply(
3880+ a: &Tensor,
3881+ b: &Tensor,
3882+ w: &Tensor,
3883+ eps: f32,
3884+ tokens: usize,
3885+ inn: usize,
3886+) -> Result<(Tensor, Tensor)> {
3887+ use objc2_metal::MTLSize;
3888+ let device = a.device().clone();
3889+ let cdev = match &device {
3890+ Device::Metal(m) => m.clone(),
3891+ _ => return Err(anyhow!("add_rmsnorm requires the Metal device")),
3892+ };
3893+ let mdev = cdev.metal_device();
3894+ let pipes = get_pipelines(mdev)?;
3895+
3896+ let buf_of = |t: &Tensor| -> Result<(Buffer, usize)> {
3897+ let (s, l) = t.storage_and_layout();
3898+ match &*s {
3899+ candle_core::Storage::Metal(ms) => Ok((ms.buffer().clone(), l.start_offset() * 2)),
3900+ _ => Err(anyhow!("add_rmsnorm inputs must be on Metal")),
3901+ }
3902+ };
3903+ let (a_buf, a_off) = buf_of(a)?;
3904+ let (b_buf, b_off) = buf_of(b)?;
3905+ let (w_buf, w_off) = buf_of(w)?;
3906+
3907+ let elem = tokens * inn;
3908+ let h_buf = cdev.new_buffer(elem, DType::BF16, "tq_addnorm_h")?;
3909+ let out_buf = cdev.new_buffer(elem, DType::BF16, "tq_addnorm_out")?;
3910+
3911+ let inn_u = inn as u32;
3912+ {
3913+ let enc = cdev.command_encoder()?;
3914+ let ce: &ComputeCommandEncoder = enc.as_ref();
3915+ ce.set_compute_pipeline_state(&pipes.add_rmsnorm);
3916+ ce.set_input_buffer(0, Some(&a_buf), a_off);
3917+ ce.set_input_buffer(1, Some(&b_buf), b_off);
3918+ ce.set_output_buffer(2, Some(h_buf.as_ref()), 0);
3919+ ce.set_output_buffer(3, Some(out_buf.as_ref()), 0);
3920+ ce.set_input_buffer(4, Some(&w_buf), w_off);
3921+ ce.set_bytes(5, &inn_u);
3922+ ce.set_bytes(6, &eps);
3923+ const SIMDW: usize = 32;
3924+ let max_w = pipes.add_rmsnorm.max_total_threads_per_threadgroup();
3925+ let mut tgw = (8 * SIMDW).min(max_w).min(inn);
3926+ tgw = (tgw / SIMDW).max(1) * SIMDW;
3927+ let grid = MTLSize { width: tokens * tgw, height: 1, depth: 1 };
3928+ let tgroup = MTLSize { width: tgw, height: 1, depth: 1 };
3929+ ce.dispatch_threads(grid, tgroup);
3930+ }
3931+
3932+ let mk = |buf: Arc<Buffer>| -> Tensor {
3933+ let storage = candle_core::MetalStorage::new(buf, cdev.clone(), elem, DType::BF16);
3934+ candle_core::Tensor::from_storage(
3935+ candle_core::Storage::Metal(storage),
3936+ Shape::from_dims(&[tokens, inn]),
3937+ candle_core::op::BackpropOp::none(),
3938+ false,
3939+ )
3940+ };
3941+ Ok((mk(h_buf), mk(out_buf)))
3942+}
3943+
3944+use candle_core::D;
3945+
3946+struct RmsNormOp {
3947+ weight: Tensor,
3948+ eps: f32,
3949+ inn: usize,
3950+ tokens: usize,
3951+}
3952+
3953+impl CustomOp1 for RmsNormOp {
3954+ fn name(&self) -> &'static str {
3955+ "tq_rmsnorm"
3956+ }
3957+ fn cpu_fwd(&self, _s: &CpuStorage, _l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> {
3958+ Err(candle_core::Error::Msg("tq_rmsnorm is Metal only".into()))
3959+ }
3960+ fn metal_fwd(
3961+ &self,
3962+ storage: &candle_core::MetalStorage,
3963+ layout: &Layout,
3964+ ) -> candle_core::Result<(candle_core::MetalStorage, Shape)> {
3965+ use objc2_metal::MTLSize;
3966+ let dev = storage.device().clone();
3967+ let mdev = dev.metal_device();
3968+ let pipes = get_pipelines(mdev).map_err(wrap)?;
3969+
3970+ let inn = self.inn as u32;
3971+ let eps = self.eps;
3972+ let elem = self.tokens * self.inn;
3973+ let out_buf = dev.new_buffer(elem, DType::BF16, "tq_rmsnorm")?;
3974+ let out_ref: &Buffer = &out_buf;
3975+ let in_off = layout.start_offset() * DType::BF16.size_in_bytes();
3976+
3977+ let w_storage = self.weight.storage_and_layout().0;
3978+ let w_buf = match &*w_storage {
3979+ candle_core::Storage::Metal(s) => s.buffer().clone(),
3980+ _ => return Err(candle_core::Error::Msg("rmsnorm weight not on metal".into())),
3981+ };
3982+
3983+ let enc = dev.command_encoder()?;
3984+ let ce: &ComputeCommandEncoder = enc.as_ref();
3985+ ce.set_compute_pipeline_state(&pipes.rmsnorm);
3986+ ce.set_input_buffer(0, Some(storage.buffer()), in_off);
3987+ ce.set_output_buffer(1, Some(out_ref), 0);
3988+ ce.set_input_buffer(2, Some(&w_buf), 0);
3989+ ce.set_bytes(3, &inn);
3990+ ce.set_bytes(4, &eps);
3991+ // One threadgroup per token; width = multiple of 32, capped at the pipeline
3992+ // max (we want enough lanes to stride over inn=1536 cheaply).
3993+ const SIMDW: usize = 32;
3994+ let max_w = pipes.rmsnorm.max_total_threads_per_threadgroup();
3995+ let mut tgw = (8 * SIMDW).min(max_w).min(self.inn);
3996+ tgw = (tgw / SIMDW).max(1) * SIMDW;
3997+ let grid = MTLSize { width: self.tokens * tgw, height: 1, depth: 1 };
3998+ let tgroup = MTLSize { width: tgw, height: 1, depth: 1 };
3999+ ce.dispatch_threads(grid, tgroup);
4000+ drop(enc);
4001+
4002+ let news = candle_core::MetalStorage::new(out_buf, dev.clone(), elem, DType::BF16);
4003+ Ok((news, layout.shape().clone()))
4004+ }
4005+}
4006+
4007+// ───────────────────────── fused RoPE (strided-view input) ─────────────────────────
4008+
4009+/// Apply RoPE (rotate-half / GPT-NeoX convention, == candle_nn::rotary_emb::rope) to
4010+/// a TRANSPOSED q/k view `[b, h, t, d]` WITHOUT first making it contiguous. The
4011+/// kernel reads the source through its real strides and writes a fresh contiguous
4012+/// `[b, h, t, d]` bf16 tensor, so candle's separate `.contiguous()` blit copy + the
4013+/// rope dispatch collapse into ONE pass. `x` must be bf16 on Metal; `cos`/`sin` are
4014+/// `[t, d/2]` contiguous bf16. Returns a contiguous bf16 tensor of the same shape.
4015+///
4016+/// We build the encoder directly (binding all three source buffers) so candle's
4017+/// hazard tracker sees the real reads — there is no candle op that consumes a
4018+/// strided input here, hence a hand-rolled dispatch rather than a CustomOp.
4019+pub fn rope_apply(x: &Tensor, cos: &Tensor, sin: &Tensor) -> Result<Tensor> {
4020+ use objc2_metal::MTLSize;
4021+ let (b, h, t, d) = x.dims4()?;
4022+ let device = x.device().clone();
4023+ let cdev = match &device {
4024+ Device::Metal(m) => m.clone(),
4025+ _ => return Err(anyhow!("rope_apply requires the Metal device")),
4026+ };
4027+ let mdev = cdev.metal_device();
4028+ let pipes = get_pipelines(mdev)?;
4029+
4030+ // Source buffer + per-dim strides (in ELEMENTS) of the (possibly transposed) view.
4031+ let (x_s, x_l) = x.storage_and_layout();
4032+ let x_buf = match &*x_s {
4033+ candle_core::Storage::Metal(ms) => ms.buffer().clone(),
4034+ _ => return Err(anyhow!("rope_apply input must be on Metal")),
4035+ };
4036+ if x.dtype() != DType::BF16 {
4037+ return Err(anyhow!("rope_apply expects bf16 input, got {:?}", x.dtype()));
4038+ }
4039+ let st = x_l.stride(); // [s_b, s_h, s_t, s_d]
4040+ if st.len() != 4 {
4041+ return Err(anyhow!("rope_apply expects a 4D layout"));
4042+ }
4043+ let x_off = x_l.start_offset() * 2; // bf16 byte offset
4044+
4045+ // cos/sin are required to ALREADY be contiguous bf16 [t, d/2] (the rope tables
4046+ // are built bf16 at model load and only narrowed — a metadata view — per token).
4047+ // We therefore consume them straight through their strides: NO per-call
4048+ // `.to_dtype(bf16)` / `.contiguous()` prep. Those used to fire 2 throwaway
4049+ // micro-dispatches each here, and rope_apply runs twice per layer (q and k), so
4050+ // ~4×28 ≈ 112 cos/sin prep dispatches/token were pure pipeline-draining overhead
4051+ // on a 64-element slice. (to_dtype/contiguous short-circuit to a clone when
4052+ // already bf16/contiguous, but we drop them outright to keep the path tight and
4053+ // assert the precondition instead.)
4054+ debug_assert_eq!(cos.dtype(), DType::BF16, "rope cos must be bf16");
4055+ debug_assert_eq!(sin.dtype(), DType::BF16, "rope sin must be bf16");
4056+ debug_assert!(cos.is_contiguous(), "rope cos must be contiguous");
4057+ debug_assert!(sin.is_contiguous(), "rope sin must be contiguous");
4058+ let buf_of = |tns: &Tensor| -> Result<(Buffer, usize)> {
4059+ let (s, l) = tns.storage_and_layout();
4060+ match &*s {
4061+ candle_core::Storage::Metal(ms) => Ok((ms.buffer().clone(), l.start_offset() * 2)),
4062+ _ => Err(anyhow!("rope_apply cos/sin must be on Metal")),
4063+ }
4064+ };
4065+ let (cos_buf, cos_off) = buf_of(cos)?;
4066+ let (sin_buf, sin_off) = buf_of(sin)?;
4067+
4068+ let out_elems = b * h * t * d;
4069+ let out_buf = cdev.new_buffer(out_elems, DType::BF16, "tq_rope")?;
4070+
4071+ let h_u = h as u32;
4072+ let t_u = t as u32;
4073+ let d_u = d as u32;
4074+ // strides as i32x4 (sb, sh, st, sd). head_dim 128, ctx <= max_position → fits i32.
4075+ let strides: [i32; 4] = [st[0] as i32, st[1] as i32, st[2] as i32, st[3] as i32];
4076+ {
4077+ let enc = cdev.command_encoder()?;
4078+ let ce: &ComputeCommandEncoder = enc.as_ref();
4079+ ce.set_compute_pipeline_state(&pipes.rope_bf16);
4080+ ce.set_input_buffer(0, Some(&x_buf), x_off);
4081+ ce.set_output_buffer(1, Some(out_buf.as_ref()), 0);
4082+ ce.set_input_buffer(2, Some(&cos_buf), cos_off);
4083+ ce.set_input_buffer(3, Some(&sin_buf), sin_off);
4084+ ce.set_bytes(4, &h_u);
4085+ ce.set_bytes(5, &t_u);
4086+ ce.set_bytes(6, &d_u);
4087+ ce.set_bytes_directly(7, std::mem::size_of_val(&strides), strides.as_ptr().cast());
4088+ // grid: (d/2, t, b*h) threads — one per (i_d<d/2, position, batch*head).
4089+ let grid = MTLSize { width: d / 2, height: t, depth: b * h };
4090+ let tgroup = MTLSize { width: d / 2, height: 1, depth: 1 };
4091+ ce.dispatch_threads(grid, tgroup);
4092+ }
4093+
4094+ let storage = candle_core::MetalStorage::new(out_buf, cdev.clone(), out_elems, DType::BF16);
4095+ let out = candle_core::Tensor::from_storage(
4096+ candle_core::Storage::Metal(storage),
4097+ Shape::from_dims(&[b, h, t, d]),
4098+ candle_core::op::BackpropOp::none(),
4099+ false,
4100+ );
4101+ Ok(out)
4102+}
added src/qwen2_legacy.rs +603 −0
@@ -0,0 +1,603 @@
1+// LEGACY inlined qwen2 forward — the ORIGINAL hard-forked qwen2 model (pre-Step-0).
2+//
3+// This is the pristine hand-forked qwen2 forward that shipped before the config-
4+// driven registry refactor. It stays the DEFAULT path (COCO_REGISTRY unset) so the
5+// Step-0 gate can A/B the OLD inlined path against the NEW registry path
6+// (`model.rs` / `config.rs`, COCO_REGISTRY=1) inside ONE binary.
7+//
8+// It reuses the shared load-time machinery (`Proj`, `WeightSource`, `WeightStats`)
9+// from `qwen2_q.rs` verbatim — only the forward (RoPE/GQA-flash-decode/SwiGLU/Model)
10+// lives here. Behavior is byte-identical to the original qwen2_q.rs::Model.
11+
12+use anyhow::Result;
13+use candle_core::{DType, Device, Module, Tensor, D};
14+use candle_nn::{Activation, VarBuilder};
15+use candle_transformers::models::qwen2::Config;
16+use std::sync::Arc;
17+
18+use crate::qlinear::{fuse_resid_enabled, rope_apply, KvCache, QGroup, QWeight, RmsNormFused};
19+use crate::qwen2_q::{Proj, WeightSource, WeightStats};
20+use crate::turboquant::{encode, LLOYD_MAX_3BIT};
21+
22+thread_local! {
23+ /// (layers_secs, head_secs, count) accumulated across profiled decode steps.
24+ static PROFILE_ACC: std::cell::RefCell<(f64, f64, usize)> =
25+ const { std::cell::RefCell::new((0.0, 0.0, 0)) };
26+
27+ /// Per-token cached RoPE cos/sin slice: (seqlen_offset, seq_len, cos, sin).
28+ static ROPE_SLICE_CACHE: std::cell::RefCell<Option<(usize, usize, Tensor, Tensor)>> =
29+ const { std::cell::RefCell::new(None) };
30+}
31+
32+/// Print + reset the COCO_PROFILE accumulator (called from the bench harness).
33+pub fn profile_report() {
34+ PROFILE_ACC.with(|a| {
35+ let (l, h, n) = *a.borrow();
36+ if n > 0 {
37+ eprintln!(
38+ "PROFILE n={} | layers {:.3} ms/tok | norm+lm_head {:.3} ms/tok | total {:.3} ms/tok",
39+ n,
40+ l / n as f64 * 1e3,
41+ h / n as f64 * 1e3,
42+ (l + h) / n as f64 * 1e3,
43+ );
44+ }
45+ });
46+}
47+
48+fn fused_max_ctx() -> usize {
49+ std::env::var("COCO_MAX_CTX")
50+ .ok()
51+ .and_then(|s| s.parse().ok())
52+ .unwrap_or(8192)
53+}
54+
55+fn fused_attn_enabled() -> bool {
56+ !matches!(std::env::var("COCO_FUSED_ATTN").as_deref(), Ok("0"))
57+}
58+
59+fn fused_min_ctx() -> usize {
60+ std::env::var("COCO_FUSED_MIN_CTX")
61+ .ok()
62+ .and_then(|s| s.parse().ok())
63+ .unwrap_or(0)
64+}
65+
66+// ─────────────────────────── model (forked) ───────────────────────────
67+
68+struct RotaryEmbedding {
69+ sin: Tensor,
70+ cos: Tensor,
71+}
72+
73+impl RotaryEmbedding {
74+ fn new(dtype: DType, cfg: &Config, dev: &Device) -> Result<Self> {
75+ let dim = cfg.hidden_size / cfg.num_attention_heads;
76+ let max_seq_len = cfg.max_position_embeddings;
77+ let inv_freq: Vec<_> = (0..dim)
78+ .step_by(2)
79+ .map(|i| 1f32 / cfg.rope_theta.powf(i as f64 / dim as f64) as f32)
80+ .collect();
81+ let inv_freq_len = inv_freq.len();
82+ let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?.to_dtype(dtype)?;
83+ let t = Tensor::arange(0u32, max_seq_len as u32, dev)?
84+ .to_dtype(dtype)?
85+ .reshape((max_seq_len, 1))?;
86+ let freqs = t.matmul(&inv_freq)?;
87+ Ok(Self {
88+ sin: freqs.sin()?,
89+ cos: freqs.cos()?,
90+ })
91+ }
92+
93+ fn apply_rotary_emb_qkv(
94+ &self,
95+ q: &Tensor,
96+ k: &Tensor,
97+ seqlen_offset: usize,
98+ ) -> Result<(Tensor, Tensor)> {
99+ let (_b_sz, _h, seq_len, _n_embd) = q.dims4()?;
100+ let (cos, sin) = ROPE_SLICE_CACHE.with(|c| -> Result<(Tensor, Tensor)> {
101+ let mut c = c.borrow_mut();
102+ if let Some((off, len, cos, sin)) = c.as_ref() {
103+ if *off == seqlen_offset && *len == seq_len {
104+ return Ok((cos.clone(), sin.clone()));
105+ }
106+ }
107+ let cos = self.cos.narrow(0, seqlen_offset, seq_len)?;
108+ let sin = self.sin.narrow(0, seqlen_offset, seq_len)?;
109+ *c = Some((seqlen_offset, seq_len, cos.clone(), sin.clone()));
110+ Ok((cos, sin))
111+ })?;
112+ if std::env::var("COCO_NO_FUSE_ROPE").is_err()
113+ && matches!(q.device(), Device::Metal(_))
114+ && q.dtype() == DType::BF16
115+ {
116+ let q_embed = rope_apply(q, &cos, &sin)?;
117+ let k_embed = rope_apply(k, &cos, &sin)?;
118+ return Ok((q_embed, k_embed));
119+ }
120+ let q_embed = candle_nn::rotary_emb::rope(&q.contiguous()?, &cos, &sin)?;
121+ let k_embed = candle_nn::rotary_emb::rope(&k.contiguous()?, &cos, &sin)?;
122+ Ok((q_embed, k_embed))
123+ }
124+}
125+
126+struct MLP {
127+ gate_up: QGroup,
128+ down_proj: Proj,
129+ act_fn: Activation,
130+}
131+
132+impl MLP {
133+ fn new(src: &mut WeightSource, prefix: &str, cfg: &Config) -> Result<Self> {
134+ Ok(Self {
135+ gate_up: src.quant_group(&[
136+ (&format!("{prefix}.gate_proj"), false),
137+ (&format!("{prefix}.up_proj"), false),
138+ ])?,
139+ down_proj: src.proj(&format!("{prefix}.down_proj"), false)?,
140+ act_fn: cfg.hidden_act,
141+ })
142+ }
143+
144+ fn forward(&self, xs: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> {
145+ if let Proj::Quant(down) = &self.down_proj {
146+ if let Some(out) = self.gate_up.forward_ffn_mega(xs, down)? {
147+ return match resid {
148+ Some(r) => Ok((out + r)?),
149+ None => Ok(out),
150+ };
151+ }
152+ }
153+ let fuse = std::env::var("COCO_FUSE_SWIGLU").as_deref() != Ok("0");
154+ if fuse {
155+ if let Some(act) = self.gate_up.forward_swiglu(xs)? {
156+ return match resid {
157+ Some(r) => self.down_proj.forward_resid(&act, r),
158+ None => self.down_proj.forward(&act),
159+ };
160+ }
161+ }
162+ let mut gu = self.gate_up.forward(xs)?;
163+ let rhs = gu.pop().unwrap();
164+ let lhs = gu.pop().unwrap().apply(&self.act_fn)?;
165+ let act = (lhs * rhs)?;
166+ match resid {
167+ Some(r) => self.down_proj.forward_resid(&act, r),
168+ None => self.down_proj.forward(&act),
169+ }
170+ }
171+}
172+
173+struct Attention {
174+ qkv: QGroup,
175+ o_proj: Proj,
176+ num_heads: usize,
177+ num_kv_heads: usize,
178+ num_kv_groups: usize,
179+ head_dim: usize,
180+ hidden_size: usize,
181+ rotary_emb: Arc<RotaryEmbedding>,
182+ kv_cache: Option<(Tensor, Tensor)>,
183+ kv_fast: Option<KvCache>,
184+ fused: bool,
185+}
186+
187+impl Attention {
188+ fn new(
189+ src: &mut WeightSource,
190+ prefix: &str,
191+ rotary_emb: Arc<RotaryEmbedding>,
192+ cfg: &Config,
193+ ) -> Result<Self> {
194+ let hidden_sz = cfg.hidden_size;
195+ let num_heads = cfg.num_attention_heads;
196+ let num_kv_heads = cfg.num_key_value_heads;
197+ let num_kv_groups = num_heads / num_kv_heads;
198+ let head_dim = hidden_sz / num_heads;
199+ Ok(Self {
200+ qkv: src.quant_group(&[
201+ (&format!("{prefix}.q_proj"), true),
202+ (&format!("{prefix}.k_proj"), true),
203+ (&format!("{prefix}.v_proj"), true),
204+ ])?,
205+ o_proj: src.proj(&format!("{prefix}.o_proj"), false)?,
206+ num_heads,
207+ num_kv_heads,
208+ num_kv_groups,
209+ head_dim,
210+ hidden_size: hidden_sz,
211+ rotary_emb,
212+ kv_cache: None,
213+ kv_fast: None,
214+ fused: fused_attn_enabled(),
215+ })
216+ }
217+
218+ fn forward(
219+ &mut self,
220+ xs: &Tensor,
221+ attention_mask: Option<&Tensor>,
222+ seqlen_offset: usize,
223+ resid: Option<&Tensor>,
224+ ) -> Result<Tensor> {
225+ let (b_sz, q_len, _) = xs.dims3()?;
226+
227+ let mut qkv = self.qkv.forward(xs)?;
228+ let value_states = qkv.pop().unwrap();
229+ let key_states = qkv.pop().unwrap();
230+ let query_states = qkv.pop().unwrap();
231+
232+ let query_states = query_states
233+ .reshape((b_sz, q_len, self.num_heads, self.head_dim))?
234+ .transpose(1, 2)?;
235+ let key_states = key_states
236+ .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))?
237+ .transpose(1, 2)?;
238+ let value_states = value_states
239+ .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))?
240+ .transpose(1, 2)?;
241+
242+ let (query_states, key_states) =
243+ self.rotary_emb
244+ .apply_rotary_emb_qkv(&query_states, &key_states, seqlen_offset)?;
245+
246+ if self.fused && b_sz == 1 {
247+ if self.kv_fast.is_none() {
248+ self.kv_fast = Some(KvCache::new(
249+ self.num_heads,
250+ self.num_kv_heads,
251+ self.head_dim,
252+ fused_max_ctx(),
253+ query_states.device(),
254+ )?);
255+ }
256+ let k_f = key_states.squeeze(0)?.contiguous()?;
257+ let v_f = value_states.squeeze(0)?.contiguous()?;
258+
259+ if q_len == 1 {
260+ let ctx_now = self.kv_fast.as_ref().unwrap().len();
261+ let k1 = k_f.squeeze(1)?;
262+ let v1 = v_f.squeeze(1)?;
263+ if ctx_now >= fused_min_ctx() {
264+ let kc = self.kv_fast.as_mut().unwrap();
265+ let q_f = query_states.squeeze(0)?.squeeze(1)?.contiguous()?;
266+ let attn = kc.decode(&q_f, &k1, &v1)?;
267+ let attn = attn.to_dtype(xs.dtype())?;
268+ return match resid {
269+ Some(r) => self.o_proj.forward_resid(&attn, r),
270+ None => self.o_proj.forward(&attn),
271+ };
272+ } else {
273+ self.kv_fast
274+ .as_mut()
275+ .unwrap()
276+ .append_prefill(&k1.unsqueeze(1)?, &v1.unsqueeze(1)?)?;
277+ return self.candle_attention(
278+ &query_states,
279+ &key_states,
280+ &value_states,
281+ attention_mask,
282+ b_sz,
283+ q_len,
284+ resid,
285+ );
286+ }
287+ } else {
288+ self.kv_fast.as_mut().unwrap().append_prefill(&k_f, &v_f)?;
289+ return self.candle_attention(
290+ &query_states,
291+ &key_states,
292+ &value_states,
293+ attention_mask,
294+ b_sz,
295+ q_len,
296+ resid,
297+ );
298+ }
299+ }
300+
301+ self.candle_attention(
302+ &query_states,
303+ &key_states,
304+ &value_states,
305+ attention_mask,
306+ b_sz,
307+ q_len,
308+ resid,
309+ )
310+ }
311+
312+ #[allow(clippy::too_many_arguments)]
313+ fn candle_attention(
314+ &mut self,
315+ query_states: &Tensor,
316+ key_states: &Tensor,
317+ value_states: &Tensor,
318+ attention_mask: Option<&Tensor>,
319+ b_sz: usize,
320+ q_len: usize,
321+ resid: Option<&Tensor>,
322+ ) -> Result<Tensor> {
323+ let (key_states, value_states) = match &self.kv_cache {
324+ None => (key_states.clone(), value_states.clone()),
325+ Some((prev_k, prev_v)) => {
326+ let key_states = Tensor::cat(&[prev_k, key_states], 2)?;
327+ let value_states = Tensor::cat(&[prev_v, value_states], 2)?;
328+ (key_states, value_states)
329+ }
330+ };
331+ self.kv_cache = Some((key_states.clone(), value_states.clone()));
332+
333+ let key_states =
334+ candle_transformers::utils::repeat_kv(key_states, self.num_kv_groups)?.contiguous()?;
335+ let value_states =
336+ candle_transformers::utils::repeat_kv(value_states, self.num_kv_groups)?.contiguous()?;
337+
338+ let attn_output = {
339+ let scale = 1f64 / f64::sqrt(self.head_dim as f64);
340+ let attn_weights = (query_states.matmul(&key_states.transpose(2, 3)?)? * scale)?;
341+
342+ let attn_weights = match attention_mask {
343+ None => attn_weights,
344+ Some(mask) => attn_weights.broadcast_add(mask)?,
345+ };
346+ let attn_weights = candle_nn::ops::softmax_last_dim(&attn_weights)?;
347+ attn_weights.matmul(&value_states)?
348+ };
349+ let attn_output = attn_output
350+ .transpose(1, 2)?
351+ .reshape((b_sz, q_len, self.hidden_size))?;
352+ match resid {
353+ Some(r) => self.o_proj.forward_resid(&attn_output, r),
354+ None => self.o_proj.forward(&attn_output),
355+ }
356+ }
357+
358+ fn clear_kv_cache(&mut self) {
359+ self.kv_cache = None;
360+ if let Some(kc) = self.kv_fast.as_mut() {
361+ kc.clear();
362+ }
363+ }
364+}
365+
366+struct DecoderLayer {
367+ self_attn: Attention,
368+ mlp: MLP,
369+ input_layernorm: RmsNormFused,
370+ post_attention_layernorm: RmsNormFused,
371+}
372+
373+impl DecoderLayer {
374+ fn new(
375+ src: &mut WeightSource,
376+ idx: usize,
377+ rotary_emb: Arc<RotaryEmbedding>,
378+ cfg: &Config,
379+ norm_vb: &VarBuilder,
380+ ) -> Result<Self> {
381+ let prefix = format!("model.layers.{idx}");
382+ let self_attn = Attention::new(src, &format!("{prefix}.self_attn"), rotary_emb, cfg)?;
383+ let mlp = MLP::new(src, &format!("{prefix}.mlp"), cfg)?;
384+ let input_layernorm = RmsNormFused::new(
385+ norm_vb
386+ .pp(format!("model.layers.{idx}.input_layernorm"))
387+ .get(cfg.hidden_size, "weight")?,
388+ cfg.rms_norm_eps,
389+ )?;
390+ let post_attention_layernorm = RmsNormFused::new(
391+ norm_vb
392+ .pp(format!("model.layers.{idx}.post_attention_layernorm"))
393+ .get(cfg.hidden_size, "weight")?,
394+ cfg.rms_norm_eps,
395+ )?;
396+ Ok(Self {
397+ self_attn,
398+ mlp,
399+ input_layernorm,
400+ post_attention_layernorm,
401+ })
402+ }
403+
404+ fn forward(
405+ &mut self,
406+ xs: &Tensor,
407+ attention_mask: Option<&Tensor>,
408+ seqlen_offset: usize,
409+ ) -> Result<Tensor> {
410+ let residual = xs;
411+ let xs = self.input_layernorm.forward(xs)?;
412+ if fuse_resid_enabled() {
413+ let h = self
414+ .self_attn
415+ .forward(&xs, attention_mask, seqlen_offset, Some(residual))?;
416+ let normed = self.post_attention_layernorm.forward(&h)?;
417+ return self.mlp.forward(&normed, Some(&h));
418+ }
419+ let attn_out = self
420+ .self_attn
421+ .forward(&xs, attention_mask, seqlen_offset, None)?;
422+ let (h, normed) = self.post_attention_layernorm.forward_add(residual, &attn_out)?;
423+ let xs2 = self.mlp.forward(&normed, None)?;
424+ Ok((&h + xs2)?)
425+ }
426+
427+ fn clear_kv_cache(&mut self) {
428+ self.self_attn.clear_kv_cache()
429+ }
430+}
431+
432+pub struct Model {
433+ embed_tokens: candle_nn::Embedding,
434+ layers: Vec<DecoderLayer>,
435+ norm: RmsNormFused,
436+ lm_head: Proj,
437+ sliding_window: usize,
438+ device: Device,
439+ dtype: DType,
440+}
441+
442+impl Model {
443+ pub fn new(cfg: &Config, mut src: WeightSource, vb: VarBuilder) -> Result<(Self, WeightStats)> {
444+ let device = src.device.clone();
445+ let dtype = src.dtype;
446+ let vb_m = vb.pp("model");
447+ let embed_tokens =
448+ candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embed_tokens"))?;
449+ let rotary_emb = Arc::new(RotaryEmbedding::new(dtype, cfg, &device)?);
450+ let mut layers = Vec::with_capacity(cfg.num_hidden_layers);
451+ for idx in 0..cfg.num_hidden_layers {
452+ layers.push(DecoderLayer::new(&mut src, idx, rotary_emb.clone(), cfg, &vb)?);
453+ }
454+ let norm = RmsNormFused::new(
455+ vb_m.pp("norm").get(cfg.hidden_size, "weight")?,
456+ cfg.rms_norm_eps,
457+ )?;
458+
459+ let head_separate = vb.contains_tensor("lm_head.weight");
460+ let quant_head = matches!(std::env::var("COCO_QUANT_HEAD").as_deref(), Ok(v) if v != "0");
461+ let lm_head = if !head_separate {
462+ if quant_head {
463+ eprintln!(
464+ "COCO_QUANT_HEAD set but this model TIES lm_head to the embeddings \
465+ (no separate lm_head.weight) — keeping the head fp16 to avoid \
466+ double-quantizing the shared embedding matrix."
467+ );
468+ }
469+ Proj::Dense(candle_nn::Linear::new(embed_tokens.embeddings().clone(), None))
470+ } else if quant_head {
471+ if matches!(std::env::var("COCO_QUANT_HEAD").as_deref(), Ok("8")) {
472+ eprintln!(
473+ "COCO_QUANT_HEAD=8 requested but the qmatvec kernel is 3-bit (8-level) \
474+ only — a Q8 head is not wired; using the standard turboquant 3-bit head."
475+ );
476+ }
477+ let w = vb
478+ .get((cfg.vocab_size, cfg.hidden_size), "lm_head.weight")?
479+ .to_dtype(DType::F32)?
480+ .flatten_all()?
481+ .to_vec1::<f32>()?;
482+ let q = encode(&w, cfg.vocab_size, cfg.hidden_size, &src.cfg, &LLOYD_MAX_3BIT);
483+ drop(w);
484+ let qw = QWeight::from_tq(&q, None, &device)?;
485+ src.total_compressed_bytes += qw.compressed_bytes;
486+ src.total_fp16_bytes += cfg.vocab_size * cfg.hidden_size * 2;
487+ src.n_quant += 1;
488+ eprintln!(
489+ "COCO_QUANT_HEAD: lm_head compressed {:.1} MB fp16 -> {:.1} MB (3-bit)",
490+ (cfg.vocab_size * cfg.hidden_size * 2) as f64 / (1024.0 * 1024.0),
491+ qw.compressed_bytes as f64 / (1024.0 * 1024.0),
492+ );
493+ Proj::Quant(qw)
494+ } else {
495+ Proj::Dense(candle_nn::linear_no_bias(
496+ cfg.hidden_size,
497+ cfg.vocab_size,
498+ vb.pp("lm_head"),
499+ )?)
500+ };
501+
502+ let stats = src.stats();
503+ Ok((
504+ Self {
505+ embed_tokens,
506+ layers,
507+ norm,
508+ lm_head,
509+ sliding_window: cfg.sliding_window,
510+ device,
511+ dtype,
512+ },
513+ stats,
514+ ))
515+ }
516+
517+ fn prepare_causal_attention_mask(
518+ &self,
519+ b_size: usize,
520+ tgt_len: usize,
521+ seqlen_offset: usize,
522+ ) -> Result<Tensor> {
523+ let mask: Vec<_> = (0..tgt_len)
524+ .flat_map(|i| {
525+ (0..tgt_len).map(move |j| {
526+ if i < j || j + self.sliding_window < i {
527+ f32::NEG_INFINITY
528+ } else {
529+ 0.
530+ }
531+ })
532+ })
533+ .collect();
534+ let mask = Tensor::from_slice(&mask, (tgt_len, tgt_len), &self.device)?;
535+ let mask = if seqlen_offset > 0 {
536+ let mask0 = Tensor::zeros((tgt_len, seqlen_offset), DType::F32, &self.device)?;
537+ Tensor::cat(&[&mask0, &mask], D::Minus1)?
538+ } else {
539+ mask
540+ };
541+ Ok(mask
542+ .expand((b_size, 1, tgt_len, tgt_len + seqlen_offset))?
543+ .to_dtype(self.dtype)?)
544+ }
545+
546+ pub fn forward(&mut self, input_ids: &Tensor, seqlen_offset: usize) -> Result<Tensor> {
547+ let (b_size, seq_len) = input_ids.dims2()?;
548+ let attention_mask: Option<Tensor> = if seq_len <= 1 {
549+ None
550+ } else {
551+ Some(self.prepare_causal_attention_mask(b_size, seq_len, seqlen_offset)?)
552+ };
553+ let profile = seq_len == 1 && std::env::var("COCO_PROFILE").is_ok();
554+ let mut xs = self.embed_tokens.forward(input_ids)?;
555+ if profile {
556+ self.device.synchronize()?;
557+ let t = std::time::Instant::now();
558+ for layer in self.layers.iter_mut() {
559+ xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)?;
560+ }
561+ self.device.synchronize()?;
562+ let t_layers = t.elapsed().as_secs_f64();
563+ let t = std::time::Instant::now();
564+ let xn = xs.narrow(1, seq_len - 1, 1)?;
565+ let xn = self.norm.forward(&xn)?;
566+ let out = self.lm_head.forward(&xn)?;
567+ self.device.synchronize()?;
568+ let t_head = t.elapsed().as_secs_f64();
569+ PROFILE_ACC.with(|a| {
570+ let mut a = a.borrow_mut();
571+ a.0 += t_layers;
572+ a.1 += t_head;
573+ a.2 += 1;
574+ });
575+ return Ok(out);
576+ }
577+ for layer in self.layers.iter_mut() {
578+ xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)?;
579+ }
580+ let xs = xs.narrow(1, seq_len - 1, 1)?;
581+ let xs = self.norm.forward(&xs)?;
582+ self.lm_head.forward(&xs)
583+ }
584+
585+ pub fn clear_kv_cache(&mut self) {
586+ for layer in self.layers.iter_mut() {
587+ layer.clear_kv_cache()
588+ }
589+ }
590+}
591+
592+// The legacy inlined model also satisfies the shared `Model` contract so main.rs can
593+// hold it in the SAME `Box<dyn Model>` as the registry path — the ONLY difference
594+// between the two paths is which builder ran, gated by COCO_REGISTRY. The methods
595+// forward verbatim to the inherent ones above (byte-identical behavior).
596+impl crate::model::Model for Model {
597+ fn forward(&mut self, ids: &Tensor, offset: usize) -> Result<Tensor> {
598+ Model::forward(self, ids, offset)
599+ }
600+ fn clear_kv_cache(&mut self) {
601+ Model::clear_kv_cache(self)
602+ }
603+}
added src/qwen2_q.rs +163 −0
@@ -0,0 +1,163 @@
1+// Shared load-time turboquant machinery for the config-driven decoder.
2+//
3+// STEP 0 refactor: the inlined qwen2 forward (RmsNorm/RoPE/GQA-flash-decode/SwiGLU +
4+// the Model struct) moved to `model.rs` behind the `Model`/`SequenceMixer` traits.
5+// What remains here is the arch-agnostic LOAD-TIME machinery the design says to reuse
6+// verbatim (design §1.2, §1.4): the `Proj` projection enum (dense fp16 OR compressed
7+// QWeight), the `WeightSource` turboquant encoder, and `WeightStats`. These know only
8+// linear shapes — zero architecture knowledge — so every arch's wiring calls the same
9+// `quant` / `quant_group` / `quant_lm_head` here.
10+
11+use anyhow::Result;
12+use candle_core::{DType, Device, Tensor};
13+use candle_nn::VarBuilder;
14+use std::collections::HashMap;
15+
16+use crate::qlinear::{QGroup, QWeight};
17+use crate::turboquant::{encode, TqConfig, LLOYD_MAX_3BIT};
18+
19+/// A projection that is either a dense fp16 Linear or a compressed QWeight.
20+/// (`Dense` is the documented fp16 fallback; the fast path uses `Quant` for all
21+/// seven projections.) Design §1.2 promotes this toward the shared `QLinear`.
22+#[allow(dead_code)]
23+pub enum Proj {
24+ Dense(candle_nn::Linear),
25+ Quant(QWeight),
26+}
27+
28+impl Proj {
29+ pub fn forward(&self, x: &Tensor) -> Result<Tensor> {
30+ match self {
31+ Proj::Dense(l) => Ok(candle_core::Module::forward(l, x)?),
32+ Proj::Quant(q) => q.forward(x),
33+ }
34+ }
35+
36+ /// forward + residual, with the residual folded into the qmatvec store
37+ /// epilogue on the quant path (COCO_FUSE_RESID). Dense keeps the plain add.
38+ pub fn forward_resid(&self, x: &Tensor, resid: &Tensor) -> Result<Tensor> {
39+ match self {
40+ Proj::Dense(l) => Ok((candle_core::Module::forward(l, x)? + resid)?),
41+ Proj::Quant(q) => q.forward_resid(x, resid),
42+ }
43+ }
44+}
45+
46+/// Holds the raw fp16 weights pulled from safetensors, used to build projections.
47+/// We turboquant-encode the target weights at build time (data-free) and hand
48+/// the compressed `TqWeight` to the GPU; non-target weights stay dense.
49+pub struct WeightSource {
50+ pub tensors: HashMap<String, Tensor>, // CPU f32 copies of the quant-target tensors
51+ pub device: Device,
52+ pub dtype: DType,
53+ pub cfg: TqConfig,
54+ pub total_compressed_bytes: usize,
55+ pub total_fp16_bytes: usize,
56+ pub n_quant: usize,
57+}
58+
59+impl WeightSource {
60+ /// Bias tensor (if present) on device, in model dtype. Removed from the map.
61+ fn bias(&mut self, name: &str) -> Result<Option<Tensor>> {
62+ match self.tensors.remove(&format!("{name}.bias")) {
63+ Some(t) => Ok(Some(t.to_dtype(self.dtype)?.to_device(&self.device)?)),
64+ None => Ok(None),
65+ }
66+ }
67+
68+ /// Build a projection: turboquant-encode the weight data-free and keep it
69+ /// COMPRESSED on the GPU. The f32 source weight is REMOVED from the map (freed)
70+ /// right after encoding so the build-time RAM peak stays bounded.
71+ fn quant(&mut self, name: &str, bias: bool) -> Result<Proj> {
72+ let wt = self
73+ .tensors
74+ .remove(&format!("{name}.weight"))
75+ .ok_or_else(|| anyhow::anyhow!("missing {name}.weight"))?;
76+ let dims = wt.dims().to_vec();
77+ let (out, inn) = (dims[0], dims[1]);
78+ let w: Vec<f32> = wt.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
79+ drop(wt);
80+ let q = encode(&w, out, inn, &self.cfg, &LLOYD_MAX_3BIT);
81+
82+ let b = if bias { self.bias(name)? } else { None };
83+ let qw = QWeight::from_tq(&q, b, &self.device)?;
84+
85+ self.total_compressed_bytes += qw.compressed_bytes;
86+ self.total_fp16_bytes += out * inn * 2;
87+ self.n_quant += 1;
88+ Ok(Proj::Quant(qw))
89+ }
90+
91+ /// Build a projection, choosing dense vs quant. (Currently always quant.)
92+ pub fn proj(&mut self, name: &str, bias: bool) -> Result<Proj> {
93+ self.quant(name, bias)
94+ }
95+
96+ /// Build a FUSED group of projections that share the same input activation
97+ /// (q/k/v, or gate/up): encode each data-free, then concatenate their codes
98+ /// into one `QGroup` so the group runs as one rotate + one qmatvec.
99+ pub fn quant_group(&mut self, members: &[(&str, bool)]) -> Result<QGroup> {
100+ let mut qs = Vec::with_capacity(members.len());
101+ let mut biases = Vec::with_capacity(members.len());
102+ for (name, has_bias) in members {
103+ let wt = self
104+ .tensors
105+ .remove(&format!("{name}.weight"))
106+ .ok_or_else(|| anyhow::anyhow!("missing {name}.weight"))?;
107+ let dims = wt.dims().to_vec();
108+ let (out, inn) = (dims[0], dims[1]);
109+ let w: Vec<f32> = wt.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?;
110+ drop(wt);
111+ let q = encode(&w, out, inn, &self.cfg, &LLOYD_MAX_3BIT);
112+ biases.push(if *has_bias { self.bias(name)? } else { None });
113+ self.total_fp16_bytes += out * inn * 2;
114+ self.n_quant += 1;
115+ qs.push(q);
116+ }
117+ let refs: Vec<&_> = qs.iter().collect();
118+ let group = QGroup::from_tqs(&refs, biases, &self.device)?;
119+ self.total_compressed_bytes += group.compressed_bytes;
120+ Ok(group)
121+ }
122+
123+ /// Turboquant-compress a SEPARATE lm_head weight (pulled from the mmap'd VarBuilder,
124+ /// not the f32 map), data-free the same way a layer weight is. Returns the compressed
125+ /// weight + (compressed_bytes, fp16_bytes) for the caller's report. Stats are also
126+ /// folded into the running totals. Mirrors the old inlined COCO_QUANT_HEAD path.
127+ pub fn quant_lm_head(
128+ &mut self,
129+ vb: &VarBuilder,
130+ vocab_size: usize,
131+ hidden_size: usize,
132+ ) -> Result<(QWeight, usize, usize)> {
133+ let w = vb
134+ .get((vocab_size, hidden_size), "lm_head.weight")?
135+ .to_dtype(DType::F32)?
136+ .flatten_all()?
137+ .to_vec1::<f32>()?;
138+ let q = encode(&w, vocab_size, hidden_size, &self.cfg, &LLOYD_MAX_3BIT);
139+ drop(w);
140+ let qw = QWeight::from_tq(&q, None, &self.device)?;
141+ let comp = qw.compressed_bytes;
142+ let fp16 = vocab_size * hidden_size * 2;
143+ self.total_compressed_bytes += comp;
144+ self.total_fp16_bytes += fp16;
145+ self.n_quant += 1;
146+ Ok((qw, comp, fp16))
147+ }
148+
149+ /// Snapshot the accumulated load-time weight stats.
150+ pub fn stats(&self) -> WeightStats {
151+ WeightStats {
152+ n_quant: self.n_quant,
153+ compressed_bytes: self.total_compressed_bytes,
154+ fp16_bytes: self.total_fp16_bytes,
155+ }
156+ }
157+}
158+
159+pub struct WeightStats {
160+ pub n_quant: usize,
161+ pub compressed_bytes: usize,
162+ pub fp16_bytes: usize,
163+}
added src/turboquant.rs +636 −0
@@ -0,0 +1,636 @@
1+// coco turboquant-v2 — data-free weight quantization, pure Rust.
2+//
3+// Clean-room port of the validated POC math (lab/coco/poc/turboquant_v2.py):
4+// 1. Pad input dim of W (out,in) to next power of two P; multiply by a fixed
5+// ±1 sign vector seeded by a constant; apply an orthonormal Fast
6+// Walsh-Hadamard Transform along the (padded) input dim. This "incoherence
7+// rotation" spreads outliers across all coords so a single Gaussian
8+// codebook fits every weight matrix (concentration of measure on the sphere).
9+// 2. Flatten the rotated rows and split into blocks of d=128. Per block compute
10+// an fp16 RMS *radius*; normalize the block by the radius so coords ~ N(0,1).
11+// 3. Quantize each normalized coord to the nearest level of a precomputed
12+// Lloyd-Max N(0,1) codebook (bits=3 → 8 levels).
13+// 4. (Optional) outlier split: keep the top `outlier_frac` |rotated| values in
14+// fp16 in a sparse side-list; zero them before block quantization.
15+//
16+// Decode = codebook lookup → ×radius → restore outliers → inverse FWHT (same
17+// butterfly, it's self-inverse) → ×signs → crop to `inn` columns.
18+//
19+// NO Python, NO llama.cpp, NO external quant libs. FWHT + codebook + (de)quant
20+// are all implemented here. f16 is provided by candle's re-exported `half` crate.
21+
22+use half::f16;
23+
24+/// Lloyd-Max optimal scalar quantizer for N(0,1) at bits=3 (8 levels), sorted.
25+/// Computed once via Lloyd's algorithm on Gaussian samples in the POC; the values
26+/// are stable across seeds so we ship them as a const (matches turboquant.py's
27+/// `lloyd_max_gaussian(3)`). `codebook_for_bits` can rebuild any table at runtime.
28+pub const LLOYD_MAX_3BIT: [f32; 8] = [
29+ -2.152_152_3,
30+ -1.348_969_7,
31+ -0.762_198_9,
32+ -0.250_466_1,
33+ 0.240_071_25,
34+ 0.751_659_1,
35+ 1.339_368_1,
36+ 2.149_770_1,
37+];
38+
39+/// Build a Lloyd-Max N(0,1) codebook with 2^bits levels at runtime (Lloyd's
40+/// algorithm / k-means on Gaussian samples). Used as a fallback / for other bit
41+/// widths; bits=3 uses the const table by default for determinism & speed.
42+pub fn codebook_for_bits(bits: u32, iters: usize, n_samples: usize, seed: u64) -> Vec<f32> {
43+ // Deterministic Gaussian samples via a tiny splitmix64 + Box-Muller.
44+ let mut state = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
45+ let mut next_u64 = || {
46+ state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
47+ let mut z = state;
48+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
49+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
50+ z ^ (z >> 31)
51+ };
52+ let mut next_unit = || (next_u64() >> 11) as f64 / (1u64 << 53) as f64;
53+ let mut samples = Vec::with_capacity(n_samples);
54+ while samples.len() < n_samples {
55+ // Box-Muller; clamp u1 away from 0 to avoid ln(0).
56+ let u1 = next_unit().max(1e-12);
57+ let u2 = next_unit();
58+ let r = (-2.0 * u1.ln()).sqrt();
59+ let theta = std::f64::consts::TAU * u2;
60+ samples.push((r * theta.cos()) as f32);
61+ if samples.len() < n_samples {
62+ samples.push((r * theta.sin()) as f32);
63+ }
64+ }
65+ samples.sort_by(|a, b| a.partial_cmp(b).unwrap());
66+
67+ let k = 1usize << bits;
68+ // Init centroids at quantiles for stable convergence.
69+ let mut c: Vec<f32> = (0..k)
70+ .map(|j| {
71+ let q = (j as f64 + 0.5) / k as f64;
72+ let idx = ((q * samples.len() as f64) as usize).min(samples.len() - 1);
73+ samples[idx]
74+ })
75+ .collect();
76+
77+ for _ in 0..iters {
78+ // assign + accumulate (samples are sorted, but plain scan is fine here).
79+ let mut sum = vec![0f64; k];
80+ let mut cnt = vec![0u64; k];
81+ let edges: Vec<f32> = (0..k - 1).map(|j| (c[j] + c[j + 1]) / 2.0).collect();
82+ for &s in &samples {
83+ // nearest centroid = searchsorted on midpoint edges
84+ let mut j = 0usize;
85+ while j < edges.len() && s > edges[j] {
86+ j += 1;
87+ }
88+ sum[j] += s as f64;
89+ cnt[j] += 1;
90+ }
91+ let mut max_delta = 0f32;
92+ for j in 0..k {
93+ if cnt[j] > 0 {
94+ let newc = (sum[j] / cnt[j] as f64) as f32;
95+ max_delta = max_delta.max((newc - c[j]).abs());
96+ c[j] = newc;
97+ }
98+ }
99+ if max_delta < 1e-7 {
100+ break;
101+ }
102+ }
103+ c
104+}
105+
106+/// Fixed ±1 sign vector of length `p`, seeded by `seed` (splitmix64). Matches the
107+/// POC's `_signs(P, seed)` in spirit: a deterministic, reproducible sign flip.
108+///
109+/// `pub(crate)` so the fast inference path (`qlinear`) can rotate the ACTIVATION
110+/// with the exact same sign vector the encoder used for the weights.
111+pub(crate) fn signs(p: usize, seed: u64) -> Vec<f32> {
112+ let mut state = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
113+ let mut out = Vec::with_capacity(p);
114+ for _ in 0..p {
115+ state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
116+ let mut z = state;
117+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
118+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
119+ z ^= z >> 31;
120+ out.push(if z & 1 == 0 { 1.0 } else { -1.0 });
121+ }
122+ out
123+}
124+
125+/// In-place orthonormal Fast Walsh-Hadamard Transform on `x` (length must be a
126+/// power of two). Self-inverse: applying it twice is the identity. O(n log n).
127+///
128+/// `pub(crate)` so `qlinear` can rotate the activation per d-wide block.
129+pub(crate) fn fwht_inplace(x: &mut [f32]) {
130+ let n = x.len();
131+ debug_assert!(n.is_power_of_two(), "FWHT length must be a power of two");
132+ let mut h = 1usize;
133+ while h < n {
134+ let mut i = 0usize;
135+ while i < n {
136+ for j in i..i + h {
137+ let a = x[j];
138+ let b = x[j + h];
139+ x[j] = a + b;
140+ x[j + h] = a - b;
141+ }
142+ i += 2 * h;
143+ }
144+ h *= 2;
145+ }
146+ let scale = 1.0f32 / (n as f32).sqrt();
147+ for v in x.iter_mut() {
148+ *v *= scale;
149+ }
150+}
151+
152+/// Quantization config.
153+#[derive(Clone, Copy)]
154+pub struct TqConfig {
155+ pub d: usize, // block size along the flattened rotated rows
156+ pub bits: u32, // codebook bits (3 → 8 levels)
157+ pub outlier_frac: f32, // fraction of |rotated| values kept in fp16 (0.0 = off)
158+ pub seed: u64, // sign-vector seed
159+ /// Rotation mode:
160+ /// false → "v2": pad input dim to next power of two P and FWHT the WHOLE
161+ /// row (max quality, but codes scale with P → padding-bpw cost
162+ /// when inn is not already a power of two).
163+ /// true → "block": when inn is a multiple of `d`, FWHT each consecutive
164+ /// d-wide sub-block of the input independently (block-diagonal
165+ /// Hadamard). NO padding → exactly `bits` bpw for the codes
166+ /// (~3.125 bpw at d=128/bits=3). Slightly higher recon error than
167+ /// full-row rotation, equivalent to the v1 recipe's quality.
168+ pub block_hadamard: bool,
169+}
170+
171+impl Default for TqConfig {
172+ fn default() -> Self {
173+ Self { d: 128, bits: 3, outlier_frac: 0.005, seed: 0, block_hadamard: false }
174+ }
175+}
176+
177+/// Compressed representation of one weight matrix W (out, inn).
178+pub struct TqWeight {
179+ pub out: usize,
180+ pub inn: usize,
181+ pub p: usize, // rotated-grid columns per row (= next_pow2(inn) in v2 mode, = inn in block mode)
182+ pub d: usize,
183+ pub bits: u32,
184+ pub seed: u64,
185+ pub block_hadamard: bool, // which rotation was used (decode must match)
186+ pub codes: Vec<u8>, // one code (0..2^bits) per coord of the (out*P) rotated grid
187+ pub radius: Vec<f16>, // one fp16 RMS radius per block of d coords
188+ pub codebook: Vec<f32>, // 2^bits levels
189+ pub outlier_idx: Vec<u32>, // flat indices into the (out*P) grid kept in fp16
190+ pub outlier_val: Vec<f16>, // the corresponding fp16 values (rotated space)
191+}
192+
193+impl TqWeight {
194+ /// Bytes actually needed to store this compressed weight (codes packed to
195+ /// `bits` bits, fp16 radius, fp16 outlier values + u32 indices, codebook).
196+ pub fn compressed_bytes(&self) -> usize {
197+ let code_bits = self.codes.len() * self.bits as usize;
198+ let code_bytes = code_bits.div_ceil(8);
199+ let radius_bytes = self.radius.len() * 2;
200+ let outlier_bytes = self.outlier_idx.len() * 4 + self.outlier_val.len() * 2;
201+ let codebook_bytes = self.codebook.len() * 4;
202+ code_bytes + radius_bytes + outlier_bytes + codebook_bytes
203+ }
204+
205+ /// Effective bits-per-weight for this matrix (over the *original* inn*out
206+ /// weights), matching the POC's `tq_v2_bpw` accounting.
207+ pub fn bpw(&self) -> f64 {
208+ let orig = (self.out * self.inn) as f64;
209+ (self.compressed_bytes() * 8) as f64 / orig
210+ }
211+
212+ /// Pack the 3-bit codes two-per-byte (4-bit nibbles, low nibble first) for
213+ /// the fast GPU kernel. 3-bit codes (0..8) fit in a nibble with the top bit
214+ /// unused. This is what the kernel actually reads: 4 bpw resident for codes
215+ /// (vs 16 for fp16) — the matmul touches ~4× fewer bytes per weight.
216+ /// Returns a `Vec<u8>` of length `ceil(codes.len()/2)`.
217+ pub fn codes_packed_nibble(&self) -> Vec<u8> {
218+ let n = self.codes.len();
219+ let mut out = vec![0u8; n.div_ceil(2)];
220+ for (i, &c) in self.codes.iter().enumerate() {
221+ let byte = i / 2;
222+ if i & 1 == 0 {
223+ out[byte] |= c & 0x0F;
224+ } else {
225+ out[byte] |= (c & 0x0F) << 4;
226+ }
227+ }
228+ out
229+ }
230+
231+ /// Pack the 3-bit codes TRUE 3-bit: 8 codes → 3 bytes (24 bits) as a
232+ /// little-endian bitstream (code k at bits 3k..3k+3). This is 3.125 bpw vs
233+ /// the nibble path's 4.125 → ~24% less weight-memory traffic for the matmul,
234+ /// raising the decode roofline. Requires `codes.len() % 8 == 0` (true here:
235+ /// per-row `inn ∈ {1536, 8960}` is a multiple of 8, and rows are contiguous).
236+ /// The GPU kernel reads each octet's 3 bytes, forms a 24-bit word, and
237+ /// bit-extracts `(v >> 3k) & 7`. Returns a `Vec<u8>` of length
238+ /// `codes.len() / 8 * 3`.
239+ pub fn codes_packed_3bit(&self) -> Vec<u8> {
240+ let n = self.codes.len();
241+ debug_assert_eq!(n % 8, 0, "3-bit packing needs codes.len() % 8 == 0");
242+ let mut out = vec![0u8; (n / 8) * 3];
243+ for (g, octet) in self.codes.chunks_exact(8).enumerate() {
244+ // little-endian 24-bit field: code j at bits 3j..3j+3
245+ let mut v: u32 = 0;
246+ for (j, &c) in octet.iter().enumerate() {
247+ v |= ((c as u32) & 0x7) << (3 * j);
248+ }
249+ let b = g * 3;
250+ out[b] = (v & 0xFF) as u8;
251+ out[b + 1] = ((v >> 8) & 0xFF) as u8;
252+ out[b + 2] = ((v >> 16) & 0xFF) as u8;
253+ }
254+ out
255+ }
256+
257+ /// ALIGNED 3-bit packing for the coalesced-uint kernel (`tq_qmatvec3a_bf16`).
258+ /// 32 codes → 3 u32 words (96 bits, zero waste = 3.0 bpw for codes). Code `c`
259+ /// (0..32 within a block) occupies bits `3c..3c+3` of the little-endian 96-bit
260+ /// field spanning the 3 words; the two straddling fields (c=10 at bit 30, c=21
261+ /// at bit 63) split across word boundaries — written here, stitched in-kernel.
262+ /// Requires `codes.len() % 32 == 0` (true: every row's inn ∈ {512,3584,8960,
263+ /// 18944} is a multiple of 32 and rows are contiguous). Returns bytes (3 u32
264+ /// per 32-code block, little-endian), length `codes.len()/32*12`.
265+ #[allow(dead_code)] // negative result: aligned 3-bit reads were SLOWER than octets
266+ pub fn codes_packed_3bit_aligned(&self) -> Vec<u8> {
267+ let n = self.codes.len();
268+ debug_assert_eq!(n % 32, 0, "aligned 3-bit packing needs codes.len() % 32 == 0");
269+ let nblk = n / 32;
270+ let mut out = vec![0u8; nblk * 12];
271+ for (b, blk) in self.codes.chunks_exact(32).enumerate() {
272+ let mut words = [0u32; 3];
273+ for (c, &code) in blk.iter().enumerate() {
274+ let bit = 3 * c; // 0..96
275+ let w = bit / 32; // 0,1,2
276+ let off = bit % 32;
277+ let v = (code as u64) & 0x7;
278+ // place into a 64-bit window starting at word w, then split back.
279+ let lo = (v << off) as u32;
280+ words[w] |= lo;
281+ if off > 29 && w < 2 {
282+ words[w + 1] |= (v >> (32 - off)) as u32;
283+ }
284+ }
285+ let base = b * 12;
286+ for (wi, word) in words.iter().enumerate() {
287+ let wb = base + wi * 4;
288+ out[wb] = (word & 0xFF) as u8;
289+ out[wb + 1] = ((word >> 8) & 0xFF) as u8;
290+ out[wb + 2] = ((word >> 16) & 0xFF) as u8;
291+ out[wb + 3] = ((word >> 24) & 0xFF) as u8;
292+ }
293+ }
294+ out
295+ }
296+}
297+
298+/// Nearest-centroid quantize via midpoint edges (searchsorted), returns code.
299+#[inline]
300+fn quantize_one(v: f32, edges: &[f32]) -> u8 {
301+ let mut j = 0usize;
302+ while j < edges.len() && v > edges[j] {
303+ j += 1;
304+ }
305+ j as u8
306+}
307+
308+/// Pick the rotated-grid width P and whether block-Hadamard is usable.
309+/// Block-Hadamard needs `inn` to be a multiple of `d` (so each d-wide sub-block
310+/// is an exact power-of-two FWHT with no padding). Otherwise fall back to the
311+/// v2 full-row pad-to-power-of-two rotation.
312+fn rotation_plan(inn: usize, d: usize, want_block: bool) -> (usize, bool) {
313+ if want_block && inn % d == 0 {
314+ (inn, true) // P == inn, no padding
315+ } else {
316+ (inn.next_power_of_two(), false)
317+ }
318+}
319+
320+/// The largest power-of-two block size ≤ `max_d` that evenly divides `inn`.
321+/// Block-Hadamard requires `d` to be a power of two (per-block FWHT) AND `inn %
322+/// d == 0` (no padding). The configured `max_d` (128) works for every width that
323+/// is a multiple of 128 (all qwen projections, and most DeepSeek ones). Widths
324+/// like DeepSeek-V2-Lite's dense `mlp.down_proj` inn=10944 (= 64·171) are only
325+/// 64-divisible, so this drops to d=64 for that matrix while keeping 128
326+/// everywhere else. `d` is stored per-weight (`q.d`) and read by the inference
327+/// rotate, so the encode/decode transforms always match.
328+pub fn effective_block_d(inn: usize, max_d: usize) -> usize {
329+ let mut d = max_d.max(1).next_power_of_two();
330+ if d > max_d {
331+ d >>= 1; // next_power_of_two rounds up; keep ≤ max_d
332+ }
333+ while d > 1 && inn % d != 0 {
334+ d >>= 1;
335+ }
336+ d.max(1)
337+}
338+
339+/// Rotate one input row into `grid_row` (length p). `block` selects the mode.
340+/// In block mode, FWHT each consecutive d-wide chunk independently.
341+///
342+/// `pub(crate)`: the fast inference path rotates the *activation* x with exactly
343+/// this transform (same sgn, same per-d-block FWHT) so that
344+/// `⟨x, unrotate(w)⟩ = ⟨rotate(x), w_rotated⟩` and the matmul can read the
345+/// compressed rotated codes directly.
346+pub(crate) fn rotate_row(
347+ src: &[f32],
348+ sgn: &[f32],
349+ grid_row: &mut [f32],
350+ _p: usize, // grid_row already has length p; kept for call-site symmetry
351+ d: usize,
352+ block: bool,
353+) {
354+ for v in grid_row.iter_mut() {
355+ *v = 0.0;
356+ }
357+ let inn = src.len();
358+ if block {
359+ // sgn has length inn; copy*sign then FWHT each d-wide block in place.
360+ for k in 0..inn {
361+ grid_row[k] = src[k] * sgn[k];
362+ }
363+ let nblk = inn / d;
364+ for b in 0..nblk {
365+ fwht_inplace(&mut grid_row[b * d..b * d + d]);
366+ }
367+ } else {
368+ // sgn has length p; pad to p, sign-flip, single full-row FWHT.
369+ for k in 0..inn {
370+ grid_row[k] = src[k] * sgn[k];
371+ }
372+ fwht_inplace(grid_row);
373+ }
374+}
375+
376+/// Encode a weight matrix `w` (row-major, shape out×inn) data-free.
377+pub fn encode(w: &[f32], out: usize, inn: usize, cfg: &TqConfig, codebook: &[f32]) -> TqWeight {
378+ // Effective block size: when block-Hadamard is requested, shrink `d` to the
379+ // largest power-of-two divisor of `inn` (≤ cfg.d) so block mode is always
380+ // usable — d=128 for every 128-divisible width, d=64 for e.g. inn=10944
381+ // (DeepSeek-V2-Lite dense down_proj). Stored as `q.d` so inference rotates
382+ // identically. Non-block modes keep cfg.d unchanged.
383+ let d = if cfg.block_hadamard {
384+ effective_block_d(inn, cfg.d)
385+ } else {
386+ cfg.d
387+ };
388+ let (p, block) = rotation_plan(inn, d, cfg.block_hadamard);
389+ let sgn = signs(p, cfg.seed);
390+
391+ // Build the rotated grid: per row, sign-flip + (full or block-diagonal) FWHT.
392+ let mut grid = vec![0f32; out * p];
393+ let mut row_buf = vec![0f32; p];
394+ for r in 0..out {
395+ let src = &w[r * inn..r * inn + inn];
396+ rotate_row(src, &sgn, &mut row_buf, p, d, block);
397+ grid[r * p..r * p + p].copy_from_slice(&row_buf);
398+ }
399+
400+ // Outlier split (in rotated space): keep top-k |value| in fp16, zero them.
401+ let mut outlier_idx = Vec::new();
402+ let mut outlier_val = Vec::new();
403+ let k = (cfg.outlier_frac as f64 * grid.len() as f64) as usize;
404+ if k > 0 {
405+ // Partial selection: find the k largest |grid|. Simple approach — collect
406+ // (|v|, idx), select the k-th largest via select_nth_unstable.
407+ let mut mags: Vec<(f32, u32)> =
408+ grid.iter().enumerate().map(|(i, &v)| (v.abs(), i as u32)).collect();
409+ let kth = mags.len() - k;
410+ mags.select_nth_unstable_by(kth, |a, b| a.0.partial_cmp(&b.0).unwrap());
411+ for &(_, idx) in &mags[kth..] {
412+ let i = idx as usize;
413+ outlier_idx.push(idx);
414+ outlier_val.push(f16::from_f32(grid[i]));
415+ grid[i] = 0.0;
416+ }
417+ }
418+
419+ // Block-quantize: per block of d (the effective, per-matrix block size bound
420+ // above), RMS radius (fp16), normalize, codebook lookup.
421+ debug_assert_eq!(grid.len() % d, 0, "out*P must be divisible by d");
422+ let nblocks = grid.len() / d;
423+ let edges: Vec<f32> = (0..codebook.len() - 1)
424+ .map(|j| (codebook[j] + codebook[j + 1]) / 2.0)
425+ .collect();
426+
427+ let mut codes = vec![0u8; grid.len()];
428+ let mut radius = Vec::with_capacity(nblocks);
429+ for b in 0..nblocks {
430+ let blk = &grid[b * d..b * d + d];
431+ let mean_sq: f32 = blk.iter().map(|&v| v * v).sum::<f32>() / d as f32;
432+ let r = mean_sq.sqrt() + 1e-12;
433+ let r16 = f16::from_f32(r);
434+ radius.push(r16);
435+ // Use the fp16-rounded radius for normalization so decode matches exactly.
436+ let r_used = r16.to_f32();
437+ let inv = 1.0 / r_used;
438+ for (j, &v) in blk.iter().enumerate() {
439+ codes[b * d + j] = quantize_one(v * inv, &edges);
440+ }
441+ }
442+
443+ TqWeight {
444+ out,
445+ inn,
446+ p,
447+ d,
448+ bits: cfg.bits,
449+ seed: cfg.seed,
450+ block_hadamard: block,
451+ codes,
452+ radius,
453+ codebook: codebook.to_vec(),
454+ outlier_idx,
455+ outlier_val,
456+ }
457+}
458+
459+/// Decode the compressed weight back to a dense row-major f32 matrix (out×inn).
460+pub fn decode(q: &TqWeight) -> Vec<f32> {
461+ let d = q.d;
462+ let p = q.p;
463+
464+ // Reconstruct the rotated grid: codebook[code] * radius (per block).
465+ let mut grid = vec![0f32; q.out * p];
466+ for (b, &r16) in q.radius.iter().enumerate() {
467+ let r = r16.to_f32();
468+ for j in 0..d {
469+ let idx = b * d + j;
470+ grid[idx] = q.codebook[q.codes[idx] as usize] * r;
471+ }
472+ }
473+
474+ // Restore outliers (fp16) into the rotated grid.
475+ for (slot, &idx) in q.outlier_idx.iter().enumerate() {
476+ grid[idx as usize] = q.outlier_val[slot].to_f32();
477+ }
478+
479+ // Inverse rotation: per row, FWHT (self-inverse) then × signs, crop to inn.
480+ // Must mirror the same mode (full pad-to-pow2 vs block-diagonal) used to encode.
481+ let sgn = signs(p, q.seed);
482+ let mut out = vec![0f32; q.out * q.inn];
483+ let mut row_buf = vec![0f32; p];
484+ for r in 0..q.out {
485+ row_buf.copy_from_slice(&grid[r * p..r * p + p]);
486+ if q.block_hadamard {
487+ let nblk = p / d; // p == inn here
488+ for b in 0..nblk {
489+ fwht_inplace(&mut row_buf[b * d..b * d + d]);
490+ }
491+ } else {
492+ fwht_inplace(&mut row_buf);
493+ }
494+ for k in 0..q.inn {
495+ out[r * q.inn + k] = row_buf[k] * sgn[k];
496+ }
497+ }
498+ out
499+}
500+
501+/// Relative Frobenius error ‖W − Ŵ‖ / ‖W‖ — the recon-quality metric from the POC.
502+pub fn relative_fro(w: &[f32], wq: &[f32]) -> f64 {
503+ let mut num = 0f64;
504+ let mut den = 0f64;
505+ for i in 0..w.len() {
506+ let dv = (w[i] - wq[i]) as f64;
507+ num += dv * dv;
508+ den += (w[i] as f64) * (w[i] as f64);
509+ }
510+ (num.sqrt()) / (den.sqrt().max(1e-30))
511+}
512+
513+#[cfg(test)]
514+mod tests {
515+ use super::*;
516+
517+ #[test]
518+ fn packed_3bit_roundtrips() {
519+ // codes_packed_3bit must reproduce every code under the GPU kernel's
520+ // unpack (8 codes per 24-bit little-endian octet, code j at bits 3j..3j+3).
521+ let (out, inn) = (4usize, 256usize); // inn % 8 == 0
522+ let mut st = 7u64;
523+ let mut nf = || {
524+ st = st.wrapping_mul(6364136223846793005).wrapping_add(1);
525+ ((st >> 11) as f64 / (1u64 << 53) as f64 - 0.5) as f32
526+ };
527+ let w: Vec<f32> = (0..out * inn).map(|_| nf()).collect();
528+ let cfg = TqConfig { outlier_frac: 0.0, block_hadamard: true, ..TqConfig::default() };
529+ let q = encode(&w, out, inn, &cfg, &LLOYD_MAX_3BIT);
530+ let packed = q.codes_packed_3bit();
531+ assert_eq!(packed.len(), q.codes.len() / 8 * 3);
532+ // unpack exactly as tq_qmatvec3_f32 does
533+ for (g, chunk) in q.codes.chunks_exact(8).enumerate() {
534+ let bb = g * 3;
535+ let v = (packed[bb] as u32) | ((packed[bb + 1] as u32) << 8) | ((packed[bb + 2] as u32) << 16);
536+ for (j, &c) in chunk.iter().enumerate() {
537+ let dec = ((v >> (3 * j)) & 0x7) as u8;
538+ assert_eq!(dec, c, "3-bit unpack mismatch at octet {g} code {j}");
539+ assert!(c < 8, "code out of 3-bit range");
540+ }
541+ }
542+ }
543+
544+ #[test]
545+ fn fwht_self_inverse() {
546+ let mut x = vec![1.0f32, -2.0, 3.0, 0.5, -1.5, 2.0, -0.25, 4.0];
547+ let orig = x.clone();
548+ fwht_inplace(&mut x);
549+ fwht_inplace(&mut x);
550+ for (a, b) in x.iter().zip(orig.iter()) {
551+ assert!((a - b).abs() < 1e-4, "FWHT not self-inverse: {a} vs {b}");
552+ }
553+ }
554+
555+ #[test]
556+ fn activation_rotation_matches_dense_matmul() {
557+ // The fast path computes y[o] = Σ_k rotate(x)[k] * Wr[o,k] where
558+ // Wr[o,k] = codebook[codes[o*inn+k]] * radius(block) and
559+ // rotate(x) = blockFWHT(x ∘ sgn). This must equal the dense
560+ // y[o] = Σ_k x[k] * decode(W)[o,k]. Verify on a block-Hadamard weight.
561+ let (out, inn) = (64usize, 256usize); // inn % d(128)==0
562+ let mut state = 99u64;
563+ let mut nextf = || {
564+ state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
565+ ((state >> 11) as f64 / (1u64 << 53) as f64 - 0.5) as f32
566+ };
567+ let w: Vec<f32> = (0..out * inn).map(|_| nextf()).collect();
568+ let x: Vec<f32> = (0..inn).map(|_| nextf()).collect();
569+
570+ let cfg = TqConfig { outlier_frac: 0.0, block_hadamard: true, ..TqConfig::default() };
571+ let q = encode(&w, out, inn, &cfg, &LLOYD_MAX_3BIT);
572+ assert!(q.block_hadamard);
573+ let wq = decode(&q); // dense reconstructed weight (out×inn)
574+
575+ // dense reference: y_dense[o] = Σ_k x[k] * wq[o,k]
576+ let mut y_dense = vec![0f32; out];
577+ for o in 0..out {
578+ let mut acc = 0f32;
579+ for k in 0..inn {
580+ acc += x[k] * wq[o * inn + k];
581+ }
582+ y_dense[o] = acc;
583+ }
584+
585+ // fast path: rotate x, then dot with the reconstructed rotated codes.
586+ let sgn = signs(q.p, q.seed);
587+ let mut xr = vec![0f32; q.p];
588+ rotate_row(&x, &sgn, &mut xr, q.p, q.d, true);
589+ let mut y_fast = vec![0f32; out];
590+ for o in 0..out {
591+ let mut acc = 0f32;
592+ for k in 0..inn {
593+ let idx = o * inn + k;
594+ let r = q.radius[idx / q.d].to_f32();
595+ let wr = q.codebook[q.codes[idx] as usize] * r;
596+ acc += xr[k] * wr;
597+ }
598+ y_fast[o] = acc;
599+ }
600+
601+ let mut max_abs = 0f32;
602+ for o in 0..out {
603+ max_abs = max_abs.max((y_dense[o] - y_fast[o]).abs());
604+ }
605+ assert!(
606+ max_abs < 1e-3,
607+ "activation-rotation identity broken: max |Δ| = {max_abs}"
608+ );
609+ }
610+
611+ #[test]
612+ fn roundtrip_gaussian_is_reasonable() {
613+ // A Gaussian matrix should reconstruct with relFro well under 0.2 at 3 bits.
614+ let (out, inn) = (256usize, 300usize);
615+ let mut state = 12345u64;
616+ let mut nextf = || {
617+ state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
618+ ((state >> 11) as f64 / (1u64 << 53) as f64) as f32
619+ };
620+ let mut w = vec![0f32; out * inn];
621+ for chunk in w.chunks_mut(2) {
622+ let u1 = (nextf() as f64).max(1e-12);
623+ let u2 = nextf() as f64;
624+ let r = (-2.0 * u1.ln()).sqrt();
625+ chunk[0] = (r * (std::f64::consts::TAU * u2).cos()) as f32;
626+ if chunk.len() > 1 {
627+ chunk[1] = (r * (std::f64::consts::TAU * u2).sin()) as f32;
628+ }
629+ }
630+ let cfg = TqConfig::default();
631+ let q = encode(&w, out, inn, &cfg, &LLOYD_MAX_3BIT);
632+ let wq = decode(&q);
633+ let rf = relative_fro(&w, &wq);
634+ assert!(rf < 0.2, "relFro too high: {rf}");
635+ }
636+}
added tests/fixtures/fa_oracle/config.json +13 −0
@@ -0,0 +1,13 @@
1+{
2+ "hidden_size": 256,
3+ "num_attention_heads": 8,
4+ "num_key_value_heads": 2,
5+ "head_dim": 64,
6+ "partial_rotary_factor": 0.25,
7+ "rope_theta": 10000.0,
8+ "max_position_embeddings": 64,
9+ "rms_norm_eps": 1e-06,
10+ "num_hidden_layers": 1,
11+ "seq_len": 6,
12+ "rot_dim": 16
13+}
No newline at the end of the file
added tests/fixtures/gdn_oracle/BLUEPRINT.md +17 −0
@@ -0,0 +1,17 @@
1+# GatedDeltaNet — verified blueprint (numpy matches HF oracle to 4e-7)
2+Ref: transformers Qwen3NextGatedDeltaNet. Dims (mini oracle): hidden=256, nk=4, nv=8, hk=hv=32, conv_k=4, key_dim=128, value_dim=256, rep=nv/nk=2.
3+Forward (batch=1, prefill token-by-token):
4+ 1. qkvz = x @ Wqkvz.T [s,768]; ba = x @ Wba.T [s,16]
5+ 2. reshape qkvz→[s,nk,2*hk+2*hv*rep]; split [hk,hk,rep*hv,rep*hv] → q,k[s,nk,hk] v,z[s,nk,rep*hv]→reshape[s,nv,hv]
6+ reshape ba→[s,nk,2*rep]; split [rep,rep] → b,a → reshape [s,nv]
7+ 3. q,k,v → [s,-1]; mixed=cat(q,k,v)[s,512]→[512,s]
8+ 4. conv: causal depthwise k=4 (left-pad 3, no bias), then SiLU → [s,512]
9+ 5. split [key_dim,key_dim,value_dim]; q,k→[s,nk,hk], v→[s,nv,hv]
10+ 6. beta=sigmoid(b); g = -exp(A_log)*softplus(a+dt_bias) (per v-head)
11+ 7. repeat_interleave q,k by rep along head dim → [s,nv,hk]
12+ 8. recurrence (f32): q=l2norm(q)*(1/sqrt(hk)); k=l2norm(k); S=zeros[nv,hk,hv]
13+ per t: S*=exp(g_t)[:,None,None]; kv=(S*k_t[:,:,None]).sum(1); d=(v_t-kv)*beta_t[:,None];
14+ S+=k_t[:,:,None]*d[:,None,:]; out_t=(S*q_t[:,:,None]).sum(1)
15+ 9. RMSNormGated: oc=out.reshape(-1,hv); oc=oc/sqrt(mean(oc^2,-1)+eps); oc=norm_w*oc; oc*=silu(z)
16+10. y = oc.reshape(s,-1) @ Wout.T
17+Candle templates: rwkv_v7.rs (matrix state) + mamba2.rs:262 (conv1d). Cache: RecurrentStateCache{S f32, conv_state[512,3]}.
added tests/fixtures/gdn_oracle/config.json +15 −0
@@ -0,0 +1,15 @@
1+{
2+ "hidden_size": 256,
3+ "linear_key_head_dim": 32,
4+ "linear_value_head_dim": 32,
5+ "linear_num_key_heads": 4,
6+ "linear_num_value_heads": 8,
7+ "linear_conv_kernel_dim": 4,
8+ "rms_norm_eps": 1e-06,
9+ "num_hidden_layers": 1,
10+ "hidden_act": "silu",
11+ "seq_len": 6,
12+ "conv_dim": 512,
13+ "key_dim": 128,
14+ "value_dim": 256
15+}
No newline at the end of the file
added tests/fixtures/gdn_oracle/oracle.npz +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.