Archived
Compare commits
808
Commits
6174d5ee5c
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b52a180141 | ||
|
|
eda5b01708 | ||
|
|
8931aae8b2 | ||
|
|
4b70a96378 | ||
|
|
ca793ea99a | ||
|
|
b8bca7885a | ||
|
|
e78d484e60 | ||
|
|
d0fd4aa1bb | ||
|
|
9b6eba80c6 | ||
|
|
e912b04f5a | ||
|
|
ca7a7212ec | ||
|
|
946a6f9e2b | ||
|
|
01f08152dc | ||
|
|
304597970f | ||
|
|
cfec01ec8d | ||
|
|
315aea7db9 | ||
|
|
d1b5a45e31 | ||
|
|
590dbcc178 | ||
|
|
73a284d799 | ||
|
|
33f9644701 | ||
|
|
2e558e2dcc | ||
|
|
79ac2bd50d | ||
|
|
742191a244 | ||
|
|
73f94b4345 | ||
|
|
7bd195d394 | ||
|
|
b2228c176b | ||
|
|
8dcd8fdcd7 | ||
|
|
8f2e511fcc | ||
|
|
78ad2096a3 | ||
|
|
bfadfbee76 | ||
|
|
1f50d235ed | ||
|
|
df453ff434 | ||
|
|
eaa14ac72a | ||
|
|
ceb92ea701 | ||
|
|
2e0945c106 | ||
|
|
6b96295f54 | ||
|
|
29057b0c6b | ||
|
|
09ad42e633 | ||
|
|
1f00224501 | ||
|
|
21c4544b61 | ||
|
|
f5d2d74a20 | ||
|
|
6997f8da14 | ||
|
|
6c7bcefefa | ||
|
|
660d410196 | ||
|
|
38c182a2ba | ||
|
|
b988378e70 | ||
|
|
bd3fa646bc | ||
|
|
1d94e416a6 | ||
|
|
ba3ebd380f | ||
|
|
157959fd80 | ||
|
|
aadabde0de | ||
|
|
b27f352259 | ||
|
|
c9bce68d45 | ||
|
|
a8d82678fa | ||
|
|
8ac613ddb9 | ||
|
|
97b4590761 | ||
|
|
c256342bc1 | ||
|
|
66b0dcf019 | ||
|
|
0f011f27e1 | ||
|
|
c3a4775f54 | ||
|
|
b9ecbde0d6 | ||
|
|
5e2e596644 | ||
|
|
3bf9dc9593 | ||
|
|
d893fd05d1 | ||
|
|
5c66eecc8e | ||
|
|
f4981154fc | ||
|
|
392746da6b | ||
|
|
4943bba2fb | ||
|
|
6e8a2f0a94 | ||
|
|
9a960c3da9 | ||
|
|
79cc319db2 | ||
|
|
0ff61a19a2 | ||
|
|
b98c2eb13e | ||
|
|
5736dd11c3 | ||
|
|
90b1229bfc | ||
|
|
e5862f3d26 | ||
|
|
c2403b2e29 | ||
|
|
444b85158b | ||
|
|
965a7caa51 | ||
|
|
4c9a79ca98 | ||
|
|
70be48c6fa | ||
|
|
be09d90c71 | ||
|
|
3ac3954fea | ||
|
|
9bfdd95cb6 | ||
|
|
e30ada33e8 | ||
|
|
1231eefbd3 | ||
|
|
51e4c7f0f0 | ||
|
|
1b4e405969 | ||
|
|
d7e3c2a58a | ||
|
|
b44f7a9bb1 | ||
|
|
981cd1e4e1 | ||
|
|
50ea36f283 | ||
|
|
f2f94fc6e7 | ||
|
|
e46a8ba3d4 | ||
|
|
7b9f33653f | ||
|
|
2fda03ccdd | ||
|
|
b83d53cf19 | ||
|
|
41a1aa00fe | ||
|
|
2a2b756371 | ||
|
|
ddcb9c69bb | ||
|
|
b4c04b6042 | ||
|
|
f0f764d6f5 | ||
|
|
60bcc30e5e | ||
|
|
7da9ccf38b | ||
|
|
f3e4d11872 | ||
|
|
c6ef279a12 | ||
|
|
e1d612b29d | ||
|
|
0a1fed0bcf | ||
|
|
aafec91773 | ||
|
|
0aad575475 | ||
|
|
9aef29661b | ||
|
|
47d1a952e9 | ||
|
|
dd20835f18 | ||
|
|
d35027aaf7 | ||
|
|
0c7606423b | ||
|
|
25c8fbd136 | ||
|
|
ff4b7c9fb4 | ||
|
|
e1e21935cc | ||
|
|
b0ac7fd42c | ||
|
|
d04a27fad3 | ||
|
|
6abca01f17 | ||
|
|
2f1fdd4d11 | ||
|
|
3582900903 | ||
|
|
989db71bfc | ||
|
|
098b1779fc | ||
|
|
45f3b510c7 | ||
|
|
2bb2f7bacc | ||
|
|
451b136874 | ||
|
|
a58304632a | ||
|
|
6e134fc15f | ||
|
|
c00b882b96 | ||
|
|
5a8c5533d1 | ||
|
|
f87d03d304 | ||
|
|
f713f449c2 | ||
|
|
e0c386ee85 | ||
|
|
8ef50a7708 | ||
|
|
b954585f9f | ||
|
|
220cb3f12c | ||
|
|
be623ba1dc | ||
|
|
c9e34d534c | ||
|
|
8fa226e620 | ||
|
|
bd38e7eced | ||
|
|
8c389c02e7 | ||
|
|
d858aa722b | ||
|
|
f776ecbf2e | ||
|
|
e494369ed9 | ||
|
|
17f0eae420 | ||
|
|
b632c72f5d | ||
|
|
12b7b7889b | ||
|
|
01c7a3334a | ||
|
|
e3d65f3a7c | ||
|
|
28939a99df | ||
|
|
df4e2ea889 | ||
|
|
b87010c7dd | ||
|
|
4bd9c39728 | ||
|
|
7f5218ee5f | ||
|
|
036bd8fec0 | ||
|
|
87c604370d | ||
|
|
8ab6f2a8b3 | ||
|
|
e2e9416843 | ||
|
|
b0a58b5dbf | ||
|
|
aeaf6a4580 | ||
|
|
d6109d7e3e | ||
|
|
030a3a37b7 | ||
|
|
1a900398a3 | ||
|
|
6436410e63 | ||
|
|
7cad854f2b | ||
|
|
72160a9cff | ||
|
|
882050e45a | ||
|
|
0c4292e45b | ||
|
|
cc46e3b714 | ||
|
|
eda0e92e8e | ||
|
|
6f9c084ac6 | ||
|
|
c9c3a98894 | ||
|
|
3b7ef1ed48 | ||
|
|
b466c91b26 | ||
|
|
2420b2b383 | ||
|
|
63416510a0 | ||
|
|
3b278dcec3 | ||
|
|
44490c859a | ||
|
|
dccc6329a9 | ||
|
|
a1b7643310 | ||
|
|
e6787b7bdd | ||
|
|
394b8cd290 | ||
|
|
e0c3f971dc | ||
|
|
19d4e8fe0e | ||
|
|
3af8065cc6 | ||
|
|
a72686b7e7 | ||
|
|
c1c05e9029 | ||
|
|
a0ea6ad1ba | ||
|
|
eb3aa7eae7 | ||
|
|
c6391e6ef9 | ||
|
|
da7b911c64 | ||
|
|
81be3cb63d | ||
|
|
a00e5e7094 | ||
|
|
9782a9afb5 | ||
|
|
326443ca89 | ||
|
|
b88d370722 | ||
|
|
d4d6d6cb3e | ||
|
|
8088c9a783 | ||
|
|
c1c8e40445 | ||
|
|
cebf759a36 | ||
|
|
51b08808de | ||
|
|
c96cfc9e7b | ||
|
|
e14463b8eb | ||
|
|
f98ccd3f56 | ||
|
|
5b98ba37e8 | ||
|
|
9ca20a1fba | ||
|
|
445bf8e0d9 | ||
|
|
340ff8781a | ||
|
|
b43088a334 | ||
|
|
f692c3f446 | ||
|
|
416c231a18 | ||
|
|
95af71af3a | ||
|
|
50b60078ab | ||
|
|
acd256ba25 | ||
|
|
a4403a1a90 | ||
|
|
4a60c64ec5 | ||
|
|
6295ba1d92 | ||
|
|
40442cc81b | ||
|
|
08c3e752f7 | ||
|
|
cb97b1c886 | ||
|
|
5d6de60318 | ||
|
|
f697660b8b | ||
|
|
213403b458 | ||
|
|
a5b2f84450 | ||
|
|
8cb2c0a841 | ||
|
|
4204fa4da7 | ||
|
|
1c96558970 | ||
|
|
48407fb52d | ||
|
|
125854df79 | ||
|
|
1483a1ae17 | ||
|
|
e56d948889 | ||
|
|
a0f9eb29c0 | ||
|
|
ab736ca3e3 | ||
|
|
303060f210 | ||
|
|
36de701090 | ||
|
|
ccb5071228 | ||
|
|
a78352dad1 | ||
|
|
0b18331a34 | ||
|
|
638663e9ff | ||
|
|
dd43d31e93 | ||
|
|
8611feb85e | ||
|
|
1c2f55027c | ||
|
|
523349dd8f | ||
|
|
e4ca20ddf8 | ||
|
|
7169c9da0a | ||
|
|
9c5d4a656c | ||
|
|
702a0970cc | ||
|
|
798fb21e51 | ||
|
|
aa14eea76c | ||
|
|
ded64c0bd3 | ||
|
|
61e275e30f | ||
|
|
9cb04f62a8 | ||
|
|
aa182fc156 | ||
|
|
c776ab9e46 | ||
|
|
d564e6e5b1 | ||
|
|
8be040f599 | ||
|
|
08fa89255c | ||
|
|
742f17f1e3 | ||
|
|
599d904e01 | ||
|
|
51db1729b1 | ||
|
|
d537dc09aa | ||
|
|
c36d04d99c | ||
|
|
1554b451e1 | ||
|
|
d5bb6a6c6e | ||
|
|
757ad11b0d | ||
|
|
aaafebcf0a | ||
|
|
7bba83c075 | ||
|
|
0ac154c803 | ||
|
|
638aa3a683 | ||
|
|
4d8be7099d | ||
|
|
08c85ea527 | ||
|
|
72ab60ed64 | ||
|
|
4e35a00493 | ||
|
|
e53286cdbe | ||
|
|
bf7e473224 | ||
|
|
8bbf402d9e | ||
|
|
fc5f00a169 | ||
|
|
5e44973a36 | ||
|
|
86955a62c5 | ||
|
|
2da2eb0b6c | ||
|
|
769b4c64a6 | ||
|
|
7f95c567ad | ||
|
|
c3145b08e8 | ||
|
|
c5fe770657 | ||
|
|
8fced2e79f | ||
|
|
84af4ef2f9 | ||
|
|
9a1633596f | ||
|
|
10a99a5bf2 | ||
|
|
b9fdfc0a79 | ||
|
|
8f84939aa2 | ||
|
|
b5f116e797 | ||
|
|
d63b985161 | ||
|
|
175f0bbd33 | ||
|
|
bfb1ebd1dd | ||
|
|
9d6eb9fba1 | ||
|
|
8bc5366045 | ||
|
|
531fda7313 | ||
|
|
e6f4862c7e | ||
|
|
49d7d0b238 | ||
|
|
4511822138 | ||
|
|
f26eec2633 | ||
|
|
2d2356ad4b | ||
|
|
726e532114 | ||
|
|
7580ec3d17 | ||
|
|
cfa6a668f6 | ||
|
|
7892524801 | ||
|
|
b55791b398 | ||
|
|
141212dd88 | ||
|
|
b264e9bd0c | ||
|
|
55da38afbd | ||
|
|
b34b1ac844 | ||
|
|
34c52ebe96 | ||
|
|
203064b487 | ||
|
|
b6acbd69e4 | ||
|
|
40e1b3073b | ||
|
|
3decb3ca13 | ||
|
|
8e65e1a302 | ||
|
|
1577854d00 | ||
|
|
ad3f03dbc6 | ||
|
|
1c967b2f14 | ||
|
|
5f7244da4d | ||
|
|
ec53bce5dc | ||
|
|
d54f3b9e6e | ||
|
|
546f0c2047 | ||
|
|
9560780bfa | ||
|
|
9ed3ef7a7b | ||
|
|
8da043c246 | ||
|
|
9efdd00c4c | ||
|
|
9647b84ee0 | ||
|
|
6f6b5c3f78 | ||
|
|
74e7fddd79 | ||
|
|
d773992abc | ||
|
|
8df9240d65 | ||
|
|
167595a9b4 | ||
|
|
9cf8d3dad8 | ||
|
|
94c90b17ad | ||
|
|
33108e488b | ||
|
|
0792d86375 | ||
|
|
f8e69c4825 | ||
|
|
ec243c2a7d | ||
|
|
8df39472b6 | ||
|
|
b8cd1c950a | ||
|
|
ed1e5caf9d | ||
|
|
9093bf618e | ||
|
|
b9c685a9c3 | ||
|
|
a28221eb6a | ||
|
|
ed5f990d92 | ||
|
|
187a015bda | ||
|
|
e668d493d9 | ||
|
|
4a61d7296b | ||
|
|
481fcd5df0 | ||
|
|
a64c75eb34 | ||
|
|
49ca5ff9c6 | ||
|
|
460de4a1fd | ||
|
|
711cdd0cd7 | ||
|
|
035ecde18c | ||
|
|
b6cf2b3574 | ||
|
|
cc58402b71 | ||
|
|
213aff9753 | ||
|
|
9c605a103d | ||
|
|
d24cf32a13 | ||
|
|
e1323afeb9 | ||
|
|
f9fdc7b57f | ||
|
|
4374bea1c4 | ||
|
|
890715fd96 | ||
|
|
6cb9826975 | ||
|
|
1ffa770901 | ||
|
|
b64b0de7de | ||
|
|
73bee2dcc2 | ||
|
|
11076c06fc | ||
|
|
222cbe7981 | ||
|
|
c896a870ed | ||
|
|
fe2b8cd7fe | ||
|
|
14e91c4d9f | ||
|
|
3efb37254b | ||
|
|
14b8f21a1a | ||
|
|
662b7720b5 | ||
|
|
f43929ccb8 | ||
|
|
64c3dc9893 | ||
|
|
d73abc28d5 | ||
|
|
385318f81a | ||
|
|
6f034d989f | ||
|
|
6b544e0d39 | ||
|
|
9f707a0f67 | ||
|
|
812cdeceb0 | ||
|
|
9497bf9061 | ||
|
|
caa468389c | ||
|
|
bbf90ebaa2 | ||
|
|
1f4f4420e9 | ||
|
|
7a039cbb5c | ||
|
|
1720ed3f4a | ||
|
|
0bb00a836d | ||
|
|
586f77ae0a | ||
|
|
27f1b27387 | ||
|
|
d4371cdd3a | ||
|
|
04d4f8e9cc | ||
|
|
8e8b4352a1 | ||
|
|
6969fcf8cb | ||
|
|
6a192ff0d7 | ||
|
|
65a9e78acf | ||
|
|
0b756e64f8 | ||
|
|
72d192dbf6 | ||
|
|
b1da6a28bd | ||
|
|
a96bfe821f | ||
|
|
555fbf62f5 | ||
|
|
5a2732f063 | ||
|
|
d60da58732 | ||
|
|
5ed4ff847e | ||
|
|
d63d1bc8a5 | ||
|
|
dd0ee312a4 | ||
|
|
13c64a3d78 | ||
|
|
2365a2ae51 | ||
|
|
82c114e84e | ||
|
|
e85124c0f0 | ||
|
|
efdfc4a570 | ||
|
|
ab0175564b | ||
|
|
2d1f168ec3 | ||
|
|
6c33ee4e12 | ||
|
|
fd40bb430c | ||
|
|
4853db97db | ||
|
|
157450a82b | ||
|
|
13d3a8b7af | ||
|
|
b74a6b2ece | ||
|
|
ce79b12126 | ||
|
|
cb0abe9ac7 | ||
|
|
72a58d0c0c | ||
|
|
fb8cb95b7e | ||
|
|
c2565369e9 | ||
|
|
d947d7139e | ||
|
|
da8c95d4d9 | ||
|
|
fbffd33e22 | ||
|
|
05ccf42964 | ||
|
|
31ac68549b | ||
|
|
2c9d415166 | ||
|
|
85b5388089 | ||
|
|
c301f3315e | ||
|
|
edbdc44b8e | ||
|
|
87cb41b5fa | ||
|
|
9d6ae971e8 | ||
|
|
ad26c95675 | ||
|
|
3a1706f1fa | ||
|
|
9916dcace3 | ||
|
|
36c39efdca | ||
|
|
d59cdce040 | ||
|
|
bb48b14005 | ||
|
|
492d33c470 | ||
|
|
aeedae4027 | ||
|
|
692ce7ed8b | ||
|
|
9f90451599 | ||
|
|
2ef0536051 | ||
|
|
99edcc97e0 | ||
|
|
f69c9d8324 | ||
|
|
f406c4dafc | ||
|
|
74e701ea17 | ||
|
|
731a23a65a | ||
|
|
fe27edb4da | ||
|
|
70639f7ea2 | ||
|
|
fa8c746497 | ||
|
|
b56139a96a | ||
|
|
68468fc957 | ||
|
|
9d37941a44 | ||
|
|
6645337f69 | ||
|
|
1592580337 | ||
|
|
b7998146d7 | ||
|
|
7dd17c6488 | ||
|
|
55db8c7c65 | ||
|
|
d87dd860ce | ||
|
|
341cedfc2d | ||
|
|
2c645333a1 | ||
|
|
b6ad757bfa | ||
|
|
96bc0465b3 | ||
|
|
22df1c7264 | ||
|
|
1c6acaf84b | ||
|
|
dab34da373 | ||
|
|
21c01f9930 | ||
|
|
a323b76bca | ||
|
|
d8b9ce3a32 | ||
|
|
66c86b9f89 | ||
|
|
5c1c71b147 | ||
|
|
6a7824a837 | ||
|
|
64c652f01e | ||
|
|
bf6c019571 | ||
|
|
f55570e351 | ||
|
|
55cf057a30 | ||
|
|
ae7f16b22b | ||
|
|
15065f0463 | ||
|
|
c5d61eafbb | ||
|
|
258d97339a | ||
|
|
2370687c70 | ||
|
|
2e1a5022a9 | ||
|
|
aa989db567 | ||
|
|
ca713b4732 | ||
|
|
09f80b8b1e | ||
|
|
2675dba42c | ||
|
|
2a5e815a95 | ||
|
|
34ae231e97 | ||
|
|
5d09eb98b5 | ||
|
|
c2160c9e45 | ||
|
|
ed8e26c2fc | ||
|
|
dad30c6b59 | ||
|
|
68d510b1f4 | ||
|
|
c463a0ab1b | ||
|
|
fe311c5c80 | ||
|
|
69087ce773 | ||
|
|
2a764d2d38 | ||
|
|
640cc7e231 | ||
|
|
47b7aae7a3 | ||
|
|
207b10b3c3 | ||
|
|
8c547fe240 | ||
|
|
340231d007 | ||
|
|
bcdc89eded | ||
|
|
5a463bf992 | ||
|
|
70e50f4758 | ||
|
|
8a6a1180ce | ||
|
|
1b2cc6d826 | ||
|
|
36b8941096 | ||
|
|
d650eca840 | ||
|
|
1f3154d366 | ||
|
|
c5483e3241 | ||
|
|
baa10db1aa | ||
|
|
92093976fe | ||
|
|
2d2f638fa8 | ||
|
|
e3eab050bd | ||
|
|
7e04bcac2b | ||
|
|
7621e4ac2b | ||
|
|
a6702f8db5 | ||
|
|
91fc4192aa | ||
|
|
0e7e6ee09a | ||
|
|
ac8b3a5017 | ||
|
|
36b131f039 | ||
|
|
0e953eb78b | ||
|
|
b95265eb51 | ||
|
|
06172e98de | ||
|
|
59870fc32e | ||
|
|
f3c6443d95 | ||
|
|
07904a3628 | ||
|
|
ef6c6e13fa | ||
|
|
fc1f2bba59 | ||
|
|
5010e1d083 | ||
|
|
258d685768 | ||
|
|
aa5dfaec19 | ||
|
|
88540cd263 | ||
|
|
feaf008927 | ||
|
|
19f6cd711e | ||
|
|
6efffe2a59 | ||
|
|
32bb5592d0 | ||
|
|
cc0a862afa | ||
|
|
baf503e021 | ||
|
|
2918a2eef2 | ||
|
|
2078b28fcb | ||
|
|
d2d9b9687e | ||
|
|
1fb35740df | ||
|
|
e9555d2bc1 | ||
|
|
d0c44cf5a3 | ||
|
|
2af1079415 | ||
|
|
bc272f897d | ||
|
|
8998349eec | ||
|
|
de53cd18c1 | ||
|
|
c9f79c32d8 | ||
|
|
be85c0ba7f | ||
|
|
fa7a5e4164 | ||
|
|
0044d8d201 | ||
|
|
7935897260 | ||
|
|
2721f7c951 | ||
|
|
cbc299417e | ||
|
|
a596f68782 | ||
|
|
f16854499c | ||
|
|
486c933161 | ||
|
|
32881da9fd | ||
|
|
6d6541af42 | ||
|
|
b61394e13c | ||
|
|
75b4c92e7e | ||
|
|
0ef2cc9dd6 | ||
|
|
2dbeaf93d1 | ||
|
|
d49a2ccb9c | ||
|
|
8af24965cc | ||
|
|
2b1eca5d23 | ||
|
|
01345a16f4 | ||
|
|
ac5de25b38 | ||
|
|
523dbab68a | ||
|
|
df338d49a5 | ||
|
|
613bbaacfd | ||
|
|
49a02c79df | ||
|
|
c8e635f4b1 | ||
|
|
9d5169e8a2 | ||
|
|
d7b7aefdd3 | ||
|
|
ec6bfcd1ab | ||
|
|
e0bf58dd40 | ||
|
|
adee014122 | ||
|
|
7c3b5ab7d5 | ||
|
|
4134b70088 | ||
|
|
ba8f13bea3 | ||
|
|
dfed12883b | ||
|
|
2bf1096131 | ||
|
|
c3567d3f03 | ||
|
|
82a2187188 | ||
|
|
eda7169749 | ||
|
|
1438aad26c | ||
|
|
6bcb481450 | ||
|
|
b5eef7e1ab | ||
|
|
cbe1a74716 | ||
|
|
a613a1a3e1 | ||
|
|
1afb9de4e9 | ||
|
|
55a1e9f110 | ||
|
|
672d49d07e | ||
|
|
ecf8bf547a | ||
|
|
b40dfb8e8e | ||
|
|
a14ea5abad | ||
|
|
bbc7607222 | ||
|
|
a7868f37f3 | ||
|
|
9da46ab7fe | ||
|
|
e25951c51e | ||
|
|
b66b1243d2 | ||
|
|
9a9c831f79 | ||
|
|
1a61aac915 | ||
|
|
e6fa74087a | ||
|
|
74f186ca85 | ||
|
|
3041596a6e | ||
|
|
3ab0affbbc | ||
|
|
782ea73fd8 | ||
|
|
8a765db488 | ||
|
|
50db0dbd90 | ||
|
|
905a7ec242 | ||
|
|
99fb3108cd | ||
|
|
09d83c42bc | ||
|
|
531146b4e8 | ||
|
|
a886d2a6ec | ||
|
|
5092098123 | ||
|
|
c036bfcb88 | ||
|
|
e54e570bf1 | ||
|
|
aa1b050f93 | ||
|
|
cc198e98c4 | ||
|
|
fc034b526e | ||
|
|
be47bf19af | ||
|
|
6579556715 | ||
|
|
b54a80de59 | ||
|
|
5b415b2ef8 | ||
|
|
c2219fccb0 | ||
|
|
a9e627b7ca | ||
|
|
cce687bf2c | ||
|
|
c55ca689fe | ||
|
|
248ecf5858 | ||
|
|
60f6eab298 | ||
|
|
7e42d394a5 | ||
|
|
7054e505d9 | ||
|
|
6a6c50e718 | ||
|
|
8f6f12e288 | ||
|
|
e1ddb61087 | ||
|
|
c4e372e699 | ||
|
|
5a9ce4912b | ||
|
|
0709322819 | ||
|
|
f7c349075c | ||
|
|
71356b773e | ||
|
|
ea25b98e23 | ||
|
|
99fd4ea59a | ||
|
|
4bca30369b | ||
|
|
eeeeea3c88 | ||
|
|
f41f998e60 | ||
|
|
cf10b28663 | ||
|
|
d337f53043 | ||
|
|
9921067b04 | ||
|
|
a58d23f4eb | ||
|
|
e9d34c1611 | ||
|
|
f2c892761a | ||
|
|
7fa2ec0e4a | ||
|
|
acd06d2a48 | ||
|
|
4ec175549c | ||
|
|
48e41fda1e | ||
|
|
0d2b502d51 | ||
|
|
0c813784a0 | ||
|
|
5838c25343 | ||
|
|
ad01fcaf19 | ||
|
|
284feda3a6 | ||
|
|
28f1f2dd8c | ||
|
|
73b1d039a0 | ||
|
|
57d2cb4043 | ||
|
|
d39e0511e7 | ||
|
|
0f4c1afc38 | ||
|
|
fb880cbc2d | ||
|
|
40d205929a | ||
|
|
f3429d8c13 | ||
|
|
d4eacec5c6 | ||
|
|
9daf738909 | ||
|
|
0fb3badc6c | ||
|
|
2382686d3b | ||
|
|
b66752adcc | ||
|
|
75b4d0baa7 | ||
|
|
d6957e88a1 | ||
|
|
192fe10278 | ||
|
|
6dad488dbe | ||
|
|
db9a464ac4 | ||
|
|
8f2fd45750 | ||
|
|
c571fa36b3 | ||
|
|
3b30d7803b | ||
|
|
e9b2714081 | ||
|
|
316c3b20bc | ||
|
|
0ffac0ee38 | ||
|
|
bce0f4db70 | ||
|
|
15944be7e3 | ||
|
|
1ac980a928 | ||
|
|
3158324bdb | ||
|
|
20ddb6aba1 | ||
|
|
4edbcd6882 | ||
|
|
d3609e585d | ||
|
|
d47d4b50b5 | ||
|
|
879b9de3ce | ||
|
|
199d4a017e | ||
|
|
96d785d347 | ||
|
|
c0497e040e | ||
|
|
a71783806a | ||
|
|
b57c2db60c | ||
|
|
96b3e1be83 | ||
|
|
a65ab54213 | ||
|
|
5da5c1ba05 | ||
|
|
8db5b6efff | ||
|
|
d0e797844e | ||
|
|
ed76fc8aaa | ||
|
|
649178eb59 | ||
|
|
dc89eb45fb | ||
|
|
0e81041881 | ||
|
|
ea065f596c | ||
|
|
8addda231b | ||
|
|
17524c95bd | ||
|
|
58bca7602e | ||
|
|
c10caa44fb | ||
|
|
9322ea0b92 | ||
|
|
877e8e44e4 | ||
|
|
7e2d6a205d | ||
|
|
634e805ce2 | ||
|
|
da52bc8593 | ||
|
|
90e14c5015 | ||
|
|
4d68a01a08 | ||
|
|
a75bdd7fd6 | ||
|
|
4ca02f18dd | ||
|
|
6131e59693 | ||
|
|
a1a75da7e9 | ||
|
|
dab82de105 | ||
|
|
d912c694f3 | ||
|
|
2477456b36 | ||
|
|
e9d03362f0 | ||
|
|
5a7dac7ce1 | ||
|
|
58142a6638 | ||
|
|
b90723eabe | ||
|
|
824e238996 | ||
|
|
6249462bfa | ||
|
|
a85f87ea2f | ||
|
|
168a26a6b8 | ||
|
|
3aded1bbf8 | ||
|
|
d90e19dc15 | ||
|
|
eb14e4f642 | ||
|
|
7d7c66da55 | ||
|
|
87701cb6b8 | ||
|
|
f7cc1b3a3b | ||
|
|
c2e4dea468 | ||
|
|
5fb9dc92ad | ||
|
|
80b13b49d8 | ||
|
|
d480a47bef | ||
|
|
bf6dc374d4 | ||
|
|
f617cbafb5 | ||
|
|
c783a7cb72 | ||
|
|
ea7a4e2d26 | ||
|
|
cfbccb46dc | ||
|
|
3a7a79fb47 | ||
|
|
cd393a0973 | ||
|
|
8785774fc0 | ||
|
|
b1f4fccc52 | ||
|
|
871aa7dd97 | ||
|
|
bdc5c5b063 | ||
|
|
4e750fed01 | ||
|
|
00f9703892 | ||
|
|
d886e4d0ab | ||
|
|
a01d1c1cd5 | ||
|
|
f201c140ab | ||
|
|
346efdeb2e | ||
|
|
832a88faac | ||
|
|
61abb990ab | ||
|
|
baf6e89ecb | ||
|
|
0c35fc8070 | ||
|
|
8a993b7de9 | ||
|
|
c8c8f93789 | ||
|
|
ad7e0f8b89 | ||
|
|
0fe7771210 | ||
|
|
cbbab03183 | ||
|
|
5098672aee | ||
|
|
fce342d710 | ||
|
|
4277d414a2 | ||
|
|
5dd0ba8a81 | ||
|
|
60e920cd4d | ||
|
|
8ddcbbf01f | ||
|
|
4b0b787d53 | ||
|
|
40e4e3c2d8 | ||
|
|
1dc850d17f | ||
|
|
2acc0261ff | ||
|
|
39602c1c7b | ||
|
|
0bfde46414 | ||
|
|
04440dd3a9 | ||
|
|
241629fe8c | ||
|
|
04daf51e42 | ||
|
|
393d5416b0 | ||
|
|
7f4bc9c3a4 | ||
|
|
f4c8af1eb3 | ||
|
|
d73f94c387 | ||
|
|
e93dae4f5e | ||
|
|
658f7b7214 | ||
|
|
72624973ad | ||
|
|
490d4c604a |
No files matched your search
@@ -5,3 +5,5 @@ build*
|
||||
.claude
|
||||
**/*.rad
|
||||
compile_commands.json
|
||||
dashboard/node_modules
|
||||
dashboard/dist
|
||||
+1
-1
@@ -6,4 +6,4 @@ compile_commands.json
|
||||
/sync-jarvis.sh
|
||||
__pycache__/
|
||||
.cache/
|
||||
/paper/
|
||||
/baseline-models/
|
||||
+34
-8
@@ -1,7 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
# VERSION is the server release that /version reports. The plugin ABI version is separate and is
|
||||
# read from abi/rad_abi.h below.
|
||||
project(radiance VERSION 1.11.0 LANGUAGES C CXX)
|
||||
project(radiance VERSION 2.1.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -20,6 +20,7 @@ set(RAD_WITH_FFMPEG "AUTO" CACHE STRING
|
||||
"ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample")
|
||||
set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO)
|
||||
option(RAD_BUILD_TESTS "Build the test suite" ON)
|
||||
option(RAD_ENABLE_KV_ROLLBACK_TEST_HOOK "Compile the test-only device KV rollback observer" OFF)
|
||||
option(RAD_ASAN "Build host code with AddressSanitizer and UBSan" OFF)
|
||||
option(RAD_TSAN "Build host code with ThreadSanitizer" OFF)
|
||||
# LLVM 24's VOPD pairing is not repeatable unless patched (docker/llvm-vopd-pairing.patch); when
|
||||
@@ -194,7 +195,7 @@ file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/kernels ${RAD_PLUGIN_OUT}/architectures)
|
||||
# Recorded kernel fixtures, copied into the build's $RADIANCE_HOME (where rad-kbench looks; an
|
||||
# installed prefix has no source tree). data/kernels.rkb lets rad-kbench run with no model: it holds
|
||||
# geometries, input seeds and libref's answers reduced to a norm and a sample. Re-record with a 27B
|
||||
# container:
|
||||
# IQ8R container that carries its DFlash2 drafter:
|
||||
#
|
||||
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels.rkb
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
|
||||
@@ -205,8 +206,8 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
|
||||
endif()
|
||||
|
||||
# A recording covers one container's geometries, and no single model declares the whole vocabulary.
|
||||
# The 27B is dense with a DFlash2 drafter and gqa 6; the 35B-A3B is routed (moe_gemm_q,
|
||||
# router_topk, moe_scatter, moe_gather, scale_rows) with an MTP head and gqa 8. Re-record with
|
||||
# The 27B is dense with a DFlash2 drafter and gqa 6; the 35B-A3B IQ8R container is routed
|
||||
# (moe_gemm_q, the fused router, moe_gather, scale_rows) with an MTP head and gqa 8. Re-record with
|
||||
#
|
||||
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels_moe.rkb
|
||||
#
|
||||
@@ -258,8 +259,8 @@ foreach(tok 1 8 16 128)
|
||||
list(APPEND RAD_M2XFP4_FIXTURES ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m${tok}.rkb)
|
||||
endif()
|
||||
endforeach()
|
||||
# The downloader behind `radiance --model <owner/name>` (core/hf_model.cpp). The engine looks in
|
||||
# <bin>/../libexec/radiance/, so the build tree mirrors that layout.
|
||||
# The downloader behind a model source naming a repo, `model: <owner/name>` (core/hf_model.cpp).
|
||||
# The engine looks in <bin>/../libexec/radiance/, so the build tree mirrors that layout.
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY)
|
||||
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
@@ -372,6 +373,10 @@ if(RAD_SYCL_FOUND)
|
||||
install(FILES ${RAD_SYCL_BINARY_DIR}/librad_sycl.so DESTINATION ${CMAKE_INSTALL_LIBDIR})
|
||||
install(FILES ${RAD_PLUGIN_OUT}/kernels/libxe2.so
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance/kernels)
|
||||
# its large-register kernels, a library of their own that libxe2 loads from its own libxe2.d
|
||||
# (libxe2/CMakeLists.txt, xe2_grf256)
|
||||
install(FILES ${RAD_PLUGIN_OUT}/kernels/libxe2.d/libxe2_grf256.so
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance/kernels/libxe2.d)
|
||||
endif()
|
||||
|
||||
add_subdirectory(vendor)
|
||||
@@ -385,6 +390,22 @@ add_subdirectory(libquant)
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
|
||||
add_subdirectory(libr4d)
|
||||
endif()
|
||||
# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP
|
||||
# toolchain. It declares itself for `^gfx11` and returns without a target when the build's
|
||||
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it, and
|
||||
# declines every machine without a gfx11 card (rad_plugin_open). A card with no kernel library of
|
||||
# its own refuses device-only ops (docs/PLUGIN.md §10).
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt)
|
||||
add_subdirectory(libr3d)
|
||||
endif()
|
||||
# libhalo: the Strix Halo (gfx1151) kernel library, built only when RAD_GPU_TARGETS names gfx1151.
|
||||
# On a gfx1151 it is preferred over libr3d, which also serves the chip: with no --kernels list the
|
||||
# loader takes libraries in file-name order (libhalo.so ahead of libr3d.so), the first library with
|
||||
# a row for an op supplies it, and libhalo declines every machine without a gfx1151
|
||||
# (rad_plugin_open), so other RDNA3 cards get libr3d alone.
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libhalo/CMakeLists.txt)
|
||||
add_subdirectory(libhalo)
|
||||
endif()
|
||||
# libavx: the production host kernels (x86 SIMD, dispatched by CPU feature), built on every x86-64.
|
||||
# Not optional: host-placed ops need a kernel other than the oracle (rad_gate_reference_kernels
|
||||
# refuses libref), and a table too large for the card, such as the n-gram embedding's gather, runs
|
||||
@@ -393,6 +414,9 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
|
||||
add_subdirectory(libavx)
|
||||
endif()
|
||||
add_subdirectory(arch)
|
||||
# spechub: the linear-MTP coupling kernels (--draft-coupling). Built by default; without the flag
|
||||
# no op resolves to its rows.
|
||||
add_subdirectory(plugin/spechub)
|
||||
add_subdirectory(tools)
|
||||
if(RAD_BUILD_TESTS)
|
||||
enable_testing()
|
||||
@@ -457,9 +481,11 @@ install(FILES
|
||||
install(FILES LICENSE NOTICE DESTINATION ${CMAKE_INSTALL_DOCDIR})
|
||||
install(FILES vendor/llama/LICENSE
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME llama.cpp.LICENSE)
|
||||
install(FILES vendor/nlohmann/LICENSE.MIT
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME nlohmann-json.LICENSE)
|
||||
install(FILES vendor/yyjson/LICENSE
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME yyjson.LICENSE)
|
||||
install(FILES vendor/cpp-httplib/LICENSE
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME cpp-httplib.LICENSE)
|
||||
install(FILES core/server/LICENSE.lfm
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME liquidai-d1.LICENSE)
|
||||
install(FILES dashboard/THIRD-PARTY-LICENSES.txt
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME dashboard.LICENSES)
|
||||
+14
-8
@@ -28,10 +28,12 @@
|
||||
# and refuses a compressed bundle.
|
||||
#
|
||||
# GPU_TARGETS must be named: a build container has no card to detect, unlike a bare-metal
|
||||
# ./build.sh. They are the targets of the shipped kernel libraries; libr4d serves RDNA4 only and
|
||||
# drops every architecture outside gfx12. The engine's own kernels carry the generic family
|
||||
# targets and run on every AMD GPU family, so a kernel library for another card is added by
|
||||
# mounting it on the search path:
|
||||
# ./build.sh. They are the targets of the shipped kernel libraries, each of which keeps only its own
|
||||
# family: libr4d takes gfx1201 (RDNA4), libr3d gfx11-generic (every RDNA3 chip) and gfx1151, and
|
||||
# libhalo gfx1151 (Strix Halo), where the loader prefers it over libr3d. On any one card the other
|
||||
# libraries decline or are left out, so the default image serves all three. The engine's own
|
||||
# kernels carry the generic family targets and run on every AMD GPU family, so a kernel library for
|
||||
# another card is added by mounting it on the search path:
|
||||
# docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance
|
||||
#
|
||||
# The image's ROCm userspace must be supported by the host's amdgpu kernel driver; it is pinned to
|
||||
@@ -131,7 +133,7 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
|
||||
# ------------------------------------------------------------------------------------------ build
|
||||
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
|
||||
ARG GPU_TARGETS=gfx1201
|
||||
ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
|
||||
# Parallel compile jobs; empty means one per core. A device-kernel translation unit takes 2-3 GB
|
||||
# of RAM under hipcc, so lower it on a host that is also serving.
|
||||
ARG JOBS=
|
||||
@@ -140,9 +142,12 @@ ARG JOBS=
|
||||
# libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which
|
||||
# mawk lacks. libdav1d7, libwebp7 and libopenh264-7 are the runtime libraries of the ffmpeg stage's
|
||||
# AV1 decoder, WebP encoder and H.264 encoder; busybox-static goes into the runtime image.
|
||||
# libopenblas-dev: libquant's GPTQ factorises its Hessians through LAPACK where it finds OpenBLAS
|
||||
# (libquant/CMakeLists.txt); without it rad-convert's gptq rule runs single-threaded loops.
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \
|
||||
libopenblas-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
|
||||
@@ -224,11 +229,12 @@ ARG TEST_EXCLUDE=
|
||||
# perf_event_open, so the tests that bound work count CPU time rather than instructions
|
||||
# (tests/work_counter.h). The `oot` suite (every shipped plugin rebuilt against the installed
|
||||
# package) repeats this stage's whole compile, so it runs from the development tree instead
|
||||
# (tests/oot_plugins.sh).
|
||||
# (tests/oot_plugins.sh). The `parity` entry (halo_parity: libhalo's tables against libr4d's) is
|
||||
# left out until libhalo has ported the ops libr4d added after it (the test names each one).
|
||||
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
bash /src/docker/llvm-check.sh /build \
|
||||
&& RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \
|
||||
ctest --test-dir /build -LE 'gpu|oot' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \
|
||||
ctest --test-dir /build -LE 'gpu|oot|parity' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \
|
||||
-j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \
|
||||
&& touch /build/host-tests-passed
|
||||
|
||||
@@ -280,7 +286,7 @@ RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
|
||||
|
||||
# ---------------------------------------------------------------------------------------- runtime
|
||||
FROM scratch AS runtime
|
||||
ARG GPU_TARGETS=gfx1201
|
||||
ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
|
||||
ARG VERSION=dev
|
||||
ARG REVISION=unknown
|
||||
|
||||
|
||||
@@ -15,28 +15,68 @@ Written by Deadcode, with contributions from:
|
||||
adaptive draft window, the MoE prefill forms, the sorted operand's decode kernel, two K blocks a
|
||||
pass for up to 80 routed rows, --prefill-span, the towers' lookup tables counted once, and for
|
||||
Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused
|
||||
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, and the
|
||||
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files
|
||||
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, the
|
||||
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared
|
||||
layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio
|
||||
encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights
|
||||
through w4a16_asym, the Ornith-1.5-122B compose files, the Gemma 4 31B's asymmetric int5
|
||||
linears (w5a8i8 and w5a16), the junctions at quant_act_i8g's grid (rmsnorm_quant_i8g,
|
||||
gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g) with the prefill overlap on the i8a8, a4 and w5
|
||||
grids, the 31B's i8g, heretic-ara-i8g and w5 compose files, and Ling-3.0-flash (bailing_hybrid:
|
||||
KDA, dense latent attention, group-limited sigmoid routing, the clipped SwiGLU and its MTP layer as
|
||||
a serial drafter) with mla_attn_paged, its w4a8 recipes and compose files, possessive quantifiers
|
||||
in the tokenizer's patterns, the Grafana dashboard's first screen, and Gemma 4 12B (its picture
|
||||
and audio embedders, a picture's placeholders read both ways on the sliding layers, the windowed
|
||||
attention at head_dim 512, suppress_tokens) with its compose files, and
|
||||
NVIDIA-Nemotron-3.5-Bolt-74B-A9B (nemotronh: Mamba-2 with ssd_update and ple_conv_bias, the
|
||||
latent MoE's ungated relu^2 experts, NoPE attention with KV heads replicated over ranks, the
|
||||
paged attention at head_dim 128 and gqa 16, attention sinks) with NVIDIA's LiLiCorr drafter
|
||||
(RadBatch::anchor_rows, the candidate correlator), the C-RADIO vision tower and video tubelets,
|
||||
calibration in layer ranges, its recipes and compose files, and the kernel report's fixture
|
||||
- mechkbfan: the token embedding in the pinned host pool
|
||||
- Code000: the n-gram gather on the card and the MTP head's history-pass skip
|
||||
- Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft
|
||||
coupling with its cooperative verify (--draft-coupling), the W4A8 prefill's tail scale read, the
|
||||
ISA instruments' VGPR granule, back-edge count and fail-closed parse, scored steps
|
||||
(rad_declare_scores, RadBatch::score_only), the gated prefill fold, the short-prompt split row and
|
||||
the rows forms of rmsnorm and rope, LFM2's 8-bit trunk with the d1-3B recipe, the file tier's
|
||||
routed reads with their own router's counts and its deposit wait, the stop-string hold-back, and
|
||||
the sampler's planes by the step's token bound, its n-gram ban beside a drafter and no candidate
|
||||
cut over a top-1 row, and --prefill-interleave auto[:SHARE], sized from measured step times and
|
||||
served by default, and the diagnose mode, in which the engine measures itself, with its token
|
||||
parity and reproducibility checks
|
||||
- baKon: three-rank tensor parallelism, serving any world size from the shipped container, the
|
||||
request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's
|
||||
context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8
|
||||
wire, the diagnosis of the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, curl,
|
||||
jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, --prefill-interleave,
|
||||
runtime LoRA adapters served beside the base model and picked per request, and the prefix cache's
|
||||
reserved snapshots held until their save lands
|
||||
reserved snapshots held until their save lands, --expert-stats, imatrix entries in llama.cpp's
|
||||
spelling, typed tool-call argument tags, a chat template refused at load when it cannot render,
|
||||
rad-chatparse --request, a draft head's routed experts in host memory (--draft-expert-placement
|
||||
host) and decode-hot residency (--expert-profile, --expert-pin-top), prefix hits over KV groups of
|
||||
different block sizes and a hybrid's window in the checkpoint slot, --prefix-resume exact,
|
||||
DeepSeek-V4.1-Flash's conversion from its release (the Engram tables, the fused imatrix, the
|
||||
UD-IQ1_S recipe and rad-convert --chat-template), a preempted prefill admitted only with its whole
|
||||
recompute and the running sequences' next blocks free and the bound on its wait
|
||||
(--preempt-wait-ms), prompt lookup alone (--spec-ngram) with each sequence's n-gram index and the
|
||||
gate that verifies a proposal only when it pays, and DeepSeek-V4.1's reply format with its DSML
|
||||
tool calls, and expert_stats_report.py, and the KL mode's own line in the VRAM shortfall report
|
||||
- hazyumps: static YaRN for the Qwen rotary paths
|
||||
- malic: ParoQuant, with its MXFP4, int5 and int4 checkpoints imported and served, the Givens
|
||||
rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and 4-bit
|
||||
asymmetric GEMMs
|
||||
asymmetric GEMMs, and the int8 tiled GEMMs loading the weight a slab ahead
|
||||
- Perire: Gemma 4 26B-A4B with z-lab's DFlash drafter -- its plugin, its kernels in libr4d (the
|
||||
windowed paged attention, pair_argmax, the fused sandwich joins and expert_scale) and the host
|
||||
emulator that tests them, the prefill split into two slices with their all-reduces beside the
|
||||
compute, and the vocabulary-sharded draft head; Gemma 4 31B on four cards (its all-reduces fused
|
||||
with the junctions, overlapped with the compute and sent compressed, chained launches with block
|
||||
drafters), the embedding scale rounded as Hugging Face rounds it, and block drafters' drafts
|
||||
accepted on the card
|
||||
drafters), the embedding scale rounded as Hugging Face rounds it, block drafters' drafts
|
||||
accepted on the card, z-lab's DFlash drafter drafting on after a prefix-cache hit and the 31B's
|
||||
GPTQ calibration tap, and for speculation the MTP head's first draft read up to where it sits, no
|
||||
step queued behind one that ends its requests, a step's tokens streamed before the drafter's
|
||||
passes end, a block drafter's proposals verified as a tree, the 31B's block-16 DFlash2 tree with
|
||||
its short block under load, a block drafter's window carried in the window snapshot, and window
|
||||
snapshots from short prompts
|
||||
- redxherring: --model taking a Hugging Face repo id
|
||||
- Smellyyyy: the idea behind --prefill-interleave
|
||||
- gearwave00001: /v1/messages as Claude Code sends it
|
||||
@@ -44,12 +84,29 @@ Written by Deadcode, with contributions from:
|
||||
- sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix
|
||||
reuse that leaves a windowed group alone -- and --host-headroom-mib
|
||||
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg
|
||||
PR 50, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime
|
||||
PR 50, Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime, and Fish Audio drama-3 -- its
|
||||
plugin, its codec encoder and decoder, voice cloning from reference clips, and the torch.save
|
||||
reader
|
||||
- mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the
|
||||
sandwich junction's all-reduce and its DFlash2 drafter -- the fp8_v4 and k6_v4 KV caches, GPTQ's
|
||||
factorisations through LAPACK and a column-split linear's Hessian from per-rank parts,
|
||||
R4D_AR_MAX_BLOCKS for two engines on one set of cards, and added tokens decoded as HuggingFace
|
||||
decodes them
|
||||
R4D_AR_MAX_BLOCKS for two engines on one set of cards, added tokens decoded as HuggingFace decodes
|
||||
them, the MXFP4 GEMM rows for one to 64 rows and the tiled prefill GEMM's TN=4 form, the fp8 and
|
||||
int8 heads read once up to 128 rows, the pipelined prefill of one sequence on a second lane, Gemma
|
||||
3's junctions under a lossy wire, the block drafter's short block (--draft-short-from), the f16
|
||||
delta-net state cache, the two-rank all-reduce checking a peer's push has landed, the MXFP4 decode
|
||||
gate_up folded with its activation and fp8 quantiser, the head-256 split-KV decode attention,
|
||||
weight reads beside the decode all-reduces (--weight-prefetch), the head-256 prefill attention's
|
||||
KV split for small launches, the GUIDE's two engines on one pair, DFlash2's coupled acceptance at
|
||||
T > 0, the prefix cache's snapshot at a head prompts share, tip-only's snapshot a drafter window
|
||||
below the tip, Gemma 3's fused all-reduce junction on the lossy wire, the three-wave verify's
|
||||
split by depth, the delta net's out-projection read beside its decode recurrent update, the MXFP4
|
||||
feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's
|
||||
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6
|
||||
paged prefill, the preempted-prefill gate past a KV group that holds no blocks, and the norms'
|
||||
lane sum issuing its reads eight at a time, chained forms for every kernel of
|
||||
Qwen3.8-Flash-Next's decode step with hc_read's forms G, S and B3, and a preempted request
|
||||
publishing its prefix with an overdue one keeping its place
|
||||
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
|
||||
out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8
|
||||
linears' operands directly
|
||||
@@ -59,20 +116,94 @@ Written by Deadcode, with contributions from:
|
||||
exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose
|
||||
name the opener opens, GLM-5.3-Flash's vision tower and processor, its decode at a few rows and
|
||||
its DSA indexer split over the ranks, a host-tier restore that makes room as pressure does, KV
|
||||
groups every rank holds kept once a host slot, and the eight-rank two-shot in ring order
|
||||
groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA
|
||||
row form (--tp-attn-split rows), DELETE /sessions, the dispatch stamps of a played pass with
|
||||
stampgaps.py, one n-gram table for engines on separate cards (--ngram-placement ram=DIR), GGUF
|
||||
Q8_0, Q4_K and Q6_K tensors imported as their planes, the dense integer rows at the group they
|
||||
compute, and the GDN conv kernels on an f32 weight
|
||||
- John McDonough: GLM-5.3-Flash -- its plugin, its blocks (mHC streams, KDA, the DSA indexer and
|
||||
sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their
|
||||
reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the
|
||||
one-sequence KV floor over the live plan, and prefill staging paid by expert residency
|
||||
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and
|
||||
the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped
|
||||
rotation
|
||||
rotation, the dashboard's history line, session extremes, card-count changes and Requests-header
|
||||
JSON export, with the page's JavaScript driven by tests/js
|
||||
- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual
|
||||
projection
|
||||
projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's
|
||||
request history, KV streaming traffic and one-unit KV meter, and the mapped tier kept in the page
|
||||
cache across a load
|
||||
- J-Nova: Unlimited-OCR, and Sage-A1.5 with its vision tower and its DFlash2 drafter
|
||||
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8)
|
||||
- lortht: Krea 2's rebalance of the text taps
|
||||
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8), and the
|
||||
diagnosis of the expert loan held at zero by leftover cache blocks
|
||||
- lortht: Krea 2's rebalance of the text taps and its presets, MiniMax-H3's modulation rows, and
|
||||
keyframes carried through a latent upscale
|
||||
- Quackster: cards with a small PCI BAR, their kernel arguments kept in host memory
|
||||
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix, and
|
||||
Breeze-TTS-2's native voice cloning with its delivery direction (the Qwen3-TTS reference encoder,
|
||||
vq_euclidean and elu)
|
||||
- gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its
|
||||
BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode
|
||||
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds),
|
||||
and the head-256 prefill softmax rescaled by row rather than by wave, Spark 2.5 (spark25: bf16 and
|
||||
rotated-int8 IQ8R checkpoints, tensor parallelism with exact collectives, reasoning and tagged
|
||||
tool calls) with its DSpark drafter (exact attention and Markov walk ops), the prefill split keyed
|
||||
by live KV bounds, and --gpu-memory-mib
|
||||
- launch80_assets: tuning collectives as the exchange they serve at the served configuration, the
|
||||
per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch, and
|
||||
Meta Muse Glimmer 30B -- the museglimmer plugins, its windowed vision tower, its DFlash drafter,
|
||||
the ATEM tool dialect and its context extension
|
||||
- hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2
|
||||
drafter -- and the ParoQuant M2XFP4 import
|
||||
- steki: Gemma 4 E2B's per-layer MLP width and the bf16 descriptor for Google's E2B/E4B
|
||||
directories, nomic-embed-text-v2-moe (the nomicbert plugin), its config key aliases and
|
||||
RAD_MAP_TRANSPOSE honouring src_index, an f32 source narrowed to a bf16 declaration at load, and
|
||||
the snapshot store's floor ahead of --host-headroom-mib
|
||||
- griffin-warrior: the kernel report's consistency checks and coverage header, collective selftest
|
||||
cases skipped without a peer path, the build's media capability in the diagnostics, and the
|
||||
GUIDE's ROCm SDK and ffmpeg notes
|
||||
- nickreese: GBNF bounded-repetition chains shared across identical operands
|
||||
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid
|
||||
wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS
|
||||
and its gated three-tile form at 8 waves
|
||||
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library, and its wave-matrix rewrite: the GEMMs
|
||||
retiled to 16x128 blocks, the grouped MoE GEMMs, the norms and quantisers, and the QSA and MoE
|
||||
router rows, its MoE GEMMs at w4a8 and w4a4 with dequant_w4, row_topk_merge, ngram_ids and the
|
||||
biased and short GEMMs, and w4a4's reference implementation, and Ling-3.0-tiny on bailing_hybrid
|
||||
from its GGUF releases (the K-quant and IQ4_NL imports, the MLA query LoRA) with libr3d's
|
||||
gemm_nt_f32, ple_conv, grouped router, kda_update, mla_project and mla_attn_paged
|
||||
- fl0l0u: every request entry point bounded, gated and sanitised (JSON parses bounded in depth,
|
||||
errors safe on invalid UTF-8, control bytes kept off the log, the dashboard's CSP, cross-origin
|
||||
browsers refused on the loopback-only routes, method-scoped API-key exemptions), prompt ids that
|
||||
name no vocabulary row refused, and the telemetry the HTTP thread reads made atomic
|
||||
- Brandon Bertelsen: Cloudflare's clef and clef-flash with their joint schema head on the card
|
||||
(seg_softmax_pool, a request's words for the plugin), Convai Innovations' Laya decision models,
|
||||
Mica on /v1/systemone, and Metaspace prepending only to text not already starting with its
|
||||
replacement
|
||||
- Gaspa79: NVIDIA's Nemotron 3.5 Embed 1B and 8B -- the nemotron35_embed plugin, its Pixtral
|
||||
tower and their CPU path -- and Nemotron 3.5 Rerank 8B on /rerank, with its BF16 masked mean
|
||||
(seg_mean_bf16_sum)
|
||||
- overchop: the file tier for large MoEs -- routing-aware reads of only the routed experts, the
|
||||
hot VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read
|
||||
file-direct under expert parallelism -- the stall watch counting drive reads as progress, and
|
||||
the DMA lane's lists fenced so a stalled read pointer no longer fills its ring
|
||||
- pokesjw: the n-gram reader refilling its reads as they land, and a decode gather waiting on the
|
||||
other rank's read of a row instead of reading it again
|
||||
- AnimusNull: GLM-5.3-Flash on four cards -- its experts split by width, the small-M MXFP4 expert
|
||||
form at the TP4 slices, the indexer's take-all steps -- its E4M3 latent cache (mla_attn's fp8kv
|
||||
rows), and the DMA lane's room check over a reused fence slot
|
||||
- neuromanMD: libr3d's MXFP4 GEMM leaving VRAM exponent planes unscanned from the host, and its
|
||||
branch-free e4m3_to_f32
|
||||
- everplays: the paged attention at seven queries a KV head, head_dim 128 (Nanbeige4.3-33B), and
|
||||
Recursive Flint -- its plugin, the sink-aware WMMA prefill attention and the fused prologue at
|
||||
rotary_dim 0
|
||||
- Kezi: the decode tile arms of the int4 and int5 x int8 GEMM
|
||||
- dschmitz: the two-rank fused writes' host-mailbox twins taking their chained forms, the card
|
||||
telemetry's junction temperature, and a replayed tool call's blank arguments read as the empty
|
||||
object with arguments that are not JSON refused naming the call
|
||||
- eniga: the diagnosis of GLM-5.3-Flash's template refused for tools (jinja's unique filter)
|
||||
- tnhnyzc: the mixed-step service-time target (mixed-step-target-ms)
|
||||
- aelfwyne: the diagnosis of draft trees refusing the int8 KV cache's rows
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
@@ -81,9 +212,21 @@ license text is in the file named beside each.
|
||||
vendor/llama/, and the code lifted or ported from it: core/sample/gbnf.*, the
|
||||
host samplers in core/sample/host_ref.*, the tokenisers in core/text/, and
|
||||
libquant/lq_ggml_*
|
||||
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
|
||||
yyjson Copyright (c) 2020 YaoYuan vendor/yyjson/LICENSE
|
||||
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
|
||||
|
||||
The dashboard's page, compiled into the server from core/server/dashboard_page.h, carries
|
||||
third-party software built into it: React, Base UI and Floating UI, uPlot, shadcn/ui's components
|
||||
and helpers, Tailwind CSS's generated style and tw-animate-css (MIT), class-variance-authority
|
||||
(Apache-2.0), the Lucide icons (ISC), and the Geist and Geist Mono typefaces (SIL Open Font License
|
||||
1.1, Copyright the Geist Project Authors). dashboard/THIRD-PARTY-LICENSES.txt lists every package
|
||||
with its version and license text, as the page's build wrote it.
|
||||
|
||||
tests/data/chat/hyv3/chat_template.jinja is Tencent's Hy-Memory-30B-A3B chat template,
|
||||
copied unchanged from tencent/Hy-Memory-30B-A3B on Hugging Face.
|
||||
Copyright (C) 2026 Tencent. All rights reserved. Licensed under Apache-2.0 (LICENSE).
|
||||
Its source and content checksum are recorded in tests/data/chat/hyv3/README.md.
|
||||
|
||||
core/server/systemone.cpp carries text from Liquid AI's d1 (prompt.py and api.py in the
|
||||
LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the option codes and their
|
||||
fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid
|
||||
@@ -98,3 +241,28 @@ Community License 1.0 -- data/vectors/LICENSE.qwen-community-1.0.txt -- which ca
|
||||
every copy of it, including its condition that a Model-as-a-Service or AI-work-assistant business
|
||||
needs a separate license from Qwen to use it commercially. radiance's Apache-2.0 grant covers the
|
||||
code that loads and applies the file; it does not cover the file or its directions.
|
||||
|
||||
core/server/clef.cpp carries clef's system prompt, and it and arch/common/rad_block_clef.h follow
|
||||
clef's released joint head (Cloudflare's clef and clef-flash, Hugging Face, Apache-2.0).
|
||||
core/server/laya.cpp is a rewrite of the laya package (github.com/NandhaKishorM/laya, Apache-2.0).
|
||||
core/server/mica.cpp carries Mica's system prompt and option labels and is a rewrite of its
|
||||
contract.py and native.py, and tests/data/golden/mica_contract_cases.json is its
|
||||
tests/fixtures/contract_cases.json (github.com/akivet/Mica, Apache-2.0).
|
||||
|
||||
Nemotron 3.5 input fixtures
|
||||
--------------------------
|
||||
|
||||
tests/data/chat/nemotron35/template.jinja and tokenizer-subset.json come from NVIDIA's
|
||||
Nemotron-3.5-Embed-8B-BF16 checkpoint, revision
|
||||
781e779ee4ca9c2d2a4f38321993556baeab49a1:
|
||||
https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16/tree/781e779ee4ca9c2d2a4f38321993556baeab49a1
|
||||
The checkpoint's governing license is OpenMDW-1.1, retained in
|
||||
tests/data/chat/nemotron35/LICENSE. The tokenizer fixture is a subset preserving source token
|
||||
IDs and the BPE entries needed by the test corpus; it is not the complete serving tokenizer.
|
||||
|
||||
tests/data/chat/nemotron35/rerank-template.jinja comes from NVIDIA's
|
||||
Nemotron-3.5-Rerank-8B-BF16 checkpoint, revision
|
||||
f88f8d9104726747791283ab156d2fcdb29e90a7:
|
||||
https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16/tree/f88f8d9104726747791283ab156d2fcdb29e90a7
|
||||
It is covered by the same retained OpenMDW-1.1 license.
|
||||
Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
||||
@@ -6,56 +6,144 @@ APIs, Anthropic's Messages API and llama-server's native one, so their clients a
|
||||
unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this
|
||||
tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
|
||||
|
||||
The bundled device kernels (`libr4d`) target AMD RDNA4 (`gfx1200`, `gfx1201`). The serve flags
|
||||
The bundled device kernels target AMD RDNA4 (`libr4d`: `gfx1200`, `gfx1201`), RDNA3 (`libr3d`:
|
||||
`gfx11xx`) and Strix Halo (`libhalo`: `gfx1151`). The serve settings
|
||||
below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family;
|
||||
another card needs a kernel library for it. A machine with no GPU builds the host backend, whose
|
||||
AVX-512/AVX2 kernels (`libavx`) serve every model here: the small ones (EmbeddingGemma 2,
|
||||
Qwen3-ASR, the 0.8B-3B models) at interactive speed on a desktop CPU, the 27B and larger far more
|
||||
slowly than a card.
|
||||
|
||||
This fork adds a native **Intel GPU backend** (SYCL / Level Zero, kernel library `libxe2`) for the
|
||||
Arc Pro B65 (Battlemage, Xe2), next to the unchanged AMD and CPU paths. Its state and to-dos are in
|
||||
[Intel GPU backend](#intel-gpu-backend-sycl) below.
|
||||
|
||||
To support the development of radiance: [Patreon](https://patreon.com/StillDeadCode).
|
||||
|
||||
## Intel GPU backend (SYCL)
|
||||
|
||||
Target: Arc Pro B65 (`intel_gpu_bmg_g31`, 32 GB), oneAPI 2026.2. Main test model (from
|
||||
2026-10-27): `qwen3.8-27b-w4a16-rtn` (Qwen3.8-27B, int4 W4A16 trunk, int8 head, gated DeltaNet + full
|
||||
attention, MTP drafter); before it `Qwen3.8-27B-DFLASH2-PARO-M2XFP4` (m2xfp4 weights, DFlash2
|
||||
drafter). Reference point: vLLM-SYCL on the same class of model, ~90 tok/s decode and ~1200 tok/s
|
||||
prefill. The full log, measurements and decisions are in
|
||||
[`docs/SYCL_PROGRESS.md`](docs/SYCL_PROGRESS.md); the design is in
|
||||
[`docs/SYCL_PORTING.md`](docs/SYCL_PORTING.md).
|
||||
|
||||
**Current numbers** (Qwen3.8-27B, one sequence, BetterBench quick runs):
|
||||
|
||||
| | decode tok/s | prefill tok/s (~2000 tokens) |
|
||||
|---|---|---|
|
||||
| M2XFP4, first bring-up | 0.1 | 68 |
|
||||
| M2XFP4 (`2a5e815`) | 53.2 | 355 |
|
||||
| W4A16 RTN, first run (`e85124c`) | 44.9 | 301 |
|
||||
| W4A16 RTN now (`13c64a3`) | 46.4 | 490 |
|
||||
| vLLM-SYCL reference | ~90 | ~1200 |
|
||||
|
||||
MiniCPM5-2B bf16: decode 51.8 tok/s, prefill 1576 tok/s.
|
||||
|
||||
**Done**
|
||||
- A SYCL device backend in the engine and the `libxe2` kernel library: every op MiniCPM5-2B,
|
||||
Qwen3.8-27B M2XFP4 and Qwen3.8-27B W4A16 need, each with an exact form that matches libref bit for
|
||||
bit (`XE2_EXACT=1` selects them all).
|
||||
- W4A16 (int4 with zero points): weights tiled at load; decode GEMMs on fp16 DPAS, prefill GEMMs on
|
||||
int8 DPAS with the u4 codes as the B operand (libref's result bit for bit), the int8 head in
|
||||
ESIMD; prefill attention on DPAS (flash attention).
|
||||
- Fast kernels checked against libref with `rad-kbench` (1410/1410 fixture cases) and on live
|
||||
operands with the engine's op oracle; end to end held to a KL bound against the exact kernels.
|
||||
- Decode: m2xfp4 GEMV, 8-row verify GEMMs, the logits and 2-bit draft heads, the Givens rotation
|
||||
and split-KV attention on the matrix engine through register DPAS; exact DeltaNet recurrence,
|
||||
norms and drafter selection ops.
|
||||
- Speculative decoding with the DFlash2 drafter (~4 tokens accepted a round).
|
||||
- Prefill: GEMMs on oneMKL (85-91 TFLOPS), exact chunk-parallel DeltaNet scan and kkt solve.
|
||||
- BetterBench runs with reports posted to Discord (`scripts/sycl/bench_report.sh`), a decode
|
||||
profiler (`scripts/sycl/profile_decode.sh`).
|
||||
|
||||
**To do**
|
||||
- [ ] Decode (W4A16): the 4-row verify GEMMs (~27.6 of a ~58 ms round; floor ~22.7), the MTP
|
||||
drafter's bf16 GEMVs, the norms' ordered-sum floor, the narrow bf16 GEMV, fused casts; then the
|
||||
speculation depth. MTP accepts ~0.75 a position here, so 90 tok/s also needs model-side help
|
||||
(a calibrated quant, an int4 MTP block).
|
||||
- [ ] Prefill (W4A16): the DeltaNet ops (~2 s of a 2234-token prefill: chunk scan, kkt, conv,
|
||||
gated norm) on the matrix engine, the w4a8i8 GEMMs past ~75 int8 TOPS, gated_quant's double exp.
|
||||
- [ ] A KL check of the speculative (8-row) path, which the KL tool's 64-token chunks do not reach.
|
||||
- [ ] Batched serving (several sequences) on the fast paths; most fast paths assume one sequence.
|
||||
- [ ] Phase 5: README/Docker image for the Intel build, more model families.
|
||||
|
||||
**Build and run**
|
||||
|
||||
```sh
|
||||
. /opt/intel/oneapi/setvars.sh # icpx, Level Zero, oneMKL; also needed at run time
|
||||
cmake -S . -B build-sycl -G Ninja -DRAD_SYCL=ON # RAD_SYCL_TARGETS defaults to intel_gpu_bmg_g31
|
||||
cmake --build build-sycl -j16
|
||||
RADIANCE_HOME=$PWD/build-sycl/radiance_home build-sycl/bin/radiance \
|
||||
--model /models/qwen3.8-27b-dflash2-paro-m2xfp4/Qwen3.8-27B-DFLASH2-PARO-M2XFP4.rad \
|
||||
--max-model-len 8192 --max-num-seqs 1 --embedding-placement vram
|
||||
```
|
||||
|
||||
On a card behind a narrow PCIe link (the B65 here runs at x1), `--embedding-placement vram` keeps the
|
||||
token embedding on the card instead of reading it over the link. oneMKL is linked when CMake finds
|
||||
it (`-DRAD_XE2_MKL=OFF`, or `XE2_NO_MKL=1` at run time, keeps the hand-written prefill GEMMs).
|
||||
|
||||
## Models
|
||||
|
||||
| model | container | get it | compose file |
|
||||
| model | container | get it | fleet file |
|
||||
|---|---|---|---|
|
||||
| Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` |
|
||||
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
|
||||
| Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` |
|
||||
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
|
||||
| Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` |
|
||||
| Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` |
|
||||
| Sage-A1.5 FP8, MTP, vision | `sage-a1.5-fp8.rad` (35 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8) | `sage-a1.5.yaml`, `sage-a1.5-tp1.yaml` |
|
||||
| Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` |
|
||||
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
|
||||
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
|
||||
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` |
|
||||
| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (22 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash) | `gemma4-31b-w4a8-df.yaml` |
|
||||
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` |
|
||||
| Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` |
|
||||
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
|
||||
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
|
||||
| Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` |
|
||||
| Krea 2 Raw FP8: the same, undistilled | `krea-2-raw-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-fp8) | `krea-2-raw.yaml` |
|
||||
| FLUX.3 [klein] FP8: text to image and edits from up to ten pictures, one card | `flux-3-klein-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-fp8) | `flux-3-klein.yaml` |
|
||||
| FLUX.3 [klein] base FP8 | `flux-3-klein-base-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-fp8) | `flux-3-klein.yaml` |
|
||||
| LTX-2.5 distilled FP8: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-fp8) | `ltx-2.5.yaml` |
|
||||
| LTX-2.5 base FP8 | `ltx-2.5-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-fp8) | `ltx-2.5.yaml` |
|
||||
| MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` |
|
||||
| FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` |
|
||||
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` |
|
||||
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | `unlimited-ocr-bf16.yaml` |
|
||||
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` |
|
||||
| Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` |
|
||||
| TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` |
|
||||
| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, vision, eight cards | `glm53-flash-mxfp4.rad` (172 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` |
|
||||
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` |
|
||||
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` |
|
||||
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | `sdxl.yaml` |
|
||||
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
|
||||
| Anima Aesthetic FP8: anime and illustration, text to image, one card (Base and Turbo convert the same way) | `anima-aesthetic-fp8.rad` (3.0 GiB) | [convert](#convert-a-checkpoint) | `anima.yaml` |
|
||||
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | — |
|
||||
| Qwen3.8-Flash-Next: IQR-V4 experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-iqr-v4.rad` (113 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-iqr-v4) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Qwen3.8-27B IQ8R (rotated int8), DFlash2 drafter, vision | `qwen3.8-27b-iq8r-dflash.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iq8r-dflash) | `tp2.yaml` |
|
||||
| Qwen3.8-27B IQR-V4, 2.5 to 8 bits a weight ([docs/IQR.md](docs/IQR.md)), DFlash2 drafter, vision | `qwen3.8-27b-iq2r-v4.rad` .. `qwen3.8-27b-iq8r-v4.rad` (10 to 28 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4) | `tp1.yaml` (IQ4R-L) |
|
||||
| Qwen3.6-35B-A3B IQ8R, MTP | `qwen3.6-35b-a3b-iq8r.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-iq8r) | — |
|
||||
| MiniCPM5-2B IQ8R, DSpark drafter | `minicpm5-2b-iq8r.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r) | `tp1.yaml`, `tp2.yaml` |
|
||||
| MiniCPM5-2B bf16 (served without its drafter) | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | — |
|
||||
| Spark X2.6 4B bf16: thinking and tool calls, one to four cards | `spark-x2.6-4b-bf16.rad` (8.3 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | — |
|
||||
| Gemma 4 31B w5: GPTQ int5 trunk (a scale and a zero point per 128 weights), MTP, vision | `gemma4-31b-w5.rad` (23 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w5) | — |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | — |
|
||||
| Gemma 4 31B: int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-i8g) | — |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-heretic-ara-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-i8g) | — |
|
||||
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Gemma 4 12B bf16: MTP, vision, audio | `gemma4-12b-bf16.rad` (25 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-bf16) | — |
|
||||
| Gemma 4 12B int8 (i8a8): MTP, vision, audio | `gemma4-12b-i8g.rad` (14 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-i8g) | — |
|
||||
| Qwen-Image 2.1 IQ8R: text to image and image edits | `qwen-image-2.1-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-iq8r) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Qwen-Image 2.1 Turbo IQ8R: the same in 8 steps | `qwen-image-2.1-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-iq8r) | — |
|
||||
| Krea 2 Turbo IQ8R: text to image, one card | `krea-2-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-iq8r) | — |
|
||||
| Krea 2 Raw IQ8R: the same, undistilled | `krea-2-raw-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-iq8r) | — |
|
||||
| FLUX.3 [klein] IQ8R: text to image and edits from up to ten pictures, one card | `flux-3-klein-iq8r.rad` (9.4 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-iq8r) | — |
|
||||
| FLUX.3 [klein] base IQ8R | `flux-3-klein-base-iq8r.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-iq8r) | — |
|
||||
| LTX-2.5 distilled IQ8R: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-iq8r) | — |
|
||||
| LTX-2.5 base IQ8R | `ltx-2.5-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-iq8r) | — |
|
||||
| MiniMax-H3, int8 DiT: video with its stereo soundtrack from text | `minimax-h3-i8.rad` (63 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-i8) | `tp2.yaml` |
|
||||
| FastH3 8-Step V2, int8 DiT: the same in eight steps | `fasth3-8-step-v2-i8.rad` (65 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-i8) | — |
|
||||
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | — |
|
||||
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `tp1.yaml`, `tp2.yaml` |
|
||||
| TranslateGemma 27B, int8 trunk: translation | `translategemma-27b-i8.rad` (28 GiB) | [download](https://huggingface.co/StillDeadcode/translategemma-27b-i8) | — |
|
||||
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | — |
|
||||
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `tp1.yaml`, `tp2.yaml` |
|
||||
| nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | — |
|
||||
| LiquidAI LFM3-1.7B IQ8R: rotated int8 trunk, bf16 head; text, tool calls and reasoning, one card | `lfm3-1.7b-iq8r.rad` (2.5 GiB) | [convert](#convert-a-checkpoint) with `data/recipes/lfm3-1.7b-iq8r.recipe` | — |
|
||||
| LiquidAI LFM3-1.7B bf16: text, tool calls and reasoning, one card | `lfm3-1.7b-bf16.rad` (3.8 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Meta Muse Glimmer 30B bf16: text, images and video; sliding-window rotary layers between NoPE full ones, a windowed ViT | `muse-glimmer-30b-bf16.rad` (56 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Meta Muse Glimmer 30B w4a8: int4 trunk, images and video, one card | `muse-glimmer-30b-w4a8.rad` (16 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Meta Muse Glimmer 30B IQ8R: rotated int8 trunk, int8 head, DFlash drafter, images and video | `muse-glimmer-30b-iq8r-dflash.rad` (36 GiB) | [download](https://huggingface.co/StillDeadcode/muse-glimmer-30b-iq8r-dflash) | — |
|
||||
| Recursive Flint (39.8B, about 2.5B active) IQ8R: rotated int8 trunk and experts, two cards | `flint-iq8r.rad` (38 GiB) | [download](https://huggingface.co/StillDeadcode/flint-iq8r) | — |
|
||||
| Ling-3.0-tiny IQ8R: rotated int8 trunk and experts, one card | `ling-3.0-tiny-iq8r.rad` (7.9 GiB) | [download](https://huggingface.co/StillDeadcode/ling-3.0-tiny-iq8r) | — |
|
||||
| Nemotron 3.5 Embed 1B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16) | — |
|
||||
| Nemotron 3.5 Embed 8B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) | — |
|
||||
| Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | `tp1.yaml`, `tp2.yaml` |
|
||||
|
||||
**Not served by this version.** A container whose weights are block FP8, MXFP4, M2XFP4 or
|
||||
ParoQuant, or whose experts read E4M3 activations, is refused at startup by the name of the first
|
||||
such weight. That is every FP8 and MXFP4 container of the models above, and the models that have
|
||||
no int8 container yet: Ornith-1.5 (35B-A3B and 122B), Sage-A1.5,
|
||||
NVIDIA-Nemotron-3.5-Bolt-74B-A9B, GLM-5.3-Flash, Ling-3.0-flash-Sante, Fish Audio drama-3 and
|
||||
Anima's FP8 container (Anima converted to bf16 is served). Each returns with an int8 container.
|
||||
A container with an int8 or bf16 trunk and a block-FP8 drafter (NVIDIA-Nemotron-3.5-Bolt-E4B,
|
||||
the Gemma 4 31B DFlash and DFlash2 containers, MiniCPM5-2B bf16) serves without the drafter
|
||||
under `num-speculative-tokens: 0`.
|
||||
|
||||
A container holds everything the server needs: the weights, the tokeniser, the chat template and
|
||||
any drafter. Each download link's repository has the recipe and the exact command that made the
|
||||
@@ -63,7 +151,7 @@ file. Download one into your models directory (the transfer resumes if interrupt
|
||||
|
||||
```sh
|
||||
mkdir -p /srv/models/rad && cd /srv/models/rad
|
||||
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/minicpm5-2b-fp8.rad
|
||||
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r/resolve/main/minicpm5-2b-iq8r.rad
|
||||
```
|
||||
|
||||
The Gemma 4 container is keptn42's: GPTQ calibrated in transformers, with an int8 lm_head; its
|
||||
@@ -73,53 +161,43 @@ with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkp
|
||||
that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's,
|
||||
and accepts 0.46 of its drafts on prose against 0.50.
|
||||
|
||||
TranslateGemma 27B is converted from Google's bf16 checkpoint in three steps: an int8 container to
|
||||
calibrate in, its Gram matrices over translation prompts, then MXFP4 with GPTQ
|
||||
(`data/recipes/translategemma-27b-*.recipe`, the steps in docs/ARCHITECTURES.md). On two R9700s it
|
||||
decodes 56 tok/s a stream (205 at four) and scores mean KL 0.042 against the bf16 model on held-out
|
||||
translations; with a DFlash2 drafter, 152 a stream. Its chat template takes structured turns
|
||||
naming the two languages and refuses the plain turn the server renders at startup, so
|
||||
`translategemma-27b.yaml` serves a plain Gemma 3 template (`deploy/compose/gemma3.jinja`) and a
|
||||
client sends on `/v1/completions` the prompt the checkpoint's template renders.
|
||||
|
||||
GLM-5.3-Flash is converted from AMD's Quark export (`amd/GLM-5.3-Flash-Quark-MXFP4`) with
|
||||
`data/recipes/glm53-mxfp4.recipe`, which keeps every weight as stored except the latent
|
||||
attention's small kv_b, decoded to bf16. At 172 GiB it takes eight R9700s (`--tp 8`), every expert
|
||||
resident, and its own MTP layer drafts. On eight R9700s it prefills 3958 tok/s at 6k tokens,
|
||||
decodes 166 tok/s on one stream and 426 over eight, and 506 under eight streams of agent turns.
|
||||
Pictures go through its own vision tower, up to 4096 tokens an image at the default encoder pass
|
||||
(`--mm-max-patches 32000` serves the checkpoint's 8000); the KV cache is bf16. Its template knows
|
||||
the reasoning efforts `low` and
|
||||
`high` and renders any other as its maximum, so `glm53-flash.yaml` maps `medium` and `xhigh`
|
||||
to `high`.
|
||||
|
||||
The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned
|
||||
Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from
|
||||
`Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with
|
||||
`data/recipes/q38-27b-paro-mxfp4-df2.recipe` and the DFlash2 drafter. A ParoQuant container made
|
||||
before 1.5.0 is refused at startup; convert it again with the old one as `--reuse`, which copies
|
||||
every tensor that did not change.
|
||||
TranslateGemma 27B is converted from Google's bf16 checkpoint with
|
||||
`data/recipes/translategemma-27b-i8a8.recipe`, an int8 trunk rounded without calibration data.
|
||||
Its chat template takes structured turns
|
||||
naming the two languages and refuses the plain turn the server renders at startup, so its entry
|
||||
serves a plain Gemma 3 template, `deploy/compose/gemma3.jinja` (`override-chat-template` names it;
|
||||
in a compose file, mount it into the container), and a client sends on `/v1/completions` the prompt
|
||||
the checkpoint's template renders.
|
||||
|
||||
The Qwen-Image containers serve OpenAI's images API (`/v1/images/generations`, `/v1/images/edits`):
|
||||
pictures from a prompt, and edits of up to ten pictures with an optional mask, 2048x2048 by default.
|
||||
On two R9700s a 2048x2048 picture takes 61 s at the base model's 40 steps and 13 s with Turbo (56 and
|
||||
12 s with `--tp-wire wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
|
||||
license, which is non-commercial.
|
||||
12 s with `tp-wire: wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
|
||||
license, which is non-commercial. Krea 2 is under the Krea 2 Community License and Krea's
|
||||
acceptable use policy, FLUX.3 [klein] under the FLUX Kommunity License (non-commercial use),
|
||||
LTX-2.5 under the LTX-2.x Community License, and an SDXL finetune under its checkpoint's own
|
||||
license.
|
||||
|
||||
The MiniMax-H3 containers serve OpenAI's video jobs (`/v1/videos`): a video with its stereo
|
||||
soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip at 1344x768 takes
|
||||
about 68 s with FastH3 and 8.8 minutes at MiniMax-H3's 50 steps; both read about 39 GiB of pinned
|
||||
host memory. With LBH-123-AI's latent upscaler in the container, `"latent_upscale": 2` runs the first
|
||||
steps at half the size and refines at the full size: MiniMax-H3's clip then takes 3.4 minutes
|
||||
(docs/GUIDE.md §5.16). MiniMax-H3's license, which FastH3 carries, does not cover the EU, the UK,
|
||||
the Republic of Korea or the USA.
|
||||
(docs/GUIDE.md §5.16). A ComfyUI node, `integrations/comfyui/ComfyUI-Radiance-MiniMax`, renders
|
||||
through `/v1/videos` from a ComfyUI graph as a client of the server. MiniMax-H3's license, which
|
||||
FastH3 carries, does not cover the EU, the UK, the Republic of Korea or the USA.
|
||||
|
||||
MiniMax-Music3 and Breeze-TTS-2 answer `/v1/audio/speech`, whole or streamed as they are made: a song
|
||||
from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays on two cards; and
|
||||
speech in a voice the request describes, made in 0.6 of its playing time on one card, its first
|
||||
streamed audio 0.21 s after the request. Breeze-TTS-2 also speaks text while it is being written,
|
||||
over the `/v1/audio/speech/stream` WebSocket; it is licensed for research and non-commercial use
|
||||
only.
|
||||
only. Fish Audio's drama-3 speaks a script whose speakers and direction are written in it
|
||||
(`<|speaker:1|>`, `[laughs]`), each speaker in the model's voice or one cloned from a reference
|
||||
clip and its transcript, at 0.3 of its playing time on two cards, its first streamed audio
|
||||
0.23 s after the request; under the Fish Audio Community License a service that lets others
|
||||
generate speech with it needs a licence from Fish Audio, and imitating a real person's voice needs
|
||||
their consent.
|
||||
|
||||
## Run with Docker
|
||||
|
||||
@@ -128,21 +206,28 @@ card works best with Resizable BAR on (Above 4G Decoding and Resizable BAR in th
|
||||
without it the engine keeps kernel arguments in pinned host memory, and every dispatch reads them
|
||||
over the link. The image
|
||||
is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels
|
||||
built for `gfx1201`. Pull it, clone this repository for its compose files, then start a model from
|
||||
one of them:
|
||||
built for `gfx1201` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix Halo). Pull it, clone
|
||||
this repository for its compose files, then start one of them:
|
||||
|
||||
```sh
|
||||
docker pull stilldeadcode/radiance
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git
|
||||
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
|
||||
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_API_KEY, the GIDs
|
||||
docker compose -f minicpm5-2b.yaml up -d # or any file from the table
|
||||
docker compose -f minicpm5-2b.yaml logs -f
|
||||
docker compose -f minicpm5-2b.yaml down
|
||||
docker compose -f tp2.yaml up -d # two cards; tp1.yaml for one (RADIANCE_GPU)
|
||||
docker compose -f tp2.yaml logs -f
|
||||
docker compose -f tp2.yaml down
|
||||
```
|
||||
|
||||
Every model listens on the same port and most use both cards, so run one at a time. Running without
|
||||
compose, and the reason for each `docker run` option, is in [`docs/DOCKER.md`](docs/DOCKER.md).
|
||||
A file serves all its models from one container behind one port, and brings a model onto the cards
|
||||
when a request names it ([`docs/MULTIMODEL.md`](docs/MULTIMODEL.md)): a request's `model` is the
|
||||
entry's name (`flashnext`, `qwen3.8-27b`, `minicpm5-2b`, ...). The entries are in
|
||||
`tp1.radiance.yaml` and `tp2.radiance.yaml` beside the compose files, the server's configuration as
|
||||
it reads it. Delete the entries of the containers
|
||||
you do not have; any other model from the table is added as an entry with its keys from the table
|
||||
under [Run without Docker](#run-without-docker). The two files take the same port, so run one at a
|
||||
time. Running without compose, and the reason for each `docker run` option, is in
|
||||
[`docs/DOCKER.md`](docs/DOCKER.md).
|
||||
|
||||
To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'`
|
||||
in the clone (it needs `docker buildx` and tests the build as it goes). Then set
|
||||
@@ -171,73 +256,141 @@ prefix gets `bin/`, `include/radiance/`, `lib/cmake/radiance/`, `libexec/radianc
|
||||
With ROCm 10.1 the build turns the compiler's VOPD pairing (dual-issue instruction pairs) off: its
|
||||
LLVM 24 pairs in an order that follows heap addresses, so two builds of the same source can differ.
|
||||
The Docker image builds its compiler with the fix and keeps the pairing, which is 1.4-3.5% faster
|
||||
on the fp8 prefill GEMMs; a compiler that has the same fix is declared with
|
||||
on prefill GEMMs; a compiler that has the same fix is declared with
|
||||
`-DRAD_HIP_VOPD_REPEATABLE=ON`. ROCm 7.2 is unaffected.
|
||||
|
||||
## Run without Docker
|
||||
|
||||
```sh
|
||||
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install finds its own
|
||||
build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 <flags>
|
||||
build/bin/radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000 <flags>
|
||||
The server reads its settings from a YAML file: `server:` holds the listener, `memory:` the
|
||||
per-card VRAM budget, and `models:` one entry whose name is the model id requests use. Every key
|
||||
is named as in the [`docs/GUIDE.md`](docs/GUIDE.md) §4.11 reference; `radiance --help` prints it.
|
||||
|
||||
```yaml
|
||||
# radiance.yaml
|
||||
server:
|
||||
port: 8000
|
||||
models:
|
||||
minicpm5-2b-iq8r:
|
||||
model: /srv/models/rad/minicpm5-2b-iq8r.rad # or a Hugging Face repo id: StillDeadcode/minicpm5-2b-iq8r
|
||||
```
|
||||
|
||||
`--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
|
||||
and `jq` (`scripts/hfget.sh`) into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere),
|
||||
```sh
|
||||
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install finds its own
|
||||
build/bin/radiance --config radiance.yaml --check # validate the file, serve nothing
|
||||
build/bin/radiance --config radiance.yaml
|
||||
```
|
||||
|
||||
`model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
|
||||
and `jq` (`scripts/hfget.sh`) into `~/.cache/radiance/hf` (`server.download-dir` puts it elsewhere),
|
||||
serves the container it holds, and checks it for changes at every start; a start that cannot reach
|
||||
the hub serves the copy it has. The Docker image carries both tools; in a container,
|
||||
`--download-dir` must name a writable mount, since the compose files mount `/models` read-only.
|
||||
`server.download-dir` must name a writable mount, since the compose files mount `/models` read-only.
|
||||
|
||||
These rows match the compose files, minus Flash-Next's `--prefix-cache-mib`; the three- and
|
||||
four-rank rows have no compose file. The other models' flags are in their compose files.
|
||||
The server takes no other command-line options. A command line written for an earlier release
|
||||
(`radiance --model ... --tp 2`) is refused with the same settings printed as YAML, and
|
||||
`rad-yaml FLAGS...` prints that file without starting anything:
|
||||
`rad-yaml --model x.rad --tp 2 > radiance.yaml`. [`docs/MULTIMODEL.md`](docs/MULTIMODEL.md) §4
|
||||
describes the file's levels.
|
||||
|
||||
| model | flags |
|
||||
Each row holds the keys a model is served with in a file of its own (the Flash-Next rows leave out
|
||||
`prefix-cache-mib`). They go under the model's entry, except `gpu-headroom-mib`, which goes under
|
||||
`memory:` and in a file of several models holds for all of them. `tp1.radiance.yaml` and
|
||||
`tp2.radiance.yaml` carry their models' entries as set for sharing the cards; a model added to either takes its row from
|
||||
here.
|
||||
|
||||
| model | keys |
|
||||
|---|---|
|
||||
| Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-27B FP8 and MXFP4, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` |
|
||||
| Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` |
|
||||
| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` |
|
||||
| Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` |
|
||||
| Qwen-Image 2.1 and 2.1 Turbo | `--tp 2 --tp-wire wht6` |
|
||||
| MiniMax-H3 and FastH3 | `--tp 2 --vision-tower-placement ram` |
|
||||
| MiniMax-Music3 | `--tp 2` |
|
||||
| Breeze-TTS-2 | `--tp 1` |
|
||||
| Qwen3.8-Flash-Next | `tp: 2, tp-wire: wht6, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
|
||||
| Qwen3.8-Flash-Next, one card | `tp: 1, max-num-seqs: 4, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 43000, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 4096, checkpoint-interval: 4096` |
|
||||
| Qwen3.8-Flash-Next, four ranks | `tp: 4, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 49152, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
|
||||
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `tp: 3, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
|
||||
| Qwen3.8-27B IQ8R and IQR-V4, Qwen3.6-35B-A3B | `tp: 2, max-num-seqs: 32, max-model-len: 200000, kv-cache-dtype: i8` |
|
||||
| Qwen3.8-27B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 200000, kv-cache-dtype: i8` |
|
||||
| MiniCPM5-2B IQ8R and bf16 | `tp: 2, max-num-seqs: 32, max-model-len: 131072, kv-cache-dtype: i8, gpu-headroom-mib: 160, max-num-batched-tokens: 512` |
|
||||
| Qwen3.8-Flash-Next bf16 | `tp: 2, max-model-len: 32768, placement: expert_tiered, weights-disk-tier: true, host-pool-mib: 24576, gpu-headroom-mib: 768, deterministic: true, max-num-seqs: 32, max-num-batched-tokens: 32768, num-speculative-tokens: 0` |
|
||||
| Qwen-Image 2.1 and 2.1 Turbo | `tp: 2, tp-wire: wht6` |
|
||||
| MiniMax-H3 and FastH3 | `tp: 2, vision-tower-placement: ram` |
|
||||
| MiniMax-Music3 | `tp: 2`, or `tp: 1` (20.5 GiB of weights on the card) |
|
||||
| Breeze-TTS-2 | `tp: 1` |
|
||||
| Gemma 4 31B (GPTQ int4) | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
|
||||
| Gemma 4 31B w5, heretic-ara int4, int8 and heretic-ara int8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, vision-tower-placement: ram, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
|
||||
| Gemma 4 31B Q8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 0, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
|
||||
| Gemma 4 12B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
|
||||
| Gemma 4 12B int8 | `tp: 1, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16, int8 and 4-bit, without the drafter | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 0, mm-max-patches: 2520, vision-tower-placement: ram, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}`; `tp: 1` on one card |
|
||||
| TranslateGemma 27B | `tp: 2, max-num-seqs: 8, max-model-len: 16384, kv-cache-dtype: i8`, and `override-chat-template` naming `deploy/compose/gemma3.jinja` |
|
||||
| Unlimited-OCR | `tp: 1, max-num-seqs: 8, max-model-len: 32768, kv-cache-dtype: i8, gpu-headroom-mib: 96`, and `override-chat-template` naming `deploy/chat-templates/unlimited-ocr-parser.jinja` (`/chat-templates/unlimited-ocr-parser.jinja` in the compose files' container) |
|
||||
| Krea 2 Turbo and Raw, FLUX.3 [klein] and its base, Stable Diffusion XL | `tp: 1` |
|
||||
| LTX-2.5 distilled and base | `tp: 1, vision-tower-placement: ram` |
|
||||
| EmbeddingGemma 2 | `tp: 1, max-num-seqs: 64, max-num-batched-tokens: 8192` |
|
||||
| Qwen3-ASR 1.7B | `tp: 1, max-num-seqs: 16` |
|
||||
|
||||
Every model here runs at up to 32 sequences a step. The Flash-Next rows (except the bf16 reference)
|
||||
and the 27B in bf16 keep 8: on a hybrid model each sequence holds its own recurrent state, and 32 of
|
||||
them take that memory from the attention cache and, on Flash-Next, from the expert slab. See
|
||||
The 27B in IQ8R and IQR-V4, the 35B-A3B, MiniCPM5 and the Flash-Next bf16 reference run at up to
|
||||
32 sequences a step. The other Flash-Next rows and the 27B in bf16 keep 8, the one-card Flash-Next
|
||||
row 4: on a hybrid model each sequence holds its own recurrent state, and 32 of them take that
|
||||
memory from the attention cache and, on Flash-Next, from the expert slab. See
|
||||
[`docs/GUIDE.md`](docs/GUIDE.md) §4.4.
|
||||
|
||||
At `--tp 4`, decode and verify steps carry the exact all-reduce in the gated residual's write, with
|
||||
On one card a Flash-Next prefill step copies every pooled expert across the link once, so a
|
||||
4096-token step shares that copy among twice the tokens of a 2048-token one (26K-token prompts:
|
||||
2545 against 1413 tok/s); the checkpoint interval matches the step because a prefill chunk never
|
||||
crosses a checkpoint. At 4 sequences that row's cache holds 301K tokens. The Flash-Next bf16 row
|
||||
is a reference to calibrate and compare against, a step taking tens of seconds whatever its size;
|
||||
its 32K of context keeps QSA's score plane for a 32K-token step at 1 GiB.
|
||||
|
||||
At `tp: 4`, decode and verify steps carry the exact all-reduce in the gated residual's write, with
|
||||
the MoE gather in front of it; a prefill chunk runs the unfused chain. That chain's exact
|
||||
all-reduce is one-shot up to 1 MiB a message and two-shot above, which sends half the bytes on a
|
||||
prefill chunk; both produce the same bits. The four-rank row runs exact. At three and four ranks
|
||||
`--tp-wire wht6` selects a different lossy wire, tiered int8 over the two-shot, above
|
||||
`--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at startup
|
||||
`tp-wire: wht6` selects a different lossy wire, tiered int8 over the two-shot, above
|
||||
`tp-wire-min-kb`. Eight ranks have no lossy wire, so `tp: 8` with `tp-wire: wht6` stops at startup
|
||||
naming the all-reduce.
|
||||
|
||||
Four ranks is a capacity configuration: its per-step rate against `--tp 2` on the same cards has
|
||||
not been measured, and its tiering flags are the two-rank recipe carried over. As at two ranks, each
|
||||
Four ranks is a capacity configuration: its per-step rate against `tp: 2` on the same cards has
|
||||
not been measured, and its tiering keys are the two-rank recipe carried over. As at two ranks, each
|
||||
rank owns a slice of every expert's width: each parity's 128-column blocks are cut contiguously over
|
||||
the ranks and the odd block alternates with the parity, so every rank's share is whole blocks and
|
||||
every block has one owner. The resident expert bytes per rank are smaller, so the elastic window
|
||||
has a different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before
|
||||
has a different shape: read the boot log's `elastic` line and re-derive `host-pool-mib` before
|
||||
trusting it.
|
||||
|
||||
`--host-pool-mib` is pinned on every card, so the four-rank row pins 4 × 12 GiB = 48 GiB of RAM
|
||||
that nothing else can use and the kernel cannot swap out. The amdgpu driver caps what all processes
|
||||
`host-pool-mib` is what a model pins for its weights in all, each rank an equal share: the
|
||||
four-rank row pins 48 GiB of RAM (12 GiB a rank) that nothing else can use and the kernel cannot
|
||||
swap out. The amdgpu driver caps what all processes
|
||||
together pin at the machine's RAM less 1/64 and 1.5 GiB; the pool is locked user memory, which
|
||||
`ttm.pages_limit` does not count. A 64 GiB machine serves `flashnext-tp1.yaml` with 49 GiB pinned
|
||||
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
|
||||
`ttm.pages_limit` does not count. A 64 GiB machine serves the one-card Flash-Next row alone, with
|
||||
`prefix-cache-mib: 4096`, at about 49 GiB pinned ([`docs/GUIDE.md`](docs/GUIDE.md) §7). In
|
||||
`tp1.yaml` its entry carries `prefix-cache-mib: 1024` so its host pins fit such a host beside the
|
||||
8 GiB the fleet keeps free; there it is unloaded when another model loads, and on a 61 GB host it
|
||||
answered its next request after 17 to 19 s, loaded from its container again.
|
||||
|
||||
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `--debug-graph`
|
||||
The Gemma 4 rows sample as the checkpoint's `generation_config` states, and a request switches
|
||||
thinking (`chat_template_kwargs`). `vision-tower-placement: ram` keeps the vision tower in host
|
||||
memory, so its VRAM goes to the KV cache. The 31B takes its full 262,144-token context at
|
||||
`max-model-len: 262144, max-num-seqs: 2`. The 12B keeps a bf16 cache because an 8-bit one costs it
|
||||
more than it saves; on Bolt-E4B an E4M3 cache cost 9x the KL and the int8 cache is unmeasured. The
|
||||
Bolt-E4B row serves without speculation because the published containers' drafters are block FP8.
|
||||
|
||||
EmbeddingGemma 2 takes an input in one step, so its `max-num-batched-tokens` is the longest input
|
||||
as well as the batch. A live Qwen3-ASR session holds one sequence, so its `max-num-seqs` is the
|
||||
most sessions served at once. On one card LTX-2.5's adapter slots fit at `max-lora-rank: 16,
|
||||
max-loras: 1` (433 MiB).
|
||||
|
||||
In a file of several models, Qwen-Image's grant counts two sequences of `max-model-len` tokens of
|
||||
cache, which at the model's own 33600 tokens is 55.8 GiB on one card and 32.6 GiB a card on two,
|
||||
more than the cards. `tp1.yaml` sets `max-model-len: 8192` (it needs 29.7 GiB; pictures up to
|
||||
about 1.9 megapixels, 1024x1024 being 4096 tokens) and `tp2.yaml` `20480` (25.4 GiB a card; the
|
||||
default 2048x2048 is 16384 tokens). Alone in a file it loads at its own length, its cache taking
|
||||
what the cards have left. It sizes its buffers itself and warns that it does not take
|
||||
`image-gen-max-pixels` or `image-gen-max-refs`.
|
||||
|
||||
Add `server.api-key: KEY` (or `server.api-key-env: VAR`, which reads it from the environment) to
|
||||
require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `debug-graph: true` on the model
|
||||
prints every op and the kernel it resolved to, then exits without serving. A chat request:
|
||||
|
||||
```sh
|
||||
curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
|
||||
-d '{"model":"minicpm5-2b-iq8r","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
|
||||
```
|
||||
|
||||
An image model answers OpenAI's images API instead, with base64 pictures:
|
||||
@@ -257,6 +410,8 @@ budgets, long context, speculative decoding and operating a server.
|
||||
`data/recipes/` names. Download checkpoints with `scripts/hfget.sh <org/repo> <dir>`.
|
||||
|
||||
```sh
|
||||
# Spark X2.6 uses the checkpoint's BF16 weights, tokenizer and chat template; no recipe required.
|
||||
build/bin/rad-convert /srv/models/hf/XHToken-Spark-X2.6-4B -o spark-x2.6-4b-bf16.rad --max-ctx 4096
|
||||
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \
|
||||
--recipe data/recipes/q38-27b-bf16.recipe
|
||||
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096
|
||||
@@ -272,9 +427,17 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-q
|
||||
--recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \
|
||||
--set quantization_config.quant_method=compressed-tensors \
|
||||
--draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash
|
||||
build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \
|
||||
--recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \
|
||||
--draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2
|
||||
# Meta's Muse Glimmer 30B, as it ships (bf16), with an int4 trunk and int8 attention values, or
|
||||
# with an IQ8R trunk and an int8 head
|
||||
build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-bf16.rad \
|
||||
--recipe data/recipes/museglimmer-30b-bf16.recipe
|
||||
build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-w4a8.rad \
|
||||
--recipe data/recipes/museglimmer-30b-w4a8.recipe \
|
||||
--set quantization_config.quant_method=compressed-tensors
|
||||
build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-iq8r-dflash.rad \
|
||||
--draft-model /srv/models/hf/meta-models/Muse-Glimmer-30B-assistant \
|
||||
--recipe data/recipes/museglimmer-30b-iq8r.recipe \
|
||||
--set quantization_config.quant_method=compressed-tensors
|
||||
build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \
|
||||
--recipe data/recipes/q38-27b-w4a16.recipe
|
||||
# Any single-file SDXL checkpoint (SDXL 1.0, Illustrious, NoobAI, Pony, a civitai finetune), with
|
||||
@@ -286,15 +449,20 @@ build/bin/rad-convert /srv/models/hf/OnomaAIResearch/Illustrious-XL-v2.0/Illustr
|
||||
|
||||
With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`.
|
||||
In the image the recipes are in `/opt/radiance/share/radiance/recipes/`. A checkpoint served at its
|
||||
own precision needs no container: `radiance --model /srv/models/hf/Qwen/Qwen3.8-27B-FP8`. A release
|
||||
someone else quantised is read as it ships when the engine serves its form (block-scaled FP8,
|
||||
Quark's MXFP4), written at its own numbers when the kernels read them in another spelling (an int4
|
||||
W4A16 release, compressed-tensors' AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with
|
||||
`data/recipes/q38-27b-w4a16.recipe`), and converted from its exact dequantisation when no kernel
|
||||
reads it: NVFP4 (compressed-tensors' and NVIDIA ModelOpt's) to the MXFP4 kernels, an AutoRound
|
||||
Flash-Next's int4 block projections to int8. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
|
||||
own precision needs no container: its directory is the entry's `model`
|
||||
(`model: /srv/models/hf/Qwen/Qwen3.8-27B`). A release someone else quantised to an integer grid is
|
||||
written at its own numbers where the kernels read them (an int4 W4A16 release, compressed-tensors'
|
||||
AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with `data/recipes/q38-27b-w4a16.recipe`). Block
|
||||
FP8, MXFP4, NVFP4 and ParoQuant releases are not served: convert the model's bf16 checkpoint with
|
||||
an int8 recipe. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
|
||||
with their `rad-convert` commands.
|
||||
|
||||
Spark X2.6 runs BF16 at `tp: 1`, `2`, `3` or `4` -- and `8`, the worlds libr4d has an exact
|
||||
all-reduce for -- without a drafter or quantisation recipe. Its checkpoint's chat template enables
|
||||
thinking by default; replies return reasoning in `reasoning_content`. Set
|
||||
`chat_template_kwargs.enable_thinking` to `false` for a non-thinking request. Tool calls use the
|
||||
checkpoint's tagged format and are returned as OpenAI `tool_calls`.
|
||||
|
||||
## Test
|
||||
|
||||
```sh
|
||||
@@ -313,11 +481,14 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o
|
||||
|---|---|
|
||||
| [`docs/GUIDE.md`](docs/GUIDE.md) | installing, converting, serving, the HTTP API, operating a server |
|
||||
| [`docs/TOOLS.md`](docs/TOOLS.md) | every flag of every tool, and the recipe syntax |
|
||||
| [`docs/DIAGNOSE.md`](docs/DIAGNOSE.md) | `diagnose`: the engine measures itself, and what makes a run a measurement |
|
||||
| [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files |
|
||||
| [`docs/PREPARING_YOUR_RIG.md`](docs/PREPARING_YOUR_RIG.md) | a two-R9700 machine from firmware setup to a serving model |
|
||||
| [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card |
|
||||
| [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry |
|
||||
| [`docs/TP3.md`](docs/TP3.md) | any world size: the attention world and uneven delta-net heads; three ranks |
|
||||
| [`docs/OPS.md`](docs/OPS.md), [`docs/KERNELS.md`](docs/KERNELS.md) | the op vocabulary, and what `rad-kbench` last measured |
|
||||
| [`docs/SYCL_PROGRESS.md`](docs/SYCL_PROGRESS.md), [`docs/SYCL_PORTING.md`](docs/SYCL_PORTING.md) | the Intel GPU (SYCL) backend: progress log and design |
|
||||
| [`spec.md`](spec.md) | the design |
|
||||
|
||||
## License
|
||||
|
||||
+64
-12
@@ -13,12 +13,15 @@ extern "C" {
|
||||
#endif
|
||||
|
||||
/* Bumped whenever anything a plugin compiles against changes shape: this header, rad_types.h,
|
||||
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h or rad_sample.h. Every
|
||||
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
|
||||
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
|
||||
* change of shape: a plugin without it gets the default. rad_sycl.h is versioned on its own
|
||||
* (RAD_SYCL_STREAM_VERSION), since only SYCL kernel libraries read it. */
|
||||
#define RAD_ABI_VERSION 26u
|
||||
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h, rad_sample.h or
|
||||
* rad_spechub.h, a field appended to a struct included; the release that ships the change assigns
|
||||
* the number. Every kind of plugin reports it, and a plugin that does not report exactly this
|
||||
* version is refused at load with both versions printed. Each also exports the layout's fingerprint
|
||||
* (rad_abi_layout.h), so two layouts given one number are refused as well. A new optional export
|
||||
* (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default.
|
||||
* rad_sycl.h is versioned on its own (RAD_SYCL_STREAM_VERSION), since only SYCL kernel libraries
|
||||
* read it. */
|
||||
#define RAD_ABI_VERSION 42u
|
||||
|
||||
/* ================================================================== plugin identity */
|
||||
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
|
||||
@@ -36,8 +39,10 @@ typedef struct RadPluginInfo {
|
||||
const char* build_target;
|
||||
} RadPluginInfo;
|
||||
|
||||
/* Every plugin exports these two. */
|
||||
/* Every plugin exports these three; rad_plugin_abi_layout is RAD_PLUGIN_ABI_LAYOUT_EXPORT
|
||||
* (rad_abi_layout.h). */
|
||||
uint32_t rad_plugin_abi_version(void);
|
||||
uint64_t rad_plugin_abi_layout(void);
|
||||
const RadPluginInfo* rad_plugin_info(void);
|
||||
|
||||
/* ================================================================== execution domain */
|
||||
@@ -57,6 +62,16 @@ typedef struct RadArgs {
|
||||
void* instance; /* whatever init() returned for this resolved instance */
|
||||
int rank; /* tensor-parallel rank and world size, for collectives */
|
||||
int world_size;
|
||||
/* ABI 35: host-side maximum KV length represented by this exact launch operand (a seqused
|
||||
* span or a supported one-sequence prefill boundary), or -1 when it cannot be proven. In a
|
||||
* decode, verify or draft pass it is instead the step's context bound plus its longest query,
|
||||
* which the recorded pass's key holds. Plugins
|
||||
* must not infer it from a device pointer or synchronously read device memory to get it. */
|
||||
int32_t kv_used_max_h;
|
||||
/* The current rank's WGP count (HIP multiProcessorCount on RDNA); lets split launchers use
|
||||
* exactly the same per-device occupancy as architecture pass-key callbacks without querying
|
||||
* the process-global current device on the hot path. */
|
||||
int32_t wgp_count;
|
||||
} RadArgs;
|
||||
|
||||
/* Read a parameter by key. Inline definitions, because a plugin links only the ABI headers and
|
||||
@@ -149,7 +164,8 @@ typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEnc
|
||||
|
||||
/* Write the stored form `layout` described into `dst`, `dst_bytes` long, from the planes, which
|
||||
* now carry their bytes. Pure host code, run by the loader on a pool behind the container read,
|
||||
* so it has to keep pace with the disk. */
|
||||
* so it has to keep pace with the disk. The planes are read only: the loader may hand them
|
||||
* straight out of its read buffer, which the copies for other ranks read at the same time. */
|
||||
typedef int (*RadRelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n_planes, void* dst,
|
||||
int64_t dst_bytes);
|
||||
@@ -462,15 +478,20 @@ typedef struct RadKernelInfo {
|
||||
* against: a named skip, not a failure. */
|
||||
RadUnrelayoutFn unrelayout;
|
||||
/* The chain of conventional ops this kernel computes in one launch, or null if it is not a
|
||||
* fusion. Non-null also counts in rad-kbench's fusion-claim column.
|
||||
* fusion. Non-null also counts in rad-kbench's fusion-claim column. */
|
||||
RadFuseFn replaces;
|
||||
/* Flags describing runtime behavior relevant to core safety decisions. Zero means none.
|
||||
*
|
||||
* Keep this field last. Kernel tables are positional aggregate initialisers
|
||||
* (`{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}`), so a field inserted
|
||||
* anywhere else shifts every later initialiser, and since `nullptr` converts to any function
|
||||
* pointer type, part of that shift would still compile. Append new fields after this one. */
|
||||
RadFuseFn replaces;
|
||||
uint64_t capabilities;
|
||||
} RadKernelInfo;
|
||||
|
||||
/* This row's launch grid can depend on live seqused during prefill. */
|
||||
#define RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT (1ull << 0)
|
||||
|
||||
/* ================================================================== kernel plugin exports */
|
||||
/* Every kernel plugin exports the whole set. The first plugin in hierarchy order to declare an op
|
||||
* fixes its schema; a later plugin declaring the same op name with a different schema is refused
|
||||
@@ -497,6 +518,15 @@ const RadKernelInfo* rad_kernel_at(int i);
|
||||
typedef int (*RadPluginOpenFn) (void);
|
||||
typedef void (*RadPluginCloseFn)(void);
|
||||
|
||||
/* Optional, symbol `rad_plugin_freed`. The core has freed the device memory [base, base + bytes)
|
||||
* and nothing launched against it runs any more. A kernel library that keeps state keyed by an
|
||||
* operand's address (a counter block per output buffer, made at the first launch and replayed by
|
||||
* recorded passes) drops what it keeps for addresses inside the range. A process serving several
|
||||
* models frees an engine's memory when it unloads the model, so state kept past that would pile
|
||||
* up with every load. Called from the freeing thread, any number of times, possibly for ranges the
|
||||
* plugin never saw. */
|
||||
typedef void (*RadPluginFreedFn)(const void* base, int64_t bytes);
|
||||
|
||||
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means every launch reads and writes
|
||||
* only its operands and the scratch it was handed (no allocation it keeps, no counter kept between
|
||||
* launches), so two launches may run at once on one device when their operands and scratch do not
|
||||
@@ -516,7 +546,17 @@ typedef int (*RadKernelConcurrentFn)(int i);
|
||||
* do, adds exactly once. The record is RAD_CHAIN_REC_BYTES at byte RAD_CHAIN_KARG_OFF of the
|
||||
* kernel's argument segment: { magic, target, ctr, check }, with check = magic ^ target ^ ctr ^
|
||||
* RAD_CHAIN_CHECK. A record whose magic or check does not match means: run without waiting and do
|
||||
* not add. Without the symbol, or with 0, the engine never asks. Symbol name: `rad_kernel_chain`. */
|
||||
* not add. Without the symbol, or with 0, the engine never asks.
|
||||
*
|
||||
* 2 instead of 1 adds a second promise: the chained form's own acquire covers everything it reads
|
||||
* behind the wait, scalar loads included. A compiler's agent-scope fence invalidates the vector
|
||||
* caches only; a load every lane shares may be a scalar one, served from the scalar data cache,
|
||||
* which still holds what was there before the launch in front wrote. A form that invalidates that
|
||||
* cache behind its acquire (`s_dcache_inv`), or reads no operand through it, may say 2. Where
|
||||
* every chainable row an engine loads says 2, the engine issues a chained launch that has lost
|
||||
* its barrier bit without the packet processor's acquire as well: on an R9700 that acquire holds
|
||||
* the processor ~0.9 us a launch, and it comes too early to serve a kernel that then waits for
|
||||
* the launch in front. With 1 the packets keep it. Symbol name: `rad_kernel_chain`. */
|
||||
typedef int (*RadKernelChainFn)(int i);
|
||||
#define RAD_CHAIN_KARG_OFF 992
|
||||
#define RAD_CHAIN_REC_BYTES 32
|
||||
@@ -550,9 +590,21 @@ typedef int (*RadKernelCollectiveFn)(int i);
|
||||
* - the engine refuses to serve a model with an op only a reference library implements, unless
|
||||
* given --debug-accept-reference-kernels;
|
||||
* - rad-kbench checks every other library against it.
|
||||
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`. */
|
||||
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`.
|
||||
*
|
||||
* It is a whole-library answer, because a library is usually one implementation of one thing. A
|
||||
* plugin that ships a device row AND the host oracle beside it is not: marking the library would
|
||||
* mark its device rows too, and the engine would refuse to serve an op that has a real kernel.
|
||||
* Such a plugin exports `rad_kernel_reference` below and leaves this one 0. */
|
||||
typedef int (*RadPluginReferenceFn)(void);
|
||||
|
||||
/* Optional, per row: nonzero says kernel `i` of rad_kernel_at is that row's reference
|
||||
* implementation. Overrides `rad_plugin_reference` for the rows it is exported for, so one
|
||||
* library can declare a device row (0) and its host oracle (1) side by side. A plugin that
|
||||
* exports neither leaves every row classified by `rad_plugin_reference`. Symbol name:
|
||||
* `rad_kernel_reference`. */
|
||||
typedef int (*RadKernelReferenceFn)(int i);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/* rad_abi_layout.h -- the plugin ABI's layout fingerprint: a hash of the size of every struct abi/
|
||||
* exports and of the offset and size of each of its fields (rad_abi_layout_rows.h), as the
|
||||
* translation unit that includes this header sees them.
|
||||
*
|
||||
* RAD_ABI_VERSION names a layout, but two trees can give the same number to different layouts, and
|
||||
* a plugin built against one then reads the other's structs at the wrong offsets, with no error. A
|
||||
* plugin exports its own fingerprint (RAD_PLUGIN_ABI_LAYOUT_EXPORT, once in the plugin), and the
|
||||
* loader refuses one whose fingerprint differs from the engine's under the same version. C and C++.
|
||||
*/
|
||||
#ifndef RAD_ABI_LAYOUT_H
|
||||
#define RAD_ABI_LAYOUT_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_builder.h"
|
||||
#include "rad_device.h"
|
||||
#include "rad_encoding.h"
|
||||
#include "rad_format.h"
|
||||
#include "rad_philox.h"
|
||||
#include "rad_planes.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "rad_quant.h"
|
||||
#include "rad_runtime.h"
|
||||
#include "rad_sample.h"
|
||||
#include "rad_spechub.h"
|
||||
#include "rad_sycl.h"
|
||||
#include "rad_types.h"
|
||||
#include "rad_yarn.h"
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* FNV-1a over the eight bytes of `v`, little end first. */
|
||||
static inline uint64_t rad_abi_layout_mix(uint64_t h, uint64_t v) {
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
h ^= (v >> (8 * i)) & 0xffu;
|
||||
h *= 0x100000001b3ull;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/* The fingerprint of the abi/ headers this translation unit was compiled against. */
|
||||
static inline uint64_t rad_abi_layout(void) {
|
||||
uint64_t h = 0xcbf29ce484222325ull;
|
||||
h = rad_abi_layout_mix(h, RAD_ABI_VERSION);
|
||||
#define ABI_STRUCT(T) h = rad_abi_layout_mix(h, sizeof(T));
|
||||
#define ABI_FIELD(T, f) \
|
||||
h = rad_abi_layout_mix(h, offsetof(T, f)); \
|
||||
h = rad_abi_layout_mix(h, sizeof(((T*)0)->f));
|
||||
#include "rad_abi_layout_rows.h"
|
||||
#undef ABI_STRUCT
|
||||
#undef ABI_FIELD
|
||||
return h;
|
||||
}
|
||||
|
||||
/* The export the loader reads beside rad_plugin_abi_version: written once in a plugin, at file
|
||||
* scope. */
|
||||
#ifdef __cplusplus
|
||||
#define RAD_PLUGIN_ABI_LAYOUT_EXPORT \
|
||||
extern "C" uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); }
|
||||
#else
|
||||
#define RAD_PLUGIN_ABI_LAYOUT_EXPORT \
|
||||
uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); }
|
||||
#endif
|
||||
|
||||
#endif /* RAD_ABI_LAYOUT_H */
|
||||
@@ -1,6 +1,7 @@
|
||||
/* abi_layout_rows.h -- every struct abi/ exports and each of its top-level fields, as
|
||||
* ABI_STRUCT(type) and ABI_FIELD(type, field) lines; the includer defines both. abi_c_test.c and
|
||||
* abi_layout_test.cpp include it, so the C and C++ translation units list the same rows.
|
||||
/* rad_abi_layout_rows.h -- every struct abi/ exports and each of its top-level fields, as
|
||||
* ABI_STRUCT(type) and ABI_FIELD(type, field) lines; the includer defines both. rad_abi_layout.h
|
||||
* hashes them into the layout fingerprint every plugin exports, and tests/abi_c_test.c and
|
||||
* tests/abi_layout_test.cpp list them, so the C and C++ translation units see the same rows.
|
||||
*
|
||||
* A struct or field added to abi/ is added here too: abi_layout_test fails on a struct whose
|
||||
* listed fields do not account for its size. Included once per table, so it has no include guard.
|
||||
@@ -16,9 +17,16 @@ ABI_FIELD(RadArchProbe, gen_patches)
|
||||
ABI_FIELD(RadArchProbe, gen_audio)
|
||||
ABI_FIELD(RadArchProbe, gen_ctx)
|
||||
ABI_FIELD(RadArchProbe, gen_video)
|
||||
ABI_FIELD(RadArchProbe, kv_quant_ok)
|
||||
ABI_FIELD(RadArchProbe, kv_fp8_ok)
|
||||
ABI_FIELD(RadArchProbe, chain_pays)
|
||||
ABI_FIELD(RadArchProbe, kv_stream_ok)
|
||||
ABI_FIELD(RadArchProbe, control_vector_ok)
|
||||
ABI_FIELD(RadArchProbe, tp_attn_rows_ok)
|
||||
ABI_FIELD(RadArchProbe, state_f16_ok)
|
||||
ABI_FIELD(RadArchProbe, tree_pays)
|
||||
ABI_FIELD(RadArchProbe, gen_max_pixels)
|
||||
ABI_FIELD(RadArchProbe, gen_max_refs)
|
||||
ABI_FIELD(RadArchProbe, gen_shape)
|
||||
ABI_STRUCT(RadArgs)
|
||||
ABI_FIELD(RadArgs, t)
|
||||
ABI_FIELD(RadArgs, n_t)
|
||||
@@ -29,6 +37,8 @@ ABI_FIELD(RadArgs, scratch_bytes)
|
||||
ABI_FIELD(RadArgs, instance)
|
||||
ABI_FIELD(RadArgs, rank)
|
||||
ABI_FIELD(RadArgs, world_size)
|
||||
ABI_FIELD(RadArgs, kv_used_max_h)
|
||||
ABI_FIELD(RadArgs, wgp_count)
|
||||
ABI_STRUCT(RadBatch)
|
||||
ABI_FIELD(RadBatch, phase)
|
||||
ABI_FIELD(RadBatch, step)
|
||||
@@ -80,6 +90,21 @@ ABI_FIELD(RadBatch, vgen_b)
|
||||
ABI_FIELD(RadBatch, control_vector)
|
||||
ABI_FIELD(RadBatch, enc_seg_h)
|
||||
ABI_FIELD(RadBatch, enc_seg_w)
|
||||
ABI_FIELD(RadBatch, score_only)
|
||||
ABI_FIELD(RadBatch, n_plugin_words)
|
||||
ABI_FIELD(RadBatch, plugin_words)
|
||||
ABI_FIELD(RadBatch, plugin_cu)
|
||||
ABI_FIELD(RadBatch, plugin_words_h)
|
||||
ABI_FIELD(RadBatch, plugin_cu_h)
|
||||
ABI_FIELD(RadBatch, sgen_b)
|
||||
ABI_FIELD(RadBatch, kv_used_max_h)
|
||||
ABI_FIELD(RadBatch, positions_h)
|
||||
ABI_FIELD(RadBatch, n_bidi)
|
||||
ABI_FIELD(RadBatch, bidi_row)
|
||||
ABI_FIELD(RadBatch, bidi_n)
|
||||
ABI_FIELD(RadBatch, bidi_seq)
|
||||
ABI_FIELD(RadBatch, bidi_used)
|
||||
ABI_FIELD(RadBatch, anchor_rows)
|
||||
ABI_STRUCT(RadBufDecl)
|
||||
ABI_FIELD(RadBufDecl, dtype)
|
||||
ABI_FIELD(RadBufDecl, rank)
|
||||
@@ -105,9 +130,23 @@ ABI_FIELD(RadBuildCtx, max_enc_patches)
|
||||
ABI_FIELD(RadBuildCtx, max_out_rows)
|
||||
ABI_FIELD(RadBuildCtx, max_audio_frames)
|
||||
ABI_FIELD(RadBuildCtx, max_mixed_tok)
|
||||
ABI_FIELD(RadBuildCtx, kv_quant)
|
||||
ABI_FIELD(RadBuildCtx, attn_prefill_fp8)
|
||||
ABI_FIELD(RadBuildCtx, kv_resident_blocks)
|
||||
ABI_FIELD(RadBuildCtx, kv_stream_ok)
|
||||
ABI_FIELD(RadBuildCtx, cvec)
|
||||
ABI_FIELD(RadBuildCtx, tp_attn_rows)
|
||||
ABI_FIELD(RadBuildCtx, state_dtype)
|
||||
ABI_FIELD(RadBuildCtx, draft_coupling)
|
||||
ABI_FIELD(RadBuildCtx, weight_prefetch_off)
|
||||
ABI_FIELD(RadBuildCtx, draft_tree)
|
||||
ABI_FIELD(RadBuildCtx, calib_dir)
|
||||
ABI_FIELD(RadBuildCtx, calib_layer_lo)
|
||||
ABI_FIELD(RadBuildCtx, calib_layer_hi)
|
||||
ABI_FIELD(RadBuildCtx, calib_tokens)
|
||||
ABI_FIELD(RadBuildCtx, gen_max_pixels)
|
||||
ABI_FIELD(RadBuildCtx, gen_max_refs)
|
||||
ABI_FIELD(RadBuildCtx, expert_file_tier)
|
||||
ABI_FIELD(RadBuildCtx, slot_base)
|
||||
ABI_FIELD(RadBuildCtx, plain_norm)
|
||||
ABI_STRUCT(RadAudioGenBatch)
|
||||
ABI_FIELD(RadAudioGenBatch, n_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, lane)
|
||||
@@ -144,6 +183,17 @@ ABI_FIELD(RadAudioGenBatch, voc_latents)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_left)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_right)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_frame0)
|
||||
ABI_FIELD(RadAudioGenBatch, prev_slot)
|
||||
ABI_FIELD(RadAudioGenBatch, prev_pos)
|
||||
ABI_FIELD(RadAudioGenBatch, prev_used)
|
||||
ABI_FIELD(RadAudioGenBatch, n_ref)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_samples)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_audio)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_cu)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_cu_h)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_frame)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_frame_h)
|
||||
ABI_FIELD(RadAudioGenBatch, prompt_cu_h)
|
||||
ABI_STRUCT(RadAudioGenDecl)
|
||||
ABI_FIELD(RadAudioGenDecl, name)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl)
|
||||
@@ -176,6 +226,16 @@ ABI_FIELD(RadAudioGenDecl, prompt_whole)
|
||||
ABI_FIELD(RadAudioGenDecl, first_frame)
|
||||
ABI_FIELD(RadAudioGenDecl, voc_chunk)
|
||||
ABI_FIELD(RadAudioGenDecl, voc_context)
|
||||
ABI_FIELD(RadAudioGenDecl, branches)
|
||||
ABI_FIELD(RadAudioGenDecl, input_special)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl_ref)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_item)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_rate)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_hop)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_max_samples)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_max)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl_ref_instruct)
|
||||
ABI_FIELD(RadAudioGenDecl, neg_tmpl_ref)
|
||||
ABI_STRUCT(RadControlVector)
|
||||
ABI_FIELD(RadControlVector, dir)
|
||||
ABI_FIELD(RadControlVector, scales)
|
||||
@@ -221,6 +281,8 @@ ABI_FIELD(RadChatFormat, object_string_open)
|
||||
ABI_FIELD(RadChatFormat, object_string_close)
|
||||
ABI_FIELD(RadChatFormat, object_bare_keys)
|
||||
ABI_FIELD(RadChatFormat, reasoning_anywhere)
|
||||
ABI_FIELD(RadChatFormat, arg_json_value_prefix)
|
||||
ABI_FIELD(RadChatFormat, content_open)
|
||||
ABI_STRUCT(RadConstraint)
|
||||
ABI_FIELD(RadConstraint, key)
|
||||
ABI_FIELD(RadConstraint, op)
|
||||
@@ -237,6 +299,7 @@ ABI_FIELD(RadDeviceProps, vram_free)
|
||||
ABI_FIELD(RadDeviceProps, lds_bytes)
|
||||
ABI_FIELD(RadDeviceProps, supports_p2p)
|
||||
ABI_FIELD(RadDeviceProps, is_host_backend)
|
||||
ABI_FIELD(RadDeviceProps, unified)
|
||||
ABI_STRUCT(RadDrafterDecl)
|
||||
ABI_FIELD(RadDrafterDecl, name)
|
||||
ABI_FIELD(RadDrafterDecl, kind)
|
||||
@@ -265,6 +328,7 @@ ABI_FIELD(RadEncoderDecl, max_patches)
|
||||
ABI_FIELD(RadEncoderDecl, n_embd)
|
||||
ABI_FIELD(RadEncoderDecl, out)
|
||||
ABI_FIELD(RadEncoderDecl, one_grid)
|
||||
ABI_FIELD(RadEncoderDecl, bidirectional)
|
||||
ABI_STRUCT(RadEncoding)
|
||||
ABI_FIELD(RadEncoding, scheme)
|
||||
ABI_FIELD(RadEncoding, transform)
|
||||
@@ -453,6 +517,8 @@ ABI_FIELD(RadKVGroupBatch, state_index)
|
||||
ABI_FIELD(RadKVGroupBatch, state_index_pitch)
|
||||
ABI_FIELD(RadKVGroupBatch, block_size)
|
||||
ABI_FIELD(RadKVGroupBatch, max_blocks)
|
||||
ABI_FIELD(RadKVGroupBatch, stream)
|
||||
ABI_FIELD(RadKVGroupBatch, seqused_h)
|
||||
ABI_STRUCT(RadKVGroupDecl)
|
||||
ABI_FIELD(RadKVGroupDecl, kind)
|
||||
ABI_FIELD(RadKVGroupDecl, dtype)
|
||||
@@ -461,6 +527,16 @@ ABI_FIELD(RadKVGroupDecl, n_head_kv)
|
||||
ABI_FIELD(RadKVGroupDecl, head_dim)
|
||||
ABI_FIELD(RadKVGroupDecl, state_dim)
|
||||
ABI_FIELD(RadKVGroupDecl, conv_width)
|
||||
ABI_STRUCT(RadKVStream)
|
||||
ABI_FIELD(RadKVStream, host)
|
||||
ABI_FIELD(RadKVStream, res)
|
||||
ABI_FIELD(RadKVStream, slot_block)
|
||||
ABI_FIELD(RadKVStream, slot_state)
|
||||
ABI_FIELD(RadKVStream, ctl)
|
||||
ABI_FIELD(RadKVStream, block_bytes)
|
||||
ABI_FIELD(RadKVStream, host_layer_stride)
|
||||
ABI_FIELD(RadKVStream, slots)
|
||||
ABI_FIELD(RadKVStream, host_bytes)
|
||||
ABI_STRUCT(RadKernelInfo)
|
||||
ABI_FIELD(RadKernelInfo, name)
|
||||
ABI_FIELD(RadKernelInfo, op)
|
||||
@@ -484,6 +560,7 @@ ABI_FIELD(RadKernelInfo, relayout)
|
||||
ABI_FIELD(RadKernelInfo, opd_shape)
|
||||
ABI_FIELD(RadKernelInfo, unrelayout)
|
||||
ABI_FIELD(RadKernelInfo, replaces)
|
||||
ABI_FIELD(RadKernelInfo, capabilities)
|
||||
ABI_STRUCT(RadLayout)
|
||||
ABI_FIELD(RadLayout, tag)
|
||||
ABI_FIELD(RadLayout, dtype)
|
||||
@@ -642,6 +719,44 @@ ABI_FIELD(RadSampleParams, hist_len)
|
||||
ABI_FIELD(RadSampleParams, mask_row)
|
||||
ABI_FIELD(RadSampleParams, flags)
|
||||
ABI_FIELD(RadSampleParams, dry_rep_limit)
|
||||
ABI_STRUCT(RadShapeGenBatch)
|
||||
ABI_FIELD(RadShapeGenBatch, lane)
|
||||
ABI_FIELD(RadShapeGenBatch, patches)
|
||||
ABI_FIELD(RadShapeGenBatch, step)
|
||||
ABI_FIELD(RadShapeGenBatch, n_steps)
|
||||
ABI_FIELD(RadShapeGenBatch, sigma)
|
||||
ABI_FIELD(RadShapeGenBatch, sigma_next)
|
||||
ABI_FIELD(RadShapeGenBatch, cfg)
|
||||
ABI_FIELD(RadShapeGenBatch, pair)
|
||||
ABI_FIELD(RadShapeGenBatch, lanes)
|
||||
ABI_FIELD(RadShapeGenBatch, flags)
|
||||
ABI_FIELD(RadShapeGenBatch, seed)
|
||||
ABI_FIELD(RadShapeGenBatch, lat_cu)
|
||||
ABI_FIELD(RadShapeGenBatch, n_query)
|
||||
ABI_FIELD(RadShapeGenBatch, query)
|
||||
ABI_FIELD(RadShapeGenBatch, query_cu)
|
||||
ABI_STRUCT(RadShapeGenDecl)
|
||||
ABI_FIELD(RadShapeGenDecl, name)
|
||||
ABI_FIELD(RadShapeGenDecl, canvas)
|
||||
ABI_FIELD(RadShapeGenDecl, border_ratio)
|
||||
ABI_FIELD(RadShapeGenDecl, enc_size)
|
||||
ABI_FIELD(RadShapeGenDecl, enc_patch)
|
||||
ABI_FIELD(RadShapeGenDecl, pix_mean)
|
||||
ABI_FIELD(RadShapeGenDecl, pix_std)
|
||||
ABI_FIELD(RadShapeGenDecl, latent_rows)
|
||||
ABI_FIELD(RadShapeGenDecl, latent_channels)
|
||||
ABI_FIELD(RadShapeGenDecl, step_rows)
|
||||
ABI_FIELD(RadShapeGenDecl, default_steps)
|
||||
ABI_FIELD(RadShapeGenDecl, max_steps)
|
||||
ABI_FIELD(RadShapeGenDecl, default_guidance)
|
||||
ABI_FIELD(RadShapeGenDecl, bounds)
|
||||
ABI_FIELD(RadShapeGenDecl, level)
|
||||
ABI_FIELD(RadShapeGenDecl, default_resolution)
|
||||
ABI_FIELD(RadShapeGenDecl, min_resolution)
|
||||
ABI_FIELD(RadShapeGenDecl, max_resolution)
|
||||
ABI_FIELD(RadShapeGenDecl, max_lanes)
|
||||
ABI_FIELD(RadShapeGenDecl, max_query)
|
||||
ABI_FIELD(RadShapeGenDecl, field_out)
|
||||
ABI_STRUCT(RadSyclStream)
|
||||
ABI_FIELD(RadSyclStream, magic)
|
||||
ABI_FIELD(RadSyclStream, version)
|
||||
@@ -688,6 +803,19 @@ ABI_FIELD(RadVideoGenBatch, image)
|
||||
ABI_FIELD(RadVideoGenBatch, has_image)
|
||||
ABI_FIELD(RadVideoGenBatch, guidance)
|
||||
ABI_FIELD(RadVideoGenBatch, decoder)
|
||||
ABI_FIELD(RadVideoGenBatch, sampler)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_pixels)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_frames)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_height)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_width)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_samples)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_n_samples)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_channels)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_geom_d)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_kind)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_slot)
|
||||
ABI_FIELD(RadVideoGenBatch, ref_tab)
|
||||
ABI_FIELD(RadVideoGenBatch, mod_cu)
|
||||
ABI_STRUCT(RadVideoGenDecl)
|
||||
ABI_FIELD(RadVideoGenDecl, name)
|
||||
ABI_FIELD(RadVideoGenDecl, tmpl)
|
||||
@@ -750,6 +878,14 @@ ABI_FIELD(RadVideoGenDecl, duration_max)
|
||||
ABI_FIELD(RadVideoGenDecl, duration_dtype)
|
||||
ABI_FIELD(RadVideoGenDecl, decoders)
|
||||
ABI_FIELD(RadVideoGenDecl, decoder_max_area)
|
||||
ABI_FIELD(RadVideoGenDecl, max_ref_images)
|
||||
ABI_FIELD(RadVideoGenDecl, max_ref_videos)
|
||||
ABI_FIELD(RadVideoGenDecl, max_ref_audios)
|
||||
ABI_FIELD(RadVideoGenDecl, max_enc_frames)
|
||||
ABI_FIELD(RadVideoGenDecl, max_enc_side)
|
||||
ABI_FIELD(RadVideoGenDecl, max_enc_samples)
|
||||
ABI_FIELD(RadVideoGenDecl, enc_ratio)
|
||||
ABI_FIELD(RadVideoGenDecl, max_mod_cells)
|
||||
ABI_STRUCT(RadVideoGeom)
|
||||
ABI_FIELD(RadVideoGeom, n_text)
|
||||
ABI_FIELD(RadVideoGeom, frames)
|
||||
@@ -805,3 +941,22 @@ ABI_FIELD(RadYarn, factor)
|
||||
ABI_FIELD(RadYarn, low)
|
||||
ABI_FIELD(RadYarn, high)
|
||||
ABI_FIELD(RadYarn, magnitude)
|
||||
ABI_STRUCT(RadMtpCoupleDraw)
|
||||
ABI_FIELD(RadMtpCoupleDraw, seed)
|
||||
ABI_FIELD(RadMtpCoupleDraw, base)
|
||||
ABI_FIELD(RadMtpCoupleDraw, seq)
|
||||
ABI_FIELD(RadMtpCoupleDraw, card)
|
||||
ABI_FIELD(RadMtpCoupleDraw, mode)
|
||||
ABI_STRUCT(RadMtpCoupleState)
|
||||
ABI_FIELD(RadMtpCoupleState, draw)
|
||||
ABI_FIELD(RadMtpCoupleState, pos)
|
||||
ABI_FIELD(RadMtpCoupleState, status)
|
||||
ABI_FIELD(RadMtpCoupleState, round)
|
||||
ABI_FIELD(RadMtpCoupleState, x)
|
||||
ABI_FIELD(RadMtpCoupleState, count)
|
||||
ABI_FIELD(RadMtpCoupleState, ids)
|
||||
ABI_FIELD(RadMtpCoupleState, q)
|
||||
ABI_FIELD(RadMtpCoupleState, nkids)
|
||||
ABI_FIELD(RadMtpCoupleState, scheme)
|
||||
ABI_FIELD(RadMtpCoupleState, blk)
|
||||
ABI_FIELD(RadMtpCoupleState, pad_)
|
||||
+515
-76
@@ -56,35 +56,27 @@ double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt);
|
||||
const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt);
|
||||
|
||||
/* ================================================================== build context */
|
||||
/* RadBuildCtx::kv_quant. A layout groups each head's dims by 32 with an f16 scale per group, the
|
||||
* group's absmax over the largest code. A token's row in a head, at head_dim HD (a multiple of 32):
|
||||
/* A paged cache group's dtype says how a token's row in a head is laid out, at head_dim HD:
|
||||
*
|
||||
* RAD_KVQ_V4 (fp8_v4), 25 * HD / 16 bytes:
|
||||
* [0, HD) K, E4M3 as the fp8 cache stores it
|
||||
* [HD, 3HD/2) V's int4 codes, dim d in the nibble at bit 4 * (d % 2) of byte d / 2
|
||||
* [3HD/2, 25HD/16) V's scales (absmax / 7)
|
||||
* RAD_KVQ_K6V4 (k6_v4), 22 * HD / 16 bytes:
|
||||
* [0, HD/2) K's low four bits, as V's codes above
|
||||
* [HD/2, 3HD/4) K's high two bits, a 4-byte word per 16 dims whose byte j holds dims 2j
|
||||
* and 2j+1 in bits 0-3 and dims 8+2j and 9+2j in bits 4-7
|
||||
* [3HD/4, 5HD/4) V's int4 codes
|
||||
* [5HD/4, 21HD/16) K's scales (absmax / 31)
|
||||
* [21HD/16, 22HD/16) V's scales (absmax / 7)
|
||||
*
|
||||
* Codes are two's complement (int4 -7..7, int6 -31..31). The group is declared at RAD_F8E4M3 with
|
||||
* head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read
|
||||
* it. */
|
||||
enum {
|
||||
RAD_KVQ_NONE = 0,
|
||||
RAD_KVQ_V4 = 1,
|
||||
RAD_KVQ_K6V4 = 2
|
||||
};
|
||||
* RAD_BF16, 4 * HD bytes: K then V, as the model computes them.
|
||||
* RAD_I8, 2 * HD + 4 bytes: K and V as int8 codes with one f16 scale each per (token, head):
|
||||
* [0, HD) K's int8 codes (two's complement, -127..127)
|
||||
* [HD, 2HD) V's int8 codes
|
||||
* [2HD, 2HD + 2) K's scale (the head's absmax / 127)
|
||||
* [2HD + 2, 2HD + 4) V's scale (absmax / 127)
|
||||
* The plugin declares HD; the core adds the scales' bytes (rad_kv_row_elems). */
|
||||
|
||||
/* The products of the prefill attention a deployment accepts in e4m3 (RadBuildCtx::
|
||||
* attn_prefill_fp8, `attn_paged`'s `prefill_fp8`): bits, so both is 3. */
|
||||
/* Elements of a token's row in one head of a paged group declared at `dtype` and `head_dim`: K
|
||||
* then V, and under the int8 cache the two f16 scales after them. */
|
||||
static inline int64_t rad_kv_row_elems(uint32_t dtype, int64_t head_dim) {
|
||||
return 2 * head_dim + (dtype == RAD_I8 ? 4 : 0);
|
||||
}
|
||||
|
||||
/* RadArchProbe::chain_pays. */
|
||||
enum {
|
||||
RAD_ATTN_FP8_QK = 1, /* Q.K^T, the query rounded to e4m3 after the softmax scale */
|
||||
RAD_ATTN_FP8_PV = 2 /* P.V, the probabilities rounded to e4m3 */
|
||||
RAD_CHAIN_NONE = 0,
|
||||
RAD_CHAIN_SPEC = 1, /* with a drafter decoding speculatively */
|
||||
RAD_CHAIN_ALWAYS = 2 /* with or without one */
|
||||
};
|
||||
|
||||
typedef struct RadBuildCtx {
|
||||
@@ -111,17 +103,16 @@ typedef struct RadBuildCtx {
|
||||
int64_t tp_wire_min_bytes;
|
||||
|
||||
|
||||
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint: fp8
|
||||
* weights may want a bf16 cache and vice versa.
|
||||
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint.
|
||||
*
|
||||
* RAD_DT_INVALID (the zero-initialised default) means the plugin's default, bf16 for every
|
||||
* architecture in this tree. RAD_F8E4M3 is the only other implemented value: the fp8kv
|
||||
* attention family is band-gated on it, and the store side writes E4M3 with per-(sequence,
|
||||
* head) descales. `kv_quant` below narrows the trunk's attention cache further.
|
||||
* architecture in this tree. RAD_I8 is the other value every paged attention serves, the
|
||||
* int8 cache above: the attention kernels band on it and the store writes each token's codes
|
||||
* and scales. RAD_F8E4M3 reaches only a plugin whose probe sets RadArchProbe::kv_fp8_ok.
|
||||
*
|
||||
* An ABI field rather than an environment variable because it changes what the model
|
||||
* computes, so it must have one visible answer: --kv-cache-dtype. */
|
||||
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); or RAD_F8E4M3 */
|
||||
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); RAD_I8; RAD_F8E4M3 */
|
||||
int is_draft; /* this builder scope is a drafter (spec §10) */
|
||||
const char* scope; /* "", "draft", "vision", "audio" -- prefixes declared names */
|
||||
|
||||
@@ -172,27 +163,17 @@ typedef struct RadBuildCtx {
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_mixed_tok;
|
||||
|
||||
/* A narrower layout of the trunk's attention cache under kv_dtype RAD_F8E4M3, from
|
||||
* --kv-cache-dtype fp8_v4 or k6_v4: a RAD_KVQ_* (below). The engine sets it only for a plugin
|
||||
* whose probe has the layout's bit in RadArchProbe::kv_quant_ok and refuses the flag
|
||||
* otherwise, so no plugin sees it that would store plain E4M3 instead. A drafter's cache stays
|
||||
* E4M3.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int kv_quant;
|
||||
/* ---- appended in ABI 30 (KV streaming) */
|
||||
/* --kv-resident in tokens, 0 when nothing streams: the ring a streamed group carves is this in
|
||||
* whole blocks, raised to the engine's floors and clamped to the context. A plugin states it as
|
||||
* its `kv_resolve`'s ring depth. */
|
||||
int64_t kv_resident_blocks;
|
||||
/* RadArchProbe::kv_stream_ok. The streamed-only ops (`kv_store_streamed`, its folded form,
|
||||
* `kv_resolve`) are declared only when this is set and kv_resident_blocks asks for a ring;
|
||||
* otherwise rad_op_declared says no and the plugin takes its resident path. */
|
||||
int kv_stream_ok;
|
||||
|
||||
/* ---- appended in ABI 26 (fp8 prefill attention) */
|
||||
/* RAD_ATTN_FP8_* bits from --attn-prefill-fp8: the attention products the deployment accepts
|
||||
* in e4m3 rather than exactly. 0 (the zero-initialised default) is exact. A plugin passes a
|
||||
* nonzero value on as `attn_paged`'s `prefill_fp8` (docs/OPS.md) and omits the parameter at
|
||||
* 0, so an exact declare is unchanged. The engine refuses to start when no resolved kernel
|
||||
* takes it, so a plugin that ignores the field is refused rather than silently exact.
|
||||
*
|
||||
* Zero-defaulted and in the padding after kv_quant, so no other field moves and a plugin built
|
||||
* against the older struct is unchanged. */
|
||||
int attn_prefill_fp8;
|
||||
|
||||
/* ---- appended in ABI 26 (control vectors) */
|
||||
/* ---- appended in ABI 27 (control vectors) */
|
||||
/* A control vector loaded from a GGUF `controlvector` file found for this model, or null.
|
||||
*
|
||||
* The engine loads and validates it once, at bringup, and the plugin only reads it: the
|
||||
@@ -208,8 +189,117 @@ typedef struct RadBuildCtx {
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
const struct RadControlVector* cvec;
|
||||
|
||||
/* ---- appended in ABI 27 (row-split prefill attention) */
|
||||
/* 1 from --tp-attn-split rows: from the plugin's split threshold, a prefill-sized step under
|
||||
* tensor parallelism runs attention by rows, each rank all heads of its run of the step's
|
||||
* rows and an all_gather of the runs, instead of by heads. It is faster where the attention
|
||||
* dominates, costs the full-width projections on every rank, and is not bit-identical to the
|
||||
* head split. 0 (the zero-initialised default) is the head split. The engine sets it only
|
||||
* above one rank and only for a plugin whose probe sets RadArchProbe::tp_attn_rows_ok, and
|
||||
* refuses the flag otherwise.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int tp_attn_rows;
|
||||
|
||||
/* ---- appended in ABI 27 (recurrent state at f16) */
|
||||
/* RAD_F16 from --state-cache-dtype f16: the recurrent state caches (RAD_KV_LINEAR groups) are
|
||||
* stored at f16 instead of the plugin's f32, which halves the state pool, its checkpoints and
|
||||
* its traffic and changes the generated text. 0 (the zero-initialised default) is the
|
||||
* plugin's own width. The engine sets it only for a plugin whose probe has
|
||||
* RadArchProbe::state_f16_ok and refuses the flag otherwise.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
uint32_t state_dtype;
|
||||
|
||||
/* ---- appended in ABI 27 (draft coupling) */
|
||||
/* Nonzero from --draft-coupling on: a linear serial drafter samples each round's proposal from
|
||||
* its own shortlist law, or a block drafter's walk each position's (DFlash2), and declares the
|
||||
* planes and ops the coupled verify reads (abi/rad_spechub.h, docs/OPS.md `mtp_couple_propose`,
|
||||
* `dflash_couple_propose`). 0, the zero-initialised default,
|
||||
* declares the greedy drafter. A plugin that cannot couple returns RAD_E_UNSUPPORTED from
|
||||
* declare when it is set; the engine refuses a model whose program carries no coupled planes.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int draft_coupling;
|
||||
|
||||
/* ---- appended in ABI 28 (weight prefetch) */
|
||||
/* Nonzero from --weight-prefetch off: the plugin declares none of its weight prefetches, the
|
||||
* reads of a following GEMM's weight beside a collective (arch/common/rad_arch.h
|
||||
* prefetch_beside). An engine that shares its cards with another server sets it: where the
|
||||
* read goes on the second lane, the two servers hold more compute queues than a card has
|
||||
* slots, and the join from the first lane puts a queue switch into every decode step. 0, the
|
||||
* zero-initialised default, prefetches where the plugin does.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int weight_prefetch_off;
|
||||
|
||||
/* ---- appended in ABI 31 (tree verification) */
|
||||
/* Nonzero: grow the block drafter's proposals into a tree (rad_drafter_tree) where the plugin
|
||||
* can. The engine sets it where the plugin's probe said trees pay (RadArchProbe::tree_pays)
|
||||
* and the drafter decodes speculatively; 0 keeps the chain. A plugin that grows no trees
|
||||
* ignores it. 64-bit so it starts past the older
|
||||
* struct's tail padding, where a plugin built against it would read nothing.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t draft_tree;
|
||||
|
||||
/* ---- appended in ABI 32 (calibration) */
|
||||
/* --calib-dir DIR: the deployment records calibration statistics (the second moment of each
|
||||
* linear's input, GPTQ's Hessian) into DIR; null records nothing. A plugin that keeps none
|
||||
* ignores it. `calib_layer_lo`..`calib_layer_hi` (--calib-layers, hi exclusive; both 0 for
|
||||
* every layer) bound the layers recorded in one run, so a model whose statistics do not fit
|
||||
* in memory at once is recorded in several runs over the same corpus. `calib_tokens` is the
|
||||
* corpus's token count under --calib-corpus: the plugin writes its files once it has seen
|
||||
* that many rows; 0 when the deployment drives no corpus.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
const char* calib_dir;
|
||||
int32_t calib_layer_lo;
|
||||
int32_t calib_layer_hi;
|
||||
int64_t calib_tokens;
|
||||
|
||||
/* ---- appended in ABI 32 (an image generator's bounds) */
|
||||
/* --image-gen-max-pixels: the largest image an image generator makes, in pixels; and
|
||||
* --image-gen-max-refs: the reference pictures a request at most. 0: the model's own. A
|
||||
* generator sizes its per-image and conditioning buffers for them and states them in its
|
||||
* RadGeneratorDecl (max_tokens, max_refs), which the core holds requests to; one that keeps
|
||||
* fixed buffers ignores them, and the core says so at startup. */
|
||||
int64_t gen_max_pixels;
|
||||
int64_t gen_max_refs;
|
||||
|
||||
/* ---- appended in ABI 37 (where a routed expert may live) */
|
||||
/* --weights-disk-tier: nonzero when weights may stay in the container. An expert read from the
|
||||
* drive has to be stored whole, so a plugin that can lay its routed experts out either way
|
||||
* keeps them whole for this; 0 leaves it free to split them across the ranks by width. */
|
||||
int expert_file_tier;
|
||||
|
||||
/* ---- appended in ABI 38 (several engines in one process) */
|
||||
/* The first of this engine's slots. Each engine in the process holds a contiguous block of
|
||||
* slots, one per rank, so an instance's slot, `slot_base + rank` (rad_build_slot), is unique
|
||||
* among the ranks of every engine alive, where `rank` is unique only within one engine. A
|
||||
* plugin keeps per-instance state (handles, geometry, its step's view of the model) indexed by
|
||||
* the slot, and reads it back in step() with rad_slot(). Zero, the default, makes the slot the
|
||||
* rank: one engine in a process, or a test driving a plugin alone. Two engines may serve the
|
||||
* same plugin at once only when it says so (rad_arch_multi_instance). */
|
||||
int slot_base;
|
||||
|
||||
/* ---- appended in ABI 42 (the plain block norm) */
|
||||
/* Nonzero: where no reader of a block norm's output takes its E4M3 code pair (every reader a
|
||||
* 4-bit or plain bf16 projection, which reads the bf16 plane), the plugin may run the norm as
|
||||
* `add` (the residual stored first, as `rmsnorm_quant_fp8` stores it) then `rmsnorm`: the same
|
||||
* bf16 values, without codes nobody reads. The engine sets it on the SYCL backend, whose
|
||||
* quantising norm is bound by libref's ordered sum of squares while its `rmsnorm` is a fast
|
||||
* row (docs/SYCL_PROGRESS.md); 0 elsewhere, so other backends declare what they did. */
|
||||
int plain_norm;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* The most instances (engine ranks) one process holds at once; every slot is below it. */
|
||||
#define RAD_MAX_SLOTS 32
|
||||
|
||||
/* The declaring instance's slot (see RadBuildCtx::slot_base). */
|
||||
static inline int rad_build_slot(const RadBuildCtx* c) { return c->slot_base + c->rank; }
|
||||
|
||||
/* ================================================================== control vectors */
|
||||
/* A direction per layer, in the shape llama.cpp's `--cvec-mode project` applies it:
|
||||
*
|
||||
@@ -396,6 +486,10 @@ typedef struct RadKVGroupDecl {
|
||||
rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, const RadKVGroupDecl* d);
|
||||
/* Valid only after the op that reads this group has been declared. 0 before that. */
|
||||
int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g);
|
||||
/* Bytes one block of one layer of a paged group occupies: its pool slot's pitch and its host
|
||||
* mirror row's. 0 for a group that is not paged, or before the block size is known. Additive
|
||||
* export. */
|
||||
int64_t rad_kv_layer_bytes(RadBuilder* b, rad_kvgroup g);
|
||||
|
||||
/* Bind a layer to a group, so the block manager knows how many state instances a sequence owns. */
|
||||
int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g);
|
||||
@@ -446,6 +540,17 @@ int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
|
||||
* A no-op for a PERSIST or DERIVED buffer, which is live everywhere already. */
|
||||
int rad_buf_concurrent(RadBuilder* b, rad_buf buf);
|
||||
|
||||
/* ---- appended in ABI 27 (the second lane's window) */
|
||||
/* The second lane's window: every op the architecture issues on lane 1 is declared between
|
||||
* rad_lane1_window_begin and rad_lane1_window_end. With a window a rad_buf_concurrent buffer is live
|
||||
* over the window and its own declared uses instead of the whole program, so buffers used only
|
||||
* outside the window (a drafter's, the heads') can share its bytes. The runtime holds the
|
||||
* architecture to it: an op issued on lane 1 outside the window fails the step by name, and an op
|
||||
* issued on lane 0 outside the window joins lane 1 first when lane 1 has work pending. Optional, one
|
||||
* window a program; call both at declare, in order. */
|
||||
int rad_lane1_window_begin(RadBuilder* b);
|
||||
int rad_lane1_window_end(RadBuilder* b);
|
||||
|
||||
/* An uneven shard: this rank's slice of a RAD_SHARD_ROW or RAD_SHARD_COL weight's split dimension
|
||||
* is [lo, hi) rather than an even 1/tp. Rows of each stacked row part for ROW, columns for COL, in
|
||||
* the container's unsharded units. The declared extent must already be `hi - lo` (per row part,
|
||||
@@ -483,9 +588,16 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g);
|
||||
* rank computes whole, an indexer's key cache every rank pools into); the engine moves bytes and
|
||||
* cannot know. RADIANCE_DEBUG_TIER_VERIFY checks the claim: each follower hashes what it would
|
||||
* have written and the leader compares. Paged groups only, and never a group this rank declared
|
||||
* zero. No effect at one rank. Additive export; RAD_ABI_VERSION does not move. */
|
||||
* zero. No effect at one rank, and none on a group that streams, whose host mirror is its tier.
|
||||
* Additive export. */
|
||||
int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g);
|
||||
|
||||
/* The group is read over its whole history every decode step (an indexer's block keys), so it
|
||||
* cannot stream. While a sibling group streams, its carve holds every sequence's full context
|
||||
* rather than the split's share, as the sibling's host mirror holds --max-num-seqs sequences.
|
||||
* Additive export. */
|
||||
int rad_kv_group_dense_read(RadBuilder* b, rad_kvgroup g);
|
||||
|
||||
#define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \
|
||||
(int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf))
|
||||
|
||||
@@ -522,7 +634,10 @@ typedef struct RadNameMap {
|
||||
|
||||
/* RAD_MAP_ROWS only: piece i is rows [src_index[i], src_index[i] + src_rows[i]) of the 2-D (or
|
||||
* higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. RAD_MAP_COLS: columns
|
||||
* [src_index[0], src_index[0] + src_rows[0]) of src[0]'s last dimension. */
|
||||
* [src_index[0], src_index[0] + src_rows[0]) of src[0]'s last dimension. RAD_MAP_TRANSPOSE with
|
||||
* src_index[0] >= 0: rows [src_index[0] * src_rows[0], (src_index[0] + 1) * src_rows[0]) when
|
||||
* src[0] is rank 2 and src_rows[0] > 0 (a stack flattened over rows); otherwise src_index[0] is
|
||||
* the dim-0 sub-tensor of a higher-rank stack. */
|
||||
int64_t src_rows[8];
|
||||
} RadNameMap;
|
||||
|
||||
@@ -549,7 +664,9 @@ typedef struct RadNameMap {
|
||||
* columns it is fed.
|
||||
*
|
||||
* RAD_MAP_TRANSPOSE swaps the last two dimensions of src[0] in each leading slice, [.., a, b] to
|
||||
* [.., b, a]: a linear a checkpoint keeps as (in, out), where the GEMMs read (out, in).
|
||||
* [.., b, a]: a linear a checkpoint keeps as (in, out), where the GEMMs read (out, in). With
|
||||
* src_index[0], it first takes one expert's sub-tensor (see src_rows): a stacked expert table kept
|
||||
* [n_expert, in, out] or flattened [n_expert * in, out].
|
||||
*
|
||||
* RAD_MAP_EMA is an exponential-moving-average codebook as EnCodec-style quantisers keep it: src[0]
|
||||
* the embedding sums [bins, ...], src[1] the cluster usage [bins], and the codebook is each row
|
||||
@@ -581,6 +698,17 @@ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
|
||||
* embedding-only or encoder-only plugin declares none. */
|
||||
int rad_declare_logits(RadBuilder* b, rad_buf logits);
|
||||
|
||||
/* Scored steps (RadBatch::score_only). A plugin whose lm_head is the bf16 table `table`
|
||||
* ([n_vocab, n_embd], e.g. a tied embedding, whatever encoding the head itself is read at) and
|
||||
* whose final-normed rows land in `hidden` ([rows, n_embd] bf16, row k the step's k-th sampled row,
|
||||
* as the lm_head reads them) declares both here. On a step where every sampled row is a scored row
|
||||
* the core sets RadBatch::score_only, the plugin issues everything but the lm_head, and the core
|
||||
* reads the hidden rows and the candidates' table rows back and takes the dot products on the host
|
||||
* in f64: the logits a scored request returns, at no head read on the card (half a gigabyte a step
|
||||
* at a 128K bf16 vocabulary). Optional; one rank only (the core ignores it at --tp > 1).
|
||||
* Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table);
|
||||
|
||||
/* Which buffer holds this step's pooled vectors, what an embedding model returns instead of
|
||||
* logits. Row s is sequence s's whole input pooled into one vector, with whatever pooling the
|
||||
* model was trained with (a mean, the last token, a CLS row). The core reads rows [0, n_seq) back
|
||||
@@ -598,6 +726,11 @@ int rad_declare_logits(RadBuilder* b, rad_buf logits);
|
||||
* this or logits, never both. */
|
||||
int rad_declare_pooled(RadBuilder* b, rad_buf pooled);
|
||||
|
||||
/* The most integer words one request may hand the plugin (RadBatch::plugin_words), 0 for none.
|
||||
* The engine stages that many a sequence in the step batch and refuses a longer request before
|
||||
* it is admitted, so the plugin reads its words at the size it declared. Additive export. */
|
||||
int rad_declare_plugin_words(RadBuilder* b, int64_t max_words);
|
||||
|
||||
|
||||
/* ================================================================== the drafter */
|
||||
/* The plugin's draft head. The core drives the extra passes, and only the plugin knows what it
|
||||
@@ -626,7 +759,8 @@ typedef struct RadDrafterDecl {
|
||||
|
||||
/* Where a pass leaves its proposal. 0 = the sampler's token buffer. */
|
||||
rad_buf proposal;
|
||||
int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1 */
|
||||
int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1, and for a BLOCK
|
||||
* drafter `depth` (less is refused) */
|
||||
|
||||
/* BLOCK only. `mask_token` is the id every unfilled block position embeds; a block drafter
|
||||
* without one cannot run. `window` is the drafter's own sliding window over its own cache, 0
|
||||
@@ -678,6 +812,42 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
|
||||
* checkpoint was trained with is the plugin's to know. */
|
||||
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
|
||||
|
||||
/* A block drafter whose one pass proposes a tree rather than a chain. Called once, after
|
||||
* rad_declare_drafter. `parents` is an i32 buffer at the proposal's pitch: row i's j-th entry is
|
||||
* the parent of the proposal's j-th token as a node index, 0 for the token the verify starts from
|
||||
* (the bonus token) and j' + 1 for the proposal's j'-th token, with every parent before its child.
|
||||
* Additive export; RAD_ABI_VERSION does not move.
|
||||
*
|
||||
* Each verify then runs the proposal as a tree in the same rows: node j at row j, rotated at the
|
||||
* committed end + its depth, its K and V stored at the committed end + j, and every trunk step
|
||||
* carries RadBatch::spec_parent, which the plugin hands its attention so a row sees, inside its
|
||||
* own block, only its ancestors. The acceptance follows the deepest root path the target agrees
|
||||
* with; the core then moves that path's K and V into place in every paged group. A proposal from
|
||||
* prompt lookup is verified as the chain-shaped tree.
|
||||
*
|
||||
* Requirements on the plugin: the trunk's attention honours spec_parent on every decode row; the
|
||||
* drafter's context pass stores K and V through the slot mapping only (it is staged per node, the
|
||||
* rejected ones at slot -1); and the step is issued ahead, behind which the block driver queues
|
||||
* the drafter's passes (the KL mode drafts nothing, so trees do not apply there). */
|
||||
int rad_drafter_tree(RadBuilder* b, rad_buf parents);
|
||||
|
||||
/* The model's routing counts live in `table`: an i32 RAD_BUF_PERSIST device buffer of at least
|
||||
* [layers, n_expert], one row per layer that reports (rad_route_report's `layer`, so a head past
|
||||
* the trunk counts) and n_expert the model's expert count. Each layer's router writes its counts
|
||||
* into its own row and the report names that row as RadRouting::expert_count; the core takes it
|
||||
* in place and copies the pass's rows to the host once, at the end of the pass. Without a table
|
||||
* the core keeps the rows itself and a report costs one copy dispatch per routed layer on the
|
||||
* compute stream, since a plugin cannot bind the core's rows as operands of a recorded pass. A
|
||||
* report naming any other buffer is still copied, into the layer's row of the table.
|
||||
*
|
||||
* A row per layer also means a consumer that reads a layer's counts later in stream order (the
|
||||
* file stager, at the layer's first expert op) reads that layer's, which one buffer shared by
|
||||
* every layer does not guarantee once a later layer's router has run.
|
||||
*
|
||||
* Called at most once. The row count is checked when a context binds, where the reporting layers
|
||||
* are known. Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_route_table(RadBuilder* b, rad_buf table);
|
||||
|
||||
/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on
|
||||
* the AQL backend only, which keeps a completion counter per queue, where the model's plugin
|
||||
* measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
|
||||
@@ -686,6 +856,20 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
|
||||
* that decision. Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_chain_on(void);
|
||||
|
||||
/* A block drafter that also serves a shorter block: the plugin declared its query pass at `block`
|
||||
* rows a sequence as well as at RadDrafterDecl::block, with the same anchor convention, so the
|
||||
* core may stage a step's block at either. The short block proposes
|
||||
* `block - (RadDrafterDecl::block - depth)` tokens; a tree drafter's (rad_drafter_tree, declared
|
||||
* first) a tree of its own over the shorter pass, at most `block - 1` nodes, which needs only that
|
||||
* the short block be 2 rows or more. Called once, after rad_declare_drafter.
|
||||
*
|
||||
* The block is proposed whole, so its length is paid for by every drafting sequence whatever each
|
||||
* verifies: at one sequence a long block's extra drafts pay, at many its rows and its weaker first
|
||||
* positions cost more than they bring. The core picks per step (--draft-short-from; by default
|
||||
* a tree's from two decoding sequences on, a chain's never). */
|
||||
/* ---- appended in ABI 27 (a block drafter's short block) */
|
||||
int rad_drafter_short_block(RadBuilder* b, int64_t block);
|
||||
|
||||
/* ================================================================== the encoder */
|
||||
/* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and
|
||||
* reads its result, so the plugin declares it. A plugin that declares none serves text only, and
|
||||
@@ -722,6 +906,13 @@ typedef struct RadEncoderDecl {
|
||||
* position tables or kernels are per geometry; the core ends a pass where the grid changes.
|
||||
* 0 packs segments of any grid into a pass. */
|
||||
int32_t one_grid;
|
||||
|
||||
/* ---- appended in ABI 32 (runs the language model reads both ways) */
|
||||
/* 1: the language model attends the placeholders of one picture or video frame to each other
|
||||
* both ways (Gemma 4's use_bidirectional_attention "vision"), text before and after them
|
||||
* causally. The core then ends no prefill chunk inside such a run and states each trunk pass's
|
||||
* runs (RadBatch::n_bidi). 0 for an audio encoder. */
|
||||
int32_t bidirectional;
|
||||
} RadEncoderDecl;
|
||||
|
||||
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
|
||||
@@ -997,7 +1188,8 @@ typedef struct RadAudioGenDecl {
|
||||
/* The prompt, as text the core tokenises: `{instructions}` is replaced by the request's
|
||||
* instructions (a piece's description, a voice's) and `{input}` by its input text (lyrics, the
|
||||
* words to speak), each first rewritten by the plugin's rad_arch_text_prepare when it exports
|
||||
* one. Special tokens are spelled as text. */
|
||||
* one. Special tokens are spelled as text. NULL for a model that takes no instructions, which
|
||||
* then declares `tmpl_plain` and has a request's instructions refused. */
|
||||
const char* tmpl;
|
||||
/* The unconditional branch is the conditional prompt with every token but the first
|
||||
* `neg_keep_head` and the last `neg_keep_tail` replaced by `neg_token`, so the two branches
|
||||
@@ -1058,6 +1250,45 @@ typedef struct RadAudioGenDecl {
|
||||
* latent: `lat_num` = `lat_den` = 1, `samples_per_latent` samples a frame. */
|
||||
int64_t voc_chunk;
|
||||
int64_t voc_context;
|
||||
|
||||
/* ---- appended in ABI 27 (one-branch speech over a hybrid model, references) */
|
||||
/* Sequences a request runs: 0 or 2, the conditional and unconditional branches above; 1, the
|
||||
* conditional one alone, for a model without guidance (no unconditional prompt is rendered,
|
||||
* a request's guidance must be 1, and every per-entry array of a PROMPT or FRAME pass has one
|
||||
* entry a lane, its `slot` the lane itself). The KV, the prompt's rows and a frame's rows then
|
||||
* cost half. */
|
||||
int32_t branches;
|
||||
/* Nonzero: the `{input}` slot is tokenised with its special tokens, which the template's own
|
||||
* text always is, so a caller can write the model's speaker tags. The plugin's
|
||||
* rad_arch_text_prepare then refuses the control tokens a caller must not write. */
|
||||
int32_t input_special;
|
||||
/* References (voice cloning): with `tmpl_ref`, a request may carry up to `ref_max` of them,
|
||||
* each a transcript and a clip of the voice saying it, which the plugin encodes into frames
|
||||
* in the request's PROMPT pass (whole prompts only: `prompt_whole`). `tmpl_ref` is the prompt
|
||||
* of a request with references, `{references}` each of them rendered from `ref_item` in turn
|
||||
* and `{input}` as in `tmpl_plain`. `ref_item` is one reference: `{index}` its number from 1,
|
||||
* `{text}` its transcript (rewritten by rad_arch_text_prepare as RAD_TEXT_REFERENCE) and
|
||||
* `{audio}` its frames, one prompt row each (RadAudioGenBatch::ref_frame); the text before
|
||||
* `{audio}` is tokenised as one segment with its special tokens (the transcript's own, which
|
||||
* prepare() has limited to those a caller may write), and so is the text after it. A clip is
|
||||
* mono f32 in [-1, 1] at `ref_rate`, right-padded with zeros to a whole number of `ref_hop`
|
||||
* samples, each `ref_hop` samples one frame; a request's clips hold at most `ref_max_samples`
|
||||
* samples together. With two branches, references require default_cfg 1 and a plain
|
||||
* neg_tmpl: guidance 1 repeats the conditional prompt and frame map in both branches.
|
||||
* Reference direction is opt-in through the templates appended below. NULL `tmpl_ref`:
|
||||
* references are refused. */
|
||||
const char* tmpl_ref;
|
||||
const char* ref_item;
|
||||
int64_t ref_rate;
|
||||
int64_t ref_hop;
|
||||
int64_t ref_max_samples;
|
||||
int32_t ref_max;
|
||||
/* ABI 40: reference-plus-instructions uses tmpl_ref_instruct ({references},
|
||||
* {instructions}, {input} once each). Its guidance baseline is neg_tmpl_ref
|
||||
* ({references}, {input}, no instructions). Both branches retain the same clips;
|
||||
* their text lengths and reference-frame maps may differ. NULL: direction refused. */
|
||||
const char* tmpl_ref_instruct;
|
||||
const char* neg_tmpl_ref;
|
||||
} RadAudioGenDecl;
|
||||
|
||||
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
|
||||
@@ -1120,9 +1351,27 @@ int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
|
||||
* pass carries the geometry its latent has at that point: a step before the VUPSCALE pass is at
|
||||
* W' x H'. The schedule is the request's own, whatever size each evaluation runs at.
|
||||
*
|
||||
* Reference conditioning, for a plugin with the VAE encoders (`max_enc_side`, `max_enc_samples`,
|
||||
* below): before the prompt pass each of a request's reference media and keyframes is encoded,
|
||||
* one a pass, into the lane, where the steps read it. Nothing an encode makes is read back.
|
||||
*
|
||||
* RAD_GEN_PASS_VENCODE one picture or video, its frames in `enc_pixels` (RadVideoGenBatch),
|
||||
* through the video VAE's encoder.
|
||||
* RAD_GEN_PASS_AENCODE one soundtrack, its samples in `enc_samples`, through the audio VAE's
|
||||
* encoder.
|
||||
*
|
||||
* `enc_kind` (RAD_ENC_*, rad_runtime.h) and `enc_slot`, the media's 1-based number within its kind,
|
||||
* say where the latents go. A latent-upscaled request's keyframes, pinned on the grid its steps
|
||||
* run on, are encoded at W' x H' before the prompt pass, then again at W x H into the same slots
|
||||
* after the VUPSCALE pass and before the first evaluation at W x H. References, on their own grid,
|
||||
* are encoded once. The media's shape is the plugin's to accept: rad_arch_encode_geom
|
||||
* (below) refuses what the encoders cannot take, and the step's packed sequence with the encoded
|
||||
* media in it is the plugin's rad_arch_video_pack.
|
||||
*
|
||||
* A program declares exactly one of this, the other generators, logits or pooled vectors. */
|
||||
enum { RAD_GEN_PASS_VCOND = 8, RAD_GEN_PASS_VSTEP = 9, RAD_GEN_PASS_ADECODE = 10,
|
||||
RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12 };
|
||||
RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12,
|
||||
RAD_GEN_PASS_VENCODE = 13, RAD_GEN_PASS_AENCODE = 14 };
|
||||
|
||||
typedef struct RadVideoGenDecl {
|
||||
const char* name; /* "minimax-h3" -- the served model id and messages */
|
||||
@@ -1240,10 +1489,105 @@ typedef struct RadVideoGenDecl {
|
||||
* Null: one decoder. */
|
||||
const char* decoders;
|
||||
const int64_t* decoder_max_area;
|
||||
|
||||
/* ---- appended in ABI 31 (MiniMax-H3 reference conditioning, above) */
|
||||
/* The reference media a request may carry: pictures, videos (each with an optional soundtrack
|
||||
* of its own) and standalone soundtracks. 0 for none of a kind; a plugin that declares any
|
||||
* exports rad_arch_video_pack. */
|
||||
int64_t max_ref_images, max_ref_videos, max_ref_audios;
|
||||
/* What one encode pass carries: a video's frames after rad_arch_encode_geom pads them to whole
|
||||
* clips, a frame's longer side and a soundtrack's samples. `max_enc_side` 0: no video encoder,
|
||||
* `max_enc_samples` 0: no audio encoder. A picture's sides are multiples of `enc_ratio`. */
|
||||
int64_t max_enc_frames, max_enc_side, max_enc_samples;
|
||||
int32_t enc_ratio;
|
||||
/* The distinct modulations a step's groups may read (rad_arch_video_pack's `mod`, the highest
|
||||
* cell + 1); a request needing more is refused at submit. 0: no limit. */
|
||||
int32_t max_mod_cells;
|
||||
} RadVideoGenDecl;
|
||||
|
||||
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d);
|
||||
|
||||
/* ================================================================== the shape generator */
|
||||
/* A program that makes a 3-D shape from one picture: an image encoder reads the picture, a
|
||||
* denoiser steps a set of latent rows by flow matching, guided against an unconditioned branch,
|
||||
* and a decoder turns the latent into an occupancy field that the core samples at points of its
|
||||
* choosing and meshes. The core drives the passes (RadBatch::gen, RadShapeGenBatch), one request
|
||||
* a pass:
|
||||
*
|
||||
* RAD_GEN_PASS_SCOND the request's picture through the image encoder into the request's
|
||||
* lane: what the denoiser reads of it at every step, for both branches
|
||||
* (the picture's and the unconditioned one).
|
||||
* RAD_GEN_PASS_SSTEP one denoising step of one lane over both branches, `step_rows` rows:
|
||||
* each branch's conditioning and latent, laid out as the plugin likes, the
|
||||
* latents two entries of `latent_rows` (the conditioned first) for the
|
||||
* image generator's sampler ops. The first step draws the lane's noise.
|
||||
* RAD_GEN_PASS_SLATENT the lane's final latent through the decoder's network, into the lane:
|
||||
* what every query pass of the request reads. Runs once, after the last
|
||||
* step.
|
||||
* RAD_GEN_PASS_SQUERY the field at `n_query` points (RadShapeGenBatch::query, at most
|
||||
* `max_query`), one f32 a point in `field_out`, which the core reads
|
||||
* back.
|
||||
*
|
||||
* The picture. The core decodes it with its alpha (opaque without one) and prepares it as
|
||||
* Hunyuan3D-2's ImageProcessorV2 and image encoder do: the alpha's bounding box (its last row and
|
||||
* column left out, as the reference's slice leaves them) scaled with OpenCV's INTER_AREA to
|
||||
* (1 - border_ratio) of the longer side of the square that holds the picture, centred on it and
|
||||
* flattened onto white; that square resized to `canvas` x `canvas` with INTER_CUBIC; then as 0..1
|
||||
* values bilinearly resized to `enc_size` x `enc_size` (half-pixel centres, torchvision's), each
|
||||
* channel normalised by `pix_mean` and `pix_std`, and cut into (enc_size / enc_patch)^2 patches of
|
||||
* enc_patch x enc_patch pixels, row-major, each patch's values channel-major then row-major (a
|
||||
* convolution's weight order). An SCOND pass carries those patches.
|
||||
*
|
||||
* The sampler: a request's `steps` are sigma grid points, sigma_i = i / (steps - 1) for i in
|
||||
* [0, steps), numpy's linspace(0, 1) taken to f32; the latent starts as noise at sigma 0 and an
|
||||
* evaluation at each sigma but the last steps it to the next (the reference evaluates at the
|
||||
* last too, against itself, a step of zero). The model's timestep is sigma, the guided velocity
|
||||
* neg + cfg (pos - neg), and the step x + (sigma_next - sigma) v.
|
||||
*
|
||||
* The field: the decoder's logit at a point, inside the shape above `level`. The core samples the
|
||||
* cube [-bounds, bounds]^3 on a grid of `resolution` cells a side ((resolution + 1)^3 points,
|
||||
* numpy's linspace in f32 along each axis), coarse to fine as FlashVDM's hierarchical decoding
|
||||
* does: the whole grid at the coarsest level (resolution halved while it stays at least 63), then
|
||||
* at each finer level only the points near where the coarser one crosses `level` or is within
|
||||
* 0.95 of it. The surface is marching cubes over the finest grid, a vertex at grid index g placed
|
||||
* at g 2 bounds / (resolution + 1) - bounds, as the reference places it.
|
||||
*
|
||||
* A program declares exactly one of this, the other generators, logits or pooled vectors. */
|
||||
enum { RAD_GEN_PASS_SCOND = 15, RAD_GEN_PASS_SSTEP = 16, RAD_GEN_PASS_SLATENT = 17,
|
||||
RAD_GEN_PASS_SQUERY = 18 };
|
||||
|
||||
typedef struct RadShapeGenDecl {
|
||||
const char* name; /* "hunyuan3d-2" -- the served model id and messages */
|
||||
|
||||
/* The picture (above). */
|
||||
int64_t canvas;
|
||||
double border_ratio;
|
||||
int64_t enc_size, enc_patch;
|
||||
double pix_mean[3], pix_std[3];
|
||||
|
||||
/* The latent: `latent_rows` rows of `latent_channels` a branch; a step's rows, both branches
|
||||
* with their conditioning. */
|
||||
int64_t latent_rows, latent_channels, step_rows;
|
||||
|
||||
/* The sampler (above) and the guidance a request that names none runs at. */
|
||||
int64_t default_steps, max_steps;
|
||||
double default_guidance;
|
||||
|
||||
/* The field (above): the cube's half side, the iso value, and the grid's resolution a request
|
||||
* that names none is sampled at, with the range a request may name. */
|
||||
double bounds;
|
||||
double level;
|
||||
int64_t default_resolution, min_resolution, max_resolution;
|
||||
|
||||
/* `max_lanes` requests may hold state at once. `field_out` is a device f32 buffer of at least
|
||||
* `max_query` elements. */
|
||||
int64_t max_lanes;
|
||||
int64_t max_query;
|
||||
rad_buf field_out;
|
||||
} RadShapeGenDecl;
|
||||
|
||||
int rad_declare_shape_generator(RadBuilder* b, const RadShapeGenDecl* d);
|
||||
|
||||
/* ================================================================== diagnostics */
|
||||
/* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */
|
||||
void rad_note(RadBuilder* b, const char* fmt, ...);
|
||||
@@ -1272,6 +1616,13 @@ const char* rad_arch_quant(void);
|
||||
* move. */
|
||||
int rad_arch_serves_imports(void);
|
||||
|
||||
/* Nonzero when every piece of per-instance state the plugin keeps is indexed by
|
||||
* rad_build_slot() / rad_slot(), so several engines in one process may run it at once
|
||||
* (docs/MULTIMODEL.md §3.3). Optional: absent or zero, the core runs the plugin for one engine at
|
||||
* a time and refuses a second engine on it by name. arch/common/rad_arch.h writes it with
|
||||
* RAD_ARCH_MULTI_INSTANCE(). */
|
||||
int rad_arch_multi_instance(void);
|
||||
|
||||
/* What the plugin can say before it declares anything. Optional: a plugin that does not export
|
||||
* it answers zero to everything, each field's default.
|
||||
*
|
||||
@@ -1331,21 +1682,60 @@ typedef struct RadArchProbe {
|
||||
* `gen_rows` (its largest pass: a step's packed sequence at the largest size and length). It
|
||||
* keeps no KV. */
|
||||
int32_t gen_video;
|
||||
/* The RadBuildCtx::kv_quant layouts the plugin serves for this model, bit 1 << RAD_KVQ_*:
|
||||
* libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at
|
||||
* startup with the plugin named. */
|
||||
int32_t kv_quant_ok;
|
||||
/* Nonzero when the plugin serves an E4M3 cache for this model (--kv-cache-dtype fp8,
|
||||
* RadBuildCtx::kv_dtype RAD_F8E4M3): GLM-5.3's latent attention. The engine refuses the flag
|
||||
* for a plugin that leaves it zero, naming the int8 cache every paged attention serves. */
|
||||
int32_t kv_fp8_ok;
|
||||
|
||||
/* ---- appended in ABI 26 (chained launches, control vectors) */
|
||||
/* Nonzero when this plugin measured its speculative step faster with chained launches
|
||||
* (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the
|
||||
* queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core
|
||||
* then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin
|
||||
* that never measured them asks for nothing. */
|
||||
/* How this plugin measured chained launches (RadKernelChainFn: a dependent kernel waits in its
|
||||
* own prologue rather than behind the queue's barrier bit), a RAD_CHAIN_*. SPEC: its
|
||||
* speculative step is faster with them, and the core takes them on the AQL backend while a
|
||||
* drafter decodes speculatively. ALWAYS: its plain decode is faster too, and the core takes
|
||||
* them with or without a drafter. Zero keeps them off: some models' plain decode measured
|
||||
* slower chained, and a plugin that never measured them asks for nothing. */
|
||||
int32_t chain_pays;
|
||||
/* ---- appended in ABI 30 (KV streaming) */
|
||||
/* Nonzero when the architecture can stream a KV group between host memory and a VRAM ring: its
|
||||
* attention is sparse and block-addressed and it declares a streamed store and `kv_resolve`.
|
||||
* --kv-resident on an architecture that says 0 is turned off at startup, and nothing streamed
|
||||
* is declared (RadBuildCtx::kv_stream_ok). */
|
||||
int32_t kv_stream_ok;
|
||||
/* Nonzero when the plugin applies RadBuildCtx::cvec for this model. --control-vector is
|
||||
* refused at startup with the plugin named when this is 0. */
|
||||
int32_t control_vector_ok;
|
||||
|
||||
/* ---- appended in ABI 27 (row-split prefill attention) */
|
||||
/* Nonzero when the plugin serves RadBuildCtx::tp_attn_rows for this model. --tp-attn-split
|
||||
* rows is refused at startup with the plugin named when this is 0. */
|
||||
int32_t tp_attn_rows_ok;
|
||||
|
||||
/* ---- appended in ABI 27 (recurrent state at f16) */
|
||||
/* Nonzero when the plugin declares its recurrent state at f16 under RadBuildCtx::state_dtype
|
||||
* and its kernels read that width. --state-cache-dtype f16 is refused at startup with the
|
||||
* plugin named when this is 0. */
|
||||
int32_t state_f16_ok;
|
||||
|
||||
/* ---- appended in ABI 31 (tree verification) */
|
||||
/* Nonzero when this plugin can grow its block drafter's proposals into a tree
|
||||
* (rad_drafter_tree) and measured its speculative step faster with one. The core then asks for
|
||||
* a tree (RadBuildCtx::draft_tree) wherever that drafter decodes speculatively. Zero keeps the
|
||||
* chain: a plugin that never measured trees asks for none. 64-bit so it starts past the older
|
||||
* struct's tail padding, which a plugin built against it may copy over. */
|
||||
int64_t tree_pays;
|
||||
|
||||
/* ---- appended in ABI 32 (inputs: an image generator's bounds) */
|
||||
/* Set by the core before the call: --image-gen-max-pixels and --image-gen-max-refs, as
|
||||
* RadBuildCtx carries them to declare (0: the model's own). A generator's gen_rows and
|
||||
* gen_patches answer for them. */
|
||||
int64_t gen_max_pixels;
|
||||
int64_t gen_max_refs;
|
||||
|
||||
/* ---- appended in ABI 33 (the shape generator) */
|
||||
/* Nonzero for a shape generator, which the engine sizes as it does a video generator from
|
||||
* `gen_rows` (its largest pass: a step's two branches, or a query pass's points). It keeps no
|
||||
* KV. */
|
||||
int32_t gen_shape;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
@@ -1363,6 +1753,12 @@ int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
* arg_prefix ARG arg_name_suffix arg_value_prefix VALUE arg_value_suffix ...
|
||||
* call_end [call_close]
|
||||
*
|
||||
* An argument's tag may also say its value's type, with arg_json_value_prefix written in place of
|
||||
* arg_value_prefix before a JSON value. DeepSeek-V4.1's DSML, inside a section
|
||||
* "<|DSML| calls>" / "</|DSML| calls>", is "<|DSML| invoke name=\"" / "\">\n" / "</|DSML| invoke>",
|
||||
* arguments "<|DSML| parameter name=\"" / "\"" / " string=\"true\">" (or
|
||||
* " string=\"false\">") / "</|DSML| parameter>".
|
||||
*
|
||||
* Qwen3.8, for example, is "<think>\n" / "\n</think>\n\n", calls "<tool_call>\n" / "</tool_call>",
|
||||
* "<function=" / ">\n" / "</function>\n", arguments "<parameter=" / ">\n" / "" / "</parameter>\n".
|
||||
* Whitespace at the ends of a tag is optional when matching. Every string is NUL-terminated
|
||||
@@ -1412,14 +1808,13 @@ typedef struct RadChatFormat {
|
||||
const char* reasoning_open; /* "" when the model does not reason */
|
||||
const char* reasoning_close;
|
||||
/* Literals that end a reasoning block the model forgot to close, when a call starts there.
|
||||
* Each must be the call opener: `call_open`, or `name_prefix` when there is no call_open. */
|
||||
* Each must be a call opener (`call_open`, or `name_prefix` without one) or section_open. */
|
||||
const char* const* reasoning_breaks;
|
||||
uint32_t n_reasoning_breaks;
|
||||
uint32_t reasoning_in_prompt; /* RAD_CHAT_THINK_* */
|
||||
|
||||
/* Around all of a turn's calls, and between two calls beyond whitespace. The parser does not
|
||||
* read these yet, so a format that sets one is refused at startup by name; they are fields so
|
||||
* supporting them later does not change the struct. */
|
||||
/* Around the complete list of calls. section_open and section_close must be set together.
|
||||
* call_separator is additional text between calls beyond whitespace; it is not supported. */
|
||||
const char* section_open;
|
||||
const char* section_close;
|
||||
const char* call_separator;
|
||||
@@ -1464,6 +1859,19 @@ typedef struct RadChatFormat {
|
||||
* calls) and is read as reasoning there too, and a reasoning_close with no block open is not
|
||||
* part of the answer. Zero: only a block the reply starts with is reasoning. */
|
||||
uint32_t reasoning_anywhere;
|
||||
|
||||
/* Tagged arguments whose tag says the value's type: written in place of arg_value_prefix,
|
||||
* this opens a JSON value, and arg_value_prefix then opens a string. The tag the reply writes
|
||||
* decides how its value is read, whatever the schema says; the grammar writes the one the
|
||||
* schema calls for. NULL: the schema alone types a value. */
|
||||
const char* arg_json_value_prefix;
|
||||
|
||||
/* A header the model writes first when it answers without reasoning, in place of
|
||||
* reasoning_open: the reply then starts with this literal, which is dropped, and the rest is
|
||||
* content. A reply that starts with anything else, or with only part of it, is read as
|
||||
* written. When the model does reason, its header after the block is reasoning_close's.
|
||||
* NULL or "": the reply starts with its content. */
|
||||
const char* content_open;
|
||||
} RadChatFormat;
|
||||
|
||||
/* Return the format, or NULL for "derive it from the chat template". Called once at startup. */
|
||||
@@ -1524,11 +1932,13 @@ const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta);
|
||||
* as given. Training data has conventions a client does not know -- section tags on lines of
|
||||
* their own and lower case, no markdown in a description -- and only the plugin knows them.
|
||||
*
|
||||
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8. Writes at most `cap` bytes, the NUL included,
|
||||
* and returns the length the whole result needs without its NUL (call again with more room when
|
||||
* it is >= cap), or a negative status for text the model cannot take. Called on HTTP threads, so
|
||||
* it keeps no state. */
|
||||
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2 };
|
||||
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8: the instructions, the input, or a
|
||||
* reference's transcript (RadAudioGenDecl::ref_item's `{text}`). Writes at most `cap` bytes, the
|
||||
* NUL included, and returns the length the whole result needs without its NUL (call again with
|
||||
* more room when it is >= cap), or a negative status for text the model cannot take, with the
|
||||
* reason in `out` (NUL-terminated within `cap`) when it has one to give the caller. Called on
|
||||
* HTTP threads, so it keeps no state. */
|
||||
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2, RAD_TEXT_REFERENCE = 3 };
|
||||
int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap);
|
||||
|
||||
/* The layout of a video generator's passes (rad_declare_video_generator), which only the model
|
||||
@@ -1548,11 +1958,40 @@ typedef struct RadVideoGeom {
|
||||
enum { RAD_VPOS_STEP = 1, RAD_VPOS_DECODE = 2 };
|
||||
int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap);
|
||||
|
||||
/* The geometry of an encode pass (RAD_GEN_PASS_VENCODE, RAD_GEN_PASS_AENCODE): the int32s the
|
||||
* driver stages verbatim in RadVideoGenBatch::enc_geom_d for the plugin's kernels. `kind` is the
|
||||
* pass; `in` is {frames or samples, height, width, channels}, 0 where unused. With `out` null it
|
||||
* returns the count, with `out` it fills out[cap]; negative for media the encoders cannot take.
|
||||
* Entry 0 of an Aencode geometry is the samples padded to the encoder's hop, entry 23 of a Vencode
|
||||
* geometry the frames padded to whole clips and entry 24 its latent frames: the driver stages the
|
||||
* media padded to those lengths. A plugin with encoders exports it. Called on any thread. */
|
||||
int64_t rad_arch_encode_geom(int32_t kind, const int64_t* in, int32_t* out, int64_t cap);
|
||||
|
||||
/* The packed sequence of a step with reference media or keyframes in: `ref_tab` is
|
||||
* RadVideoGenBatch::ref_tab. Returns the sequence's rows, the rows RAD_VPOS_STEP would position, or
|
||||
* a negative status. `seg` receives the segment boundaries (seg[0] = 0, the last the rows) and
|
||||
* `mod` the boundaries of the modulation groups, then the cell each group reads (groups that read
|
||||
* the same modulation share a cell, numbered from 0); `*n_seg` and `*n_mod` are their capacities
|
||||
* in and their counts out, and a null array asks for the count alone. `pos` receives the rotary
|
||||
* positions, f32 [3, rows], when `cap_pos` holds 3 x rows. A plugin that declares reference media
|
||||
* exports it. Called on any thread. */
|
||||
int64_t rad_arch_video_pack(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* seg,
|
||||
int32_t* n_seg, int32_t* mod, int32_t* n_mod, float* pos,
|
||||
int64_t cap_pos);
|
||||
|
||||
int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx);
|
||||
/* Forward declaration; the signature is in rad_runtime.h. */
|
||||
struct RadCtx;
|
||||
struct RadBatch;
|
||||
void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
|
||||
/* Optional. Return a stable fingerprint of actual dispatch geometry whose grid depends on live
|
||||
* per-group seqused values. `kv_used_max_h[g]` is the host maximum for batch->kv[g], and
|
||||
* rad_ctx_wgp_count(c) supplies the device's WGP count. Return 0 when exact geometry is unknown;
|
||||
* that pass runs live and is not recorded. Only prefill and mixed launches read the live maximum:
|
||||
* in a decode, verify or draft pass every launch reads the step's keyed context bound
|
||||
* (RadArgs::kv_used_max_h), so such a pass needs no geometry here and returns nonzero. */
|
||||
uint64_t rad_arch_pass_key(struct RadCtx* c, const struct RadBatch* batch,
|
||||
const int32_t* kv_used_max_h);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
/* rad_clef.h -- the words a clef request hands its head (RadBatch::plugin_words).
|
||||
*
|
||||
* clef's joint schema head (arch/common/rad_block_clef.h) reads more of a request than its
|
||||
* tokens: which prompt positions hold each question's instructions and each option's text, each
|
||||
* option's token ids (the lm_head rows it averages), and each question's type. The server lays
|
||||
* them out with the functions below, in the forms the head's kernels read (a cu_seqlens here, a
|
||||
* gather index there), and the engine carries them to the plugin as one range of int32 words.
|
||||
* Both sides include this header, so the layout is stated once.
|
||||
*
|
||||
* Plain C, like every abi/ header: the plugin is built apart from the engine.
|
||||
*/
|
||||
#ifndef RAD_CLEF_H
|
||||
#define RAD_CLEF_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* The bounds the head's buffers are declared at. A request past one is refused by the server. */
|
||||
enum {
|
||||
RAD_CLEF_MAX_QUESTIONS = 64,
|
||||
RAD_CLEF_MAX_OPTIONS = 512, /* every question's options together */
|
||||
RAD_CLEF_MAX_LEX = 8192, /* every option's tokens together */
|
||||
/* Prompt tokens. The head gathers every row of a prompt into buffers of its own, so this,
|
||||
* not the deployment's context, sizes them: at the model's own 262144 they would take
|
||||
* 4.5 GiB of the card for prompts that never pass a fifth of it. */
|
||||
RAD_CLEF_MAX_PROMPT = 32768
|
||||
};
|
||||
|
||||
/* The header: word 0 is the engine's (RadBatch::plugin_words), the rest the counts the layout is
|
||||
* computed from. */
|
||||
enum {
|
||||
RAD_CLEF_W_ROW = 0, /* the sequence's logits row this step, written by the engine */
|
||||
RAD_CLEF_W_N = 1, /* prompt tokens */
|
||||
RAD_CLEF_W_Q = 2, /* questions */
|
||||
RAD_CLEF_W_O = 3, /* options, every question together, in head order */
|
||||
RAD_CLEF_W_L = 4, /* option tokens, every option together */
|
||||
RAD_CLEF_W_S = 5, /* segments the prompt is cut into at every span's edges */
|
||||
RAD_CLEF_HDR = 8
|
||||
};
|
||||
|
||||
/* Where each array starts, in words from the range's start. Every array is int32. */
|
||||
typedef struct RadClefWords {
|
||||
int32_t n, q, o, l, s;
|
||||
int32_t seg_cu; /* [s + 1]: a partition of [0, n) with a boundary at every span's edges */
|
||||
int32_t q_seg; /* [q]: the segment holding each question's instructions */
|
||||
int32_t o_seg; /* [o]: the segment holding each option's text */
|
||||
int32_t o_q; /* [o]: each option's question */
|
||||
int32_t opt_cu; /* [q + 1]: each question's options, consecutive */
|
||||
int32_t type; /* [q]: 0 noul, 1 choice, 2 score */
|
||||
int32_t lex_cu; /* [o + 1]: each option's tokens in lex_ids, consecutive */
|
||||
int32_t lex_ids; /* [l]: the option tokens, as the prompt holds them */
|
||||
int32_t last; /* [1]: n - 1, the prompt's last position */
|
||||
int32_t cu_q; /* [2]: {0, q} */
|
||||
int32_t cu_o; /* [2]: {0, o} */
|
||||
int32_t cu_k; /* [2]: {0, n} */
|
||||
int32_t total; /* words in all */
|
||||
} RadClefWords;
|
||||
|
||||
static inline RadClefWords rad_clef_words_layout(int32_t n, int32_t q, int32_t o, int32_t l,
|
||||
int32_t s) {
|
||||
RadClefWords w;
|
||||
int32_t at = RAD_CLEF_HDR;
|
||||
w.n = n; w.q = q; w.o = o; w.l = l; w.s = s;
|
||||
w.seg_cu = at; at += s + 1;
|
||||
w.q_seg = at; at += q;
|
||||
w.o_seg = at; at += o;
|
||||
w.o_q = at; at += o;
|
||||
w.opt_cu = at; at += q + 1;
|
||||
w.type = at; at += q;
|
||||
w.lex_cu = at; at += o + 1;
|
||||
w.lex_ids = at; at += l;
|
||||
w.last = at; at += 1;
|
||||
w.cu_q = at; at += 2;
|
||||
w.cu_o = at; at += 2;
|
||||
w.cu_k = at; at += 2;
|
||||
w.total = at;
|
||||
return w;
|
||||
}
|
||||
|
||||
/* The layout a range of words carries, read off its header. */
|
||||
static inline RadClefWords rad_clef_words_read(const int32_t* words) {
|
||||
return rad_clef_words_layout(words[RAD_CLEF_W_N], words[RAD_CLEF_W_Q], words[RAD_CLEF_W_O],
|
||||
words[RAD_CLEF_W_L], words[RAD_CLEF_W_S]);
|
||||
}
|
||||
|
||||
/* The most words a request can carry within the bounds: what the head declares
|
||||
* (rad_declare_plugin_words). A span's two edges each cut the prompt, so the segments are at most
|
||||
* two a span plus one. */
|
||||
static inline int32_t rad_clef_max_words(void) {
|
||||
const int32_t spans = RAD_CLEF_MAX_QUESTIONS + RAD_CLEF_MAX_OPTIONS;
|
||||
return rad_clef_words_layout(0, RAD_CLEF_MAX_QUESTIONS, RAD_CLEF_MAX_OPTIONS,
|
||||
RAD_CLEF_MAX_LEX, 2 * spans + 1).total;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* RAD_CLEF_H */
|
||||
@@ -36,12 +36,21 @@ typedef struct RadDeviceProps {
|
||||
int64_t lds_bytes; /* per-workgroup scratch, for occupancy arithmetic only */
|
||||
int supports_p2p;
|
||||
int is_host_backend; /* 1 when there is no accelerator behind this device */
|
||||
int unified; /* 1 when device memory is host memory (integrated graphics):
|
||||
* one address space and one RAM ledger -- the device pools and
|
||||
* the pinned host pools are charged against the same bytes,
|
||||
* KV tiers collapse to resident, and a copy whose source and
|
||||
* destination are the same address is a no-op */
|
||||
} RadDeviceProps;
|
||||
|
||||
int rad_dev_count(void);
|
||||
int rad_dev_set(int device);
|
||||
int rad_dev_props(int device, RadDeviceProps* out);
|
||||
int rad_dev_enable_peer(int self, int peer);
|
||||
/* 1 when the driver reports that `self` can reach `peer`'s memory, 0 when not, negative on a
|
||||
* device error. A tool that declares a multi-rank graph sets the device.p2p fact from it, as the
|
||||
* engine does (RAD_FACT_P2P). */
|
||||
int rad_dev_peer_access(int self, int peer);
|
||||
|
||||
void* rad_dev_alloc(int64_t bytes, int kind);
|
||||
void rad_dev_free(void* p, int kind);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/* rad_laya.h -- the words a Laya request hands its plugin (RadBatch::plugin_words), and the pooled
|
||||
* row the plugin answers in.
|
||||
*
|
||||
* Laya (arch/laya) reads one sequence a question, `[CLS] <type> question: <instructions> [SEP]
|
||||
* [MASK] opt0 [MASK] opt1 ... [SEP] <state> [SEP]`, and scores each option at its [MASK]. The
|
||||
* server builds the sequence (core/server/laya.cpp) and hands the plugin what the tokens do not
|
||||
* say: the question's type, which picks the head's type embedding, and where the markers are. The
|
||||
* plugin answers in the sequence's pooled row: one logit an option, in marker order.
|
||||
*
|
||||
* Plain C, like every abi/ header: the plugin is built apart from the engine.
|
||||
*/
|
||||
#ifndef RAD_LAYA_H
|
||||
#define RAD_LAYA_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
enum {
|
||||
/* Options a question, llama.cpp's bound for laya. The pooled row holds one logit an option. */
|
||||
RAD_LAYA_MAX_OPTIONS = 255,
|
||||
RAD_LAYA_POOLED = 256
|
||||
};
|
||||
|
||||
/* The question types in the order of the head's type embedding rows (laya's QTYPES). */
|
||||
enum { RAD_LAYA_CHOICE = 0, RAD_LAYA_SCORE = 1, RAD_LAYA_NOUL = 2 };
|
||||
|
||||
/* A sequence's words. Word 0 is the engine's (RadBatch::plugin_words). */
|
||||
enum {
|
||||
RAD_LAYA_W_ROW = 0, /* written by the engine */
|
||||
RAD_LAYA_W_N = 1, /* the sequence's tokens */
|
||||
RAD_LAYA_W_TYPE = 2, /* RAD_LAYA_CHOICE, RAD_LAYA_SCORE or RAD_LAYA_NOUL */
|
||||
RAD_LAYA_W_K = 3, /* options, so markers */
|
||||
RAD_LAYA_W_MARKERS = 4, /* [k]: each option's [MASK] position in the sequence, in order */
|
||||
RAD_LAYA_MAX_WORDS = RAD_LAYA_W_MARKERS + RAD_LAYA_MAX_OPTIONS
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* RAD_LAYA_H */
|
||||
@@ -0,0 +1,323 @@
|
||||
/* rad_mtp_block.h -- BLOCK VERIFICATION of a linear MTP draft chain (--draft-verify block).
|
||||
*
|
||||
* Sun, Mendlovic, Leviathan, Aharoni, Beirami, Ro, Suresh, "Block Verification Accelerates
|
||||
* Speculative Decoding" (arXiv 2403.10444): the chain's draft tokens X_1 .. X_g are accepted or
|
||||
* rejected JOINTLY. Token-wise speculative sampling (what --draft-coupling does at each row) is
|
||||
* optimal per token; block verification is optimal for the whole block: the expected number of
|
||||
* accepted tokens is never lower and the output law is the target's, exactly.
|
||||
*
|
||||
* With P_i = the target's law after X^i (the sampler's filtered candidate softmax at verify row i,
|
||||
* i = 0 .. g-1) and Q_{i+1} = the head's law the draft X_{i+1} was sampled from (the coupled state
|
||||
* of round i + 1, the FP64 softmax of the reranked top 8):
|
||||
*
|
||||
* p_0 = 1, p_i = min(1, p_{i-1} P_{i-1}(X_i) / Q_i(X_i)) i = 1 .. g
|
||||
* S_i = sum_x max(p_i P_i(x) - Q_{i+1}(x), 0) i = 0 .. g-1
|
||||
* h_i = S_i / (S_i + 1 - p_i) (i < g), h_g = p_g
|
||||
*
|
||||
* for i = g, g-1, ..., 0: accept the block's first i tokens with probability h_i; the first
|
||||
* success is tau. (h_0 = 1: it always stops.)
|
||||
* tau = g: X_1 .. X_g are emitted and the next token is the ordinary draw from P_g.
|
||||
* tau < g: X_1 .. X_tau are emitted, then Y ~ max(p_tau P_tau - Q_{tau+1}, 0) normalised.
|
||||
*
|
||||
* Exactness is checked in tests/mtp_block_test.cpp by exact enumeration of the draft tree of a toy
|
||||
* model (the law of the emitted tokens computed in closed form, to 1e-12) and by a chi-square of the
|
||||
* real device-shared code, with a negative control (the same rule with a wrong residual).
|
||||
*
|
||||
* Y may equal X_{tau+1}; the core then takes that draft as accepted (ADV_ACCEPT: "the draft is the
|
||||
* sampler's token at this row") and reads the next row, which keeps its ordinary pick: a draw from
|
||||
* the target's law given exactly the tokens emitted so far, so the extra tokens continue the same
|
||||
* autoregressive sample. The verify op therefore writes only rows 0 .. tau of the block and leaves
|
||||
* every later row alone.
|
||||
*
|
||||
* Relation to --draft-coupling: the DRAFT half is shared (x ~ Q at temperature 1 from the head's
|
||||
* top 8, coupled states with their FP64 Q); only the verify half differs. Maximal coupling decides
|
||||
* row k from P_k and Q_{k+1} alone, so it is a per-row rule the core's token comparison walks
|
||||
* unchanged. Block verification decides row k from the rows after it (h_i for i > k), so the two
|
||||
* rules cannot be applied to the same row; `--draft-verify block` replaces the coupling's verify
|
||||
* and requires the coupled drafting (it switches it on), and it is for a LINEAR chain; Traversal
|
||||
* Verification (abi/rad_mtp_traversal.h, 2505.12398) is the walk that also covers a node with
|
||||
* several children.
|
||||
*/
|
||||
#ifndef RAD_MTP_BLOCK_H
|
||||
#define RAD_MTP_BLOCK_H
|
||||
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
#ifdef __HIPCC__
|
||||
#define RAD_BLK_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_BLK_HD
|
||||
#endif
|
||||
|
||||
#define RAD_MTP_BLOCK_MAX RAD_MTP_COUPLE_MAX_ROUNDS /* g: the chain's longest block */
|
||||
#define RAD_MTP_BLOCK_KEY_STOP 0x424c4b53544f5000ull /* the h_i uniforms, per block */
|
||||
|
||||
/* Summation structure. The device decides a block with one workgroup of RAD_MTP_BLOCK_LANES
|
||||
* threads, so every FP64 sum over a row's candidate plane is DEFINED as this fixed tree, which the
|
||||
* host reference mirrors operation for operation (FP64 addition is not associative: the tree is
|
||||
* the definition, not an approximation):
|
||||
* - plane slot j belongs to lane j % LANES; a lane adds its live slots in ascending j;
|
||||
* - the lanes are reduced inside each group of RAD_MTP_BLOCK_WAVE by the butterfly
|
||||
* a[l] = a[l] + a[l ^ d], d = 16, 8, 4, 2, 1 (every lane of a group ends with the same bits),
|
||||
* and the LANES / WAVE group sums are added as ((g0 + g1) + (g2 + g3)).
|
||||
* The exp() of a slot is the same libm / device function on both sides, as before. */
|
||||
#define RAD_MTP_BLOCK_LANES 128
|
||||
#define RAD_MTP_BLOCK_WAVE 32
|
||||
|
||||
/* One verify row's candidate plane, dense (n slots, holes id < 0 and -inf scores skipped), with
|
||||
* `valid` and `top` the scan of the whole plane (rad_mtp_block_scan makes it on the host; the
|
||||
* device reduces the same two values across its workgroup: a max and an OR are order free). */
|
||||
struct RadBlockRow {
|
||||
const int32_t* ids;
|
||||
const float* val;
|
||||
int64_t n;
|
||||
int valid;
|
||||
float top;
|
||||
};
|
||||
|
||||
/* The dense row's validity and maximum, as rad_mtp_couple_decide scans them. */
|
||||
static inline RAD_BLK_HD void rad_mtp_block_scan(RadBlockRow* r, int64_t vocab) {
|
||||
float top = -INFINITY;
|
||||
int valid = 1;
|
||||
for (int64_t j = 0; j < r->n; ++j) {
|
||||
if (r->ids[j] < 0) continue;
|
||||
if (r->ids[j] >= vocab || r->val[j] != r->val[j] || r->val[j] == INFINITY) valid = 0;
|
||||
else if (r->val[j] > top) top = r->val[j];
|
||||
}
|
||||
r->valid = valid;
|
||||
r->top = top;
|
||||
}
|
||||
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_live(int32_t id, float v) { return id >= 0 && v != -INFINITY; }
|
||||
|
||||
/* A lane's partial sums of one row: v[0..7] the mass on Q's ids (by their place in the state),
|
||||
* v[8] the mass off Q's support, v[9] the total. */
|
||||
struct RadBlockAcc { double v[10]; };
|
||||
|
||||
static inline RAD_BLK_HD int rad_mtp_block_find(const RadMtpCoupleState& s, int32_t id) {
|
||||
int k = 0;
|
||||
while (k < s.count && id != s.ids[k]) ++k;
|
||||
return k;
|
||||
}
|
||||
|
||||
/* Adds the live slot (id, v) to a lane's partial. */
|
||||
static inline RAD_BLK_HD void rad_mtp_block_acc_add(RadBlockAcc* a, const RadMtpCoupleState& s,
|
||||
int32_t id, float v, float top) {
|
||||
const double w = ::exp((double)v - top);
|
||||
const int k = rad_mtp_block_find(s, id);
|
||||
for (int kk = 0; kk < 8; ++kk) a->v[kk] += kk == k ? w : 0.0;
|
||||
a->v[8] += k >= s.count ? w : 0.0;
|
||||
a->v[9] += w;
|
||||
}
|
||||
|
||||
/* The lanes' partials reduced by the tree above (the host form; the device does the butterfly with
|
||||
* shuffles and adds the four group sums the same way). */
|
||||
static inline RAD_BLK_HD RadBlockAcc rad_mtp_block_tree(const RadBlockAcc* lane) {
|
||||
RadBlockAcc grp[RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE];
|
||||
for (int w = 0; w < RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE; ++w) {
|
||||
RadBlockAcc a[RAD_MTP_BLOCK_WAVE], t[RAD_MTP_BLOCK_WAVE];
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) a[l] = lane[w * RAD_MTP_BLOCK_WAVE + l];
|
||||
for (int d = RAD_MTP_BLOCK_WAVE / 2; d > 0; d >>= 1) {
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) t[l] = a[l];
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l)
|
||||
for (int c = 0; c < 10; ++c) a[l].v[c] = t[l].v[c] + t[l ^ d].v[c];
|
||||
}
|
||||
grp[w] = a[0];
|
||||
}
|
||||
RadBlockAcc o;
|
||||
for (int c = 0; c < 10; ++c) o.v[c] = (grp[0].v[c] + grp[1].v[c]) + (grp[2].v[c] + grp[3].v[c]);
|
||||
return o;
|
||||
}
|
||||
|
||||
/* P_i over Q_{i+1}'s support (pq, normalised, duplicate candidates aggregated), the mass off that
|
||||
* support (pout), the normaliser `sum` and the index `ix` of the draft token in the state's ids. */
|
||||
struct RadBlockStat {
|
||||
double pq[8];
|
||||
double pout, sum;
|
||||
int ix;
|
||||
};
|
||||
|
||||
/* The stat from the reduced partials `t` (what the device builds from its workgroup's tree). */
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_stat_from(const RadBlockAcc& t, int valid, float top,
|
||||
const RadMtpCoupleState& s, RadBlockStat* o) {
|
||||
if (!valid || top == -INFINITY) return false;
|
||||
const double sum = t.v[9];
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
|
||||
o->ix = -1;
|
||||
for (int k = 0; k < 8; ++k) o->pq[k] = k < s.count ? t.v[k] : 0.0;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
o->pq[k] /= sum;
|
||||
if (s.ids[k] == s.x) o->ix = k;
|
||||
}
|
||||
o->pout = t.v[8] / sum;
|
||||
o->sum = sum;
|
||||
return o->ix >= 0;
|
||||
}
|
||||
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_stat(const RadBlockRow& r, const RadMtpCoupleState& s,
|
||||
RadBlockStat* o) {
|
||||
if (!r.valid || r.top == -INFINITY) return false;
|
||||
RadBlockAcc lane[RAD_MTP_BLOCK_LANES];
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l)
|
||||
for (int c = 0; c < 10; ++c) lane[l].v[c] = 0;
|
||||
for (int64_t j = 0; j < r.n; ++j)
|
||||
if (rad_mtp_block_live(r.ids[j], r.val[j]))
|
||||
rad_mtp_block_acc_add(&lane[j % RAD_MTP_BLOCK_LANES], s, r.ids[j], r.val[j], r.top);
|
||||
return rad_mtp_block_stat_from(rad_mtp_block_tree(lane), r.valid, r.top, s, o);
|
||||
}
|
||||
|
||||
/* The block's weights. p[i] (i = 0 .. g), h[i] (i = 0 .. g). */
|
||||
struct RadBlockPlan {
|
||||
int g;
|
||||
double p[RAD_MTP_BLOCK_MAX + 1];
|
||||
double h[RAD_MTP_BLOCK_MAX + 1];
|
||||
double s[RAD_MTP_BLOCK_MAX + 1]; /* S_i, the residual's mass (s[g] unused) */
|
||||
};
|
||||
|
||||
/* The residual mass of one token of row i at weight p: max(p P(x) - Q(x), 0) on Q's support,
|
||||
* p P(x) off it. */
|
||||
static inline RAD_BLK_HD double rad_mtp_block_resid_sum(const RadMtpCoupleState& s,
|
||||
const RadBlockStat& t, double p) {
|
||||
double r = p * t.pout;
|
||||
for (int k = 0; k < s.count; ++k) r += rad_spechub_positive(p * t.pq[k] - s.q[k]);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* st[i] / stat[i] for i = 0 .. g-1. */
|
||||
static inline RAD_BLK_HD void rad_mtp_block_plan(const RadMtpCoupleState* st,
|
||||
const RadBlockStat* stat, int g,
|
||||
RadBlockPlan* o) {
|
||||
o->g = g;
|
||||
o->p[0] = 1.0;
|
||||
for (int i = 0; i < g; ++i) {
|
||||
const double ratio = stat[i].pq[stat[i].ix] / st[i].q[stat[i].ix];
|
||||
const double v = o->p[i] * ratio;
|
||||
o->p[i + 1] = v < 1.0 ? v : 1.0;
|
||||
}
|
||||
for (int i = 0; i < g; ++i) {
|
||||
const double S = rad_mtp_block_resid_sum(st[i], stat[i], o->p[i]);
|
||||
o->s[i] = S;
|
||||
const double den = S + (1.0 - o->p[i]);
|
||||
o->h[i] = (den > 0 && rad_spechub_finite(den)) ? S / den : 1.0;
|
||||
}
|
||||
o->s[g] = 0;
|
||||
o->h[g] = o->p[g];
|
||||
}
|
||||
|
||||
/* tau: the first i, counting down from g, whose uniform falls below h_i. The uniforms are keyed by
|
||||
* the block's first output position, so no row's own draws are reused. */
|
||||
static inline RAD_BLK_HD int rad_mtp_block_tau(const RadBlockPlan& pl, uint64_t seed, uint64_t pos0) {
|
||||
for (int i = pl.g; i > 0; --i)
|
||||
if (rad_spechub_uniform(seed, pos0, RAD_MTP_BLOCK_KEY_STOP + (uint64_t)i) < pl.h[i]) return i;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* One lane's partials of the residual draw: `off` the off-support masses p * (w / sum) (slots whose
|
||||
* id is not among Q's), `all` the plain weights (the fallback draw from P itself), and the last
|
||||
* positive id of each, in the lane's slot order. */
|
||||
struct RadBlockLane { double off, all; int32_t last_off, last_all; };
|
||||
|
||||
static inline RAD_BLK_HD void rad_mtp_block_lane_add(RadBlockLane* a, const RadMtpCoupleState& s,
|
||||
const RadBlockStat& t, double p, int32_t id,
|
||||
float v, float top) {
|
||||
const double w = ::exp((double)v - top);
|
||||
a->all += w;
|
||||
if (w > 0) a->last_all = id;
|
||||
if (rad_mtp_block_find(s, id) >= s.count) {
|
||||
const double m = p * (w / t.sum);
|
||||
a->off += m;
|
||||
if (m > 0) a->last_off = id;
|
||||
}
|
||||
}
|
||||
|
||||
/* Y ~ max(p P - Q, 0) normalised (state s, row r, stat t) with the uniform u in [0, 1). The mass
|
||||
* is walked in a fixed order: the ids of Q (place k = 0 .. count-1, mass max(p pq[k] - q[k], 0)),
|
||||
* then the other live slots lane by lane (the lanes of the tree above, each lane's slots in
|
||||
* ascending order; the lane totals are added in lane order). The walk subtracts the masses from
|
||||
* c = u * total and stops at the first negative; inside the lane it stops in, the walk restarts
|
||||
* from the c at the lane's start, so the structure is exactly what the workgroup computes. When
|
||||
* the total underflows to zero (FP64 cancellation with p = 1: P == Q) Y is drawn from P itself
|
||||
* over all live slots in the same lane order, a branch that depends on (P, Q) only. False: no live
|
||||
* candidate. */
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_resid_walk(const RadBlockRow& r,
|
||||
const RadMtpCoupleState& s,
|
||||
const RadBlockStat& t, double p, double u,
|
||||
const RadBlockLane* lane, int32_t* out) {
|
||||
double on[8];
|
||||
double total = 0;
|
||||
for (int k = 0; k < s.count; ++k) { on[k] = rad_spechub_positive(p * t.pq[k] - s.q[k]); total += on[k]; }
|
||||
double offt = 0;
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) offt += lane[l].off;
|
||||
total += offt;
|
||||
const bool resid = total > 0 && rad_spechub_finite(total);
|
||||
double c = resid ? u * total : u * t.sum;
|
||||
int32_t last = -1;
|
||||
if (resid) {
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (on[k] > 0) { last = s.ids[k]; c -= on[k]; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) {
|
||||
const double T = resid ? lane[l].off : lane[l].all;
|
||||
const int32_t ll = resid ? lane[l].last_off : lane[l].last_all;
|
||||
if (!(T > 0)) continue;
|
||||
if (ll >= 0) last = ll;
|
||||
if (c - T < 0) {
|
||||
double cl = c;
|
||||
int32_t lastl = -1;
|
||||
for (int64_t j = l; j < r.n; j += RAD_MTP_BLOCK_LANES) {
|
||||
if (!rad_mtp_block_live(r.ids[j], r.val[j])) continue;
|
||||
const double w = ::exp((double)r.val[j] - r.top);
|
||||
double m;
|
||||
if (resid) {
|
||||
if (rad_mtp_block_find(s, r.ids[j]) < s.count) continue;
|
||||
m = p * (w / t.sum);
|
||||
} else {
|
||||
m = w;
|
||||
}
|
||||
if (m > 0) { lastl = r.ids[j]; cl -= m; if (cl < 0) { *out = lastl; return true; } }
|
||||
}
|
||||
*out = lastl >= 0 ? lastl : ll;
|
||||
return *out >= 0;
|
||||
}
|
||||
c -= T;
|
||||
}
|
||||
*out = last;
|
||||
return last >= 0;
|
||||
}
|
||||
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_resid_draw(const RadBlockRow& r,
|
||||
const RadMtpCoupleState& s,
|
||||
const RadBlockStat& t, double p, double u,
|
||||
int32_t* out) {
|
||||
RadBlockLane lane[RAD_MTP_BLOCK_LANES];
|
||||
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) lane[l] = RadBlockLane{ 0, 0, -1, -1 };
|
||||
for (int64_t j = 0; j < r.n; ++j)
|
||||
if (rad_mtp_block_live(r.ids[j], r.val[j]))
|
||||
rad_mtp_block_lane_add(&lane[j % RAD_MTP_BLOCK_LANES], s, t, p, r.ids[j], r.val[j], r.top);
|
||||
return rad_mtp_block_resid_walk(r, s, t, p, u, lane, out);
|
||||
}
|
||||
|
||||
/* The whole decision on the host: rows[0 .. g-1] / st[0 .. g-1] are the block's verify rows and
|
||||
* their coupled states (round i + 1 at row i), pos0 the first row's output position. Writes tau and
|
||||
* *y; *y = -1 when tau == g (the g-th row's ordinary draw stands). False for an invalid target. */
|
||||
static inline RAD_BLK_HD bool rad_mtp_block_decide(const RadMtpCoupleState* st,
|
||||
const RadBlockRow* rows, int g, uint64_t seed,
|
||||
uint64_t pos0, int* tau, int32_t* y) {
|
||||
RadBlockStat stat[RAD_MTP_BLOCK_MAX];
|
||||
RadBlockPlan pl;
|
||||
if (g < 1 || g > RAD_MTP_BLOCK_MAX) return false;
|
||||
for (int i = 0; i < g; ++i)
|
||||
if (!rad_mtp_block_stat(rows[i], st[i], &stat[i])) return false;
|
||||
rad_mtp_block_plan(st, stat, g, &pl);
|
||||
const int t = rad_mtp_block_tau(pl, seed, pos0);
|
||||
*tau = t;
|
||||
*y = -1;
|
||||
if (t >= g) return true;
|
||||
return rad_mtp_block_resid_draw(rows[t], st[t], stat[t], pl.p[t],
|
||||
rad_spechub_uniform(seed, pos0 + (uint64_t)t, RAD_SAMPLE_KEY_RESID), y);
|
||||
}
|
||||
|
||||
#endif /* __cplusplus */
|
||||
#endif /* RAD_MTP_BLOCK_H */
|
||||
@@ -0,0 +1,426 @@
|
||||
/* rad_mtp_rrs.h -- recursive rejection sampling over a node's SIBLING drafts under
|
||||
* --draft-coupling on: the draft side (children sampled without replacement from Q) and the
|
||||
* verify side (the walk over a node's children against the target's P), as plain code the host
|
||||
* oracle, the device kernels and the tests share, so they cannot drift. Traversal verification
|
||||
* (abi/rad_mtp_traversal.h) walks nodes that drafted several children; the serial head of this
|
||||
* engine drafts one (nkids <= 1, the chain), so nothing in the engine draws siblings yet: the
|
||||
* header is the verify side's definition and its tests (tests/mtp_rrs_test.cpp). The short proof:
|
||||
*
|
||||
* Draft. A node whose head pass left the law Q (the FP64 T1 softmax of the reranked top 8,
|
||||
* rad_mtp_couple_build_q) drafts its children x_1, x_2, ... by Gumbel-top-k over log Q: add an
|
||||
* independent Gumbel to every log q_i and take the entries in descending order. That is sampling
|
||||
* without replacement (Plackett-Luce): x_1 ~ Q, x_2 ~ Q(. | not x_1), ... The first m of them are
|
||||
* the node's children, m chosen by anything that does not read the values x_j it applies to
|
||||
* (a fixed count, or a rule over the slot priorities, the j-th largest q of Q, never the drawn
|
||||
* token).
|
||||
*
|
||||
* Verify (Sequoia, Chen et al. 2024, Alg. 1; SpecInfer's multi-step verification with the draft
|
||||
* law renormalised after each removal). P_1 = the target's law, q_1 = Q. For i = 1..m:
|
||||
* accept x_i with probability min(1, P_i(x_i) / q_i(x_i));
|
||||
* on rejection P_{i+1} = norm(max(P_i - q_i, 0)), q_{i+1} = q_i with x_i removed, renormalised.
|
||||
* All rejected: the token is a draw from P_{m+1}. Exactness (induction on m): after a rejection of
|
||||
* the first draft the continuation depends on x_1 only through q_2, and P_2 = norm(max(P - q, 0))
|
||||
* does not depend on x_1 at all, so by the hypothesis it emits ~ P_2 whatever x_1 was; then
|
||||
* P(emit y) = sum_x q(x) min(1, P(x)/q(x)) [x = y] + P(reject) P_2(y) = min(P, q)(y) +
|
||||
* max(P - q, 0)(y) = P(y). The emitted token is the accepted child's token, or a residual draw that
|
||||
* has no mass on any rejected child (P_{i+1}(x_i) = 0 after a rejection), so the core's rule "follow
|
||||
* the first child whose token is the sampler's token at the row" (ADV_ACCEPT) walks exactly the
|
||||
* decision made here and needs no change.
|
||||
*
|
||||
* Wire: the node's RadMtpCoupleState holds Q (ids, q), the children in draft order in ids[0 ..
|
||||
* nkids), x = ids[0]. A state with nkids <= 1 is the chain's (rad_mtp_couple_decide, bit for bit).
|
||||
*/
|
||||
#ifndef RAD_MTP_RRS_H
|
||||
#define RAD_MTP_RRS_H
|
||||
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
#ifdef __HIPCC__
|
||||
#define RAD_RRS_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_RRS_HD
|
||||
#endif
|
||||
|
||||
#define RAD_MTP_RRS_KEY_TREE 0x4d54524545474d42ull /* the draft's Gumbel stream */
|
||||
#define RAD_MTP_RRS_KEY_ACCEPT 0x41435054ull
|
||||
|
||||
static inline RAD_RRS_HD uint64_t rad_mtp_rrs_mix(uint64_t z) {
|
||||
z += 0x9e3779b97f4a7c15ull;
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
|
||||
/* The open-interval uniform of candidate `c` of draft node `node`: (seed, base) name the draft
|
||||
* stream (the request's seed and its pre-commit output length, which no later step reuses). */
|
||||
static inline RAD_RRS_HD double rad_mtp_rrs_gumbel_u(uint64_t seed, uint64_t base,
|
||||
uint64_t node, int c) {
|
||||
uint64_t z = rad_mtp_rrs_mix(seed ^ RAD_MTP_RRS_KEY_TREE);
|
||||
z = rad_mtp_rrs_mix(z ^ base);
|
||||
z = rad_mtp_rrs_mix(z + node * 16u + (uint64_t)c);
|
||||
return ((double)(z >> 11) + 0.5) * 0x1p-53;
|
||||
}
|
||||
|
||||
/* Gumbel-top-k order of Q's support: order[0 .. s.count) are indices into s.ids, the draft order
|
||||
* (descending of log q + Gumbel, ties to the lower index). Draws one uniform per support entry from
|
||||
* the state's own draw, node `node`. */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_order(const RadMtpCoupleState& s, uint64_t node,
|
||||
int* order) {
|
||||
double key[8];
|
||||
for (int i = 0; i < s.count; ++i) {
|
||||
const double u = rad_mtp_rrs_gumbel_u(s.draw.seed, s.draw.base, node, i);
|
||||
key[i] = ::log(s.q[i]) - ::log(-::log(u));
|
||||
order[i] = i;
|
||||
}
|
||||
for (int i = 1; i < s.count; ++i) { /* insertion sort, stable */
|
||||
const int o = order[i];
|
||||
int j = i;
|
||||
while (j > 0 && key[order[j - 1]] < key[o]) { order[j] = order[j - 1]; --j; }
|
||||
order[j] = o;
|
||||
}
|
||||
}
|
||||
|
||||
/* Draw the node's children: reorder Q's support into the draft order (ids and q together), set
|
||||
* x = ids[0] and nkids = `nkids`. */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_draw(RadMtpCoupleState* s, uint64_t node, int nkids) {
|
||||
int order[8];
|
||||
rad_mtp_rrs_order(*s, node, order);
|
||||
int32_t ids[8];
|
||||
double q[8];
|
||||
for (int i = 0; i < s->count; ++i) { ids[i] = s->ids[order[i]]; q[i] = s->q[order[i]]; }
|
||||
for (int i = 0; i < s->count; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
|
||||
s->x = s->ids[0];
|
||||
s->nkids = nkids < s->count ? nkids : s->count;
|
||||
}
|
||||
|
||||
/* The SLOT priorities of a node's law: slot j carries the log of the j-th LARGEST q of Q
|
||||
* (descending, ties by position), -inf past the support. They are a function of Q alone, never of
|
||||
* which token was drawn into which slot, so a rule that reads only them admits children by a
|
||||
* quantity independent of the values the children take. `s` is read before the draw reorders it
|
||||
* or after (the multiset of q is the same). */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq(const RadMtpCoupleState& s, float* ov) {
|
||||
double qs[8];
|
||||
const int n = s.count < 8 ? s.count : 8;
|
||||
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
|
||||
for (int i = 1; i < n; ++i) {
|
||||
const double v = qs[i];
|
||||
int j = i;
|
||||
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
|
||||
qs[j] = v;
|
||||
}
|
||||
for (int c = 0; c < 8; ++c) ov[c] = c < n ? (float)::log(qs[c]) : -INFINITY;
|
||||
}
|
||||
|
||||
/* The longest prefix of the state's children that are the first `n` of `kid[]` (the tree's
|
||||
* children of this row, in node order, repeats dropped): what a verify may keep when a window cut
|
||||
* the tree short. 0 when even the first differs. */
|
||||
static inline RAD_RRS_HD int rad_mtp_rrs_prefix(const RadMtpCoupleState& s, const int32_t* kid,
|
||||
int n) {
|
||||
const int have = s.nkids >= 1 ? s.nkids : 1;
|
||||
int m = 0;
|
||||
while (m < have && m < n && m < s.count && s.ids[m] == kid[m]) ++m;
|
||||
return s.nkids >= 2 ? m : (n >= 1 && s.x == kid[0] ? 1 : 0);
|
||||
}
|
||||
|
||||
/* The acceptance uniform of the i-th child at output position `pos`: the first is the chain's. */
|
||||
static inline RAD_RRS_HD double rad_mtp_rrs_uaccept(uint64_t seed, uint64_t pos, int i) {
|
||||
return rad_spechub_uniform(seed, pos, i == 0 ? (uint64_t)RAD_SAMPLE_KEY_ACCEPT
|
||||
: RAD_MTP_RRS_KEY_ACCEPT ^ rad_mtp_rrs_mix((uint64_t)i));
|
||||
}
|
||||
|
||||
/* The verify of a node with nkids >= 2 children: the recursion above over the sampler's surviving
|
||||
* candidates (ids/val, n of them, FP64 P = softmax of val). Writes the emitted token to *out and
|
||||
* returns true, or false for an invalid target (the row keeps the ordinary token).
|
||||
*
|
||||
* The decision reads the live candidates (id >= 0, value not -inf) in ascending order through a view
|
||||
* `C::each(f)`, f(id, w, k) -> bool (false stops): w = exp(val - top) in FP64, k the id's slot in the
|
||||
* state's support (the first match) or s.count when it is outside. The host view (RadRrsHostCands)
|
||||
* computes them on the fly; the device verify (plugin/spechub/spechub.hip) compacts the live
|
||||
* candidates and computes every w and k with the whole workgroup, then runs this same function on one
|
||||
* lane over the stored values, so the ordered sums, and with them the token, are the host's. `pq_out`
|
||||
* and `sum_out` (optional) hand back P's masses on the support and their normaliser (the export). */
|
||||
template <class C>
|
||||
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_over(const RadMtpCoupleState& s, const C& cs,
|
||||
uint64_t seed, uint64_t pos, int32_t* out,
|
||||
double* pq_out = nullptr,
|
||||
double* sum_out = nullptr) {
|
||||
double sum = 0, pq[8] = {}, wout = 0;
|
||||
cs.each([&](int32_t, double w, int k) {
|
||||
sum += w;
|
||||
if (k < s.count) pq[k] += w; else wout += w;
|
||||
return true;
|
||||
});
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
|
||||
if (pq_out) for (int k = 0; k < 8; ++k) pq_out[k] = pq[k];
|
||||
if (sum_out) *sum_out = sum;
|
||||
/* P over Q's support (normalised), and the off-support mass's scale `so` (P_i(y) = so * w / sum
|
||||
* there). qr: the draft law with the drawn children removed. */
|
||||
double r[8], qr[8], so = 1.0;
|
||||
for (int k = 0; k < s.count; ++k) { r[k] = pq[k] / sum; qr[k] = s.q[k]; }
|
||||
const double pout = wout / sum;
|
||||
bool direct = false;
|
||||
for (int i = 0; i < s.nkids && !direct; ++i) {
|
||||
double sq = 0;
|
||||
for (int k = 0; k < s.count; ++k) sq += qr[k];
|
||||
if (!(sq > 0)) break;
|
||||
const double qx = qr[i] / sq;
|
||||
if (r[i] >= qx || rad_mtp_rrs_uaccept(seed, pos, i) * qx < r[i]) { *out = s.ids[i]; return true; }
|
||||
double z = so * pout;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
const double d = r[k] - qr[k] / sq;
|
||||
r[k] = d > 0 ? d : 0;
|
||||
z += r[k];
|
||||
}
|
||||
if (!(z > 0) || !rad_spechub_finite(z)) { direct = true; break; }
|
||||
for (int k = 0; k < s.count; ++k) r[k] /= z;
|
||||
so /= z;
|
||||
qr[i] = 0;
|
||||
}
|
||||
const double u = rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID);
|
||||
double c;
|
||||
int32_t last = -1;
|
||||
if (direct) {
|
||||
c = u * sum;
|
||||
bool hit = false;
|
||||
cs.each([&](int32_t id, double w, int) {
|
||||
if (w > 0) { last = id; c -= w; if (c < 0) { hit = true; return false; } }
|
||||
return true;
|
||||
});
|
||||
*out = last;
|
||||
(void)hit;
|
||||
return true;
|
||||
}
|
||||
double total = 0;
|
||||
for (int k = 0; k < s.count; ++k) total += r[k];
|
||||
total += so * pout;
|
||||
c = u * total;
|
||||
unsigned seen = 0;
|
||||
bool hit = false;
|
||||
cs.each([&](int32_t id, double w, int k) {
|
||||
double m;
|
||||
if (k < s.count) {
|
||||
if (seen & (1u << k)) return true;
|
||||
seen |= 1u << k;
|
||||
m = r[k];
|
||||
} else {
|
||||
m = so * (w / sum);
|
||||
}
|
||||
if (m > 0) { last = id; c -= m; if (c < 0) { hit = true; return false; } }
|
||||
return true;
|
||||
});
|
||||
*out = last;
|
||||
(void)hit;
|
||||
return last >= 0;
|
||||
}
|
||||
|
||||
/* The host view: the candidates as the sampler wrote them, weights computed as they are read. */
|
||||
struct RadRrsHostCands {
|
||||
const RadMtpCoupleState& s;
|
||||
const int32_t* ids; const float* val; int64_t n; float top;
|
||||
template <class F> RAD_RRS_HD void each(F&& f) const {
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
int k = 0;
|
||||
while (k < s.count && ids[j] != s.ids[k]) ++k;
|
||||
if (!f(ids[j], ::exp((double)val[j] - top), k)) return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static inline RAD_RRS_HD bool rad_mtp_rrs_decide(const RadMtpCoupleState& s, const int32_t* ids,
|
||||
const float* val, int64_t n, int64_t vocab,
|
||||
uint64_t seed, uint64_t pos, int32_t* out) {
|
||||
float top = -INFINITY;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0) continue;
|
||||
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
|
||||
if (val[j] > top) top = val[j];
|
||||
}
|
||||
if (top == -INFINITY) return false;
|
||||
return rad_mtp_rrs_decide_over(s, RadRrsHostCands{ s, ids, val, n, top }, seed, pos, out);
|
||||
}
|
||||
|
||||
/* ================================================================== RheoSampling siblings
|
||||
*
|
||||
* --draft-siblings rheo (--draft-rheo-m m). Hu et al. 2025 (arXiv 2502.18779, Thm 8, the greedy
|
||||
* multi-draft verifier) and RheoSampling (arXiv 2609.21827): instead of Gumbel-top-k siblings, a node's
|
||||
* children are
|
||||
* T = the m tokens of largest Q, in descending q order (deterministic, rank slots 0 .. m-1), and
|
||||
* u ~ Qt, ONE token sampled from the tail law Qt(x) = Q(x) / z over the support outside T,
|
||||
* z = Q(outside T), in slot m;
|
||||
* the draft order stored in the state is ids = [T..., u, the rest of the support in descending q],
|
||||
* scheme = m + 1. A node whose support has no more than m tokens has no tail child (all of it is T).
|
||||
*
|
||||
* Verify (derived here, not quoted; the law is checked by tests/mtp_rrs_test.cpp by exhaustive
|
||||
* enumeration). P = the target's law, children present = the first nkids of the draft order.
|
||||
* tail child present (nkids > |T|, which with a prefix draft order means every T token is a child):
|
||||
* accept u with probability min(1, P(u) / Qt(u)) -> emit u
|
||||
* else emit y ~ R / |R|, R(y) = P(y) y in T or off Q's support,
|
||||
* R(y) = max(P(y) - Qt(y), 0) y in the tail support (R(u) = 0 here)
|
||||
* otherwise (the tail slot was pruned or cut by a window, or Q has no tail): emit y ~ P directly.
|
||||
* Exactness: P(emit y) = min(P, Qt)(y) [y in tail] + (1 - A) R(y) / |R| with |R| = 1 - A,
|
||||
* A = sum_tail min(P, Qt), and min(P, Qt) + R = P on the tail, R = P elsewhere: P(emit y) = P(y).
|
||||
* It needs only that u ~ Qt independently of the verifier's uniforms (a separate draft stream), and
|
||||
* that WHICH slots exist depends on Q and the tree's budget alone (never on the value of u): both
|
||||
* hold, the slot priorities are rad_mtp_rrs_slot_logq_rheo. The emitted token is a child with
|
||||
* probability P(T) + A = sum_T P + sum_tail min(P, Qt), Thm 8's value, and a residual draw never
|
||||
* lands on u (R(u) = 0 when u was rejected), so the core's "follow the first child whose token is
|
||||
* the sampler's" walks the decision made here.
|
||||
* m = 0 is the single-draft maximal coupling of the chain (rad_mtp_couple_decide) with the sampled
|
||||
* child in slot 0.
|
||||
*/
|
||||
#define RAD_MTP_RRS_KEY_TAIL_C 8 /* candidate index of the tail draw in the draft stream (0..7 are Gumbel's) */
|
||||
|
||||
/* Slot priorities of a rheo node (functions of Q alone, non-increasing): slots 0 .. m-1 carry the
|
||||
* log of the j-th largest q, slot m RheoSampling's proxy log min{q_(m-1), z} (z = the tail mass; with
|
||||
* m = 0, z = 1), -inf for the other slots and for slots past the support. */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq_rheo(const RadMtpCoupleState& s, int m, float* ov) {
|
||||
double qs[8];
|
||||
const int n = s.count < 8 ? s.count : 8;
|
||||
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
|
||||
for (int i = 1; i < n; ++i) {
|
||||
const double v = qs[i];
|
||||
int j = i;
|
||||
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
|
||||
qs[j] = v;
|
||||
}
|
||||
const int nt = m < n ? m : n;
|
||||
for (int c = 0; c < 8; ++c) ov[c] = c < nt ? (float)::log(qs[c]) : -INFINITY;
|
||||
if (n > nt) {
|
||||
double z = 0;
|
||||
for (int i = nt; i < n; ++i) z += qs[i];
|
||||
if (z > 1) z = 1;
|
||||
const double ref = nt > 0 ? qs[nt - 1] : 1.0;
|
||||
ov[nt] = (float)::log(z < ref ? z : ref);
|
||||
}
|
||||
}
|
||||
|
||||
/* Draw a rheo node's children: reorder Q's support into [top-m by q desc, the sampled tail child,
|
||||
* the rest by q desc], set x = ids[0], scheme = m + 1 and nkids = min(nkids, children possible). The
|
||||
* tail child is the inverse-CDF draw of Qt with the draft stream's uniform of (seed, base, node). */
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo_u(RadMtpCoupleState* s, double ut, int nkids, int m) {
|
||||
int ord[8];
|
||||
const int n = s->count;
|
||||
for (int i = 0; i < n; ++i) ord[i] = i;
|
||||
for (int i = 1; i < n; ++i) { /* descending q, stable */
|
||||
const int o = ord[i];
|
||||
int j = i;
|
||||
while (j > 0 && s->q[ord[j - 1]] < s->q[o]) { ord[j] = ord[j - 1]; --j; }
|
||||
ord[j] = o;
|
||||
}
|
||||
const int nt = m < n ? m : n;
|
||||
if (n > nt) {
|
||||
double z = 0;
|
||||
for (int i = nt; i < n; ++i) z += s->q[ord[i]];
|
||||
double c = ut * z;
|
||||
int pick = n - 1;
|
||||
for (int i = nt; i < n; ++i) { c -= s->q[ord[i]]; if (c < 0) { pick = i; break; } }
|
||||
const int o = ord[pick];
|
||||
for (int i = pick; i > nt; --i) ord[i] = ord[i - 1];
|
||||
ord[nt] = o;
|
||||
}
|
||||
int32_t ids[8];
|
||||
double q[8];
|
||||
for (int i = 0; i < n; ++i) { ids[i] = s->ids[ord[i]]; q[i] = s->q[ord[i]]; }
|
||||
for (int i = 0; i < n; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
|
||||
const int cap = nt + (n > nt ? 1 : 0);
|
||||
s->x = s->ids[0];
|
||||
s->scheme = m + 1;
|
||||
s->nkids = nkids < cap ? nkids : cap;
|
||||
}
|
||||
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo(RadMtpCoupleState* s, uint64_t node, int nkids, int m) {
|
||||
rad_mtp_rrs_draw_rheo_u(s, rad_mtp_rrs_gumbel_u(s->draw.seed, s->draw.base, node, RAD_MTP_RRS_KEY_TAIL_C),
|
||||
nkids, m);
|
||||
}
|
||||
|
||||
/* The verify of a rheo node (any nkids >= 0): the rule above. Same contract as rad_mtp_rrs_decide. */
|
||||
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo_u(const RadMtpCoupleState& s, const int32_t* ids,
|
||||
const float* val, int64_t n, int64_t vocab,
|
||||
double u_accept, double u_resid, int32_t* out) {
|
||||
float top = -INFINITY;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0) continue;
|
||||
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
|
||||
if (val[j] > top) top = val[j];
|
||||
}
|
||||
if (top == -INFINITY) return false;
|
||||
double sum = 0, pq[8] = {};
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
const double w = ::exp((double)val[j] - top);
|
||||
sum += w;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (ids[j] == s.ids[k]) { pq[k] += w; break; }
|
||||
}
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
|
||||
const int m = s.scheme - 1;
|
||||
const int nt = m < s.count ? m : s.count;
|
||||
const bool tail = m >= 0 && s.count > nt && s.nkids > nt;
|
||||
double qt[8] = {}, r[8] = {};
|
||||
bool dominated = true;
|
||||
for (int k = 0; k < s.count; ++k) pq[k] /= sum;
|
||||
if (tail) {
|
||||
double z = 0;
|
||||
for (int k = nt; k < s.count; ++k) z += s.q[k];
|
||||
for (int k = nt; k < s.count; ++k) {
|
||||
const double v = nt == 0 ? s.q[k] : s.q[k] / z;
|
||||
qt[k] = v > 1 ? 1 : v; /* clamp: rounding must not push a one-token tail past 1 */
|
||||
dominated = dominated && pq[k] >= qt[k];
|
||||
}
|
||||
for (int k = 0; k < s.count; ++k) r[k] = k < nt ? pq[k] : rad_spechub_positive(pq[k] - qt[k]);
|
||||
}
|
||||
/* mass of candidate j in R (the tail case) or in P (otherwise); Q tokens count once. */
|
||||
unsigned seen = 0;
|
||||
auto mass = [&](int64_t j) -> double {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) return 0;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (s.ids[k] == ids[j]) {
|
||||
if (seen & (1u << k)) return 0;
|
||||
seen |= 1u << k;
|
||||
return tail ? r[k] : pq[k];
|
||||
}
|
||||
return ::exp((double)val[j] - top) / sum;
|
||||
};
|
||||
double resid = 0;
|
||||
if (tail) {
|
||||
for (int64_t j = 0; j < n; ++j) resid += mass(j);
|
||||
seen = 0;
|
||||
}
|
||||
if (!tail || (!dominated && !(resid > 0 && rad_spechub_finite(resid)))) {
|
||||
double c = u_resid * sum; /* P itself, in the sampler's candidate order */
|
||||
int32_t last = -1;
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
if (ids[j] >= 0 && val[j] != -INFINITY) {
|
||||
const double w = ::exp((double)val[j] - top);
|
||||
if (w > 0) { last = ids[j]; c -= w; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
*out = last;
|
||||
return last >= 0;
|
||||
}
|
||||
const int iu = nt;
|
||||
if (pq[iu] >= qt[iu] || u_accept * qt[iu] < pq[iu]) {
|
||||
*out = s.ids[iu];
|
||||
return true;
|
||||
}
|
||||
double c = u_resid * resid;
|
||||
int32_t last = -1;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] == s.ids[iu]) continue;
|
||||
const double mm = mass(j);
|
||||
if (mm > 0) { last = ids[j]; c -= mm; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
*out = last;
|
||||
return last >= 0;
|
||||
}
|
||||
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo(const RadMtpCoupleState& s, const int32_t* ids,
|
||||
const float* val, int64_t n, int64_t vocab,
|
||||
uint64_t seed, uint64_t pos, int32_t* out) {
|
||||
return rad_mtp_rrs_decide_rheo_u(s, ids, val, n, vocab,
|
||||
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_ACCEPT),
|
||||
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID), out);
|
||||
}
|
||||
|
||||
#endif /* __cplusplus */
|
||||
#endif /* RAD_MTP_RRS_H */
|
||||
@@ -0,0 +1,549 @@
|
||||
/* rad_mtp_traversal.h -- Traversal Verification (Weng et al., arXiv 2505.12398) of a draft under
|
||||
* sampling (--draft-verify traversal, needs --draft-coupling on). The walk is defined on a tree; the
|
||||
* serial head of this engine drafts a chain, a tree of one child a node, which the sampler stages
|
||||
* (core/sample/sampler.cpp). Plain code shared by the host oracle, the device kernel and the tests;
|
||||
* the short form of the argument:
|
||||
*
|
||||
* Row-wise verification (rad_mtp_rrs_decide) decides each node on its own. Traversal verification
|
||||
* decides a whole ROOT-TO-LEAF PATH at once, bottom-up, and so can accept a longer prefix from the
|
||||
* same tree (for a chain it is Block Verification, never worse than token-level rejection sampling).
|
||||
*
|
||||
* State of a node v during the walk: p_v (its acceptance rate, a sequence-level ratio), the target
|
||||
* law M_b(.|v) restricted to what has not been rejected below it (r), and the law the NEXT child of
|
||||
* v was drawn from.
|
||||
* - A child c of v enters with p_c = min(1, p_v * r(c)/qn(c)), qn the law c was drawn from GIVEN
|
||||
* the children tried before it.
|
||||
* - The walk descends to the first leaf and tests eta < p_leaf. Accept: the path is accepted and
|
||||
* the final token is drawn from that node's current residual law r (the plain target if none of
|
||||
* its children was rejected). Reject: the leaf is deleted and its parent v is updated:
|
||||
* S = sum_x [ p_v r(x) - qn(x) ]+
|
||||
* p_v' = S / (S + 1 - p_v)
|
||||
* r' = [ p_v r - qn ]+ / S
|
||||
* and the walk continues with v's next child, or tests v itself once it has none.
|
||||
* The walk keeps the PRODUCT m(x) = p_v r(x) (on the draft support per slot, and one number for
|
||||
* everything off it, where qn is zero), which is all the rules read: p_c = min(1, m(c)/qn(c)), and
|
||||
* the update is one division, m' = [m - qn]+ / (S + 1 - p_v), p_v' = S / (S + 1 - p_v), the
|
||||
* off-support mass scaled alike; the final token is drawn in proportion to m. A node entered with
|
||||
* rate p keeps its target law unscaled and the factor p beside it (sc) until its first child is
|
||||
* rejected, so entering a node costs one division (the child's rate) and no pass over its law.
|
||||
* Exactness (Theorem 3.3 of the paper, Lemma A.2 by induction over a node's descendants): the
|
||||
* subtree of v is accepted with probability p_v and, given that, the token after v follows r. One
|
||||
* step of the induction, for a child drawn from ANY law qn that may depend on the children before
|
||||
* it: P(accepted through a child x) = qn(x) min(1, p_v r(x)/qn(x)) = min(qn(x), p_v r(x));
|
||||
* P(the child's subtree is rejected) = 1 - p_v + S; the rest then accepts with p_v' and r', which
|
||||
* adds (1 - p_v + S) p_v' r'(x) = [p_v r(x) - qn(x)]+, and the two sum to p_v r(x). It needs the
|
||||
* tree's shape to be independent of the drawn tokens (a chain's is), and each child's own law:
|
||||
* - Gumbel-top-k siblings (the default, Plackett-Luce without replacement): qn is the node's Q
|
||||
* with the children already tried removed, renormalised;
|
||||
* - RheoSampling siblings (state.scheme = m + 1, abi/rad_mtp_rrs.h): the
|
||||
* sampled tail child is tried FIRST with qn = Qt, the tail law, then the deterministic top-q
|
||||
* children in their order, each with qn = a point mass on its token. A point mass accepts with
|
||||
* p_v r(c) and leaves r without c; tried in this order the node's children take
|
||||
* sum_tail min(P, Qt) + P(T) of the target, the greedy multi-draft verifier's value (Hu et al.
|
||||
* 2025, Thm 8).
|
||||
* tests/mtp_rrs_test.cpp checks the walk by exact enumeration and by chi-square, and shows that
|
||||
* plausible mistakes (token-level ratios, no (1 - p) term, with-replacement update for
|
||||
* without-replacement drafts, a rheo node walked as a Gumbel one) fail the same statistic.
|
||||
*
|
||||
* THE TARGET LAW IN FIXED POINT. The walk reads a row's target law only through its mass on the
|
||||
* node's draft support (eight ids), the mass off it and the total; the final token needs the
|
||||
* off-support candidates in order. Each live candidate's weight is an INTEGER:
|
||||
*
|
||||
* m_j = floor(2^40 * e(val_j - top)), e(x) = rad_mtp_trav_mass's FP32 exponential
|
||||
*
|
||||
* (top the row's largest value; the scale drops a bit per doubling of the plane past 4096 slots so
|
||||
* a row's total stays below 2^53). Integer addition is associative, so the sums are the same bits
|
||||
* whatever order a workgroup adds them in: the device kernel (plugin/spechub/spechub.hip) splits a
|
||||
* row over its threads any way it likes and still equals this header's serial loops, with no
|
||||
* reduction tree to mirror. e() is basic FP32 arithmetic and integer shifts, identical on host and
|
||||
* device (no libm call, no contraction: -ffp-contract=off, and the attribute below for a host
|
||||
* build that enables FMA).
|
||||
* Why FP32 suffices: the algorithm is exact for whatever positive weights define the law, as long as
|
||||
* every decision reads the same ones, which the integers guarantee. The law it realises is
|
||||
* P~(y) = m_y / sum m, within 2^-22 relative per candidate (e's error, tests/mtp_rrs_test.cpp checks
|
||||
* it) plus 2^-40 absolute of the softmax of the sampler's FP32 candidates: the accuracy class of the
|
||||
* uncoupled sample_pick (FP32 expf, FP32 running sum, a 24-bit uniform), which is the law a request
|
||||
* gets without speculation. The 8-wide FP64 sums of the walk are a fixed tree (rad_mtp_trav_sum8),
|
||||
* so a device may run them on one lane or across eight.
|
||||
*
|
||||
* Wire: no new state. The walk reads the same RadMtpCoupleState rows as the row-wise verify and
|
||||
* writes the SAME plane the core already walks (ADV_ACCEPT: the first child whose token is the
|
||||
* sampler's token at the row): on the accepted path every row's token is its path child's token and
|
||||
* the last row's token is the final one; the other rows are not on the walk and keep the pick.
|
||||
*/
|
||||
#ifndef RAD_MTP_TRAVERSAL_H
|
||||
#define RAD_MTP_TRAVERSAL_H
|
||||
|
||||
#include "rad_spechub.h"
|
||||
#include "rad_mtp_rrs.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
#define RAD_MTP_TRAV_MAX_DEPTH 16
|
||||
#define RAD_MTP_TRAV_MAX_ROWS 64 /* rows of one request the walk reads (its first ones) */
|
||||
#define RAD_MTP_TRAV_KEY 0x54524156ull /* "TRAV": the walk's acceptance uniforms */
|
||||
#define RAD_MTP_TRAV_QBITS 40 /* the unit of a candidate's mass: 2^-40 of the top's */
|
||||
|
||||
/* A host build with FMA enabled must not contract the exponential's products into its sums: the
|
||||
* device does not (-ffp-contract=off), and the masses have to be the same bits. */
|
||||
#if defined(__GNUC__) && !defined(__clang__)
|
||||
#define RAD_TRAV_STRICT __attribute__((optimize("fp-contract=off")))
|
||||
#else
|
||||
#define RAD_TRAV_STRICT
|
||||
#endif
|
||||
|
||||
/* Test-only switches; the engine passes the zero value. */
|
||||
struct RadMtpTravOpt {
|
||||
int ctl = 0; /* negative controls: 1 token-level ratios, 2 no (1 - p) term, 3 q never
|
||||
renormalised (the with-replacement update on without-replacement drafts),
|
||||
4 a RheoSampling node walked as a Gumbel one */
|
||||
/* Enumeration (tests): >= 0 replaces the uniforms -- test number `accept_at` (1-based) accepts
|
||||
* and every earlier one rejects; `p_test[i]` receives the acceptance rate of test i + 1 and
|
||||
* `*n_tests` their count. */
|
||||
int accept_at = -1;
|
||||
double* p_test = nullptr;
|
||||
int* n_tests = nullptr;
|
||||
int max_tests = 0;
|
||||
double u_final = -1.0; /* >= 0: the final token's uniform (rad_mtp_trav_walk) */
|
||||
};
|
||||
|
||||
struct RadMtpTravOut {
|
||||
int n = 0; /* nodes on the path, root first */
|
||||
int node[RAD_MTP_TRAV_MAX_DEPTH + 2] = {};
|
||||
int32_t y = -1; /* the final token ... */
|
||||
bool has_y = false; /* ... when the last node carries a valid state */
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- the target law in fixed point */
|
||||
|
||||
/* The mass unit of a plane of n candidates: 2^-qbits of the top candidate's weight, so that a
|
||||
* row's total stays below 2^53 (exact in FP64). */
|
||||
static inline RAD_RRS_HD int rad_mtp_trav_qbits(int64_t n) {
|
||||
int q = RAD_MTP_TRAV_QBITS;
|
||||
for (int64_t c = 4096; c < n && q > 20; c <<= 1) --q;
|
||||
return q;
|
||||
}
|
||||
|
||||
/* floor(2^qbits * e^(v - top)) for a live candidate (v <= top, both finite): the FP32 exponential
|
||||
* of Cephes' expf (argument reduction by n ln 2 in two parts, a degree-5 polynomial in the reduced
|
||||
* argument), taken as a 24-bit mantissa and shifted. Zero below 2^-41 of the top. Basic IEEE FP32
|
||||
* operations and integer shifts only. */
|
||||
RAD_TRAV_STRICT static inline RAD_RRS_HD uint64_t rad_mtp_trav_mass(float v, float top, int qbits) {
|
||||
#if defined(__clang__)
|
||||
#pragma clang fp contract(off)
|
||||
#endif
|
||||
const float x = v - top;
|
||||
if (!(x > -28.5f)) return 0;
|
||||
const int n = (int)(x * 1.44269504088896341f - 0.5f); /* round(x / ln 2), x <= 0 */
|
||||
const float fn = (float)n;
|
||||
float r = x - fn * 0.693359375f;
|
||||
r = r - fn * -2.12194440e-4f;
|
||||
const float z = r * r;
|
||||
float y = 1.9875691500e-4f;
|
||||
y = y * r + 1.3981999507e-3f;
|
||||
y = y * r + 8.3334519073e-3f;
|
||||
y = y * r + 4.1665795894e-2f;
|
||||
y = y * r + 1.6666665459e-1f;
|
||||
y = y * r + 5.0000001201e-1f;
|
||||
y = y * z + r;
|
||||
y = y + 1.0f; /* e^r, in [0.70, 1.42] */
|
||||
const uint32_t mant = (uint32_t)(y * 8388608.0f); /* y * 2^23, below 2^24 */
|
||||
const int sh = qbits + n - 23;
|
||||
if (sh >= 0) return (uint64_t)mant << sh;
|
||||
return sh > -32 ? (uint64_t)(mant >> -sh) : 0;
|
||||
}
|
||||
|
||||
/* An integer below 2^53 as a double, exactly, the same way on host and device. */
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_u2d(uint64_t x) {
|
||||
return (double)(uint32_t)(x >> 32) * 4294967296.0 + (double)(uint32_t)x;
|
||||
}
|
||||
/* The integer part of a double in [0, 2^53). */
|
||||
static inline RAD_RRS_HD uint64_t rad_mtp_trav_d2u(double d) {
|
||||
const uint32_t hi = (uint32_t)(d * (1.0 / 4294967296.0));
|
||||
const double lo = d - (double)hi * 4294967296.0;
|
||||
return ((uint64_t)hi << 32) + (uint64_t)(uint32_t)lo;
|
||||
}
|
||||
|
||||
/* Candidate id's slot in a node's support (the first match), or cnt when it is outside. */
|
||||
static inline RAD_RRS_HD int rad_mtp_trav_slot(const int32_t* sid, int cnt, int32_t id) {
|
||||
int k = 0;
|
||||
while (k < cnt && id != sid[k]) ++k;
|
||||
return k;
|
||||
}
|
||||
|
||||
/* A row's validity and largest value, as rad_mtp_couple_decide scans them: false for an id past the
|
||||
* vocabulary, a NaN or +inf among the ids >= 0, or no finite value at all. */
|
||||
static inline RAD_RRS_HD bool rad_mtp_trav_row_top(const int32_t* ids, const float* val, int64_t n,
|
||||
int64_t vocab, float* top_out) {
|
||||
float top = -INFINITY;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0) continue;
|
||||
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
|
||||
if (val[j] > top) top = val[j];
|
||||
}
|
||||
*top_out = top;
|
||||
return top != -INFINITY;
|
||||
}
|
||||
|
||||
/* One row's target law over a node's support `sid[0 .. cnt)`: the masses on the support slots
|
||||
* (duplicate candidates aggregated at the first matching slot), off it, and the total. The serial
|
||||
* definition; a workgroup adds the same integers in its own order. */
|
||||
struct RadTravLaw {
|
||||
uint64_t pq[8];
|
||||
uint64_t off, sum;
|
||||
};
|
||||
static inline RAD_RRS_HD void rad_mtp_trav_row_law(const int32_t* ids, const float* val, int64_t n,
|
||||
float top, const int32_t* sid, int cnt,
|
||||
RadTravLaw* o) {
|
||||
const int qb = rad_mtp_trav_qbits(n);
|
||||
for (int k = 0; k < 8; ++k) o->pq[k] = 0;
|
||||
o->off = 0; o->sum = 0;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
|
||||
o->sum += m;
|
||||
const int k = rad_mtp_trav_slot(sid, cnt, ids[j]);
|
||||
if (k < cnt) o->pq[k] += m; else o->off += m;
|
||||
}
|
||||
}
|
||||
|
||||
/* The off-support candidate that holds unit `t` of the off-support mass, candidates in ascending
|
||||
* slot order (t < the row's off-support mass). -1 when there is none. */
|
||||
static inline RAD_RRS_HD int32_t rad_mtp_trav_off_token(const int32_t* ids, const float* val,
|
||||
int64_t n, float top, const int32_t* sid,
|
||||
int cnt, uint64_t t) {
|
||||
const int qb = rad_mtp_trav_qbits(n);
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
if (rad_mtp_trav_slot(sid, cnt, ids[j]) < cnt) continue;
|
||||
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
|
||||
if (t < m) return ids[j];
|
||||
t -= m;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the prepared tree */
|
||||
|
||||
/* The eight-wide FP64 sums of the walk, as one fixed tree: the xor-4, xor-2, xor-1 butterfly of
|
||||
* eight lanes (IEEE addition is commutative, so every lane of the butterfly ends with these bits). */
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_sum8(const double* v) {
|
||||
return ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7]));
|
||||
}
|
||||
|
||||
/* A node's draft side in the walk's canonical order: the children first, in draft order (a chain's
|
||||
* one child is x). `nk` the children the walk may try, `nt` -1 for Gumbel-top-k siblings, else the
|
||||
* number of deterministic top-q children of a RheoSampling node (its tail child is slot nt, `tail`
|
||||
* whether the node carries it), `swap` the stored slot that changed places with slot 0 (a chain row
|
||||
* whose x was not first; else 0).
|
||||
* False when the state names no child (unreachable for a rad_mtp_couple_state_valid state). */
|
||||
static inline RAD_RRS_HD bool rad_mtp_trav_canon(const RadMtpCoupleState& s, int ctl, int32_t* ids,
|
||||
double* q, int* nk, int* nt, int* tail, int* swap) {
|
||||
/* Every index below is a constant: a device lane keeps the state and the result in registers. */
|
||||
*swap = 0;
|
||||
*tail = 0;
|
||||
if (s.scheme > 0 && ctl != 4) {
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
ids[k] = k < s.count ? s.ids[k] : -1;
|
||||
q[k] = k < s.count ? s.q[k] : 0.0;
|
||||
}
|
||||
const int m = s.scheme - 1;
|
||||
const int t = m < s.count ? m : s.count;
|
||||
const int cap = t + (s.count > t ? 1 : 0);
|
||||
*nt = t;
|
||||
*nk = s.nkids < cap ? (s.nkids > 0 ? s.nkids : 0) : cap;
|
||||
*tail = *nk > t;
|
||||
return true;
|
||||
}
|
||||
*nt = -1;
|
||||
*nk = s.nkids >= 2 ? (s.nkids < s.count ? s.nkids : s.count) : 1;
|
||||
/* a chain row: x to the front (the first slot that holds it changes places with slot 0) */
|
||||
int kx = 0;
|
||||
if (s.nkids < 2) {
|
||||
kx = 8;
|
||||
for (int k = 7; k >= 0; --k)
|
||||
if (k < s.count && s.ids[k] == s.x) kx = k;
|
||||
}
|
||||
const bool found = kx < 8;
|
||||
int32_t idx = -1;
|
||||
double qx = 0.0;
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
idx = k == kx ? s.ids[k] : idx;
|
||||
qx = k == kx ? s.q[k] : qx;
|
||||
}
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
const bool in = found && k < s.count;
|
||||
const int32_t idk = k == 0 ? idx : (k == kx ? s.ids[0] : s.ids[k]);
|
||||
const double qk = k == 0 ? qx : (k == kx ? s.q[0] : s.q[k]);
|
||||
ids[k] = in ? idk : -1;
|
||||
q[k] = in ? qk : 0.0;
|
||||
}
|
||||
*swap = found ? kx : 0;
|
||||
return found;
|
||||
}
|
||||
|
||||
/* One request's tree as the walk reads it, node-indexed (node 0 the root, parents before
|
||||
* children). Plain data: the device keeps it in LDS and fills it with a workgroup. */
|
||||
struct RadTravTree {
|
||||
int n; /* nodes */
|
||||
int ok[RAD_MTP_TRAV_MAX_ROWS]; /* an eligible state with a valid target law */
|
||||
int nk[RAD_MTP_TRAV_MAX_ROWS]; /* children the walk tries */
|
||||
int nt[RAD_MTP_TRAV_MAX_ROWS]; /* -1 Gumbel; else a rheo node's deterministic children */
|
||||
int tail[RAD_MTP_TRAV_MAX_ROWS]; /* a rheo node that carries its sampled tail child */
|
||||
int ci[RAD_MTP_TRAV_MAX_ROWS]; /* children tried so far */
|
||||
int child[RAD_MTP_TRAV_MAX_ROWS][8]; /* slot k's child node, or -1 */
|
||||
int32_t ids[RAD_MTP_TRAV_MAX_ROWS][8]; /* the support, canonical order, -1 past it */
|
||||
double qr[RAD_MTP_TRAV_MAX_ROWS][8]; /* the draft law (Gumbel: tried children zeroed) */
|
||||
double m[RAD_MTP_TRAV_MAX_ROWS][8]; /* rate * residual on the support slots (the target's
|
||||
law itself until the node is entered) */
|
||||
double moff[RAD_MTP_TRAV_MAX_ROWS]; /* the same off the support, in all */
|
||||
double sc[RAD_MTP_TRAV_MAX_ROWS]; /* the factor m and moff still owe: the node's rate from
|
||||
its entry to its first rejected child, then 1 */
|
||||
double p[RAD_MTP_TRAV_MAX_ROWS]; /* the node's acceptance rate */
|
||||
uint64_t off[RAD_MTP_TRAV_MAX_ROWS]; /* the off-support mass in units (the final draw) */
|
||||
float top[RAD_MTP_TRAV_MAX_ROWS]; /* the row's largest value */
|
||||
int stack[RAD_MTP_TRAV_MAX_DEPTH + 1];
|
||||
};
|
||||
|
||||
/* Node v's laws from its canonical draft side and its row's integer law (`valid`: the row scanned
|
||||
* clean and its total is positive). */
|
||||
static inline RAD_RRS_HD void rad_mtp_trav_set_law(RadTravTree* t, int v, bool valid, float top,
|
||||
const RadTravLaw& w) {
|
||||
const bool ok = valid && w.sum > 0;
|
||||
const double sum = ok ? rad_mtp_trav_u2d(w.sum) : 1.0;
|
||||
for (int k = 0; k < 8; ++k) t->m[v][k] = ok ? rad_mtp_trav_u2d(w.pq[k]) / sum : 0.0;
|
||||
t->moff[v] = ok ? rad_mtp_trav_u2d(w.off) / sum : 0.0;
|
||||
t->off[v] = ok ? w.off : 0;
|
||||
t->top[v] = top;
|
||||
t->ci[v] = 0;
|
||||
t->ok[v] = ok;
|
||||
}
|
||||
|
||||
/* The slot of node v's j-th tried child. Gumbel: the draft order. Rheo: the sampled tail child
|
||||
* first (when the node carries it), then the deterministic ones. */
|
||||
static inline RAD_RRS_HD int rad_mtp_trav_try_slot(const RadTravTree& t, int v, int j) {
|
||||
const int nt = t.nt[v];
|
||||
if (nt < 0) return j;
|
||||
return t.tail[v] ? (j == 0 ? nt : j - 1) : j;
|
||||
}
|
||||
|
||||
/* The law node v's j-th tried child was drawn from, at support slot k. `isq` is the reciprocal of
|
||||
* rad_mtp_trav_try_norm: the sum of the node's remaining draft law (Gumbel) or of its tail's (rheo). */
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_try_norm(const RadTravTree& t, int v) {
|
||||
const int nt = t.nt[v];
|
||||
if (nt < 0) return rad_mtp_trav_sum8(t.qr[v]);
|
||||
double tail[8];
|
||||
for (int k = 0; k < 8; ++k) tail[k] = k >= nt ? t.qr[v][k] : 0.0;
|
||||
return rad_mtp_trav_sum8(tail);
|
||||
}
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_try_q(const RadTravTree& t, int v, int j, double isq,
|
||||
int k) {
|
||||
const int nt = t.nt[v];
|
||||
if (nt < 0) return t.qr[v][k] * isq;
|
||||
const int slot = rad_mtp_trav_try_slot(t, v, j);
|
||||
if (slot != nt) return k == slot ? 1.0 : 0.0; /* a deterministic child: a point mass */
|
||||
if (k < nt) return 0.0;
|
||||
const double q = nt == 0 ? t.qr[v][k] : t.qr[v][k] * isq;
|
||||
return q > 1.0 ? 1.0 : q; /* clamp: rounding must not push a one-token tail past 1 */
|
||||
}
|
||||
/* m / q for node v's j-th tried child at its own slot i, m the child's mass in the node's law: the
|
||||
* child's rate before the cap, in one division (m * sq / qr rather than m / (qr / sq)). Negative
|
||||
* when the law has no mass there (the child is not tried). */
|
||||
static inline RAD_RRS_HD double rad_mtp_trav_try_ratio(const RadTravTree& t, int v, int j, int i,
|
||||
double m) {
|
||||
const int nt = t.nt[v];
|
||||
const double q = t.qr[v][i];
|
||||
if (nt >= 0 && i != nt) return m; /* a point mass */
|
||||
if (!(q > 0)) return -1.0;
|
||||
if (nt == 0) return q < 1.0 ? m / q : m;
|
||||
const double sq = rad_mtp_trav_try_norm(t, v);
|
||||
return q < sq ? m * sq / q : m; /* the law's value is at most 1 */
|
||||
}
|
||||
|
||||
/* The walk over a prepared tree: the accepted path into path[0 .. *n_path). Returns false when
|
||||
* nothing was decided (an invalid root state: every row keeps the pick). `pos0` is the root row's
|
||||
* output position, the coordinate of the acceptance uniforms. Updates the tree in place: the last
|
||||
* node's m / moff are its residual law (up to the node's factor sc), which
|
||||
* rad_mtp_trav_final_pick reads. */
|
||||
static inline RAD_RRS_HD bool rad_mtp_trav_walk_tree(RadTravTree& t, uint64_t seed, uint64_t pos0,
|
||||
int* path, int* n_path,
|
||||
const RadMtpTravOpt& opt = RadMtpTravOpt{}) {
|
||||
int top = 0, tests = 0;
|
||||
t.stack[0] = 0;
|
||||
t.p[0] = 1.0;
|
||||
t.sc[0] = 1.0; /* the root's m is the target's law itself */
|
||||
*n_path = 0;
|
||||
if (!t.ok[0]) return false;
|
||||
for (;;) {
|
||||
const int v = t.stack[top];
|
||||
if (t.ok[v] && t.ci[v] < t.nk[v]) {
|
||||
const int j = t.ci[v];
|
||||
const int i = rad_mtp_trav_try_slot(t, v, j);
|
||||
/* p_c = min(1, p_v r(c) / qn(c)); control 1 drops p_v (token-level ratios) */
|
||||
const double f = opt.ctl == 1 ? (t.p[v] > 0 ? t.sc[v] / t.p[v] : 0.0) : t.sc[v];
|
||||
const double ratio = rad_mtp_trav_try_ratio(t, v, j, i, f * t.m[v][i]);
|
||||
const int c = top < RAD_MTP_TRAV_MAX_DEPTH && ratio >= 0 ? t.child[v][i] : -1;
|
||||
if (c < 0) { t.nk[v] = j; continue; } /* a child the verify no longer carries: cut here */
|
||||
const double pc = ratio < 1.0 ? ratio : 1.0;
|
||||
t.p[c] = pc;
|
||||
t.sc[c] = pc; /* the child's law becomes rate * law, when it is first needed */
|
||||
t.stack[++top] = c;
|
||||
continue;
|
||||
}
|
||||
/* a leaf: the sequence-level test */
|
||||
++tests;
|
||||
bool accept;
|
||||
if (opt.accept_at >= 0) {
|
||||
if (opt.p_test && tests <= opt.max_tests) opt.p_test[tests - 1] = t.p[v];
|
||||
if (opt.n_tests) *opt.n_tests = tests;
|
||||
accept = tests == opt.accept_at;
|
||||
} else {
|
||||
const double u = rad_spechub_uniform(
|
||||
seed, pos0, RAD_MTP_TRAV_KEY ^ rad_mtp_rrs_mix((uint64_t)tests));
|
||||
accept = u < t.p[v];
|
||||
}
|
||||
if (accept) {
|
||||
*n_path = top + 1;
|
||||
for (int i = 0; i <= top; ++i) path[i] = t.stack[i];
|
||||
return true;
|
||||
}
|
||||
if (top == 0) return false; /* the root always accepts (p = 1); only roundoff gets here */
|
||||
--top;
|
||||
const int g = t.stack[top];
|
||||
const int j = t.ci[g];
|
||||
const double isq = 1.0 / rad_mtp_trav_try_norm(t, g);
|
||||
const double pold = t.p[g], sc = t.sc[g];
|
||||
double d[8];
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
const double x = sc * t.m[g][k] - rad_mtp_trav_try_q(t, g, j, isq, k);
|
||||
d[k] = x > 0 ? x : 0;
|
||||
}
|
||||
const double moff = sc * t.moff[g];
|
||||
const double S = moff + rad_mtp_trav_sum8(d);
|
||||
if (!(S > 0) || !rad_spechub_finite(S)) {
|
||||
/* nothing of the target is left above the draft: this node cannot accept, nor a child of it */
|
||||
t.p[g] = 0;
|
||||
t.sc[g] = 0;
|
||||
} else {
|
||||
const double den = opt.ctl == 2 ? S : S + 1.0 - pold;
|
||||
const double inv = 1.0 / den;
|
||||
const double pn = S * inv;
|
||||
t.p[g] = pn < 1.0 ? pn : 1.0; /* a rate is at most 1: rounding may not push it past */
|
||||
for (int k = 0; k < 8; ++k) t.m[g][k] = d[k] * inv;
|
||||
t.moff[g] = moff * inv;
|
||||
t.sc[g] = 1.0;
|
||||
}
|
||||
/* Gumbel siblings are drawn WITHOUT replacement: the remaining Q renormalises */
|
||||
if (t.nt[g] < 0 && opt.ctl != 3) t.qr[g][j] = 0;
|
||||
++t.ci[g];
|
||||
}
|
||||
}
|
||||
|
||||
/* The final token of node v's residual law (in proportion to m on the support slots and moff off it:
|
||||
* the node's factor sc is common to both and cancels), by the uniform
|
||||
* u: the support slots first, in the canonical order, then the off-support candidates in slot
|
||||
* order. kind 0: no token (the row keeps the pick); 1: the token of support slot `slot`; 2: the
|
||||
* off-support candidate holding unit `t` of the row's off-support mass (rad_mtp_trav_off_token). */
|
||||
struct RadTravPick {
|
||||
int kind, slot;
|
||||
uint64_t t;
|
||||
};
|
||||
static inline RAD_RRS_HD RadTravPick rad_mtp_trav_final_pick(const RadTravTree& t, int v, double u) {
|
||||
RadTravPick o;
|
||||
o.kind = 0; o.slot = -1; o.t = 0;
|
||||
const double woff = t.moff[v];
|
||||
const double total = rad_mtp_trav_sum8(t.m[v]) + woff;
|
||||
if (!(total > 0) || !rad_spechub_finite(total)) return o;
|
||||
double c = u * total;
|
||||
int last = -1;
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
const double m = t.m[v][k];
|
||||
if (m > 0) {
|
||||
last = k;
|
||||
c -= m;
|
||||
if (c < 0) { o.kind = 1; o.slot = k; return o; }
|
||||
}
|
||||
}
|
||||
const uint64_t off = t.off[v];
|
||||
if (woff > 0 && off > 0) {
|
||||
const double frac = c / woff;
|
||||
uint64_t tt = frac < 1.0 ? rad_mtp_trav_d2u(frac * rad_mtp_trav_u2d(off)) : off - 1;
|
||||
if (tt >= off) tt = off - 1;
|
||||
o.kind = 2; o.t = tt;
|
||||
return o;
|
||||
}
|
||||
if (last >= 0) { o.kind = 1; o.slot = last; }
|
||||
return o;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- a tree behind an interface
|
||||
*
|
||||
* The tree the walk reads (a Tree type provides):
|
||||
* const RadMtpCoupleState* state(int v) the node's bound state, or null (node is a leaf)
|
||||
* bool cand(int v, const int32_t** ids, const float** val, int64_t* n) target candidates
|
||||
* int child(int v, int32_t token) the node's first child row with that token, or -1
|
||||
* int64_t vocab()
|
||||
* rad_mtp_trav_walk prepares the nodes the walk can reach (in discovery order, at most
|
||||
* RAD_MTP_TRAV_MAX_ROWS), walks and draws the final token: the host reference and the tests. */
|
||||
template <class Tree>
|
||||
static inline bool rad_mtp_trav_walk(const Tree& T, int root, uint64_t seed, uint64_t pos0,
|
||||
RadMtpTravOut* out, RadMtpTravOpt opt = RadMtpTravOpt{},
|
||||
RadTravTree* keep = nullptr, int* ids_out = nullptr) {
|
||||
RadTravTree local;
|
||||
RadTravTree& t = keep ? *keep : local;
|
||||
int id[RAD_MTP_TRAV_MAX_ROWS]; /* node -> the tree's own id */
|
||||
struct Row { const int32_t* ids; const float* val; int64_t n; };
|
||||
Row rows[RAD_MTP_TRAV_MAX_ROWS];
|
||||
t.n = 1;
|
||||
id[0] = root;
|
||||
for (int a = 0; a < t.n; ++a) {
|
||||
const int v = id[a];
|
||||
t.ok[a] = 0; t.nk[a] = 0; t.nt[a] = -1; t.tail[a] = 0; t.ci[a] = 0;
|
||||
t.moff[a] = 0; t.sc[a] = 1.0; t.p[a] = 0; t.off[a] = 0; t.top[a] = -INFINITY;
|
||||
for (int k = 0; k < 8; ++k) { t.child[a][k] = -1; t.ids[a][k] = -1; t.qr[a][k] = 0; t.m[a][k] = 0; }
|
||||
rows[a] = Row{ nullptr, nullptr, 0 };
|
||||
const RadMtpCoupleState* sp = T.state(v);
|
||||
if (!sp) continue;
|
||||
int swap = 0;
|
||||
if (!rad_mtp_trav_canon(*sp, opt.ctl, t.ids[a], t.qr[a], &t.nk[a], &t.nt[a], &t.tail[a], &swap)) continue;
|
||||
const int32_t* ids = nullptr; const float* val = nullptr;
|
||||
int64_t n = 0;
|
||||
if (!T.cand(v, &ids, &val, &n)) continue;
|
||||
rows[a] = Row{ ids, val, n };
|
||||
float top = -INFINITY;
|
||||
RadTravLaw w{};
|
||||
const bool valid = rad_mtp_trav_row_top(ids, val, n, T.vocab(), &top);
|
||||
if (valid) rad_mtp_trav_row_law(ids, val, n, top, t.ids[a], sp->count, &w);
|
||||
rad_mtp_trav_set_law(&t, a, valid, top, w);
|
||||
if (!t.ok[a]) continue;
|
||||
for (int k = 0; k < t.nk[a]; ++k) {
|
||||
const int c = T.child(v, t.ids[a][k]);
|
||||
if (c < 0 || t.n >= RAD_MTP_TRAV_MAX_ROWS) continue;
|
||||
t.child[a][k] = t.n;
|
||||
id[t.n++] = c;
|
||||
}
|
||||
}
|
||||
int path[RAD_MTP_TRAV_MAX_DEPTH + 1], np = 0;
|
||||
if (ids_out) for (int a = 0; a < t.n; ++a) ids_out[a] = id[a];
|
||||
if (!rad_mtp_trav_walk_tree(t, seed, pos0, path, &np, opt)) return false;
|
||||
out->n = np;
|
||||
for (int i = 0; i < np; ++i) out->node[i] = id[path[i]];
|
||||
out->has_y = false;
|
||||
const int f = path[np - 1];
|
||||
if (t.ok[f]) {
|
||||
const double ur = opt.u_final >= 0 ? opt.u_final
|
||||
: rad_spechub_uniform(seed, pos0 + (uint64_t)(np - 1), RAD_SAMPLE_KEY_RESID);
|
||||
const RadTravPick pk = rad_mtp_trav_final_pick(t, f, ur);
|
||||
if (pk.kind == 1) { out->y = t.ids[f][pk.slot]; out->has_y = true; }
|
||||
if (pk.kind == 2) {
|
||||
int cnt = 0;
|
||||
while (cnt < 8 && t.ids[f][cnt] >= 0) ++cnt;
|
||||
out->y = rad_mtp_trav_off_token(rows[f].ids, rows[f].val, rows[f].n, t.top[f], t.ids[f], cnt, pk.t);
|
||||
out->has_y = out->y >= 0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif /* __cplusplus */
|
||||
#endif /* RAD_MTP_TRAVERSAL_H */
|
||||
@@ -0,0 +1,55 @@
|
||||
/* rad_prefill_split.h -- host-pure live-KV prefill split law shared by libr4d launchers and
|
||||
* architecture pass-key callbacks. Keep this independent of HIP so callbacks can run before tape
|
||||
* lookup without a device copy or launch.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
|
||||
/* `bq` query positions per workgroup, `tile` keys per KV tile. `units` counts the workgroups that
|
||||
* do work: a ragged batch's grid is sized from its longest sequence, but a shorter sequence's
|
||||
* tiles past its end exit at once. Each split keeps at least eight tiles of the supplied context.
|
||||
*/
|
||||
static inline int rad_prefill_splits_law(int bq, int tile, int q_len, int total_q, int num_seqs,
|
||||
int kv_heads, int max_ctx, int wgps) {
|
||||
const long n = std::max(1, num_seqs);
|
||||
const long qt = std::min(n * ((std::max(1, q_len) + bq - 1) / bq),
|
||||
(std::max(1, total_q) + (long)(bq - 1) * n) / bq);
|
||||
const long units = (long)std::max(1, kv_heads) * std::max(1L, qt);
|
||||
if (units >= wgps) return 1;
|
||||
const int s1 = (int)(wgps / units), s2 = (int)(2L * wgps / units);
|
||||
int sp = s2 > 2 * s1 ? s2 : s1;
|
||||
const int cap = ((max_ctx > 0 ? max_ctx : (1 << 30) - 1) + tile - 1) / tile / 8;
|
||||
sp = std::min(sp, std::max(1, cap));
|
||||
return std::max(1, std::min(sp, 64));
|
||||
}
|
||||
|
||||
/* The launcher's live-context refinement of the initial model-bound law. */
|
||||
static inline int rad_prefill_splits_for_live(int bq, int tile, int q_len, int total_q,
|
||||
int num_seqs, int kv_heads, int max_ctx,
|
||||
int used_ctx, int wgps) {
|
||||
int splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, max_ctx,
|
||||
wgps);
|
||||
if (splits > 1 && used_ctx > 0 && (max_ctx <= 0 || used_ctx < max_ctx))
|
||||
splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, used_ctx,
|
||||
wgps);
|
||||
return splits;
|
||||
}
|
||||
|
||||
/* Fingerprint one actual launch tuple in packet-global sizes. Use this instead of the raw context
|
||||
* so equal split grids share a recording key as live context advances. */
|
||||
static inline uint64_t rad_prefill_grid_key(int q_len, int bq, int splits, int kv_heads,
|
||||
int num_seqs, int threads) {
|
||||
const uint64_t gx = (uint64_t)((std::max(1, q_len) + bq - 1) / bq) *
|
||||
(uint64_t)std::max(1, splits) * (uint64_t)threads;
|
||||
const uint64_t gy = (uint64_t)std::max(1, kv_heads);
|
||||
const uint64_t gz = (uint64_t)std::max(1, num_seqs);
|
||||
uint64_t h = 0x9e3779b97f4a7c15ull;
|
||||
const uint64_t grid[3] = {gx, gy, gz};
|
||||
for (uint64_t v : grid) {
|
||||
h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
|
||||
h *= 0xbf58476d1ce4e5b9ull;
|
||||
}
|
||||
return h | 1;
|
||||
}
|
||||
@@ -106,6 +106,15 @@ typedef struct RadQuantizerInfo {
|
||||
int rad_quant_count(void);
|
||||
const RadQuantizerInfo* rad_quant_at(int i);
|
||||
|
||||
/* Optional: the cards a quantiser may run on, as the HIP runtime numbers them (after
|
||||
* HIP_VISIBLE_DEVICES); none is the host alone, the state before any call. rad-convert calls it
|
||||
* once, after loading and before the first weight, with its --gpus list. A quantiser that uses a
|
||||
* card writes the same bytes it writes on the host, so a container does not depend on the machine
|
||||
* that converted it, and --reuse matches it either way. RAD_E_UNSUPPORTED: this build has no
|
||||
* device path; any other negative status refuses the list (a card that is not there). Symbol
|
||||
* name: `rad_quant_devices`. */
|
||||
typedef int (*RadQuantDevicesFn)(const int* ids, int n);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
+259
-10
@@ -22,6 +22,38 @@ typedef struct RadCtx RadCtx;
|
||||
* scheduler and the run phase the bounds without a device read. */
|
||||
enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 };
|
||||
|
||||
/* ================================================================== KV streaming */
|
||||
/* A streamed KV group keeps its whole context in pinned host memory and a ring of blocks on the
|
||||
* card (docs/KV-STREAMING.md). The step batch points every group that streams at this view, which
|
||||
* is fixed from bring-up (so a recorded pass replays a resolve); a resident group's is null.
|
||||
*
|
||||
* The mirror is laid out like the pool, layer by layer: layer l's row for block b is at
|
||||
* `host + l * host_layer_stride + b * block_bytes`. `res`, `slot_block`, `slot_state` and `ctl`
|
||||
* are device memory, read and rewritten by every resolve launch. */
|
||||
typedef struct RadKVStream {
|
||||
/* The mirror: pinned host memory a kernel reads over the link in place, every layer, zeroed at
|
||||
* bring-up. */
|
||||
uint8_t* host;
|
||||
/* Residency, one slice a layer: `res` is block -> ring slot or -1 (layer l at `res + l *
|
||||
* blocks`), `slot_block` is slot -> block or -1, `slot_state` is [slots, 2]: the epoch of a
|
||||
* slot's last use and its CLOCK reference bit. Per layer, because the resolve copies one
|
||||
* layer's bytes. */
|
||||
int32_t* res;
|
||||
int32_t* slot_block;
|
||||
int32_t* slot_state;
|
||||
/* The group's control block: epoch, clock hand, the last launch's miss count, the overflow
|
||||
* latch and cumulative counters (docs/OPS.md "kv_resolve"). */
|
||||
int32_t* ctl;
|
||||
/* Bytes one block of one layer occupies: the mirror's row pitch and the ring's slot pitch. */
|
||||
int64_t block_bytes;
|
||||
/* Bytes between one layer's mirror and the next. */
|
||||
int64_t host_layer_stride;
|
||||
/* The ring's depth in blocks; a selection names block ids over the whole context. */
|
||||
int64_t slots;
|
||||
/* The whole mirror's bytes, every layer. */
|
||||
int64_t host_bytes;
|
||||
} RadKVStream;
|
||||
|
||||
typedef struct RadKVGroupBatch {
|
||||
rad_kvgroup group;
|
||||
int32_t* slot_mapping; /* [n_tok] flat slot index per token, device */
|
||||
@@ -36,6 +68,10 @@ typedef struct RadKVGroupBatch {
|
||||
int64_t state_index_pitch;
|
||||
int64_t block_size;
|
||||
int64_t max_blocks;
|
||||
/* Null unless this group streams (RadKVStream). */
|
||||
const RadKVStream* stream;
|
||||
/* ABI 35: host mirror of seqused, retained through this batch for exact sliced-launch bounds. */
|
||||
const int32_t* seqused_h;
|
||||
} RadKVGroupBatch;
|
||||
|
||||
typedef struct RadBatch {
|
||||
@@ -85,7 +121,12 @@ typedef struct RadBatch {
|
||||
/* Speculative window (spec §10). n_spec == 0 for an ordinary decode step. */
|
||||
int n_spec; /* draft tokens per sequence this step */
|
||||
const int32_t* num_accepted; /* [n_seq] device, from the previous verify */
|
||||
const int32_t* spec_parent; /* [n_tok] device, tree layout; null for a linear chain */
|
||||
/* [n_tok] device; null for a linear chain. A tree verify (rad_drafter_tree): -2 marks an
|
||||
* ordinary causal row; any other entry is a node of its sequence's verify block and names its
|
||||
* parent by row within the sequence's rows (cu_seqlens), -1 for the block's first row, every
|
||||
* parent before its child. Inside its block such a row attends to itself and its ancestors
|
||||
* only (docs/OPS.md, attn_paged_tree). */
|
||||
const int32_t* spec_parent;
|
||||
|
||||
/* The draft pass. 0 is an ordinary step that runs the trunk; non-zero runs only the draft
|
||||
* head, and the sign gives the kind:
|
||||
@@ -135,9 +176,9 @@ typedef struct RadBatch {
|
||||
/* The longest query in each half. max_q_len over a mixed step is the prefill chunk's, and
|
||||
* banding the decode half with it would give eight rows a thousand-row GEMM's band.
|
||||
*
|
||||
* Only the decode value is currently read (by the GDN blocks). The prefill value is for a
|
||||
* block whose prefill path bands on a per-sequence query length; the GDN prefill ops band on
|
||||
* the step's total tokens, taken from their operands. */
|
||||
* The decode value is read by the GDN blocks and the fp8 gated attention's per-band issue
|
||||
* (rad_block_attn_gated_fp8.h), which also bands its prefill half on the prefill value; the
|
||||
* GDN prefill ops band on the step's total tokens, taken from their operands. */
|
||||
int32_t max_q_len_decode;
|
||||
int32_t max_q_len_prefill;
|
||||
|
||||
@@ -256,6 +297,72 @@ typedef struct RadBatch {
|
||||
* position tables per grid) reads them here; they live as long as the pass. */
|
||||
const int32_t* enc_seg_h;
|
||||
const int32_t* enc_seg_w;
|
||||
|
||||
/* ================================================ scored steps */
|
||||
|
||||
/* Non-zero when every row the sampler wants is a scored row (a /v1/systemone question: the raw
|
||||
* logits at a few candidate ids, the sampled token discarded) and the program declared where
|
||||
* the core finds the hidden rows and the head (rad_declare_scores). The plugin then skips its
|
||||
* lm_head and leaves `rad_declare_scores`' hidden buffer holding the gathered, final-normed
|
||||
* rows; the core computes the candidates' logits itself. Zero on every other step, and always
|
||||
* for a program that declared no scores. Appended; an older plugin never sees it set. */
|
||||
int32_t score_only;
|
||||
|
||||
/* ---- appended in ABI 32 (a request's words for the plugin) */
|
||||
/* Integer words a request hands the plugin whole (Request::plugin_words), for a head that
|
||||
* needs more of a request than its tokens: clef's joint schema head reads the prompt's
|
||||
* question and option spans and the option tokens (abi/rad_clef.h). Sequence s's words are
|
||||
* `plugin_words[plugin_cu[s] .. plugin_cu[s+1])`; a sequence with none has an empty range.
|
||||
* The engine writes the sequence's first sampled logits row of this step into word 0 of its
|
||||
* range, so the head can put its result beside that row's logits; the words after it are the
|
||||
* request's own. Carried only on the trunk step that samples a prompt's first token, so a
|
||||
* head runs once a request, when every prompt row has been computed.
|
||||
*
|
||||
* `plugin_words_h` and `plugin_cu_h` are the same words on the host, for a plugin that reads
|
||||
* counts before it issues; they live as long as the pass. All null, with `n_plugin_words`
|
||||
* 0, on a step no sequence of which carries words, and on every step of a program that
|
||||
* declared none (rad_declare_plugin_words). */
|
||||
int64_t n_plugin_words;
|
||||
const int32_t* plugin_words; /* [n_plugin_words] device */
|
||||
const int32_t* plugin_cu; /* [n_seq + 1] device */
|
||||
const int32_t* plugin_words_h;
|
||||
const int32_t* plugin_cu_h;
|
||||
|
||||
/* ---- appended in ABI 33 (the shape generator) */
|
||||
/* A shape generator's pass (rad_declare_shape_generator; `gen` is one of its
|
||||
* RAD_GEN_PASS_S*): its payload. Null on every other step. */
|
||||
const struct RadShapeGenBatch* sgen_b;
|
||||
|
||||
/* ---- appended in ABI 34: host-side max seqused per entry of kv[], for an architecture's
|
||||
* optional recorded-pass geometry key. Null when the batch has no host summary. */
|
||||
const int32_t* kv_used_max_h;
|
||||
/* ABI 35: host mirror of positions, for a one-sequence prefill op whose exact KV bound is the
|
||||
* position immediately after its first query piece. Valid through the batch's issue pass. */
|
||||
const int32_t* positions_h;
|
||||
/* ---- appended in ABI 35 (runs read both ways) */
|
||||
/* The runs of a trunk pass whose rows attend to each other both ways
|
||||
* (RadEncoderDecl::bidirectional): a picture's or a video frame's placeholders inside one
|
||||
* sequence's chunk. The pass attends them causally like every other row; the plugin attends a
|
||||
* run's rows again without the causal bound, over the keys before `bidi_used` (the position
|
||||
* after the run's last token), in place of that result. The scheduler ends no chunk inside such
|
||||
* a run, so its keys are this pass's or, after a prefix hit, the cache's; a run longer than any
|
||||
* step is cut where its chunk ends, and that chunk's rows see the run up to the cut.
|
||||
*
|
||||
* host: n_bidi and, per run, its first row in this pass, its rows and the index of its sequence
|
||||
* in the per-sequence arrays; device: [n_bidi] the keys a run's rows see. 0 runs on every other
|
||||
* pass. */
|
||||
int64_t n_bidi;
|
||||
const int32_t* bidi_row; /* host */
|
||||
const int32_t* bidi_n; /* host */
|
||||
const int32_t* bidi_seq; /* host */
|
||||
const int32_t* bidi_used; /* device */
|
||||
/* ---- appended in ABI 36 (a block drafter's anchor row) */
|
||||
/* A block drafter's query pass (draft_pass 1): [n_seq] device, for each drafting sequence the
|
||||
* row of its last committed position in the context pass just run, whose rows are the verify
|
||||
* step's in order. -1 for a row the card did not position. A drafter that conditions on the
|
||||
* context state at the anchor (LiLiCorr) gathers it there; the query rows themselves sit past
|
||||
* that position. Null on every other pass. */
|
||||
const int32_t* anchor_rows;
|
||||
} RadBatch;
|
||||
|
||||
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
|
||||
@@ -399,8 +506,13 @@ typedef struct RadGenBatch {
|
||||
|
||||
/* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */
|
||||
enum {
|
||||
RAD_GEN_COND_REBALANCE = 1 /* the conditioning at the plugin's fixed rebalance gains (the
|
||||
RAD_GEN_COND_REBALANCE = 1, /* the conditioning at the plugin's fixed rebalance gains (the
|
||||
* request field `rebalance`; Krea 2: its text taps) */
|
||||
/* which of the plugin's rebalance presets, beside RAD_GEN_COND_REBALANCE: 0 its default
|
||||
* gains, Krea 2: 1 balanced, 2 detail, 3 subtle (arch/krea2). A plugin declares these bits in
|
||||
* RadGeneratorDecl::cond_opts when it has presets. */
|
||||
RAD_GEN_COND_REBALANCE_PRESET = 0xff00,
|
||||
RAD_GEN_COND_REBALANCE_PRESET_SHIFT = 8
|
||||
};
|
||||
|
||||
/* An entry's flags on a DENOISE pass. */
|
||||
@@ -489,6 +601,33 @@ typedef struct RadAudioGenBatch {
|
||||
/* VOCODE with RadAudioGenDecl::voc_chunk: the lane's first frame the pass reads, counted
|
||||
* from the first kept frame. 64 bits so that it starts past the struct's ABI 18 end. */
|
||||
int64_t voc_frame0;
|
||||
|
||||
/* ---- appended in ABI 27 (a frame head at the previous row, references) */
|
||||
/* FRAME, one value per entry ([n_seq]): the row before the frame's own row -- the one whose
|
||||
* hidden state the frame is sampled from -- as its KV slot, its position, and the context
|
||||
* through it (position + 1). A model whose frame head attends at that row (Fish Audio
|
||||
* drama-3's codebook tower, layers bound to the language model's full-attention group) issues
|
||||
* those layers there, before the language model runs at the frame's own row. */
|
||||
const int32_t* prev_slot;
|
||||
const int32_t* prev_pos;
|
||||
const int32_t* prev_used;
|
||||
|
||||
/* PROMPT of a request with references (RadAudioGenDecl::tmpl_ref; n_ref 0 without): its
|
||||
* clips' samples end to end (`ref_samples` f32 on the device), the clips' bounds in samples
|
||||
* ([n_ref + 1], each a whole number of RadAudioGenDecl::ref_hop), and for every row of the
|
||||
* pass the frame of the clips it is or -1 for a token row ([n_tok]), frames counted over the
|
||||
* clips in order, frame f the samples [f ref_hop, (f + 1) ref_hop). A frame's row stages
|
||||
* token 0; the plugin embeds the frame there instead. */
|
||||
int64_t n_ref;
|
||||
int64_t ref_samples;
|
||||
const float* ref_audio;
|
||||
const int32_t* ref_cu;
|
||||
const int32_t* ref_cu_h;
|
||||
const int32_t* ref_frame;
|
||||
const int32_t* ref_frame_h;
|
||||
/* ABI 40: PROMPT branch boundaries on the host, [n_seq + 1], including unequal
|
||||
* reference-direction branches. Same rows as RadBatch::cu_seqlens on device. */
|
||||
const int32_t* prompt_cu_h;
|
||||
} RadAudioGenBatch;
|
||||
|
||||
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
|
||||
@@ -510,8 +649,11 @@ enum {
|
||||
* ADECODE no rows of the pass's own.
|
||||
* VDECODE `dec_rows` rows of the decoder's own (rad_arch_video_positions, RAD_VPOS_DECODE).
|
||||
* VUPSCALE no rows of the pass's own: the lane's video latent from `geom_from` to `geom`.
|
||||
* VENCODE no rows of the pass's own: a picture's or a video's frames in `enc_pixels`.
|
||||
* AENCODE no rows of the pass's own: a soundtrack's samples in `enc_samples`.
|
||||
*
|
||||
* Every pointer is device memory unless the name ends in _h. */
|
||||
|
||||
typedef struct RadVideoGenBatch {
|
||||
int32_t lane;
|
||||
RadVideoGeom geom; /* the request's geometry */
|
||||
@@ -520,9 +662,10 @@ typedef struct RadVideoGenBatch {
|
||||
/* The same lane, i32 [1], and 1 on a request's first step (0 otherwise), i32 [1]. */
|
||||
const int32_t* lane_d;
|
||||
const int32_t* first_d;
|
||||
/* i32 [4]: the packed sequence's segments, {0, n_text, n_text + audio rows, n_tok} -- text,
|
||||
* soundtrack, video -- and i32 [4] {0, video rows, 0, audio rows}, the bounds of the lane's two
|
||||
* latents counted from each one's first row. */
|
||||
/* i32: the packed sequence's segment boundaries, {0, n_text, n_text + audio rows, n_tok} --
|
||||
* text, soundtrack, video -- or rad_arch_video_pack's for a request with references; and i32
|
||||
* [4] {0, video rows, 0, audio rows}, the bounds of the lane's two latents counted from each
|
||||
* one's first row. */
|
||||
const int32_t* seg_cu;
|
||||
const int32_t* lat_cu;
|
||||
|
||||
@@ -533,7 +676,8 @@ typedef struct RadVideoGenBatch {
|
||||
|
||||
/* ---- VSTEP */
|
||||
int32_t step; /* from 0; the first draws the lane's noise */
|
||||
/* f32 [6]: the video's timestep, sigma and next sigma, then the soundtrack's. */
|
||||
/* f32 [16]: the video's timestep, sigma and next sigma, then the soundtrack's; from [6] the
|
||||
* res_multistep scalars of the video, then of the soundtrack (`sampler`, below). */
|
||||
const float* sched;
|
||||
const float* pos; /* f32 [3, n_tok]: RAD_VPOS_STEP */
|
||||
/* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first (VSTEP, VUPSCALE and
|
||||
@@ -573,8 +717,94 @@ typedef struct RadVideoGenBatch {
|
||||
/* VDECODE: the decoder the request named (RadVideoGenDecl::decoders), its index; 0 the
|
||||
* default. */
|
||||
int32_t decoder;
|
||||
|
||||
/* ---- appended in ABI 31 (rad_builder.h, "Reference conditioning") */
|
||||
/* The sampler a VSTEP advances the latents with: RAD_SAMPLER_EULER, the first-order step on
|
||||
* sched[0..5], or RAD_SAMPLER_RES_MULTISTEP, the second-order one on the clean estimate
|
||||
* (k-diffusion's res_multistep at eta 0), which keeps the previous step's estimate. Its scalars
|
||||
* are sched[6..10] for the video and sched[11..15] for the soundtrack: sigma, r = next sigma /
|
||||
* sigma, the weights hb1 and hb2 of this step's estimate and the previous one, and the order,
|
||||
* 1 where there is no previous estimate on the same grid. */
|
||||
int32_t sampler;
|
||||
/* VENCODE: f32 [enc_frames, enc_height, enc_width, 3] RGB in 0..255, the frames padded to
|
||||
* whole clips by repeating the last (rad_arch_encode_geom's entry 23). AENCODE: f32
|
||||
* [enc_channels, enc_n_samples], each channel padded with zeros to the hop (entry 0). Both:
|
||||
* the pass's geometry as rad_arch_encode_geom gave it, i32 in pinned host memory also readable
|
||||
* by device kernels (mixed-site encoders share it), and the media's
|
||||
* kind (RAD_ENC_*, below) and its number within the kind from 1. */
|
||||
const float* enc_pixels;
|
||||
int32_t enc_frames, enc_height, enc_width;
|
||||
const float* enc_samples;
|
||||
int64_t enc_n_samples;
|
||||
int32_t enc_channels;
|
||||
const int32_t* enc_geom_d;
|
||||
int32_t enc_kind, enc_slot;
|
||||
/* VCOND and VSTEP of a request with reference media or keyframes: their table, host i32, null
|
||||
* without. [0] the references, [1] the keyframes, then 6 words a reference {kind, slot, latent
|
||||
* height, latent width, latent frames, soundtrack latents} in presentation order and 3 a
|
||||
* keyframe {frame, latent frames, soundtrack latents}, then the prompt's vision pads: a count
|
||||
* and {first token, tokens} of each picture's run. A reference's kind is RAD_VREF_PICTURE,
|
||||
* _AUDIO or _VIDEO; its slot is its encode pass's. */
|
||||
const int32_t* ref_tab;
|
||||
/* VSTEP: i32, rad_arch_video_pack's `mod`: the boundaries of the modulation groups, then the
|
||||
* cell each reads; `seg_cu` then holds the segment boundaries. A request without references
|
||||
* stages `seg_cu`'s four and no cells. */
|
||||
const int32_t* mod_cu;
|
||||
} RadVideoGenBatch;
|
||||
|
||||
enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1 };
|
||||
|
||||
/* What a shape generator's pass carries beside the step batch's own fields (rad_builder.h,
|
||||
* RadShapeGenDecl, describes the passes). Every pass is one request's, in lane `lane`:
|
||||
*
|
||||
* SCOND `n_tok` is the picture's patches, `patches` [n_tok, 3 enc_patch^2] f32.
|
||||
* SSTEP `n_tok` is step_rows. The two branches' latents are entries 0 (the picture's) and 1
|
||||
* (the unconditioned one) of the image generator's sampler ops (`randn_lanes`,
|
||||
* `lane_gather`, `flow_euler`): `lat_cu` bounds them and the per-entry arrays are
|
||||
* theirs, entry 0 guided against entry 1 (`pair` {1, -2}) at the request's scale.
|
||||
* SLATENT `n_tok` is latent_rows; nothing of the pass's own.
|
||||
* SQUERY `n_tok` is n_query, `query` [n_query, 3] f32: x, y, z a point, and `query_cu`
|
||||
* {0, n_query}.
|
||||
*
|
||||
* `lanes` and `lat_cu` are staged on every pass; the latent's rows are lat_cu[0..1]. Every
|
||||
* pointer is device memory. */
|
||||
typedef struct RadShapeGenBatch {
|
||||
int32_t lane;
|
||||
|
||||
/* ---- SCOND */
|
||||
const float* patches;
|
||||
|
||||
/* ---- SSTEP: the step (from 0) of the request's `n_steps` evaluations, then the two
|
||||
* entries' sampler operands, [2] each but `seed` [2, 2] (low word first) and `lat_cu` [3]. */
|
||||
int32_t step, n_steps;
|
||||
const float* sigma;
|
||||
const float* sigma_next;
|
||||
const float* cfg;
|
||||
const int32_t* pair;
|
||||
const int32_t* lanes;
|
||||
const int32_t* flags; /* RAD_GEN_F_FIRST on entry 0 of the first step */
|
||||
const uint32_t* seed;
|
||||
const int32_t* lat_cu;
|
||||
|
||||
/* ---- SQUERY */
|
||||
int64_t n_query;
|
||||
const float* query;
|
||||
const int32_t* query_cu;
|
||||
} RadShapeGenBatch;
|
||||
|
||||
/* RadVideoGenBatch::enc_kind: the media an encode pass carries, numbered from 1 within a kind. A
|
||||
* keyframe is 1 for the first frame and 2 for the last. */
|
||||
enum {
|
||||
RAD_ENC_IMAGE = 1, /* a reference picture; Vencode */
|
||||
RAD_ENC_VIDEO = 2, /* a reference video; Vencode */
|
||||
RAD_ENC_VAUDIO = 3, /* the soundtrack of reference video `enc_slot`; Aencode */
|
||||
RAD_ENC_AUDIO = 4, /* a standalone soundtrack; Aencode */
|
||||
RAD_ENC_KEYFRAME = 5 /* a first or last frame; Vencode */
|
||||
};
|
||||
|
||||
/* RadVideoGenBatch::ref_tab: a reference's kind. */
|
||||
enum { RAD_VREF_PICTURE = 0, RAD_VREF_AUDIO = 1, RAD_VREF_VIDEO = 2 };
|
||||
|
||||
/* RadVideoGenBatch::geom_d. The request's latent geometry, then a VDECODE pass's chunk: the latent
|
||||
* frames it reads (from latent frame `chunk_lat0`), its latent grid again so that (frames, h, w,
|
||||
* first, last) is one run, and the same chunk in patches. */
|
||||
@@ -681,7 +911,8 @@ int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n)
|
||||
* the all-reduce numbers its scratch slots per launch and the ranks must agree; a kernel with a
|
||||
* device-wide arrival counter must key it on the stream (libr4d's split-K GEMM does), or it may
|
||||
* not run here; and every buffer the second lane touches must be named to rad_buf_concurrent,
|
||||
* because the planner packs transients from one linear order. */
|
||||
* because the planner packs transients from one linear order (live for the whole program, or across
|
||||
* the second lane's window where the architecture declares one, abi/rad_builder.h). */
|
||||
int rad_lane(RadCtx* c, int lane);
|
||||
int rad_lane_join(RadCtx* c, int from, int to);
|
||||
|
||||
@@ -696,8 +927,26 @@ int rad_step_fail(RadCtx* c, const char* what);
|
||||
|
||||
/* ================================================================== run-phase queries */
|
||||
const RadBatch* rad_batch(RadCtx* c);
|
||||
/* The position of model layer `layer` among `group`'s bound layers, or -1 when this rank has no
|
||||
* pool for it or the group does not hold the layer: the lookup a RAD_KV operand makes, and the
|
||||
* index of the layer's host mirror row. Bound layers need not be contiguous. */
|
||||
int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer);
|
||||
/* Prefill staging of a streamed group (the ordering rule is in core/kvstream/stage.h).
|
||||
* rad_kv_stage_layer, before the layer's store: when the pass uses the one-layer stage view, make
|
||||
* the layer's mirror row whole in it (once a pass) and return 1, after which the caller reads
|
||||
* block ids directly and must not resolve; 0 when the group has no stage view.
|
||||
* rad_kv_stage_next, after every attention launch of the layer: start the next layer's copy. */
|
||||
int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb,
|
||||
int layer);
|
||||
int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer);
|
||||
int rad_rank(RadCtx* c);
|
||||
/* The instance's slot, rad_build_slot() of the declare that built it: what a plugin indexes its
|
||||
* per-instance state by. */
|
||||
int rad_slot(RadCtx* c);
|
||||
int rad_world_size(RadCtx* c);
|
||||
/* Workgroups the current rank's card can run concurrently (HIP multiProcessorCount on RDNA;
|
||||
* 32 on the host backend or when the backend has no positive count). */
|
||||
int rad_ctx_wgp_count(RadCtx* c);
|
||||
RadStream rad_stream(RadCtx* c);
|
||||
|
||||
/* The routing result for a MoE layer, resolved on device against the current residency table.
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
/* rad_spechub.h -- the speculative coupling (linear MTP and DFlash2's block walk): wire rows and
|
||||
* the shared arithmetic.
|
||||
*
|
||||
* The core writes these rows and a kernel plugin reads them, so their layout is ABI. The helpers
|
||||
* are header-only and stateless, so the host reference, the device kernel and the sampler share
|
||||
* one definition of the wire and of the arithmetic that turns it into a token.
|
||||
*
|
||||
* A row lives in a U32 plane whose base and row stride are eight-byte aligned, so a state can be
|
||||
* loaded whole on the device.
|
||||
*/
|
||||
#ifndef RAD_SPECHUB_H
|
||||
#define RAD_SPECHUB_H
|
||||
|
||||
#include <math.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* The verify reads a RadSampleParams row. */
|
||||
#include "rad_sample.h"
|
||||
|
||||
/* Linear MTP coupling (--draft-coupling on). One draw per drafting row, staged before the
|
||||
* serial passes; one state per (temporal round, row). `base` is the request's PRE-commit output
|
||||
* size, so (base, round) names one draft stream that no later step reuses. `card` is the step slot
|
||||
* the advance writes, checked against RadBatch::seq_ids. `mode` 1 samples x~Q; 0 keeps the greedy
|
||||
* proposal (temperature 0 or top_k 1). */
|
||||
typedef struct RadMtpCoupleDraw {
|
||||
uint64_t seed, base, seq;
|
||||
int32_t card;
|
||||
uint32_t mode;
|
||||
} RadMtpCoupleDraw;
|
||||
/* status 1: x sampled from the exact q[] stored here; 0: greedy proposal kept; -1: malformed
|
||||
* shortlist or row identity, greedy proposal kept. `pos` is the verify row's output position, bound
|
||||
* by the host after commit; the device writes 0. ids[count..7] = -1, q[count..7] = 0. */
|
||||
typedef struct RadMtpCoupleState {
|
||||
RadMtpCoupleDraw draw;
|
||||
uint64_t pos;
|
||||
int32_t status, round, x, count;
|
||||
int32_t ids[8];
|
||||
double q[8];
|
||||
/* The node drafted `nkids` children, sampled without replacement from q, and ids[0 .. nkids) are
|
||||
* them in draft order (x == ids[0]; ids[nkids .. count) the rest of the support). nkids <= 1 is
|
||||
* the linear chain's single draw, whose ids keep the shortlist's order, and what the serial
|
||||
* MTP head writes (abi/rad_mtp_rrs.h states the siblings' law; the traversal walk of
|
||||
* abi/rad_mtp_traversal.h reads it). Zero from every writer that is not a sibling draw. */
|
||||
int32_t nkids;
|
||||
/* The sibling scheme of those children: 0 = Gumbel-top-k without replacement (the only one a
|
||||
* writer in this engine produces), m + 1 = RheoSampling's m deterministic top-q children plus one
|
||||
* sampled from the tail law (abi/rad_mtp_rrs.h). Zero from every other writer. */
|
||||
int32_t scheme;
|
||||
/* --draft-verify block (abi/rad_mtp_block.h): the length g of the block this row's chain is
|
||||
* verified as one (the rows 0 .. g-1 bound to rounds 1 .. g, staged on every row of it); 0 for
|
||||
* token-by-token verification. Written by the sampler's staging only; zero from the device. */
|
||||
int32_t blk;
|
||||
int32_t pad_;
|
||||
} RadMtpCoupleState;
|
||||
#define RAD_MTP_COUPLE_MAX_RHEO_M 7
|
||||
#define RAD_MTP_COUPLE_DRAW_WORDS (sizeof(RadMtpCoupleDraw) / 4)
|
||||
#define RAD_MTP_COUPLE_STATE_WORDS (sizeof(RadMtpCoupleState) / 4)
|
||||
#define RAD_MTP_COUPLE_MAX_ROUNDS 8
|
||||
/* Draft stream of round r: seed ^ (KEY_DRAFT + r) at coordinate `base`. Acceptance and the
|
||||
* residual draw use RAD_SAMPLE_KEY_ACCEPT / RAD_SAMPLE_KEY_RESID at the verify position. */
|
||||
#define RAD_MTP_COUPLE_KEY_DRAFT 0x4d5450434f55504cull
|
||||
#ifdef __cplusplus
|
||||
static_assert(sizeof(RadMtpCoupleDraw) == 32, "MTP coupling draw wire");
|
||||
static_assert(sizeof(RadMtpCoupleState) == 168, "MTP coupling state wire");
|
||||
static_assert(offsetof(RadMtpCoupleState, q) % 8 == 0, "MTP coupling q alignment");
|
||||
#endif
|
||||
|
||||
/* ================================================================== the shared arithmetic
|
||||
*
|
||||
* Q is the FP64 softmax of an FP32 shortlist at temperature 1; P is the FP64 softmax of the
|
||||
* sampler's FP32 candidate logits; uniforms are 53-bit. A coupled row therefore realises the
|
||||
* filtered target law to FP64 rounding rather than sample_pick's FP32/24-bit law, and is not
|
||||
* seed-identical to the ordinary pick.
|
||||
*/
|
||||
#ifdef __cplusplus
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_SPECHUB_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_SPECHUB_HD
|
||||
#endif
|
||||
|
||||
static inline RAD_SPECHUB_HD double rad_spechub_positive(double a) { return a > 0 ? a : 0; }
|
||||
static inline RAD_SPECHUB_HD bool rad_spechub_finite(double x) {
|
||||
return x == x && x <= 1.7976931348623157e308 && x >= -1.7976931348623157e308;
|
||||
}
|
||||
|
||||
/* A 53-bit uniform in [0, 1): splitmix64 over (seed ^ key, pos), top 53 bits scaled by 2^-53. */
|
||||
static inline RAD_SPECHUB_HD double rad_spechub_uniform(uint64_t seed, uint64_t pos, uint64_t key) {
|
||||
uint64_t z = (seed ^ key) * 0x9e3779b97f4a7c15ull + pos + 0x9e3779b97f4a7c15ull;
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
|
||||
z ^= z >> 31;
|
||||
return (double)(z >> 11) * 0x1p-53;
|
||||
}
|
||||
|
||||
/* Is `s` a state the coupling's propose kernel could have written for a sampled row? The verifier
|
||||
* and the engine's bind check refuse a row by this rule, on the device and on the host. */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleState& s,
|
||||
int64_t vocab) {
|
||||
if (s.status != 1 || s.draw.mode != 1 || s.count < 1 || s.count > 8 || s.round < 1 ||
|
||||
s.round > RAD_MTP_COUPLE_MAX_ROUNDS)
|
||||
return false;
|
||||
double sum = 0;
|
||||
bool has_x = false;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (i >= s.count) {
|
||||
if (s.ids[i] != -1 || s.q[i] != 0) return false;
|
||||
continue;
|
||||
}
|
||||
if (s.ids[i] < 0 || s.ids[i] >= vocab || !rad_spechub_finite(s.q[i]) || !(s.q[i] > 0) ||
|
||||
s.q[i] > 1)
|
||||
return false;
|
||||
for (int j = 0; j < i; ++j)
|
||||
if (s.ids[j] == s.ids[i]) return false;
|
||||
sum += s.q[i];
|
||||
has_x |= s.ids[i] == s.x;
|
||||
}
|
||||
if (s.nkids < 0 || s.nkids > s.count || (s.nkids >= 2 && s.ids[0] != s.x)) return false;
|
||||
if (s.scheme < 0 || s.scheme > RAD_MTP_COUPLE_MAX_RHEO_M + 1 || (s.scheme && s.nkids >= 1 && s.ids[0] != s.x))
|
||||
return false;
|
||||
return has_x && (sum - 1) <= 1e-12 && (1 - sum) <= 1e-12;
|
||||
}
|
||||
|
||||
/* The verify position of coupled round r (1-based): the coordinate the engine's bind and the
|
||||
* sampler's row check must agree on.
|
||||
*
|
||||
* The sampler stages row k of a request at output position `n_out + k`, where `n_out` is the
|
||||
* request's committed output length when the step is built; round r is verified at row r - 1. The
|
||||
* acceptance and residual uniforms are drawn at this position.
|
||||
*
|
||||
* `n_out` is read from the request after the drafting step's commit. It is not rebuilt from the
|
||||
* draft's pre-commit `base` plus the accepted count: the two differ when the commit emits fewer
|
||||
* tokens than the card accepted (a max_tokens or context cut) or a step is carried. */
|
||||
static inline RAD_SPECHUB_HD uint64_t rad_mtp_couple_verify_pos(uint64_t n_out, int round) {
|
||||
return n_out + (round > 0 ? (uint64_t)(round - 1) : 0);
|
||||
}
|
||||
|
||||
/* Would the verify row for draft index `k` (0-based) of a request with committed output length
|
||||
* `n_out` take `c` as its coupled state? Same request and seed, the round this row's draft came
|
||||
* from, the position it samples, the very token it proposes, and a state the proposer could have
|
||||
* written. Anything else is a stale state from another step, and coupling against it would apply a
|
||||
* law this step never drew.
|
||||
*
|
||||
* Asked by the sampler's step build, against the state the engine bound. The engine's own bind
|
||||
* does not call it: it checks the readback against the card (draw, round, x, status) and writes
|
||||
* the position with rad_mtp_couple_verify_pos, the formula here that both sides must agree on. */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_binds(const RadMtpCoupleState& c, uint64_t seq,
|
||||
uint64_t seed, uint64_t n_out, int k,
|
||||
int32_t draft_x, int64_t vocab) {
|
||||
return c.status == 1 && c.draw.seq == seq && c.draw.seed == seed && c.round == k + 1 &&
|
||||
c.pos == rad_mtp_couple_verify_pos(n_out, k + 1) && c.x == draft_x &&
|
||||
rad_mtp_couple_state_valid(c, vocab);
|
||||
}
|
||||
|
||||
/* Build the stored Q from a shortlist of eight (id, score) slots.
|
||||
*
|
||||
* Holes (id < 0) and -inf scores carry no mass. An entry whose FP64 weight or normalized q
|
||||
* underflows to zero is dropped, so the stored q[] is exactly the law the draw walks. False on an
|
||||
* out-of-range id, NaN/+inf score, duplicate id or empty support (s->count = 0). */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_build_q(const int32_t* ids, const float* val,
|
||||
int64_t vocab, RadMtpCoupleState* s) {
|
||||
int32_t kid[8];
|
||||
float kv[8];
|
||||
int n = 0;
|
||||
s->count = 0;
|
||||
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (ids[i] < 0) continue;
|
||||
if (ids[i] >= vocab || val[i] != val[i] || val[i] == INFINITY) return false;
|
||||
if (val[i] == -INFINITY) continue;
|
||||
for (int j = 0; j < n; ++j)
|
||||
if (kid[j] == ids[i]) return false;
|
||||
kid[n] = ids[i];
|
||||
kv[n++] = val[i];
|
||||
}
|
||||
if (!n) return false;
|
||||
float top = kv[0];
|
||||
for (int j = 1; j < n; ++j)
|
||||
if (kv[j] > top) top = kv[j];
|
||||
double w[8], sum = 0;
|
||||
for (int j = 0; j < n; ++j) { w[j] = ::exp((double)kv[j] - top); sum += w[j]; }
|
||||
for (int j = 0; j < n; ++j) {
|
||||
const double q = w[j] / sum;
|
||||
if (q > 0) { s->ids[s->count] = kid[j]; s->q[s->count++] = q; }
|
||||
}
|
||||
return s->count > 0;
|
||||
}
|
||||
|
||||
/* Inverse CDF over the stored q with a uniform in [0, 1); index into ids. */
|
||||
static inline RAD_SPECHUB_HD int rad_mtp_couple_pick(const RadMtpCoupleState& s, double u) {
|
||||
double total = 0;
|
||||
for (int i = 0; i < s.count; ++i) total += s.q[i];
|
||||
double c = u * total;
|
||||
for (int i = 0; i < s.count; ++i) { c -= s.q[i]; if (c < 0) return i; }
|
||||
return s.count - 1;
|
||||
}
|
||||
|
||||
/* Residual mass r(y) = max(0, P(y) - Q(y)) of one candidate. Q tokens use their P aggregated over
|
||||
* duplicate candidates, counted once at the first occurrence (`seen`). */
|
||||
static inline RAD_SPECHUB_HD double rad_mtp_couple_mass(const RadMtpCoupleState& s, const double* pq,
|
||||
int32_t id, float v, float top, double sum,
|
||||
unsigned* seen) {
|
||||
if (id < 0 || v == -INFINITY) return 0;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (s.ids[k] == id) {
|
||||
if (*seen & (1u << k)) return 0;
|
||||
*seen |= 1u << k;
|
||||
return rad_spechub_positive(pq[k] - s.q[k]);
|
||||
}
|
||||
return ::exp((double)v - top) / sum;
|
||||
}
|
||||
|
||||
/* The maximal coupling of the target's law P (over the surviving candidates) with the draft's Q.
|
||||
* Writes the emitted token to *out and returns true, or returns false for an invalid or empty
|
||||
* target. u_accept and u_resid are independent uniforms in [0, 1).
|
||||
*
|
||||
* The draft x is kept when P dominates Q on every Q token or when u_accept * Q(x) < P(x); otherwise
|
||||
* the token is drawn from the residual (P - Q)+. The emitted token is distributed as P, and it
|
||||
* equals x with probability sum min(P, Q).
|
||||
*
|
||||
* If FP64 cancellation leaves the residual total R at 0 while some Q token has P < Q, P is sampled
|
||||
* directly in FP64 with u_resid. That branch depends on (P, Q) only, never on x or a uniform.
|
||||
*
|
||||
* R sums r over every candidate including x. The residual walk runs only when P(x) < Q(x), where
|
||||
* r(x) is exactly +0, so skipping x in the walk leaves its total equal to R bit for bit. */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_decide(const RadMtpCoupleState& s,
|
||||
const int32_t* ids, const float* val,
|
||||
int64_t n, int64_t vocab, double u_accept,
|
||||
double u_resid, int32_t* out) {
|
||||
float top = -INFINITY;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0) continue;
|
||||
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
|
||||
if (val[j] > top) top = val[j];
|
||||
}
|
||||
if (top == -INFINITY) return false;
|
||||
double sum = 0, pq[8] = {};
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
const double w = ::exp((double)val[j] - top);
|
||||
sum += w;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (ids[j] == s.ids[k]) { pq[k] += w; break; }
|
||||
}
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
|
||||
int ix = -1;
|
||||
bool dominated = true;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
pq[k] /= sum;
|
||||
dominated = dominated && pq[k] >= s.q[k];
|
||||
if (s.ids[k] == s.x) ix = k;
|
||||
}
|
||||
if (ix < 0) return false; /* unreachable for a rad_mtp_couple_state_valid state */
|
||||
unsigned seen = 0;
|
||||
double resid = 0;
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
resid += rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen);
|
||||
if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) {
|
||||
double c = u_resid * sum;
|
||||
int32_t last = -1;
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
if (ids[j] >= 0 && val[j] != -INFINITY) {
|
||||
const double w = ::exp((double)val[j] - top);
|
||||
if (w > 0) { last = ids[j]; c -= w; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
*out = last;
|
||||
return true;
|
||||
}
|
||||
if (pq[ix] >= s.q[ix] || u_accept * s.q[ix] < pq[ix]) { *out = s.x; return true; }
|
||||
/* Rejected, so P(x) < Q(x): not dominated, resid > 0, and some y != x has mass > 0 below. */
|
||||
double c = u_resid * resid;
|
||||
int32_t last = -1;
|
||||
seen = 0;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] == s.x) continue;
|
||||
const double m = rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen);
|
||||
if (m > 0) { last = ids[j]; c -= m; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
*out = last;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ================================================================== DFlash2's coupled walk
|
||||
*
|
||||
* The block drafter's counterpart of mtp_couple_propose (`dflash_couple_propose`). DFlash2 proposes
|
||||
* a block in one pass and `dflash_select` walks its candidate lattice greedily: at draft position l
|
||||
* every candidate c of that position scores
|
||||
*
|
||||
* score[l, c] = unary[l, c] + sum_r pred[pid][r] * hp[l][r] * succ[cand[l, c]][r]
|
||||
*
|
||||
* with pid the anchor at l = 0 and the walk's own previous token after it. The coupled walk scores
|
||||
* the same lattice but SAMPLES each position instead of taking its argmax:
|
||||
*
|
||||
* Q_l = the FP64 softmax of score[l, c] / q_temp over the eight best-scoring candidates whose
|
||||
* ids are in the vocabulary (rad_mtp_couple_build_q), x_l ~ Q_l at the draw's
|
||||
* (seed, base, KEY_DRAFT + l + 1), and pid = x_l for position l + 1.
|
||||
*
|
||||
* Q_l depends on the committed text (through the drafter's pass and the anchor) and on x_0..x_{l-1},
|
||||
* never on the target's verification, and it is stored exactly in the state row the verify reads,
|
||||
* which is all the maximal coupling needs to be exact (rad_mtp_couple_decide). The pairwise term is
|
||||
* what makes Q_l follow the walk's own earlier samples rather than the drafter's marginal.
|
||||
*
|
||||
* Bit-identical on host and device: each candidate's edge is RAD_DFLASH_EDGE_PARTS partial sums,
|
||||
* each a serial fmaf chain over a contiguous slice of the rank, added in order and then to the unary
|
||||
* score. The plugin builds with -ffp-contract=off, so nothing else is fused. */
|
||||
#define RAD_DFLASH_EDGE_PARTS 8
|
||||
#define RAD_DFLASH_COUPLE_MAX_K 32
|
||||
#define RAD_DFLASH_COUPLE_MAX_R 512
|
||||
|
||||
static inline RAD_SPECHUB_HD float rad_dflash_bf2f(uint16_t h) {
|
||||
union { uint32_t u; float f; } c;
|
||||
c.u = (uint32_t)h << 16;
|
||||
return c.f;
|
||||
}
|
||||
|
||||
/* Part `j` of one candidate's edge: a[r] * succ_row[r] over r in [j*R/P, (j+1)*R/P), fmaf in order.
|
||||
* `a` is the candidate-independent half, pred[pid][r] * hp[r] (or pred[pid][r] with no hp, 0 for a
|
||||
* predecessor outside the vocabulary). */
|
||||
static inline RAD_SPECHUB_HD float rad_dflash_edge_part(const float* a, const uint16_t* succ_row,
|
||||
int64_t R, int j) {
|
||||
const int64_t w = R / RAD_DFLASH_EDGE_PARTS;
|
||||
float acc = 0.0f;
|
||||
for (int64_t r = (int64_t)j * w; r < (int64_t)(j + 1) * w; ++r)
|
||||
acc = fmaf(a[r], rad_dflash_bf2f(succ_row[r]), acc);
|
||||
return acc;
|
||||
}
|
||||
|
||||
/* One position of the walk, given its K scores and ids (the ids as the candidate plane holds them).
|
||||
* Fills `*s` as mtp_couple_propose fills a round's state and returns the proposed token:
|
||||
*
|
||||
* mode 0 (a greedy request): status 0, x = `greedy_x`, the token dflash_select already wrote;
|
||||
* mode 1, its card's draw and a Q that builds: status 1, x ~ Q;
|
||||
* mode 1 otherwise: status -1, x = the walk's argmax (ties to the lower index, dflash_select's
|
||||
* rule over these scores), and the ordinary verify applies to it.
|
||||
*
|
||||
* The eight are taken in descending score, ties to the lower index, among candidates with an id
|
||||
* in [0, vocab); a NaN score is never taken (build_q would refuse it). */
|
||||
static inline RAD_SPECHUB_HD int32_t rad_dflash_couple_step(const float* sc, const int32_t* id,
|
||||
int K, float q_temp,
|
||||
const RadMtpCoupleDraw& d, bool card_ok,
|
||||
int round, int64_t vocab,
|
||||
int32_t greedy_x, RadMtpCoupleState* s) {
|
||||
s->draw = d;
|
||||
s->pos = 0;
|
||||
s->round = round;
|
||||
s->count = 0;
|
||||
s->nkids = 0; /* a walk's position is one draw: the chain's wire */
|
||||
s->scheme = 0;
|
||||
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
|
||||
if (d.mode != 1) {
|
||||
s->status = 0;
|
||||
s->x = greedy_x;
|
||||
return greedy_x;
|
||||
}
|
||||
s->status = -1;
|
||||
if (card_ok) {
|
||||
int32_t kid[8];
|
||||
float kv[8];
|
||||
unsigned taken = 0;
|
||||
int n = 0;
|
||||
for (; n < 8; ++n) {
|
||||
int best = -1;
|
||||
for (int c = 0; c < K; ++c) {
|
||||
if ((taken >> c) & 1u) continue;
|
||||
if (id[c] < 0 || id[c] >= vocab || sc[c] != sc[c]) continue;
|
||||
if (best < 0 || sc[c] > sc[best]) best = c;
|
||||
}
|
||||
if (best < 0) break;
|
||||
taken |= 1u << best;
|
||||
kid[n] = id[best];
|
||||
kv[n] = sc[best] / q_temp;
|
||||
}
|
||||
for (int i = n; i < 8; ++i) { kid[i] = -1; kv[i] = -INFINITY; }
|
||||
if (n > 0 && rad_mtp_couple_build_q(kid, kv, vocab, s)) {
|
||||
const double u = rad_spechub_uniform(d.seed, d.base,
|
||||
RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)round);
|
||||
s->x = s->ids[rad_mtp_couple_pick(*s, u)];
|
||||
s->status = 1;
|
||||
return s->x;
|
||||
}
|
||||
s->count = 0;
|
||||
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
|
||||
}
|
||||
int best = 0;
|
||||
float bv = -INFINITY;
|
||||
for (int c = 0; c < K; ++c)
|
||||
if (sc[c] > bv) { bv = sc[c]; best = c; }
|
||||
s->x = id[best];
|
||||
return s->x;
|
||||
}
|
||||
|
||||
/* One sequence's whole walk on the host: the reference the device kernel is checked against, and
|
||||
* what the tests drive. `cand`/`unary` are `steps` rows at pitches `ld_cand`/`ld_unary`, `hp`
|
||||
* `steps` rows at `ld_hp` (null: ones), `tokens` the `steps` tokens dflash_select wrote (rewritten
|
||||
* for a sampled row), `state` round 1's row with `st_round` u32 words between rounds. K <= 32, R a
|
||||
* multiple of RAD_DFLASH_EDGE_PARTS and at most RAD_DFLASH_COUPLE_MAX_R (the plugin's validation).
|
||||
* `pred`/`succ` are [vocab, R]. */
|
||||
static inline void rad_dflash_couple_walk(const int32_t* cand, const float* unary, int64_t ld_cand,
|
||||
int64_t ld_unary, const uint16_t* hp, int64_t ld_hp,
|
||||
int32_t anchor, const uint16_t* pred,
|
||||
const uint16_t* succ, int K,
|
||||
int64_t R, int64_t vocab, int64_t steps, float q_temp,
|
||||
const RadMtpCoupleDraw& d, bool card_ok, int32_t* tokens,
|
||||
uint32_t* state, int64_t st_round) {
|
||||
float a[RAD_DFLASH_COUPLE_MAX_R], sc[RAD_DFLASH_COUPLE_MAX_K] = {};
|
||||
int32_t pid = anchor;
|
||||
for (int64_t l = 0; l < steps; ++l) {
|
||||
RadMtpCoupleState* s = reinterpret_cast<RadMtpCoupleState*>(state + l * st_round);
|
||||
const int32_t* id = cand + l * ld_cand;
|
||||
if (d.mode == 1) {
|
||||
const float* un = unary + l * ld_unary;
|
||||
const bool ok = pid >= 0 && pid < vocab;
|
||||
for (int64_t r = 0; r < R; ++r)
|
||||
a[r] = ok ? rad_dflash_bf2f(pred[(int64_t)pid * R + r]) *
|
||||
(hp ? rad_dflash_bf2f(hp[l * ld_hp + r]) : 1.0f)
|
||||
: 0.0f;
|
||||
for (int c = 0; c < K; ++c) {
|
||||
float acc = 0.0f;
|
||||
if (id[c] >= 0 && id[c] < vocab)
|
||||
for (int j = 0; j < RAD_DFLASH_EDGE_PARTS; ++j)
|
||||
acc += rad_dflash_edge_part(a, succ + (int64_t)id[c] * R, R, j);
|
||||
sc[c] = un[c] + acc;
|
||||
}
|
||||
}
|
||||
pid = rad_dflash_couple_step(sc, id, K, q_temp, d, card_ok, (int)l + 1, vocab, tokens[l], s);
|
||||
tokens[l] = pid;
|
||||
}
|
||||
}
|
||||
|
||||
#undef RAD_SPECHUB_HD
|
||||
#endif /* __cplusplus */
|
||||
#endif /* RAD_SPECHUB_H */
|
||||
@@ -184,7 +184,7 @@ struct Model {
|
||||
std::string mul, add;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype,
|
||||
std::initializer_list<int64_t> shape, int access, int group) {
|
||||
@@ -978,8 +978,9 @@ static int find_prefix(RadBuilder* b, Model& m, const char** marker) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta, ctx));
|
||||
@@ -1335,7 +1336,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "anima is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1361,6 +1362,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(anima)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(anima, "anima", "", "0.1.0",
|
||||
"Anima (Base, Aesthetic, Turbo): Qwen3-0.6B through the LLM adapter, Cosmos-Predict2's "
|
||||
"2B diffusion transformer and the Qwen-Image VAE; bf16 or block-fp8 linears")
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf -- the GGUF variant of bailing_hybrid for the tiny family's IQ4_NL release: the same
|
||||
* declaration and step, claiming the ftype-25 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_25"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q4km -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q4km LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q4km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q4km.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q4km -- the GGUF variant of bailing_hybrid for the tiny family's Q4_K_M release: the same
|
||||
* declaration and step, claiming the ftype-15 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q4km
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q4km"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_15"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q5km -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q5km LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q5km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q5km.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q5km -- the GGUF variant of bailing_hybrid for the tiny family's Q5_K_M release: the same
|
||||
* declaration and step, claiming the ftype-17 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q5km
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q5km"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_17"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q6k -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q6k LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q6k architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q6k.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q6k -- the GGUF variant of bailing_hybrid for the tiny family's Q6_K release: the same
|
||||
* declaration and step, claiming the ftype-18 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q6k
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q6k"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_18"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid_gguf_q80 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid_gguf_q80 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid_gguf_q80 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q80.cpp)
|
||||
@@ -0,0 +1,12 @@
|
||||
/* bailing_hybrid_gguf_q80 -- the GGUF variant of bailing_hybrid for the tiny family's Q8_0 release: the same
|
||||
* declaration and step, claiming the ftype-7 descriptor so the quantised GGUF converts
|
||||
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
|
||||
* namespace, the plugin name and the quant redefined. */
|
||||
#define bailing_hybrid bailing_hybrid_gguf_q80
|
||||
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q80"
|
||||
#define BAILING_HYBRID_QUANT "gguf_ftype_7"
|
||||
#include "../bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
|
||||
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
+145
-34
@@ -1,8 +1,9 @@
|
||||
/* breeze -- Breeze-TTS-2: speech from text, with an optional description of the voice; 24 kHz mono.
|
||||
/* breeze -- Breeze-TTS-2: speech from text, voice design or a reference recording; 24 kHz mono.
|
||||
*
|
||||
* ============================== THE MODEL ==============================
|
||||
*
|
||||
* Four networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer):
|
||||
* Four generation networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer),
|
||||
* plus the reference-audio encoder in reference.h for voice cloning:
|
||||
*
|
||||
* Text encoder: T5Gemma 2's text encoder, Gemma 3 1B's shape (26 layers of 1152, 4 query heads
|
||||
* over one KV head of 256, gelu-tanh GLU 6912, sandwich RMS norms with a (1 + w) gain), read
|
||||
@@ -85,6 +86,8 @@ constexpr int64_t kVocChunk = 4, kConvCtx = 12, kAttnWin = 72;
|
||||
constexpr int64_t kVocContext = 2 + (kAttnWin - 1) + kConvCtx;
|
||||
constexpr int64_t kConvFrames = kConvCtx + kVocChunk;
|
||||
constexpr int64_t kCbBins = 2048, kCbDim = 256;
|
||||
/* One clean reference of at most ten seconds (rounded to complete codec frames). */
|
||||
constexpr int64_t kMaxRefFrames = 125, kMaxRefSamples = kMaxRefFrames * kSamplesPerFrame;
|
||||
/* The codec's sequence rates, rows a frame: the transformer's frames, the convolutions' frames,
|
||||
* the two upsamplings', and each decoder block's output (8, 5, 4, 3 times). */
|
||||
constexpr int kRates = 8;
|
||||
@@ -160,7 +163,34 @@ struct Llama3 {
|
||||
double factor = 0, low = 0, high = 0, orig = 0;
|
||||
};
|
||||
|
||||
struct RefConv {
|
||||
rad_weight w = 0, b = 0;
|
||||
rad_op op = 0;
|
||||
};
|
||||
struct RefLayer {
|
||||
rad_weight n1 = 0, b1 = 0, n2 = 0, b2 = 0, qkv = 0, o = 0, fc1 = 0, fc2 = 0;
|
||||
rad_weight ls1 = 0, ls2 = 0;
|
||||
rad_op norm1 = 0, norm2 = 0, proj = 0, rope = 0, attn = 0, out = 0;
|
||||
rad_op f1 = 0, act = 0, f2 = 0, scale1 = 0, scale2 = 0, add1 = 0, add2 = 0;
|
||||
};
|
||||
struct Reference {
|
||||
RefConv first{}, res1[4]{}, res2[4]{}, down[4]{}, last{}, sample{};
|
||||
rad_buf x[5]{}, a[5]{}, h[4]{}, z = 0, pad = 0, sampled = 0;
|
||||
rad_op elu[5]{}, elu_h[4]{};
|
||||
rad_buf th = 0, qkv = 0, attn = 0, o = 0, ff = 0, act = 0;
|
||||
RefLayer layer[8]{};
|
||||
rad_buf index = 0, cu = 0, text_pos = 0, text_cu = 0;
|
||||
rad_op indices = 0, copy_i = 0, copy_f = 0, text_indices = 0;
|
||||
rad_buf q[2]{}, codes = 0, eos_codes = 0;
|
||||
rad_weight qi[2]{}, cb[16]{};
|
||||
rad_op project[2]{}, quant[16]{}, embed = 0, eos = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Reference ref{};
|
||||
/* The model holds the reference encoder (reference_stored), whose first weight is then already
|
||||
* in the name map. */
|
||||
bool ref_stored = false;
|
||||
Names nm{""};
|
||||
Llama3 l3{};
|
||||
Geom ge{}, gl{}, gd{}; /* the text encoder's, the backbone's, the depth decoder's */
|
||||
@@ -225,7 +255,7 @@ struct Model {
|
||||
rad_buf b_vout = 0, b_audio = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x,
|
||||
@@ -1183,10 +1213,13 @@ static int check_format(const RadModelMeta* meta) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#include "reference.h"
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -1213,6 +1246,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(declare_encoder(b, meta, m));
|
||||
RAD_ARCH_TRY(declare_frame(b, meta, m));
|
||||
RAD_ARCH_TRY(declare_codec(b, meta, m));
|
||||
/* A container converted before the reference encoder was in the recipe holds the generator
|
||||
* alone: it serves speech as before, and with no reference templates declared below the
|
||||
* server refuses a request that brings references, saying the model clones no voice. */
|
||||
m.ref_stored = reference_stored(b, m);
|
||||
if (m.ref_stored) RAD_ARCH_TRY(declare_reference(b, meta, m));
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadAudioGenDecl d{};
|
||||
@@ -1220,6 +1258,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.tmpl = kTemplate;
|
||||
d.tmpl_plain = kPlain;
|
||||
d.neg_tmpl = kPlain;
|
||||
d.branches = 2;
|
||||
if (m.ref_stored) {
|
||||
d.tmpl_ref = "{references}<bos>[S0]{input}";
|
||||
d.tmpl_ref_instruct = "{references}<bos>[S0]<ins_bos>{instructions}<ins_eos>{input}";
|
||||
d.neg_tmpl_ref = d.tmpl_ref;
|
||||
d.ref_item = "<bos>[S0]{text}{audio}<|audio_eos|>";
|
||||
d.ref_rate = kSampleRate;
|
||||
d.ref_hop = kSamplesPerFrame;
|
||||
d.ref_max_samples = kMaxRefSamples;
|
||||
d.ref_max = 1;
|
||||
}
|
||||
d.prompt_whole = 1;
|
||||
d.first_frame = 0;
|
||||
d.max_prompt = kMaxPrompt;
|
||||
@@ -1266,34 +1315,91 @@ static void step_backbone(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
m.b_h2, m.b_gu, m.b_ff, pos, cu, layer++);
|
||||
}
|
||||
|
||||
static void step_text(RadCtx* c, const Model& m, int64_t T, RadOperand tokens,
|
||||
RadOperand pos, RadOperand cu, RadOperand output) {
|
||||
const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim;
|
||||
/* The encoder over each branch's prompt, bidirectional within it; its projection is the
|
||||
* backbone's input. */
|
||||
RAD_ISSUE_N(c, m.op_eembed, T, tokens, RAD_W(m.w_etok),
|
||||
brows(m.b_ex, T));
|
||||
for (const EncLayer& L : m.enc) {
|
||||
RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_qkv, T, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T));
|
||||
RAD_ISSUE_N(c, L.op_qknr, T, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn));
|
||||
RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T),
|
||||
bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T));
|
||||
RAD_ISSUE_N(c, L.op_o, T, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T));
|
||||
RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
RAD_ISSUE_N(c, L.op_n3, T, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_gu, T, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T));
|
||||
RAD_ISSUE_N(c, L.op_act, T, brows(m.b_egu, T), brows(m.b_eff, T));
|
||||
RAD_ISSUE_N(c, L.op_down, T, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T));
|
||||
RAD_ISSUE_N(c, L.op_n4, T, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_enorm, T, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T));
|
||||
RAD_ISSUE_N(c, m.op_eproj, T, brows(m.b_eh, T), RAD_W(m.w_eproj), output);
|
||||
}
|
||||
|
||||
/* rvq_embed reads codebook 0 from its first table and codebooks 1..15 from its
|
||||
* second table, whose row zero must therefore be the start of codebook 1. */
|
||||
static RadOperand residual_codebooks(const Model& m) {
|
||||
RadOperand t = RAD_W(m.w_cb);
|
||||
t.offset = (int64_t)kVocab * m.gl.n_embd;
|
||||
t.rows = (int64_t)(kCodes - 1) * kVocab;
|
||||
return t;
|
||||
}
|
||||
|
||||
static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadAudioGenBatch* A = batch->agen_b;
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim;
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1);
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
/* The encoder over each branch's prompt, bidirectional within it; its projection is the
|
||||
* backbone's input. */
|
||||
RAD_ISSUE(c, m.op_eembed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_etok),
|
||||
brows(m.b_ex, T));
|
||||
for (const EncLayer& L : m.enc) {
|
||||
RAD_ISSUE(c, L.op_n1, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_qkv, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T));
|
||||
RAD_ISSUE(c, L.op_qknr, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn));
|
||||
RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T),
|
||||
bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T));
|
||||
RAD_ISSUE(c, L.op_o, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T));
|
||||
RAD_ISSUE(c, L.op_n2, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_add1, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
RAD_ISSUE(c, L.op_n3, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_gu, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T));
|
||||
RAD_ISSUE(c, L.op_act, brows(m.b_egu, T), brows(m.b_eff, T));
|
||||
RAD_ISSUE(c, L.op_down, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T));
|
||||
RAD_ISSUE(c, L.op_n4, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, L.op_add2, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
|
||||
if (A->n_ref) {
|
||||
if (!A->prompt_cu_h || A->prompt_cu_h[0] != 0 ||
|
||||
A->prompt_cu_h[batch->n_seq] != T) {
|
||||
rad_step_fail(c, "breeze: reference prompt needs its host branch boundaries");
|
||||
return;
|
||||
}
|
||||
step_reference(c, batch, m);
|
||||
const Reference& E = m.ref;
|
||||
RAD_ISSUE_N(c, E.text_indices, kMaxPrompt, brows(E.text_pos, kMaxPrompt));
|
||||
RAD_ISSUE_N(c, E.eos, 16, brows(E.eos_codes, 16));
|
||||
/* Each branch has two independent text-encoder segments around its audio. The
|
||||
* backbone alone attends across the concatenation. Never encode audio placeholders
|
||||
* or the audio EOS as text, and reset rotary positions for each text segment. */
|
||||
for (int64_t branch = 0; branch < batch->n_seq; ++branch) {
|
||||
const int64_t end = A->prompt_cu_h[branch + 1];
|
||||
for (int64_t t = A->prompt_cu_h[branch]; t < end;) {
|
||||
const int32_t f = A->ref_frame_h[t];
|
||||
if (f >= 0) {
|
||||
int64_t n = 1;
|
||||
while (t + n < end && A->ref_frame_h[t + n] == f + n) ++n;
|
||||
if (t + n >= end) {
|
||||
rad_step_fail(c, "breeze: reference frames need their audio EOS row");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, E.embed, n, bcol(E.codes, f, n, 16), RAD_W(m.w_cb),
|
||||
residual_codebooks(m), brow_slice(m.b_x, t, n, m.gl.n_embd));
|
||||
t += n;
|
||||
RAD_ISSUE_N(c, E.embed, 1, brows(E.eos_codes, 16), RAD_W(m.w_cb),
|
||||
residual_codebooks(m), brow_slice(m.b_x, t, 1, m.gl.n_embd));
|
||||
++t;
|
||||
} else {
|
||||
int64_t n = 1;
|
||||
while (t + n < end && A->ref_frame_h[t + n] < 0) ++n;
|
||||
ref_bounds(c, E, E.text_cu, n);
|
||||
step_text(c, m, n, praw(batch->token_ids + t, RAD_I32, n),
|
||||
brows(E.text_pos, n), brows(E.text_cu, 2),
|
||||
brow_slice(m.b_x, t, n, m.gl.n_embd));
|
||||
t += n;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
step_text(c, m, T, praw(batch->token_ids, RAD_I32, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(m.b_x, T));
|
||||
}
|
||||
RAD_ISSUE(c, m.op_enorm, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T));
|
||||
RAD_ISSUE(c, m.op_eproj, brows(m.b_eh, T), RAD_W(m.w_eproj), brows(m.b_x, T));
|
||||
step_backbone(c, batch, m);
|
||||
bool any_last = false;
|
||||
for (int64_t i = 0; i < A->n_lane; ++i) any_last = any_last || A->last_h[i];
|
||||
@@ -1357,10 +1463,8 @@ static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
/* 3. the frame into its lane's history, and the backbone over the frame's embedding */
|
||||
RAD_ISSUE_N(c, m.op_store, n, brows(m.b_codes, kCodes), lanes, frame,
|
||||
brows(m.b_status, m.lanes), brows(m.b_codes_all, m.lanes * kCodes));
|
||||
RadOperand t1 = RAD_W(m.w_cb);
|
||||
t1.offset = (int64_t)kVocab * D;
|
||||
t1.rows = (int64_t)(kCodes - 1) * kVocab;
|
||||
RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), t1, brows(m.b_x, S));
|
||||
RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), residual_codebooks(m),
|
||||
brows(m.b_x, S));
|
||||
step_backbone(c, batch, m);
|
||||
store_hidden(c, m, A, S, A->last_row, S);
|
||||
}
|
||||
@@ -1475,7 +1579,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->agen_b) {
|
||||
rad_step_fail(c, "breeze is an audio generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1503,6 +1607,11 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
if (!in) return RAD_E_INVAL;
|
||||
std::string r = in;
|
||||
if (field == RAD_TEXT_REFERENCE) {
|
||||
for (const char* marker : {"<bos>", "<eos>", "<|AUDIO|>", "<|audio_eos|>",
|
||||
"<ins_bos>", "<ins_eos>"})
|
||||
if (r.find(marker) != std::string::npos) return RAD_E_INVAL;
|
||||
}
|
||||
if (field == RAD_TEXT_INSTRUCTIONS) {
|
||||
const size_t a = r.find_first_not_of(" \t\r\n"), z = r.find_last_not_of(" \t\r\n");
|
||||
r = a == std::string::npos ? std::string() : r.substr(a, z - a + 1);
|
||||
@@ -1521,6 +1630,8 @@ RAD_ARCH_PROBE(breeze)
|
||||
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
return breeze::text_prepare(field, in, out, cap);
|
||||
}
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(breeze, "breeze", "", "0.1.0",
|
||||
"Breeze-TTS-2: a T5Gemma 2 text encoder over a Qwen3 backbone with a 16-codebook "
|
||||
"depth decoder and the Qwen3-TTS 12 Hz codec; 24 kHz mono speech")
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
/* Breeze's Qwen3-TTS/Mimi reference encoder. Included inside namespace breeze after the
|
||||
* ordinary networks. Kept in f32, as the released audio tokenizer encodes references. */
|
||||
static rad_op ref_rows(RadBuilder* b, const char* op, int64_t rows, int64_t n,
|
||||
std::initializer_list<rad_buf> in, std::initializer_list<rad_buf> out,
|
||||
const char* dtype = "f32") {
|
||||
return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", dtype)), RAD_NOWEIGHTS), in, out);
|
||||
}
|
||||
|
||||
static rad_op ref_gemm(RadBuilder* b, int64_t rows, int64_t n, int64_t k, rad_weight w,
|
||||
rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n),
|
||||
RAD_INT("K", k), RAD_STR("dtype", "f32")), RAD_WEIGHTS(w)), {x}, {y});
|
||||
}
|
||||
|
||||
static int ref_conv(RadBuilder* b, Model& m, RefConv& C, const char* name, const char* src,
|
||||
int64_t ci, int64_t co, int64_t k, int64_t st, int64_t rate, int64_t rows,
|
||||
rad_buf x, rad_buf res, rad_buf y, bool bias = true) {
|
||||
/* The first convolution's weight is mapped by reference_stored when that ran. */
|
||||
C.w = (m.ref_stored && &C == &m.ref.first)
|
||||
? decl_w(b, m.nm.f("ref.%s.weight", name), RAD_F32, {co, ci, k}, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(kGrpCodec + 1))
|
||||
: wcopy(b, m.nm, m.nm.f("ref.%s.weight", name), m.nm.ckpt("%s.weight", src),
|
||||
RAD_F32, {co, ci, k}, kGrpCodec + 1);
|
||||
if (bias) C.b = wcopy(b, m.nm, m.nm.f("ref.%s.bias", name), m.nm.ckpt("%s.bias", src),
|
||||
RAD_F32, {co}, kGrpCodec + 1);
|
||||
const rad_weight weights[] = {C.w, C.b};
|
||||
C.op = rw(b, RAD_OP(b, "conv1d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", ci),
|
||||
RAD_INT("cout", co), RAD_INT("k", k), RAD_INT("dil", 1),
|
||||
RAD_INT("causal", 1), RAD_INT("stride", st), RAD_INT("cu_div", rate),
|
||||
RAD_STR("dtype", "f32")), weights, bias ? 2 : 1),
|
||||
{x, m.ref.cu, res}, {y});
|
||||
return C.w && (!bias || C.b) && C.op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Whether the model holds the reference encoder, asked of its first convolution through the name
|
||||
* map entry declared here (the one ref_conv would declare). A builder with no model behind it
|
||||
* answers no. */
|
||||
static bool reference_stored(RadBuilder* b, Model& m) {
|
||||
const std::string dn = m.nm.f("ref.first.weight");
|
||||
if (map_copy(b, dn.c_str(),
|
||||
m.nm.ckpt("%s.weight", "audio_tokenizer.encoder.encoder.layers.0.conv")) < 0)
|
||||
return false;
|
||||
RadEncoding enc{};
|
||||
return weight_enc(b, dn.c_str(), &enc);
|
||||
}
|
||||
|
||||
static int declare_reference(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
Reference& E = m.ref;
|
||||
Names& nm = m.nm;
|
||||
const char* ec = "audio_tokenizer.encoder_config";
|
||||
if (rad_meta_geti(meta, nm.f("%s.hidden_size", ec), 0) != 512 ||
|
||||
rad_meta_geti(meta, nm.f("%s.num_hidden_layers", ec), 0) != 8 ||
|
||||
rad_meta_geti(meta, nm.f("%s.num_filters", ec), 0) != 64 ||
|
||||
rad_meta_geti(meta, nm.f("%s.use_causal_conv", ec), 1) != 1 ||
|
||||
rad_meta_geti(meta, nm.f("%s.use_conv_shortcut", ec), 0) != 0) {
|
||||
fprintf(stderr, "radiance: breeze: reference encoder is not the released Qwen3-TTS encoder\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
constexpr int64_t R = kMaxRefSamples / 960; /* SEANet's 25 Hz output */
|
||||
constexpr int64_t NI = 2 * kMaxPrompt + 3;
|
||||
E.index = decl_b(b, nm.f("ref.index"), RAD_I32, {NI}, RAD_BUF_PERSIST);
|
||||
E.indices = iota_op(b, NI, 0, 1, E.index);
|
||||
E.cu = decl_b(b, nm.f("ref.cu"), RAD_I32, {2}, RAD_BUF_PERSIST);
|
||||
E.text_pos = decl_b(b, nm.f("ref.text_pos"), RAD_I32, {kMaxPrompt}, RAD_BUF_PERSIST);
|
||||
E.text_cu = decl_b(b, nm.f("ref.text_cu"), RAD_I32, {2}, RAD_BUF_PERSIST);
|
||||
E.text_indices = iota_op(b, kMaxPrompt, 0, 1, E.text_pos);
|
||||
E.copy_i = rw(b, RAD_OP(b, "int_affine", RAD_PARAMS(RAD_INT("M", 1), RAD_STR("src", "0"),
|
||||
RAD_STR("mul", "1"), RAD_STR("add", "0")), RAD_NOWEIGHTS),
|
||||
{E.index}, {E.cu, E.text_cu});
|
||||
E.copy_f = rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512),
|
||||
RAD_STR("from", "f32"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {}, {});
|
||||
int64_t rows = kMaxRefSamples, ch = 64, rate = 1;
|
||||
static const int64_t stride[] = {4, 5, 6, 8};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
E.x[i] = decl_b(b, nm.f("ref.x%d", i), RAD_F32, {rows, ch});
|
||||
E.a[i] = decl_b(b, nm.f("ref.a%d", i), RAD_F32, {rows, ch});
|
||||
E.elu[i] = ref_rows(b, "elu", rows, ch, {E.x[i]}, {E.a[i]});
|
||||
if (i < 4) {
|
||||
E.h[i] = decl_b(b, nm.f("ref.h%d", i), RAD_F32, {rows, ch / 2});
|
||||
E.elu_h[i] = ref_rows(b, "elu", rows, ch / 2, {E.h[i]}, {E.h[i]});
|
||||
rows /= stride[i]; ch *= 2;
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.first, "first", "audio_tokenizer.encoder.encoder.layers.0.conv",
|
||||
1, 64, 7, 1, 1, kMaxRefSamples, 0, 0, E.x[0]));
|
||||
rows = kMaxRefSamples; ch = 64; rate = 1;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const int li = 1 + 3 * i;
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.res1[i], nm.f("res%d.1", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.1.conv", li),
|
||||
ch, ch / 2, 3, 1, rate, rows, E.a[i], 0, E.h[i]));
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.res2[i], nm.f("res%d.2", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.3.conv", li),
|
||||
ch / 2, ch, 1, 1, rate, rows, E.h[i], E.x[i], E.x[i]));
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.down[i], nm.f("down%d", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.conv", li + 2),
|
||||
ch, 2 * ch, 2 * stride[i], stride[i], rate, rows,
|
||||
E.a[i], 0, E.x[i + 1]));
|
||||
rows /= stride[i]; rate *= stride[i]; ch *= 2;
|
||||
}
|
||||
E.z = decl_b(b, nm.f("ref.z"), RAD_F32, {R, 512});
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.last, "last", "audio_tokenizer.encoder.encoder.layers.14.conv",
|
||||
1024, 512, 3, 1, 960, R, E.a[4], 0, E.z));
|
||||
E.th = decl_b(b, nm.f("ref.th"), RAD_F32, {R, 512});
|
||||
E.qkv = decl_b(b, nm.f("ref.qkv"), RAD_F32, {R, 1536});
|
||||
E.attn = decl_b(b, nm.f("ref.attn"), RAD_F32, {R, 512});
|
||||
E.o = decl_b(b, nm.f("ref.o"), RAD_F32, {R, 512});
|
||||
E.ff = decl_b(b, nm.f("ref.ff"), RAD_F32, {R, 2048});
|
||||
E.act = decl_b(b, nm.f("ref.act"), RAD_F32, {R, 2048});
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
RefLayer& L = E.layer[i];
|
||||
auto w = [&](const char* dn, const char* sn, std::initializer_list<int64_t> sh) {
|
||||
return wcopy(b, nm, nm.f("ref.t%d.%s", i, dn),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.%s", i, sn),
|
||||
RAD_F32, sh, kGrpCodec + 1);
|
||||
};
|
||||
L.n1 = w("n1", "input_layernorm.weight", {512});
|
||||
L.b1 = w("b1", "input_layernorm.bias", {512});
|
||||
L.n2 = w("n2", "post_attention_layernorm.weight", {512});
|
||||
L.b2 = w("b2", "post_attention_layernorm.bias", {512});
|
||||
L.ls1 = w("ls1", "self_attn_layer_scale.scale", {512});
|
||||
L.ls2 = w("ls2", "mlp_layer_scale.scale", {512});
|
||||
const char* qn = nm.f("ref.t%d.qkv", i);
|
||||
RAD_ARCH_TRY(map_concat(b, qn, {
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.q_proj.weight", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.k_proj.weight", i),
|
||||
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.v_proj.weight", i)}));
|
||||
L.qkv = decl_w(b, qn, RAD_F32, {1536, 512}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(kGrpCodec + 1));
|
||||
L.o = w("out", "self_attn.o_proj.weight", {512, 512});
|
||||
L.fc1 = w("fc1", "mlp.fc1.weight", {2048, 512});
|
||||
L.fc2 = w("fc2", "mlp.fc2.weight", {512, 2048});
|
||||
auto ln = [&](rad_weight nw, rad_weight nb) {
|
||||
return rw(b, RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512),
|
||||
RAD_F64("eps", 1e-5), RAD_STR("dtype", "f32")), RAD_WEIGHTS(nw, nb)),
|
||||
{E.z}, {E.th});
|
||||
};
|
||||
L.norm1 = ln(L.n1, L.b1); L.norm2 = ln(L.n2, L.b2);
|
||||
L.proj = ref_gemm(b, R, 1536, 512, L.qkv, E.th, E.qkv);
|
||||
L.rope = rw(b, RAD_OP(b, "rope", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", 64),
|
||||
RAD_INT("n_head", 8), RAD_INT("n_head_kv", 8), RAD_F64("theta", 10000),
|
||||
RAD_F64("scale", 1), RAD_STR("mode", "neox")), RAD_NOWEIGHTS),
|
||||
{E.qkv, E.index}, {E.qkv});
|
||||
L.attn = rw(b, RAD_OP(b, "attn_dense", RAD_PARAMS(RAD_RANGE("M", 1, R),
|
||||
RAD_INT("head_dim", 64), RAD_INT("gqa", 1), RAD_INT("causal", 1),
|
||||
RAD_F64("scale", 0.125), RAD_INT("window", 250), RAD_INT("max_seqlen", R),
|
||||
RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {E.qkv, E.cu}, {E.attn});
|
||||
L.out = ref_gemm(b, R, 512, 512, L.o, E.attn, E.o);
|
||||
L.f1 = ref_gemm(b, R, 2048, 512, L.fc1, E.th, E.ff);
|
||||
L.act = ref_rows(b, "gelu", R, 2048, {E.ff}, {E.act});
|
||||
L.f2 = ref_gemm(b, R, 512, 2048, L.fc2, E.act, E.o);
|
||||
auto scale = [&](rad_weight sw) {
|
||||
return rw(b, RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R),
|
||||
RAD_INT("n", 512), RAD_STR("dtype", "f32")), RAD_WEIGHTS(sw)), {E.o}, {E.o});
|
||||
};
|
||||
L.scale1 = scale(L.ls1); L.scale2 = scale(L.ls2);
|
||||
L.add1 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z});
|
||||
L.add2 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z});
|
||||
if (!L.n1 || !L.b1 || !L.n2 || !L.b2 || !L.qkv || !L.o || !L.fc1 || !L.fc2 ||
|
||||
!L.ls1 || !L.ls2 || !L.norm1 || !L.norm2 || !L.proj || !L.rope || !L.attn ||
|
||||
!L.out || !L.f1 || !L.act || !L.f2 || !L.scale1 || !L.scale2 || !L.add1 || !L.add2)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The last downsample uses replicate padding. Prepending two copies of the first row,
|
||||
* using the ordinary causal conv, then dropping its first output is exactly that pad. */
|
||||
E.pad = decl_b(b, nm.f("ref.pad"), RAD_F32, {R + 2, 512});
|
||||
E.sampled = decl_b(b, nm.f("ref.sampled"), RAD_F32, {kMaxRefFrames + 1, 512});
|
||||
RAD_ARCH_TRY(rad_op_reads(b, E.copy_f, &E.z, 1));
|
||||
RAD_ARCH_TRY(rad_op_writes(b, E.copy_f, &E.pad, 1));
|
||||
RAD_ARCH_TRY(ref_conv(b, m, E.sample, "sample", "audio_tokenizer.encoder.downsample.conv",
|
||||
512, 512, 4, 2, 1, R + 2, E.pad, 0, E.sampled, false));
|
||||
E.codes = decl_b(b, nm.f("ref.codes"), RAD_I32, {16, kMaxRefFrames}, RAD_BUF_PERSIST);
|
||||
E.eos_codes = decl_b(b, nm.f("ref.eos_codes"), RAD_I32, {16, 1}, RAD_BUF_PERSIST);
|
||||
for (int part = 0; part < 2; ++part) {
|
||||
const char* qs = part ? "acoustic_residual_vector_quantizer" : "semantic_residual_vector_quantizer";
|
||||
E.q[part] = decl_b(b, nm.f("ref.q%d", part), RAD_F32, {kMaxRefFrames, 256});
|
||||
E.qi[part] = wcopy(b, nm, nm.f("ref.q%d.in", part),
|
||||
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.input_proj.weight", qs),
|
||||
RAD_F32, {256, 512}, kGrpCodec + 1);
|
||||
/* A 1x1 Conv1d weight's trailing singleton is immaterial to GEMM's matrix view. */
|
||||
E.project[part] = ref_gemm(b, kMaxRefFrames, 256, 512, E.qi[part], E.sampled, E.q[part]);
|
||||
const int first = part ? 1 : 0, count = part ? 15 : 1;
|
||||
for (int j = 0; j < count; ++j) {
|
||||
const int k = first + j;
|
||||
const char* dn = nm.f("ref.cb%d", k);
|
||||
RAD_ARCH_TRY(map_ema(b, dn,
|
||||
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.embed_sum", qs, j),
|
||||
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.cluster_usage", qs, j)));
|
||||
E.cb[k] = decl_w(b, dn, RAD_F32, {2048, 256}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(kGrpCodec + 1));
|
||||
E.quant[k] = rw(b, RAD_OP(b, "vq_euclidean", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames),
|
||||
RAD_INT("n", 256), RAD_INT("bins", 2048), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(E.cb[k])), {E.q[part]}, {E.q[part], E.codes});
|
||||
if (!E.cb[k] || !E.quant[k]) return RAD_E_INVAL;
|
||||
}
|
||||
if (!E.qi[part] || !E.project[part]) return RAD_E_INVAL;
|
||||
}
|
||||
E.embed = rw(b, RAD_OP(b, "rvq_embed", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames),
|
||||
RAD_INT("n_embd", m.gl.n_embd), RAD_INT("n_codes", 16), RAD_INT("vocab", kVocab),
|
||||
RAD_INT("off0", 0), RAD_F64("scale", 1), RAD_INT("round", 1),
|
||||
RAD_STR("dtype", "bf16")), RAD_WEIGHTS(m.w_cb, m.w_cb)), {E.codes}, {m.b_x});
|
||||
E.eos = iota_op(b, 16, 0, 0, E.eos_codes);
|
||||
RAD_ARCH_TRY(rad_op_reads(b, E.embed, &E.eos_codes, 1));
|
||||
/* Both branches' text segments are encoded separately at position zero. These buffers must
|
||||
* remain live through each segment's encoder, projection and the backbone prefill. */
|
||||
for (const EncLayer& L : m.enc) {
|
||||
RAD_ARCH_TRY(rad_op_reads(b, L.op_qknr, &E.text_pos, 1));
|
||||
RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &E.text_cu, 1));
|
||||
}
|
||||
return E.indices && E.copy_i && E.copy_f && E.text_indices && E.embed && E.eos ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Copy the endpoints of an iota into a two-entry cu, without a host upload or ABI change. */
|
||||
static void ref_bounds(RadCtx* c, const Reference& E, rad_buf cu, int64_t len) {
|
||||
RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, 0, 1, 1), brow_slice(cu, 0, 1, 1));
|
||||
RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, len, 1, 1), brow_slice(cu, 1, 1, 1));
|
||||
}
|
||||
|
||||
static void step_reference(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const Reference& E = m.ref;
|
||||
const auto* A = batch->agen_b;
|
||||
const int64_t L = A->ref_samples, R = L / 960, F = R / 2;
|
||||
RAD_ISSUE_N(c, E.indices, 2 * kMaxPrompt + 3, brows(E.index, 2 * kMaxPrompt + 3));
|
||||
const RadOperand raw_cu = praw(A->ref_cu, RAD_I32, 2);
|
||||
auto conv = [&](const RefConv& C, RadOperand x, RadOperand res, RadOperand y,
|
||||
int64_t rows, RadOperand cu) {
|
||||
RAD_ISSUE_N(c, C.op, rows, x, RAD_W(C.w), cu, res, y, C.b ? RAD_W(C.b) : RAD_NONE);
|
||||
};
|
||||
conv(E.first, praw(A->ref_audio, RAD_F32, L), RAD_NONE, brows(E.x[0], L), L, raw_cu);
|
||||
static const int64_t stride[] = {4, 5, 6, 8};
|
||||
int64_t rows = L;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows));
|
||||
conv(E.res1[i], brows(E.a[i], rows), RAD_NONE, brows(E.h[i], rows), rows, raw_cu);
|
||||
RAD_ISSUE_N(c, E.elu_h[i], rows, brows(E.h[i], rows), brows(E.h[i], rows));
|
||||
conv(E.res2[i], brows(E.h[i], rows), brows(E.x[i], rows), brows(E.x[i], rows), rows, raw_cu);
|
||||
RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows));
|
||||
conv(E.down[i], brows(E.a[i], rows), RAD_NONE, brows(E.x[i + 1], rows / stride[i]), rows, raw_cu);
|
||||
rows /= stride[i];
|
||||
}
|
||||
RAD_ISSUE_N(c, E.elu[4], R, brows(E.x[4], R), brows(E.a[4], R));
|
||||
conv(E.last, brows(E.a[4], R), RAD_NONE, brows(E.z, R), R, raw_cu);
|
||||
ref_bounds(c, E, E.cu, R);
|
||||
const RadOperand cu = brows(E.cu, 2), pos = brows(E.index, R);
|
||||
for (const RefLayer& T : E.layer) {
|
||||
auto norm = [&](rad_op op, rad_weight w, rad_weight bias) {
|
||||
RAD_ISSUE_N(c, op, R, brows(E.z, R), RAD_W(w), RAD_W(bias), brows(E.th, R));
|
||||
};
|
||||
auto gemm = [&](rad_op op, rad_buf x, rad_weight w, rad_buf y) {
|
||||
RAD_ISSUE_N(c, op, R, brows(x, R), RAD_W(w), brows(y, R));
|
||||
};
|
||||
norm(T.norm1, T.n1, T.b1);
|
||||
gemm(T.proj, E.th, T.qkv, E.qkv);
|
||||
RAD_ISSUE_N(c, T.rope, R, brows(E.qkv, R), pos);
|
||||
RAD_ISSUE_N(c, T.attn, R, bcol(E.qkv, 0, 512, R), bcol(E.qkv, 512, 512, R),
|
||||
bcol(E.qkv, 1024, 512, R), cu, brows(E.attn, R));
|
||||
gemm(T.out, E.attn, T.o, E.o);
|
||||
RAD_ISSUE_N(c, T.scale1, R, brows(E.o, R), RAD_W(T.ls1), brows(E.o, R));
|
||||
RAD_ISSUE_N(c, T.add1, R, brows(E.z, R), brows(E.o, R), brows(E.z, R));
|
||||
norm(T.norm2, T.n2, T.b2);
|
||||
gemm(T.f1, E.th, T.fc1, E.ff);
|
||||
RAD_ISSUE_N(c, T.act, R, brows(E.ff, R), brows(E.act, R));
|
||||
gemm(T.f2, E.act, T.fc2, E.o);
|
||||
RAD_ISSUE_N(c, T.scale2, R, brows(E.o, R), RAD_W(T.ls2), brows(E.o, R));
|
||||
RAD_ISSUE_N(c, T.add2, R, brows(E.z, R), brows(E.o, R), brows(E.z, R));
|
||||
}
|
||||
RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 0, 1, 512));
|
||||
RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 1, 1, 512));
|
||||
RAD_ISSUE_N(c, E.copy_f, R, brows(E.z, R), brow_slice(E.pad, 2, R, 512));
|
||||
ref_bounds(c, E, E.cu, R + 2);
|
||||
conv(E.sample, brows(E.pad, R + 2), RAD_NONE, brows(E.sampled, F + 1), R + 2, cu);
|
||||
for (int p = 0; p < 2; ++p) {
|
||||
RAD_ISSUE_N(c, E.project[p], F, brow_slice(E.sampled, 1, F, 512), RAD_W(E.qi[p]), brows(E.q[p], F));
|
||||
for (int k = p ? 1 : 0; k < (p ? 16 : 1); ++k) {
|
||||
RadOperand codes = brow_slice(E.codes, k, 1, kMaxRefFrames);
|
||||
codes.cols = F;
|
||||
RAD_ISSUE_N(c, E.quant[k], F, brows(E.q[p], F), RAD_W(E.cb[k]), codes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/clef_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(clef_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(clef_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/clef_bf16.cpp)
|
||||
@@ -0,0 +1,70 @@
|
||||
/* clef_bf16 -- Cloudflare's clef and clef-flash decision models, bf16: the qwen35_bf16 trunk with
|
||||
* the joint schema head on the card (arch/common/rad_block_clef.h), served on /v1/systemone.
|
||||
*
|
||||
* This is arch/qwen35_bf16/qwen35_bf16.cpp built again under its own architecture id, as
|
||||
* qwen35_w8a8 is qwen35_fp8 built again: the trunk's declare and step are that file's, untouched,
|
||||
* and this file adds the head after them. A container selects it with `rad-convert --arch clef`,
|
||||
* so a plain qwen35 container never pays for the head and the qwen35 plugins carry no decision
|
||||
* code. The head needs `decision.type=clef` and the head's geometry in the container header,
|
||||
* which rad-convert writes from joint_head_config.json and joint_head.safetensors (--add).
|
||||
*/
|
||||
#define RAD_ARCH_NO_EXPORTS 1
|
||||
#include "../qwen35_bf16/qwen35_bf16.cpp"
|
||||
#undef RAD_ARCH_NO_EXPORTS
|
||||
|
||||
#include <arch/rad_block_clef.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
namespace clef_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* One head per rank beside the trunk's own per-rank state (qwen35_bf16::g_model). */
|
||||
static ClefHead g_head[MAX_SLOTS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_bf16 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
"joint_head.safetensors); this one declares no decision model\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(qwen35_bf16::declare(b, meta, ctx));
|
||||
/* The trunk's declare does not take part in sizing declares (no probe), so its state and the
|
||||
* head's are the real ones. The head goes after the vision tower: its buffers join the same
|
||||
* arena, and it reads the final norm's rows, the lm_head and the trunk's cache block size. */
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_build_slot(ctx)];
|
||||
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
|
||||
* skips the lm_head on a step every sampled row of which carries a request's words
|
||||
* (plugin_words_cover_rows) and leaves zero rows instead. */
|
||||
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
|
||||
if (!m.op_logits_fill) return RAD_E_INVAL;
|
||||
ClefHead& h = g_head[rad_build_slot(ctx)];
|
||||
h = ClefHead{};
|
||||
return h.declare(b, meta, ctx, m.nm, m.g, m.b_h, m.b_logits, m.w_lm_head, m.kv_full,
|
||||
(int)m.g.n_layer + 256);
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
qwen35_bf16::step(c, batch);
|
||||
/* An encoder pass runs the tower alone and leaves no rows for the head. */
|
||||
if (batch->enc) return;
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_slot(c)];
|
||||
ClefHead& h = g_head[rad_slot(c)];
|
||||
/* The final norm's rows are still in `h` after the trunk's step; the logits row of each
|
||||
* sampled sequence has been written, and the head adds its values beside it. */
|
||||
h.step_tokens(c, batch, m.b_h);
|
||||
if (batch->n_out > 0) h.step_heads(c, batch, m.b_logits, m.w_lm_head);
|
||||
}
|
||||
|
||||
} /* namespace clef_bf16 */
|
||||
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(clef_bf16, "clef", "", "0.1.0",
|
||||
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_bf16, bf16, "
|
||||
"with the joint schema head on the card for /v1/systemone")
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/clef_fp8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(clef_fp8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(clef_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/clef_fp8.cpp)
|
||||
@@ -0,0 +1,67 @@
|
||||
/* clef_fp8 -- Cloudflare's clef and clef-flash decision models, block fp8: the qwen35_fp8 trunk
|
||||
* with the joint schema head on the card (arch/common/rad_block_clef.h), served on
|
||||
* /v1/systemone.
|
||||
*
|
||||
* This is arch/qwen35_fp8/qwen35_fp8.cpp built again under its own namespace and architecture
|
||||
* id, as qwen35_w8a8 and qwen35moe_fp8 are: the trunk's declare, step and probe are that file's,
|
||||
* untouched, and this file adds the head after them. A container selects it with `rad-convert
|
||||
* --arch clef` and the fp8 recipe; the lm_head stays bf16, which the head reads.
|
||||
*/
|
||||
#define QWEN35_NS qwen35_clef_fp8
|
||||
#define QWEN35_ARCH_ID "clef"
|
||||
#define RAD_ARCH_NO_EXPORTS 1
|
||||
#include "../qwen35_fp8/qwen35_fp8.cpp"
|
||||
#undef RAD_ARCH_NO_EXPORTS
|
||||
|
||||
#include <arch/rad_block_clef.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
namespace clef_fp8 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
static ClefHead g_head[MAX_SLOTS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_fp8 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
"joint_head.safetensors); this one declares no decision model\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(qwen35_clef_fp8::declare(b, meta, ctx));
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_build_slot(ctx)];
|
||||
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
|
||||
* skips the lm_head on a step every sampled row of which carries a request's words
|
||||
* (plugin_words_cover_rows) and leaves zero rows instead. */
|
||||
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
|
||||
if (!m.op_logits_fill) return RAD_E_INVAL;
|
||||
ClefHead& h = g_head[rad_build_slot(ctx)];
|
||||
h = ClefHead{};
|
||||
return h.declare(b, meta, ctx, m.nm, m.g, m.a_h.x, m.b_logits, m.w_lm_head, m.kv_full,
|
||||
(int)m.g.n_layer + 256);
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
qwen35_clef_fp8::step(c, batch);
|
||||
/* An encoder pass leaves no rows for the head, and a drafter's pass is not a trunk step. */
|
||||
if (batch->enc || batch->draft_pass != 0) return;
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_slot(c)];
|
||||
ClefHead& h = g_head[rad_slot(c)];
|
||||
/* The final norm's rows are in `a_h.x` after either of the trunk's step paths. */
|
||||
h.step_tokens(c, batch, m.a_h.x);
|
||||
if (batch->n_out > 0) h.step_heads(c, batch, m.b_logits, m.w_lm_head);
|
||||
}
|
||||
|
||||
} /* namespace clef_fp8 */
|
||||
|
||||
RAD_ARCH_PROBE(qwen35_clef_fp8)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(clef_fp8, "clef", "fp8_e4m3", "0.1.0",
|
||||
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_fp8, "
|
||||
"block-scaled fp8, with the joint schema head on the card for /v1/systemone")
|
||||
+301
-30
@@ -15,7 +15,9 @@
|
||||
#include "rad_device.h"
|
||||
#include "rad_runtime.h"
|
||||
#include "rad_yarn.h"
|
||||
#include "rad_abi_layout.h"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -35,9 +37,12 @@ namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* One thread per tensor-parallel rank in one process (spec §1), and declare runs once per rank,
|
||||
* so declared handles are per-rank state; a single global would let rank 1 overwrite rank 0.
|
||||
* libr4d all-reduces over 2/4/8 ranks, hence eight. */
|
||||
enum { MAX_RANKS = 8 };
|
||||
* so declared handles are per-instance state; a single global would let rank 1 overwrite rank 0.
|
||||
* libr4d all-reduces over 2/4/8 ranks, hence eight ranks. Several engines may run in the process
|
||||
* (docs/MULTIMODEL.md), each with its own ranks, so state is indexed by the instance's slot
|
||||
* (rad_build_slot at declare, rad_slot in step), unique across all of them, never by the rank two
|
||||
* engines share. */
|
||||
enum { MAX_RANKS = 8, MAX_SLOTS = RAD_MAX_SLOTS };
|
||||
|
||||
/* ================================================================== a debug residual probe
|
||||
*
|
||||
@@ -122,6 +127,36 @@ inline const char* calib_dir() {
|
||||
return d && *d ? d : nullptr;
|
||||
}
|
||||
|
||||
/* Whether layer `layer` taps (RADIANCE_CALIB_LAYERS: comma-separated layers and "lo-hi" ranges;
|
||||
* unset, every layer). A model whose per-expert Hessians do not fit the host at once (Nemotron-3.5
|
||||
* Bolt's are 169 GiB) calibrates in several runs over disjoint ranges; each run writes only its
|
||||
* layers' files, so the runs share one directory. */
|
||||
inline bool calib_layer_on(int layer) {
|
||||
static const std::vector<std::pair<int, int>> ranges = [] {
|
||||
std::vector<std::pair<int, int>> r;
|
||||
const char* s = std::getenv("RADIANCE_CALIB_LAYERS");
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const long lo = std::strtol(s, &e, 10);
|
||||
if (e == s) break;
|
||||
long hi = lo;
|
||||
if (*e == '-') {
|
||||
const char* h = e + 1;
|
||||
hi = std::strtol(h, &e, 10);
|
||||
if (e == h) break;
|
||||
}
|
||||
r.emplace_back((int)lo, (int)hi);
|
||||
s = *e == ',' ? e + 1 : e;
|
||||
if (*s && *s != ',' && !std::isdigit((unsigned char)*s)) break;
|
||||
}
|
||||
return r;
|
||||
}();
|
||||
if (!std::getenv("RADIANCE_CALIB_LAYERS")) return true;
|
||||
for (const auto& r : ranges)
|
||||
if (layer >= r.first && layer <= r.second) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Token count at which the tap dumps and switches itself off (RADIANCE_CALIB_TOKENS, default
|
||||
* 65536). Whether the tap runs at all is calib_dir()'s decision. */
|
||||
inline long long calib_target() {
|
||||
@@ -188,13 +223,14 @@ inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const c
|
||||
return calib_write_host(h.data(), k, rows, what, domain, rad_rank(c));
|
||||
}
|
||||
|
||||
/* A pinned host buffer of at least `bytes`, one per rank, held for the process lifetime, so a tap
|
||||
* that copies a scratch back every pass runs at link speed. Null (and logged) on failure. */
|
||||
/* A pinned host buffer of at least `bytes`, one per instance (slot), held for the process
|
||||
* lifetime, so a tap that copies a scratch back every pass runs at link speed. Null (and logged)
|
||||
* on failure. */
|
||||
inline float* calib_staging(RadCtx* c, int64_t bytes) {
|
||||
static std::mutex mu;
|
||||
static std::map<int, std::pair<void*, int64_t>> per_rank;
|
||||
static std::map<int, std::pair<void*, int64_t>> per_slot;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
std::pair<void*, int64_t>& s = per_rank[rad_rank(c)];
|
||||
std::pair<void*, int64_t>& s = per_slot[rad_slot(c)];
|
||||
if (s.second >= bytes) return (float*)s.first;
|
||||
if (s.first) rad_dev_free(s.first, RAD_MEM_HOST_PINNED);
|
||||
s.first = rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED);
|
||||
@@ -513,12 +549,33 @@ inline int map_copy_alt(RadBuilder* b, const char* declared, const char* a, cons
|
||||
|
||||
/* One expert's slice of a stacked checkpoint tensor. GGUF stores a MoE layer's experts as one
|
||||
* ffn_gate_exps [.., n_expert], while placement moves one expert at a time and so needs one
|
||||
* declared weight per expert (spec §4.2). src_index carries the expert index explicitly. */
|
||||
inline int map_slice(RadBuilder* b, const char* declared, const char* src, int index) {
|
||||
* declared weight per expert (spec §4.2). src_index carries the expert index explicitly.
|
||||
*
|
||||
* `sub_rows` is for a stack flattened into the rows of a rank-2 tensor (Nomic's
|
||||
* experts.mlp.w1 is [n_expert * n_ff, n_embd]): it is the sub-tensor's row count, so the slice is
|
||||
* rows [index * sub_rows, (index + 1) * sub_rows). Left 0, a rank-3 stack takes index as its
|
||||
* dim-0 sub-tensor. */
|
||||
inline int map_slice(RadBuilder* b, const char* declared, const char* src, int index,
|
||||
int64_t sub_rows = 0) {
|
||||
RadNameMap m = map_base(declared, RAD_MAP_COPY);
|
||||
m.n_src = 1;
|
||||
m.src[0] = src;
|
||||
m.src_index[0]= index;
|
||||
m.src_rows[0] = sub_rows;
|
||||
return rad_decl_name_map(b, &m);
|
||||
}
|
||||
|
||||
/* One expert's slice of a stacked tensor, transposed: the per-expert table a grouped GEMM reads
|
||||
* when the checkpoint keeps it [in, out]. A rank-3 stack takes index as its dim-0 sub-tensor. A
|
||||
* rank-2 stack flattened over its rows takes `sub_rows` as the sub-tensor's row count, as
|
||||
* map_slice's. */
|
||||
inline int map_transpose_slice(RadBuilder* b, const char* declared, const char* src, int index,
|
||||
int64_t sub_rows = 0) {
|
||||
RadNameMap m = map_base(declared, RAD_MAP_TRANSPOSE);
|
||||
m.n_src = 1;
|
||||
m.src[0] = src;
|
||||
m.src_index[0]= index;
|
||||
m.src_rows[0] = sub_rows;
|
||||
return rad_decl_name_map(b, &m);
|
||||
}
|
||||
|
||||
@@ -617,9 +674,15 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w));
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. */
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
|
||||
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. A plugin declares
|
||||
* none where the deployment turns the reads off (RadBuildCtx::weight_prefetch_off). */
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes, int64_t blocks = 0) {
|
||||
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
|
||||
/* `blocks`: the workgroups reading, where the architecture measured its own count (docs/OPS.md);
|
||||
* 0 leaves the kernel's. Stated only when asked, so a declaration without it is what it was. */
|
||||
if (blocks > 0)
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes), RAD_INT("blocks", blocks)),
|
||||
RAD_WEIGHTS(w));
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
|
||||
}
|
||||
|
||||
@@ -663,6 +726,9 @@ struct Geom {
|
||||
int64_t max_tok = 0;
|
||||
int64_t max_seqs = 0;
|
||||
int64_t max_ctx = 0;
|
||||
/* --kv-resident in tokens (RadBuildCtx::kv_resident_blocks), 0 when nothing streams: what
|
||||
* kv_resolve_declare states as the ring's depth. */
|
||||
int64_t kv_resident = 0;
|
||||
int max_spec = 0;
|
||||
/* Most rows the sampler can want in one step: one per sequence, or one per draft position per
|
||||
* sequence at a speculative verify. Bounds the logits buffer (at a 248K vocab, 63 MiB rather
|
||||
@@ -676,9 +742,9 @@ struct Geom {
|
||||
/* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as
|
||||
* `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */
|
||||
int64_t wire_min_bytes = 0;
|
||||
/* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it).
|
||||
* decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */
|
||||
int attn_prefill_fp8 = 0;
|
||||
/* RadBuildCtx::plain_norm: a block norm none of whose readers takes codes may run as `add` +
|
||||
* `rmsnorm` (rad_fp8.h, NormQuantFP8::x_only). */
|
||||
int plain_norm = 0;
|
||||
float eps = 1e-6f;
|
||||
/* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and
|
||||
* store `w` near 0.1, so reading it as a plain gain shrinks every normed activation 5-10x. An
|
||||
@@ -714,6 +780,12 @@ struct Geom {
|
||||
* setting because producers and consumers must agree; the plugin reads it off a trunk weight's
|
||||
* encoding and every linear checks its own against it. */
|
||||
bool w_bf16 = false;
|
||||
/* The linears are rotated int8 (rad_fp8.h's linear_is_w8h: IQ8R, or the 128-group form) with
|
||||
* one activation scale per `w_i8_group` columns, for a plugin whose producers are declared away
|
||||
* from its probe: each then declares an int8 code pair (ActFP8::declare_pair). Model-wide as
|
||||
* w_bf16 is. */
|
||||
bool w_i8h = false;
|
||||
int64_t w_i8_group = 128;
|
||||
|
||||
int64_t q_dim() const { return n_head * head_dim; }
|
||||
int64_t kv_dim() const { return n_head_kv * head_dim; }
|
||||
@@ -939,6 +1011,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.max_tok = c->max_tok;
|
||||
g.max_seqs = c->max_seqs;
|
||||
g.max_ctx = c->max_ctx;
|
||||
g.kv_resident = c->kv_resident_blocks;
|
||||
g.max_spec = c->max_spec;
|
||||
g.max_logit_rows = c->max_seqs * (c->max_spec > 0 ? c->max_spec + 1 : 1);
|
||||
if (g.max_logit_rows > c->max_tok) g.max_logit_rows = c->max_tok;
|
||||
@@ -949,7 +1022,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.world = c->world_size ? c->world_size : 1;
|
||||
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.attn_prefill_fp8 = c->attn_prefill_fp8;
|
||||
g.plain_norm = c->plain_norm != 0;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
@@ -1059,6 +1132,95 @@ inline int64_t vocab_head_rows(const Geom& g) {
|
||||
* handle. */
|
||||
inline RadOperand kv_cache(rad_kvgroup group, int layer) { return RAD_KV(group, layer); }
|
||||
|
||||
/* One layer of a streamed group (RadKVStream): its rows of the host mirror and the ring's maps.
|
||||
* The mirror is layer-major over the group's bound layers in KVPoolBinding::layer_slot order, not
|
||||
* over model layers (Flash-Next's full-attention layers are every other layer, plus the MTP head),
|
||||
* so the row comes from rad_kv_layer_index. `host` is null when the group does not stream on this
|
||||
* rank or has no row for the layer. */
|
||||
struct KVStreamLayer {
|
||||
const RadKVStream* st = nullptr;
|
||||
const uint8_t* host = nullptr; /* [blocks, bbytes] mirror row */
|
||||
int32_t* res = nullptr; /* [blocks] block -> ring slot, -1 when absent */
|
||||
int32_t* slot_block = nullptr; /* [slots] ring slot -> block */
|
||||
int32_t* slot_state = nullptr; /* [slots, 2] */
|
||||
int64_t blocks = 0, bbytes = 0, slots = 0;
|
||||
};
|
||||
inline KVStreamLayer kv_stream_layer(RadCtx* c, rad_kvgroup group, int layer,
|
||||
const RadKVGroupBatch* kvb) {
|
||||
KVStreamLayer L;
|
||||
const RadKVStream* st = kvb ? kvb->stream : nullptr;
|
||||
if (!st || !st->host || st->block_bytes <= 0) return L;
|
||||
const int64_t li = rad_kv_layer_index(c, group, layer);
|
||||
if (li < 0) return L;
|
||||
L.st = st;
|
||||
L.bbytes = st->block_bytes;
|
||||
L.blocks = st->host_layer_stride / L.bbytes;
|
||||
L.slots = st->slots;
|
||||
L.host = st->host + li * st->host_layer_stride;
|
||||
L.res = st->res + li * L.blocks;
|
||||
L.slot_block = st->slot_block + li * L.slots;
|
||||
L.slot_state = st->slot_state + li * L.slots * 2;
|
||||
return L;
|
||||
}
|
||||
|
||||
/* The prefill stage of a streamed group (the ordering rule is in core/kvstream/stage.h):
|
||||
*
|
||||
* kv_stage_wait -- immediately before the layer's store: the copy from the mirror must land
|
||||
* before the store writes this chunk's newer bytes into the stage;
|
||||
* kv_stage_layer -- before the attention: true when the pass uses the stage, so the caller
|
||||
* reads block ids directly and must not resolve;
|
||||
* kv_stage_next -- after every attention launch of the layer: the next layer's copy starts
|
||||
* once the last read of the aliased stage is behind it.
|
||||
*
|
||||
* Both of the first two are rad_kv_stage_layer, which stages a layer once per pass. */
|
||||
inline bool kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) {
|
||||
return rad_kv_stage_layer(c, group, kvb, layer) != 0;
|
||||
}
|
||||
inline bool kv_stage_wait(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) {
|
||||
return rad_kv_stage_layer(c, group, kvb, layer) != 0;
|
||||
}
|
||||
inline void kv_stage_next(RadCtx* c, rad_kvgroup group, int layer) {
|
||||
(void)rad_kv_stage_next(c, group, layer);
|
||||
}
|
||||
|
||||
/* The `kv_resolve` a streamed group's block declares. None of its geometry is free:
|
||||
*
|
||||
* blocks the block-id space a selection can name: max_seqs sequences of the context;
|
||||
* slots the ring --kv-resident carves, in whole blocks, raised to one decode step's
|
||||
* selection (max_seqs x (1 + n_spec) x sel_pitch) as kvstream_ring raises it, and
|
||||
* at most `blocks`; the resolve is issued with the pool's depth, so declaring the
|
||||
* context would size its scratch for slots it cannot reach;
|
||||
* sel_pitch the selection row's pitch, which the attention declares its rows with
|
||||
* (`qsa_topk + 1` on the sparse path, the indexer's count on GLM).
|
||||
*
|
||||
* The kernel sizes its claim list from these (`M * sel_pitch`, r4d_kv_resolve.hip's
|
||||
* kv_claim_cap); ctl[12] reports the largest claim count a launch made, so a wrong declaration
|
||||
* shows in the engine's stream report. `sel` is read as well as written, so the arena keeps it
|
||||
* live from its producer to the attention. Returns 0 when the op is not declared or the group has
|
||||
* nothing to address. */
|
||||
inline rad_op kv_resolve_declare(RadBuilder* b, const Geom& g, rad_kvgroup kv, rad_buf sel,
|
||||
rad_buf nsel, int64_t sel_pitch) {
|
||||
if (!rad_op_declared(b, "kv_resolve") || !sel || !nsel || sel_pitch <= 0) return 0;
|
||||
const int64_t bs = rad_kv_block_size(b, kv);
|
||||
const int64_t bbytes = rad_kv_layer_bytes(b, kv);
|
||||
const int64_t blocks = bs > 0 ? g.max_seqs * ((g.max_ctx + bs - 1) / bs) : 0;
|
||||
if (bs <= 0 || bbytes <= 0 || blocks <= 0) return 0;
|
||||
const int64_t ring = g.kv_resident > 0 ? (g.kv_resident + bs - 1) / bs : 0;
|
||||
const int64_t step = g.max_seqs * (1 + (g.max_spec > 0 ? g.max_spec : 0)) * sel_pitch;
|
||||
const int64_t want = ring > 0 && step > ring ? step : ring;
|
||||
const int64_t slots = want > 0 && want < blocks ? want : blocks;
|
||||
const rad_op op = RAD_OP(b, "kv_resolve",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", blocks),
|
||||
RAD_INT("slots", slots), RAD_INT("sel_pitch", sel_pitch),
|
||||
RAD_INT("block_bytes", bbytes)),
|
||||
RAD_NOWEIGHTS);
|
||||
if (!op) return 0;
|
||||
const rad_buf rd[2] = { sel, nsel };
|
||||
rad_op_reads(b, op, rd, 2);
|
||||
rad_op_writes(b, op, &sel, 1);
|
||||
return op;
|
||||
}
|
||||
|
||||
/* ================================================================== step-sized operands */
|
||||
/* Every operand a step issues carries the step's row count, not the buffer's.
|
||||
*
|
||||
@@ -1097,6 +1259,17 @@ inline RadOperand bcol_at(rad_buf h, int64_t first_row, int64_t pitch,
|
||||
return o;
|
||||
}
|
||||
|
||||
/* Whether every logits row this step samples belongs to a sequence that carries words for the
|
||||
* plugin (RadBatch::plugin_words). A head that answers from those words then has no use for the
|
||||
* lm_head's row: it is sampled once and discarded. One row a sampled sequence; a speculative
|
||||
* step samples more and answers false. */
|
||||
inline bool plugin_words_cover_rows(const RadBatch* b) {
|
||||
if (b->n_out <= 0 || !b->plugin_cu_h) return false;
|
||||
int64_t n = 0;
|
||||
for (int64_t s = 0; s < b->n_seq; ++s) n += b->plugin_cu_h[s + 1] > b->plugin_cu_h[s] ? 1 : 0;
|
||||
return n == b->n_out;
|
||||
}
|
||||
|
||||
/* Rows [first, first + n), seen by the kernel as [n, pitch]; RadOperand::offset is in elements.
|
||||
*
|
||||
* Lets one op be issued in slices: an op whose widest kernel stops at M=64 (the delta net's
|
||||
@@ -1124,6 +1297,16 @@ inline RadOperand praw(const void* p, uint32_t dtype, int64_t rows) {
|
||||
return o;
|
||||
}
|
||||
|
||||
/* kv_resolve over `rows` selection rows (kv_resolve_declare): makes the blocks they name resident
|
||||
* in the ring and rewrites `sel` from block ids to ring slots. */
|
||||
inline void kv_resolve_issue(RadCtx* c, rad_op op, const KVStreamLayer& L, RadOperand sel,
|
||||
RadOperand nsel, rad_kvgroup group, int layer, int64_t rows) {
|
||||
RAD_ISSUE_N(c, op, rows, sel, nsel, praw(L.res, RAD_I32, L.blocks),
|
||||
praw(L.slot_block, RAD_I32, L.slots), praw2(L.slot_state, RAD_I32, L.slots, 2),
|
||||
praw(L.st->ctl, RAD_I32, 16), praw2(L.host, RAD_U8, L.blocks, L.bbytes),
|
||||
kv_cache(group, layer));
|
||||
}
|
||||
|
||||
/* Rotary positions of a pass, in the two forms consumers take.
|
||||
*
|
||||
* `rope_pos1`: one component per token, RadBatch::rope_pos's plane 0 if present, else
|
||||
@@ -1156,16 +1339,6 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the
|
||||
* parameters are passed unchanged, so op identities and tune keys do not change. */
|
||||
inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
|
||||
* after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
|
||||
* free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
|
||||
@@ -1274,16 +1447,18 @@ inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int6
|
||||
}
|
||||
|
||||
/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them,
|
||||
* `mode` otherwise. */
|
||||
* `mode` otherwise. `op` names the row: "rope" (every caller), or "rope_rows" for a model that
|
||||
* wants the per-(token, pair) angles form at prefill row counts. */
|
||||
inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim,
|
||||
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) {
|
||||
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode,
|
||||
const char* op = "rope") {
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", g.rope_mc ? g.rope_mode : mode),
|
||||
RAD_INT("rotary_dim", rot), RAD_STR("sections", g.rope_sections) };
|
||||
const int n = (int)(sizeof ps / sizeof ps[0]) - (g.rope_mc ? 0 : 1);
|
||||
return decl_rotary(b, g, "rope", ps, n, nullptr, 0);
|
||||
return decl_rotary(b, g, op, ps, n, nullptr, 0);
|
||||
}
|
||||
|
||||
/* How many of this step's sequences are decode rows, and where their tokens end.
|
||||
@@ -1300,6 +1475,45 @@ inline void batch_split(const RadBatch* b, int64_t* n_seq_dec, int64_t* n_tok_de
|
||||
}
|
||||
}
|
||||
|
||||
/* What a step's attention reads of the QSA selection (AttnGatedFP8::qsa_use), which decides what
|
||||
* the indexer issues for the layer (QsaIndexer::step, docs/QSA.md "Below the bound"):
|
||||
*
|
||||
* kQsaSelect score and select, per layer: a step past the exactness bound, a streamed group,
|
||||
* and every step of a block that did not ask for the forms below;
|
||||
* kQsaUnread nothing reads the selection: the step is entirely at or below the bound and its
|
||||
* attention is the dense one, or the sparse row over the sequence's own block table
|
||||
* (one row a sequence), which is what the selection would be. The indexer stores its
|
||||
* keys and tail and issues no query, score or select;
|
||||
* kQsaOnce the attention reads a selection (the sparse row a query) on a step entirely at or
|
||||
* below the bound: every complete block is taken whatever it scores, so the
|
||||
* selection depends on the positions and the block table alone and is the same
|
||||
* bytes at every layer. The first full-attention layer of the pass issues it as
|
||||
* always; no later layer issues a query, a score or a select. */
|
||||
enum QsaUse : int { kQsaSelect = 0, kQsaUnread = 1, kQsaOnce = 2 };
|
||||
|
||||
/* Ops of a chain that is independent of a block's own, for the block to issue behind its ordered
|
||||
* launches. A recorded pass lets a launch start beside the last ordered one when it touches
|
||||
* nothing in flight (Ctx::haz_mark). A dependent chain issued in one piece is therefore a row of
|
||||
* ordered launches, each paid in turn; issued one op behind each of the block's own ordered
|
||||
* launches, every op of it is unordered behind the block's launch in front of it, and still
|
||||
* behind its own predecessor, which that launch already waited for. The block calls `at(k)` for
|
||||
* k = 0, 1, 2, ... behind its ordered launches in turn, and the owner issues what is left once
|
||||
* the block returns. The chain must read nothing the block writes and write nothing the block
|
||||
* touches, and its buffers must be excluded from sharing (rad_buf_concurrent): they are in use at
|
||||
* launches the linear order puts after their last declared use. */
|
||||
struct SideOps {
|
||||
void (*fn)(void* u, int stage) = nullptr;
|
||||
void* u = nullptr;
|
||||
void at(int stage) const { if (fn) fn(u, stage); }
|
||||
};
|
||||
|
||||
/* RADIANCE_DEBUG_QSA_EAGER: every step is kQsaSelect, the issue sequence before the forms above
|
||||
* existed. An instrument for comparing the two (the text must not move); read once. */
|
||||
inline bool qsa_eager() {
|
||||
static const bool on = std::getenv("RADIANCE_DEBUG_QSA_EAGER") != nullptr;
|
||||
return on;
|
||||
}
|
||||
|
||||
/* The step batch's entry for one declared KV group (built once per step by the core, spec §8). */
|
||||
inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
|
||||
for (int i = 0; i < b->n_kv_groups; ++i)
|
||||
@@ -1307,6 +1521,44 @@ inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* ================================================================== calibration in slices */
|
||||
|
||||
/* The draft head's rows: the vocabulary's first RADIANCE_MTP_DRAFT_VOCAB ids (a prefix shortlist,
|
||||
* rounded down to whole 16-row tiles) or all of it. Byte-level BPE vocabularies number their
|
||||
* merges by frequency, so a prefix keeps the likely drafts and the head reads that much less of
|
||||
* its weight a draft round; a draft outside it is never proposed, which costs acceptance only --
|
||||
* the verify still runs the full head. */
|
||||
inline int64_t mtp_draft_rows(int64_t n_vocab_all) {
|
||||
static const long long want = [] {
|
||||
const char* s = std::getenv("RADIANCE_MTP_DRAFT_VOCAB");
|
||||
return s ? std::atoll(s) : 0LL;
|
||||
}();
|
||||
if (want <= 0 || want >= n_vocab_all) return n_vocab_all;
|
||||
const int64_t r = (int64_t)want / 16 * 16;
|
||||
return r > 0 ? r : n_vocab_all;
|
||||
}
|
||||
|
||||
/* The layers [lo, hi) of n a calibration taps: the environment variable `var` as "lo:hi", else
|
||||
* all of them. A large model's Grams do not fit beside its weights at once, so it is calibrated
|
||||
* in slices of layers, the corpus pushed through once a slice. */
|
||||
inline int calib_layers(const char* who, const char* var, int64_t n, int64_t* lo, int64_t* hi) {
|
||||
*lo = 0;
|
||||
*hi = n;
|
||||
const char* s = std::getenv(var);
|
||||
if (!s) return RAD_OK;
|
||||
long long l = 0, h = 0;
|
||||
int used = 0;
|
||||
if (std::sscanf(s, "%lld:%lld%n", &l, &h, &used) != 2 || s[used] != '\0' || l < 0 || h > n ||
|
||||
l >= h) {
|
||||
fprintf(stderr, "radiance: %s: %s '%s' is not lo:hi within 0:%lld\n", who, var, s,
|
||||
(long long)n);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
*lo = l;
|
||||
*hi = h;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== a block drafter */
|
||||
/* A drafter's Geom: the target's (n_embd, vocabulary, deployment bounds, rank, wire) with the
|
||||
* layer, head, feed-forward, norm and rotary geometry of the container's `draft.` config, split
|
||||
@@ -1323,7 +1575,12 @@ inline const char* drafter_layer_prefix(const RadModelMeta* meta) {
|
||||
return "draft.transformer_layer_config.";
|
||||
return "draft.";
|
||||
}
|
||||
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) {
|
||||
/* `kv_repl_ok`: the drafter block reads its k and v at Geom::kv_off (rad_block_dflash2.h does), so
|
||||
* fewer KV heads than ranks are replicated as geom_from replicates the target's: world a multiple
|
||||
* of the head count, one KV head a rank, `kv_off` its first row in the unsharded k/v projection.
|
||||
* Otherwise such a world is refused, as before. */
|
||||
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what,
|
||||
bool kv_repl_ok = false) {
|
||||
dg = target;
|
||||
const char* pre = drafter_layer_prefix(meta);
|
||||
char key[160];
|
||||
@@ -1348,7 +1605,15 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, pre, dg.head_dim));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv));
|
||||
/* The target's kv_off is the target's; the drafter's is set here or zero. */
|
||||
dg.kv_off = 0;
|
||||
if (kv_repl_ok && dg.world > dg.n_head_kv_all && dg.world % dg.n_head_kv_all == 0) {
|
||||
dg.n_head_kv = 1; /* world / n_head_kv_all ranks share each KV head */
|
||||
dg.kv_off = (dg.rank / (dg.world / dg.n_head_kv_all)) * dg.head_dim;
|
||||
} else {
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads",
|
||||
&dg.n_head_kv));
|
||||
}
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff));
|
||||
const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all);
|
||||
if (dvocab != dg.n_vocab_all) {
|
||||
@@ -1396,6 +1661,7 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
|
||||
NS::step(c, batch); \
|
||||
} \
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } \
|
||||
extern "C" uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); } \
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) { \
|
||||
/* The plugin's name (rad_abi.h: "qwen3_dense_bf16"), not the architecture id: plugin \
|
||||
* names must be unique and one architecture can have several plugins. */ \
|
||||
@@ -1432,6 +1698,11 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
|
||||
#define RAD_ARCH_SERVES_IMPORTS(V) \
|
||||
extern "C" int rad_arch_serves_imports(void) { return V; }
|
||||
|
||||
/* RAD_ARCH_MULTI_INSTANCE() states that the plugin keeps all per-instance state by slot, so several
|
||||
* engines in one process may run it at once (rad_builder.h, rad_arch_multi_instance). */
|
||||
#define RAD_ARCH_MULTI_INSTANCE() \
|
||||
extern "C" int rad_arch_multi_instance(void) { return 1; }
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
|
||||
/* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
|
||||
* kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
* the GEMM output directly.
|
||||
* - No output gate. The attention output goes straight into the out-projection.
|
||||
*
|
||||
* `rotary_dim` 0 is attention without positions (NoPE, Nemotron-H's attention layers): no `rope`
|
||||
* is declared, and position reaches the model through its recurrent layers alone.
|
||||
*
|
||||
* That allows a fused q|k|v, which the gated block cannot have (its query projection is [q|gate]
|
||||
* interleaved per head). The three weights concatenate along dim 0 into one
|
||||
* [q_dim + 2*kv_dim, n_embd], and `rope` takes that row as is: q heads, then k heads, v untouched
|
||||
@@ -81,19 +84,21 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
const int64_t q_dim = g.q_dim();
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
if (n_rot < 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* No KV-head replication: the fused [q|k|v] uses the plain even row shard, so above the KV head
|
||||
* count a rank would read the wrong rows. rad_block_attn_gated_fp8.h is the block that uses
|
||||
* geom_from's `kv_off`. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld.\n", __func__, g.world,
|
||||
(long long)g.n_head_kv_all);
|
||||
/* Above the KV head count geom_from replicates KV heads (rad_arch.h): each of the fused row's
|
||||
* three parts takes its own span (as gemma4's q|k|v does), q this rank's heads and k and v the
|
||||
* shared head at `kv_off`, where the even shard would hand a rank part of a head. A smaller
|
||||
* attention world (Geom::attn_world) is not served here. */
|
||||
const bool kv_repl = g.world > g.n_head_kv_all;
|
||||
if (kv_repl && g.attn_world != g.world) {
|
||||
fprintf(stderr, "radiance: %s replicates KV heads but declares no attention-zero ranks; "
|
||||
"world_size = %d must be a multiple of n_head_kv = %lld.\n", __func__,
|
||||
g.world, (long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
@@ -107,9 +112,17 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
|
||||
0, { q_dim, kv_dim, kv_dim }));
|
||||
if (kv_repl) {
|
||||
const int64_t lo[3] = { g.rank * q_dim, g.kv_off, g.kv_off };
|
||||
const int64_t hi[3] = { lo[0] + q_dim, lo[1] + kv_dim, lo[2] + kv_dim };
|
||||
const int64_t tot[3] = { g.n_head_all * g.head_dim, g.n_head_kv_all * g.head_dim,
|
||||
g.n_head_kv_all * g.head_dim };
|
||||
RAD_ARCH_TRY(qkv.span_parts(b, lo, hi, tot, 3));
|
||||
}
|
||||
|
||||
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
|
||||
{w.qkv}, {w.qkv});
|
||||
if (n_rot > 0)
|
||||
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
|
||||
{w.qkv}, {w.qkv});
|
||||
|
||||
/* Copies the query out of the fused row: libr4d's paged attention reads `q` as a dense
|
||||
* [total_q, n_head, head_dim] block with no pitch argument (r4d_attn_args.h, fill_paged), so a
|
||||
@@ -124,7 +137,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
|
||||
* explains declare vs issue order). */
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
@@ -179,7 +192,7 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
qkv.step(c, w.h, w.qkv, T);
|
||||
/* In place over the fused row: rotates n_head query heads, then n_head_kv key heads, and
|
||||
* leaves the value heads alone. */
|
||||
RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
|
||||
if (op_rope) RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
|
||||
|
||||
/* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
|
||||
@@ -195,7 +195,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
*
|
||||
* The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
|
||||
* a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* state); the gate pass quantises the out-projection's input.
|
||||
* - Per-head norms, rope, kv_store and attn_paged stay bf16.
|
||||
* - The KV cache dtype is `g.kv_dtype`, not `g.dtype`: it is a deployment choice that selects
|
||||
* libr4d's fp8kv attention family. The attention op and kv_store both take it, so they agree.
|
||||
* the attention family's cache rows. The attention op and kv_store both take it, so they agree.
|
||||
* - Optional fused prologue, QSA sparse attention and an attention-zero mode (see declare).
|
||||
*
|
||||
* The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, scale plane
|
||||
@@ -69,6 +69,7 @@ struct AttnGatedFP8 {
|
||||
* block table and context length: same op, same kernel, different list. `sel` is `topk + 1`
|
||||
* wide and the kernel takes its block-table pitch from the operand. */
|
||||
rad_buf qsa_sel = 0;
|
||||
rad_buf qsa_nsel = 0; /* [max_tok] i32, the valid entries of each `qsa_sel` row */
|
||||
rad_buf qsa_sequ = 0;
|
||||
/* Context length up to which dense attention gives the same result, `budget + ratio - 1`.
|
||||
* Below it every complete block is selected, the paths agree to the bit, and dense is cheaper
|
||||
@@ -78,6 +79,21 @@ struct AttnGatedFP8 {
|
||||
/* `sel`'s row pitch is `topk + 1`; the extra slot is the partial page
|
||||
* (r4d_qsa_select_bf16.hip). */
|
||||
int64_t qsa_topk = 0;
|
||||
/* The architecture's word that a sequence with one row in the step has that row at its
|
||||
* context's last position (`seqused - 1`: a plain decode row, a serial head's round), so at or
|
||||
* below `qsa_exact_to` such a row's selection is the head of the sequence's block table and its
|
||||
* `seqused` the sequence's (qsa_select: every complete block in block order, then the partial
|
||||
* page, and `pos + 1`). The sparse row is then issued over the table and the indexer selects
|
||||
* nothing (qsa_use). Off: such a step keeps the selection. */
|
||||
bool qsa_table_rows = false;
|
||||
/* The architecture's pass key carries whether this group's exact host bound
|
||||
* (RadBatch::kv_used_max_h, the furthest context any row of the step can read) is within
|
||||
* `qsa_exact_to`, so that bound may say whether the step needs scores (qsa_within) in place of
|
||||
* the rounded `max_ctx_len + max_q_len`, which a 4-row step leaves at 1025 tokens. It never
|
||||
* moves the choice between the dense and the sparse kernel, which stays the rounded bound's:
|
||||
* the two agree on the keys, not on the last bit of the sum. Off: the rounded bound, which the
|
||||
* core's key holds. */
|
||||
bool qsa_exact_host = false;
|
||||
/* Query rows per sparse attention launch, a scratch budget. The decode kernel's split-KV
|
||||
* partials are sized at declare from `max_seqs` and `q_len`, so issuing more rows than
|
||||
* `max_seqs` means declaring a larger value, which grows the scratch arena (the maximum over
|
||||
@@ -106,14 +122,35 @@ struct AttnGatedFP8 {
|
||||
/* The input was normed and quantised by the caller; this block declares no norm. */
|
||||
bool ext_in = false;
|
||||
LinearFP8 qg{}, kp{}, vp{}, o{};
|
||||
/* Set by the architecture after declare: a `prefetch` of the out projection's leading bytes
|
||||
* (decl_prefetch, rad_arch.h), issued behind the q, k and v projections on decode steps
|
||||
* (prefetch_beside). 0 where none is declared. */
|
||||
rad_op op_pf_o = 0;
|
||||
/* The same read as a second op for steps of at least pf_o_v_rows rows, where the
|
||||
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
|
||||
* every step takes op_pf_o. */
|
||||
rad_op op_pf_o_v = 0;
|
||||
int64_t pf_o_v_rows = 0;
|
||||
/* The most rows of a decode step whose k and v projections are issued in front of the q|gate
|
||||
* projection (step()); 0, the default, keeps the declared order on every step. */
|
||||
int64_t kv_first_rows = 0;
|
||||
NormQuantFP8 nq_h{};
|
||||
|
||||
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
|
||||
rad_op op_fused_kv = 0; /* the same with kv_store folded in */
|
||||
/* The same with the streamed store folded in, issued instead when the batch hands this group a
|
||||
* stream (its mirror and map are the batch's). */
|
||||
rad_op op_fused_stream = 0;
|
||||
int64_t fused_rows = 0; /* widest T the fused ops take */
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_gq = 0;
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 or gate_had_quant_i8g */
|
||||
/* kv_store_streamed: the host mirror always, the ring slot when `res` says the block is resident
|
||||
* (docs/OPS.md). Zero when no row serves it; a streamed group then fails the step. */
|
||||
rad_op op_kv_stream = 0;
|
||||
/* kv_resolve: this layer's selection made resident and rewritten as ring slots, issued before
|
||||
* each sparse launch. */
|
||||
rad_op op_resolve = 0;
|
||||
/* The output gate as `sigmoid` then `mul`: the bf16-linear form (Geom::w_bf16), and with fp8
|
||||
* linears the chain gate_quant_fp8 fuses, where it is not served. `gate` is the sigmoid's
|
||||
* output (the wire's with bf16 linears, the block's own otherwise) and `q_gate` the chain's
|
||||
@@ -143,12 +180,23 @@ struct AttnGatedFP8 {
|
||||
* by passes that only leave layer state behind, such as the MTP head's history pass over a
|
||||
* prompt chunk with no drafting row. */
|
||||
void store_kv(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The layer's cache store, before its resolve and attention: `kv_store`, or for a streamed
|
||||
* group the stage wait and `kv_store_streamed`. */
|
||||
void store_cache(RadCtx* c, const RadKVGroupBatch* kvb, const int32_t* slot, int64_t T) const;
|
||||
/* A staged pass reads the pool at block-id identity, while the streamed store writes only
|
||||
* where the residency map names a ring slot (none before the group's first decode). This
|
||||
* stores the same bytes at identity, after the mirror writer. */
|
||||
void store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const;
|
||||
|
||||
/* The block's tail, declared last by every rank: the all-reduce and the trailing add. */
|
||||
int declare_out(RadBuilder* b, bool add_out);
|
||||
/* `own_ar` false: the caller issues the all-reduce itself (GdnFP8::step says when). */
|
||||
/* `side`: an independent chain's ops, issued behind this block's ordered launches (SideOps,
|
||||
* rad_arch.h): one behind the prologue and the store, one behind the attention, one behind
|
||||
* the gate where the gate is a launch of its own. Null, and on the paths that return early,
|
||||
* nothing is asked of it. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
|
||||
ArPieces* pieces = nullptr) const;
|
||||
ArPieces* pieces = nullptr, const SideOps* side = nullptr) const;
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
|
||||
@@ -157,6 +205,57 @@ struct AttnGatedFP8 {
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
|
||||
/* Whether step() with `own_ar` false runs the dense path a piece at a time over a caller's
|
||||
* normed pieces (ArPieces::in_ready): one prefill sequence in two pieces, each the chunk a
|
||||
* span of 1 makes, on the unfused prologue with one rotary component per token (every token's
|
||||
* components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and
|
||||
* the gate quantised by gate_quant_fp8. A streamed group never takes it: the pieces path's
|
||||
* plain store never writes the host mirror. */
|
||||
/* The rounded host bound of the furthest context a row of the step reads; by it a step of
|
||||
* several rows a sequence takes the dense or the sparse kernel (step(), `sparse`). */
|
||||
int64_t qsa_reach(const RadBatch* batch) const {
|
||||
return (int64_t)batch->max_ctx_len + batch->max_q_len;
|
||||
}
|
||||
/* Whether every row of the step is at or below the exactness bound, by the tightest host
|
||||
* ceiling there is: the group's exact one where the pass key holds its side of the bound
|
||||
* (qsa_exact_host), else the rounded one. Every row's position + 1 is at most either. */
|
||||
bool qsa_within(const RadBatch* batch, const RadKVGroupBatch* kvb) const {
|
||||
if (qsa_exact_to <= 0) return false;
|
||||
int64_t reach = qsa_reach(batch);
|
||||
if (qsa_exact_host && kvb && batch->kv && batch->kv_used_max_h) {
|
||||
const int64_t tight = batch->kv_used_max_h[kvb - batch->kv];
|
||||
if (tight > 0 && tight < reach) reach = tight;
|
||||
}
|
||||
return reach <= qsa_exact_to;
|
||||
}
|
||||
/* What this step's attention reads of the selection (QsaUse, rad_arch.h); the architecture
|
||||
* hands it to the indexer, which runs first, and step() takes its path by the same call. */
|
||||
int qsa_use(const RadBatch* batch) const {
|
||||
if (!qsa_sel || !qsa_sequ || op_fill || qsa_eager()) return kQsaSelect;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
/* A streamed group may be ring-bound, where every pass is sparse and the resolve rewrites
|
||||
* the selection; it keeps the selection at every context. */
|
||||
if (!kvb || kvb->stream || !kvb->block_table || !kvb->seqused) return kQsaSelect;
|
||||
if (!qsa_within(batch, kvb)) return kQsaSelect;
|
||||
/* One row a sequence is the sparse row at every context: over the table where the
|
||||
* architecture vouches for it, else over a selection. */
|
||||
if (batch->n_tok == batch->n_seq)
|
||||
return (qsa_table_rows && batch->max_q_len == 1) ? kQsaUnread : kQsaOnce;
|
||||
/* Several rows a sequence: the dense attention, which reads the table, where the rounded
|
||||
* bound is within the budget too, else the sparse row a query over a selection. */
|
||||
return qsa_reach(batch) <= qsa_exact_to ? kQsaUnread : kQsaOnce;
|
||||
}
|
||||
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
return pieces && pieces->in_ready && pieces->cu && pieces->cuts(T) &&
|
||||
T <= 2 * pieces->rows && !op_add && !op_fill && op_gq && !op_sig && !qsa_sel &&
|
||||
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL &&
|
||||
!(T <= fused_rows) && batch->positions && !rope_mixed(batch) &&
|
||||
kvb && !kvb->stream && kvb->slot_mapping && kvb->block_table && kvb->seqused;
|
||||
}
|
||||
};
|
||||
|
||||
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
@@ -219,7 +318,15 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* One norm+quantise op feeds all three input projections (rad_fp8.h: NormQuantFP8). */
|
||||
/* One norm+quantise op feeds all three input projections (rad_fp8.h: NormQuantFP8). Where
|
||||
* none of them reads the code pair, the plain form (NormQuantFP8::x_only): the projections are
|
||||
* probed for it first, and their declare() does not map them again. */
|
||||
if (!ext_in && g.plain_norm && ar_in == kArNone && !g.attn_zero) {
|
||||
RAD_ARCH_TRY(qg.probe(b, nm, g, nm.f("blk.%d.attn_qg", l), { src.qg }));
|
||||
RAD_ARCH_TRY(kp.probe(b, nm, g, nm.f("blk.%d.attn_k", l), { src.k }));
|
||||
RAD_ARCH_TRY(vp.probe(b, nm, g, nm.f("blk.%d.attn_v", l), { src.v }));
|
||||
nq_h.x_only = qg.codes_free && kp.codes_free && vp.codes_free;
|
||||
}
|
||||
if (!ext_in)
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0, 0, ar_in));
|
||||
@@ -293,7 +400,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size`
|
||||
* (rad_block_attn_gated.h). */
|
||||
op_attn = decl_attn(b, g, "attn_paged",
|
||||
op_attn = rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
@@ -311,11 +418,18 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
* ids: an aperture violation outside the cache. rad_op_reads rather than rw() because the list
|
||||
* depends on whether the layer has an indexer. */
|
||||
if (op_attn) {
|
||||
const rad_buf rd[3] = { w.q, qsa_sel, qsa_sequ };
|
||||
rad_op_reads(b, op_attn, rd, (qsa_sel && qsa_sequ) ? 3 : 1);
|
||||
const rad_buf rd[4] = { w.q, qsa_sel, qsa_sequ, qsa_nsel };
|
||||
rad_op_reads(b, op_attn, rd,
|
||||
(qsa_sel && qsa_sequ) ? (qsa_nsel ? 4 : 3) : 1);
|
||||
rad_op_writes(b, op_attn, &w.attn.x, 1);
|
||||
}
|
||||
|
||||
/* The resolve belongs here rather than in the indexer: it must follow this layer's store,
|
||||
* since a block copied in from the mirror has to carry this step's tokens. Its band is the
|
||||
* step's widest launch and its row `qsa_topk + 1` wide, as the attention declares. */
|
||||
if (qsa_sel && qsa_nsel)
|
||||
op_resolve = kv_resolve_declare(b, g, kv, qsa_sel, qsa_nsel, qsa_topk + 1);
|
||||
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
@@ -324,10 +438,23 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* The streamed store: kv_store's operands and parameters plus the residency map and the layer's
|
||||
* mirror row, which the batch carries (store_cache). `block_size` does not bind the group;
|
||||
* `attn_paged` already has. */
|
||||
if (rad_op_declared(b, "kv_store_streamed"))
|
||||
op_kv_stream = rw(b, RAD_OP(b, "kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* The fused prologue with the cache store folded in: a k head's block already holds its
|
||||
* token's rotated k, so it also writes k and v into the cache, byte-identical to kv_store.
|
||||
* Declared here because the cache block size is read back from the attention op above.
|
||||
* Resolves for E4M3 and bf16 caches. */
|
||||
* Resolves for either cache. */
|
||||
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store"))
|
||||
op_fused_kv = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
|
||||
@@ -340,6 +467,20 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm)),
|
||||
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
|
||||
|
||||
/* The fold for a streamed group: also writes the mirror and consults the residency map, whose
|
||||
* operands are added at issue. */
|
||||
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
|
||||
op_fused_stream = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("n_head_kv", g.n_head_kv), RAD_INT("rot", n_rot),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm)),
|
||||
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
|
||||
|
||||
/* Output gate, multiply and quantiser in one pass (`gate_quant_fp8`); at decode the dispatch
|
||||
* gaps between three small ops are comparable to the work. Each row is a (token, head) pair:
|
||||
* the gate is a fixed stride inside [q|gate], the attention output is contiguous, and the
|
||||
@@ -374,18 +515,29 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
if (g.w_bf16) {
|
||||
RAD_ARCH_TRY(gate_pair(w.gate));
|
||||
} else {
|
||||
if (rad_op_declared(b, "gate_quant_fp8"))
|
||||
op_gq = rw(b, RAD_OP(b, "gate_quant_fp8",
|
||||
/* Rotated int8 codes (ActFP8::q8_rot): gate_had_quant_i8g, had_quant_act_i8g's codes. */
|
||||
const char* gq = w.attn.q8_rot ? "gate_had_quant_i8g" : "gate_quant_fp8";
|
||||
if (rad_op_declared(b, gq))
|
||||
op_gq = rw(b, RAD_OP(b, gq,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("n", g.head_dim), RAD_INT("group", w.attn.cg()),
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
|
||||
/* Under Geom::plain_norm an out projection that reads no codes (a 4-bit one) takes the
|
||||
* pair alone: the quantiser after it wrote codes nobody read. */
|
||||
bool o_plain = false;
|
||||
if (!op_gq && g.plain_norm) {
|
||||
RAD_ARCH_TRY(o.probe(b, nm, g, nm.f("blk.%d.attn_output", l), { src.o }));
|
||||
o_plain = o.codes_free && o.reads_x;
|
||||
}
|
||||
if (!op_gq && g.head_dim % RAD_FP8_BLOCK == 0) {
|
||||
RAD_ARCH_TRY(gate_pair(decl_b(b, nm.f("blk.%d.attn_gate", l), g.act_dtype,
|
||||
{g.max_tok, q_dim})));
|
||||
RAD_ARCH_TRY(q_gate.declare(b, g, w.attn, q_dim));
|
||||
if (!q_gate.op) return RAD_E_INVAL;
|
||||
if (!o_plain) {
|
||||
RAD_ARCH_TRY(q_gate.declare(b, g, w.attn, q_dim));
|
||||
if (!q_gate.op) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,10 +545,12 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
* row is one (token, head) at q_len 1, and the merge already holds the head_dim values the gate
|
||||
* and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the
|
||||
* pair). Declared only with a selection: the dense path also uses the prefill kernel, which
|
||||
* has no merge. */
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 &&
|
||||
rad_op_declared(b, "attn_paged_gate_quant")) {
|
||||
op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
|
||||
* has no merge. Rotated int8 codes (ActFP8::q8_rot) take attn_paged_gate_had_quant, the merge
|
||||
* with gate_had_quant_i8g's quantiser. */
|
||||
const char* attn_gq = w.attn.q8_rot ? "attn_paged_gate_had_quant" : "attn_paged_gate_quant";
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && w.attn.cg() == RAD_FP8_BLOCK &&
|
||||
rad_op_declared(b, attn_gq)) {
|
||||
op_attn_gq = RAD_OP(b, attn_gq,
|
||||
RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
@@ -454,6 +608,34 @@ inline int AttnGatedFP8::declare_out(RadBuilder* b, bool add_out) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_kv_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, layer));
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_cache(RadCtx* c, const RadKVGroupBatch* kvb,
|
||||
const int32_t* slot, int64_t T) const {
|
||||
if (!kvb || !kvb->stream) {
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
return;
|
||||
}
|
||||
/* A streamed group writes its host mirror, and the ring slot only where the block is resident
|
||||
* (docs/OPS.md "kv_store_streamed"). kv_store alone would treat a block id as a ring slot, so
|
||||
* a build without the streamed store fails the step. */
|
||||
const bool staged = kv_stage_wait(c, kv, kvb, layer);
|
||||
const KVStreamLayer L = kv_stream_layer(c, kv, layer, kvb);
|
||||
if (!op_kv_stream || !L.host || L.blocks <= 0) {
|
||||
rad_step_fail(c, "kv streaming: this layer's KV group streams but the build has no "
|
||||
"kv_store_streamed row to write its host mirror with");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE(c, op_kv_stream,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer),
|
||||
praw(L.res, RAD_I32, L.blocks), praw2(L.host, RAD_U8, L.blocks, L.bbytes));
|
||||
if (staged) store_stage_identity(c, slot, T);
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
@@ -464,12 +646,11 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
|
||||
vp.step(c, w.h, w.v, T);
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
store_cache(c, kvb, slot, T);
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
ArPieces* pieces) const {
|
||||
ArPieces* pieces, const SideOps* side) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
@@ -477,6 +658,51 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
/* One prefill sequence in two pieces over the caller's normed input (takes_pieces): the
|
||||
* projections, prologue, cache store, attention, gate and out projection of the first piece,
|
||||
* then the second's, so the first piece's reduction runs beside all of the second piece's
|
||||
* work. Each piece is the chunk a span of 1 makes: its rows, its positions, its slots, and an
|
||||
* attention over its own query bounds (ArPieces::cu) that sees the cache up to its own end --
|
||||
* the first piece's position after its last row, the step's seqused for the second, which
|
||||
* reads the first piece's keys from the cache as a later chunk would. */
|
||||
if (!own_ar && takes_pieces(batch, pieces)) {
|
||||
const int64_t R = pieces->rows, hd = g.head_dim, qw = g.q_dim();
|
||||
const int64_t qgw = g.n_head * 2 * hd, kvw = g.n_head_kv * hd;
|
||||
const int64_t tpitch = kvb->block_table_pitch;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p == 0 ? 0 : R;
|
||||
const int64_t n = p == 0 ? R : T - R;
|
||||
const int32_t* pos = (batch->rope_pos ? batch->rope_pos : batch->positions) + r0;
|
||||
qg.step(c, w.h, w.qg, T, r0, n);
|
||||
kp.step(c, w.h, w.k, T, r0, n);
|
||||
vp.step(c, w.h, w.v, T, r0, n);
|
||||
RAD_ISSUE_N(c, op_q_norm, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, 0, hd, n), RAD_W(w_q_norm),
|
||||
brow_slice(w.q, r0, n, qw));
|
||||
RAD_ISSUE_N(c, op_k_norm, n * g.n_head_kv,
|
||||
brow_slice(w.k, r0, n, kvw), RAD_W(w_k_norm),
|
||||
brow_slice(w.k, r0, n, kvw));
|
||||
RAD_ISSUE_N(c, op_rope_q, n, brow_slice(w.q, r0, n, qw), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_rope_k, n, brow_slice(w.k, r0, n, kvw), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_kv_store, n,
|
||||
brow_slice(w.k, r0, n, kvw), brow_slice(w.v, r0, n, kvw),
|
||||
praw(slot + r0, RAD_I32, n), kv_cache(kv, layer));
|
||||
RAD_ISSUE_N(c, op_attn, n,
|
||||
brows(w.q, T), kv_cache(kv, layer), praw2(table, RAD_I32, 1, tpitch),
|
||||
praw(p == 0 ? batch->positions + R : used, RAD_I32, 1),
|
||||
RAD_NONE, RAD_NONE, praw(pieces->cu + p, RAD_I32, 2),
|
||||
brows(w.attn.x, T));
|
||||
RAD_ISSUE_N(c, op_gq, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, hd, hd, n), brow_slice(w.attn.x, r0, n, qw),
|
||||
brow_slice(w.attn.cq(), r0, n, qw),
|
||||
brow_slice(w.attn.cs(), r0, n, qw / w.attn.cg()),
|
||||
brow_slice(w.attn.x, r0, n, qw));
|
||||
o.step(c, w.attn, w.h.x, T, r0, n);
|
||||
if (p == 0) pieces->hand(r0, n);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
if (op_fill) {
|
||||
/* Attention-zero rank: zero output, then the reduce and the residual. */
|
||||
@@ -486,17 +712,47 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
return;
|
||||
}
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
/* The three projections read the same input and none reads another's output, so a recorded
|
||||
* pass starts them together (Ctx::haz_mark) whatever their order; the order decides which
|
||||
* the card launches first. On a decode step of up to `kv_first_rows` rows the two small ones
|
||||
* go first: behind the wide q|gate projection their launches wait until its blocks are all
|
||||
* on the card, and the prologue then waits for them. Qwen3.8-Flash-Next at tp 2, chain 3
|
||||
* with coupling (twelve trunk layers and the head's): -0.66% a step. */
|
||||
if (T <= kv_first_rows && batch->phase == RAD_PHASE_DECODE) {
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
} else {
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
}
|
||||
/* The out projection's weight, read beside the prologue and the attention (op_pf_o). */
|
||||
prefetch_beside(c, op_pf_o_v && T >= pf_o_v_rows ? op_pf_o_v : op_pf_o, o.w, T);
|
||||
|
||||
/* Fused or unfused prologue. The fused kernel takes the whole [q|gate] projection and splits it
|
||||
* itself, and rotates k in place like the unfused ops. It reads one rotary component per
|
||||
* token, so a pass with media tokens (differing components) takes the unfused path with the
|
||||
* full [3, T] positions. */
|
||||
const bool fuse_ok = T <= fused_rows && !rope_mixed(batch);
|
||||
const bool fused_kv = op_fused_kv && fuse_ok;
|
||||
if (fused_kv) {
|
||||
/* A streamed group folds the streamed store into the prologue instead (op_fused_stream); one
|
||||
* whose layer has no mirror row leaves the store to store_cache, which fails the step. */
|
||||
const bool streamed = kvb && kvb->stream;
|
||||
const bool fused_kv = op_fused_kv && fuse_ok && !streamed;
|
||||
const KVStreamLayer L = streamed && op_fused_stream && fuse_ok
|
||||
? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
|
||||
const bool folded_stream = L.host && L.blocks > 0;
|
||||
if (folded_stream) {
|
||||
/* The prologue is the store, so the stage copy must land before it (kv_stage_wait). */
|
||||
const bool staged = kv_stage_wait(c, kv, kvb, layer);
|
||||
RAD_ISSUE_N(c, op_fused_stream, T,
|
||||
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
|
||||
RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
brows(w.q, T), brows(w.k, T), RAD_NONE,
|
||||
brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer),
|
||||
praw(L.res, RAD_I32, L.blocks), praw2(L.host, RAD_U8, L.blocks, L.bbytes));
|
||||
if (staged) store_stage_identity(c, slot, T);
|
||||
} else if (fused_kv) {
|
||||
RAD_ISSUE_N(c, op_fused_kv, T,
|
||||
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
|
||||
RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
@@ -516,9 +772,8 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
|
||||
if (!fused_kv)
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
if (!fused_kv && !folded_stream) store_cache(c, kvb, slot, T);
|
||||
if (side) side->at(0);
|
||||
|
||||
/* Sparse attention issues one row per query. `attn_paged` indexes its block table and length
|
||||
* by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with
|
||||
@@ -531,10 +786,46 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* Launches are chunked because the split-KV scratch is sized at declare from `max_seqs` and
|
||||
* `q_len` (rows = max_seqs * q_len_max * heads); more rows are refused as RAD_E_SCRATCH at
|
||||
* issue. Rows of q_len 1 up to the declared max_seqs always fit. */
|
||||
const int64_t reach = (int64_t)batch->max_ctx_len + batch->max_q_len;
|
||||
const int64_t reach = qsa_reach(batch);
|
||||
/* A pass on a streamed group's ring (a ring smaller than the id space, and not staged) must
|
||||
* take the sparse path: on the ring a block id is not a pool address, so the dense path would
|
||||
* read ring slots as pages. `T == n_seq` alone misses a verify pass, whose T is
|
||||
* n_seq x (1 + n_spec), on a context under qsa_exact_to. A ring that covers the context keeps
|
||||
* the dense path, where ids and slots coincide. */
|
||||
const RadKVStream* st = kvb ? kvb->stream : nullptr;
|
||||
const int64_t st_blocks =
|
||||
(st && st->block_bytes > 0) ? st->host_layer_stride / st->block_bytes : 0;
|
||||
const bool ring_addressed = st && st->slots > 0 && st_blocks > 0 && st->slots < st_blocks;
|
||||
const bool ring_bound = ring_addressed && !kv_stage_layer(c, kv, kvb, layer);
|
||||
const bool sparse = qsa_sel && qsa_sequ &&
|
||||
(T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to);
|
||||
(ring_bound || T == batch->n_seq || qsa_exact_to <= 0 ||
|
||||
reach > qsa_exact_to);
|
||||
/* At or below the bound a step of one row a sequence has no selection (qsa_use): the sparse
|
||||
* row reads the sequence's own block table and length, which is what qsa_select would have
|
||||
* written for it (the field says why), so the launch, its kernel and its bytes are the sparse
|
||||
* row's. */
|
||||
const bool by_table = sparse && T == batch->n_seq && qsa_use(batch) == kQsaUnread;
|
||||
const int64_t tpitch = kvb ? kvb->block_table_pitch : 0;
|
||||
auto sel_rows = [&](int64_t off, int64_t rows) {
|
||||
return by_table ? praw2(table + off * tpitch, RAD_I32, rows, tpitch)
|
||||
: brow_slice(qsa_sel, off, rows, qsa_topk + 1);
|
||||
};
|
||||
auto sequ_rows = [&](int64_t off, int64_t rows) {
|
||||
return by_table ? praw(used + off, RAD_I32, rows) : brow_slice(qsa_sequ, off, rows, 1);
|
||||
};
|
||||
const bool gated = sparse && op_attn_gq;
|
||||
/* A streamed group's selection, per launch: make the rows' blocks resident and rewrite `sel`
|
||||
* as ring slots, after this layer's store (a block copied in from the mirror must carry this
|
||||
* step's tokens) and before the attention. A pass on the stage view leaves `sel` as block ids
|
||||
* and never resolves, so a prefill cannot overflow the ring. */
|
||||
const KVStreamLayer res_l = op_resolve ? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
|
||||
auto resolve_sel = [&](int64_t off, int64_t rows) {
|
||||
if (by_table) return; /* never a streamed group (qsa_use) */
|
||||
if (kv_stage_layer(c, kv, kvb, layer)) return;
|
||||
if (!res_l.host || res_l.blocks <= 0 || res_l.slots <= 0 || rows <= 0) return;
|
||||
kv_resolve_issue(c, op_resolve, res_l, brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_nsel, off, rows, 1), kv, layer, rows);
|
||||
};
|
||||
/* A piece at a time where the caller takes the all-reduce that way (ArPieces). On the gated
|
||||
* sparse path every query row is its own (q_len 1) and the gate rides in the merge, so the
|
||||
* attention and out projection can finish a piece's rows and hand off its reduction while the
|
||||
@@ -547,20 +838,22 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const int64_t pn = T - p0 < pieces->rows ? T - p0 : pieces->rows;
|
||||
for (int64_t off = p0; off < p0 + pn; off += chunk) {
|
||||
const int64_t rows = (p0 + pn - off) < chunk ? (p0 + pn - off) : chunk;
|
||||
resolve_sel(off, rows);
|
||||
RAD_ISSUE_N(c, op_attn_gq, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_sequ, off, rows, 1),
|
||||
sel_rows(off, rows), sequ_rows(off, rows),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw),
|
||||
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
|
||||
brow_slice(w.attn.cq(), off, rows, qw),
|
||||
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
|
||||
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
|
||||
}
|
||||
o.step(c, w.attn, w.h.x, T, p0, pn);
|
||||
if (p0 + pn < T) pieces->hand(p0, pn);
|
||||
}
|
||||
/* Every attention launch of this layer is issued: start the next layer's stage copy. */
|
||||
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
|
||||
return;
|
||||
}
|
||||
if (gated) {
|
||||
@@ -568,42 +861,88 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const int64_t qw = g.q_dim(), hd = g.head_dim;
|
||||
for (int64_t off = 0; off < T; off += chunk) {
|
||||
const int64_t rows = (T - off) < chunk ? (T - off) : chunk;
|
||||
resolve_sel(off, rows);
|
||||
RAD_ISSUE_N(c, op_attn_gq, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_sequ, off, rows, 1),
|
||||
sel_rows(off, rows), sequ_rows(off, rows),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw),
|
||||
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
|
||||
brow_slice(w.attn.cq(), off, rows, qw),
|
||||
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
|
||||
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
|
||||
}
|
||||
} else if (sparse) {
|
||||
const int64_t chunk = qsa_rows();
|
||||
const int64_t qw = g.q_dim();
|
||||
for (int64_t off = 0; off < T; off += chunk) {
|
||||
const int64_t rows = (T - off) < chunk ? (T - off) : chunk;
|
||||
resolve_sel(off, rows);
|
||||
RAD_ISSUE_N(c, op_attn, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_sequ, off, rows, 1),
|
||||
sel_rows(off, rows), sequ_rows(off, rows),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw));
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq,
|
||||
kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
/* cu_seqlens: the batch may be ragged (a prefill chunk beside decode rows). */
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
/* Below qsa_exact_to the dense path reads block ids straight from the table and never
|
||||
* resolves, so a staged pass stages this layer here (a no-op without a stage view). A
|
||||
* ring-bound pass with no selection to resolve cannot be served at all. */
|
||||
if (ring_bound) {
|
||||
rad_step_fail(c, "kv streaming: a pass on the streamed group's ring has no selection "
|
||||
"to resolve, so its block ids are not pool addresses");
|
||||
} else if (kvb && kvb->stream) {
|
||||
(void)kv_stage_layer(c, kv, kvb, layer);
|
||||
}
|
||||
/* A mixed step issues its attention once per band, as the GDN blocks do: one launch at
|
||||
* the chunk's band would walk every decode sequence's whole context with one query-tiled
|
||||
* workgroup a KV head, the step's tail beside a long chunk. The decode half (sequences
|
||||
* [0, D), rows [0, DT)) is a prefix at its own band. The prefill half takes its
|
||||
* per-sequence arrays past the decode sequences and keeps q, out and cu at their absolute
|
||||
* rows, as the kernels index q and out by cu.
|
||||
*
|
||||
* The prefill half is issued at the op's top band, not at its own query length: a launch
|
||||
* over part of the step must be served by the query-tiled row, while a short chunk's band
|
||||
* (10 rows or fewer at gqa 6) is the split-KV decode row's, whose partials are sized at
|
||||
* declare for that band and would overflow the scratch. Kernels read exact lengths from
|
||||
* cu, so the loose band costs nothing. A chunk no longer than the verify blocks beside it
|
||||
* keeps one launch at their band: the whole step is decode-shaped then. */
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
const int64_t pitch = kvb ? kvb->block_table_pitch : 0;
|
||||
const int32_t qp = batch->max_q_len_prefill > 0 ? batch->max_q_len_prefill
|
||||
: batch->max_q_len;
|
||||
if (batch->phase == RAD_PHASE_MIXED && D > 0 && D < batch->n_seq &&
|
||||
batch->max_q_len_decode > 0 && qp > batch->max_q_len_decode) {
|
||||
const int64_t P = batch->n_seq - D;
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len_decode,
|
||||
brows(w.q, DT), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, D, pitch), praw(used, RAD_I32, D),
|
||||
RAD_NONE, RAD_NONE, praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
brows(w.attn.x, DT));
|
||||
RAD_ISSUE_N(c, op_attn, g.max_tok,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table ? table + D * pitch : nullptr, RAD_I32, P, pitch),
|
||||
praw(used ? used + D : nullptr, RAD_I32, P),
|
||||
RAD_NONE, RAD_NONE, praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
brows(w.attn.x, T));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, pitch),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
/* cu_seqlens: verify rows may be of different lengths. */
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
}
|
||||
}
|
||||
|
||||
/* Every attention launch of this layer is issued: start the next layer's stage copy, which
|
||||
* crosses the link under the out projection and the next layer's projections. */
|
||||
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
|
||||
if (side) side->at(1);
|
||||
if (gated) {
|
||||
/* the sparse attention gated and quantised in its merge */
|
||||
} else if (op_sig) {
|
||||
@@ -617,6 +956,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.attn.x, T),
|
||||
brows(w.attn.cq(), T), brows(w.attn.cs(), T), brows(w.attn.x, T));
|
||||
}
|
||||
if (side && !gated) side->at(2);
|
||||
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
|
||||
|
||||
@@ -0,0 +1,666 @@
|
||||
/* rad_block_clef.h -- clef's joint schema head, inside the backbone's plugin.
|
||||
*
|
||||
* Cloudflare's clef and clef-flash decide every question of a request jointly from the backbone's
|
||||
* final hidden state at EVERY prompt position (joint_schema_model.py, JointSchemaHead). This block
|
||||
* runs that head on the card, after the trunk, so /v1/systemone needs no second process:
|
||||
*
|
||||
* per token, every step hn = layernorm(h); hn is stored in a paged KV group of its own,
|
||||
* so a prefix hit keeps the rows the trunk did not recompute
|
||||
* per request, once every row of hn is gathered back out of the group's blocks, the
|
||||
* memory projection and the six cross-attention layers run over all
|
||||
* of them, the question and option spans are averaged, and the
|
||||
* routing, decoder layers and scorer give three numbers an option
|
||||
* (its lexical prior, its cosine and its residual) into the request's
|
||||
* logits row, where the server reads them (core/server/clef.cpp)
|
||||
*
|
||||
* The spans, the option tokens and the question types come as the request's words
|
||||
* (abi/rad_clef.h, RadBatch::plugin_words), laid out as the kernels read them. The head's own
|
||||
* tensors are the release's joint_head.safetensors, added to the container at convert, under their
|
||||
* own names. Every op here has a device kernel and a host reference, so the same block serves
|
||||
* the tiny CPU test and the card.
|
||||
*
|
||||
* Differences from the reference, all within bf16: the cosine and the prior are means of
|
||||
* products of RMS-normalised rows (an identity, with eps 1e-12 against torch's max(norm, 1e-12));
|
||||
* the routing softmax is formed in f32 (seg_softmax_pool). The learned scalars (prior_logit_scale,
|
||||
* joint_logit_scale, residual_gate) are applied by the server from the container header.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
#include <rad_clef.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct ClefHead {
|
||||
bool on = false;
|
||||
|
||||
int64_t E = 0; /* the backbone's hidden size: the head's input width */
|
||||
int64_t W = 0; /* the head's width */
|
||||
int64_t H = 0; /* heads */
|
||||
int64_t HD = 0; /* W / H */
|
||||
int64_t F = 0; /* feedforward */
|
||||
int64_t bs = 0; /* the cache's block size */
|
||||
int64_t nblk = 0; /* blocks a context holds at most */
|
||||
int64_t NM = 0; /* nblk * bs: rows a request holds at most */
|
||||
int64_t n_vocab = 0; /* this rank's logits width */
|
||||
int layer = 0; /* the group's bound layer index */
|
||||
double eps = 1e-5; /* torch.nn.LayerNorm's default */
|
||||
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* ---- weights */
|
||||
rad_weight hn_w = 0, hn_b = 0, w_mem = 0, w_q = 0, w_oq = 0, w_glob = 0, w_octx = 0,
|
||||
w_olex = 0, w_type = 0, osn_w = 0, osn_b = 0, fn_w = 0, fn_b = 0, on_w = 0,
|
||||
on_b = 0, rs1_w = 0, rs1_b = 0, rs2_w = 0, rs2_b = 0;
|
||||
struct Ev {
|
||||
rad_weight qn_w = 0, qn_b = 0, mn_w = 0, mn_b = 0, wq = 0, bq = 0, wk = 0, bk = 0, wv = 0,
|
||||
bv = 0, wo = 0, bo = 0, fn_w = 0, fn_b = 0, w1 = 0, b1 = 0, w2 = 0, b2 = 0;
|
||||
rad_op ln_q = 0, ln_m = 0, pq = 0, pk = 0, pv = 0, attn = 0, po = 0, ln_f = 0, f1 = 0,
|
||||
f2 = 0;
|
||||
};
|
||||
struct Dec {
|
||||
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0, n3w = 0, n3b = 0, sa_w = 0, sa_b = 0,
|
||||
so_w = 0, so_b = 0, cq_w = 0, cq_b = 0, ck_w = 0, ck_b = 0, cv_w = 0, cv_b = 0,
|
||||
co_w = 0, co_b = 0, w1 = 0, b1 = 0, w2 = 0, b2 = 0;
|
||||
rad_op ln1 = 0, qkv = 0, sattn = 0, so = 0, ln2 = 0, pq = 0, pk = 0, pv = 0, cattn = 0,
|
||||
co = 0, ln3 = 0, f1 = 0, f2 = 0;
|
||||
};
|
||||
std::vector<Ev> ev;
|
||||
std::vector<Dec> dec;
|
||||
|
||||
/* ---- buffers */
|
||||
rad_buf b_hn = 0, b_all = 0, b_mem = 0, b_mn = 0, b_k = 0, b_v = 0, b_seg = 0, b_qv = 0,
|
||||
b_oc = 0, b_g = 0, b_lx = 0, b_lex = 0, b_x = 0, b_t1 = 0, b_t2 = 0, b_ff = 0,
|
||||
b_qq = 0, b_bf = 0, b_fr = 0, b_sc = 0, b_sum = 0, b_f = 0, b_fq = 0, b_f1 = 0,
|
||||
b_f2 = 0, b_gw = 0, b_fn = 0, b_on = 0, b_na = 0, b_nb = 0, b_an = 0, b_ln = 0,
|
||||
b_p = 0, b_neg1 = 0, b_d = 0, b_nd = 0, b_abs = 0, b_prod = 0, b_feat = 0, b_r = 0,
|
||||
b_out3 = 0;
|
||||
|
||||
/* ---- ops, one a use site: the arena plans from each op's read and write sets */
|
||||
rad_op op_hn = 0, op_store = 0, op_gather = 0, op_mem = 0, op_seg = 0, op_g_q = 0, op_g_o = 0,
|
||||
op_g_last = 0, op_lex = 0, op_lexmean = 0, op_octx = 0, op_olex = 0, op_add_x1 = 0,
|
||||
op_oq = 0, op_g_oq = 0, op_add_x2 = 0, op_qproj = 0, op_g_fr = 0, op_mul_sc = 0,
|
||||
op_score = 0, op_route = 0, op_ln_osn = 0, op_add_f1 = 0, op_glob = 0, op_add_fg = 0,
|
||||
op_type = 0, op_add_f2 = 0, op_ln_fn = 0, op_g_fr2 = 0, op_ln_on = 0, op_rms_a = 0,
|
||||
op_rms_b = 0, op_mul_cos = 0, op_mean_cos = 0, op_g_an = 0, op_add_an = 0,
|
||||
op_rms_an = 0, op_rms_lex = 0, op_mul_pri = 0, op_mean_pri = 0, op_neg1 = 0,
|
||||
op_nd = 0, op_d = 0, op_relu_d = 0, op_nd2 = 0, op_relu_nd = 0, op_abs = 0,
|
||||
op_prod = 0, op_cp_fr = 0, op_cp_on = 0, op_cp_prod = 0, op_cp_abs = 0, op_rs1 = 0,
|
||||
op_rs2 = 0, op_cast = 0;
|
||||
|
||||
static bool present(const RadModelMeta* meta) {
|
||||
const char* t = rad_meta_gets(meta, "decision.type", "");
|
||||
return t && !std::strcmp(t, "clef");
|
||||
}
|
||||
|
||||
/* Declared after the trunk's layers and lm_head: the trunk's cache block size is known then,
|
||||
* and the head's rows read the final norm's output `b_h` and write `b_logits`. */
|
||||
int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Names& nm,
|
||||
const Geom& g, rad_buf b_h, rad_buf b_logits, rad_weight w_lm_head,
|
||||
rad_kvgroup kv_trunk, int bind_layer);
|
||||
|
||||
/* Every trunk step: the final norm's rows into the head's cache. */
|
||||
void step_tokens(RadCtx* c, const RadBatch* batch, rad_buf b_h);
|
||||
/* After the lm_head: the head over every sequence that carries words. */
|
||||
void step_heads(RadCtx* c, const RadBatch* batch, rad_buf b_logits, rad_weight w_lm_head);
|
||||
|
||||
private:
|
||||
const RadKVGroupBatch* group_of(const RadBatch* batch) const {
|
||||
for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == kv) return &batch->kv[i];
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
inline int ClefHead::declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
|
||||
Names& nm, const Geom& g, rad_buf b_h, rad_buf b_logits,
|
||||
rad_weight w_lm_head, rad_kvgroup kv_trunk, int bind_layer) {
|
||||
(void)ctx;
|
||||
E = g.n_embd;
|
||||
W = rad_meta_geti(meta, "decision.clef.width", 0);
|
||||
H = rad_meta_geti(meta, "decision.clef.heads", 0);
|
||||
F = rad_meta_geti(meta, "decision.clef.feedforward", 0);
|
||||
const long long R = rad_meta_geti(meta, "decision.clef.routing_layers", 0);
|
||||
const long long D = rad_meta_geti(meta, "decision.clef.layers", 0);
|
||||
const long long hidden = rad_meta_geti(meta, "decision.clef.hidden_size", 0);
|
||||
if (W <= 0 || H <= 0 || F <= 0 || R <= 0 || D <= 0 || W % H || hidden != E) {
|
||||
std::fprintf(stderr, "radiance: clef: the container's decision.clef.* keys do not describe "
|
||||
"the head (hidden_size %lld against the backbone's %lld, width %lld, "
|
||||
"heads %lld, feedforward %lld, routing_layers %lld, layers %lld); "
|
||||
"rad-convert sets them from joint_head_config.json\n",
|
||||
hidden, (long long)E, (long long)W, (long long)H, (long long)F, R, D);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
HD = W / H;
|
||||
if (g.world != 1) {
|
||||
std::fprintf(stderr, "radiance: clef's head runs on one rank: its rows are replicated and "
|
||||
"the option tokens read the whole lm_head\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16) != RAD_BF16) {
|
||||
std::fprintf(stderr, "radiance: clef's head averages lm_head rows as bf16; this container's "
|
||||
"lm_head is quantised. Keep output.weight bf16 in the recipe\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (E % 2) return RAD_E_INVAL;
|
||||
bs = rad_kv_block_size(b, kv_trunk);
|
||||
if (bs <= 0) return RAD_E_STATE;
|
||||
/* Rows a request may hold: the context, or the head's own bound where that is less (the
|
||||
* server refuses a longer prompt before it is admitted). */
|
||||
const int64_t rows = g.max_ctx < RAD_CLEF_MAX_PROMPT ? g.max_ctx : RAD_CLEF_MAX_PROMPT;
|
||||
nblk = (rows + bs - 1) / bs;
|
||||
NM = nblk * bs;
|
||||
n_vocab = g.n_vocab;
|
||||
layer = bind_layer;
|
||||
const int64_t QM = RAD_CLEF_MAX_QUESTIONS, OM = RAD_CLEF_MAX_OPTIONS, LM = RAD_CLEF_MAX_LEX;
|
||||
const int64_t SM = 2 * (QM + OM) + 1;
|
||||
if (n_vocab < 3 * OM) {
|
||||
std::fprintf(stderr, "radiance: clef's head writes %lld values into a logits row of %lld\n",
|
||||
(long long)(3 * OM), (long long)n_vocab);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- the cache: one FULL group, hn's two halves as a slot's K and V, so a block holds
|
||||
* bs rows of E in position order and a gather of a sequence's blocks is its rows. Bound past
|
||||
* the trunk, so the scheduler counts it as the head's; cached with the trunk's groups because
|
||||
* its block size is theirs (core/mem/prefix.cpp). */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = RAD_BF16;
|
||||
kd.n_head_kv = 1;
|
||||
kd.head_dim = E / 2;
|
||||
kv = rad_decl_kv_group(b, nm.f("clef.kv"), &kd);
|
||||
if (!kv) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, layer, kv));
|
||||
RAD_ARCH_TRY(rad_declare_plugin_words(b, rad_clef_max_words()));
|
||||
|
||||
/* ---- weights: the release's names, bf16, read once a request. */
|
||||
const int ACC = RAD_ACCESS_PER_REQUEST;
|
||||
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, grp_model());
|
||||
};
|
||||
/* A packed in_proj's third: rows [k W, (k+1) W) of the weight, and of the bias. */
|
||||
auto bw_rows = [&](const char* dn, const char* src, int k, int64_t cols) -> rad_weight {
|
||||
if (map_rows(b, dn, { { src, (int)(k * W), W } }) < 0) return 0;
|
||||
return cols ? decl_w(b, dn, RAD_BF16, { W, cols }, ACC, RAD_SHARD_NONE, grp_model())
|
||||
: decl_w(b, dn, RAD_BF16, { W }, ACC, RAD_SHARD_NONE, grp_model());
|
||||
};
|
||||
hn_w = bw(nm.f("clef.hidden_norm.weight"), nm.ckpt("hidden_norm.weight"), { E });
|
||||
hn_b = bw(nm.f("clef.hidden_norm.bias"), nm.ckpt("hidden_norm.bias"), { E });
|
||||
w_mem = bw(nm.f("clef.memory_projection.weight"), nm.ckpt("memory_projection.weight"), { W, E });
|
||||
w_q = bw(nm.f("clef.question_projection.weight"), nm.ckpt("question_projection.weight"), { W, E });
|
||||
w_oq = bw(nm.f("clef.option_question_projection.weight"), nm.ckpt("option_question_projection.weight"), { W, E });
|
||||
w_glob = bw(nm.f("clef.global_projection.weight"), nm.ckpt("global_projection.weight"), { W, E });
|
||||
w_octx = bw(nm.f("clef.option_context_projection.weight"), nm.ckpt("option_context_projection.weight"), { W, E });
|
||||
w_olex = bw(nm.f("clef.option_lexical_projection.weight"), nm.ckpt("option_lexical_projection.weight"), { W, E });
|
||||
w_type = bw(nm.f("clef.type_embedding.weight"), nm.ckpt("type_embedding.weight"), { 3, W });
|
||||
osn_w = bw(nm.f("clef.option_summary_norm.weight"), nm.ckpt("option_summary_norm.weight"), { W });
|
||||
osn_b = bw(nm.f("clef.option_summary_norm.bias"), nm.ckpt("option_summary_norm.bias"), { W });
|
||||
fn_w = bw(nm.f("clef.field_norm.weight"), nm.ckpt("field_norm.weight"), { W });
|
||||
fn_b = bw(nm.f("clef.field_norm.bias"), nm.ckpt("field_norm.bias"), { W });
|
||||
on_w = bw(nm.f("clef.option_norm.weight"), nm.ckpt("option_norm.weight"), { W });
|
||||
on_b = bw(nm.f("clef.option_norm.bias"), nm.ckpt("option_norm.bias"), { W });
|
||||
/* The scorer's first linear reads [field | option | field*option | |field-option|], one row
|
||||
* of 4 W an option, which the blocks below assemble in `feat`. */
|
||||
rs1_w = bw(nm.f("clef.residual_scorer.0.weight"), nm.ckpt("residual_scorer.0.weight"), { W, 4 * W });
|
||||
rs1_b = bw(nm.f("clef.residual_scorer.0.bias"), nm.ckpt("residual_scorer.0.bias"), { W });
|
||||
rs2_w = bw(nm.f("clef.residual_scorer.3.weight"), nm.ckpt("residual_scorer.3.weight"), { 1, W });
|
||||
rs2_b = bw(nm.f("clef.residual_scorer.3.bias"), nm.ckpt("residual_scorer.3.bias"), { 1 });
|
||||
if (!hn_w || !hn_b || !w_mem || !w_q || !w_oq || !w_glob || !w_octx || !w_olex || !w_type ||
|
||||
!osn_w || !osn_b || !fn_w || !fn_b || !on_w || !on_b || !rs1_w || !rs1_b || !rs2_w || !rs2_b)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
ev.assign((size_t)R, Ev{});
|
||||
for (int i = 0; i < (int)R; ++i) {
|
||||
Ev& e = ev[(size_t)i];
|
||||
const char* p = "evidence_layers";
|
||||
e.qn_w = bw(nm.f("clef.ev.%d.query_norm.weight", i), nm.ckpt("%s.%d.query_norm.weight", p, i), { W });
|
||||
e.qn_b = bw(nm.f("clef.ev.%d.query_norm.bias", i), nm.ckpt("%s.%d.query_norm.bias", p, i), { W });
|
||||
e.mn_w = bw(nm.f("clef.ev.%d.memory_norm.weight", i), nm.ckpt("%s.%d.memory_norm.weight", p, i), { W });
|
||||
e.mn_b = bw(nm.f("clef.ev.%d.memory_norm.bias", i), nm.ckpt("%s.%d.memory_norm.bias", p, i), { W });
|
||||
e.wq = bw_rows(nm.f("clef.ev.%d.q.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 0, W);
|
||||
e.wk = bw_rows(nm.f("clef.ev.%d.k.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 1, W);
|
||||
e.wv = bw_rows(nm.f("clef.ev.%d.v.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 2, W);
|
||||
e.bq = bw_rows(nm.f("clef.ev.%d.q.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 0, 0);
|
||||
e.bk = bw_rows(nm.f("clef.ev.%d.k.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 1, 0);
|
||||
e.bv = bw_rows(nm.f("clef.ev.%d.v.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 2, 0);
|
||||
e.wo = bw(nm.f("clef.ev.%d.o.weight", i), nm.ckpt("%s.%d.attention.out_proj.weight", p, i), { W, W });
|
||||
e.bo = bw(nm.f("clef.ev.%d.o.bias", i), nm.ckpt("%s.%d.attention.out_proj.bias", p, i), { W });
|
||||
e.fn_w = bw(nm.f("clef.ev.%d.ff_norm.weight", i), nm.ckpt("%s.%d.feedforward_norm.weight", p, i), { W });
|
||||
e.fn_b = bw(nm.f("clef.ev.%d.ff_norm.bias", i), nm.ckpt("%s.%d.feedforward_norm.bias", p, i), { W });
|
||||
e.w1 = bw(nm.f("clef.ev.%d.ff1.weight", i), nm.ckpt("%s.%d.feedforward.0.weight", p, i), { F, W });
|
||||
e.b1 = bw(nm.f("clef.ev.%d.ff1.bias", i), nm.ckpt("%s.%d.feedforward.0.bias", p, i), { F });
|
||||
e.w2 = bw(nm.f("clef.ev.%d.ff2.weight", i), nm.ckpt("%s.%d.feedforward.3.weight", p, i), { W, F });
|
||||
e.b2 = bw(nm.f("clef.ev.%d.ff2.bias", i), nm.ckpt("%s.%d.feedforward.3.bias", p, i), { W });
|
||||
if (!e.qn_w || !e.qn_b || !e.mn_w || !e.mn_b || !e.wq || !e.wk || !e.wv || !e.bq || !e.bk ||
|
||||
!e.bv || !e.wo || !e.bo || !e.fn_w || !e.fn_b || !e.w1 || !e.b1 || !e.w2 || !e.b2)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
dec.assign((size_t)D, Dec{});
|
||||
for (int i = 0; i < (int)D; ++i) {
|
||||
Dec& d = dec[(size_t)i];
|
||||
const char* p = "layers";
|
||||
d.n1w = bw(nm.f("clef.dec.%d.norm1.weight", i), nm.ckpt("%s.%d.norm1.weight", p, i), { W });
|
||||
d.n1b = bw(nm.f("clef.dec.%d.norm1.bias", i), nm.ckpt("%s.%d.norm1.bias", p, i), { W });
|
||||
d.n2w = bw(nm.f("clef.dec.%d.norm2.weight", i), nm.ckpt("%s.%d.norm2.weight", p, i), { W });
|
||||
d.n2b = bw(nm.f("clef.dec.%d.norm2.bias", i), nm.ckpt("%s.%d.norm2.bias", p, i), { W });
|
||||
d.n3w = bw(nm.f("clef.dec.%d.norm3.weight", i), nm.ckpt("%s.%d.norm3.weight", p, i), { W });
|
||||
d.n3b = bw(nm.f("clef.dec.%d.norm3.bias", i), nm.ckpt("%s.%d.norm3.bias", p, i), { W });
|
||||
/* Self-attention keeps its packed in_proj: one GEMM, then column slices. */
|
||||
d.sa_w = bw(nm.f("clef.dec.%d.sa.in.weight", i), nm.ckpt("%s.%d.self_attn.in_proj_weight", p, i), { 3 * W, W });
|
||||
d.sa_b = bw(nm.f("clef.dec.%d.sa.in.bias", i), nm.ckpt("%s.%d.self_attn.in_proj_bias", p, i), { 3 * W });
|
||||
d.so_w = bw(nm.f("clef.dec.%d.sa.o.weight", i), nm.ckpt("%s.%d.self_attn.out_proj.weight", p, i), { W, W });
|
||||
d.so_b = bw(nm.f("clef.dec.%d.sa.o.bias", i), nm.ckpt("%s.%d.self_attn.out_proj.bias", p, i), { W });
|
||||
d.cq_w = bw_rows(nm.f("clef.dec.%d.ca.q.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 0, W);
|
||||
d.ck_w = bw_rows(nm.f("clef.dec.%d.ca.k.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 1, W);
|
||||
d.cv_w = bw_rows(nm.f("clef.dec.%d.ca.v.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 2, W);
|
||||
d.cq_b = bw_rows(nm.f("clef.dec.%d.ca.q.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 0, 0);
|
||||
d.ck_b = bw_rows(nm.f("clef.dec.%d.ca.k.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 1, 0);
|
||||
d.cv_b = bw_rows(nm.f("clef.dec.%d.ca.v.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 2, 0);
|
||||
d.co_w = bw(nm.f("clef.dec.%d.ca.o.weight", i), nm.ckpt("%s.%d.multihead_attn.out_proj.weight", p, i), { W, W });
|
||||
d.co_b = bw(nm.f("clef.dec.%d.ca.o.bias", i), nm.ckpt("%s.%d.multihead_attn.out_proj.bias", p, i), { W });
|
||||
d.w1 = bw(nm.f("clef.dec.%d.ff1.weight", i), nm.ckpt("%s.%d.linear1.weight", p, i), { F, W });
|
||||
d.b1 = bw(nm.f("clef.dec.%d.ff1.bias", i), nm.ckpt("%s.%d.linear1.bias", p, i), { F });
|
||||
d.w2 = bw(nm.f("clef.dec.%d.ff2.weight", i), nm.ckpt("%s.%d.linear2.weight", p, i), { W, F });
|
||||
d.b2 = bw(nm.f("clef.dec.%d.ff2.bias", i), nm.ckpt("%s.%d.linear2.bias", p, i), { W });
|
||||
if (!d.n1w || !d.n1b || !d.n2w || !d.n2b || !d.n3w || !d.n3b || !d.sa_w || !d.sa_b ||
|
||||
!d.so_w || !d.so_b || !d.cq_w || !d.ck_w || !d.cv_w || !d.cq_b || !d.ck_b || !d.cv_b ||
|
||||
!d.co_w || !d.co_b || !d.w1 || !d.b1 || !d.w2 || !d.b2)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- buffers, bf16, at the bounds the words are refused past. */
|
||||
b_hn = decl_b(b, nm.f("clef.hn"), RAD_BF16, { g.max_tok, E });
|
||||
b_all = decl_b(b, nm.f("clef.all"), RAD_BF16, { NM, E });
|
||||
b_mem = decl_b(b, nm.f("clef.mem"), RAD_BF16, { NM, W });
|
||||
b_mn = decl_b(b, nm.f("clef.mn"), RAD_BF16, { NM, W });
|
||||
b_k = decl_b(b, nm.f("clef.k"), RAD_BF16, { NM, W });
|
||||
b_v = decl_b(b, nm.f("clef.v"), RAD_BF16, { NM, W });
|
||||
b_seg = decl_b(b, nm.f("clef.seg"), RAD_BF16, { SM, E });
|
||||
b_qv = decl_b(b, nm.f("clef.qv"), RAD_BF16, { QM, E });
|
||||
b_oc = decl_b(b, nm.f("clef.oc"), RAD_BF16, { OM, E });
|
||||
b_g = decl_b(b, nm.f("clef.g"), RAD_BF16, { 1, E });
|
||||
b_lx = decl_b(b, nm.f("clef.lx"), RAD_BF16, { LM, E });
|
||||
b_lex = decl_b(b, nm.f("clef.lex"), RAD_BF16, { OM, E });
|
||||
b_x = decl_b(b, nm.f("clef.x"), RAD_BF16, { OM, W });
|
||||
b_t1 = decl_b(b, nm.f("clef.t1"), RAD_BF16, { OM, W });
|
||||
b_t2 = decl_b(b, nm.f("clef.t2"), RAD_BF16, { OM, W });
|
||||
b_ff = decl_b(b, nm.f("clef.ff"), RAD_BF16, { OM, F });
|
||||
b_qq = decl_b(b, nm.f("clef.qq"), RAD_BF16, { QM, W });
|
||||
b_bf = decl_b(b, nm.f("clef.bf"), RAD_BF16, { QM, W });
|
||||
b_fr = decl_b(b, nm.f("clef.fr"), RAD_BF16, { OM, W });
|
||||
b_sc = decl_b(b, nm.f("clef.sc"), RAD_BF16, { OM, 1 });
|
||||
b_sum = decl_b(b, nm.f("clef.sum"), RAD_BF16, { QM, W });
|
||||
b_f = decl_b(b, nm.f("clef.f"), RAD_BF16, { QM, W });
|
||||
b_fq = decl_b(b, nm.f("clef.fq"), RAD_BF16, { QM, 3 * W });
|
||||
b_f1 = decl_b(b, nm.f("clef.f1"), RAD_BF16, { QM, W });
|
||||
b_f2 = decl_b(b, nm.f("clef.f2"), RAD_BF16, { QM, W });
|
||||
b_gw = decl_b(b, nm.f("clef.gw"), RAD_BF16, { 1, W });
|
||||
b_fn = decl_b(b, nm.f("clef.fn"), RAD_BF16, { QM, W });
|
||||
b_on = decl_b(b, nm.f("clef.on"), RAD_BF16, { OM, W });
|
||||
b_na = decl_b(b, nm.f("clef.na"), RAD_BF16, { OM, W });
|
||||
b_nb = decl_b(b, nm.f("clef.nb"), RAD_BF16, { OM, W });
|
||||
b_an = decl_b(b, nm.f("clef.an"), RAD_BF16, { OM, E });
|
||||
b_ln = decl_b(b, nm.f("clef.ln"), RAD_BF16, { OM, E });
|
||||
b_p = decl_b(b, nm.f("clef.p"), RAD_BF16, { OM, E });
|
||||
b_neg1 = decl_b(b, nm.f("clef.neg1"), RAD_BF16, { 1, W });
|
||||
b_d = decl_b(b, nm.f("clef.d"), RAD_BF16, { OM, W });
|
||||
b_nd = decl_b(b, nm.f("clef.nd"), RAD_BF16, { OM, W });
|
||||
b_abs = decl_b(b, nm.f("clef.abs"), RAD_BF16, { OM, W });
|
||||
b_prod = decl_b(b, nm.f("clef.prod"), RAD_BF16, { OM, W });
|
||||
b_feat = decl_b(b, nm.f("clef.feat"), RAD_BF16, { OM, 4 * W });
|
||||
b_r = decl_b(b, nm.f("clef.r"), RAD_BF16, { OM, W });
|
||||
b_out3 = decl_b(b, nm.f("clef.out3"), RAD_BF16, { 3 * OM, 1 });
|
||||
if (!b_hn || !b_all || !b_mem || !b_mn || !b_k || !b_v || !b_seg || !b_qv || !b_oc || !b_g ||
|
||||
!b_lx || !b_lex || !b_x || !b_t1 || !b_t2 || !b_ff || !b_qq || !b_bf || !b_fr || !b_sc ||
|
||||
!b_sum || !b_f || !b_fq || !b_f1 || !b_f2 || !b_gw || !b_fn || !b_on || !b_na || !b_nb ||
|
||||
!b_an || !b_ln || !b_p || !b_neg1 || !b_d || !b_nd || !b_abs || !b_prod || !b_feat || !b_r ||
|
||||
!b_out3)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- ops. The lambdas state each kind once; the row bound is the op's band. */
|
||||
auto lnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_weight bias) {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gemmb = [&](int64_t rows, int64_t N, int64_t K, const char* act, rad_weight w,
|
||||
rad_weight bias) {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", act)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto gather = [&](int64_t rows, int64_t n) { return unary("gather_rows", rows, n); };
|
||||
auto cross = [&](int64_t rows) {
|
||||
return RAD_OP(b, "attn_cross",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", HD), RAD_INT("gqa", 1),
|
||||
RAD_INT("causal", 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)HD))),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto rmsp = [&](int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, "rmsnorm_p",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", 1e-12),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
/* The mean of a row: a cosine from two RMS-normed rows, or with `mult` the dot product
|
||||
* scaled (mult = n / sqrt(W) gives options . field / sqrt(W)). */
|
||||
auto rowmean = [&](int64_t rows, int64_t n, double mult) {
|
||||
return RAD_OP(b, "pool_cols",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_INT("k", n),
|
||||
RAD_F64("mult", mult), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
|
||||
/* Every step: the final norm's rows into the cache. kv_store carries the block size and so is
|
||||
* the group's consumer (core/build/rad_builder.cpp, find_kv_consumer); its write is the pool. */
|
||||
op_hn = rw(b, lnorm(g.max_tok, E, hn_w, hn_b), { b_h }, { b_hn });
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", E / 2),
|
||||
RAD_INT("n_head_kv", 1), RAD_INT("block_size", bs),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_hn }, {});
|
||||
if (rad_kv_block_size(b, kv) != bs) {
|
||||
std::fprintf(stderr, "radiance: clef's cache took block size %lld, the trunk's is %lld\n",
|
||||
(long long)rad_kv_block_size(b, kv), (long long)bs);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* Per request. A sequence's blocks are rows of bs * E: the gather reads the pool as
|
||||
* [n_blocks, bs * E] and writes `all` as [nblk, bs * E], which the ops below read as rows of E
|
||||
* (a contiguous buffer at another width, core/runtime and libr4d's r4d_rows_pitch). */
|
||||
op_gather = rw(b, gather(nblk, bs * E), {}, { b_all });
|
||||
op_mem = rw(b, gemm(NM, W, E, w_mem), { b_all }, { b_mem });
|
||||
op_seg = rw(b, unary("seg_mean", NM, E), { b_all }, { b_seg });
|
||||
op_g_q = rw(b, gather(QM, E), { b_seg }, { b_qv });
|
||||
op_g_o = rw(b, gather(OM, E), { b_seg }, { b_oc });
|
||||
op_g_last = rw(b, gather(1, E), { b_all }, { b_g });
|
||||
op_lex = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, LM), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_lm_head)),
|
||||
{}, { b_lx });
|
||||
op_lexmean = rw(b, unary("seg_mean", LM, E), { b_lx }, { b_lex });
|
||||
op_octx = rw(b, gemm(OM, W, E, w_octx), { b_oc }, { b_x });
|
||||
op_olex = rw(b, gemm(OM, W, E, w_olex), { b_lex }, { b_t1 });
|
||||
op_add_x1 = rw(b, unary("add", OM, W), { b_x, b_t1 }, { b_x });
|
||||
op_oq = rw(b, gemm(QM, W, E, w_oq), { b_qv }, { b_qq });
|
||||
op_g_oq = rw(b, gather(OM, W), { b_qq }, { b_t1 });
|
||||
op_add_x2 = rw(b, unary("add", OM, W), { b_x, b_t1 }, { b_x });
|
||||
for (Ev& e : ev) {
|
||||
e.ln_q = rw(b, lnorm(OM, W, e.qn_w, e.qn_b), { b_x }, { b_t1 });
|
||||
e.ln_m = rw(b, lnorm(NM, W, e.mn_w, e.mn_b), { b_mem }, { b_mn });
|
||||
e.pq = rw(b, gemmb(OM, W, W, "none", e.wq, e.bq), { b_t1 }, { b_t2 });
|
||||
e.pk = rw(b, gemmb(NM, W, W, "none", e.wk, e.bk), { b_mn }, { b_k });
|
||||
e.pv = rw(b, gemmb(NM, W, W, "none", e.wv, e.bv), { b_mn }, { b_v });
|
||||
e.attn = rw(b, cross(OM), { b_t2, b_k, b_v }, { b_t1 });
|
||||
e.po = rw(b, gemmb(OM, W, W, "none", e.wo, e.bo), { b_t1, b_x }, { b_x });
|
||||
e.ln_f = rw(b, lnorm(OM, W, e.fn_w, e.fn_b), { b_x }, { b_t1 });
|
||||
e.f1 = rw(b, gemmb(OM, F, W, "gelu", e.w1, e.b1), { b_t1 }, { b_ff });
|
||||
e.f2 = rw(b, gemmb(OM, W, F, "none", e.w2, e.b2), { b_ff, b_x }, { b_x });
|
||||
}
|
||||
op_qproj = rw(b, gemm(QM, W, E, w_q), { b_qv }, { b_bf });
|
||||
op_g_fr = rw(b, gather(OM, W), { b_bf }, { b_fr });
|
||||
op_mul_sc = rw(b, unary("mul", OM, W), { b_x, b_fr }, { b_t1 });
|
||||
op_score = rw(b, rowmean(OM, W, (double)W / std::sqrt((double)W)), { b_t1 }, { b_sc });
|
||||
op_route = rw(b, unary("seg_softmax_pool", OM, W), { b_sc, b_x }, { b_sum });
|
||||
op_ln_osn = rw(b, lnorm(QM, W, osn_w, osn_b), { b_sum }, { b_f1 });
|
||||
op_add_f1 = rw(b, unary("add", QM, W), { b_bf, b_f1 }, { b_f });
|
||||
op_glob = rw(b, gemm(1, W, E, w_glob), { b_g }, { b_gw });
|
||||
op_add_fg = rw(b, unary("add", QM, W), { b_f, b_gw }, { b_f });
|
||||
op_type = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, QM), RAD_INT("n_embd", W),
|
||||
RAD_INT("n_vocab", 3), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", 0)),
|
||||
RAD_WEIGHTS(w_type)),
|
||||
{}, { b_f1 });
|
||||
op_add_f2 = rw(b, unary("add", QM, W), { b_f, b_f1 }, { b_f });
|
||||
for (Dec& d : dec) {
|
||||
d.ln1 = rw(b, lnorm(QM, W, d.n1w, d.n1b), { b_f }, { b_f1 });
|
||||
d.qkv = rw(b, gemmb(QM, 3 * W, W, "none", d.sa_w, d.sa_b), { b_f1 }, { b_fq });
|
||||
d.sattn = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, QM), RAD_INT("head_dim", HD),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)HD)),
|
||||
RAD_INT("max_seqlen", QM)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_fq }, { b_f1 });
|
||||
d.so = rw(b, gemmb(QM, W, W, "none", d.so_w, d.so_b), { b_f1, b_f }, { b_f });
|
||||
d.ln2 = rw(b, lnorm(QM, W, d.n2w, d.n2b), { b_f }, { b_f1 });
|
||||
d.pq = rw(b, gemmb(QM, W, W, "none", d.cq_w, d.cq_b), { b_f1 }, { b_f2 });
|
||||
d.pk = rw(b, gemmb(NM, W, W, "none", d.ck_w, d.ck_b), { b_mem }, { b_k });
|
||||
d.pv = rw(b, gemmb(NM, W, W, "none", d.cv_w, d.cv_b), { b_mem }, { b_v });
|
||||
d.cattn = rw(b, cross(QM), { b_f2, b_k, b_v }, { b_f1 });
|
||||
d.co = rw(b, gemmb(QM, W, W, "none", d.co_w, d.co_b), { b_f1, b_f }, { b_f });
|
||||
d.ln3 = rw(b, lnorm(QM, W, d.n3w, d.n3b), { b_f }, { b_f1 });
|
||||
d.f1 = rw(b, gemmb(QM, F, W, "gelu", d.w1, d.b1), { b_f1 }, { b_ff });
|
||||
d.f2 = rw(b, gemmb(QM, W, F, "none", d.w2, d.b2), { b_ff, b_f }, { b_f });
|
||||
}
|
||||
op_ln_fn = rw(b, lnorm(QM, W, fn_w, fn_b), { b_f }, { b_fn });
|
||||
/* The scorer, an option at a time against its question's field. */
|
||||
op_g_fr2 = rw(b, gather(OM, W), { b_fn }, { b_fr });
|
||||
op_ln_on = rw(b, lnorm(OM, W, on_w, on_b), { b_x }, { b_on });
|
||||
op_rms_a = rw(b, rmsp(OM, W), { b_fr }, { b_na });
|
||||
op_rms_b = rw(b, rmsp(OM, W), { b_on }, { b_nb });
|
||||
op_mul_cos = rw(b, unary("mul", OM, W), { b_na, b_nb }, { b_t1 });
|
||||
op_mean_cos = rw(b, rowmean(OM, W, 1.0), { b_t1 }, { b_out3 });
|
||||
op_g_an = rw(b, gather(OM, E), { b_qv }, { b_an });
|
||||
op_add_an = rw(b, unary("add", OM, E), { b_an, b_g }, { b_an });
|
||||
op_rms_an = rw(b, rmsp(OM, E), { b_an }, { b_p });
|
||||
op_rms_lex = rw(b, rmsp(OM, E), { b_lex }, { b_ln });
|
||||
op_mul_pri = rw(b, unary("mul", OM, E), { b_p, b_ln }, { b_an });
|
||||
op_mean_pri = rw(b, rowmean(OM, E, 1.0), { b_an }, { b_out3 });
|
||||
op_neg1 = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", W),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("value", -1.0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_neg1 });
|
||||
op_nd = rw(b, unary("mul", OM, W), { b_on, b_neg1 }, { b_nd });
|
||||
op_d = rw(b, unary("add", OM, W), { b_fr, b_nd }, { b_d });
|
||||
op_relu_d = rw(b, unary("relu", OM, W), { b_d }, { b_abs });
|
||||
op_nd2 = rw(b, unary("mul", OM, W), { b_d, b_neg1 }, { b_nd });
|
||||
op_relu_nd = rw(b, unary("relu", OM, W), { b_nd }, { b_nd });
|
||||
op_abs = rw(b, unary("add", OM, W), { b_abs, b_nd }, { b_abs });
|
||||
op_prod = rw(b, unary("mul", OM, W), { b_fr, b_on }, { b_prod });
|
||||
/* The four feature blocks side by side in `feat`: the field rows are gathered straight into
|
||||
* the first, the other three copied in (cast at one dtype is the copy op), so the scorer's
|
||||
* first linear is one GEMM over 4 W, rounded once as the reference rounds it. */
|
||||
auto copy = [&]() {
|
||||
return RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, OM), RAD_INT("n", W), RAD_STR("from", "bf16"),
|
||||
RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
op_cp_fr = rw(b, copy(), { b_fr }, { b_feat });
|
||||
op_cp_on = rw(b, copy(), { b_on }, { b_feat });
|
||||
op_cp_prod = rw(b, copy(), { b_prod }, { b_feat });
|
||||
op_cp_abs = rw(b, copy(), { b_abs }, { b_feat });
|
||||
op_rs1 = rw(b, gemmb(OM, W, 4 * W, "gelu", rs1_w, rs1_b), { b_feat }, { b_r });
|
||||
op_rs2 = rw(b, gemmb(OM, 1, W, "none", rs2_w, rs2_b), { b_r }, { b_out3 });
|
||||
op_cast = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 3 * OM),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_out3 }, { b_logits });
|
||||
|
||||
rad_note(b, "clef's joint schema head on the card: width %lld, %lld heads of %lld, "
|
||||
"feedforward %lld, %lld routing + %lld decoder layers; hn cached as a FULL group "
|
||||
"of block %lld (%lld rows a context); at most %d questions, %d options, %d option "
|
||||
"tokens a request; three values an option into the logits row",
|
||||
(long long)W, (long long)H, (long long)HD, (long long)F, R, D, (long long)bs,
|
||||
(long long)NM, (int)QM, (int)OM, (int)LM);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void ClefHead::step_tokens(RadCtx* c, const RadBatch* batch, rad_buf b_h) {
|
||||
if (!on || batch->n_tok <= 0) return;
|
||||
const RadKVGroupBatch* kb = group_of(batch);
|
||||
if (!kb) { rad_step_fail(c, "clef: the head's cache group is not in the step batch"); return; }
|
||||
const int64_t T = batch->n_tok;
|
||||
RAD_ISSUE_N(c, op_hn, T, brows(b_h, T), RAD_W(hn_w), RAD_W(hn_b), brows(b_hn, T));
|
||||
RAD_ISSUE_N(c, op_store, T, bcol(b_hn, 0, E / 2, T), bcol(b_hn, E / 2, E / 2, T),
|
||||
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
|
||||
}
|
||||
|
||||
inline void ClefHead::step_heads(RadCtx* c, const RadBatch* batch, rad_buf b_logits,
|
||||
rad_weight w_lm_head) {
|
||||
if (!on || !batch->plugin_cu_h || !batch->plugin_words_h) return;
|
||||
const RadKVGroupBatch* kb = group_of(batch);
|
||||
if (!kb) { rad_step_fail(c, "clef: the head's cache group is not in the step batch"); return; }
|
||||
const int64_t QM = RAD_CLEF_MAX_QUESTIONS, OM = RAD_CLEF_MAX_OPTIONS, LM = RAD_CLEF_MAX_LEX;
|
||||
const int64_t SM = 2 * (QM + OM) + 1;
|
||||
for (int64_t s = 0; s < batch->n_seq; ++s) {
|
||||
const int32_t w0 = batch->plugin_cu_h[s], w1 = batch->plugin_cu_h[s + 1];
|
||||
if (w1 <= w0) continue;
|
||||
if (w1 - w0 < RAD_CLEF_HDR) { rad_step_fail(c, "clef: a request's words have no header"); return; }
|
||||
const int32_t* hw = batch->plugin_words_h + w0;
|
||||
const int32_t* dw = batch->plugin_words + w0;
|
||||
const RadClefWords L = rad_clef_words_read(hw);
|
||||
const int64_t N = L.n, Q = L.q, O = L.o, Lx = L.l, S = L.s;
|
||||
const int32_t row = hw[RAD_CLEF_W_ROW];
|
||||
const int64_t nb = (N + bs - 1) / bs;
|
||||
if (w1 - w0 < L.total || N < 1 || N > NM || Q < 1 || Q > QM || O < 1 || O > OM ||
|
||||
Lx < 1 || Lx > LM || S < 1 || S > SM || row < 0 || row >= batch->n_out ||
|
||||
nb > kb->max_blocks) {
|
||||
rad_step_fail(c, "clef: a request's words are out of the head's bounds");
|
||||
return;
|
||||
}
|
||||
auto dev = [&](int32_t off, int64_t n) { return praw(dw + off, RAD_I32, n); };
|
||||
auto out3 = [&](int64_t at, int64_t rows) { return bcol_at(b_out3, at, 1, 0, 1, rows); };
|
||||
const int32_t* bt = kb->block_table + s * kb->block_table_pitch;
|
||||
|
||||
/* Every row of hn, from the sequence's blocks. */
|
||||
RAD_ISSUE_N(c, op_gather, nb, kv_cache(kv, layer), praw(bt, RAD_I32, nb),
|
||||
brows(b_all, nb * bs));
|
||||
RAD_ISSUE_N(c, op_mem, N, brows(b_all, N), RAD_W(w_mem), brows(b_mem, N));
|
||||
/* The question, option and global vectors. */
|
||||
RAD_ISSUE_N(c, op_seg, N, brows(b_all, N), dev(L.seg_cu, S + 1), brows(b_seg, S));
|
||||
RAD_ISSUE_N(c, op_g_q, Q, brows(b_seg, S), dev(L.q_seg, Q), brows(b_qv, Q));
|
||||
RAD_ISSUE_N(c, op_g_o, O, brows(b_seg, S), dev(L.o_seg, O), brows(b_oc, O));
|
||||
RAD_ISSUE_N(c, op_g_last, 1, brows(b_all, N), dev(L.last, 1), brows(b_g, 1));
|
||||
RAD_ISSUE_N(c, op_lex, Lx, dev(L.lex_ids, Lx), RAD_W(w_lm_head), brows(b_lx, Lx));
|
||||
RAD_ISSUE_N(c, op_lexmean, Lx, brows(b_lx, Lx), dev(L.lex_cu, O + 1), brows(b_lex, O));
|
||||
/* Option queries, then the evidence layers over the memory. */
|
||||
RAD_ISSUE_N(c, op_octx, O, brows(b_oc, O), RAD_W(w_octx), brows(b_x, O));
|
||||
RAD_ISSUE_N(c, op_olex, O, brows(b_lex, O), RAD_W(w_olex), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, op_add_x1, O, brows(b_x, O), brows(b_t1, O), brows(b_x, O));
|
||||
RAD_ISSUE_N(c, op_oq, Q, brows(b_qv, Q), RAD_W(w_oq), brows(b_qq, Q));
|
||||
RAD_ISSUE_N(c, op_g_oq, O, brows(b_qq, Q), dev(L.o_q, O), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, op_add_x2, O, brows(b_x, O), brows(b_t1, O), brows(b_x, O));
|
||||
for (const Ev& e : ev) {
|
||||
RAD_ISSUE_N(c, e.ln_q, O, brows(b_x, O), RAD_W(e.qn_w), RAD_W(e.qn_b), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, e.ln_m, N, brows(b_mem, N), RAD_W(e.mn_w), RAD_W(e.mn_b), brows(b_mn, N));
|
||||
RAD_ISSUE_N(c, e.pq, O, brows(b_t1, O), RAD_W(e.wq), RAD_W(e.bq), RAD_NONE, brows(b_t2, O));
|
||||
RAD_ISSUE_N(c, e.pk, N, brows(b_mn, N), RAD_W(e.wk), RAD_W(e.bk), RAD_NONE, brows(b_k, N));
|
||||
RAD_ISSUE_N(c, e.pv, N, brows(b_mn, N), RAD_W(e.wv), RAD_W(e.bv), RAD_NONE, brows(b_v, N));
|
||||
RAD_ISSUE_N(c, e.attn, O, brows(b_t2, O), brows(b_k, N), brows(b_v, N),
|
||||
dev(L.cu_o, 2), dev(L.cu_k, 2), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, e.po, O, brows(b_t1, O), RAD_W(e.wo), RAD_W(e.bo), brows(b_x, O), brows(b_x, O));
|
||||
RAD_ISSUE_N(c, e.ln_f, O, brows(b_x, O), RAD_W(e.fn_w), RAD_W(e.fn_b), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, e.f1, O, brows(b_t1, O), RAD_W(e.w1), RAD_W(e.b1), RAD_NONE, brows(b_ff, O));
|
||||
RAD_ISSUE_N(c, e.f2, O, brows(b_ff, O), RAD_W(e.w2), RAD_W(e.b2), brows(b_x, O), brows(b_x, O));
|
||||
}
|
||||
/* Base fields, each question's routing over its options, and the field vectors. */
|
||||
RAD_ISSUE_N(c, op_qproj, Q, brows(b_qv, Q), RAD_W(w_q), brows(b_bf, Q));
|
||||
RAD_ISSUE_N(c, op_g_fr, O, brows(b_bf, Q), dev(L.o_q, O), brows(b_fr, O));
|
||||
RAD_ISSUE_N(c, op_mul_sc, O, brows(b_x, O), brows(b_fr, O), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, op_score, O, brows(b_t1, O), brows(b_sc, O));
|
||||
RAD_ISSUE_N(c, op_route, O, brows(b_sc, O), brows(b_x, O), dev(L.opt_cu, Q + 1), brows(b_sum, Q));
|
||||
RAD_ISSUE_N(c, op_ln_osn, Q, brows(b_sum, Q), RAD_W(osn_w), RAD_W(osn_b), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, op_add_f1, Q, brows(b_bf, Q), brows(b_f1, Q), brows(b_f, Q));
|
||||
RAD_ISSUE_N(c, op_glob, 1, brows(b_g, 1), RAD_W(w_glob), brows(b_gw, 1));
|
||||
RAD_ISSUE_N(c, op_add_fg, Q, brows(b_f, Q), brows(b_gw, 1), brows(b_f, Q));
|
||||
RAD_ISSUE_N(c, op_type, Q, dev(L.type, Q), RAD_W(w_type), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, op_add_f2, Q, brows(b_f, Q), brows(b_f1, Q), brows(b_f, Q));
|
||||
for (const Dec& d : dec) {
|
||||
RAD_ISSUE_N(c, d.ln1, Q, brows(b_f, Q), RAD_W(d.n1w), RAD_W(d.n1b), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.qkv, Q, brows(b_f1, Q), RAD_W(d.sa_w), RAD_W(d.sa_b), RAD_NONE, brows(b_fq, Q));
|
||||
RAD_ISSUE_N(c, d.sattn, Q, bcol(b_fq, 0, W, Q), bcol(b_fq, W, W, Q),
|
||||
bcol(b_fq, 2 * W, W, Q), dev(L.cu_q, 2), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.so, Q, brows(b_f1, Q), RAD_W(d.so_w), RAD_W(d.so_b), brows(b_f, Q), brows(b_f, Q));
|
||||
RAD_ISSUE_N(c, d.ln2, Q, brows(b_f, Q), RAD_W(d.n2w), RAD_W(d.n2b), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.pq, Q, brows(b_f1, Q), RAD_W(d.cq_w), RAD_W(d.cq_b), RAD_NONE, brows(b_f2, Q));
|
||||
RAD_ISSUE_N(c, d.pk, N, brows(b_mem, N), RAD_W(d.ck_w), RAD_W(d.ck_b), RAD_NONE, brows(b_k, N));
|
||||
RAD_ISSUE_N(c, d.pv, N, brows(b_mem, N), RAD_W(d.cv_w), RAD_W(d.cv_b), RAD_NONE, brows(b_v, N));
|
||||
RAD_ISSUE_N(c, d.cattn, Q, brows(b_f2, Q), brows(b_k, N), brows(b_v, N),
|
||||
dev(L.cu_q, 2), dev(L.cu_k, 2), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.co, Q, brows(b_f1, Q), RAD_W(d.co_w), RAD_W(d.co_b), brows(b_f, Q), brows(b_f, Q));
|
||||
RAD_ISSUE_N(c, d.ln3, Q, brows(b_f, Q), RAD_W(d.n3w), RAD_W(d.n3b), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.f1, Q, brows(b_f1, Q), RAD_W(d.w1), RAD_W(d.b1), RAD_NONE, brows(b_ff, Q));
|
||||
RAD_ISSUE_N(c, d.f2, Q, brows(b_ff, Q), RAD_W(d.w2), RAD_W(d.b2), brows(b_f, Q), brows(b_f, Q));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_ln_fn, Q, brows(b_f, Q), RAD_W(fn_w), RAD_W(fn_b), brows(b_fn, Q));
|
||||
/* The scorer: the cosine, the lexical prior and the residual, one value an option, into
|
||||
* out3's three stretches (prior | cosine | residual). */
|
||||
RAD_ISSUE_N(c, op_g_fr2, O, brows(b_fn, Q), dev(L.o_q, O), brows(b_fr, O));
|
||||
RAD_ISSUE_N(c, op_ln_on, O, brows(b_x, O), RAD_W(on_w), RAD_W(on_b), brows(b_on, O));
|
||||
RAD_ISSUE_N(c, op_rms_a, O, brows(b_fr, O), brows(b_na, O));
|
||||
RAD_ISSUE_N(c, op_rms_b, O, brows(b_on, O), brows(b_nb, O));
|
||||
RAD_ISSUE_N(c, op_mul_cos, O, brows(b_na, O), brows(b_nb, O), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, op_mean_cos, O, brows(b_t1, O), out3(OM, O));
|
||||
RAD_ISSUE_N(c, op_g_an, O, brows(b_qv, Q), dev(L.o_q, O), brows(b_an, O));
|
||||
RAD_ISSUE_N(c, op_add_an, O, brows(b_an, O), brows(b_g, 1), brows(b_an, O));
|
||||
RAD_ISSUE_N(c, op_rms_an, O, brows(b_an, O), brows(b_p, O));
|
||||
RAD_ISSUE_N(c, op_rms_lex, O, brows(b_lex, O), brows(b_ln, O));
|
||||
RAD_ISSUE_N(c, op_mul_pri, O, brows(b_p, O), brows(b_ln, O), brows(b_an, O));
|
||||
RAD_ISSUE_N(c, op_mean_pri, O, brows(b_an, O), out3(0, O));
|
||||
RAD_ISSUE_N(c, op_neg1, 1, brows(b_neg1, 1));
|
||||
RAD_ISSUE_N(c, op_nd, O, brows(b_on, O), brows(b_neg1, 1), brows(b_nd, O));
|
||||
RAD_ISSUE_N(c, op_d, O, brows(b_fr, O), brows(b_nd, O), brows(b_d, O));
|
||||
RAD_ISSUE_N(c, op_relu_d, O, brows(b_d, O), brows(b_abs, O));
|
||||
RAD_ISSUE_N(c, op_nd2, O, brows(b_d, O), brows(b_neg1, 1), brows(b_nd, O));
|
||||
RAD_ISSUE_N(c, op_relu_nd, O, brows(b_nd, O), brows(b_nd, O));
|
||||
RAD_ISSUE_N(c, op_abs, O, brows(b_abs, O), brows(b_nd, O), brows(b_abs, O));
|
||||
RAD_ISSUE_N(c, op_prod, O, brows(b_fr, O), brows(b_on, O), brows(b_prod, O));
|
||||
/* [field | option | field*option | |field-option|], then the scorer. The field rows go
|
||||
* in again (a copy into the first block) so every block arrives the same way. */
|
||||
RAD_ISSUE_N(c, op_cp_fr, O, brows(b_fr, O), bcol(b_feat, 0, W, O));
|
||||
RAD_ISSUE_N(c, op_cp_on, O, brows(b_on, O), bcol(b_feat, W, W, O));
|
||||
RAD_ISSUE_N(c, op_cp_prod, O, brows(b_prod, O), bcol(b_feat, 2 * W, W, O));
|
||||
RAD_ISSUE_N(c, op_cp_abs, O, brows(b_abs, O), bcol(b_feat, 3 * W, W, O));
|
||||
RAD_ISSUE_N(c, op_rs1, O, brows(b_feat, O), RAD_W(rs1_w), RAD_W(rs1_b), RAD_NONE, brows(b_r, O));
|
||||
RAD_ISSUE_N(c, op_rs2, O, brows(b_r, O), RAD_W(rs2_w), RAD_W(rs2_b), RAD_NONE, out3(2 * OM, O));
|
||||
/* The three stretches, as f32, into the request's logits row (one row of 3 OM). */
|
||||
RAD_ISSUE_N(c, op_cast, 1, brows(b_out3, 3 * OM),
|
||||
bcol_at(b_logits, row, n_vocab, 0, 3 * OM, 1));
|
||||
}
|
||||
}
|
||||
|
||||
/* The zero logits rows a trunk leaves when it skips its lm_head for rows a decision head answers
|
||||
* (the qwen35 plugins' `op_logits_fill`): declared here, by the plugin that wants the skip, so a
|
||||
* trunk serving a plain container declares the same graph as before. */
|
||||
inline rad_op clef_logits_fill(RadBuilder* b, Names& nm, const Geom& g, rad_buf b_logits) {
|
||||
return rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_vocab),
|
||||
RAD_STR("dtype", "f32"), RAD_F64("value", 0.0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_logits });
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
+438
-104
@@ -47,6 +47,13 @@
|
||||
* hp = hidden_projection(x) the selector's query, rank 256
|
||||
* tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor)
|
||||
*
|
||||
* ============================== LILICORR ==============================
|
||||
*
|
||||
* Config::lili is NVIDIA's LiLiCorr backbone (Nemotron-3.5-Bolt's drafter): the same layers with a
|
||||
* learned sink logit a query head in the attention (attn_paged_sink, `attention_sink_bias`), and no
|
||||
* selector or draft head here. The query pass ends with the gather into `sel_h`; the plugin then
|
||||
* runs rad_block_lilicorr.h's correlator over those rows, which reads the target's own head.
|
||||
*
|
||||
* ============================== WHAT IS SHARED WITH THE TARGET ==============================
|
||||
*
|
||||
* The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and
|
||||
@@ -68,6 +75,8 @@
|
||||
*
|
||||
* q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per
|
||||
* draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor.
|
||||
* Fewer KV heads than ranks are replicated (drafter_geom's `kv_repl_ok`): each rank reads its
|
||||
* head's k/v rows at `kv_off` and keeps that head in its cache.
|
||||
*
|
||||
* fc [n_embd, n_taps*n_embd], 262 MiB in fp8 at Qwen3.8's width, read whole by the
|
||||
* context pass every step. Split by rows over the ranks and all-gathered, and
|
||||
@@ -98,6 +107,7 @@
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire (--draft-coupling) */
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -122,15 +132,51 @@ struct Dflash2 {
|
||||
int64_t group = 16;
|
||||
int64_t sel_rank = 256; /* the codebooks' width */
|
||||
int64_t sel_topk = 16; /* candidates kept per position */
|
||||
/* Propose a tree of `steps()` nodes instead of the selector's one path (`dflash_tree`,
|
||||
* rad_drafter_tree): best-first over the candidate lattice by path probability, each
|
||||
* edge's probability the softmax of its scores over the K candidates divided by
|
||||
* `tree_temp`. False: the greedy walk. */
|
||||
bool tree = false;
|
||||
double tree_temp = 1.0;
|
||||
/* A tree's draft nodes a step, 0 for `steps()`. More than the block drafts is a wider tree
|
||||
* over the same lattice (its depth is still at most `steps()`); the proposal buffers, the
|
||||
* drafter's declared depth and the verify are this wide. */
|
||||
int64_t tree_nodes = 0;
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 0;
|
||||
/* The target's embedding scale, applied to the query block as the drafter was trained
|
||||
* (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */
|
||||
double escale = 1.0;
|
||||
/* Optional DFlash2 logit transform shipped by Muse Glimmer. */
|
||||
double omul = 1.0;
|
||||
double scap = 0.0;
|
||||
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
|
||||
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
|
||||
int64_t prefetch = 0;
|
||||
|
||||
/* Also declare the short block's query pass (kShortBlock rows, or `short_rows`) for
|
||||
* --draft-short-from; an architecture that does not call rad_drafter_short_block leaves
|
||||
* it off and its graph as it was. A tree's selector at that block grows a tree of its own
|
||||
* over the shorter pass, `short_rows - 1` nodes or fewer. */
|
||||
int short_block = 0;
|
||||
/* --draft-coupling: the temperature of the draft law Q the coupled walk samples from
|
||||
* (dflash_couple_propose's `q_temp`). Any value keeps the output exact; it only moves
|
||||
* acceptance, sum min(P, Q). */
|
||||
double q_temp = 1.0;
|
||||
int64_t short_rows = 0;
|
||||
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
|
||||
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
|
||||
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
|
||||
* by had_quant_act_i8g. Every linear must agree. `fc_mapped`: probe_i8 made
|
||||
* `dflash.fc.weight`'s name map. */
|
||||
bool act_i8 = false;
|
||||
int64_t act_g8 = RAD_FP8_BLOCK;
|
||||
bool fc_mapped = false;
|
||||
/* LiLiCorr's backbone (the LILICORR section above): sinks, and the head left to the
|
||||
* plugin. sel_rank and sel_topk are then unused. */
|
||||
int lili = 0;
|
||||
int64_t steps() const { return block - 1; }
|
||||
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
|
||||
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
|
||||
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
|
||||
* `dflash_conv` reads a slice of it at the full row pitch. */
|
||||
@@ -163,7 +209,9 @@ struct Dflash2 {
|
||||
rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
|
||||
rad_buf ffn = 0; /* [qrows, n_ff] */
|
||||
/* FP8 codes and scales of the activations the linears read, written by `quant_act_fp8`
|
||||
* and read only by the `gemm_nt_q` linears. One pair per activation, not per linear: q, k
|
||||
* and read only by the `gemm_nt_q` linears (int8 codes with a scale per Config::act_g8,
|
||||
* written by `had_quant_act_i8g`, when the drafter's linears are rotated int8:
|
||||
* Config::act_i8). One pair per activation, not per linear: q, k
|
||||
* and v all read h2. h2 is still quantised twice a layer, because the convolution
|
||||
* rewrites it between the attention and feed-forward halves. */
|
||||
rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] e4m3 | [.., /128] f32 */
|
||||
@@ -185,6 +233,11 @@ struct Dflash2 {
|
||||
rad_buf dpair = 0; /* [srows, sel_topk, 2] f32 */
|
||||
rad_buf dgath = 0; /* [srows, world * sel_topk, 2] f32 */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
|
||||
/* --draft-coupling: [max_seqs, DRAW_WORDS] draws the engine stages, and [steps, max_seqs,
|
||||
* STATE_WORDS] states it reads back (abi/rad_spechub.h). Both or neither. */
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
/* [max_seqs, steps] i32 a tree's parents (Config::tree, rad_drafter_tree); 0 otherwise */
|
||||
rad_buf parents = 0;
|
||||
};
|
||||
|
||||
/* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
|
||||
@@ -220,6 +273,9 @@ struct Dflash2 {
|
||||
* 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and
|
||||
* the 2-bit grid otherwise. Set by declare from the copy's encoding. */
|
||||
bool head_i8 = false;
|
||||
/* Muse Glimmer's 202048-token vocab is not divisible by the int8/w2a8 head kernels' 128-row
|
||||
* tile; its copied draft head stays BF16 and uses gemm_nt. */
|
||||
bool head_bf16 = false;
|
||||
|
||||
/* per-layer weights */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
@@ -260,7 +316,15 @@ struct Dflash2 {
|
||||
rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
|
||||
rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */
|
||||
rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {};
|
||||
/* The short block's (block_lo rows a sequence): the convolutions mask at the block's first row
|
||||
* and the selector strides by it, so each has an op of its own; every other op is per row. */
|
||||
rad_op op_aconv_lo[MAX_LAYERS] = {}, op_fconv_lo[MAX_LAYERS] = {}, op_sel_lo = 0;
|
||||
int64_t block_lo = 0;
|
||||
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
/* LiLiCorr: the attention with each layer's sinks, a weight, so one op a layer. */
|
||||
rad_weight w_sink[MAX_LAYERS] = {};
|
||||
rad_op op_attn_sink[MAX_LAYERS] = {};
|
||||
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
|
||||
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
|
||||
* that norm where it resolves: op_afn[i] after layer i's attention (its feed-forward norm),
|
||||
@@ -276,7 +340,7 @@ struct Dflash2 {
|
||||
rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {};
|
||||
|
||||
/* head and selector */
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dcap = 0, op_dtopk = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_drerank = 0; /* the candidates rescored against the target's head */
|
||||
/* The target's lm_head, set by the plugin before declare when logit_rerank can read it (fp8 or
|
||||
@@ -287,6 +351,24 @@ struct Dflash2 {
|
||||
static constexpr int64_t kRerankR = 32;
|
||||
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
|
||||
rad_op op_hp = 0, op_sel = 0;
|
||||
/* --draft-coupling: the sampled walk after the greedy one (dflash_couple_propose), for the
|
||||
* drafter's block and its short one. 0 when the coupling is off. */
|
||||
rad_op op_couple = 0, op_couple_lo = 0;
|
||||
/* The short block: kShortBlock rows (depth 3, the window that pays at many sequences), when
|
||||
* the drafter's own block is longer (rad_drafter_short_block). */
|
||||
static constexpr int64_t kShortBlock = 4;
|
||||
|
||||
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
|
||||
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
|
||||
* declared, since it decides their dtype and scale grid. */
|
||||
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
|
||||
const char* fwn = nm.f("dflash.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
RadEncoding fe{};
|
||||
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
|
||||
@@ -314,7 +396,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
(long long)g.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg.block < 2 || cfg.n_taps <= 0 || cfg.sel_rank <= 0 || cfg.sel_topk <= 0)
|
||||
if (cfg.block < 2 || cfg.n_taps <= 0 || (!cfg.lili && (cfg.sel_rank <= 0 || cfg.sel_topk <= 0)))
|
||||
return RAD_E_INVAL;
|
||||
|
||||
const int64_t NG = cfg.ng(g.n_embd);
|
||||
@@ -327,11 +409,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
|
||||
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
|
||||
w_fc.w8h_ok = cfg.act_i8;
|
||||
for (int i = 0; i < MAX_LAYERS; ++i)
|
||||
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
|
||||
w_dn[i].w8h_ok = cfg.act_i8;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
{
|
||||
const int64_t K = cfg.n_taps * g.n_embd;
|
||||
const char* fwn = nm.f("dflash.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
if (!cfg.fc_mapped) RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
/* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole
|
||||
* 16-byte words (the gather's unit). */
|
||||
RadEncoding fe{};
|
||||
@@ -362,23 +451,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
}
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
|
||||
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
|
||||
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
|
||||
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
|
||||
|
||||
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* The 2-bit draft head, declared as the MTP head's is (rad_block_mtp_fp8.h):
|
||||
* `dflash.draft_head.weight` is the target's lm_head under its own name, quantised by the
|
||||
@@ -388,35 +464,59 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* When sharded, each rank's `row_topk` reports global ids, an all_gather moves R pairs a row,
|
||||
* and `row_topk_merge` reduces them to exactly the unsharded global top-R, ties included
|
||||
* (docs/OPS.md). This runs before the selector, so every rank holds the same candidates for
|
||||
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16). */
|
||||
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16).
|
||||
*
|
||||
* LiLiCorr has neither the selector nor this head (its correlator reads the target's). */
|
||||
enum { DF_W2_GROUP = 128 };
|
||||
const bool dh_shard = head_sharded(g);
|
||||
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const char* dhn = nm.f("dflash.draft_head.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
|
||||
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which gemm_nt_q
|
||||
* reads at w8a8 against the same quant_act_i8 activation (without its asum). */
|
||||
{
|
||||
RadEncoding e{};
|
||||
const RadEncPlane* sc = nullptr;
|
||||
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 &&
|
||||
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 &&
|
||||
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
|
||||
}
|
||||
if (head_i8) {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
|
||||
if (!cfg.lili) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
|
||||
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
|
||||
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
|
||||
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
|
||||
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
const char* dhn = nm.f("dflash.draft_head.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
|
||||
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which
|
||||
* gemm_nt_q reads at w8a8 against the same quant_act_i8 activation (without its asum). */
|
||||
RadEncoding dhe{};
|
||||
const bool head_known = weight_enc(b, dhn, &dhe);
|
||||
{
|
||||
const RadEncPlane* sc = nullptr;
|
||||
head_i8 = head_known && rad_enc_is(&dhe, "affine") && dhe.n_planes == 2 &&
|
||||
!dhe.transform[0] && dhe.plane[0].dtype == RAD_I8 && dhe.plane[0].block[1] == 1 &&
|
||||
(sc = rad_enc_plane(&dhe, "scale")) && sc->dtype == RAD_F16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
|
||||
}
|
||||
if (head_i8) {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
|
||||
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN,
|
||||
dh_split, grp_model());
|
||||
} else if (head_known && rad_enc_is(&dhe, "plain") && dhe.n_planes == 1 &&
|
||||
dhe.plane[0].dtype == RAD_BF16) {
|
||||
head_bf16 = true;
|
||||
w_dh = decl_w(b, dhn, RAD_BF16, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
|
||||
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN, dh_split,
|
||||
grp_model());
|
||||
} else {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
} else {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split,
|
||||
grp_model());
|
||||
}
|
||||
if (!w_dh || (!head_bf16 && !w_dhs)) return RAD_E_INVAL;
|
||||
}
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
@@ -453,6 +553,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
|
||||
/* Fewer KV heads than ranks (drafter_geom's `kv_repl_ok`): k and v are this rank's
|
||||
* replicated head, rows [kv_off, kv_off + kv_dim) of the unsharded projection, where the
|
||||
* even shard would hand a rank part of a head. q stays an even share of the heads. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
RAD_ARCH_TRY(w_k[i].span(b, g.kv_off, g.kv_off + kvd));
|
||||
RAD_ARCH_TRY(w_v[i].span(b, g.kv_off, g.kv_off + kvd));
|
||||
}
|
||||
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
|
||||
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
@@ -481,6 +588,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
w_fcb[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_base", i), RAD_BF16,
|
||||
{2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(first_layer + i));
|
||||
/* LiLiCorr's sink logit a query head, split with the heads. */
|
||||
if (cfg.lili) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_sinks", i),
|
||||
nm.ckpt("%s.layers.%d.self_attn.attention_sink_bias", ck, i)));
|
||||
w_sink[i] = decl_w(b, nm.f("dflash.blk.%d.attn_sinks", i), RAD_F32, {g.n_head},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i));
|
||||
if (!w_sink[i]) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -490,15 +605,35 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
*
|
||||
* Declared before both kv_stores, which read the resolved `block_size` back with
|
||||
* rad_kv_block_size(); before this declaration it returns zero. */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
if (!cfg.lili) {
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
} else {
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_attn_sink[i] = rw(b, RAD_OP(b, "attn_paged_sink",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs),
|
||||
RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_WEIGHTS(w_sink[i])),
|
||||
{w.q}, {w.attn});
|
||||
if (!op_attn_sink[i]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
/* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
|
||||
@@ -508,20 +643,43 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* Nothing is row-sliced: the fp8a8 pair covers every M, and libr4d's bf16 GEMM row (used by
|
||||
* the conv coefficient projections and the selector's hidden projection, K = n_embd) is
|
||||
* C_LE("M", 65536). */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
/* A rotated int8 drafter (cfg.act_i8): the same five quantisers as had_quant_act_i8g at its
|
||||
* scale group, and no fp8a8 fold. Its linears read one activation pair, so they are all
|
||||
* i8a8h forms at one group or none is. */
|
||||
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
{
|
||||
auto fits = [&](const DenseFP8& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l)
|
||||
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
|
||||
fits(w_gu[l]) && fits(w_dn[l]);
|
||||
if (!same) {
|
||||
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
|
||||
"group or all block fp8 / MXFP4; they read one activation pair, so the "
|
||||
"recipe must give them one format\n");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
op_qsrc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
if (fc_rows) {
|
||||
/* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of
|
||||
* them gathered into `c`. The GEMM takes its K split from the whole width. The gather
|
||||
* rides the trunk's all-reduce instance (the same numel bound, so the same instance). */
|
||||
* rides the trunk's all-reduce instance (the same numel bound, so the same instance).
|
||||
* The message is a range, as the all-reduce's: a fixed numel follows max_tok, and the
|
||||
* arena's sizing declare (RadBuildCtx::shape_probe) refuses a fixed parameter that
|
||||
* changes with the step size. */
|
||||
op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart},
|
||||
g.n_embd);
|
||||
op_cgath = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", crows * g.n_embd),
|
||||
RAD_RANGE("numel", g.n_embd, crows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.cpart}, {w.c});
|
||||
@@ -537,9 +695,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* One quantise for all layers: every layer's k and v read the same `c`. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
@@ -603,19 +761,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{w.x}, {w.x});
|
||||
/* The query pass's quantisers, issued per layer: h2 twice (the convolution rewrites it between
|
||||
* the halves), attn and ffn once each. */
|
||||
op_qh2 = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qh2 = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h2}, {w.h2q, w.h2s});
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qat = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn}, {w.atq, w.ats});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qff = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn}, {w.ffq, w.ffs});
|
||||
|
||||
@@ -662,7 +820,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
|
||||
/* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
|
||||
* fp8a8 tile, so an MXFP4 or M2XFP4 gate_up takes the pair. */
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x)
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h2q, w.h2s}, {w.ffq, w.ffs}, &gated_rows);
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
|
||||
@@ -695,7 +853,29 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* layers. Planned from those alone, its range would end before the coefficients' begins and
|
||||
* the plan could lay one over the other. Read by the last convolution as well, it is live
|
||||
* wherever the coefficients are. */
|
||||
{
|
||||
const int64_t rows = cfg.short_rows > 0 ? cfg.short_rows : kShortBlock;
|
||||
block_lo = cfg.short_block && rows >= 2 && cfg.block > rows ? rows : 0;
|
||||
}
|
||||
for (int64_t l = 0; block_lo && l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_aconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
|
||||
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
|
||||
RAD_INT("NG", NG), RAD_INT("block_size", block_lo),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_acb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
op_fconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
|
||||
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
|
||||
RAD_INT("NG", NG), RAD_INT("block_size", block_lo),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fcb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
}
|
||||
if (rad_op_reads(b, op_fconv[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
|
||||
if (block_lo && rad_op_reads(b, op_fconv_lo[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
|
||||
op_qrope = rope(qrows, g.n_head, w.q);
|
||||
op_krope = rope(qrows, g.n_head_kv, w.k);
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
@@ -713,12 +893,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* Only for a shape a library serves: an op declared for one that resolves to no device
|
||||
* kernel is a hole that refuses startup (Program::device_holes), whether or not it is
|
||||
* issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in
|
||||
* steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim
|
||||
* 128) keeps the chain. */
|
||||
* steps of 256, bf16 rows, either cache). Qwen3.8's DFlash2 drafter (head_dim 128) keeps
|
||||
* the chain. */
|
||||
const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 &&
|
||||
!std::strcmp(g.dtype, "bf16") &&
|
||||
(!std::strcmp(g.kv_dtype, "fp8_e4m3") ||
|
||||
!std::strcmp(g.kv_dtype, "bf16"));
|
||||
!std::strcmp(g.dtype, "bf16");
|
||||
if (fold_shape && g.yarn.factor == 0.0f &&
|
||||
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
|
||||
const int64_t bsz = rad_kv_block_size(b, kv);
|
||||
@@ -779,12 +957,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h2}, {w.x});
|
||||
op_final = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
op_final = cfg.omul != 1.0
|
||||
? rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_F64("mult", cfg.omul), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h})
|
||||
: rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
/* Each residual add and the norm after it as one launch where a library serves add_rmsnorm
|
||||
* (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only
|
||||
* where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run
|
||||
@@ -808,6 +993,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
op_afinal = all ? an(w_norm) : 0;
|
||||
if (!op_afinal)
|
||||
for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0;
|
||||
/* add_rmsnorm has no `mult`; keep Muse's output_multiplier on the final norm. */
|
||||
if (cfg.omul != 1.0) op_afinal = 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the head and the selector
|
||||
@@ -823,12 +1010,21 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.sel_h});
|
||||
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.sel_h}, {w.dq, w.ds, w.dsum});
|
||||
op_dlogits = head_i8
|
||||
/* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */
|
||||
if (cfg.lili) return RAD_OK;
|
||||
if (!head_bf16)
|
||||
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.sel_h}, {w.dq, w.ds, w.dsum});
|
||||
op_dlogits = head_bf16
|
||||
? rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_dh)),
|
||||
{w.sel_h}, {w.dlog})
|
||||
: head_i8
|
||||
? rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
|
||||
@@ -841,6 +1037,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_STR("dtype", "w2a8")),
|
||||
RAD_WEIGHTS(w_dh, w_dhs)),
|
||||
{w.dq, w.ds, w.dsum}, {w.dlog});
|
||||
if (cfg.scap > 0.0) {
|
||||
op_dcap = rw(b, RAD_OP(b, "logit_softcap",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", head_rows(g)),
|
||||
RAD_F64("cap", cfg.scap), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.dlog});
|
||||
if (!op_dcap) return RAD_E_INVAL;
|
||||
}
|
||||
/* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
|
||||
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
|
||||
* with value 0 is a different declaration from an absent one. */
|
||||
@@ -901,14 +1105,101 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_selp)),
|
||||
{w.sel_h}, {w.hp});
|
||||
/* `anchor_stride` is `block`: the operand is the step's token_ids, `block` per sequence with
|
||||
* the anchor first. */
|
||||
op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
* the anchor first.
|
||||
*
|
||||
* A tree (Config::tree): `dflash_tree` grows `steps` nodes best-first over the same lattice
|
||||
* and the same edge scores, writing each node's parent beside its token. Where no library
|
||||
* serves it the block falls back to the chain and says so; the caller reads `cfg.tree` after
|
||||
* declare to decide whether to tell the core (rad_drafter_tree). --draft-coupling samples one
|
||||
* path per sequence, so a coupled drafter proposes the chain. */
|
||||
if (cfg.tree && (w.couple_draws || w.couple_state)) {
|
||||
rad_note(b, "DFlash2: --draft-coupling samples a chain; the drafter proposes no tree");
|
||||
cfg.tree = false;
|
||||
}
|
||||
if (cfg.tree) {
|
||||
op_sel = RAD_OP(b, "dflash_tree",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block),
|
||||
RAD_INT("nodes", cfg.nodes()), RAD_F64("temp", cfg.tree_temp),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ));
|
||||
if (op_sel && rad_op_resolved(b, op_sel)) {
|
||||
rw(b, op_sel, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
|
||||
} else {
|
||||
rad_note(b, "DFlash2: no library serves dflash_tree here; the drafter proposes its "
|
||||
"selector's chain");
|
||||
cfg.tree = false;
|
||||
op_sel = 0;
|
||||
}
|
||||
}
|
||||
if (!cfg.tree) op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp}, {w.tokens});
|
||||
if (block_lo && cfg.tree) {
|
||||
/* A tree over the short block's own lattice (the pass attends across its block, so it is
|
||||
* not the full pass's prefix): as many nodes as the block drafts, or the tree's own count
|
||||
* where that is fewer. */
|
||||
sel_lo_nodes = std::min<int64_t>(cfg.nodes(), block_lo - 1);
|
||||
op_sel_lo = RAD_OP(b, "dflash_tree",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", block_lo),
|
||||
RAD_INT("nodes", sel_lo_nodes), RAD_F64("temp", cfg.tree_temp),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ));
|
||||
if (op_sel_lo && rad_op_resolved(b, op_sel_lo)) {
|
||||
rw(b, op_sel_lo, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
|
||||
} else {
|
||||
rad_note(b, "DFlash2: no library serves dflash_tree at the short block; the tree keeps "
|
||||
"its own block under load");
|
||||
op_sel_lo = 0;
|
||||
block_lo = 0;
|
||||
sel_lo_nodes = 0;
|
||||
}
|
||||
} else if (block_lo)
|
||||
op_sel_lo = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", block_lo), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp}, {w.tokens});
|
||||
|
||||
/* --draft-coupling: the walk again, sampled (abi/rad_spechub.h, rad_dflash_couple_step), over
|
||||
* the same lattice right after the greedy walk. A greedy request's row keeps the selector's
|
||||
* tokens; a sampled one gets x ~ Q at every position and the Q it was drawn from, which the
|
||||
* engine reads back and binds to the verify. The tokens stay global ids, so the engine's take
|
||||
* (ADV_BTAKE) is unchanged. */
|
||||
if (w.couple_draws || w.couple_state) {
|
||||
if (!w.couple_draws || !w.couple_state || cfg.steps() > RAD_MTP_COUPLE_MAX_ROUNDS ||
|
||||
cfg.sel_topk > RAD_DFLASH_COUPLE_MAX_K)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
auto couple = [&](int64_t steps, int64_t stride) {
|
||||
return rw(b, RAD_OP(b, "dflash_couple_propose",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", steps),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", stride),
|
||||
RAD_INT("max_rounds", cfg.steps()),
|
||||
RAD_F64("q_temp", cfg.q_temp)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp, w.couple_draws, w.tokens},
|
||||
{w.tokens, w.couple_state});
|
||||
};
|
||||
op_couple = couple(cfg.steps(), cfg.block);
|
||||
if (!op_couple) return RAD_E_INVAL;
|
||||
if (block_lo) {
|
||||
op_couple_lo = couple(block_lo - 1, block_lo);
|
||||
if (!op_couple_lo) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* The reads beside the all-reduces, after every weight they read is declared. */
|
||||
if (op_ar && cfg.prefetch > 0)
|
||||
@@ -942,7 +1233,8 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
|
||||
if (fc_rows) {
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.cpart, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cgath, T, bcol(w.cpart, fc_off, fc_share, T), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_cgath, T * g.n_embd, bcol(w.cpart, fc_off, fc_share, T),
|
||||
brows(w.c, T));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
@@ -983,6 +1275,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t NG = cfg.ng(g.n_embd);
|
||||
const int64_t half = cfg.taps * NG; /* prepare's coefficients, then finish's */
|
||||
|
||||
/* The block this pass was staged at: every drafting sequence carries the same number of rows,
|
||||
* the drafter's own block or its short one (rad_drafter_short_block). */
|
||||
const int64_t blk = batch->n_seq > 0 && T % batch->n_seq == 0 ? T / batch->n_seq : 0;
|
||||
const bool lo = block_lo > 0 && blk == block_lo;
|
||||
if (!lo && blk != cfg.block) {
|
||||
rad_step_fail(c, "dflash2: a query pass staged at a block this drafter has no ops for");
|
||||
return;
|
||||
}
|
||||
const rad_op* aconv = lo ? op_aconv_lo : op_aconv;
|
||||
const rad_op* fconv = lo ? op_fconv_lo : op_fconv;
|
||||
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
|
||||
if (op_embed_ar)
|
||||
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
|
||||
@@ -1005,7 +1308,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
/* ---- attention, wrapped in the two halves of one convolution */
|
||||
norm(op_anorm[i], op_aan[i], w_anorm[i]);
|
||||
RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T));
|
||||
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
RAD_ISSUE_N(c, aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
@@ -1029,13 +1332,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, first_layer + i),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
if (cfg.lili)
|
||||
RAD_ISSUE_N(c, op_attn_sink[i], batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, first_layer + i),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
RAD_W(w_sink[i]), brows(w.attn, T));
|
||||
else
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, first_layer + i),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
|
||||
@@ -1044,14 +1356,14 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* replicated norm, so either order gives the same result; reducing first keeps x's
|
||||
* update agreed across ranks. */
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
RAD_ISSUE_N(c, aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
add_pending = true;
|
||||
|
||||
/* ---- the feed-forward, wrapped in the other convolution */
|
||||
norm(op_fnorm[i], op_afn[i], w_fnorm[i]);
|
||||
RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T));
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
if (op_gug[i] && T <= gated_rows) {
|
||||
@@ -1068,7 +1380,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
|
||||
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pff[i][j], pff_w[i][j], T);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
add_pending = true;
|
||||
}
|
||||
@@ -1079,15 +1391,21 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
|
||||
if (cfg.lili) return; /* the plugin's correlator takes sel_h from here */
|
||||
|
||||
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
|
||||
* whole. */
|
||||
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
|
||||
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
|
||||
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric and
|
||||
* takes no asum. */
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
|
||||
if (head_bf16) {
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.sel_h, S), RAD_W(w_dh), brows(w.dlog, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
|
||||
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
|
||||
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric
|
||||
* and takes no asum. */
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
|
||||
}
|
||||
if (op_dcap) RAD_ISSUE_N(c, op_dcap, S, brows(w.dlog, S), brows(w.dlog, S));
|
||||
/* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
|
||||
* the merge overwrites `cand`/`unary`. */
|
||||
if (op_dmerge) {
|
||||
@@ -1107,10 +1425,26 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
/* A tree's outputs as views exactly its nodes wide, at the buffers' row pitch: at the short
|
||||
* block it grows fewer nodes than a row holds, and the proposals are read at the full pitch. */
|
||||
const int64_t nn = lo ? sel_lo_nodes : cfg.nodes();
|
||||
if (cfg.tree)
|
||||
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
bcol(w.tokens, 0, nn, batch->n_seq), bcol(w.parents, 0, nn, batch->n_seq));
|
||||
else
|
||||
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
if (op_couple)
|
||||
RAD_ISSUE_N(c, lo ? op_couple_lo : op_couple, batch->n_seq,
|
||||
bcol(w.cand, 0, cfg.sel_topk, S), bcol(w.unary, 0, cfg.sel_topk, S),
|
||||
brows(w.hp, S), praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred),
|
||||
RAD_W(w_succ), praw(batch->seq_ids, RAD_I32, batch->n_seq),
|
||||
brows(w.couple_draws, batch->n_seq), brows(w.tokens, batch->n_seq),
|
||||
RAD_B(w.couple_state));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
|
||||
@@ -93,12 +93,15 @@
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* E4M3 + a bf16 [N/128][K/128] plane fc, q/k/v/o, gate_up, down -- every linear
|
||||
* what the recipe made them fc, q/k/v/o, gate_up, down -- every linear
|
||||
* bf16, no plane every norm, and both Markov codebooks
|
||||
*
|
||||
* The checkpoint is dense bf16; the linears are rad_fp8.h's DenseFP8 over weights the recipe
|
||||
* quantises, because the drafter is read whole every decode step (324M parameters: 648 MB at
|
||||
* bf16, 324 MB at fp8). This can only change acceptance.
|
||||
* bf16, 324 MB at eight bits). DenseFP8 reads block fp8 or MXFP4 against E4M3 activations, or a
|
||||
* rotated int8 form (IQ8R and the narrower grids under the same rotation) against int8 ones
|
||||
* (Config::act_i8); one format for all of them, since they share the activation pairs. This can
|
||||
* only change acceptance.
|
||||
*
|
||||
* The codebooks are bf16 and replicated: they are gathered by global token id from a merged
|
||||
* candidate set. 66.8 MiB each; only K rows are read per position, so the cost is residency.
|
||||
@@ -135,6 +138,14 @@ struct Dspark {
|
||||
int64_t top_k = 0; /* candidates the Markov walk re-ranks */
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 0;
|
||||
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
|
||||
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
|
||||
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
|
||||
* by had_quant_act_i8g and the rotating norm. Every linear must agree. `fc_mapped`:
|
||||
* probe_i8 made `dspark.fc.weight`'s name map. */
|
||||
bool act_i8 = false;
|
||||
int64_t act_g8 = RAD_FP8_BLOCK;
|
||||
bool fc_mapped = false;
|
||||
/* Every row predicts, so `block`, not `block - 1` (see ROW ALIGNMENT). */
|
||||
int64_t steps() const { return block; }
|
||||
};
|
||||
@@ -149,7 +160,10 @@ struct Dspark {
|
||||
* rows_pitch). */
|
||||
rad_buf ck = 0; /* [max_tok, kv_dim] one layer's K, reused across layers */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] one layer's V, reused across layers */
|
||||
rad_buf srcq = 0, srcs = 0; /* fp8 codes and scales: e4m3 | f32 [.., /128] */
|
||||
/* The codes and scales the linears read: e4m3 | f32 [.., /128], or with Config::act_i8
|
||||
* i8 | f32 [.., /act_g8]. The same holds for the three ActFP8 pairs below, whose `q` and
|
||||
* `s` are then the int8 pair. */
|
||||
rad_buf srcq = 0, srcs = 0;
|
||||
rad_buf cq = 0, cs = 0;
|
||||
|
||||
/* ---- the query pass, `block` rows per sequence */
|
||||
@@ -235,6 +249,18 @@ struct Dspark {
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_sel = 0;
|
||||
|
||||
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
|
||||
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
|
||||
* declared, since it decides their dtype and scale grid. */
|
||||
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
|
||||
const char* fwn = nm.f("dspark.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
RadEncoding fe{};
|
||||
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
|
||||
const char* ck_lm, const char* ck_lm_alt, const Wire& wire);
|
||||
@@ -274,10 +300,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
|
||||
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
|
||||
w_fc.w8h_ok = cfg.act_i8;
|
||||
for (int i = 0; i < MAX_LAYERS; ++i)
|
||||
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
|
||||
w_dn[i].w8h_ok = cfg.act_i8;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), g.n_embd, cfg.n_taps * g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
|
||||
{ nm.ckpt("%s.fc.weight", ck) }));
|
||||
{ nm.ckpt("%s.fc.weight", ck) }, {}, cfg.fc_mapped));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
|
||||
nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
@@ -379,19 +412,34 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass
|
||||
*
|
||||
* Every linear is `fp8a8`, fed by a `quant_act_fp8`. There is no `fp8a16` band: that kernel is
|
||||
* M <= 1, and neither pass runs at one row. */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
* Every linear is a DenseFP8 GEMM over the pair its quantiser writes: `quant_act_fp8` codes
|
||||
* for block fp8 or MXFP4, had_quant_act_i8g's at the weights' scale group for a rotated int8
|
||||
* drafter (cfg.act_i8). The linears read one activation pair, so they are all i8a8h forms at
|
||||
* one group or none is. There is no `fp8a16` band: that kernel is M <= 1, and neither pass
|
||||
* runs at one row. */
|
||||
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
{
|
||||
auto fits = [&](const DenseFP8& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l)
|
||||
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
|
||||
fits(w_gu[l]) && fits(w_dn[l]);
|
||||
if (!same) {
|
||||
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
|
||||
"group or all block fp8 / MXFP4; they read one activation pair, so the "
|
||||
"recipe must give them one format\n");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
op_qsrc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_fc.w, w_fc.s)),
|
||||
{w.srcq, w.srcs}, {w.c});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
|
||||
* written. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -401,27 +449,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* One quantise for all layers: every layer's k and v read the same `c`. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
|
||||
* and residency class. */
|
||||
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.cq, w.cs}, {w.cv});
|
||||
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
@@ -468,7 +506,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
{w.x}, {w.x});
|
||||
|
||||
/* Norm, residual add and quantise are one op, `rmsnorm_quant_fp8` (what rad_fp8.h's
|
||||
* NormQuantFP8 wraps). Layer 0 has no delta to fold, each later norm folds the previous
|
||||
* NormQuantFP8 wraps), or its rotating int8 twin `rmsnorm_had_quant_i8g` for a rotated int8
|
||||
* drafter, which takes the same operands. Layer 0 has no delta to fold, each later norm folds the previous
|
||||
* block's delta, and op_outnorm folds the last into the final norm, so there is no `add` op.
|
||||
* The final norm's fp8 output is unused (the head runs its own i8 quantiser), a few KiB of
|
||||
* waste that saves a launch: libr4d has no plain `rmsnorm_add` row.
|
||||
@@ -478,9 +517,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* stream as `x` and no residual. `residual` is INOUT, so it is in both the read and write sets;
|
||||
* otherwise the planner could reorder a reader in front of it. */
|
||||
auto decl_norm = [&](rad_weight gain, bool fold) -> rad_op {
|
||||
rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
rad_op h = RAD_OP(b, cfg.act_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", qgr),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(gain));
|
||||
if (!h) return 0;
|
||||
@@ -490,9 +529,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
rad_op_writes(b, h, wr, fold ? 4 : 3);
|
||||
return h;
|
||||
};
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qat = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.x}, {w.attn.q, w.attn.s});
|
||||
if (!op_qat) return RAD_E_INVAL;
|
||||
@@ -508,24 +547,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = decl_norm(w_anorm[i], i != 0);
|
||||
if (!op_anorm[i]) return RAD_E_INVAL;
|
||||
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
|
||||
{w.h.q, w.h.s}, {w.q});
|
||||
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.h.q, w.h.s}, {w.k});
|
||||
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.h.q, w.h.s}, {w.v});
|
||||
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h.q, w.h.s}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
@@ -538,28 +562,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
|
||||
{w.attn.q, w.attn.s}, {w.h.x});
|
||||
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.attn.q, w.attn.s}, {w.h.x});
|
||||
op_fnorm[i] = decl_norm(w_fnorm[i], true);
|
||||
if (!op_fnorm[i]) return RAD_E_INVAL;
|
||||
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h.q, w.h.s}, {w.gate_up});
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
|
||||
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
|
||||
{w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h.q, w.h.s}, {w.gate_up});
|
||||
/* The fold is an fp8a8 tile, so any other gate_up takes the pair. */
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
}
|
||||
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
@@ -588,9 +599,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ffn.x});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qff = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn.x}, {w.ffn.q, w.ffn.s});
|
||||
/* One collective, issued after both the out and the down projection (same shape, same buffer).
|
||||
@@ -687,16 +698,16 @@ inline void Dspark::context(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, RAD_NONE);
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
|
||||
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
@@ -735,11 +746,11 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* quantises; at layer 0 it norms the embedding. */
|
||||
issue_norm(op_anorm[i], i != 0, w_anorm[i], T);
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
|
||||
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
|
||||
@@ -757,7 +768,7 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
brows(w.attn.x, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn.x, T), brows(w.attn.q, T), brows(w.attn.s, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.attn.q, T), brows(w.attn.s, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, w_o[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
|
||||
/* ---- the feed-forward, behind the same fused norm-add-quantise */
|
||||
@@ -769,12 +780,12 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
RAD_NONE);
|
||||
w_gu[i].bref());
|
||||
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn.x, T));
|
||||
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn.x, T), brows(w.ffn.q, T), brows(w.ffn.s, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffn.q, T), brows(w.ffn.s, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, w_dn[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,958 @@
|
||||
/* rad_block_dspark_bf16.h -- the DSpark drafter over bf16 weights, at the widths a Spark layer
|
||||
* uses: a few plain attention layers that denoise a whole block of masked positions in one pass,
|
||||
* conditioned on the trunk's residual stream at a handful of layers, with a rank-N Markov head
|
||||
* over the target's own output table.
|
||||
*
|
||||
* ============================== WHY A SECOND DSPARK BLOCK ==============================
|
||||
*
|
||||
* rad_block_dspark.h is the same drafter shape for a block-fp8 release: its linears are DenseFP8
|
||||
* behind `quant_act_fp8`, its feed-forward is `silu_mul`, its norms carry q/k gains, and its draft
|
||||
* head is a 2-bit copy of the target's. The published Spark drafts (`dflash` GGUFs, and the HF
|
||||
* Spark drafter releases behind them) ship the other way: bf16 linears, no q/k norms, one sigmoid
|
||||
* gate a head on the attention output, exact-erf GELU, one RMS gain per tap, and a sliding window.
|
||||
* Those are different ops, not different parameters, so this block declares its own graph and
|
||||
* uses an explicit anchor-window attention op and a full-vocabulary Markov selector so neither
|
||||
* semantic distinction is silently folded into the generic per-row window or candidate-lattice ops.
|
||||
*
|
||||
* Nothing here is quantised. The drafter is 624M parameters read whole a draft pass, so bf16 costs
|
||||
* 1.2 GiB of residency and one extra weight pass a step; quantising it is a separate measurement
|
||||
* (it can only move acceptance, since every draft is verified by the target).
|
||||
*
|
||||
* ============================== THE FORWARD PASS ==============================
|
||||
*
|
||||
* The reference is llama.cpp's `llama_model_dflash::graph<false>` (XHToken/llama.cpp
|
||||
* 22c0ae1871b, the branch the Spark draft cards name), which mirrors the HF export:
|
||||
*
|
||||
* tap(l) = rmsnorm(residual after trunk layer l) * fc_norm[l] one gain row per tap
|
||||
* ctx = rmsnorm(fc(concat_l tap(l))) hidden_norm
|
||||
* per draft layer (x5):
|
||||
* h_n = input_layernorm(h)
|
||||
* q,k,v = q_proj/k_proj/v_proj(h_n); k_ctx, v_ctx = k_proj/v_proj(ctx)
|
||||
* rope(q, k); attention over [the layer's context K/V, this block] non-causally,
|
||||
* inside a `window` positions
|
||||
* h += o_proj(sigmoid(g_proj(h)) * attn) one gate a head, no q/k norms
|
||||
* h += mlp(post_attention_layernorm(h)) gelu(gate) * up, then down
|
||||
* logits = target.lm_head(output_norm(h)) + markov_w2 @ markov_w1[prev]
|
||||
*
|
||||
* The two projections of `ctx` are the drafter's own k_proj and v_proj, one pair per layer, and
|
||||
* they run over every committed token; the drafter's layers never see the context rows. That is
|
||||
* the context pass below, and the block above is the query pass -- the same split
|
||||
* rad_block_dspark.h makes, and the same `RAD_DRAFT_BLOCK` drive.
|
||||
*
|
||||
* ============================== THE TAPS ARE NORMED, NOT JUST READ ==================
|
||||
*
|
||||
* `fc_norm` is [n_taps, n_embd]: the residual entering each tap layer is normed with its own gain
|
||||
* before the concatenation, so `fc` sees n_taps unit-scaled streams instead of one sum whose
|
||||
* magnitudes the trunk happens to have. One `rmsnorm` per tap over that tap's column slice of the
|
||||
* tap buffer, into the same slice layout of a normed copy; `fc` then reads one contiguous
|
||||
* [n_taps * n_embd] row.
|
||||
*
|
||||
* ============================== THE SHARED ANCHOR WINDOW ==========================
|
||||
*
|
||||
* The pinned llama.cpp oracle increments the configured history from 512 to 513 and repeats the
|
||||
* anchor row's mask for every row in the denoising block. `attn_paged_anchor_window` implements
|
||||
* that exact predicate: every row sees keys through the end of the staged context whose absolute
|
||||
* position is less than 513 behind the anchor. The query row does not move the lower cutoff. The
|
||||
* same 513-token width is passed to the KV group and scheduler, so rollback, cache recycling and
|
||||
* block staging all retain the exact history the drafter reads.
|
||||
*
|
||||
* ============================== ROW ALIGNMENT ==============================
|
||||
*
|
||||
* Every row predicts, the anchor included (`dflash.sample_from_anchor`, which the GGUF import
|
||||
* refuses when false): row j of [anchor, MASK x (block-1)] proposes the token at the anchor's
|
||||
* position plus j + 1, so `steps()` is `block` and the head runs over all the block's rows. The
|
||||
* core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
|
||||
* rows, which covers this and Dflash2's shift-by-one convention (abi/rad_builder.h).
|
||||
*
|
||||
* ============================== THE MARKOV HEAD ==============================
|
||||
*
|
||||
* The draft logits get a learned bigram bias
|
||||
*
|
||||
* score[l, token] = logits[l, token] + markov_w2[token] . markov_w1[prev(l)]
|
||||
* prev(0) = the anchor; prev(l) = the greedy token chosen at l - 1
|
||||
*
|
||||
* `dflash_markov_greedy` scans the full vocabulary at every position and greedily chooses the
|
||||
* largest biased score, following the structure of the pinned reference's serial Markov walk.
|
||||
* Base logits are F32; reduction order and tie behavior can still differ from the reference. It
|
||||
* does not prune to the base head's top K, use a joint-path heap, or apply confidence to logits.
|
||||
*
|
||||
* The confidence head (`conf_proj`, one sigmoid a position predicting acceptance) is imported and
|
||||
* ignored: it exists to let a serving loop cut the block short, this engine's depth is fixed at
|
||||
* declare, and it changes nothing the drafter proposes.
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* bf16 for every weight and activation except the residual stream, which is f32 exactly as the
|
||||
* Spark trunk keeps it (rad_block_dspark.h's fp8 graphs fold the residual into the norm; here the
|
||||
* norms read the f32 stream and write bf16, and `add` keeps the sum in f32). The reference runs
|
||||
* bf16 weights against an f32 residual, so rounding the drafter's stream to bf16 would be a third
|
||||
* opinion on every layer's output for no saved bytes worth having at `block` rows.
|
||||
*
|
||||
* ============================== NOT DONE ==============================
|
||||
*
|
||||
* The head and full-vocabulary Markov scan are read replicated, so a vocab-sharded deployment
|
||||
* cannot draft with them. The plugin refuses `world > 1` rather than scoring only one rank's
|
||||
* slice of the vocabulary.
|
||||
*
|
||||
* The drafter's linears are four GEMMs and one attention a layer with no folding: the norms are
|
||||
* plain `rmsnorm`, not a fused norm-add-quantise, because nothing here quantises. At seven rows
|
||||
* a pass the launches, not the bytes, are the cost.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_DSPARK_BF16_H
|
||||
#define RAD_BLOCK_DSPARK_BF16_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* The builder refuses a declaration it cannot serve and says why in its own words; this names which
|
||||
* handle did not come back, so that message reads against a line of this file. An op that resolves
|
||||
* to no kernel is recorded and handed back null -- it is only an error if the block issues it -- so
|
||||
* without this a missing kernel surfaces as a bare "invalid argument" at startup. */
|
||||
#define DS_REFUSED(...) ::rad::arch::drafter_refused({ __VA_ARGS__ })
|
||||
inline int drafter_refused(std::initializer_list<const char*> what) {
|
||||
std::string list;
|
||||
for (const char* w : what) { if (!list.empty()) list += ", "; list += w; }
|
||||
std::fprintf(stderr, "DSpark drafter: the builder gave no handle for %s\n", list.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
struct DsparkBF16 {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
|
||||
/* The drafter's config beyond its geometry. Everything here comes from the container's
|
||||
* `draft.` keys; nothing is defaulted quietly, because a silently ignored gate or window only
|
||||
* moves acceptance, which is the one number the user cannot see. */
|
||||
struct Config {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* noise rows a sequence, and drafts (one per row) */
|
||||
int64_t rank = 0; /* markov_rank: the codebooks' width */
|
||||
int64_t window = 0; /* reference's anchor-aligned n_swa (configured history + 1) */
|
||||
int64_t rot = 0; /* rotary dimensions a head; 0 for all of head_dim */
|
||||
int causal = 0;
|
||||
int tap_norm = 0; /* `fc_norm`: one RMS gain a tap before the concatenation */
|
||||
int qk_norm = 0; /* per-head q/k gains, and no output gate */
|
||||
int gate = 0; /* one sigmoid gate a head on the attention output */
|
||||
const char* act = "gelu"; /* the feed-forward's activation */
|
||||
int64_t steps() const { return block; } /* every row predicts */
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
/* ---- the context pass, one row per committed token */
|
||||
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
|
||||
rad_buf srcn = 0; /* [max_tok, n_taps * n_embd] each tap normed, same layout */
|
||||
rad_buf c = 0, cn = 0; /* [max_tok, n_embd] fc output and separately normed context */
|
||||
rad_buf ck = 0, ckn = 0; /* [max_tok, kv_dim] projected and optionally normed K */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] and its V */
|
||||
|
||||
/* ---- the query pass, `block` rows per sequence */
|
||||
rad_buf x = 0; /* [qrows, n_embd] f32 the drafter's residual stream */
|
||||
rad_buf delta = 0; /* [qrows, n_embd] f32 the block a projection just wrote */
|
||||
rad_buf h = 0; /* [qrows, n_embd] bf16 the normed stream, and every linear's output */
|
||||
rad_buf q = 0, k = 0, v = 0, qn = 0, kn = 0;
|
||||
rad_buf gate = 0, gaten = 0; /* [qrows, n_head] projection and sigmoid */
|
||||
rad_buf attn = 0, attng = 0; /* [qrows, q_dim] attention and gated attention */
|
||||
rad_buf gate_up = 0; rad_buf ff = 0;
|
||||
|
||||
/* ---- the head and the walk, one row per draft position */
|
||||
rad_buf dlog = 0; /* [srows, n_vocab] f32 full-vocabulary draft logits */
|
||||
rad_buf best_score = 0; /* [max_seqs, ceil(n_vocab/64)] f32 partial argmax scores */
|
||||
rad_buf best_token = 0; /* [max_seqs, ceil(n_vocab/64)] i32 partial argmax ids */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
|
||||
};
|
||||
|
||||
Geom g{}; /* the drafter's geometry, not the trunk's */
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
|
||||
int64_t qrows = 0, crows = 0, srows = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* ---- model-scope weights */
|
||||
rad_weight w_fc = 0, w_hnorm = 0, w_norm = 0;
|
||||
rad_weight w_fcnorm[MAX_LAYERS] = {}; /* one row of `fc_norm` a tap */
|
||||
rad_weight w_mk1 = 0, w_mk2 = 0; /* markov_w1 (pred), markov_w2 (succ) */
|
||||
rad_weight w_tok = 0; /* the target's embedding table */
|
||||
rad_weight w_head = 0; /* the target's output table */
|
||||
|
||||
/* ---- per-layer weights */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
rad_weight w_q[MAX_LAYERS] = {}, w_k[MAX_LAYERS] = {}, w_v[MAX_LAYERS] = {}, w_o[MAX_LAYERS] = {};
|
||||
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}, w_gate[MAX_LAYERS] = {};
|
||||
rad_weight w_gu[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
|
||||
|
||||
/* ---- the context pass */
|
||||
rad_op op_tapn[MAX_LAYERS] = {}; /* one per tap, not per layer */
|
||||
rad_op op_cfc = 0, op_cnorm = 0;
|
||||
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
|
||||
rad_op op_crope = 0, op_cstore = 0;
|
||||
|
||||
/* ---- the query pass. The weightless ops are declared once and issued per layer; the ones
|
||||
* with weights are per layer, since a weight's prefetch interval and residency class come
|
||||
* from the op that declares it. */
|
||||
rad_op op_embed = 0, op_widen = 0, op_add = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
|
||||
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
|
||||
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}, op_gp[MAX_LAYERS] = {};
|
||||
rad_op op_op[MAX_LAYERS] = {}, op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
|
||||
rad_op op_widen2 = 0, op_widen3 = 0;
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
rad_op op_sig = 0, op_gate_heads = 0, op_act = 0;
|
||||
|
||||
/* ---- the head and the walk */
|
||||
rad_op op_dlogits = 0, op_markov = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck, const char* ck_head,
|
||||
const Wire& wire);
|
||||
/* The context pass, one row per committed token. */
|
||||
void context(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The query pass, the head and the Markov walk, `block` rows per sequence. */
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
|
||||
private:
|
||||
int64_t q_dim() const { return g.n_head * g.head_dim; }
|
||||
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------------------ declare */
|
||||
|
||||
inline int DsparkBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
|
||||
int base_layer, rad_kvgroup group, rad_weight tok_embd,
|
||||
const char* ck, const char* ck_head, const Wire& wire) {
|
||||
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
|
||||
if (!ck || !ck_head || !w_tok) return DS_REFUSED("ck", "ck_head", "w_tok");
|
||||
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
|
||||
fprintf(stderr, "radiance: the bf16 DSpark drafter has %lld layers; this block carries at "
|
||||
"most %d\n", (long long)g.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg.n_taps <= 0 || cfg.n_taps > MAX_LAYERS || cfg.block < 2 || cfg.rank <= 0)
|
||||
return RAD_E_INVAL;
|
||||
if (cfg.qk_norm && cfg.gate) {
|
||||
fprintf(stderr, "radiance: the drafter declares both per-head q/k norms and a per-head "
|
||||
"output gate; no published drafter ships both, and this block would have "
|
||||
"to guess which one the checkpoint trained with\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The full-vocabulary head and Markov scan are read replicated; partial-vocabulary drafting
|
||||
* would need an exact distributed argmax and replicated codebook access. */
|
||||
if (g.world > 1) {
|
||||
fprintf(stderr, "radiance: the bf16 DSpark drafter reads the target's whole output table "
|
||||
"and cannot draft at tp %d; run it at tp 1\n", g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
const int64_t qd = q_dim(), kvd = kv_dim(), E = g.n_embd;
|
||||
crows = g.max_tok;
|
||||
qrows = g.max_seqs * cfg.block;
|
||||
if (qrows > g.max_tok) qrows = g.max_tok;
|
||||
srows = g.max_seqs * cfg.steps(); /* every row predicts */
|
||||
if (qrows <= 0 || srows <= 0 || cfg.rot < 0 || cfg.rot > g.head_dim || cfg.rot % 2)
|
||||
return RAD_E_INVAL;
|
||||
const int64_t rot = cfg.rot ? cfg.rot : g.head_dim;
|
||||
|
||||
/* One op declaration per kernel shape, shared by the layers: `rmsnorm`'s and `gemm_nt`'s
|
||||
* parameters are geometry, and only the weights differ per layer. */
|
||||
auto gemm = [&](int64_t rows, int64_t n, int64_t k, rad_weight wt, rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n),
|
||||
RAD_INT("K", k), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt)),
|
||||
{x}, {y});
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.fc.weight"), nm.ckpt("%s.fc.weight", ck)));
|
||||
w_fc = decl_w(b, nm.f("dspark.fc.weight"), RAD_BF16, {E, cfg.n_taps * E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
|
||||
nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_fc || !w_hnorm || !w_norm) return DS_REFUSED("w_fc", "w_hnorm", "w_norm");
|
||||
|
||||
/* `fc_norm` is [n_taps, n_embd]: one gain row a tap, read as that tap's slice. */
|
||||
if (cfg.tap_norm) {
|
||||
const char* src = nm.ckpt("%s.fc_norm.weight", ck);
|
||||
for (int64_t t = 0; t < cfg.n_taps; ++t) {
|
||||
const int i = (int)t;
|
||||
RAD_ARCH_TRY(map_rows(b, nm.f("dspark.fc_norm.%d.weight", i),
|
||||
{ { src, (int)t, 1 } }));
|
||||
w_fcnorm[i] = decl_w(b, nm.f("dspark.fc_norm.%d.weight", i), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_fcnorm[i]) return DS_REFUSED("w_fcnorm[i]");
|
||||
}
|
||||
}
|
||||
|
||||
/* The Markov codebooks, bf16, replicated over the whole vocabulary: both are [vocab, rank], so
|
||||
* `w2 @ w1[prev]` is `<w1[prev], w2[token]>`. RAD_ACCESS_VOCAB: each walk position reads one
|
||||
* predecessor row and scans every successor row. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
|
||||
nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
|
||||
nm.ckpt("%s.markov_head.markov_w2.weight", ck)));
|
||||
w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, {g.n_vocab_all, cfg.rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_mk1 || !w_mk2) return DS_REFUSED("w_mk1", "w_mk2");
|
||||
|
||||
/* The target's output table under the drafter's own name: one stored tensor, two arch weights,
|
||||
* as rad_block_dspark.h does for its 2-bit copy. bf16 and replicated here, since the drafter
|
||||
* reads it as the head its full-vocabulary walk scores (see NOT DONE for sharding). */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.head.weight"), ck_head));
|
||||
w_head = decl_w(b, nm.f("dspark.head.weight"), RAD_BF16, {g.n_vocab_all, E},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_head) return DS_REFUSED("w_head");
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights
|
||||
*
|
||||
* One name map and one declaration a weight, spelled out: the list is the readable form of
|
||||
* which checkpoint tensor feeds which matmul, and a drafter has few enough of them that a
|
||||
* table would only hide it. */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
const RadWeightGroup grp = grp_layer(first_layer + i);
|
||||
|
||||
/* A norm gain: f32, read whole, never sharded. */
|
||||
auto norm_w = [&](rad_weight* out, const char* suffix, const char* from,
|
||||
std::initializer_list<int64_t> shape) -> int {
|
||||
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
|
||||
RAD_ARCH_TRY(map_copy(b, name, nm.ckpt("%s.layers.%d.%s", ck, i, from)));
|
||||
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
|
||||
return *out ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
/* A linear: bf16. More than one source is a concatenation, whose row parts say where each
|
||||
* piece begins (RadWeightDecl::row_parts), so `act_mul` can read [gate | up] as one
|
||||
* weight. */
|
||||
auto lin_w = [&](rad_weight* out, const char* suffix,
|
||||
std::initializer_list<const char*> srcs,
|
||||
std::initializer_list<int64_t> shape,
|
||||
std::initializer_list<int64_t> parts = {}) -> int {
|
||||
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
|
||||
if (srcs.size() > 1) RAD_ARCH_TRY(map_concat(b, name, srcs));
|
||||
else RAD_ARCH_TRY(map_copy(b, name, *srcs.begin()));
|
||||
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp, 0,
|
||||
parts);
|
||||
return *out ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
|
||||
#define SRC(path) nm.ckpt("%s.layers.%d." path, ck, i)
|
||||
RAD_ARCH_TRY(norm_w(&w_anorm[i], "attn_norm.weight", "input_layernorm.weight", {E}));
|
||||
RAD_ARCH_TRY(norm_w(&w_fnorm[i], "ffn_norm.weight", "post_attention_layernorm.weight", {E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_q[i], "attn_q", { SRC("self_attn.q_proj.weight") }, {qd, E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_k[i], "attn_k", { SRC("self_attn.k_proj.weight") }, {kvd, E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_v[i], "attn_v", { SRC("self_attn.v_proj.weight") }, {kvd, E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_o[i], "attn_output", { SRC("self_attn.o_proj.weight") }, {E, qd}));
|
||||
RAD_ARCH_TRY(lin_w(&w_gu[i], "ffn_gate_up",
|
||||
{ SRC("mlp.gate_proj.weight"), SRC("mlp.up_proj.weight") },
|
||||
{2 * g.n_ff, E}, { g.n_ff, g.n_ff }));
|
||||
RAD_ARCH_TRY(lin_w(&w_dn[i], "ffn_down", { SRC("mlp.down_proj.weight") },
|
||||
{E, g.n_ff}));
|
||||
if (cfg.gate)
|
||||
RAD_ARCH_TRY(lin_w(&w_gate[i], "attn_gate", { SRC("self_attn.g_proj.weight") },
|
||||
{g.n_head, E}));
|
||||
if (cfg.qk_norm) {
|
||||
RAD_ARCH_TRY(norm_w(&w_qn[i], "attn_q_norm.weight", "self_attn.q_norm.weight",
|
||||
{g.head_dim}));
|
||||
RAD_ARCH_TRY(norm_w(&w_kn[i], "attn_k_norm.weight", "self_attn.k_norm.weight",
|
||||
{g.head_dim}));
|
||||
}
|
||||
#undef SRC
|
||||
}
|
||||
|
||||
/* Non-causal: every query row sees its whole block and the context the trunk committed
|
||||
* (`causal` comes from `draft.is_causal`). Declared before both kv_stores, which read the
|
||||
* resolved `block_size` back with rad_kv_block_size(); before it, that returns zero. */
|
||||
op_attn = rw(b, RAD_OP(b, cfg.window > 0 ? "attn_paged_anchor_window" : "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{cfg.qk_norm ? w.qn : w.q}, {w.attn});
|
||||
if (!op_attn) return DS_REFUSED("op_attn");
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass
|
||||
*
|
||||
* One row per committed token, run once per trunk step: the taps become the drafter's own K
|
||||
* and V. Nothing here is per query row, so its cost follows the trunk's token count, not the
|
||||
* block's. */
|
||||
for (int64_t t = 0; t < cfg.n_taps; ++t) {
|
||||
const int i = (int)t;
|
||||
op_tapn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_fcnorm[i])),
|
||||
{w.src}, {w.srcn});
|
||||
if (!op_tapn[i]) return DS_REFUSED("op_tapn[i]");
|
||||
}
|
||||
op_cfc = gemm(crows, E, cfg.n_taps * E, w_fc, w.srcn, w.c);
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.cn});
|
||||
if (!op_cfc || !op_cnorm) return DS_REFUSED("op_cfc", "op_cnorm");
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
|
||||
* and residency class. */
|
||||
op_ck[i] = gemm(crows, kvd, E, w_k[i], w.cn, w.ck);
|
||||
op_cv[i] = gemm(crows, kvd, E, w_v[i], w.cn, w.cv);
|
||||
if (!op_ck[i] || !op_cv[i]) return DS_REFUSED("op_ck[i]", "op_cv[i]");
|
||||
if (cfg.qk_norm) {
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.ck}, {w.ckn});
|
||||
if (!op_cknorm[i]) return DS_REFUSED("op_cknorm[i]");
|
||||
}
|
||||
}
|
||||
|
||||
/* K-only rope: `rope` rotates the first n_head + n_head_kv heads, so a K-only tensor is
|
||||
* n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer. Each context
|
||||
* row is rotated by its own absolute position, as the reference's single concatenated rope
|
||||
* does. */
|
||||
op_crope = rw(b, decl_rope(b, g, crows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
|
||||
{cfg.qk_norm ? w.ckn : w.ck}, {cfg.qk_norm ? w.ckn : w.ck});
|
||||
op_cstore = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{cfg.qk_norm ? w.ckn : w.ck, w.cv}, {});
|
||||
if (!op_crope || !op_cstore) return DS_REFUSED("op_crope", "op_cstore");
|
||||
|
||||
/* ---------------------------------------------------------------- the query pass
|
||||
*
|
||||
* `block` rows per sequence, through the drafter's layers. The residual stream is f32 and the
|
||||
* linears read bf16, exactly as the trunk keeps them: `rmsnorm` reads the stream and writes the
|
||||
* activations, `cast` widens a projection's output, and `add` keeps the sum in f32. */
|
||||
op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {w.h});
|
||||
op_widen = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.x});
|
||||
/* One widen and one add serve both residual sites a layer: same shapes, same buffers. */
|
||||
op_widen2 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.delta});
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.delta}, {w.x});
|
||||
if (!op_embed || !op_widen || !op_widen2 || !op_add)
|
||||
return DS_REFUSED("op_embed", "op_widen", "op_widen2", "op_add");
|
||||
|
||||
/* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
|
||||
* planner's liveness (core/build/rad_bufplan.cpp), and the stream `x` lives over the ops that
|
||||
* touch it: each layer's two norms in the loop, the final one after everything the layers
|
||||
* issue. Declared up front, the stream's lifetime would end before the layers and the planner
|
||||
* could overlay a feed-forward temporary on it. */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_anorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_qp[i] = gemm(qrows, qd, E, w_q[i], w.h, w.q);
|
||||
op_kp[i] = gemm(qrows, kvd, E, w_k[i], w.h, w.k);
|
||||
op_vp[i] = gemm(qrows, kvd, E, w_v[i], w.h, w.v);
|
||||
op_op[i] = gemm(qrows, E, qd, w_o[i], cfg.gate ? w.attng : w.attn, w.h);
|
||||
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_fnorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_gu[i] = gemm(qrows, 2 * g.n_ff, E, w_gu[i], w.h, w.gate_up);
|
||||
op_dn[i] = gemm(qrows, E, g.n_ff, w_dn[i], w.ff, w.h);
|
||||
if (!op_anorm[i] || !op_qp[i] || !op_kp[i] || !op_vp[i] || !op_op[i] || !op_fnorm[i] ||
|
||||
!op_gu[i] || !op_dn[i])
|
||||
return RAD_E_INVAL;
|
||||
if (cfg.qk_norm) {
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_qn[i])),
|
||||
{w.q}, {w.qn});
|
||||
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.kn});
|
||||
if (!op_qn[i] || !op_kn[i]) return DS_REFUSED("op_qn[i]", "op_kn[i]");
|
||||
}
|
||||
if (cfg.gate) {
|
||||
op_gp[i] = gemm(qrows, g.n_head, E, w_gate[i], w.h, w.gate);
|
||||
if (!op_gp[i]) return DS_REFUSED("op_gp[i]");
|
||||
}
|
||||
}
|
||||
|
||||
op_qrope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head, 0, rot, "neox"),
|
||||
{cfg.qk_norm ? w.qn : w.q}, {cfg.qk_norm ? w.qn : w.q});
|
||||
op_krope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
|
||||
{cfg.qk_norm ? w.kn : w.k}, {cfg.qk_norm ? w.kn : w.k});
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{cfg.qk_norm ? w.kn : w.k, w.v}, {});
|
||||
/* The gate the trunk uses too: one sigmoid a head, then one scale a head's whole row. */
|
||||
if (cfg.gate) {
|
||||
op_sig = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_head),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate}, {w.gaten});
|
||||
op_gate_heads = rw(b, RAD_OP(b, "scale_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("act", "none"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn, w.gaten}, {w.attng});
|
||||
if (!op_sig || !op_gate_heads) return DS_REFUSED("op_sig", "op_gate_heads");
|
||||
}
|
||||
/* `act_mul` with the activation the drafter was trained with: exact-erf gelu for the Spark
|
||||
* drafts (`hidden_activation: gelu`), silu for a Qwen3-shaped one. `gelu_mul` is the tanh
|
||||
* approximation and is not what the reference runs. */
|
||||
op_act = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("act", cfg.act), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ff});
|
||||
op_outnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
if (!op_qrope || !op_krope || !op_store || !op_act || !op_outnorm)
|
||||
return DS_REFUSED("op_qrope", "op_krope", "op_store", "op_act", "op_outnorm");
|
||||
|
||||
/* ---------------------------------------------------------------- the head and full-vocabulary walk
|
||||
*
|
||||
* Every row predicts, so the head scores all `steps` rows, anchor included. The row order is
|
||||
* sequence-major, which is the selector's [sequence, position, vocabulary] contract. The
|
||||
* greedy Markov op scans all vocabulary entries at every position and feeds each winning id
|
||||
* into the next position's bigram bias.
|
||||
*/
|
||||
op_dlogits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_head)),
|
||||
{w.h}, {w.dlog});
|
||||
op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy_f32",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
|
||||
RAD_INT("steps", cfg.steps()), RAD_INT("rank", cfg.rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_mk1, w_mk2)),
|
||||
{w.dlog}, {w.best_score, w.best_token, w.tokens});
|
||||
if (!op_dlogits || !op_markov) return DS_REFUSED("op_dlogits", "op_markov");
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the context pass */
|
||||
|
||||
inline void DsparkBF16::context(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int64_t E = g.n_embd;
|
||||
|
||||
/* Each tap's slice of the residual the trunk just tapped, normed with its own gain into the
|
||||
* same slice layout of one row-per-token buffer. */
|
||||
for (int64_t t = 0; t < cfg.n_taps; ++t) {
|
||||
const int i = (int)t;
|
||||
if (!cfg.tap_norm) continue;
|
||||
RAD_ISSUE_N(c, op_tapn[i], T, bcol(w.src, t * E, E, T), RAD_W(w_fcnorm[i]),
|
||||
bcol(w.srcn, t * E, E, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_cfc, T, cfg.tap_norm ? brows(w.srcn, T) : brows(w.src, T), RAD_W(w_fc),
|
||||
brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.cn, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cn, T), RAD_W(w_k[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cn, T), RAD_W(w_v[i]), brows(w.cv, T));
|
||||
if (cfg.qk_norm)
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
|
||||
brows(w.ckn, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_cstore, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), brows(w.cv, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the query pass */
|
||||
|
||||
inline void DsparkBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
|
||||
/* The block the core staged: the token the sampler just chose, then the mask token in every
|
||||
* unfilled slot. */
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_widen, T, brows(w.h, T), brows(w.x, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
|
||||
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h, T), RAD_W(w_q[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h, T), RAD_W(w_k[i]), brows(w.k, T));
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h, T), RAD_W(w_v[i]), brows(w.v, T));
|
||||
if (cfg.qk_norm) {
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.qn, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]),
|
||||
brows(w.kn, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_qrope, T, brows(cfg.qk_norm ? w.qn : w.q, T), pos);
|
||||
RAD_ISSUE_N(c, op_krope, T, brows(cfg.qk_norm ? w.kn : w.k, T), pos);
|
||||
/* The block's own K and V go into the cache past `seqused`, which is how every row of the
|
||||
* block attends to every other; the next context pass overwrites them, which is the
|
||||
* reference's `crop(start)`. */
|
||||
RAD_ISSUE_N(c, op_store, T, brows(cfg.qk_norm ? w.kn : w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, first_layer + i));
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(cfg.qk_norm ? w.qn : w.q, T), kv_cache(kv, first_layer + i),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T));
|
||||
if (cfg.gate) {
|
||||
/* One gate a head, applied to that head's whole row of the attention output, before
|
||||
* o_proj. View [rows, heads * dim] and [rows, heads] as one row a head. */
|
||||
RAD_ISSUE_N(c, op_gp[i], T, brows(w.h, T), RAD_W(w_gate[i]), brows(w.gate, T));
|
||||
RAD_ISSUE_N(c, op_sig, T, brows(w.gate, T), brows(w.gaten, T));
|
||||
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, w.attn), RAD_BF16, T * g.n_head,
|
||||
g.head_dim);
|
||||
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, w.gaten), RAD_BF16, T * g.n_head, 1);
|
||||
const RadOperand gated = RAD_P_T2(rad_buf_ptr(c, w.attng), RAD_BF16, T * g.n_head,
|
||||
g.head_dim);
|
||||
RAD_ISSUE_N(c, op_gate_heads, T * g.n_head, heads, gates, RAD_NONE, gated);
|
||||
}
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(cfg.gate ? w.attng : w.attn, T), RAD_W(w_o[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
|
||||
|
||||
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h, T), RAD_W(w_gu[i]), brows(w.gate_up, T));
|
||||
RAD_ISSUE_N(c, op_act, T, bcol(w.gate_up, 0, g.n_ff, T),
|
||||
bcol(w.gate_up, g.n_ff, g.n_ff, T), brows(w.ff, T));
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ff, T), RAD_W(w_dn[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_outnorm, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
|
||||
/* The predicting rows, named by the scheduler through `out_ids`. */
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.h, S), RAD_W(w_head), brows(w.dlog, S));
|
||||
RAD_ISSUE_N(c, op_markov, batch->n_seq, brows(w.dlog, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
|
||||
brows(w.best_score, batch->n_seq), brows(w.best_token, batch->n_seq),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
}
|
||||
|
||||
/* ================================================================== the trunk's side of it
|
||||
*
|
||||
* The taps, and one call a target plugin makes to put a drafter on. Both live here because both
|
||||
* are the drafter's contract with the trunk: which residual streams it reads, where its blocks
|
||||
* live, and how deep a proposal it makes. */
|
||||
|
||||
/* The residual streams a drafter reads, captured as the trunk passes them. */
|
||||
struct DsparkTaps {
|
||||
enum { MAX_TAPS = DsparkBF16::MAX_LAYERS };
|
||||
|
||||
int n = 0;
|
||||
int layer[MAX_TAPS] = {}; /* the trunk layer whose OUTPUT is tapped */
|
||||
rad_buf src = 0; /* [rows, n * n_embd] f32, one column slice a tap */
|
||||
rad_op op = 0; /* the residual stream, copied into that slice */
|
||||
|
||||
/* Read `draft.target_layer_ids`, which names the layers whose output is tapped. Zero taps when
|
||||
* the container carries no drafter, or one that reads no trunk stream. Out-of-range ids are
|
||||
* dropped, not clamped: a drafter naming a layer this model lacks belongs to another target. */
|
||||
int read(const RadModelMeta* meta, int64_t n_layer) {
|
||||
n = 0;
|
||||
const char* ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
|
||||
if (!ids) ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
|
||||
if (!ids) ids = rad_meta_gets(meta, "draft.gguf_target_layers", nullptr);
|
||||
n = parse_layer_ids(ids, n_layer, layer, MAX_TAPS);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* The copy that saves a tap. A drafter reads the trunk's own residual stream, which is f32
|
||||
* here and stays f32: the widening the fp8 graphs do is theirs, not this one's. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, int64_t rows, rad_buf residual) {
|
||||
if (n <= 0) return RAD_OK;
|
||||
src = decl_b(b, nm.f("draft_src"), RAD_F32, {rows, (int64_t)n * g.n_embd});
|
||||
if (!src) return DS_REFUSED("src");
|
||||
/* Declared over the trunk's own residual buffer: the op's operand pair is the stream and a
|
||||
* tap's slice, and every issue site passes the slice it is writing. */
|
||||
op = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("from", "f32"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{residual}, {src});
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The tap that follows trunk layer `l`, if any. Issued on prefill and decode alike: the
|
||||
* drafter conditions on every committed token's residual stream. */
|
||||
void step(RadCtx* c, rad_buf residual, int64_t rows, int64_t l, int64_t n_embd) const {
|
||||
if (!op) return;
|
||||
for (int t = 0; t < n; ++t)
|
||||
if (layer[t] == l)
|
||||
RAD_ISSUE(c, op, brows(residual, rows),
|
||||
bcol(src, (int64_t)t * n_embd, n_embd, rows));
|
||||
}
|
||||
};
|
||||
|
||||
/* Put a DSpark drafter on a trunk: its config from the container's `draft.` keys, its own KV
|
||||
* group, its graph, and the drafter declaration the core drives. `base_layer` is the absolute
|
||||
* layer its first block takes, one past the trunk's last.
|
||||
*
|
||||
* Nothing is defaulted quietly. A `draft.` key that describes a drafter this file does not
|
||||
* implement is refused by name, because a silently ignored gate, window or block length only moves
|
||||
* acceptance -- the one number a user cannot see in the output.
|
||||
*
|
||||
* The plugin calls it last, after its own head and logits: a drafter's passes run after the whole
|
||||
* trunk, and the buffer planner lays an op's lifetimes out in declaration order, so declaring it
|
||||
* earlier would let a trunk temporary land on the stream the drafter is still reading. */
|
||||
inline int declare_dspark(DsparkBF16* ds, DsparkBF16::Wire* w, rad_kvgroup* kv, RadBuilder* b,
|
||||
Names& nm, const RadModelMeta* meta, const RadBuildCtx* ctx,
|
||||
const Geom& target, const DsparkTaps& taps, int base_layer,
|
||||
rad_weight tok_embd, const char* ck_head) {
|
||||
Geom dg{};
|
||||
RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DSpark"));
|
||||
/* The width the drafter concatenates and projects is the trunk's, and `drafter_geom` keeps the
|
||||
* target's -- so a draft that disagrees is a draft for another model, and its `fc` would be
|
||||
* read at a shape it was not trained at. */
|
||||
const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size",
|
||||
rad_meta_geti(meta, "draft.dflash_config.hidden_size",
|
||||
dg.n_embd));
|
||||
if (want_embd != dg.n_embd) {
|
||||
fprintf(stderr, "radiance: the drafter reads a %lld-wide trunk and this target is %lld "
|
||||
"wide; they are not the same model\n", (long long)want_embd,
|
||||
(long long)dg.n_embd);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
DsparkBF16::Config c{};
|
||||
c.n_taps = taps.n;
|
||||
c.rank = rad_meta_geti(meta, "draft.markov_rank", 0);
|
||||
c.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
|
||||
c.tap_norm = rad_meta_geti(meta, "draft.fc_norm", 0) ? 1 : 0;
|
||||
c.qk_norm = rad_meta_geti(meta, "draft.qk_norm", 0) ? 1 : 0;
|
||||
c.gate = rad_meta_geti(meta, "draft.headwise_attn_output_gate", 0) ? 1 : 0;
|
||||
const char* act = rad_meta_gets(meta, "draft.hidden_act", "silu");
|
||||
c.act = (!std::strcmp(act, "gelu") || !std::strcmp(act, "none")) ? "gelu"
|
||||
: (!std::strcmp(act, "silu")) ? "silu" : nullptr;
|
||||
if (!c.act) {
|
||||
fprintf(stderr, "radiance: the drafter's feed-forward is '%s'; this block runs exact-erf "
|
||||
"gelu (what the Spark drafts train with) or silu, and the two are not the "
|
||||
"same function\n", act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* gate_mode = rad_meta_gets(meta, "draft.gate_attn_act_mode", "sigmoid");
|
||||
if (c.gate && std::strcmp(gate_mode, "sigmoid")) {
|
||||
fprintf(stderr, "radiance: the drafter gates its attention output with '%s'; this block "
|
||||
"applies a sigmoid\n", gate_mode);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* Every row predicts, the anchor included. Without it a block row's worth of proposals is
|
||||
* missing and the head reads rows the drafter never filled. */
|
||||
if (!rad_meta_geti(meta, "draft.sample_from_anchor", 1)) {
|
||||
fprintf(stderr, "radiance: the drafter declares sample_from_anchor false, whose bonus "
|
||||
"anchor slot this block has no rows for\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The reference applies the bigram bias to the full vocabulary before each greedy choice. */
|
||||
if (c.rank <= 0 || c.rank % 32 || c.rank > 512) {
|
||||
fprintf(stderr, "radiance: the drafter's Markov head has rank %lld; the walk that applies "
|
||||
"the bigram bias takes a multiple of 32 up to 512\n", (long long)c.rank);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The block is both the number of noise rows and the number of drafts: every row, the anchor
|
||||
* included, predicts the token after it, so the depth is `block_size` rather than the
|
||||
* `block_size - 1` a DFlash2 container's is. A block-diffusion drafter is trained for one
|
||||
* block length and has no partial block, so any other depth is refused. */
|
||||
const int64_t trained = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
if (trained < 2) {
|
||||
fprintf(stderr, "radiance: this drafter declares no draft.block_size; the number of masked "
|
||||
"positions it denoises is not a number this engine may choose.\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if ((long long)ctx->max_spec != trained) {
|
||||
fprintf(stderr, "radiance: the drafter was trained at block_size %lld, which is %lld draft "
|
||||
"tokens, and this serve asks for %d. A block-diffusion drafter denoises a "
|
||||
"fixed number of mask positions; run it at %lld.\n",
|
||||
(long long)trained, (long long)trained, ctx->max_spec, (long long)trained);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
c.block = trained;
|
||||
|
||||
/* The reference gives every row of the block the anchor's history. `window` is the configured
|
||||
* number of preceding positions; llama.cpp sets n_swa to window + 1 and masks when
|
||||
* anchor - key >= n_swa. Keep that exact width in attention, the KV group and scheduler. */
|
||||
int64_t window = 0;
|
||||
if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
|
||||
window = rad_meta_geti(meta, "draft.sliding_window", 0);
|
||||
if (window < 0 || (window && window < c.block)) {
|
||||
fprintf(stderr, "radiance: the drafter's %lld-token window does not cover the %lld-token "
|
||||
"block it denoises\n", (long long)window, (long long)c.block);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (window > 0 && window == INT64_MAX) return RAD_E_INVAL;
|
||||
c.window = window > 0 ? window + 1 : 0; /* llama.cpp dflash: n_swa += 1 */
|
||||
const double prf = rad_meta_getf(meta, "draft.partial_rotary_factor",
|
||||
rad_meta_getf(meta,
|
||||
"draft.rope_parameters.partial_rotary_factor", 1.0));
|
||||
const double rot = (double)dg.head_dim * prf;
|
||||
if (!(prf > 0.0) && prf != 0.0) {
|
||||
fprintf(stderr, "radiance: the drafter's partial_rotary_factor is %g\n", prf);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (std::floor(rot) != rot || (int64_t)rot % 2 || rot > (double)dg.head_dim) {
|
||||
fprintf(stderr, "radiance: the drafter rotates %g of %lld head dimensions\n", rot,
|
||||
(long long)dg.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c.rot = (int64_t)rot ? (int64_t)rot : dg.head_dim;
|
||||
|
||||
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, c.window, base_layer, kv));
|
||||
|
||||
/* Activations: one row per committed token for the context pass, one row per block position
|
||||
* for the query pass. Both are small; the drafter's cost is its weights. */
|
||||
const int64_t qd = dg.n_head * dg.head_dim, kvd = dg.n_head_kv * dg.head_dim;
|
||||
int64_t qr = dg.max_seqs * c.block;
|
||||
if (qr > dg.max_tok) qr = dg.max_tok;
|
||||
const int64_t sr = dg.max_seqs * c.steps();
|
||||
DsparkBF16::Wire& dw = *w;
|
||||
dw.src = taps.src;
|
||||
dw.srcn = decl_b(b, nm.f("ds_srcn"), RAD_BF16, {dg.max_tok, c.n_taps * dg.n_embd});
|
||||
dw.c = decl_b(b, nm.f("ds_c"), RAD_BF16, {dg.max_tok, dg.n_embd});
|
||||
dw.cn = decl_b(b, nm.f("ds_cn"), RAD_BF16, {dg.max_tok, dg.n_embd});
|
||||
dw.ck = decl_b(b, nm.f("ds_ck"), RAD_BF16, {dg.max_tok, kvd});
|
||||
dw.cv = decl_b(b, nm.f("ds_cv"), RAD_BF16, {dg.max_tok, kvd});
|
||||
if (c.qk_norm) dw.ckn = decl_b(b, nm.f("ds_ckn"), RAD_BF16, {dg.max_tok, kvd});
|
||||
dw.x = decl_b(b, nm.f("ds_x"), RAD_F32, {qr, dg.n_embd});
|
||||
dw.delta = decl_b(b, nm.f("ds_delta"), RAD_F32, {qr, dg.n_embd});
|
||||
dw.h = decl_b(b, nm.f("ds_h"), RAD_BF16, {qr, dg.n_embd});
|
||||
dw.q = decl_b(b, nm.f("ds_q"), RAD_BF16, {qr, qd});
|
||||
dw.k = decl_b(b, nm.f("ds_k"), RAD_BF16, {qr, kvd});
|
||||
dw.v = decl_b(b, nm.f("ds_v"), RAD_BF16, {qr, kvd});
|
||||
if (c.qk_norm) {
|
||||
dw.qn = decl_b(b, nm.f("ds_qn"), RAD_BF16, {qr, qd});
|
||||
dw.kn = decl_b(b, nm.f("ds_kn"), RAD_BF16, {qr, kvd});
|
||||
}
|
||||
dw.gate = decl_b(b, nm.f("ds_gate"), RAD_BF16, {qr, dg.n_head});
|
||||
dw.attn = decl_b(b, nm.f("ds_attn"), RAD_BF16, {qr, qd});
|
||||
if (c.gate) {
|
||||
dw.gaten = decl_b(b, nm.f("ds_gaten"), RAD_BF16, {qr, dg.n_head});
|
||||
dw.attng = decl_b(b, nm.f("ds_attng"), RAD_BF16, {qr, qd});
|
||||
}
|
||||
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), RAD_BF16, {qr, 2 * dg.n_ff});
|
||||
dw.ff = decl_b(b, nm.f("ds_ff"), RAD_BF16, {qr, dg.n_ff});
|
||||
dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab});
|
||||
const int64_t n_markov_tiles = (dg.n_vocab_all + 63) / 64;
|
||||
dw.best_score = decl_b(b, nm.f("ds_markov_score"), RAD_F32,
|
||||
{dg.max_seqs, n_markov_tiles});
|
||||
dw.best_token = decl_b(b, nm.f("ds_markov_token"), RAD_I32,
|
||||
{dg.max_seqs, n_markov_tiles});
|
||||
/* The proposal buffer (RadDrafterDecl::proposal): a block pass proposes through the drafter's
|
||||
* own walk, never through the sampler's token buffer. */
|
||||
dw.tokens = decl_b(b, nm.f("ds_tokens"), RAD_I32, {dg.max_seqs, c.steps()});
|
||||
if (!dw.srcn || !dw.c || !dw.cn || !dw.ck || !dw.cv ||
|
||||
(c.qk_norm && (!dw.ckn || !dw.qn || !dw.kn)) ||
|
||||
(c.gate && (!dw.gaten || !dw.attng)) || !dw.x || !dw.delta || !dw.h || !dw.q || !dw.k ||
|
||||
!dw.v || !dw.gate || !dw.attn || !dw.gate_up || !dw.ff || !dw.dlog ||
|
||||
!dw.best_score || !dw.best_token || !dw.tokens)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
RAD_ARCH_TRY(ds->declare(b, nm, dg, c, base_layer, *kv, tok_embd, "draft", ck_head, dw));
|
||||
|
||||
RadDrafterDecl drf{};
|
||||
drf.name = "dspark";
|
||||
drf.kind = RAD_DRAFT_BLOCK;
|
||||
drf.depth = ctx->max_spec;
|
||||
drf.block = c.block;
|
||||
drf.proposal = dw.tokens;
|
||||
drf.proposal_pitch = c.steps();
|
||||
drf.window = c.window;
|
||||
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.mask_token_id", -1);
|
||||
if (drf.mask_token < 0)
|
||||
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1);
|
||||
if (drf.mask_token < 0) {
|
||||
fprintf(stderr, "radiance: this drafter declares no mask_token_id, which every unfilled "
|
||||
"block position embeds\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
|
||||
rad_note(b, "DSpark drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
|
||||
"ffn %lld, %s attention with a %lld-token anchor-aligned window (%lld configured "
|
||||
"history + 1), %lld of %lld rotary dimensions, %s, %s a head, %d trunk tap(s); one "
|
||||
"forward over %lld noise row(s), the anchor included, proposes %lld tokens",
|
||||
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
|
||||
(long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
|
||||
(long long)dg.n_ff, c.causal ? "causal" : "non-causal", (long long)c.window,
|
||||
(long long)window, (long long)c.rot, (long long)dg.head_dim, c.act,
|
||||
c.gate ? "sigmoid gate" : "no gate", (int)c.n_taps, (long long)c.block,
|
||||
(long long)c.steps());
|
||||
rad_note(b, "the rank-%lld Markov bigram head greedily scans all %lld vocabulary tokens at "
|
||||
"each draft position; confidence is not applied to logits%s",
|
||||
(long long)c.rank, (long long)dg.n_vocab_all,
|
||||
rad_meta_geti(meta, "draft.has_confidence_head", 0)
|
||||
? " (its reference role is adaptive depth, which this fixed-depth graph does not use)"
|
||||
: "");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_DSPARK_BF16_H */
|
||||
+108
-25
@@ -109,6 +109,11 @@ struct GdnFP8 {
|
||||
rad_weight w_norm = 0, w_ab = 0, w_conv = 0;
|
||||
/* The input was normed and quantised by the caller; this block declares no norm. */
|
||||
bool ext_in = false;
|
||||
/* Set by the architecture before declare: the a|b projection runs on the second lane beside the
|
||||
* in-projection at decode and verify sizes. Not where lane 1 carries collectives, which the
|
||||
* projection would queue behind. Its concurrent buffers cost memory (at Qwen3.8-27B TP2: +70
|
||||
* MiB arena and +33 MiB queues a card) for about +1 % at one stream. */
|
||||
bool ab_lane = false;
|
||||
rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0;
|
||||
LinearFP8 in{}, out{};
|
||||
NormQuantFP8 nq_h{};
|
||||
@@ -121,7 +126,22 @@ struct GdnFP8 {
|
||||
* convolution in the recurrent update's prologue. The pair is declared either way; cr_rows is
|
||||
* the widest decode window the fold serves. */
|
||||
rad_op op_cr = 0;
|
||||
/* Geom::plain_norm with an out projection that reads no codes (a 4-bit one): the recurrent
|
||||
* epilogue and the prefill quantiser leave the code pair unwritten. */
|
||||
bool o_plain = false;
|
||||
/* Whether op_cr writes the out projection's codes; otherwise q_o follows it. */
|
||||
bool cr_codes = false;
|
||||
int64_t cr_rows = 0;
|
||||
/* Set by the architecture after declare: a `prefetch` of the out-projection's leading bytes
|
||||
* (decl_prefetch, rad_arch.h), issued beside the decode recurrent update on steps of up to
|
||||
* pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
|
||||
rad_op op_pf_out = 0;
|
||||
int64_t pf_out_rows = 0, pf_out_seqs = 0;
|
||||
/* The same read as a second op for steps of at least pf_out_v_rows rows, where the
|
||||
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
|
||||
* every step takes op_pf_out. */
|
||||
rad_op op_pf_out_v = 0;
|
||||
int64_t pf_out_v_rows = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */
|
||||
bool ar_out = false;
|
||||
@@ -139,6 +159,13 @@ struct GdnFP8 {
|
||||
* trailing add, which would read the delta before the reduction. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
|
||||
ArPieces* pieces = nullptr) const;
|
||||
/* Whether step() with `own_ar` false runs the whole block a piece at a time over `pieces`
|
||||
* (its piece path), asked by a caller that must know before it commits to a schedule. */
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
return pieces && pieces->cu && pieces->cuts(batch->n_tok) &&
|
||||
batch->n_tok <= 2 * pieces->rows && (ext_in || pieces->in_ready) && !op_add &&
|
||||
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL;
|
||||
}
|
||||
/* Whether a step of T rows issues the all-reduce itself, asked by a caller before taking it
|
||||
* over; and that all-reduce over rows [r0, r0 + rows) of the output. */
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
@@ -216,7 +243,12 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* Norm and quantise in one op (rad_fp8.h: NormQuantFP8); the qkv|z and a|b projections read
|
||||
* it. */
|
||||
* it. a|b is a plain bf16 GEMM over the bf16 plane, so where qkv|z does not read the code pair
|
||||
* the norm takes its plain form (NormQuantFP8::x_only; qkv|z probed first). */
|
||||
if (!ext_in && g.plain_norm && ar_in == kArNone) {
|
||||
RAD_ARCH_TRY(in.probe(b, nm, g, nm.f("blk.%d.ssm_inz", l), { s.in_qkv, s.in_z }));
|
||||
nq_h.x_only = in.codes_free;
|
||||
}
|
||||
if (!ext_in)
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0, 0, ar_in));
|
||||
@@ -264,6 +296,10 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", ab_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_ab)), {w.h.x}, {w.ab});
|
||||
if (ab_lane) {
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, w.h.x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, w.ab));
|
||||
}
|
||||
|
||||
/* ---- the chunked path. As in the bf16 block, except `a` and `b_gate` are views of `ab`. */
|
||||
op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
|
||||
@@ -307,8 +343,14 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)),
|
||||
{w.q, w.k, w.v, w.ab, w.in.x}, {w.o.x});
|
||||
/* The epilogue's codes for an fp8 or int8 out-projection (int8 when ActFP8::q8_fed; the codes
|
||||
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent. */
|
||||
if (op_recur && w.o.cq()) {
|
||||
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent.
|
||||
* Rotated int8 codes (ActFP8::q8_rot) only the conv fold writes (gdn_conv_recurrent_update_had);
|
||||
* rows this update serves are quantised by q_o. */
|
||||
if (g.plain_norm) {
|
||||
RAD_ARCH_TRY(out.probe(b, nm, g, nm.f("blk.%d.ssm_out", l), { s.out }));
|
||||
o_plain = out.codes_free && out.reads_x;
|
||||
}
|
||||
if (op_recur && w.o.cq() && !o_plain && !w.o.q8_rot) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
|
||||
}
|
||||
@@ -316,24 +358,32 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
|
||||
{
|
||||
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
|
||||
op_cr = rw(b, RAD_OP(b, "gdn_conv_recurrent_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width),
|
||||
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
|
||||
RAD_STR("state_form",
|
||||
g.max_spec > 0 ? "anchor" : "per_candidate")),
|
||||
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias, w_out_norm)),
|
||||
/* The fold's rotated epilogue writes one scale per (row, 128), or per 256 for an IQ8R
|
||||
* trunk's codes (ActFP8::g8; `group`, stated to that form alone: last, and cut off
|
||||
* otherwise), where this rank's value heads pair up. */
|
||||
const bool cr_wide = w.o.q8_rot && w.o.g8 == RAD_I8_GROUP_WIDE && cfg.n_head_v % 2 == 0;
|
||||
cr_codes = w.o.cq() && !o_plain && (!w.o.q8_rot || w.o.g8 == RAD_FP8_BLOCK || cr_wide);
|
||||
const RadParam cp[] = { RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width),
|
||||
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
|
||||
RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate"),
|
||||
RAD_INT("group", RAD_I8_GROUP_WIDE) };
|
||||
const rad_weight cw[] = { w_conv, w_a_log, w_dt_bias, w_out_norm };
|
||||
op_cr = rw(b, rad_decl_op(b, w.o.q8_rot && cr_codes ? "gdn_conv_recurrent_update_had"
|
||||
: "gdn_conv_recurrent_update",
|
||||
cp, (int)(sizeof cp / sizeof *cp) - (cr_wide && cr_codes ? 0 : 1),
|
||||
cw, 4),
|
||||
{w.in.x, w.ab}, {w.o.x});
|
||||
if (op_cr && w.o.cq()) {
|
||||
if (op_cr && cr_codes) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_cr, oq, 2));
|
||||
}
|
||||
if (op_cr) cr_rows = hi;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(q_o.declare(b, g, w.o, v_dim));
|
||||
if (!o_plain) RAD_ARCH_TRY(q_o.declare(b, g, w.o, v_dim));
|
||||
RAD_ARCH_TRY(out.declare(b, nm, g, nm.f("blk.%d.ssm_out", l), g.n_embd, v_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), { s.out }, w.o, w.h.x, 0, {},
|
||||
cfg.uneven() ? cfg.v_first * cfg.head_v : 0,
|
||||
@@ -389,10 +439,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* piece the chunk a span of 1 makes (the projection over its rows; the convolution, solve and
|
||||
* scan over its bounds, with the state handed on through the cache; the gated norm, quantiser
|
||||
* and out projection), so the first piece's reduction runs beside all of the second piece's
|
||||
* work. The second piece reads the history the first left in the convolution slot: a spanned
|
||||
* step is past the prompt's first interval, so its context length is never zero. */
|
||||
if (!own_ar && pieces && pieces->cu && pieces->cuts(T) && T <= 2 * pieces->rows && ext_in &&
|
||||
!op_add && S == 1 && batch->phase == RAD_PHASE_PREFILL) {
|
||||
* work. The second piece reads the history the first left in the convolution slot, so each
|
||||
* piece passes its own context length, its first row's position: the step's would tell the
|
||||
* second piece of a prompt's first chunk that it has none. */
|
||||
if (!own_ar && takes_pieces(batch, pieces)) {
|
||||
const int64_t in_w = conv_dim + v_dim;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p * pieces->rows;
|
||||
@@ -405,7 +455,7 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log),
|
||||
RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2),
|
||||
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
|
||||
praw(cv_idx, RAD_I32, 1), praw(batch->ctx_lens, RAD_I32, 1),
|
||||
praw(cv_idx, RAD_I32, 1), praw(batch->positions + r0, RAD_I32, 1),
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
brows(w.gdec, T), brows(w.beta, T));
|
||||
RAD_ISSUE_N(c, op_kkt, n,
|
||||
@@ -429,8 +479,23 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
}
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
in.step(c, w.h, w.in.x, T);
|
||||
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
|
||||
/* At decode and verify sizes the a|b projection is nearly all launch cost and reads only the
|
||||
* norm's output, as the in-projection does, so it runs beside it on lane 1 and is joined before
|
||||
* the convolution reads `ab`. A prefill chunk keeps one lane, where the two would share
|
||||
* bandwidth. Where launches chain it stays on lane 0: its chained form starts beside the
|
||||
* in-projection without the two lane joins, each of which holds a launch back until the host
|
||||
* has seen the other lane finish (Qwen3.8-27B on two cards: the projection started 55 us late
|
||||
* and the update behind it another 20 to 40 us). */
|
||||
if (ab_lane && !rad_chain_on() && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK &&
|
||||
rad_lane(c, 1) == RAD_OK) {
|
||||
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
|
||||
rad_lane(c, 0);
|
||||
in.step(c, w.h, w.in.x, T);
|
||||
rad_lane_join(c, 1, 0);
|
||||
} else {
|
||||
in.step(c, w.h, w.in.x, T);
|
||||
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
|
||||
}
|
||||
|
||||
/* Each path runs over its own run of sequences. The step is sorted decode-first: decode rows
|
||||
* are sequences [0, D) with tokens [0, DT), prefill chunks are [D, S) with the rest. A pure
|
||||
@@ -454,6 +519,21 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const int64_t PT = T - DT;
|
||||
const int64_t in_w = conv_dim + v_dim; /* w.in.x's declared row width */
|
||||
|
||||
/* The recurrent update at decode heights runs one workgroup per (sequence, head) and leaves the
|
||||
* card's memory mostly idle, so the out-projection's weight is read into the on-die cache
|
||||
* beside it: in front of the update on lane 0 where launches chain (the read's chained form
|
||||
* holds nothing behind it), else on the second lane behind a join from lane 0 (as
|
||||
* prefetch_beside). */
|
||||
if (op_pf_out && D > 0 && D <= pf_out_seqs && P == 0 && T <= pf_out_rows) {
|
||||
const rad_op pf = op_pf_out_v && T >= pf_out_v_rows ? op_pf_out_v : op_pf_out;
|
||||
if (prefetch_lane0()) {
|
||||
RAD_ISSUE(c, pf, RAD_W(out.w));
|
||||
} else {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
|
||||
RAD_ISSUE(c, pf, RAD_W(out.w));
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
}
|
||||
if (D > 0 && op_cr && qd <= cr_rows) {
|
||||
RAD_ISSUE_N(c, op_cr, qd,
|
||||
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
|
||||
@@ -463,8 +543,9 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
|
||||
w.o.cq() ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
cr_codes ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
cr_codes ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
if (w.o.cq() && !o_plain && !cr_codes) q_o.step(c, T, 0, DT);
|
||||
} else if (D > 0) {
|
||||
RAD_ISSUE_N(c, op_conv_update, qd,
|
||||
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
|
||||
@@ -478,8 +559,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
|
||||
w.o.cq() ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
/* Rotated codes come only from the fold; here the decode rows take the quantiser. */
|
||||
if (w.o.q8_rot && !o_plain) q_o.step(c, T, 0, DT);
|
||||
}
|
||||
|
||||
/* The output a piece at a time where the caller takes the all-reduce that way (ArPieces): the
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
/* rad_block_gemma4_audio.h -- Gemma 4's audio encoder (USM conformer), shared by the plugins whose
|
||||
* checkpoints carry it: EmbeddingGemma 2 (embgemma2) and Gemma 4 E2B/E4B (gemma4_bf16).
|
||||
*
|
||||
* a frame is 128 log-mel bins (the processor's), four frames an output row
|
||||
* subsampling: two 3x3 stride-2 convolutions over (time, frequency) -- 1 -> 128 -> 32 channels,
|
||||
* each input masked to the clip's real frames first, each followed by a channel LayerNorm (no
|
||||
* bias) and a ReLU -- then 32 x 32 features a row through a 1024 linear
|
||||
* 12 conformer blocks: a feed-forward at half weight, local attention (11 frames back, a
|
||||
* relative-position term, a softplus per-dimension query scale, a softcap of 50), a gated
|
||||
* depthwise causal convolution, a second half-weight feed-forward, a norm; their linears are
|
||||
* clipped: input and output clamped to bounds the checkpoint stores
|
||||
* 1024 -> 1536 with a bias, then the multimodal embedder: an RMS norm with no gain, 1536 -> the
|
||||
* text model's width.
|
||||
*
|
||||
* The blocks' clamps at +-1e10 ("gradient clipping") are omitted: they are ten orders of magnitude
|
||||
* beyond the activations' range and change nothing. One clip is one segment; a pass carries up to
|
||||
* RadBuildCtx::max_audio_frames frames. */
|
||||
#ifndef RAD_BLOCK_GEMMA4_AUDIO_H
|
||||
#define RAD_BLOCK_GEMMA4_AUDIO_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct Gemma4Audio {
|
||||
/* A clipped linear: the weight and its four bounds. */
|
||||
struct Clip {
|
||||
rad_weight w = 0, in_lo = 0, in_hi = 0, out_lo = 0, out_hi = 0;
|
||||
rad_op op_in = 0, op_mm = 0, op_out = 0;
|
||||
};
|
||||
struct FF {
|
||||
rad_weight pre = 0, post = 0;
|
||||
Clip l1, l2;
|
||||
rad_op op_pre = 0, op_act = 0, op_post = 0, op_add = 0;
|
||||
};
|
||||
struct Layer {
|
||||
FF ff1, ff2;
|
||||
rad_weight n_pre_attn = 0, n_post_attn = 0, n_out = 0, w_rel = 0, pds = 0;
|
||||
Clip q, k, v, post;
|
||||
rad_weight lc_pre = 0, lc_dw = 0, lc_norm = 0;
|
||||
Clip lc_start, lc_end;
|
||||
rad_op op_npa = 0, op_rel = 0, op_attn = 0, op_npo = 0, op_add_attn = 0;
|
||||
rad_op op_lc_pre = 0, op_glu = 0, op_dw = 0, op_lc_norm = 0, op_lc_act = 0, op_lc_add = 0;
|
||||
rad_op op_out = 0;
|
||||
};
|
||||
bool on = false;
|
||||
int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffw = 0, n_embd = 0, out_dims = 0;
|
||||
int64_t c0 = 0, c1 = 0, nmel = 0, merge = 4, left = 0, chunk = 0, n_rel = 0;
|
||||
double eps = 1e-6, softcap = 0;
|
||||
rad_weight w_c0 = 0, w_c1 = 0, w_n0 = 0, w_n1 = 0, w_in = 0, w_out = 0, b_outw = 0, w_emb = 0;
|
||||
rad_op op_c0 = 0, op_n0 = 0, op_r0 = 0, op_c1 = 0, op_n1 = 0, op_r1 = 0, op_in = 0;
|
||||
rad_op op_relpos = 0, op_outp = 0, op_en = 0, op_emb = 0;
|
||||
rad_buf b_s0 = 0, b_s1 = 0, b_x = 0, b_h = 0, b_hc = 0, b_f = 0, b_q = 0, b_k = 0, b_v = 0;
|
||||
rad_buf b_att = 0, b_o = 0, b_g = 0, b_u = 0, b_relpos = 0, b_relk = 0, b_o2 = 0, b_on = 0;
|
||||
rad_buf b_out = 0;
|
||||
std::vector<Layer> L;
|
||||
|
||||
/* A feature-extractor key: preprocessor_config.json's (`preprocessor.`), else
|
||||
* processor_config.json's `feature_extractor` object (`processor.feature_extractor.`). */
|
||||
static int64_t fe_i(const RadModelMeta* m, const char* k, int64_t d) {
|
||||
char a[96], b[128];
|
||||
std::snprintf(a, sizeof a, "preprocessor.%s", k);
|
||||
std::snprintf(b, sizeof b, "processor.feature_extractor.%s", k);
|
||||
return rad_meta_geti(m, a, rad_meta_geti(m, b, d));
|
||||
}
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_audio");
|
||||
}
|
||||
/* The longest clip in frames: 30 s at the extractor's 10 ms hop, rounded up to whole rows. */
|
||||
static int64_t frames_for(const RadModelMeta* m) {
|
||||
const int64_t rate = fe_i(m, "sampling_rate", 16000);
|
||||
const int64_t fl = fe_i(m, "frame_length", 320);
|
||||
const int64_t hop = fe_i(m, "hop_length", 160);
|
||||
if (rate <= 0 || hop <= 0) return 0;
|
||||
const int64_t n = 30 * rate;
|
||||
const int64_t real = (n + fl / 2 - fl - 1) / hop + 1;
|
||||
return (real + 3) / 4 * 4;
|
||||
}
|
||||
|
||||
/* `pre` is the checkpoint prefix of the encoder and its embedder ("model." for Gemma 4's
|
||||
* conditional-generation checkpoints, "" for EmbeddingGemma 2); `who` names the plugin in
|
||||
* refusals. The encoder's layers take weight groups from `first_group`. */
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group, const char* pre, const char* who) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
|
||||
const char* A = "audio_config";
|
||||
auto gi = [&](const char* k, int64_t d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_geti(m, key, d);
|
||||
};
|
||||
auto gf = [&](const char* k, double d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_getf(m, key, d);
|
||||
};
|
||||
H = gi("hidden_size", 0);
|
||||
heads = gi("num_attention_heads", 0);
|
||||
out_dims = gi("output_proj_dims", 0);
|
||||
chunk = gi("attention_chunk_size", 0);
|
||||
/* transformers masks a key unless 0 <= q - k < attention_context_left - 1, so the
|
||||
* furthest key back is context_left - 2 frames: 11 for this checkpoint, the query and
|
||||
* eleven before it. */
|
||||
left = gi("attention_context_left", 0) - 2;
|
||||
softcap = gf("attention_logit_cap", 0.0);
|
||||
eps = gf("rms_norm_eps", 1e-6);
|
||||
const int64_t depth = gi("num_hidden_layers", 0);
|
||||
const int64_t kconv = gi("conv_kernel_size", 0);
|
||||
const int64_t right = gi("attention_context_right", 0);
|
||||
const double resw = gf("residual_weight", 0.0);
|
||||
const char* act = rad_meta_gets(m, "audio_config.hidden_act", "");
|
||||
const char* chs = rad_meta_gets(m, "audio_config.subsampling_conv_channels", "");
|
||||
nmel = fe_i(m, "feature_size", 0);
|
||||
if (std::sscanf(chs ? chs : "", "%lld %lld", (long long*)&c0, (long long*)&c1) != 2)
|
||||
c0 = c1 = 0;
|
||||
hd = heads > 0 ? H / heads : 0;
|
||||
ffw = 4 * H;
|
||||
n_rel = left + 1;
|
||||
if (H <= 0 || heads <= 0 || hd * heads != H || out_dims <= 0 || depth <= 0 || kconv <= 0 ||
|
||||
chunk <= 0 || left < 0 || right != 0 || !(softcap > 0) || resw != 0.5 ||
|
||||
std::strcmp(act ? act : "", "silu") || c0 <= 0 || c1 <= 0 || nmel != 128 ||
|
||||
(nmel / 4) * c1 != H) {
|
||||
fprintf(stderr, "radiance: %s: the container's audio_config is not the "
|
||||
"conformer this plugin serves (hidden %lld, heads %lld, output %lld, "
|
||||
"layers %lld, conv %lld, left %lld right %lld, residual %g, act %s, "
|
||||
"subsampling %lld/%lld over %lld bins)\n", who, (long long)H,
|
||||
(long long)heads, (long long)out_dims, (long long)depth, (long long)kconv,
|
||||
(long long)left, (long long)right, resw, act ? act : "", (long long)c0,
|
||||
(long long)c1, (long long)nmel);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
P = ctx->max_audio_frames;
|
||||
if (P % merge) return RAD_E_SHAPE;
|
||||
R = P / merge;
|
||||
const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
char T[64];
|
||||
std::snprintf(T, sizeof T, "%saudio_tower", pre);
|
||||
|
||||
/* ---- weights */
|
||||
auto w = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
|
||||
};
|
||||
auto clip = [&](Clip& c, const char* dn, const char* src, int64_t out, int64_t in,
|
||||
RadWeightGroup g) {
|
||||
char d1[160], s1[200];
|
||||
std::snprintf(d1, sizeof d1, "%s.w", dn); std::snprintf(s1, sizeof s1, "%s.linear.weight", src);
|
||||
c.w = w(nm.f("%s", d1), nm.ckpt("%s", s1), {out, in}, g);
|
||||
const char* bn[4] = { "input_min", "input_max", "output_min", "output_max" };
|
||||
rad_weight* dst[4] = { &c.in_lo, &c.in_hi, &c.out_lo, &c.out_hi };
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
std::snprintf(d1, sizeof d1, "%s.%s", dn, bn[i]);
|
||||
std::snprintf(s1, sizeof s1, "%s.%s", src, bn[i]);
|
||||
*dst[i] = w(nm.f("%s", d1), nm.ckpt("%s", s1), {1}, g);
|
||||
}
|
||||
};
|
||||
w_c0 = w(nm.f("a.sscp.c0"), nm.ckpt("%s.subsample_conv_projection.layer0.conv.weight", T), {c0, 1, 3, 3}, grp_model());
|
||||
w_n0 = w(nm.f("a.sscp.n0"), nm.ckpt("%s.subsample_conv_projection.layer0.norm.weight", T), {c0}, grp_model());
|
||||
w_c1 = w(nm.f("a.sscp.c1"), nm.ckpt("%s.subsample_conv_projection.layer1.conv.weight", T), {c1, c0, 3, 3}, grp_model());
|
||||
w_n1 = w(nm.f("a.sscp.n1"), nm.ckpt("%s.subsample_conv_projection.layer1.norm.weight", T), {c1}, grp_model());
|
||||
w_in = w(nm.f("a.sscp.proj"), nm.ckpt("%s.subsample_conv_projection.input_proj_linear.weight", T), {H, H}, grp_model());
|
||||
w_out = w(nm.f("a.out.w"), nm.ckpt("%s.output_proj.weight", T), {out_dims, H}, grp_model());
|
||||
b_outw = w(nm.f("a.out.b"), nm.ckpt("%s.output_proj.bias", T), {out_dims}, grp_model());
|
||||
w_emb = w(nm.f("a.embed"), nm.ckpt("%sembed_audio.embedding_projection.weight", pre), {n_embd, out_dims}, grp_model());
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const long long li = (long long)i;
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
char d[96], s[160];
|
||||
auto D = [&](const char* x) { std::snprintf(d, sizeof d, "a.blk.%lld.%s", li, x); return nm.f("%s", d); };
|
||||
auto S = [&](const char* x) { std::snprintf(s, sizeof s, "%s.layers.%lld.%s", T, li, x); return nm.ckpt("%s", s); };
|
||||
for (int f = 0; f < 2; ++f) {
|
||||
FF& ff = f ? l.ff2 : l.ff1;
|
||||
const char* fn = f ? "feed_forward2" : "feed_forward1";
|
||||
char px[64]; std::snprintf(px, sizeof px, "%s.pre_layer_norm.weight", fn);
|
||||
ff.pre = w(D(px), S(px), {H}, g);
|
||||
std::snprintf(px, sizeof px, "%s.post_layer_norm.weight", fn);
|
||||
ff.post = w(D(px), S(px), {H}, g);
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l1", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_1", T, li, fn);
|
||||
clip(ff.l1, dn, sn, ffw, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l2", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_2", T, li, fn);
|
||||
clip(ff.l2, dn, sn, H, ffw, g);
|
||||
}
|
||||
l.n_pre_attn = w(D("norm_pre_attn"), S("norm_pre_attn.weight"), {H}, g);
|
||||
l.n_post_attn = w(D("norm_post_attn"), S("norm_post_attn.weight"), {H}, g);
|
||||
l.n_out = w(D("norm_out"), S("norm_out.weight"), {H}, g);
|
||||
l.w_rel = w(D("rel_k"), S("self_attn.relative_k_proj.weight"), {H, H}, g);
|
||||
l.pds = w(D("per_dim_scale"), S("self_attn.per_dim_scale"), {hd}, g);
|
||||
const char* qn[4] = { "q_proj", "k_proj", "v_proj", "post" };
|
||||
Clip* qc[4] = { &l.q, &l.k, &l.v, &l.post };
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.attn.%s", li, qn[j]);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.self_attn.%s", T, li, qn[j]);
|
||||
clip(*qc[j], dn, sn, H, H, g);
|
||||
}
|
||||
l.lc_pre = w(D("lconv.pre"), S("lconv1d.pre_layer_norm.weight"), {H}, g);
|
||||
l.lc_dw = w(D("lconv.dw"), S("lconv1d.depthwise_conv1d.weight"), {H, 1, kconv}, g);
|
||||
l.lc_norm = w(D("lconv.norm"), S("lconv1d.conv_norm.weight"), {H}, g);
|
||||
{
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.start", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_start", T, li);
|
||||
clip(l.lc_start, dn, sn, 2 * H, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.end", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_end", T, li);
|
||||
clip(l.lc_end, dn, sn, H, H, g);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- activations: the subsampler's planes at their own widths, the blocks' at R rows */
|
||||
b_s0 = decl_b(b, nm.f("a.s0"), RAD_BF16, {P / 2, (nmel / 2) * c0});
|
||||
b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {R, (nmel / 4) * c1});
|
||||
b_x = decl_b(b, nm.f("a.x"), RAD_BF16, {R, H});
|
||||
b_h = decl_b(b, nm.f("a.h"), RAD_BF16, {R, H});
|
||||
b_hc = decl_b(b, nm.f("a.hc"), RAD_BF16, {R, H});
|
||||
b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffw});
|
||||
b_q = decl_b(b, nm.f("a.q"), RAD_BF16, {R, H});
|
||||
b_k = decl_b(b, nm.f("a.k"), RAD_BF16, {R, H});
|
||||
b_v = decl_b(b, nm.f("a.v"), RAD_BF16, {R, H});
|
||||
b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
|
||||
b_o = decl_b(b, nm.f("a.o"), RAD_BF16, {R, H});
|
||||
b_g = decl_b(b, nm.f("a.g"), RAD_BF16, {R, 2 * H});
|
||||
b_u = decl_b(b, nm.f("a.u"), RAD_BF16, {R, H});
|
||||
b_relpos = decl_b(b, nm.f("a.relpos"), RAD_BF16, {n_rel, H});
|
||||
b_relk = decl_b(b, nm.f("a.relk"), RAD_BF16, {n_rel, H});
|
||||
b_o2 = decl_b(b, nm.f("a.o2"), RAD_BF16, {R, out_dims});
|
||||
b_on = decl_b(b, nm.f("a.on"), RAD_BF16, {R, out_dims});
|
||||
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
|
||||
|
||||
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight wt) {
|
||||
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
|
||||
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto rms = [&](int64_t rows, int64_t n, rad_weight wt, double mult) {
|
||||
if (!wt)
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("mult", mult)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto clamp = [&](int64_t rows, int64_t n, rad_weight lo, rad_weight hi) {
|
||||
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(lo, hi));
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto add = [&](int64_t rows, int64_t n) { return unary("add", rows, n); };
|
||||
auto lnorm = [&](int64_t rows, int64_t n, rad_weight g) {
|
||||
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(g));
|
||||
};
|
||||
auto conv = [&](int64_t rows, int64_t width, int64_t ci, int64_t co, int64_t cu_div,
|
||||
int64_t vstride, rad_weight wt) {
|
||||
return RAD_OP(b, "conv2d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
|
||||
RAD_INT("cin", ci), RAD_INT("cout", co),
|
||||
RAD_INT("kh", 3), RAD_INT("kw", 3),
|
||||
RAD_INT("stride", 2), RAD_INT("pad", 1),
|
||||
RAD_INT("cu_div", cu_div),
|
||||
RAD_INT("valid_stride", vstride),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
/* A clipped linear over rows of `in` into `out`: the input clamp writes a copy (the input
|
||||
* feeds several projections, each with its own bounds), the output clamp is in place. The
|
||||
* copy is a whole [R, n_in] buffer, since a GEMM's input must be contiguous. */
|
||||
auto clipped = [&](Clip& c, int64_t n_out, int64_t n_in, rad_buf in, rad_buf tmp,
|
||||
rad_buf out) {
|
||||
c.op_in = rw(b, clamp(R, n_in, c.in_lo, c.in_hi), {in}, {tmp});
|
||||
c.op_mm = rw(b, gemm(R, n_out, n_in, c.w), {tmp}, {out});
|
||||
c.op_out = rw(b, clamp(R, n_out, c.out_lo, c.out_hi), {out}, {out});
|
||||
};
|
||||
|
||||
op_c0 = rw(b, conv(P, nmel, 1, c0, 1, 1, w_c0), {}, {b_s0});
|
||||
op_n0 = rw(b, lnorm(P / 2 * (nmel / 2), c0, w_n0), {b_s0}, {b_s0});
|
||||
op_r0 = rw(b, unary("relu", P / 2 * (nmel / 2), c0), {b_s0}, {b_s0});
|
||||
op_c1 = rw(b, conv(P / 2, nmel / 2, c0, c1, 2, 2, w_c1), {b_s0}, {b_s1});
|
||||
op_n1 = rw(b, lnorm(R * (nmel / 4), c1, w_n1), {b_s1}, {b_s1});
|
||||
op_r1 = rw(b, unary("relu", R * (nmel / 4), c1), {b_s1}, {b_s1});
|
||||
op_in = rw(b, gemm(R, H, H, w_in), {b_s1}, {b_x});
|
||||
op_relpos = rw(b, RAD_OP(b, "rel_sinusoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, n_rel), RAD_INT("n", H),
|
||||
RAD_F64("max_timescale", 10000.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_relpos});
|
||||
for (Layer& l : L) {
|
||||
auto ffw_block = [&](FF& ff) {
|
||||
ff.op_pre = rw(b, rms(R, H, ff.pre, 1.0), {b_x}, {b_h});
|
||||
clipped(ff.l1, ffw, H, b_h, b_hc, b_f);
|
||||
ff.op_act = rw(b, unary("silu", R, ffw), {b_f}, {b_f});
|
||||
/* the activation's only reader is this linear, so its clamp is in place */
|
||||
clipped(ff.l2, H, ffw, b_f, b_f, b_o);
|
||||
ff.op_post = rw(b, rms(R, H, ff.post, 0.5), {b_o}, {b_o});
|
||||
ff.op_add = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
l.op_npa = rw(b, rms(R, H, l.n_pre_attn, 1.0), {b_x}, {b_h});
|
||||
clipped(l.q, H, H, b_h, b_hc, b_q);
|
||||
clipped(l.k, H, H, b_h, b_hc, b_k);
|
||||
clipped(l.v, H, H, b_h, b_hc, b_v);
|
||||
l.op_rel = rw(b, gemm(n_rel, H, H, l.w_rel), {b_relpos}, {b_relk});
|
||||
l.op_attn = rw(b, RAD_OP(b, "attn_local_rel",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head", heads), RAD_INT("left", left),
|
||||
RAD_INT("right", 0), RAD_F64("softcap", softcap),
|
||||
RAD_INT("cu_div", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.pds)),
|
||||
{b_q, b_k, b_v, b_relk}, {b_att});
|
||||
clipped(l.post, H, H, b_att, b_hc, b_o);
|
||||
l.op_npo = rw(b, rms(R, H, l.n_post_attn, 1.0), {b_o}, {b_o});
|
||||
l.op_add_attn = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
l.op_lc_pre = rw(b, rms(R, H, l.lc_pre, 1.0), {b_x}, {b_h});
|
||||
clipped(l.lc_start, 2 * H, H, b_h, b_hc, b_g);
|
||||
/* GLU: the first half times the sigmoid of the second. */
|
||||
l.op_glu = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_g}, {b_u});
|
||||
l.op_dw = rw(b, RAD_OP(b, "conv1d_dw",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_INT("k", kconv), RAD_INT("cu_div", merge),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.lc_dw)),
|
||||
{b_u}, {b_o});
|
||||
l.op_lc_norm = rw(b, rms(R, H, l.lc_norm, 1.0), {b_o}, {b_o});
|
||||
l.op_lc_act = rw(b, unary("silu", R, H), {b_o}, {b_o});
|
||||
clipped(l.lc_end, H, H, b_o, b_hc, b_u);
|
||||
l.op_lc_add = rw(b, add(R, H), {b_x, b_u}, {b_x});
|
||||
ffw_block(l.ff2);
|
||||
l.op_out = rw(b, rms(R, H, l.n_out, 1.0), {b_x}, {b_x});
|
||||
}
|
||||
op_outp = rw(b, RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", out_dims),
|
||||
RAD_INT("K", H), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(w_out, b_outw)),
|
||||
{b_x}, {b_o2});
|
||||
op_en = rw(b, rms(R, out_dims, 0, 1.0), {b_o2}, {b_on});
|
||||
op_emb = rw(b, gemm(R, n_embd, out_dims, w_emb), {b_on}, {b_out});
|
||||
|
||||
RadEncoderDecl e{};
|
||||
e.name = "audio";
|
||||
e.modalities = RAD_MM_AUDIO;
|
||||
e.patch_dim = nmel;
|
||||
e.merge = merge;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "audio encoder: %lld conformer blocks of %lld (%lld heads x %lld), "
|
||||
"subsampling %lld/%lld channels, local attention %lld back; %lld frames a "
|
||||
"pass -> %lld rows of %lld", (long long)depth, (long long)H, (long long)heads,
|
||||
(long long)hd, (long long)c0, (long long)c1, (long long)left, (long long)P,
|
||||
(long long)R, (long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % merge || S <= 0) {
|
||||
rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none "
|
||||
"declared, more frames than it was declared for, or not whole rows");
|
||||
return;
|
||||
}
|
||||
const int64_t Rn = Pn / merge;
|
||||
const int32_t* crd = batch->enc_coord;
|
||||
const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
|
||||
const RadOperand valid = praw(crd + Pn, RAD_I32, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
auto clipped = [&](const Clip& cl, rad_buf in, int64_t n_in, rad_buf tmp, rad_buf out,
|
||||
int64_t n_out) {
|
||||
RAD_ISSUE_N(c, cl.op_in, Rn, bcol(in, 0, n_in, Rn), RAD_W(cl.in_lo), RAD_W(cl.in_hi),
|
||||
bcol(tmp, 0, n_in, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_mm, Rn, bcol(tmp, 0, n_in, Rn), RAD_W(cl.w), bcol(out, 0, n_out, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_out, Rn, bcol(out, 0, n_out, Rn), RAD_W(cl.out_lo), RAD_W(cl.out_hi),
|
||||
bcol(out, 0, n_out, Rn));
|
||||
};
|
||||
|
||||
RAD_ISSUE_N(c, op_c0, Pn, frames, RAD_W(w_c0), cu, valid, brows(b_s0, Pn / 2), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_n0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), RAD_W(w_n0), RAD_NONE,
|
||||
brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_r0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_c1, Pn / 2, brows(b_s0, Pn / 2), RAD_W(w_c1), cu, valid, brows(b_s1, Rn),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_n1, Rn * (nmel / 4), brows(b_s1, Rn), RAD_W(w_n1), RAD_NONE,
|
||||
brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_r1, Rn * (nmel / 4), brows(b_s1, Rn), brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_in, Rn, brows(b_s1, Rn), RAD_W(w_in), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, op_relpos, n_rel, brows(b_relpos, n_rel));
|
||||
for (const Layer& l : L) {
|
||||
auto ffw_block = [&](const FF& ff) {
|
||||
RAD_ISSUE_N(c, ff.op_pre, Rn, brows(b_x, Rn), RAD_W(ff.pre), brows(b_h, Rn));
|
||||
clipped(ff.l1, b_h, H, b_hc, b_f, ffw);
|
||||
RAD_ISSUE_N(c, ff.op_act, Rn, brows(b_f, Rn), brows(b_f, Rn));
|
||||
clipped(ff.l2, b_f, ffw, b_f, b_o, H);
|
||||
RAD_ISSUE_N(c, ff.op_post, Rn, brows(b_o, Rn), RAD_W(ff.post), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, ff.op_add, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
RAD_ISSUE_N(c, l.op_npa, Rn, brows(b_x, Rn), RAD_W(l.n_pre_attn), brows(b_h, Rn));
|
||||
clipped(l.q, b_h, H, b_hc, b_q, H);
|
||||
clipped(l.k, b_h, H, b_hc, b_k, H);
|
||||
clipped(l.v, b_h, H, b_hc, b_v, H);
|
||||
RAD_ISSUE_N(c, l.op_rel, n_rel, brows(b_relpos, n_rel), RAD_W(l.w_rel),
|
||||
brows(b_relk, n_rel));
|
||||
RAD_ISSUE_N(c, l.op_attn, Rn, brows(b_q, Rn), brows(b_k, Rn), brows(b_v, Rn),
|
||||
brows(b_relk, n_rel), RAD_W(l.pds), cu, brows(b_att, Rn));
|
||||
clipped(l.post, b_att, H, b_hc, b_o, H);
|
||||
RAD_ISSUE_N(c, l.op_npo, Rn, brows(b_o, Rn), RAD_W(l.n_post_attn), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_add_attn, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_pre, Rn, brows(b_x, Rn), RAD_W(l.lc_pre), brows(b_h, Rn));
|
||||
clipped(l.lc_start, b_h, H, b_hc, b_g, 2 * H);
|
||||
RAD_ISSUE_N(c, l.op_glu, Rn, bcol(b_g, H, H, Rn), bcol(b_g, 0, H, Rn), brows(b_u, Rn));
|
||||
RAD_ISSUE_N(c, l.op_dw, Rn, brows(b_u, Rn), RAD_W(l.lc_dw), cu, brows(b_o, Rn),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, l.op_lc_norm, Rn, brows(b_o, Rn), RAD_W(l.lc_norm), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_act, Rn, brows(b_o, Rn), brows(b_o, Rn));
|
||||
clipped(l.lc_end, b_o, H, b_hc, b_u, H);
|
||||
RAD_ISSUE_N(c, l.op_lc_add, Rn, brows(b_x, Rn), brows(b_u, Rn), brows(b_x, Rn));
|
||||
ffw_block(l.ff2);
|
||||
RAD_ISSUE_N(c, l.op_out, Rn, brows(b_x, Rn), RAD_W(l.n_out), brows(b_x, Rn));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_outp, Rn, brows(b_x, Rn), RAD_W(w_out), RAD_W(b_outw), RAD_NONE,
|
||||
brows(b_o2, Rn));
|
||||
RAD_ISSUE_N(c, op_en, Rn, brows(b_o2, Rn), RAD_NONE, brows(b_on, Rn));
|
||||
RAD_ISSUE_N(c, op_emb, Rn, brows(b_on, Rn), RAD_W(w_emb), brows(b_out, Rn));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,263 @@
|
||||
/* rad_block_gemma4_unified.h -- the media embedders of Gemma 4 12B ("unified", transformers'
|
||||
* Gemma4UnifiedVisionEmbedder and the audio Gemma4UnifiedMultimodalEmbedder), served by gemma4_bf16.
|
||||
* Neither has an encoder: the language model sees each patch or audio frame after a few norms and
|
||||
* linears.
|
||||
*
|
||||
* image: a patch is 48 x 48 x 3 (3 x 3 of the processor's 16-pixel patches), staged by the core's
|
||||
* Gemma 4 processor as u / 255 in bf16, (y, x, channel); a LayerNorm over the patch, a linear with
|
||||
* a bias, a LayerNorm, plus a learned row for the patch's column and one for its row (the
|
||||
* checkpoint's [npos, 2, width] table, read as its two taps of dimension 1), a LayerNorm, then the
|
||||
* multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. The LayerNorms are
|
||||
* nn.LayerNorm's default eps 1e-5, which no config states. One patch is one row.
|
||||
* audio: a frame is 640 samples at 16 kHz as they are, the last zero-padded, in bf16; an RMS norm
|
||||
* with no gain and a 640 -> n_embd linear. One frame is one row.
|
||||
*
|
||||
* Their rows replace the placeholders' embeddings unscaled, as the vision tower's do. Every rank
|
||||
* runs them whole (RAD_SHARD_NONE). */
|
||||
#ifndef RAD_BLOCK_GEMMA4_UNIFIED_H
|
||||
#define RAD_BLOCK_GEMMA4_UNIFIED_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct Gemma4UnifiedVision {
|
||||
bool on = false;
|
||||
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
|
||||
* plugin sets it before declare. */
|
||||
bool bidirectional = false;
|
||||
int64_t P = 0, width = 0, patch_dim = 0, npos = 0, n_embd = 0;
|
||||
rad_weight w_ln1 = 0, w_ln1b = 0, w_in = 0, w_inb = 0, w_ln2 = 0, w_ln2b = 0, w_px = 0, w_py = 0;
|
||||
rad_weight w_pn = 0, w_pnb = 0, w_proj = 0;
|
||||
rad_op op_ln1 = 0, op_in = 0, op_ln2 = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0;
|
||||
rad_op op_pn = 0, op_norm = 0, op_out = 0;
|
||||
rad_buf b_n = 0, b_x = 0, b_h = 0, b_px = 0, b_py = 0, b_out = 0;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_unified_vision");
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, const char* who) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
width = rad_meta_geti(m, "vision_config.mm_embed_dim", 0);
|
||||
npos = rad_meta_geti(m, "vision_config.mm_posemb_size", 0);
|
||||
const int64_t side = rad_meta_geti(m, "vision_config.model_patch_size", 0);
|
||||
const int64_t outd = rad_meta_geti(m, "vision_config.output_proj_dims", width);
|
||||
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
|
||||
if (width <= 0 || npos <= 0 || side <= 0 || outd != width) {
|
||||
fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
|
||||
"embedder this plugin serves (mm_embed_dim %lld, mm_posemb_size %lld, "
|
||||
"model_patch_size %lld, output_proj_dims %lld)\n", who,
|
||||
(long long)width, (long long)npos, (long long)side, (long long)outd);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
patch_dim = 3 * side * side;
|
||||
P = ctx->max_enc_patches;
|
||||
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
const char* V = "model.vision_embedder";
|
||||
struct { const char* to; const char* from; } cp[] = {
|
||||
{ "v.ln1.weight", "patch_ln1.weight" }, { "v.ln1.bias", "patch_ln1.bias" },
|
||||
{ "v.in.weight", "patch_dense.weight" }, { "v.in.bias", "patch_dense.bias" },
|
||||
{ "v.ln2.weight", "patch_ln2.weight" }, { "v.ln2.bias", "patch_ln2.bias" },
|
||||
{ "v.pn.weight", "pos_norm.weight" }, { "v.pn.bias", "pos_norm.bias" } };
|
||||
for (const auto& e : cp)
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("%s", e.to), nm.ckpt("%s.%s", V, e.from)));
|
||||
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_x.weight"), nm.ckpt("%s.pos_embedding", V), 1, 0));
|
||||
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_y.weight"), nm.ckpt("%s.pos_embedding", V), 1, 1));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight")));
|
||||
w_ln1 = decl_w(b, nm.f("v.ln1.weight"), RAD_BF16, {patch_dim}, A, N, grp_model());
|
||||
w_ln1b = decl_w(b, nm.f("v.ln1.bias"), RAD_BF16, {patch_dim}, A, N, grp_model());
|
||||
w_in = decl_w(b, nm.f("v.in.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
|
||||
w_inb = decl_w(b, nm.f("v.in.bias"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_ln2 = decl_w(b, nm.f("v.ln2.weight"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_ln2b = decl_w(b, nm.f("v.ln2.bias"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
|
||||
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
|
||||
w_pn = decl_w(b, nm.f("v.pn.weight"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_pnb = decl_w(b, nm.f("v.pn.bias"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
|
||||
|
||||
b_n = decl_b(b, nm.f("v.n"), RAD_BF16, {P, patch_dim});
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
|
||||
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width});
|
||||
b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
|
||||
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {P, n_embd});
|
||||
|
||||
auto ln = [&](int64_t n, rad_weight w, rad_weight bias) {
|
||||
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
|
||||
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto lookup = [&](rad_weight w) {
|
||||
return RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
|
||||
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto add = [&]() {
|
||||
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
op_ln1 = rw(b, ln(patch_dim, w_ln1, w_ln1b), {}, {b_n});
|
||||
op_in = rw(b, RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
|
||||
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(w_in, w_inb)),
|
||||
{b_n}, {b_x});
|
||||
op_ln2 = rw(b, ln(width, w_ln2, w_ln2b), {b_x}, {b_h});
|
||||
op_px = rw(b, lookup(w_px), {}, {b_px});
|
||||
op_py = rw(b, lookup(w_py), {}, {b_py});
|
||||
op_padd = rw(b, add(), {b_px, b_py}, {b_px});
|
||||
op_add = rw(b, add(), {b_h, b_px}, {b_h});
|
||||
op_pn = rw(b, ln(width, w_pn, w_pnb), {b_h}, {b_x});
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_x}, {b_h});
|
||||
op_out = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
|
||||
RAD_INT("K", width), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_proj)),
|
||||
{b_h}, {b_out});
|
||||
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = 1;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
e.bidirectional = bidirectional ? 1 : 0;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision embedder (no tower): %lldx%lld patches of %lld values -> %lld, "
|
||||
"positions %lld a side; %lld patches a pass -> %lld rows of %lld",
|
||||
(long long)side, (long long)side, (long long)patch_dim, (long long)width,
|
||||
(long long)npos, (long long)P, (long long)P, (long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch;
|
||||
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
|
||||
rad_step_fail(c, "an encoder pass this program's vision embedder cannot serve: none "
|
||||
"declared, or more patches than it was declared for");
|
||||
return;
|
||||
}
|
||||
const int32_t* crd = batch->enc_coord;
|
||||
RAD_ISSUE_N(c, op_ln1, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim), RAD_W(w_ln1),
|
||||
RAD_W(w_ln1b), brows(b_n, Pn));
|
||||
RAD_ISSUE_N(c, op_in, Pn, brows(b_n, Pn), RAD_W(w_in), RAD_W(w_inb), RAD_NONE, brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_ln2, Pn, brows(b_x, Pn), RAD_W(w_ln2), RAD_W(w_ln2b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
|
||||
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_add, Pn, brows(b_h, Pn), brows(b_px, Pn), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, op_pn, Pn, brows(b_h, Pn), RAD_W(w_pn), RAD_W(w_pnb), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_norm, Pn, brows(b_x, Pn), RAD_NONE, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, op_out, Pn, brows(b_h, Pn), RAD_W(w_proj), brows(b_out, Pn));
|
||||
}
|
||||
};
|
||||
|
||||
struct Gemma4UnifiedAudio {
|
||||
bool on = false;
|
||||
int64_t P = 0, frame = 0, n_embd = 0;
|
||||
rad_weight w_proj = 0;
|
||||
rad_op op_norm = 0, op_out = 0;
|
||||
rad_buf b_n = 0, b_out = 0;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_unified_audio");
|
||||
}
|
||||
/* Samples a frame: the extractor's audio_samples_per_token, else the embedder's input width. */
|
||||
static int64_t frame_for(const RadModelMeta* m) {
|
||||
return rad_meta_geti(m, "processor.feature_extractor.audio_samples_per_token",
|
||||
rad_meta_geti(m, "audio_config.audio_embed_dim", 0));
|
||||
}
|
||||
/* The longest clip in frames: processor_config.json's audio_seq_length, else 30 s. */
|
||||
static int64_t frames_for(const RadModelMeta* m) {
|
||||
const int64_t f = frame_for(m);
|
||||
const int64_t rate = rad_meta_geti(m, "processor.feature_extractor.sampling_rate", 16000);
|
||||
if (f <= 0 || rate <= 0) return 0;
|
||||
return rad_meta_geti(m, "processor.audio_seq_length", (30 * rate + f - 1) / f);
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, const char* who) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
|
||||
frame = frame_for(m);
|
||||
const int64_t width = rad_meta_geti(m, "audio_config.audio_embed_dim", 0);
|
||||
const double eps = rad_meta_getf(m, "audio_config.rms_norm_eps", 1e-6);
|
||||
if (frame <= 0 || width != frame) {
|
||||
fprintf(stderr, "radiance: %s: the container's audio frame (%lld samples) is not the "
|
||||
"embedder's input (audio_embed_dim %lld)\n", who, (long long)frame,
|
||||
(long long)width);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
P = ctx->max_audio_frames;
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("a.embed.weight"), nm.ckpt("model.embed_audio.embedding_projection.weight")));
|
||||
w_proj = decl_w(b, nm.f("a.embed.weight"), RAD_BF16, {n_embd, frame}, RAD_ACCESS_PER_REQUEST,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
b_n = decl_b(b, nm.f("a.n"), RAD_BF16, {P, frame});
|
||||
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {P, n_embd});
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", frame),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_n});
|
||||
op_out = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
|
||||
RAD_INT("K", frame), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_proj)),
|
||||
{b_n}, {b_out});
|
||||
RadEncoderDecl e{};
|
||||
e.name = "audio";
|
||||
e.modalities = RAD_MM_AUDIO;
|
||||
e.patch_dim = frame;
|
||||
e.merge = 1;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "audio embedder (no encoder): frames of %lld samples -> %lld; %lld frames a pass",
|
||||
(long long)frame, (long long)n_embd, (long long)P);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch;
|
||||
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
|
||||
rad_step_fail(c, "an audio pass this program's audio embedder cannot serve: none "
|
||||
"declared, or more frames than it was declared for");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_norm, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, frame), RAD_NONE,
|
||||
brows(b_n, Pn));
|
||||
RAD_ISSUE_N(c, op_out, Pn, brows(b_n, Pn), RAD_W(w_proj), brows(b_out, Pn));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_GEMMA4_UNIFIED_H */
|
||||
@@ -19,6 +19,15 @@
|
||||
* replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the
|
||||
* image rows are not scaled).
|
||||
*
|
||||
* Clipped linears (vision_config.use_clipped_linears, Gemma 4 E2B/E4B): every projection clamps its
|
||||
* input and its output to bounds the checkpoint stores (`<proj>.input_min/max`, `output_min/max`;
|
||||
* transformers' Gemma4ClippableLinear). The tower keeps its fused q|k|v and gate|up GEMMs, so it
|
||||
* takes the input bounds of q_proj (and of gate_proj) for the fused input, q_proj's output bounds for
|
||||
* q's columns, k_proj's for k's and v's, and gate_proj's output bounds for gate|up. That is exact
|
||||
* where the fused parts share their bounds, as NVIDIA's E4B does in all 16 layers (k and v share the
|
||||
* input bounds of q and their output bounds, up shares gate's). The bound weights are one bf16
|
||||
* element each, read by `clamp`.
|
||||
*
|
||||
* One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
|
||||
* image, or one frame of a video). Every rank runs the whole tower (engine_mm.cpp), so its weights
|
||||
* are replicated (RAD_SHARD_NONE) and each rank writes the rows into its own copy of the embedding
|
||||
@@ -41,8 +50,15 @@ struct Gemma4Vision {
|
||||
rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
|
||||
rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
|
||||
rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
|
||||
/* clipped linears: the bounds (lo, hi) of the nine clamps, and the clamps */
|
||||
enum { C_QKV_IN, C_Q_OUT, C_KV_OUT, C_O_IN, C_O_OUT, C_GU_IN, C_GU_OUT, C_DN_IN, C_DN_OUT, C_N };
|
||||
rad_weight lo[C_N] = {}, hi[C_N] = {};
|
||||
rad_op op_c[C_N] = {};
|
||||
};
|
||||
bool on = false, standardize = false;
|
||||
bool on = false, standardize = false, clip = false;
|
||||
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
|
||||
* plugin sets it before declare. */
|
||||
bool bidirectional = false;
|
||||
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
|
||||
int64_t npos = 0, n_embd = 0;
|
||||
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
|
||||
@@ -88,15 +104,14 @@ struct Gemma4Vision {
|
||||
(long long)pool, (long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Clipped linears (their bounds are buffers the vision checkpoint states as infinite) and
|
||||
* any rotary or activation other than the 2-D one and gelu-tanh are refused by name. */
|
||||
if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
|
||||
(std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
|
||||
/* Any rotary or activation other than the 2-D one and gelu-tanh is refused by name. */
|
||||
if ((std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
|
||||
std::strcmp(act, "gelu_pytorch_tanh")) {
|
||||
fprintf(stderr, "radiance: %s: this vision tower uses clipped linears, a '%s' rotary or "
|
||||
"a '%s' activation, which it does not serve\n", who, rt, act);
|
||||
fprintf(stderr, "radiance: %s: this vision tower uses a '%s' rotary or a '%s' "
|
||||
"activation, which it does not serve\n", who, rt, act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
clip = rad_meta_geti(m, "vision_config.use_clipped_linears", 0) != 0;
|
||||
n_embd = model_embd;
|
||||
patch_dim = 3 * patch * patch;
|
||||
const int64_t kk = pool * pool;
|
||||
@@ -154,6 +169,27 @@ struct Gemma4Vision {
|
||||
l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g);
|
||||
l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g);
|
||||
l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g);
|
||||
if (clip) {
|
||||
/* clamp k -> the checkpoint projection whose bound it takes, and which bound */
|
||||
static const char* const proj[Layer::C_N] = {
|
||||
"self_attn.q_proj", "self_attn.q_proj", "self_attn.k_proj", "self_attn.o_proj",
|
||||
"self_attn.o_proj", "mlp.gate_proj", "mlp.gate_proj", "mlp.down_proj",
|
||||
"mlp.down_proj" };
|
||||
static const bool in_side[Layer::C_N] = { true, false, false, true, false, true,
|
||||
false, true, false };
|
||||
for (int k = 0; k < Layer::C_N; ++k) {
|
||||
const char* side = in_side[k] ? "input" : "output";
|
||||
const char* lo_n = nm.f("v.blk.%lld.clip%d.lo", li, k);
|
||||
const char* hi_n = nm.f("v.blk.%lld.clip%d.hi", li, k);
|
||||
RAD_ARCH_TRY(map_copy(b, lo_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_min", V, li,
|
||||
proj[k], side)));
|
||||
RAD_ARCH_TRY(map_copy(b, hi_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_max", V, li,
|
||||
proj[k], side)));
|
||||
l.lo[k] = decl_w(b, lo_n, RAD_BF16, {1}, A, N, g);
|
||||
l.hi[k] = decl_w(b, hi_n, RAD_BF16, {1}, A, N, g);
|
||||
if (!l.lo[k] || !l.hi[k]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
|
||||
@@ -198,6 +234,11 @@ struct Gemma4Vision {
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto clamp = [&](int64_t n, rad_weight lo, rad_weight hi) {
|
||||
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(lo, hi));
|
||||
};
|
||||
auto gain = [&](rad_weight w) {
|
||||
return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)),
|
||||
@@ -212,6 +253,19 @@ struct Gemma4Vision {
|
||||
char sec[48];
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
|
||||
for (Layer& l : L) {
|
||||
/* the clamps, each in place on the one buffer its linear reads or writes (each of those
|
||||
* is read by that linear alone, or by what follows it) */
|
||||
if (clip) {
|
||||
using C = Layer;
|
||||
const struct { int k; int64_t n; rad_buf buf; } cl[C::C_N] = {
|
||||
{ C::C_QKV_IN, width, b_h }, { C::C_Q_OUT, width, b_qkv },
|
||||
{ C::C_KV_OUT, 2 * width, b_qkv }, { C::C_O_IN, width, b_att },
|
||||
{ C::C_O_OUT, width, b_o }, { C::C_GU_IN, width, b_h },
|
||||
{ C::C_GU_OUT, 2 * ff, b_gu }, { C::C_DN_IN, ff, b_ff },
|
||||
{ C::C_DN_OUT, width, b_o } };
|
||||
for (const auto& e : cl)
|
||||
l.op_c[e.k] = rw(b, clamp(e.n, l.lo[e.k], l.hi[e.k]), {e.buf}, {e.buf});
|
||||
}
|
||||
l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
|
||||
l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
|
||||
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
|
||||
@@ -270,12 +324,14 @@ struct Gemma4Vision {
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
e.bidirectional = bidirectional ? 1 : 0;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
|
||||
"pooled %lldx%lld%s; %lld patches a pass -> %lld rows of %lld",
|
||||
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
|
||||
(long long)patch, (long long)pool, (long long)pool,
|
||||
standardize ? ", standardised" : "", (long long)P, (long long)R,
|
||||
standardize ? ", standardised" : "", clip ? ", clipped linears" : "",
|
||||
(long long)P, (long long)R,
|
||||
(long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
@@ -299,20 +355,33 @@ struct Gemma4Vision {
|
||||
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
|
||||
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
|
||||
/* a clamp of operand `x` in place, when the tower clips */
|
||||
auto cl = [&](const Layer& l, int k, RadOperand x) {
|
||||
if (clip) RAD_ISSUE_N(c, l.op_c[k], Pn, x, RAD_W(l.lo[k]), RAD_W(l.hi[k]), x);
|
||||
};
|
||||
for (const Layer& l : L) {
|
||||
RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
|
||||
cl(l, Layer::C_QKV_IN, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
|
||||
cl(l, Layer::C_Q_OUT, bcol(b_qkv, 0, width, Pn));
|
||||
cl(l, Layer::C_KV_OUT, bcol(b_qkv, width, 2 * width, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
|
||||
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
|
||||
cl(l, Layer::C_O_IN, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
|
||||
cl(l, Layer::C_O_OUT, brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
|
||||
cl(l, Layer::C_GU_IN, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
|
||||
cl(l, Layer::C_GU_OUT, brows(b_gu, Pn));
|
||||
RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
|
||||
brows(b_ff, Pn));
|
||||
cl(l, Layer::C_DN_IN, brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
|
||||
cl(l, Layer::C_DN_OUT, brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
}
|
||||
|
||||
@@ -27,6 +27,9 @@ struct DsaCache {
|
||||
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
|
||||
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
|
||||
rad_buf score = 0, selected = 0, nsel = 0, length = 0;
|
||||
/* A taking-all step's zero scores, [max_tok, topk + 1]: such a step does not split, and
|
||||
* the score plane holds only a run of rows when the step may. */
|
||||
rad_buf unscored = 0;
|
||||
/* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */
|
||||
rad_buf cu_part = 0, sel_part = 0, len_part = 0;
|
||||
};
|
||||
@@ -44,6 +47,7 @@ struct DsaCache {
|
||||
rad_kvgroup index = 0, tail = 0, attention = 0;
|
||||
rad_weight ape = 0;
|
||||
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
|
||||
rad_op op_unscored = 0, op_select_all = 0;
|
||||
rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
|
||||
@@ -90,6 +94,9 @@ struct DsaCache {
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = 17;
|
||||
*index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d);
|
||||
/* dsa_score reads this group over the whole history every step, so it stays resident and
|
||||
* holds every sequence's context while a sibling streams (kvstream/carve.cpp). */
|
||||
RAD_ARCH_TRY(rad_kv_group_dense_read(b, *index_group));
|
||||
}
|
||||
index = *index_group;
|
||||
if (!index) return RAD_E_INVAL;
|
||||
@@ -109,6 +116,15 @@ struct DsaCache {
|
||||
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.kg }, {});
|
||||
/* A step whose every row reaches topk or fewer blocks selects them all (takes_all), and
|
||||
* qsa_select takes any finite scores in block order then: zeros serve as well as the
|
||||
* scorer's. The fill spans topk + 1 columns, at least the live reach of such a step. */
|
||||
op_unscored = rw(b,
|
||||
RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("n", unscored_cols()), RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { w.unscored });
|
||||
op_score = rw(b,
|
||||
RAD_OP(b, "dsa_score",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
|
||||
@@ -136,6 +152,14 @@ struct DsaCache {
|
||||
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.score, w.nc }, { w.selected, w.nsel, w.length });
|
||||
op_select_all = rw(b,
|
||||
RAD_OP(b, "qsa_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("blocks", unscored_cols()),
|
||||
RAD_INT("topk", 512), RAD_INT("ratio", 4),
|
||||
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.unscored, w.nc }, { w.selected, w.nsel, w.length });
|
||||
if (split) {
|
||||
op_select_part = rw(
|
||||
b,
|
||||
@@ -162,8 +186,12 @@ struct DsaCache {
|
||||
if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL;
|
||||
return op_query && op_work && op_tail && op_unscored && op_score && op_select &&
|
||||
op_select_all
|
||||
? RAD_OK
|
||||
: RAD_E_INVAL;
|
||||
}
|
||||
int64_t unscored_cols() const { return c.topk + 1 < c.blocks ? c.topk + 1 : c.blocks; }
|
||||
/* The columns a step scores: the live reach the batch bounds on the host. */
|
||||
int64_t live_blocks(const RadBatch* batch) const {
|
||||
const auto* ib = kv_batch(batch, index);
|
||||
@@ -176,13 +204,19 @@ struct DsaCache {
|
||||
}
|
||||
/* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by
|
||||
* the core), so every rank takes the same path and a recorded decode pass changes it only when
|
||||
* that bound moves. */
|
||||
* that bound moves. A step that takes all its blocks never splits: with nothing to score, every
|
||||
* rank selects the whole step itself, and the gathers have nothing to save. */
|
||||
bool splits(const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
return op_score_part && (GlmTp::splits(T, g.world) ||
|
||||
(T >= GlmTp::kSplitWorkRows &&
|
||||
T * live_blocks(batch) >= GlmTp::kSplitWork));
|
||||
return op_score_part && live_blocks(batch) > c.topk &&
|
||||
(GlmTp::splits(T, g.world) ||
|
||||
(T >= GlmTp::kSplitWorkRows && T * live_blocks(batch) >= GlmTp::kSplitWork));
|
||||
}
|
||||
/* Every row's history fits the selection, so the query side (projection, head gates,
|
||||
* quantiser, scorer) has nothing to decide: the selected table is every live block in order,
|
||||
* bit for bit what scoring would select. Read from the same host bound as splits(), so every
|
||||
* rank agrees. */
|
||||
bool takes_all(const RadBatch* batch) const { return live_blocks(batch) <= c.topk; }
|
||||
/* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of).
|
||||
* A rank whose run lies wholly past a small step runs the step's first R rows instead: no
|
||||
* sequence holds its run, so its scores are -inf, and its answers land past T. The caller's
|
||||
@@ -207,11 +241,13 @@ struct DsaCache {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t work = (T + 3) / 4 + S,
|
||||
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
|
||||
const bool all = takes_all(batch);
|
||||
int64_t q0 = 0, qn = T;
|
||||
query_rows(batch, &q0, &qn);
|
||||
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.codes, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.scales, q0 * 32, qn * 32, 1));
|
||||
if (!all)
|
||||
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.codes, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.scales, q0 * 32, qn * 32, 1));
|
||||
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
|
||||
praw2(tb->state_index, RAD_I32, S, pitch),
|
||||
@@ -229,6 +265,16 @@ struct DsaCache {
|
||||
step_split(ctx, batch, live);
|
||||
return;
|
||||
}
|
||||
if (all) {
|
||||
const int64_t U = unscored_cols();
|
||||
RAD_ISSUE_N(ctx, op_unscored, T, brows(w.unscored, T));
|
||||
RAD_ISSUE_N(ctx, op_select_all, T, bcol_at(w.unscored, 0, U, 0, live, T),
|
||||
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch),
|
||||
brows(w.nc, S), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.selected, T),
|
||||
brows(w.nsel, T), brows(w.length, T));
|
||||
return;
|
||||
}
|
||||
// dsa_score declares ten operands, cu_part the optional tenth; the engine counts them.
|
||||
RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32),
|
||||
brows(w.gate, T), kv_cache(index, layer), RAD_NONE,
|
||||
@@ -345,23 +391,29 @@ struct GlmIndexer {
|
||||
};
|
||||
int64_t r0 = 0, rows = T;
|
||||
cache.query_rows(batch, &r0, &rows);
|
||||
/* The key side runs on every step, since the index cache must stay current; the query
|
||||
* side only where the selection is a choice (DsaCache::takes_all). */
|
||||
const bool all = cache.takes_all(batch);
|
||||
/* Every output row of these ops is independent of the others and of how many there are,
|
||||
* except the bf16 projection's at 64 rows and under, a band whose split count a tuned
|
||||
* configuration may set: it stays on the step's rows unless every run is wider. */
|
||||
const bool runs = cache.splits(batch);
|
||||
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
|
||||
else
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T);
|
||||
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
|
||||
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
|
||||
if (!all) {
|
||||
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
|
||||
else
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T);
|
||||
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
|
||||
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
|
||||
}
|
||||
key_gate.step(ctx, act(w.input), w.kg_raw, T);
|
||||
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
|
||||
bcol(w.cache.kg, 0, 128, T));
|
||||
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
|
||||
bcol(w.cache.kg, 128, 128, T));
|
||||
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096), RAD_W(head_weight),
|
||||
brow_slice(w.cache.gate, r0, rows, 32));
|
||||
if (!all)
|
||||
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096),
|
||||
RAD_W(head_weight), brow_slice(w.cache.gate, r0, rows, 32));
|
||||
cache.step(ctx, batch);
|
||||
}
|
||||
};
|
||||
|
||||
+202
-24
@@ -3,14 +3,24 @@
|
||||
* complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent
|
||||
* for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual.
|
||||
*
|
||||
* Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and
|
||||
* kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are
|
||||
* replicated. */
|
||||
* Under tensor parallelism the head form splits the 64 heads over the ranks (GlmTp::heads): the
|
||||
* rows of q_b and kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent
|
||||
* cache are replicated. From GlmTp::kSplitRows a prefill-sized step takes the row form instead
|
||||
* (Wire::rows, Form::rows): each rank runs its run of the step's rows (GlmTp::run_of) through q_b,
|
||||
* absorption, attention, expansion and the output projection with all 64 heads, then an
|
||||
* all_gather lays the runs out as the whole step. The latent cache and the selection are whole on
|
||||
* every rank already, so the split needs no other exchange. The gather moves half the bytes of
|
||||
* the head form's all-reduce, and the attention loads each key once for all 64 heads of a row.
|
||||
* The price is the three projections at full width on every rank (126 MB a layer); RowsWire::q
|
||||
* unset declares neither them nor the form. */
|
||||
#ifndef RAD_BLOCK_GLM_MLA_H
|
||||
#define RAD_BLOCK_GLM_MLA_H
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_glm_tp.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -18,8 +28,30 @@ struct MlaLatent {
|
||||
struct Config {
|
||||
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
|
||||
};
|
||||
/* The attention over the latent cache, `rows` rows of `heads` heads. The cache is Geom::kv_dtype
|
||||
* (bf16, or fp8_e4m3 under --kv-cache-dtype fp8); `kv_dtype` is stated only for a cache that is
|
||||
* not bf16, so a bf16 build declares the op it always did. */
|
||||
static rad_op attn_op(RadBuilder* b, const Geom& g, int64_t rows, int64_t heads,
|
||||
int64_t blocks, double scale) {
|
||||
if (g.kv_dtype && std::strcmp(g.kv_dtype, "bf16"))
|
||||
return RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", scale),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", scale),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
}
|
||||
struct Wire {
|
||||
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
|
||||
/* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`.
|
||||
* Never `length`, which is a token count. */
|
||||
rad_buf nsel = 0;
|
||||
};
|
||||
Geom g{};
|
||||
Config c{};
|
||||
@@ -56,16 +88,10 @@ struct MlaLatent {
|
||||
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(projection)),
|
||||
{ w.q }, { w.q_latent });
|
||||
op_attn =
|
||||
rw(b,
|
||||
RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim),
|
||||
RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks),
|
||||
RAD_INT("block_size", 4),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
|
||||
op_attn = rw(b,
|
||||
attn_op(b, g, g.max_tok, c.heads, c.blocks,
|
||||
1.0 / std::sqrt((double)c.head_dim)),
|
||||
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
|
||||
if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL;
|
||||
op_expand = rw(
|
||||
b,
|
||||
@@ -88,11 +114,28 @@ struct MlaLatent {
|
||||
};
|
||||
|
||||
struct GlmMla {
|
||||
/* How a prefill-sized step under tensor parallelism runs: `heads` keeps the head form at every
|
||||
* step size and spares the full-width weights' VRAM; `rows` is the row form. The plugin
|
||||
* chooses (RadBuildCtx::tp_attn_rows); the block takes the choice through whether it is given
|
||||
* RowsWire buffers. */
|
||||
enum class Form { heads, rows };
|
||||
/* The row form's buffers, `rows_for(max_tok)` rows each. `out` (Wire::out) must hold
|
||||
* world * rows_for(T) rows, since every rank's run is gathered at full length. */
|
||||
struct RowsWire {
|
||||
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0;
|
||||
ActFP8 attn{};
|
||||
};
|
||||
struct Wire {
|
||||
ActFP8 input{}, q_low{}, attn{};
|
||||
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
|
||||
MlaLatent::Wire core{};
|
||||
RowsWire rows{};
|
||||
};
|
||||
/* The gathered row of the row form: 4096 bf16, so a run is ceil(T / world) rows. */
|
||||
static constexpr int64_t kOutRowBytes = 4096 * 2;
|
||||
static int64_t rows_for(int64_t T, int world) {
|
||||
return GlmTp::run_rows(T, world, kOutRowBytes);
|
||||
}
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
@@ -102,7 +145,11 @@ struct GlmMla {
|
||||
QuantFP8 attn_quant{};
|
||||
MlaLatent core{};
|
||||
rad_weight q_gain = 0, kv_gain = 0;
|
||||
rad_op op_kv_norm = 0, op_store = 0, op_ar = 0;
|
||||
rad_op op_kv_norm = 0, op_store = 0, op_store_stream = 0, op_resolve = 0, op_ar = 0;
|
||||
LinearFP8 rows_q_b{}, rows_output{};
|
||||
QuantFP8 rows_quant{};
|
||||
rad_weight rows_kv_b = 0;
|
||||
rad_op op_rows_absorb = 0, op_rows_attn = 0, op_rows_expand = 0, op_rows_gather = 0;
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const char* prefix, rad_kvgroup group, bool reduce = true,
|
||||
bool defer_finish = false) {
|
||||
@@ -139,12 +186,13 @@ struct GlmMla {
|
||||
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world),
|
||||
1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
|
||||
w.q_low, w.core.q));
|
||||
// Cache stores contiguous halves of the normalized latent, with no duplicated K/V.
|
||||
/* Cache stores contiguous halves of the normalized latent, with no duplicated K/V. An E4M3
|
||||
* cache (Geom::kv_dtype) stores at kv_store's default descale of 1, which mla_attn reads. */
|
||||
op_store = rw(b,
|
||||
RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256),
|
||||
RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.latent }, {});
|
||||
if (!op_store) return RAD_E_INVAL;
|
||||
@@ -159,8 +207,77 @@ struct GlmMla {
|
||||
RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096,
|
||||
GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer),
|
||||
{ nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out));
|
||||
/* The streamed store: kv_store's operands plus the residency map and the layer's mirror row,
|
||||
* added at issue (prepare). */
|
||||
if (rad_op_declared(b, "kv_store_streamed") && rad_kv_block_size(b, kv) == 4)
|
||||
op_store_stream = rw(b,
|
||||
RAD_OP(b, "kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("head_dim", 256), RAD_INT("n_head_kv", 1),
|
||||
RAD_INT("block_size", 4),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.latent }, {});
|
||||
/* Issued in finish, after this layer's indexer selects and before the attention reads
|
||||
* `selected`. `sel_pitch` is the row pitch MlaLatent declares its attention with. */
|
||||
op_resolve = kv_resolve_declare(b, g, kv, w.core.selected, w.core.nsel, core.c.blocks);
|
||||
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
|
||||
return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL;
|
||||
if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL;
|
||||
return reduce ? declare_rows(b, nm, prefix) : RAD_OK;
|
||||
}
|
||||
/* Declared whatever the step size, as every TP split here is: arena levels declare again at a
|
||||
* smaller max_tok and must get the same graph. The gather's message bound is the all-reduce's,
|
||||
* so both share one exchange instance and its scratch. */
|
||||
int declare_rows(RadBuilder* b, Names& nm, const char* prefix) {
|
||||
const auto& r = w.rows;
|
||||
if (!r.q || g.world < 2) return RAD_OK;
|
||||
if (!r.q_latent || !r.attn_latent || !r.out || !r.attn.x || r.attn.x == r.q) return RAD_E_INVAL;
|
||||
const int64_t R = rows_for(g.max_tok, g.world);
|
||||
const auto wg = grp_layer(layer);
|
||||
/* Whole views of the head form's container entries: one stored weight each, whose
|
||||
* encoding (block fp8 at f32 scales, the decoded bf16 kv_b) the views inherit. */
|
||||
rows_q_b.stored = nm.f("blk.%d.attn_q_b.weight", layer);
|
||||
RAD_ARCH_TRY(rows_q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b_rows", layer), 16384, 1536,
|
||||
RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
|
||||
w.q_low, r.q, R));
|
||||
rows_kv_b = decl_view(b, nm.f("blk.%d.attn_kv_b_rows.weight", layer),
|
||||
nm.f("blk.%d.attn_kv_b.weight", layer), nullptr, RAD_BF16,
|
||||
{ 64 * 2 * 256, 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
|
||||
if (!rows_kv_b) return RAD_E_INVAL;
|
||||
auto project = [&](const char* mode, rad_buf in, rad_buf out) {
|
||||
return rw(b,
|
||||
RAD_OP(b, "mla_project",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("heads", 64),
|
||||
RAD_INT("head_dim", 256), RAD_INT("latent_dim", 512),
|
||||
RAD_STR("mode", mode), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(rows_kv_b)),
|
||||
{ in }, { out });
|
||||
};
|
||||
op_rows_absorb = project("absorb", r.q, r.q_latent);
|
||||
op_rows_attn = rw(b, MlaLatent::attn_op(b, g, R, 64, core.c.blocks, 1.0 / std::sqrt(256.0)),
|
||||
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
|
||||
op_rows_expand = project("expand", r.attn_latent, r.attn.x);
|
||||
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
|
||||
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
|
||||
RAD_ARCH_TRY(rows_output.declare(b, nm, g, nm.f("blk.%d.attn_output_rows", layer), 4096,
|
||||
16384, RAD_SHARD_NONE, wg,
|
||||
{ nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, r.out,
|
||||
R));
|
||||
op_rows_gather = rw(b,
|
||||
RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", 4096, g.max_tok * 4096),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ r.out }, { w.out });
|
||||
return op_rows_absorb && op_rows_attn && op_rows_expand && op_rows_gather ? RAD_OK
|
||||
: RAD_E_INVAL;
|
||||
}
|
||||
/* From the TP split threshold, and while the last rank's run is not empty (always at that
|
||||
* threshold for up to 8 ranks); the same answer on every rank, as the gather needs. */
|
||||
bool rows_take(int64_t T) const {
|
||||
return op_rows_gather && GlmTp::splits(T, g.world) &&
|
||||
(g.world - 1) * rows_for(T, g.world) < T;
|
||||
}
|
||||
void prepare(RadCtx* ctx, const RadBatch* batch) const {
|
||||
const auto* kb = kv_batch(batch, kv);
|
||||
@@ -173,16 +290,77 @@ struct GlmMla {
|
||||
kv_a.step(ctx, w.input, w.kv_raw, T);
|
||||
q_norm.step(ctx, T);
|
||||
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T));
|
||||
q_b.step(ctx, w.q_low, w.core.q, T);
|
||||
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
|
||||
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
|
||||
/* The row form splits the query projection into finish_rows (per rank), so q_b runs here
|
||||
* only in the head form; the latent store below is full length either way. */
|
||||
if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T);
|
||||
if (!kb->stream) {
|
||||
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
|
||||
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
|
||||
return;
|
||||
}
|
||||
/* A streamed group writes its host mirror, and the ring slot only where the block is
|
||||
* resident; the stage wait goes immediately before the store (core/kvstream/stage.h). A
|
||||
* staged pass also stores at block-id identity, which is how the stage view is read. */
|
||||
const bool staged = kv_stage_wait(ctx, kv, kb, layer);
|
||||
const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb);
|
||||
if (!op_store_stream || !L.host || L.blocks <= 0) {
|
||||
rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no "
|
||||
"kv_store_streamed row to write its host mirror with");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(ctx, op_store_stream, T, bcol(w.latent, 0, 256, T),
|
||||
bcol(w.latent, 256, 256, T), praw(kb->slot_mapping, RAD_I32, T),
|
||||
kv_cache(kv, layer), praw(L.res, RAD_I32, L.blocks),
|
||||
praw2(L.host, RAD_U8, L.blocks, L.bbytes));
|
||||
if (staged)
|
||||
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
|
||||
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
|
||||
}
|
||||
void finish(RadCtx* ctx, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
core.step(ctx, T);
|
||||
attn_quant.step(ctx, T);
|
||||
output.step(ctx, w.attn, w.out, T);
|
||||
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
|
||||
const auto* kb = kv_batch(batch, kv);
|
||||
/* A streamed group's selection is resolved here, after this layer's indexer wrote fresh
|
||||
* block ids into the one `selected` buffer every layer shares and before either form of
|
||||
* the attention reads it. A pass on the stage view reads block ids and never resolves. */
|
||||
if (kb && kb->stream && !kv_stage_layer(ctx, kv, kb, layer) && T > 0) {
|
||||
const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb);
|
||||
if (!op_resolve || !w.core.nsel || !L.host || L.blocks <= 0 || L.slots <= 0) {
|
||||
rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no "
|
||||
"kv_resolve for its selection");
|
||||
return;
|
||||
}
|
||||
/* The count is qsa_select's entry count, never `length` (a token count). */
|
||||
kv_resolve_issue(ctx, op_resolve, L, brow_slice(w.core.selected, 0, T, core.c.blocks),
|
||||
brow_slice(w.core.nsel, 0, T, 1), kv, layer, T);
|
||||
}
|
||||
if (rows_take(T)) {
|
||||
finish_rows(ctx, T);
|
||||
} else {
|
||||
core.step(ctx, T);
|
||||
attn_quant.step(ctx, T);
|
||||
output.step(ctx, w.attn, w.out, T);
|
||||
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
|
||||
}
|
||||
/* After every attention launch of this layer (core/kvstream/stage.h). */
|
||||
if (kb && kb->stream) kv_stage_next(ctx, kv, layer);
|
||||
}
|
||||
/* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the
|
||||
* gather sends its unwritten tail rows, which land past T. */
|
||||
void finish_rows(RadCtx* ctx, int64_t T) const {
|
||||
const auto& r = w.rows;
|
||||
const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kOutRowBytes);
|
||||
const int64_t first = run.first, n = run.rows;
|
||||
rows_q_b.step(ctx, w.q_low, r.q, T, first, n, 0);
|
||||
RAD_ISSUE_N(ctx, op_rows_absorb, n, brows(r.q, n), RAD_W(rows_kv_b), brows(r.q_latent, n));
|
||||
RAD_ISSUE_N(ctx, op_rows_attn, n, brows(r.q_latent, n), kv_cache(kv, layer),
|
||||
brow_slice(w.core.selected, first, n, core.c.blocks),
|
||||
brow_slice(w.core.length, first, n, 1), brows(r.attn_latent, n));
|
||||
RAD_ISSUE_N(ctx, op_rows_expand, n, brows(r.attn_latent, n), RAD_W(rows_kv_b),
|
||||
brows(r.attn.x, n));
|
||||
rows_quant.step(ctx, n);
|
||||
rows_output.step(ctx, r.attn, r.out, n);
|
||||
RAD_ISSUE_N(ctx, op_rows_gather, run.run * 4096, brows(r.out, run.run),
|
||||
brows(w.out, g.world * run.run));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -16,7 +16,11 @@
|
||||
* before the layer's attention, `join` (the residual add and the proposal rows' selection) between
|
||||
* its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's.
|
||||
* Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj
|
||||
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */
|
||||
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass.
|
||||
*
|
||||
* The same head serves another DeepSeek-style drafter by its checkpoint layout, set before
|
||||
* declare_inputs: the residual width, the layer's checkpoint prefix and index, and the name of the
|
||||
* head's final norm (Ling-3.0: 2560, `model.layers.42`, 42, `final_layernorm.weight`). */
|
||||
#ifndef RAD_BLOCK_GLM_MTP_H
|
||||
#define RAD_BLOCK_GLM_MTP_H
|
||||
#include "rad_glm_tp.h"
|
||||
@@ -31,6 +35,10 @@ struct GlmMtp {
|
||||
rad_weight token = 0, head = 0;
|
||||
};
|
||||
static constexpr int kDepth = 3; /* --num-speculative-tokens auto */
|
||||
int64_t width = 4096;
|
||||
const char* prefix = "model.language_model.layers.45";
|
||||
int layer = 45;
|
||||
const char* norm_src = "shared_head.norm.weight";
|
||||
Names nm{ "mtp" };
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
@@ -50,47 +58,48 @@ struct GlmMtp {
|
||||
w = wire;
|
||||
if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1)
|
||||
return RAD_E_INVAL;
|
||||
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 });
|
||||
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST);
|
||||
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 });
|
||||
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 });
|
||||
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 });
|
||||
const char* pre = "model.language_model.layers.45";
|
||||
const int64_t E = width;
|
||||
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, E });
|
||||
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, E }, RAD_BUF_PERSIST);
|
||||
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, E });
|
||||
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 2 * E });
|
||||
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, E });
|
||||
const char* pre = prefix;
|
||||
auto gain = [&](const char* n, const char* src) {
|
||||
const char* name = nm.f("%s", n);
|
||||
if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
|
||||
return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(45));
|
||||
return decl_w(b, name, RAD_F32, { E }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(layer));
|
||||
};
|
||||
en = gain("enorm.weight", "enorm.weight");
|
||||
hn = gain("hnorm.weight", "hnorm.weight");
|
||||
norm = gain("output_norm.weight", "shared_head.norm.weight");
|
||||
norm = gain("output_norm.weight", norm_src);
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre)));
|
||||
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(45));
|
||||
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { E, 2 * E }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(layer));
|
||||
if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh)
|
||||
return RAD_E_INVAL;
|
||||
op_prev = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.final_hidden }, { hidden });
|
||||
op_embed = rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w.token)),
|
||||
{}, { embedding });
|
||||
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, 4096, embedding));
|
||||
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, E, embedding));
|
||||
op_embed_ar = GlmTp::reduce(b, g, embedding, true);
|
||||
op_en = rmsnorm(b, en, embedding, concat);
|
||||
op_hn = rmsnorm(b, hn, hidden, concat);
|
||||
op_eh = rw(b,
|
||||
RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096),
|
||||
RAD_INT("K", 8192), RAD_STR("dtype", "bf16")),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", E),
|
||||
RAD_INT("K", 2 * E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(eh)),
|
||||
{ concat }, { x });
|
||||
return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar)
|
||||
@@ -102,14 +111,14 @@ struct GlmMtp {
|
||||
int declare_join(RadBuilder* b, rad_buf y) {
|
||||
op_residual = rw(b,
|
||||
RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x, y }, { x });
|
||||
// All history rows fill the draft cache; only proposal rows need its FFN.
|
||||
op_select = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x }, { hidden });
|
||||
@@ -124,7 +133,7 @@ struct GlmMtp {
|
||||
op_head = rw(b,
|
||||
RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", 4096),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w.head)),
|
||||
{ hidden }, { w.logits });
|
||||
@@ -150,9 +159,9 @@ struct GlmMtp {
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token),
|
||||
brows(embedding, T));
|
||||
mrows.step(c, batch, embedding, T);
|
||||
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T));
|
||||
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T));
|
||||
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * width, brows(embedding, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, width, T));
|
||||
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, width, width, T));
|
||||
RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T));
|
||||
}
|
||||
void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const {
|
||||
@@ -175,7 +184,7 @@ private:
|
||||
rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const {
|
||||
return rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(gain)),
|
||||
{ in }, { out });
|
||||
@@ -183,7 +192,7 @@ private:
|
||||
rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const {
|
||||
return rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ in }, { out });
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
|
||||
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */
|
||||
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. With `groups`
|
||||
* above 1 the selection is group-limited (router_sigmoid_group_topk, Ling-3.0's 8 groups, 4 kept). */
|
||||
#ifndef RAD_BLOCK_GLM_ROUTER_H
|
||||
#define RAD_BLOCK_GLM_ROUTER_H
|
||||
#include "rad_glm_tp.h"
|
||||
@@ -9,7 +10,7 @@ namespace rad {
|
||||
namespace arch {
|
||||
struct GlmRouter {
|
||||
struct Config {
|
||||
int64_t experts = 288, top_k = 8, rows = 32;
|
||||
int64_t experts = 288, top_k = 8, rows = 32, groups = 1, topk_groups = 1;
|
||||
int norm = 1;
|
||||
double route_scale = 2.5;
|
||||
};
|
||||
@@ -33,8 +34,9 @@ struct GlmRouter {
|
||||
w = wire;
|
||||
if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 ||
|
||||
c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 ||
|
||||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 || !w.input ||
|
||||
!w.logits || !w.ids || !w.weights || w.logits == w.weights)
|
||||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 ||
|
||||
c.groups < 1 || c.experts % c.groups || c.topk_groups < 1 || c.topk_groups > c.groups ||
|
||||
!w.input || !w.logits || !w.ids || !w.weights || w.logits == w.weights)
|
||||
return RAD_E_INVAL;
|
||||
const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name);
|
||||
RAD_ARCH_TRY(map_copy(b, pn, src.weight));
|
||||
@@ -52,14 +54,25 @@ struct GlmRouter {
|
||||
{ w.input }, { w.logits });
|
||||
RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input,
|
||||
w.logits));
|
||||
op_select =
|
||||
rw(b,
|
||||
RAD_OP(b, "router_sigmoid_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
|
||||
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(correction)),
|
||||
{ w.logits }, { w.ids, w.weights });
|
||||
if (c.groups > 1)
|
||||
op_select =
|
||||
rw(b,
|
||||
RAD_OP(b, "router_sigmoid_group_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("n_group", c.groups),
|
||||
RAD_INT("topk_group", c.topk_groups), RAD_INT("norm", c.norm),
|
||||
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(correction)),
|
||||
{ w.logits }, { w.ids, w.weights });
|
||||
else
|
||||
op_select =
|
||||
rw(b,
|
||||
RAD_OP(b, "router_sigmoid_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
|
||||
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
|
||||
RAD_WEIGHTS(correction)),
|
||||
{ w.logits }, { w.ids, w.weights });
|
||||
return op_project && op_select ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
|
||||
|
||||
+39
-11
@@ -77,12 +77,13 @@ struct HyperConn {
|
||||
* skips its own on every step takes_ar() accepts. The block's partial sum is the write's
|
||||
* input buffer, so this saves a launch. */
|
||||
int reduce = 0;
|
||||
/* Whether the read also emits Hadamard-rotated fp8 codes of the block input, for a
|
||||
* consumer whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in
|
||||
* the plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
|
||||
/* Whether the read also emits Hadamard-rotated codes of the block input, for a consumer
|
||||
* whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in the
|
||||
* plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
|
||||
int rotate = 0;
|
||||
/* Whether the plain codes are int8 (q8/s8) rather than E4M3 (q/s), for int8 trunk linears
|
||||
* (LinearFP8::i8). The rotated codes stay E4M3, the routed experts' operand. */
|
||||
* (LinearFP8::i8). The rotated codes take the same dtype (had_quant_act_i8g's beside int8,
|
||||
* had_quant_act_fp8's beside E4M3), so `Wire::rq` is declared to match. */
|
||||
int codes_i8 = 0;
|
||||
/* The most rows one read is declared for, 0 for max_tok; a wider step reads in pieces
|
||||
* (read_pieces). The read's scratch is sized for its band (some 22 KiB a row at
|
||||
@@ -115,6 +116,11 @@ struct HyperConn {
|
||||
* `mix`), read from their encoding at declare. */
|
||||
bool mix_e4m3 = false;
|
||||
rad_op op_read = 0, op_write = 0;
|
||||
/* The block input's own int8 pair is the rotated one (ActFP8::q8_rot, a trunk stored rotated):
|
||||
* the read writes its rotated codes there and its plain ones into `pq` / `ps`, a pair of this
|
||||
* connection's that nothing reads. */
|
||||
bool xrot = false;
|
||||
rad_buf pq = 0, ps = 0;
|
||||
/* The write with the all-reduce folded in; 0 when not requested or not served.
|
||||
* `op_ar_write6` is the same on the rotated 6-bit wire, declared only when a lossy payload is
|
||||
* accepted and issued on the steps ar_wire_is_exact rejects (every trunk all-reduce at a
|
||||
@@ -193,6 +199,17 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.quant && (c.codes_i8 ? (!w.x.q8 || !w.x.s8) : (!w.x.q || !w.x.s))) return RAD_E_INVAL;
|
||||
/* A trunk whose int8 linears are stored rotated reads the rotated codes alone: `x`'s int8 pair
|
||||
* is then that pair (ActFP8::q8_rot), and every reader of the block input -- the trunk's
|
||||
* projections and the rotated experts -- takes it. The read derives the rotated codes in its
|
||||
* plain codes' finisher, so the plain ones still have somewhere to go: a pair of this
|
||||
* connection's own that nothing reads. */
|
||||
xrot = c.quant && c.codes_i8 && w.x.q8_rot;
|
||||
if (xrot && c.rotate) {
|
||||
fprintf(stderr, "radiance: %s: the block input's own codes are the rotated ones "
|
||||
"(ActFP8::q8_rot), so there is no second rotated pair to ask for\n", name);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.rotate && (!c.quant || !w.rq || !w.rs)) {
|
||||
fprintf(stderr, "radiance: %s: the rotated codes need the plain ones (quant) and the "
|
||||
"rq/rs pair on the wire\n", name);
|
||||
@@ -248,8 +265,16 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
|
||||
int n_wr = 1;
|
||||
if (c.inject) wr[n_wr++] = w.inj;
|
||||
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
|
||||
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
|
||||
if (xrot) {
|
||||
pq = decl_b(b, nm.f("%s.plain.q8", name), RAD_I8, { g.max_tok, g.n_embd });
|
||||
ps = decl_b(b, nm.f("%s.plain.s8", name), RAD_F32, { g.max_tok, fp8_blocks(g.n_embd) });
|
||||
if (!pq || !ps || w.x.g8 != RAD_FP8_BLOCK) return RAD_E_INVAL;
|
||||
wr[n_wr++] = pq; wr[n_wr++] = ps;
|
||||
wr[n_wr++] = w.x.q8; wr[n_wr++] = w.x.s8;
|
||||
} else {
|
||||
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
|
||||
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
|
||||
}
|
||||
|
||||
op_read = RAD_OP(b, "hc_read",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.read_rows > 0 && c.read_rows < g.max_tok
|
||||
@@ -259,7 +284,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd), RAD_INT("inject", c.inject ? 1 : 0),
|
||||
RAD_INT("group", c.quant ? RAD_FP8_BLOCK : 0),
|
||||
RAD_INT("rotate", c.rotate ? 1 : 0),
|
||||
RAD_INT("rotate", (c.rotate || xrot) ? 1 : 0),
|
||||
RAD_STR("mix", mix_e4m3 ? "e4m3" : "bf16")),
|
||||
wts, n_wts);
|
||||
if (!op_read) return RAD_E_INVAL;
|
||||
@@ -358,11 +383,14 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
|
||||
c.inject ? RAD_W(w_inj) : RAD_NONE,
|
||||
brow_slice(w.x.x, r0, rows, g.n_embd),
|
||||
c.inject ? brow_slice(w.inj, r0, rows, c.hc) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.q8 : w.x.q, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
|
||||
c.quant ? brow_slice(xrot ? pq : c.codes_i8 ? w.x.q8 : w.x.q, r0, rows,
|
||||
g.n_embd) : RAD_NONE,
|
||||
c.quant ? brow_slice(xrot ? ps : c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rq, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
(c.rotate || xrot) ? brow_slice(xrot ? w.x.q8 : w.rq, r0, rows, g.n_embd)
|
||||
: RAD_NONE,
|
||||
(c.rotate || xrot) ? brow_slice(xrot ? w.x.s8 : w.rs, r0, rows,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* ================================================================== the control-vector projection
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
/* rad_block_lilicorr.h -- LiLiCorr's head: the candidate correlator after a DFlash2 backbone.
|
||||
*
|
||||
* NVIDIA's drafter for Nemotron-3.5-Bolt (vLLM's model_executor/models/lilicorr.py). The backbone is
|
||||
* rad_block_dflash2.h's, with attention sinks (Dflash2::Config::lili). Its final hidden states at
|
||||
* the block's draft rows go here instead of to DFlash2's selector:
|
||||
*
|
||||
* candidates each draft position's top-k from the target's own lm_head (log-softmax values,
|
||||
* vocab-parallel: each rank's shard, all-gathered, merged)
|
||||
* lattice steps x k rows a sequence, row s * k + j:
|
||||
* token_proj(embed(cand)) + pass_hidden_proj(h_s)
|
||||
* + feature_mlp(layernorm(five rank features)) + slot[s] + rank[j]
|
||||
* 2 layers rmsnorm, attention over the lattice with a learned slot bias (lili_attn), the
|
||||
* in/out projections; rmsnorm, silu MLP with biases; residuals
|
||||
* factor x = output_norm(lattice), a = anchor_norm(context_proj(the anchor's context row))
|
||||
* f = silu(W [x | a | x * a] + b), [out | in] = edge heads of f
|
||||
* walk normalised dot products, start from the anchor's own outgoing head, greedy
|
||||
* (lili_walk)
|
||||
*
|
||||
* The anchor's context row is hidden_norm(fc(taps)) at the last committed position, which the
|
||||
* context pass left in Dflash2's `c` (RadBatch::anchor_rows names the row). The head reads the
|
||||
* target's embedding and lm_head, and its own 25 linears are bf16: ModelOpt ships them NVFP4,
|
||||
* which no kernel serves, and the recipe decodes them (`cast dtype=bf16`).
|
||||
*
|
||||
* Every rank computes the whole lattice (vLLM: "candidate IDs and embeddings are replicated across
|
||||
* TP ranks"); only the head's logits and the embedding lookup are per rank, with the merge in
|
||||
* lili_cand and an exact all-reduce after the lookup.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_LILICORR_H
|
||||
#define RAD_BLOCK_LILICORR_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct LiliCorr {
|
||||
enum { MAX_LAYERS = 4 };
|
||||
|
||||
struct Config {
|
||||
int64_t steps = 0; /* draft positions a sequence: the block less the anchor */
|
||||
int64_t k = 8; /* candidates a position (lilicorr_candidate_topk) */
|
||||
int64_t hs = 1024; /* the lattice's width (lilicorr_hidden_size) */
|
||||
int64_t n_head = 8;
|
||||
int64_t mlp = 2048; /* hs * lilicorr_mlp_ratio */
|
||||
int64_t fdim = 1024; /* lilicorr_factor_dim */
|
||||
int64_t n_layer = 2;
|
||||
double eps = 1e-6; /* rms_norm_eps, the lattice's RMS norms */
|
||||
double vec_eps = 1e-4; /* lilicorr_vector_eps, F.normalize's floor */
|
||||
double scale = 8.0; /* lilicorr_logit_scale */
|
||||
};
|
||||
|
||||
/* row_k: the pairs a rank's logprob row carries, k rounded up so 2 + 2 row_k floats are whole
|
||||
* 16-byte words (the all-gather's unit): 9 for k = 8. */
|
||||
static int64_t row_k(int64_t k) { return (k % 2) ? k : k + 1; }
|
||||
|
||||
struct Wire {
|
||||
/* Dflash2's */
|
||||
rad_buf sel_h = 0; /* [srows, n_embd] the drafter's final hidden states, draft rows */
|
||||
rad_buf c = 0; /* [max_tok, n_embd] hidden_norm(fc(taps)), the context pass's rows */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32, the proposal */
|
||||
/* the head's own */
|
||||
rad_buf logits = 0; /* [srows, n_vocab] f32, this rank's shard */
|
||||
rad_buf stats = 0; /* [srows, 2 + 2 row_k] f32 */
|
||||
rad_buf sgath = 0; /* [srows, world * (2 + 2 row_k)] f32, world > 1 */
|
||||
rad_buf pas = 0; /* [srows, hs] */
|
||||
rad_buf cand = 0; /* [srows * k] i32 */
|
||||
rad_buf feat = 0; /* [lrows, hs] */
|
||||
rad_buf hh = 0; /* [lrows, hs] the lattice's residual stream; starts as lili_cand's base */
|
||||
rad_buf emb = 0; /* [lrows, n_embd] the candidates' embeddings */
|
||||
rad_buf y = 0; /* [lrows, hs] */
|
||||
rad_buf qkv = 0; /* [lrows, 3 hs] */
|
||||
rad_buf att = 0; /* [lrows, hs] */
|
||||
rad_buf up = 0; /* [lrows, mlp] */
|
||||
rad_buf ups = 0; /* [lrows, mlp] */
|
||||
rad_buf cat = 0; /* [lrows, 3 hs] */
|
||||
rad_buf fh = 0; /* [lrows, hs] */
|
||||
rad_buf fhs = 0; /* [lrows, hs] */
|
||||
rad_buf edges = 0; /* [lrows, 2 fdim] */
|
||||
rad_buf anc = 0; /* [max_seqs, n_embd] */
|
||||
rad_buf ast = 0; /* [max_seqs, hs] */
|
||||
rad_buf an = 0; /* [max_seqs, hs] */
|
||||
rad_buf aout = 0; /* [max_seqs, fdim] */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int64_t srows = 0, lrows = 0, rk = 0;
|
||||
|
||||
rad_weight w_lm = 0, w_tok = 0; /* the target's */
|
||||
rad_weight w_tokp = 0, b_tokp = 0, w_pass = 0, b_pass = 0, w_ctx = 0, b_ctx = 0;
|
||||
rad_weight w_fdn = 0, b_fdn = 0, ln_w = 0, ln_b = 0, up_w = 0, up_b = 0, w_slot = 0, w_rank = 0;
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_in[MAX_LAYERS] = {}, b_in[MAX_LAYERS] = {};
|
||||
rad_weight w_out[MAX_LAYERS] = {}, b_out[MAX_LAYERS] = {}, w_mnorm[MAX_LAYERS] = {};
|
||||
rad_weight w_up[MAX_LAYERS] = {}, b_up[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
|
||||
rad_weight b_dn[MAX_LAYERS] = {};
|
||||
rad_weight w_rel = 0, w_same = 0, w_onorm = 0, w_annorm = 0;
|
||||
rad_weight w_fac = 0, b_fac = 0, w_edge = 0, b_edge = 0, w_aout = 0, b_aout = 0;
|
||||
|
||||
rad_op op_logits = 0, op_stats = 0, op_sgath = 0, op_pas = 0, op_cand = 0;
|
||||
rad_op op_emb = 0, op_emb_ar = 0, op_tokp = 0, op_fdn = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_in[MAX_LAYERS] = {}, op_attn = 0;
|
||||
rad_op op_out[MAX_LAYERS] = {}, op_mnorm[MAX_LAYERS] = {}, op_up[MAX_LAYERS] = {};
|
||||
rad_op op_dn[MAX_LAYERS] = {}, op_silu_up = 0;
|
||||
rad_op op_onorm = 0, op_anc = 0, op_ctx = 0, op_annorm = 0, op_factor = 0, op_fac = 0;
|
||||
rad_op op_silu_f = 0, op_edge = 0, op_aout = 0, op_walk = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, rad_weight lm_head,
|
||||
rad_weight tok_embd, const char* ck, const Wire& wire);
|
||||
/* After Dflash2::step, on the same query batch: `sel_h` holds the draft rows. */
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int LiliCorr::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
|
||||
rad_weight lm_head, rad_weight tok_embd, const char* ck,
|
||||
const Wire& wire) {
|
||||
g = geom; cfg = c; w = wire; w_lm = lm_head; w_tok = tok_embd;
|
||||
if (!w_lm || !w_tok || !ck || cfg.steps < 1 || cfg.k < 2 || cfg.n_layer < 1 ||
|
||||
cfg.n_layer > MAX_LAYERS || cfg.hs % cfg.n_head)
|
||||
return RAD_E_INVAL;
|
||||
const int64_t K = cfg.k, S = cfg.steps, hs = cfg.hs, fd = cfg.fdim, E = g.n_embd;
|
||||
srows = g.max_seqs * S;
|
||||
lrows = srows * K;
|
||||
rk = row_k(K);
|
||||
const int ACC = RAD_ACCESS_PER_TOKEN;
|
||||
const RadWeightGroup grp = grp_model();
|
||||
|
||||
/* The head's weights, all replicated. Linears and tables bf16, biases, norms and the
|
||||
* feature layer f32. */
|
||||
auto wt = [&](const char* dn, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shp) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, grp);
|
||||
};
|
||||
const char* L = nm.ckpt("%s.lilicorr", ck);
|
||||
auto src = [&](const char* tail) { return nm.ckpt("%s.%s", L, tail); };
|
||||
w_tokp = wt(nm.f("dflash.lili.token_proj.weight"), src("token_proj.weight"), RAD_BF16, { hs, E });
|
||||
b_tokp = wt(nm.f("dflash.lili.token_proj.bias"), src("token_proj.bias"), RAD_F32, { hs });
|
||||
w_pass = wt(nm.f("dflash.lili.pass_proj.weight"), src("pass_hidden_proj.weight"), RAD_BF16,
|
||||
{ hs, E });
|
||||
b_pass = wt(nm.f("dflash.lili.pass_proj.bias"), src("pass_hidden_proj.bias"), RAD_F32, { hs });
|
||||
w_ctx = wt(nm.f("dflash.lili.context_proj.weight"), src("context_proj.weight"), RAD_BF16,
|
||||
{ hs, E });
|
||||
b_ctx = wt(nm.f("dflash.lili.context_proj.bias"), src("context_proj.bias"), RAD_F32, { hs });
|
||||
ln_w = wt(nm.f("dflash.lili.feature_norm.weight"), src("feature_norm.weight"), RAD_F32, { 5 });
|
||||
ln_b = wt(nm.f("dflash.lili.feature_norm.bias"), src("feature_norm.bias"), RAD_F32, { 5 });
|
||||
up_w = wt(nm.f("dflash.lili.feature_up.weight"), src("feature_mlp.up_proj.weight"), RAD_F32,
|
||||
{ hs, 5 });
|
||||
up_b = wt(nm.f("dflash.lili.feature_up.bias"), src("feature_mlp.up_proj.bias"), RAD_F32,
|
||||
{ hs });
|
||||
w_fdn = wt(nm.f("dflash.lili.feature_down.weight"), src("feature_mlp.down_proj.weight"),
|
||||
RAD_BF16, { hs, hs });
|
||||
b_fdn = wt(nm.f("dflash.lili.feature_down.bias"), src("feature_mlp.down_proj.bias"), RAD_F32,
|
||||
{ hs });
|
||||
/* [1, 1, steps, 1, hs] and [1, 1, 1, k, hs], read as tables (a reshape of one whole plane). */
|
||||
w_slot = wt(nm.f("dflash.lili.slot_embedding"), src("slot_embedding"), RAD_BF16, { S, hs });
|
||||
w_rank = wt(nm.f("dflash.lili.rank_embedding"), src("rank_embedding"), RAD_BF16, { K, hs });
|
||||
w_rel = wt(nm.f("dflash.lili.relative_slot_bias"), src("relative_slot_bias"), RAD_F32,
|
||||
{ cfg.n_head, 2 * (S + 1) - 1 });
|
||||
w_same = wt(nm.f("dflash.lili.same_slot_bias"), src("same_slot_bias"), RAD_F32, { cfg.n_head });
|
||||
for (int64_t l = 0; l < cfg.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
auto ls = [&](const char* tail) { return nm.ckpt("%s.layers.%d.%s", L, i, tail); };
|
||||
w_anorm[i] = wt(nm.f("dflash.lili.blk.%d.attn_norm.weight", i), ls("attn_norm.weight"),
|
||||
RAD_F32, { hs });
|
||||
w_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.weight", i), ls("attn.in_proj_weight"),
|
||||
RAD_BF16, { 3 * hs, hs });
|
||||
b_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.bias", i), ls("attn.in_proj_bias"), RAD_F32,
|
||||
{ 3 * hs });
|
||||
w_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.weight", i), ls("attn.out_proj.weight"),
|
||||
RAD_BF16, { hs, hs });
|
||||
b_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.bias", i), ls("attn.out_proj.bias"),
|
||||
RAD_F32, { hs });
|
||||
w_mnorm[i] = wt(nm.f("dflash.lili.blk.%d.mlp_norm.weight", i), ls("mlp_norm.weight"),
|
||||
RAD_F32, { hs });
|
||||
w_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.weight", i), ls("mlp.up_proj.weight"),
|
||||
RAD_BF16, { cfg.mlp, hs });
|
||||
b_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.bias", i), ls("mlp.up_proj.bias"), RAD_F32,
|
||||
{ cfg.mlp });
|
||||
w_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.weight", i), ls("mlp.down_proj.weight"),
|
||||
RAD_BF16, { hs, cfg.mlp });
|
||||
b_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.bias", i), ls("mlp.down_proj.bias"),
|
||||
RAD_F32, { hs });
|
||||
if (!w_anorm[i] || !w_in[i] || !b_in[i] || !w_out[i] || !b_out[i] || !w_mnorm[i] ||
|
||||
!w_up[i] || !b_up[i] || !w_dn[i] || !b_dn[i])
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
w_onorm = wt(nm.f("dflash.lili.output_norm.weight"), src("output_norm.weight"), RAD_F32, { hs });
|
||||
w_annorm = wt(nm.f("dflash.lili.anchor_norm.weight"), src("anchor_norm.weight"), RAD_F32, { hs });
|
||||
w_fac = wt(nm.f("dflash.lili.factor_proj.weight"), src("factor_input_proj.weight"), RAD_BF16,
|
||||
{ hs, 3 * hs });
|
||||
b_fac = wt(nm.f("dflash.lili.factor_proj.bias"), src("factor_input_proj.bias"), RAD_F32,
|
||||
{ hs });
|
||||
/* [out_head | in_head] as one linear, as vLLM fuses them (`_fused_edge_weight`). */
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.weight"),
|
||||
{ src("out_head.weight"), src("in_head.weight") }, 0));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.bias"),
|
||||
{ src("out_head.bias"), src("in_head.bias") }, 0));
|
||||
w_edge = decl_w(b, nm.f("dflash.lili.edge.weight"), RAD_BF16, { 2 * fd, hs }, ACC,
|
||||
RAD_SHARD_NONE, grp);
|
||||
b_edge = decl_w(b, nm.f("dflash.lili.edge.bias"), RAD_F32, { 2 * fd }, ACC, RAD_SHARD_NONE,
|
||||
grp);
|
||||
w_aout = wt(nm.f("dflash.lili.anchor_out.weight"), src("anchor_out_head.weight"), RAD_BF16,
|
||||
{ fd, hs });
|
||||
b_aout = wt(nm.f("dflash.lili.anchor_out.bias"), src("anchor_out_head.bias"), RAD_F32, { fd });
|
||||
if (!w_tokp || !b_tokp || !w_pass || !b_pass || !w_ctx || !b_ctx || !ln_w || !ln_b || !up_w ||
|
||||
!up_b || !w_fdn || !b_fdn || !w_slot || !w_rank || !w_rel || !w_same || !w_onorm ||
|
||||
!w_annorm || !w_fac || !b_fac || !w_edge || !b_edge || !w_aout || !b_aout)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- ops */
|
||||
auto gemm_b = [&](int64_t rows, int64_t N, int64_t Kd, rad_weight wgt, rad_weight bias)
|
||||
-> rad_op {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", Kd),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(wgt, bias));
|
||||
};
|
||||
auto rms = [&](int64_t rows, int64_t n, rad_weight gain) -> rad_op {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", cfg.eps),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(gain));
|
||||
};
|
||||
auto silu = [&](int64_t rows, int64_t n) -> rad_op {
|
||||
return RAD_OP(b, "silu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
const int64_t sw = 2 + 2 * rk;
|
||||
|
||||
/* The candidates: this rank's shard of the target's logits, its logprob row, the exchange. */
|
||||
op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_lm)),
|
||||
{ w.sel_h }, { w.logits });
|
||||
/* Replicated, `vocab_off` is omitted: an optional parameter present at 0 is a different
|
||||
* declaration from an absent one. */
|
||||
op_stats = g.world > 1
|
||||
? rw(b, RAD_OP(b, "sample_logprobs",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("k", rk), RAD_INT("vocab_off", g.vocab_off)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.logits }, { w.stats })
|
||||
: rw(b, RAD_OP(b, "sample_logprobs",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("k", rk)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.logits }, { w.stats });
|
||||
if (g.world > 1)
|
||||
op_sgath = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * sw), RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", sw)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.stats }, { w.sgath });
|
||||
op_pas = rw(b, gemm_b(srows, hs, E, w_pass, b_pass), { w.sel_h }, { w.pas });
|
||||
op_cand = rw(b, RAD_OP(b, "lili_cand",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("k", K),
|
||||
RAD_INT("world", g.world), RAD_INT("steps", S),
|
||||
RAD_INT("n", hs), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("eps", 1e-5), RAD_INT("row_k", rk)),
|
||||
RAD_WEIGHTS(ln_w, ln_b, up_w, up_b, w_slot, w_rank)),
|
||||
{ g.world > 1 ? w.sgath : w.stats, w.pas }, { w.cand, w.feat, w.hh });
|
||||
/* The lattice: candidates' embeddings (the trunk's vocab-sharded table, exact reduce), the
|
||||
* token and feature projections added onto lili_cand's base in their GEMMs' residual. */
|
||||
op_emb = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{ w.cand }, { w.emb });
|
||||
if (g.world > 1)
|
||||
op_emb_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", E, lrows * E),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.emb }, { w.emb });
|
||||
op_tokp = rw(b, gemm_b(lrows, hs, E, w_tokp, b_tokp), { w.emb, w.hh }, { w.hh });
|
||||
op_fdn = rw(b, gemm_b(lrows, hs, hs, w_fdn, b_fdn), { w.feat, w.hh }, { w.hh });
|
||||
for (int64_t l = 0; l < cfg.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = rw(b, rms(lrows, hs, w_anorm[i]), { w.hh }, { w.y });
|
||||
op_in[i] = rw(b, gemm_b(lrows, 3 * hs, hs, w_in[i], b_in[i]), { w.y }, { w.qkv });
|
||||
op_out[i] = rw(b, gemm_b(lrows, hs, hs, w_out[i], b_out[i]), { w.att, w.hh }, { w.hh });
|
||||
op_mnorm[i] = rw(b, rms(lrows, hs, w_mnorm[i]), { w.hh }, { w.y });
|
||||
op_up[i] = rw(b, gemm_b(lrows, cfg.mlp, hs, w_up[i], b_up[i]), { w.y }, { w.up });
|
||||
op_dn[i] = rw(b, gemm_b(lrows, hs, cfg.mlp, w_dn[i], b_dn[i]), { w.ups, w.hh }, { w.hh });
|
||||
}
|
||||
op_attn = rw(b, RAD_OP(b, "lili_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("steps", S), RAD_INT("k", K),
|
||||
RAD_INT("n_head", cfg.n_head),
|
||||
RAD_INT("head_dim", hs / cfg.n_head),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_rel, w_same)),
|
||||
{ w.qkv }, { w.att });
|
||||
op_silu_up = rw(b, silu(lrows, cfg.mlp), { w.up }, { w.ups });
|
||||
op_onorm = rw(b, rms(lrows, hs, w_onorm), { w.hh }, { w.y });
|
||||
/* The anchor: the context pass's row at each drafting sequence's last committed position. */
|
||||
op_anc = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.c }, { w.anc });
|
||||
op_ctx = rw(b, gemm_b(g.max_seqs, hs, E, w_ctx, b_ctx), { w.anc }, { w.ast });
|
||||
op_annorm = rw(b, rms(g.max_seqs, hs, w_annorm), { w.ast }, { w.an });
|
||||
op_factor = rw(b, RAD_OP(b, "lili_factor",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("L", S * K),
|
||||
RAD_INT("n", hs), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.y, w.an }, { w.cat });
|
||||
op_fac = rw(b, gemm_b(lrows, hs, 3 * hs, w_fac, b_fac), { w.cat }, { w.fh });
|
||||
op_silu_f = rw(b, silu(lrows, hs), { w.fh }, { w.fhs });
|
||||
op_edge = rw(b, gemm_b(lrows, 2 * fd, hs, w_edge, b_edge), { w.fhs }, { w.edges });
|
||||
op_aout = rw(b, gemm_b(g.max_seqs, fd, hs, w_aout, b_aout), { w.an }, { w.aout });
|
||||
op_walk = rw(b, RAD_OP(b, "lili_walk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", S),
|
||||
RAD_INT("k", K), RAD_INT("n", fd), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("eps", cfg.vec_eps), RAD_F64("scale", cfg.scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.edges, w.aout, w.cand }, { w.tokens });
|
||||
if (!op_logits || !op_stats || (g.world > 1 && (!op_sgath || !op_emb_ar)) || !op_pas ||
|
||||
!op_cand || !op_emb || !op_tokp || !op_fdn || !op_attn || !op_silu_up || !op_onorm ||
|
||||
!op_anc || !op_ctx || !op_annorm || !op_factor || !op_fac || !op_silu_f || !op_edge ||
|
||||
!op_aout || !op_walk)
|
||||
return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void LiliCorr::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t n = batch->n_seq, S = n * cfg.steps, Lr = S * cfg.k;
|
||||
if (n <= 0) return;
|
||||
if (!batch->anchor_rows) {
|
||||
rad_step_fail(c, "lilicorr: the query pass carries no anchor rows (RadBatch::anchor_rows): "
|
||||
"this engine does not position a block drafter's anchor");
|
||||
return;
|
||||
}
|
||||
const int64_t E = g.n_embd, hs = cfg.hs, fd = cfg.fdim;
|
||||
const int64_t sw = 2 + 2 * rk;
|
||||
|
||||
RAD_ISSUE_N(c, op_logits, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.logits, S));
|
||||
RAD_ISSUE_N(c, op_stats, S, brows(w.logits, S), RAD_NONE, brows(w.stats, S));
|
||||
if (op_sgath) RAD_ISSUE(c, op_sgath, brows(w.stats, S), brows(w.sgath, S));
|
||||
RAD_ISSUE_N(c, op_pas, S, brows(w.sel_h, S), RAD_W(w_pass), RAD_W(b_pass), RAD_NONE,
|
||||
brows(w.pas, S));
|
||||
RAD_ISSUE_N(c, op_cand, S, op_sgath ? brows(w.sgath, S) : brows(w.stats, S), brows(w.pas, S),
|
||||
RAD_W(ln_w), RAD_W(ln_b), RAD_W(up_w), RAD_W(up_b), RAD_W(w_slot), RAD_W(w_rank),
|
||||
brow_slice(w.cand, 0, Lr, 1), brows(w.feat, Lr), brows(w.hh, Lr));
|
||||
(void)sw;
|
||||
|
||||
RAD_ISSUE_N(c, op_emb, Lr, brow_slice(w.cand, 0, Lr, 1), RAD_W(w_tok), brows(w.emb, Lr));
|
||||
if (op_emb_ar) RAD_ISSUE_N(c, op_emb_ar, Lr * E, brows(w.emb, Lr), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_tokp, Lr, brows(w.emb, Lr), RAD_W(w_tokp), RAD_W(b_tokp), brows(w.hh, Lr),
|
||||
brows(w.hh, Lr));
|
||||
RAD_ISSUE_N(c, op_fdn, Lr, brows(w.feat, Lr), RAD_W(w_fdn), RAD_W(b_fdn), brows(w.hh, Lr),
|
||||
brows(w.hh, Lr));
|
||||
for (int64_t l = 0; l < cfg.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_anorm[i], Lr, brows(w.hh, Lr), RAD_W(w_anorm[i]), brows(w.y, Lr));
|
||||
RAD_ISSUE_N(c, op_in[i], Lr, brows(w.y, Lr), RAD_W(w_in[i]), RAD_W(b_in[i]), RAD_NONE,
|
||||
brows(w.qkv, Lr));
|
||||
RAD_ISSUE_N(c, op_attn, Lr, brows(w.qkv, Lr), RAD_W(w_rel), RAD_W(w_same), brows(w.att, Lr));
|
||||
RAD_ISSUE_N(c, op_out[i], Lr, brows(w.att, Lr), RAD_W(w_out[i]), RAD_W(b_out[i]),
|
||||
brows(w.hh, Lr), brows(w.hh, Lr));
|
||||
RAD_ISSUE_N(c, op_mnorm[i], Lr, brows(w.hh, Lr), RAD_W(w_mnorm[i]), brows(w.y, Lr));
|
||||
RAD_ISSUE_N(c, op_up[i], Lr, brows(w.y, Lr), RAD_W(w_up[i]), RAD_W(b_up[i]), RAD_NONE,
|
||||
brows(w.up, Lr));
|
||||
RAD_ISSUE_N(c, op_silu_up, Lr, brows(w.up, Lr), brows(w.ups, Lr));
|
||||
RAD_ISSUE_N(c, op_dn[i], Lr, brows(w.ups, Lr), RAD_W(w_dn[i]), RAD_W(b_dn[i]),
|
||||
brows(w.hh, Lr), brows(w.hh, Lr));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_onorm, Lr, brows(w.hh, Lr), RAD_W(w_onorm), brows(w.y, Lr));
|
||||
|
||||
RAD_ISSUE_N(c, op_anc, n, RAD_B(w.c), praw(batch->anchor_rows, RAD_I32, n), brows(w.anc, n));
|
||||
RAD_ISSUE_N(c, op_ctx, n, brows(w.anc, n), RAD_W(w_ctx), RAD_W(b_ctx), RAD_NONE, brows(w.ast, n));
|
||||
RAD_ISSUE_N(c, op_annorm, n, brows(w.ast, n), RAD_W(w_annorm), brows(w.an, n));
|
||||
RAD_ISSUE_N(c, op_factor, Lr, brows(w.y, Lr), brows(w.an, n), brows(w.cat, Lr));
|
||||
RAD_ISSUE_N(c, op_fac, Lr, brows(w.cat, Lr), RAD_W(w_fac), RAD_W(b_fac), RAD_NONE,
|
||||
brows(w.fh, Lr));
|
||||
RAD_ISSUE_N(c, op_silu_f, Lr, brows(w.fh, Lr), brows(w.fhs, Lr));
|
||||
RAD_ISSUE_N(c, op_edge, Lr, brows(w.fhs, Lr), RAD_W(w_edge), RAD_W(b_edge), RAD_NONE,
|
||||
brows(w.edges, Lr));
|
||||
RAD_ISSUE_N(c, op_aout, n, brows(w.an, n), RAD_W(w_aout), RAD_W(b_aout), RAD_NONE,
|
||||
brows(w.aout, n));
|
||||
RAD_ISSUE_N(c, op_walk, n, brows(w.edges, Lr), brows(w.aout, n),
|
||||
brow_slice(w.cand, 0, Lr, 1), brows(w.tokens, n), RAD_NONE);
|
||||
(void)E; (void)hs; (void)fd;
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_LILICORR_H */
|
||||
@@ -52,9 +52,9 @@ struct MlpFP8 {
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* gate_up with the gate and quantiser in its epilogue, so the [M, 2*n_ff] bf16 product is
|
||||
* never written (unfused, the extra launch and second pass are a sizeable decode cost).
|
||||
* Declared beside the pair, not instead of it: the fold is the narrow tile's epilogue and
|
||||
* serves M <= 64, so prefill chunks take the pair. Byte-identical, as r4d_selftest and
|
||||
* ref_test check. */
|
||||
* Declared beside the pair, not instead of it: the narrow fold serves M <= 64, so prefill
|
||||
* chunks take the pair -- unless the model asked for `wide_fold`, whose row serves every M.
|
||||
* Byte-identical, as r4d_selftest and ref_test check. */
|
||||
rad_op op_gated = 0;
|
||||
int64_t gated_rows = 0;
|
||||
/* The next block absorbs this block's closing all-reduce, so this one must not issue it.
|
||||
@@ -67,19 +67,37 @@ struct MlpFP8 {
|
||||
/* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add
|
||||
* (false for the first block of a chain). `add_out`: issue the trailing add here. See
|
||||
* rad_fp8.h. */
|
||||
/* `wide_fold`: declare the gated fold over the whole prompt (gemm_nt_q_gated_wide, whose row
|
||||
* serves every M) rather than the narrow row's 64-row band. Set by a model that runs whole
|
||||
* prompts through the fold; every other caller keeps the band and the pair past it. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const Src& src, bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0);
|
||||
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0,
|
||||
bool wide_fold = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
|
||||
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
|
||||
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
|
||||
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
/* The slice in its parts, for a caller that runs the norm and the tail elsewhere (qwen35_fp8's
|
||||
* pipelined prefill puts both on the second lane): the projections from the normed input to
|
||||
* the delta in `w.h.x`, then the all-reduce and add this block issues itself. */
|
||||
void body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
void tail(RadCtx* c, int64_t r0, int64_t rows) const;
|
||||
/* The block's all-reduce over rows [r0, r0 + rows) of the output, at `overlap` where declared
|
||||
* (a caller that runs it beside other work). */
|
||||
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
}
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
};
|
||||
|
||||
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const Src& src, bool fold, bool add_out,
|
||||
int ar_in, bool ar_out_, double swiglu_limit) {
|
||||
int ar_in, bool ar_out_, double swiglu_limit, bool wide_fold) {
|
||||
g = geom; w = wire; layer = l;
|
||||
ar_out = ar_out_;
|
||||
|
||||
@@ -88,7 +106,12 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* Norm, quantise and residual add in one op (rad_fp8.h: NormQuantFP8). Folded, it adds the
|
||||
* previous block's delta from `h` into the stream; unfolded it reads the stream directly. */
|
||||
* previous block's delta from `h` into the stream; unfolded it reads the stream directly. The
|
||||
* plain form where gate|up does not read the code pair (NormQuantFP8::x_only; probed first). */
|
||||
if (g.plain_norm && ar_in == kArNone) {
|
||||
RAD_ARCH_TRY(gate_up.probe(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), { src.gate, src.up }));
|
||||
nq_h.x_only = gate_up.codes_free;
|
||||
}
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd, fold ? w.x : 0,
|
||||
0, ar_in));
|
||||
RAD_ARCH_TRY(gate_up.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l),
|
||||
@@ -101,22 +124,42 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
const char* down_base = nm.f("blk.%d.ffn_down", l);
|
||||
RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down }));
|
||||
gq_ffn.fuse_clamped = swiglu_quant;
|
||||
/* Under Geom::plain_norm a down projection that reads the bf16 plane and no codes (a 4-bit
|
||||
* one, which quantises its own activation) takes the plain product: `silu_mul`, no E4M3 pass. */
|
||||
if (g.plain_norm && down.codes_free && down.reads_x && swiglu_limit <= 0) gq_ffn.silu_only = true;
|
||||
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0,
|
||||
down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false,
|
||||
swiglu_limit));
|
||||
|
||||
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit
|
||||
* and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product.
|
||||
* Declared over int8 codes, only a host kernel would take it, and that would pin the layer's
|
||||
* weights to the host. */
|
||||
if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx &&
|
||||
!gate_up.m2x && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8)
|
||||
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
|
||||
* MXFP4 at one to 16 rows (eight where K is short), decl_gated_fold_iqr for an IQR weight
|
||||
* whose input and output are the rotated int8 trunk's fed pairs, to 16 rows. Other gate_up
|
||||
* encodings (M2XFP4 included), and a clamped (swiglu_limit) product, take the pair. */
|
||||
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
|
||||
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
|
||||
!gate_up.i8)
|
||||
op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
{ w.h.q, w.h.s },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
|
||||
&gated_rows);
|
||||
&gated_rows, wide_fold);
|
||||
else if (fold_ok && gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.ffn.q8_fed && w.ffn.q8_rot)
|
||||
op_gated = decl_gated_fold_iqr(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
{ w.h.q8, w.h.s8 },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8,
|
||||
w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8 },
|
||||
&gated_rows);
|
||||
else if (fold_ok && gate_up.mx && !gate_up.paro)
|
||||
op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
gate_up.wref, { w.h.q, w.h.s },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s,
|
||||
w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
|
||||
&gated_rows);
|
||||
RAD_ARCH_TRY(down.declare(b, nm, g, down_base,
|
||||
g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l),
|
||||
{ src.down }, w.ffn, w.h.x));
|
||||
@@ -129,6 +172,17 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar): at `overlap` 1
|
||||
* it gets the rows that hold fewer CUs while waiting on the link. */
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes),
|
||||
RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
|
||||
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
|
||||
if (add_out)
|
||||
@@ -149,17 +203,32 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
nq_h.step(c, T, r0, rows);
|
||||
if (op_gated && rows <= gated_rows) {
|
||||
body(c, T, r0, rows);
|
||||
tail(c, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (op_gated && rows <= gated_rows && gate_up.mx) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
|
||||
RAD_W(gate_up.ws), RAD_W(gate_up.wref), brow_slice(w.ffn.q, r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
|
||||
} else if (op_gated && rows <= gated_rows) {
|
||||
/* The fp8a8 fold's E4M3 pairs, or the IQR fold's int8 ones (cq / cs: the fed pair). */
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
|
||||
brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), brow_slice(w.ffn.cq(), r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.cs(), r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
|
||||
} else {
|
||||
gate_up.step(c, w.h, w.gate_up, T, r0, rows);
|
||||
gq_ffn.step(c, w.gate_up, T, r0, rows);
|
||||
}
|
||||
down.step(c, w.ffn, w.h.x, T, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::tail(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
if (op_ar && !(ar_out && ar_fused_ok(g, rows)))
|
||||
RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (op_add)
|
||||
|
||||
+537
-192
File diff suppressed because it is too large.
Load diff
@@ -90,6 +90,7 @@
|
||||
#define RAD_BLOCK_MTP_FP8_H
|
||||
|
||||
#include "rad_block_attn_gated_fp8.h"
|
||||
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire */
|
||||
#include "rad_block_mlp_fp8.h"
|
||||
#include "rad_block_vit.h"
|
||||
|
||||
@@ -134,8 +135,16 @@ struct MtpBlockFP8 {
|
||||
rad_buf ds = 0; /* [max_logit_rows, 1] f32, one scale a row */
|
||||
rad_buf dsum = 0; /* [n_embd/group, mpad] f32, group-major (quant_act_i8's asum) */
|
||||
rad_buf dlog = 0; /* [max_logit_rows, n_vocab] bf16, the coarse logits */
|
||||
rad_buf didx = 0; /* [max_logit_rows, 1] i32, the proposed token */
|
||||
rad_buf dval = 0; /* [max_logit_rows, 1] f32, its logit */
|
||||
rad_buf didx = 0; /* [max_logit_rows, topr] i32, the proposed token (column 0) */
|
||||
rad_buf dval = 0; /* [max_logit_rows, topr] f32, its logit */
|
||||
/* --draft-coupling: the shortlist is the top kCoupleR of the 2-bit logits, rescored
|
||||
* against the trunk's head (`logit_rerank`), and each round's `mtp_couple_propose` draws
|
||||
* x ~ Q from it into column 0: [max_seqs] draws and [depth, max_seqs] states, PERSIST
|
||||
* (abi/rad_spechub.h). Zero for the ordinary argmax at topr 1. */
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
int64_t topr = 1;
|
||||
/* Q's temperature over the rescored scores: exact at any value, it moves acceptance only */
|
||||
double q_temp = 1.0;
|
||||
/* The layer reuses the trunk's working set, which is dead by the time the head runs (a
|
||||
* second set would be 150 MiB). */
|
||||
AttnGatedFP8::Wire attn{};
|
||||
@@ -159,19 +168,26 @@ struct MtpBlockFP8 {
|
||||
int layer = 0; /* absolute, for the KV group's layer_slot lookup */
|
||||
int64_t rows = 0; /* the widest pass: one row per token of a prefill chunk */
|
||||
int64_t off_e = 0, off_h = 0; /* the two halves' column offsets inside `c` */
|
||||
rad_weight w_tok = 0, w_lm = 0, w_fc = 0, w_norm = 0, w_pre_h = 0, w_pre_e = 0;
|
||||
rad_weight w_tok = 0, w_lm = 0, w_norm = 0, w_pre_h = 0, w_pre_e = 0;
|
||||
/* `fc` in whatever form the container stores it: plain bf16 (gemm_nt, as the checkpoint) or a
|
||||
* 4-bit weight with a zero point (the w4a16 / w4a8i8 GEMMs), read from the bf16 `c` plane. */
|
||||
LinearFP8 fc{};
|
||||
ActFP8 a_c{};
|
||||
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit lm_head and its (scale, zero) plane */
|
||||
bool q2 = false; /* is the draft round reading it? */
|
||||
AttnGatedFP8 attn{};
|
||||
Ffn mlp{};
|
||||
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_pre_h = 0, op_pre_e = 0, op_fc = 0;
|
||||
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_pre_h = 0, op_pre_e = 0;
|
||||
/* Media rows over the head's embedding: the history pass embeds the prompt too (one position
|
||||
* on), and an image token's embedding comes from the encoder. Set `media` before declare when
|
||||
* the program has an encoder. */
|
||||
bool media = false;
|
||||
MediaRows mrows{};
|
||||
rad_op op_norm = 0, op_dsel = 0, op_dback = 0, op_logits = 0;
|
||||
rad_op op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
rad_op op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0;
|
||||
/* --draft-coupling: one op a round (the ABI freezes `round` as a parameter). */
|
||||
rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
|
||||
int depth = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup kv,
|
||||
int64_t rotary_dim, rad_weight tok_embd, rad_weight lm_head, float out_wadd,
|
||||
@@ -197,7 +213,6 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_hidden.weight"), src.pre_norm_hidden));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_embedding.weight"), src.pre_norm_embedding));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.norm.weight"), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.fc.weight"), src.fc));
|
||||
|
||||
w_pre_h = decl_w(b, nm.f("mtp.pre_fc_norm_hidden.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
@@ -205,8 +220,6 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_norm = decl_w(b, nm.f("mtp.norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_fc = decl_w(b, nm.f("mtp.fc.weight"), RAD_BF16, {g.n_embd, 2 * g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* Separate gather_rows and embed_lookup ops over the trunk's buffers and weights, because
|
||||
* they write different buffers and liveness comes from each op's read/write sets. */
|
||||
@@ -245,11 +258,9 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
RAD_WEIGHTS(w_pre_e)),
|
||||
{w.e}, {w.c});
|
||||
|
||||
op_fc = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", 2 * g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fc)),
|
||||
{w.c}, {w.x});
|
||||
a_c.x = w.c;
|
||||
RAD_ARCH_TRY(fc.declare(b, nm, g, "mtp.fc", g.n_embd, 2 * g.n_embd, RAD_SHARD_NONE, grp_layer(l),
|
||||
{ src.fc }, a_c, w.x, rows));
|
||||
|
||||
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn));
|
||||
|
||||
@@ -329,24 +340,52 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
|
||||
|
||||
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("N", g.n_vocab_all), RAD_INT("K", g.n_embd),
|
||||
RAD_INT("N", mtp_draft_rows(g.n_vocab_all)), RAD_INT("K", g.n_embd),
|
||||
RAD_INT("group", MTP_W2_GROUP), RAD_STR("dtype", "w2a8")),
|
||||
RAD_WEIGHTS(w_dh, w_dhs)),
|
||||
{w.dq, w.ds, w.dsum}, {w.dlog});
|
||||
|
||||
const bool couple = w.couple_draws || w.couple_state;
|
||||
if (couple && (!w.couple_draws || !w.couple_state || w.topr < 2 || g.world > 1 ||
|
||||
g.max_spec < 1 || g.max_spec > RAD_MTP_COUPLE_MAX_ROUNDS))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
op_dtopk = rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("N", g.n_vocab_all), RAD_INT("R", 1),
|
||||
RAD_INT("N", mtp_draft_rows(g.n_vocab_all)), RAD_INT("R", w.topr),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.didx, w.dval});
|
||||
if (couple) {
|
||||
/* The coarse shortlist rescored exactly against the trunk's head (already resident),
|
||||
* so Q is the softmax of the target's own logits over it; in place over idx/val. */
|
||||
op_drerank = RAD_OP(b, "logit_rerank",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("R", w.topr),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("vocab_off", g.vocab_off), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_lm));
|
||||
if (!op_drerank) return RAD_E_INVAL;
|
||||
const rad_buf rd[2] = { w.hout, w.didx };
|
||||
const rad_buf wr[2] = { w.didx, w.dval };
|
||||
RAD_ARCH_TRY(rad_op_reads(b, op_drerank, rd, 2));
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_drerank, wr, 2));
|
||||
depth = (int)g.max_spec;
|
||||
for (int round = 1; round <= depth; ++round) {
|
||||
op_couple[round - 1] = rw(b, RAD_OP(b, "mtp_couple_propose",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("round", round), RAD_INT("max_rounds", depth),
|
||||
RAD_F64("q_temp", w.q_temp)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.didx, w.dval, w.couple_draws }, { w.didx, w.couple_state });
|
||||
if (!op_couple[round - 1]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Keep `hout` live through the head's last op: it is the next round's input, and if only the
|
||||
* lm_head's first op read it, the planner could give its bytes to later ops (silently lowering
|
||||
* acceptance). */
|
||||
{
|
||||
const rad_op last = q2 ? op_dtopk : op_logits;
|
||||
const rad_op last = !q2 ? op_logits : op_couple[0] ? op_couple[depth - 1] : op_dtopk;
|
||||
if (rad_op_reads(b, last, &w.hout, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -379,7 +418,7 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE(c, op_pre_h, brows(w.hout, T), RAD_W(w_pre_h), bcol(w.c, off_h, g.n_embd, T));
|
||||
RAD_ISSUE(c, op_pre_e, brows(w.e, T), RAD_W(w_pre_e), bcol(w.c, off_e, g.n_embd, T));
|
||||
|
||||
RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
|
||||
fc.step(c, a_c, w.x, T);
|
||||
|
||||
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only needs
|
||||
* K and V. `n_draft_out` is the same on every rank, so skipped collectives match. */
|
||||
@@ -413,6 +452,21 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
brows(w.dlog, L), RAD_B(w.dsum), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
|
||||
RAD_NONE); /* the `pairs` slot, absent: operands are positional */
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
|
||||
brows(w.didx, L), brows(w.dval, L), RAD_NONE);
|
||||
/* After the rescored shortlist: column 0 is what the engine reads, and a sampled row
|
||||
* replaces it with its x. Round 1 runs in the history pass (r < 0). */
|
||||
if (op_couple[0]) {
|
||||
const int round = r < 0 ? 1 : r;
|
||||
if (round < 1 || round > depth) {
|
||||
rad_step_fail(c, "MTP coupled round exceeds the declared draft depth");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_couple[round - 1], L, brows(w.didx, L), brows(w.dval, L),
|
||||
praw(batch->seq_ids, RAD_I32, batch->n_seq),
|
||||
brows(w.couple_draws, L), RAD_B(w.couple_state));
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@
|
||||
#include "rad_block_hc.h"
|
||||
#include "rad_block_moe_fp8.h"
|
||||
#include "rad_block_mtp_fp8.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */
|
||||
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire */
|
||||
#include "rad_qsa.h"
|
||||
#include "rad_block_vit.h"
|
||||
|
||||
@@ -108,6 +109,9 @@ struct MtpHcBlock {
|
||||
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
|
||||
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
|
||||
rad_buf dpair = 0, dgath = 0;
|
||||
/* --draft-coupling: [max_seqs] draws and [depth, max_seqs] states, both PERSIST across
|
||||
* the serial passes (round 1 resets the logical stream, not the plane). */
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
AttnGatedFP8::Wire attn{};
|
||||
MoeFP8::Wire mlp{};
|
||||
QsaIndexer::Wire qsa{};
|
||||
@@ -148,6 +152,13 @@ struct MtpHcBlock {
|
||||
MoeFP8 mlp{};
|
||||
|
||||
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
|
||||
/* The selected draft calibration also records the bf16 attention input shared by
|
||||
* qg/k/v, independently of the expert gate's later input. */
|
||||
rad_buf b_attn_gram = 0;
|
||||
rad_op op_attn_gram = 0;
|
||||
const char* attn_gram_stem = nullptr;
|
||||
mutable int64_t attn_gram_rows = 0;
|
||||
mutable bool attn_gram_done = false;
|
||||
|
||||
/* Media rows over the head's embedding (see MtpBlockFP8::media). Set before declare when the
|
||||
* program has an encoder. */
|
||||
@@ -158,6 +169,9 @@ struct MtpHcBlock {
|
||||
rad_op op_dsel = 0, op_dback = 0;
|
||||
rad_op op_logits = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0;
|
||||
/* --draft-coupling: one op a round. The ABI freezes `round` as a parameter, so a round
|
||||
* cannot be an operand and each gets its own declared op. */
|
||||
rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
|
||||
|
||||
/* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
|
||||
* planes. */
|
||||
@@ -251,6 +265,20 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
* order. */
|
||||
RAD_ARCH_TRY(hc_attn.declare(b, nm, g, nm.f("mtp.attn_hc"), hc, HyperConn::Wire{w.hw, w.x, w.inj},
|
||||
src.hc_attn));
|
||||
if (src.mlp.cfg.calib) {
|
||||
/* Only a BF16 source supplies domain-0 inputs for this calibration. The input
|
||||
* is replicated, so each TP rank records the same width and GPTQ sums them. */
|
||||
if (!src.mlp.cfg.expert_bf16 || !w.attn.h.x) return RAD_E_UNSUPPORTED;
|
||||
attn_gram_stem = nm.f("blk.%d.attn_qg", l);
|
||||
b_attn_gram = decl_b(b, nm.f("blk.%d.mtp_attn_gram", l), RAD_F32,
|
||||
{g.n_embd, g.n_embd}, RAD_BUF_PERSIST);
|
||||
op_attn_gram = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.h.x, b_attn_gram}, {b_attn_gram});
|
||||
if (!b_attn_gram || !op_attn_gram) return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
|
||||
attn.ar_out_take = hc_attn.ar_take();
|
||||
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn,
|
||||
@@ -275,7 +303,11 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
/* The connection's read also writes the rotated expert input, as on the trunk. */
|
||||
HyperConn::Config mcfg = hc;
|
||||
HyperConn::Wire mwire{w.hw, w.x, w.inj};
|
||||
if (src.mlp.cfg.expert_rot) { mcfg.rotate = 1; mwire.rq = w.mlp.hr.q; mwire.rs = w.mlp.hr.s; }
|
||||
if (src.mlp.cfg.expert_rot && !w.x.q8_rot) {
|
||||
mcfg.rotate = 1;
|
||||
mwire.rq = w.mlp.hr.cq();
|
||||
mwire.rs = w.mlp.hr.cs();
|
||||
}
|
||||
RAD_ARCH_TRY(hc_mlp.declare(b, nm, g, nm.f("mtp.ffn_hc"), mcfg, mwire, src.hc_mlp));
|
||||
mlp.ar_out_take = hc_mlp.ar_take();
|
||||
mlp.hr_in = mcfg.rotate != 0;
|
||||
@@ -422,6 +454,25 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
if (!op_dgather || !op_dmerge) return RAD_E_INVAL;
|
||||
}
|
||||
if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
|
||||
/* The coupled proposal: one op a round, after the final rerank/merge, over the shortlist
|
||||
* whose column 0 is the proposal. Linear chains only: x is a token, while a tree reads
|
||||
* column 0 as a parent index. The engine refuses other drafters; this check keeps a
|
||||
* mismatched declaration from writing tokens into a tree plane. */
|
||||
if (w.couple_draws || w.couple_state) {
|
||||
if (!w.couple_draws || !w.couple_state || depth < 1 ||
|
||||
depth > RAD_MTP_COUPLE_MAX_ROUNDS || !op_drerank || (g.world > 1 && !op_dmerge))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
for (int round = 1; round <= depth; ++round) {
|
||||
op_couple[round - 1] = rw(b, RAD_OP(b, "mtp_couple_propose",
|
||||
/* The whole vocabulary: `row_topk` reports global ids and the merge keeps
|
||||
* them, while `g.n_vocab` is this rank's shard. */
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("round", round), RAD_INT("max_rounds", depth)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.didx, w.dval, w.couple_draws }, { w.didx, w.couple_state });
|
||||
if (!op_couple[round - 1]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Keep the carry `hin` live through the head's last op: it is written before the mixer and
|
||||
* lm_head run, and the planner could otherwise give its bytes to them (silently lowering
|
||||
@@ -429,6 +480,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{
|
||||
rad_op last = op_logits;
|
||||
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
|
||||
if (op_couple[0]) last = op_couple[depth - 1];
|
||||
if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -440,6 +492,17 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int r = batch->draft_pass;
|
||||
/* Expert calibration needs real draft-layer inputs, not the trunk's Hessian. In a
|
||||
* selected calibration layer, run the history's teacher-forced rows through the full
|
||||
* draft block before selecting the rows needed by the drafter. Normal inference and
|
||||
* a tap that has reached its target retain the ordinary history-only fast path. */
|
||||
const bool tap_history = r < 0 && mlp.c.calib && !mlp.calib_done;
|
||||
/* serial_batch names one trunk hidden row per history token. Refuse an incomplete
|
||||
* gather instead of silently calibrating stale hin rows if that contract changes. */
|
||||
if (tap_history && (batch->n_out != T || !batch->out_ids)) {
|
||||
rad_step_fail(c, "MTP calibration needs one trunk hidden row per history token");
|
||||
return;
|
||||
}
|
||||
|
||||
/* The history pass continues from the trunk's wide stream; later rounds from the head's,
|
||||
* which the carry left in the same buffer. */
|
||||
@@ -462,11 +525,26 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
|
||||
|
||||
hc_attn.read_pieces(c, T);
|
||||
if (tap_history && op_attn_gram && !attn_gram_done) {
|
||||
if (attn_gram_rows == 0)
|
||||
rad_memset_async(rad_buf_ptr(c, b_attn_gram), 0,
|
||||
g.n_embd * g.n_embd * 4, rad_stream(c));
|
||||
RAD_ISSUE_N(c, op_attn_gram, T, brows(w.attn.h.x, T), RAD_NONE,
|
||||
brows(b_attn_gram, g.n_embd));
|
||||
attn_gram_rows += T;
|
||||
if (attn_gram_rows >= calib_target()) {
|
||||
if (!calib_write(c, b_attn_gram, g.n_embd, attn_gram_rows, attn_gram_stem, 0)) {
|
||||
rad_step_fail(c, "MTP calibration could not write its attention input Gram");
|
||||
return;
|
||||
}
|
||||
attn_gram_done = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only stores
|
||||
* the head's state: K and V, and the indexer's block keys and tail. `n_draft_out` is the same
|
||||
* on every rank, so skipped collectives match. */
|
||||
if (r < 0 && batch->n_draft_out <= 0) {
|
||||
if (r < 0 && batch->n_draft_out <= 0 && !tap_history) {
|
||||
qsa.store(c, attn.w.h, batch);
|
||||
attn.store_kv(c, batch);
|
||||
return;
|
||||
@@ -474,7 +552,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
/* The indexer runs first because the attention reads its selection; `w.h` is already final,
|
||||
* written by the connection above. */
|
||||
qsa.step(c, attn.w.h, batch, qsa_win_cu);
|
||||
qsa.step(c, attn.w.h, batch, qsa_win_cu, attn.qsa_use(batch));
|
||||
attn.step(c, batch);
|
||||
|
||||
hc_attn.write(c, T, 0, T);
|
||||
@@ -482,7 +560,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
/* A history pass with drafting rows continues on those rows alone (round 1): they are moved
|
||||
* to the front of `hw` and the rest of the head runs over them. */
|
||||
int64_t L = T; /* the rows the stream goes on with */
|
||||
if (r < 0) {
|
||||
if (r < 0 && !tap_history) {
|
||||
L = batch->n_draft_out;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.hin, L));
|
||||
@@ -493,6 +571,16 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
mlp.step_rows(c, L);
|
||||
hc_mlp.write(c, L, 0, L);
|
||||
|
||||
if (tap_history) {
|
||||
/* History-only chunks have no proposal. For the last chunk, select the same
|
||||
* round-1 rows the ordinary path would have selected before its feed-forward. */
|
||||
L = batch->n_draft_out;
|
||||
if (L <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.hin, L));
|
||||
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
|
||||
}
|
||||
|
||||
/* The carry, only if a later round reads it: a history pass is round 1, followed by round 2
|
||||
* when depth > 1; the last round is followed by a trunk step. */
|
||||
if (r < 0 ? depth > 1 : r < depth)
|
||||
@@ -524,6 +612,19 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
|
||||
brows(w.didx, L), brows(w.dval, L), RAD_NONE);
|
||||
}
|
||||
/* After the final reranked shortlist: column 0 is what ADV_TAKE reads, and a sampled row
|
||||
* replaces it with its x. Round 1 runs in the history pass (r < 0), later rounds in their
|
||||
* own passes. */
|
||||
if (op_couple[0]) {
|
||||
const int round = r < 0 ? 1 : r;
|
||||
if (round < 1 || round > depth) {
|
||||
rad_step_fail(c, "MTP coupled round exceeds the declared draft depth");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_couple[round - 1], L, brows(w.didx, L), brows(w.dval, L),
|
||||
praw(batch->seq_ids, RAD_I32, batch->n_seq),
|
||||
brows(w.couple_draws, L), RAD_B(w.couple_state));
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,584 @@
|
||||
/* rad_block_museglimmer_vision.h -- Muse Glimmer's vision tower (transformers'
|
||||
* MuseGlimmerVisionModel, an InternVit-shaped stack), its adapter and the perception norm, served
|
||||
* by museglimmer.
|
||||
*
|
||||
* What it computes, per encoder pass (RadBatch::enc), in the reference's order:
|
||||
*
|
||||
* x = patches @ Wp^T the patch embedding as a linear layer, bias-less;
|
||||
* a patch row is (temporal, channel, y, x)
|
||||
* x += position table resampled to the grid `grid_embed_pad`, bilinear at half-pixel
|
||||
* centres, align_corners=False, out-of-range taps
|
||||
* zero-weighted (grid_sample padding zeros)
|
||||
* x = LN_pre(x) LayerNorm, eps `layer_norm_eps`
|
||||
* x = x[window order] `window_order`: the 32x32-patch window permutation
|
||||
* (per frame, ragged edges smaller windows), its
|
||||
* inverse, per-slot rotary positions and the
|
||||
* per-window cumulative boundaries
|
||||
* depth times:
|
||||
* h = LN1(x) LayerNorm, eps 1e-5 (the blocks hard-code it)
|
||||
* q|k|v = qkv(h) the reference's three biased projections, joined
|
||||
* q first into one GEMM as the reference's fused
|
||||
* tensors would read
|
||||
* rope(q, k) `rope` axial, the whole head, sections
|
||||
* head_dim/4 a side on theta^(-j/(head_dim/4)),
|
||||
* positions (column + 1, row + 1) -- HF's
|
||||
* position_ids.flip(-1) + 1
|
||||
* x += proj(attn(q, k, v)) non-causal, scale 1/sqrt(head_dim). A
|
||||
* window_attention layer attends within one window
|
||||
* (cu = the per-window boundaries in permuted
|
||||
* order); a full_attention layer attends within
|
||||
* its frame (cu = the frame boundaries). The
|
||||
* window permutation never moves a patch across
|
||||
* frames, so the frame boundaries among permuted
|
||||
* rows are the boundaries among natural rows:
|
||||
* `enc_cu` is passed unchanged, exactly what the
|
||||
* reference passes (modeling_muse_glimmer.py maps
|
||||
* full_attention to the frame cu_seqlens while the
|
||||
* rows stay permuted).
|
||||
* x += fc2(gelu(fc1(LN2(x)))) both biased; `gelu` the exact erf form the
|
||||
* config's hidden_act names, in gemm_nt_bias's
|
||||
* epilogue
|
||||
* x = x[inv] the window order undone (gather_rows)
|
||||
* x = LN_post(x) LayerNorm, eps `layer_norm_eps`
|
||||
* y = pixel_shuffle(x) the merge (`pixtral_merge`): each 2x2 block's
|
||||
* four patches fold into one row of merge^2 *
|
||||
* width, channels interleaved -- the reference's
|
||||
* [block, merge^2, dim].permute(0, 2, 1)
|
||||
* y = gelu(fc2(gelu(fc1(y)))) the adapter: both linears bias-less, TWO
|
||||
* activations (projector_hidden_act)
|
||||
* y = y @ Wproj^T the projection, bias-less, the model's width
|
||||
* out = rms(y) `perception_emb_norm`, a weightless RMS norm at
|
||||
* the TEXT model's rms_norm_eps
|
||||
*
|
||||
* The reference permutes AFTER ln_pre, so the tower works in window order and un-permutes before
|
||||
* ln_post, exactly as above. The processor stages patches in the reference's raster order; the
|
||||
* merge is a real fold (not a view: the reference interleaves the four patches' channels, which
|
||||
* four consecutive rows do not spell), and its output is what the adapter reads.
|
||||
*
|
||||
* Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the
|
||||
* weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx::
|
||||
* max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's
|
||||
* step; the attention's longest segment stays at the real pass so the kernel rows do not move.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MUSEGLIMMER_VISION_H
|
||||
#define RAD_BLOCK_MUSEGLIMMER_VISION_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct MuseTower {
|
||||
/* Geometry, from the container's vision_config (never aliased: only the full prefix). The
|
||||
* adapter's widths are top-level keys of the family config. */
|
||||
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0;
|
||||
int64_t merge = 0, side = 0, npos = 0, proj_ff = 0, out_hidden = 0, n_embd = 0;
|
||||
int64_t patch_dim = 0, P = 0;
|
||||
double eps = 1e-5; /* ln_pre / ln_post; the blocks hard-code 1e-5 */
|
||||
float theta = 10000.0f;
|
||||
bool on = false;
|
||||
|
||||
struct Layer {
|
||||
bool full = false; /* full_attention: frame-wide attention, NoPE-free (rotary runs
|
||||
* on every layer of this tower, full or window) */
|
||||
rad_weight n1w = 0, n1b = 0, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
|
||||
rad_weight n2w = 0, n2b = 0, up_w = 0, up_b = 0, down_w = 0, down_b = 0;
|
||||
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
|
||||
int64_t max_seg = 0; /* the kernel band's longest segment */
|
||||
};
|
||||
std::vector<Layer> L;
|
||||
rad_weight w_patch = 0, w_pos = 0, lw_pre = 0, lb_pre = 0, lw_post = 0, lb_post = 0;
|
||||
rad_weight w_a1 = 0, w_a2 = 0, w_proj = 0;
|
||||
rad_op op_patch = 0, op_pos = 0, op_lpre = 0, op_wo = 0, op_gidx = 0, op_ginv = 0;
|
||||
rad_op op_lpost = 0, op_merge = 0, op_m1 = 0, op_g1 = 0, op_m2 = 0, op_g2 = 0, op_proj = 0,
|
||||
op_perc = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_p = 0, b_qkv = 0, b_att = 0, b_ff = 0;
|
||||
rad_buf b_idx = 0, b_inv = 0, b_pos = 0, b_cuw = 0;
|
||||
rad_buf b_mh = 0, b_m1 = 0, b_m2 = 0, b_out = 0;
|
||||
char sec[48] = {};
|
||||
|
||||
/* Whether the container carries this family's tower. */
|
||||
static bool present(const RadModelMeta* m) {
|
||||
return rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int MuseTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
|
||||
Names& nm, int64_t model_embd, int first_group) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
|
||||
depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
|
||||
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
|
||||
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
|
||||
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
|
||||
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
|
||||
temporal = rad_meta_geti(m, "vision_config.patch_temporal", 2);
|
||||
merge = rad_meta_geti(m, "vision_config.merge_size", 2);
|
||||
side = rad_meta_geti(m, "vision_config.pos_emb_height", 0);
|
||||
npos = rad_meta_geti(m, "vision_config.pos_emb_height", 0) *
|
||||
rad_meta_geti(m, "vision_config.pos_emb_width", 0);
|
||||
eps = rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-5);
|
||||
theta = (float)rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0);
|
||||
proj_ff = rad_meta_geti(m, "projector_hidden_size", 4096);
|
||||
out_hidden = rad_meta_geti(m, "out_hidden_size", 6144);
|
||||
n_embd = model_embd;
|
||||
/* Bounds the walk and the host allocations below take at face value, set against published
|
||||
* maxima rather than round numbers: the deepest vision encoder ever shipped is 48 layers
|
||||
* (ViT-22B, InternViT-6B; this family's towers are SigLIP-class, tens), and the largest
|
||||
* stored position table a side of 92 (SigLIP at 1292 px over patch 14; CLIP 16, SAM 64 --
|
||||
* native-resolution towers store no side x side table at all). The caps sit ~2.6x and
|
||||
* ~5.5x past those maxima, so they never bite an honest container, and at the cap the
|
||||
* guarded shapes are harmless: the depth vectors cost KiB and the grid products reach 2^18
|
||||
* at most. Past the caps the container is not describing a model but a vector size
|
||||
* (full.assign(depth) and L.assign(depth) would throw past max_size, and the grid products
|
||||
* below overflow signed 64 before any comparison could notice). Refuse like every other
|
||||
* bad config: say so and RAD_E_INVAL. */
|
||||
if (depth <= 0 || depth > 128 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 ||
|
||||
temporal <= 0 || merge <= 0 || side <= 0 || side > 512 || proj_ff <= 0 ||
|
||||
out_hidden <= 0 || width % heads ||
|
||||
rad_meta_geti(m, "vision_config.pos_emb_width", 0) != side) {
|
||||
fprintf(stderr, "radiance: museglimmer: the container's vision_config is incomplete, "
|
||||
"inconsistent, or past what this tower walks (depth %lld, hidden %lld, "
|
||||
"heads %lld, ff %lld, patch %lld, "
|
||||
"temporal %lld, merge %lld, position grid %lld x %lld, projector %lld, "
|
||||
"merged %lld)\n", (long long)depth, (long long)width, (long long)heads,
|
||||
(long long)ff, (long long)patch, (long long)temporal, (long long)merge,
|
||||
(long long)side, (long long)rad_meta_geti(m, "vision_config.pos_emb_width", 0),
|
||||
(long long)proj_ff, (long long)out_hidden);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The merge is `pixtral_merge`, whose kernels fold a 2x2 block: the only factor Muse Glimmer
|
||||
* ships and the only one the op serves. */
|
||||
if (merge != 2) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower states merge_size %lld; the "
|
||||
"merge op folds a 2x2 block\n", (long long)merge);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The exact-erf GELU is what this tower and its adapter state; another activation is another
|
||||
* tower (the reference would compute a different function). */
|
||||
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu");
|
||||
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
|
||||
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial");
|
||||
if (std::strcmp(act, "gelu") || std::strcmp(pact, "gelu")) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower has hidden_act '%s' and "
|
||||
"projector_hidden_act '%s'; it serves the exact gelu both call for\n",
|
||||
act, pact);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* `axial` is Meta's spelling and `default` NVIDIA's ModelOpt export of the same tower: the
|
||||
* reference's vision embedder has one rotary (axial), so both name it. Anything else is
|
||||
* another tower. */
|
||||
if (std::strcmp(rt, "axial") && std::strcmp(rt, "default")) {
|
||||
fprintf(stderr, "radiance: museglimmer: this vision tower states rope_type '%s'; it "
|
||||
"serves the axial 2-D rotary the tower's rotary embedder raises on "
|
||||
"leaving\n", rt);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The tower's full layers: every fourth, counted from the start, plus the last (the config's
|
||||
* own rule, MuseGlimmerVisionConfig.__post_init__). The shipped array must say the same
|
||||
* thing; a window layer where the rule puts a full one changes what the model saw. */
|
||||
std::vector<int> full;
|
||||
const char* kinds = rad_meta_gets(m, "vision_config.layer_types", "");
|
||||
if (kinds && *kinds) {
|
||||
RAD_ARCH_TRY(parse_layer_kinds("museglimmer vision", kinds, {"full_attention"},
|
||||
"window_attention", &full));
|
||||
if ((int64_t)full.size() != depth) {
|
||||
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types names %zu layers "
|
||||
"and the tower has %lld\n", full.size(), (long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int64_t l = 0; l < depth; ++l) {
|
||||
const bool rule = is_full_attention(l, 4) || l == depth - 1;
|
||||
if ((full[(size_t)l] != 0) != rule) {
|
||||
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types makes tower "
|
||||
"layer %lld %s and the family rule (every fourth from the first, "
|
||||
"plus the last) makes it %s\n", (long long)l,
|
||||
full[(size_t)l] ? "full" : "window", rule ? "full" : "window");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
full.assign((size_t)depth, 0);
|
||||
for (int64_t l = 0; l < depth; ++l)
|
||||
full[(size_t)l] = is_full_attention(l, 4) || l == depth - 1;
|
||||
}
|
||||
|
||||
head_dim = width / heads;
|
||||
patch_dim = 3 * temporal * patch * patch;
|
||||
/* The 2-D rotary: half the head a side, each on its own ladder (arange(0, head_dim/2, 2)
|
||||
* frequencies, sections head_dim/4 a side). */
|
||||
if (head_dim % 4) return RAD_E_SHAPE;
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4),
|
||||
(long long)(head_dim / 4));
|
||||
/* The merger's rows replace token embeddings, so they must be the model's width. */
|
||||
if (out_hidden != merge * merge * width) {
|
||||
fprintf(stderr, "radiance: museglimmer: out_hidden_size %lld is not merge %lld squared "
|
||||
"times the tower's width %lld, whose view the adapter's first layer "
|
||||
"reads\n", (long long)out_hidden, (long long)merge, (long long)width);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The tower emits merged rows the width of the model's tokens: the caller passes the model's
|
||||
* width and the projection is declared at it, so no separate check exists. */
|
||||
|
||||
const int64_t mm = merge * merge;
|
||||
P = ctx->max_enc_patches;
|
||||
if (ctx->shape_probe) {
|
||||
/* A sizing declare: rows follow the probe's step (rounded to whole merged rows), keeping
|
||||
* the activations out of the levels a decode step runs at. The kernel bands stay at the
|
||||
* real pass: the engine runs the real declare's kernels at every level. */
|
||||
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
|
||||
P = std::max<int64_t>(mm, r / mm * mm);
|
||||
}
|
||||
if (P % mm) return RAD_E_SHAPE;
|
||||
const int64_t R = P / mm;
|
||||
const int64_t ACC = RAD_ACCESS_PER_REQUEST;
|
||||
/* The window side in patches (the reference states it in pixels and divides by patch_size).
|
||||
* A window_attention layer's longest segment is one window. */
|
||||
const int64_t win_seg = side * side;
|
||||
|
||||
/* ---- weights, replicated. Model-level groups for the stem and the adapter; one group per
|
||||
* block from `first_group` on, so a tower block is its own movement unit. */
|
||||
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
w_patch = bw(nm.f("v.patch.weight"),
|
||||
nm.ckpt("model.vision_tower.patch_embedder.patch_embedding.weight"),
|
||||
{ width, patch_dim }, grp_model());
|
||||
w_pos = bw(nm.f("v.pos.weight"),
|
||||
nm.ckpt("model.vision_tower.patch_embedder.position_embedding_table.weight"),
|
||||
{ npos, width }, grp_model());
|
||||
lw_pre = bw(nm.f("v.lnpre.weight"), nm.ckpt("model.vision_tower.ln_pre.weight"), { width },
|
||||
grp_model());
|
||||
lb_pre = bw(nm.f("v.lnpre.bias"), nm.ckpt("model.vision_tower.ln_pre.bias"), { width },
|
||||
grp_model());
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
const int li = (int)i;
|
||||
auto src = [&](const char* s) { return nm.ckpt("model.vision_tower.layers.%d.%s", li, s); };
|
||||
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
|
||||
l.n1w = bw(dn("norm1.weight"), src("norm1.weight"), { width }, g);
|
||||
l.n1b = bw(dn("norm1.bias"), src("norm1.bias"), { width }, g);
|
||||
/* The reference's three biased projections, joined q | k | v into one GEMM. */
|
||||
if (map_concat(b, dn("qkv.weight"),
|
||||
{ src("attn.q_proj.weight"), src("attn.k_proj.weight"),
|
||||
src("attn.v_proj.weight") }) < 0)
|
||||
return RAD_E_INVAL;
|
||||
l.qkv_w = decl_w(b, dn("qkv.weight"), RAD_BF16, { 3 * width, width }, ACC,
|
||||
RAD_SHARD_NONE, g, 0, { width, width, width });
|
||||
if (map_concat(b, dn("qkv.bias"),
|
||||
{ src("attn.q_proj.bias"), src("attn.k_proj.bias"),
|
||||
src("attn.v_proj.bias") }) < 0)
|
||||
return RAD_E_INVAL;
|
||||
l.qkv_b = decl_w(b, dn("qkv.bias"), RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g, 0,
|
||||
{ width, width, width });
|
||||
l.out_w = bw(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g);
|
||||
l.out_b = bw(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
|
||||
l.n2w = bw(dn("norm2.weight"), src("norm2.weight"), { width }, g);
|
||||
l.n2b = bw(dn("norm2.bias"), src("norm2.bias"), { width }, g);
|
||||
l.up_w = bw(dn("fc1.weight"), src("mlp.fc1.weight"), { ff, width }, g);
|
||||
l.up_b = bw(dn("fc1.bias"), src("mlp.fc1.bias"), { ff }, g);
|
||||
l.down_w= bw(dn("fc2.weight"), src("mlp.fc2.weight"), { width, ff }, g);
|
||||
l.down_b= bw(dn("fc2.bias"), src("mlp.fc2.bias"), { width }, g);
|
||||
if (!l.n1w || !l.n1b || !l.qkv_w || !l.qkv_b || !l.out_w || !l.out_b || !l.n2w || !l.n2b ||
|
||||
!l.up_w || !l.up_b || !l.down_w || !l.down_b)
|
||||
return RAD_E_INVAL;
|
||||
l.full = full[(size_t)i] != 0;
|
||||
l.max_seg = l.full ? ctx->max_enc_patches : win_seg;
|
||||
}
|
||||
lw_post = bw(nm.f("v.lnpost.weight"), nm.ckpt("model.vision_tower.ln_post.weight"), { width },
|
||||
grp_model());
|
||||
lb_post = bw(nm.f("v.lnpost.bias"), nm.ckpt("model.vision_tower.ln_post.bias"), { width },
|
||||
grp_model());
|
||||
w_a1 = bw(nm.f("v.mlp.fc1.weight"), nm.ckpt("model.vision_adapter.fc1.weight"),
|
||||
{ proj_ff, out_hidden }, grp_model());
|
||||
w_a2 = bw(nm.f("v.mlp.fc2.weight"), nm.ckpt("model.vision_adapter.fc2.weight"),
|
||||
{ proj_ff, proj_ff }, grp_model());
|
||||
w_proj = bw(nm.f("v.proj.weight"), nm.ckpt("model.vision_projection.weight"),
|
||||
{ n_embd, proj_ff }, grp_model());
|
||||
if (!w_patch || !w_pos || !lw_pre || !lb_pre || !lw_post || !lb_post || !w_a1 || !w_a2 ||
|
||||
!w_proj)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- activations. `mh` holds the merged rows: `pixtral_merge` folds each 2x2 block's four
|
||||
* patch rows into one row of mm * width in the reference's pixel_shuffle layout, and the
|
||||
* adapter's first layer reads it. */
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
|
||||
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
|
||||
b_p = decl_b(b, nm.f("v.p"), RAD_BF16, { P, width });
|
||||
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
|
||||
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
|
||||
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
|
||||
b_idx = decl_b(b, nm.f("v.idx"), RAD_I32, { P });
|
||||
b_inv = decl_b(b, nm.f("v.inv"), RAD_I32, { P });
|
||||
b_pos = decl_b(b, nm.f("v.pos"), RAD_I32, { 2, P });
|
||||
b_cuw = decl_b(b, nm.f("v.cuw"), RAD_I32, { P + 1 });
|
||||
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mm * width });
|
||||
b_m1 = decl_b(b, nm.f("v.m1"), RAD_BF16, { R, proj_ff });
|
||||
b_m2 = decl_b(b, nm.f("v.m2"), RAD_BF16, { R, proj_ff });
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
|
||||
if (!b_x || !b_h || !b_p || !b_qkv || !b_att || !b_ff || !b_idx || !b_inv || !b_pos || !b_cuw ||
|
||||
!b_mh || !b_m1 || !b_m2 || !b_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
|
||||
rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto lnorm = [&](int64_t rows, int64_t n, double e, rad_weight w, rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", e),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto attn_op = [&](int64_t max_seg) -> rad_op {
|
||||
return RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
|
||||
RAD_INT("max_seqlen", max_seg)),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
|
||||
/* The stem is bias-less (the reference's patch_embedding states no bias). */
|
||||
op_patch = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
|
||||
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_patch)),
|
||||
{}, { b_x });
|
||||
op_pos = rw(b, RAD_OP(b, "grid_embed_pad",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_pos)),
|
||||
{ b_x }, { b_x });
|
||||
op_lpre = rw(b, lnorm(P, width, eps, lw_pre, lb_pre), { b_x }, { b_h });
|
||||
op_wo = rw(b, RAD_OP(b, "window_order",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("window", side)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_idx, b_inv, b_pos, b_cuw });
|
||||
op_gidx = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_h, b_idx }, { b_p });
|
||||
for (Layer& l : L) {
|
||||
l.ln1 = rw(b, lnorm(P, width, 1e-5, l.n1w, l.n1b), { b_p }, { b_h });
|
||||
l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
|
||||
l.rope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
|
||||
RAD_F64("theta", theta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", "axial"),
|
||||
RAD_INT("rotary_dim", head_dim),
|
||||
RAD_STR("sections", sec)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_qkv, b_pos }, { b_qkv });
|
||||
/* A window layer's segment bounds are the order op's per-window cu; a full layer's are
|
||||
* the pass's frame bounds, raw (the permutation is within frames, so they read the same
|
||||
* values in permuted order). */
|
||||
l.attn = rw(b, attn_op(l.max_seg),
|
||||
l.full ? std::initializer_list<rad_buf>{ b_qkv }
|
||||
: std::initializer_list<rad_buf>{ b_qkv, b_cuw },
|
||||
{ b_att });
|
||||
l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_p }, { b_p });
|
||||
l.ln2 = rw(b, lnorm(P, width, 1e-5, l.n2w, l.n2b), { b_p }, { b_h });
|
||||
l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff });
|
||||
l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_p }, { b_p });
|
||||
}
|
||||
op_ginv = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_p, b_inv }, { b_x });
|
||||
op_lpost = rw(b, lnorm(P, width, eps, lw_post, lb_post), { b_x }, { b_x });
|
||||
/* The reference's pixel_shuffle: each 2x2 block's four patches fold into one row with the
|
||||
* channels interleaved (block, channel, sub-patch), which is `pixtral_merge`'s layout. A view
|
||||
* over four consecutive rows cannot produce it: the concatenated form is a different tensor. */
|
||||
op_merge = rw(b, RAD_OP(b, "pixtral_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("merge", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_x }, { b_mh });
|
||||
/* The adapter: both linears bias-less, gelu between and after (the reference's
|
||||
* act(fc2(act(fc1(x))))). */
|
||||
op_m1 = rw(b, gemm(R, proj_ff, mm * width, w_a1), { b_mh }, { b_m1 });
|
||||
op_g1 = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_m1 }, { b_m2 });
|
||||
op_m2 = rw(b, gemm(R, proj_ff, proj_ff, w_a2), { b_m2 }, { b_m1 });
|
||||
op_g2 = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_m1 }, { b_m2 });
|
||||
op_proj = rw(b, gemm(R, n_embd, proj_ff, w_proj), { b_m2 }, { b_out });
|
||||
/* perception_emb_norm: MuseGlimmerRMSNorm(eps = the TEXT model's rms_norm_eps, with_scale
|
||||
* False) -- no gain operand, no centered 1+. */
|
||||
op_perc = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
|
||||
RAD_F64("eps", m->rms_eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_out }, { b_out });
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = mm;
|
||||
e.max_patches = ctx->max_enc_patches;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
int64_t nfull = 0;
|
||||
for (int64_t l = 0; l < depth; ++l) nfull += full[(size_t)l];
|
||||
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x "
|
||||
"%lld x %lld, merge %lld, windows of %lld patches (%lld full attention); "
|
||||
"%lld patches a pass -> %lld rows of %lld",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
|
||||
(long long)ff, (long long)temporal, (long long)patch, (long long)patch,
|
||||
(long long)merge, (long long)side, (long long)nfull, (long long)P, (long long)R,
|
||||
(long long)n_embd);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Stage taps, the same protocol as rad_block_sam.h's: RADIANCE_DEBUG_MM_BUFFERS names stages
|
||||
* (comma separated, matched as substrings) and RADIANCE_DEBUG_MM_DUMP's directory receives
|
||||
* tap.<tag>.bf16 -- raw bf16 rows, one file a stage. The copy is issued on the pass's stream
|
||||
* behind the producing op and synced, so it reads that op's output rather than whatever writes
|
||||
* the buffer later (the after-pass dump in core/engine_mm.cpp cannot see intermediates). */
|
||||
inline void muse_tap(RadCtx* c, const char* tag, rad_buf b, int64_t rows, int64_t cols) {
|
||||
static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP");
|
||||
static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
|
||||
if (!dir || !*dir || !env || !*env || rows <= 0 || cols <= 0 || rad_rank(c) != 0) return;
|
||||
bool want = false;
|
||||
const size_t tl = std::strlen(tag);
|
||||
for (const char* s = env; *s && !want;) {
|
||||
const char* e = s;
|
||||
while (*e && *e != ',') ++e;
|
||||
const size_t l = (size_t)(e - s);
|
||||
for (size_t i = 0; l && i + l <= tl && !want; ++i)
|
||||
want = std::strncmp(tag + i, s, l) == 0;
|
||||
s = *e ? e + 1 : e;
|
||||
}
|
||||
if (!want) return;
|
||||
void* p = rad_buf_ptr(c, b);
|
||||
if (!p) return;
|
||||
std::vector<uint16_t> h((size_t)(rows * cols));
|
||||
if (rad_memcpy_async(h.data(), p, (size_t)(rows * cols * 2), rad_stream(c)) < 0) return;
|
||||
rad_stream_sync(rad_stream(c));
|
||||
char path[512];
|
||||
std::snprintf(path, sizeof path, "%s/tap.%s.bf16", dir, tag);
|
||||
if (FILE* f = std::fopen(path, "wb")) {
|
||||
std::fwrite(h.data(), sizeof(uint16_t), h.size(), f);
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
inline void MuseTower::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
const int64_t mm = merge * merge, Rn = Pn / mm;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0 || !batch->enc_coord || !batch->enc_cu ||
|
||||
!batch->enc_seg_h || !batch->enc_seg_w || !batch->enc_pixels) {
|
||||
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or "
|
||||
"more patches than it was declared for, or not whole merged rows");
|
||||
return;
|
||||
}
|
||||
/* Windows per frame, from the pass's host grids: the window layers' cu is the per-window
|
||||
* boundaries among permuted rows, `n_win + 1` entries of the order op's output. */
|
||||
int64_t n_win = 0;
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
n_win += (batch->enc_seg_h[s] + side - 1) / side * ((batch->enc_seg_w[s] + side - 1) / side);
|
||||
if (n_win > P) {
|
||||
rad_step_fail(c, "an encoder pass whose window count exceeds the tower's declared rows");
|
||||
return;
|
||||
}
|
||||
/* Patches, coordinates (planes 0-3: row, column, segment height, segment width, in patches)
|
||||
* and the frame boundaries, staged by the core. The full layers read the frame boundaries
|
||||
* unchanged: the window permutation is within frames, so the boundaries among permuted rows
|
||||
* are these values (the reference passes its cu_seqlens the same way). */
|
||||
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
|
||||
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
RadOperand cuw = RAD_B(b_cuw);
|
||||
cuw.rows = n_win + 1;
|
||||
RadOperand pos = RAD_B(b_pos);
|
||||
pos.rows = 2;
|
||||
pos.cols = Pn;
|
||||
|
||||
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
|
||||
muse_tap(c, "v.patchpos", b_x, Pn, width);
|
||||
RAD_ISSUE_N(c, op_lpre, Pn, brows(b_x, Pn), RAD_W(lw_pre), RAD_W(lb_pre), brows(b_h, Pn));
|
||||
muse_tap(c, "v.lnpre", b_h, Pn, width);
|
||||
RAD_ISSUE_N(c, op_wo, Pn, crd, cu, brows(b_idx, Pn), brows(b_inv, Pn), pos, cuw);
|
||||
RAD_ISSUE_N(c, op_gidx, Pn, brows(b_h, Pn), brows(b_idx, Pn), brows(b_p, Pn));
|
||||
for (size_t li = 0; li < L.size(); ++li) {
|
||||
const Layer& l = L[li];
|
||||
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_p, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
|
||||
brows(b_qkv, Pn));
|
||||
RAD_ISSUE_N(c, l.rope, Pn, brows(b_qkv, Pn), pos);
|
||||
RAD_ISSUE_N(c, l.attn, Pn,
|
||||
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn),
|
||||
l.full ? cu : cuw, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
|
||||
brows(b_p, Pn), brows(b_p, Pn));
|
||||
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_p, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
|
||||
brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
|
||||
brows(b_p, Pn), brows(b_p, Pn));
|
||||
if (li == 0) muse_tap(c, "v.blk0", b_p, Pn, width);
|
||||
if (li + 1 == L.size()) muse_tap(c, "v.blkL", b_p, Pn, width);
|
||||
}
|
||||
RAD_ISSUE_N(c, op_ginv, Pn, brows(b_p, Pn), brows(b_inv, Pn), brows(b_x, Pn));
|
||||
muse_tap(c, "v.ginv", b_x, Pn, width);
|
||||
/* ln_post over the P patches, then the reference's pixel_shuffle into merged rows. */
|
||||
RAD_ISSUE_N(c, op_lpost, Pn, brows(b_x, Pn), RAD_W(lw_post), RAD_W(lb_post), brows(b_x, Pn));
|
||||
muse_tap(c, "v.lnpost", b_x, Pn, width);
|
||||
RAD_ISSUE_N(c, op_merge, Pn, brows(b_x, Pn), crd, brows(b_mh, Rn));
|
||||
muse_tap(c, "v.merge", b_mh, Rn, mm * width);
|
||||
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(w_a1), brows(b_m1, Rn));
|
||||
muse_tap(c, "v.fc1", b_m1, Rn, proj_ff);
|
||||
RAD_ISSUE_N(c, op_g1, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
|
||||
RAD_ISSUE_N(c, op_m2, Rn, brows(b_m2, Rn), RAD_W(w_a2), brows(b_m1, Rn));
|
||||
RAD_ISSUE_N(c, op_g2, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
|
||||
RAD_ISSUE_N(c, op_proj, Rn, brows(b_m2, Rn), RAD_W(w_proj), brows(b_out, Rn));
|
||||
muse_tap(c, "v.proj", b_out, Rn, n_embd);
|
||||
RAD_ISSUE_N(c, op_perc, Rn, brows(b_out, Rn), RAD_NONE, brows(b_out, Rn));
|
||||
muse_tap(c, "v.out", b_out, Rn, n_embd);
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MUSEGLIMMER_VISION_H */
|
||||
+141
-26
@@ -98,18 +98,36 @@ struct PleLayer {
|
||||
rad_weight w_table = 0, w_scale = 0, w_mult = 0, w_vsz = 0, w_off = 0;
|
||||
/* The table is plain bf16 as shipped (no scale weight) rather than E4M3. */
|
||||
bool table_bf16 = false;
|
||||
rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
|
||||
rad_weight w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
|
||||
/* The two projections of the gathered embedding, each in the encoding its container stores:
|
||||
* plain bf16 as the checkpoint ships them, or rotated int8 (or a narrower rotated form), which
|
||||
* halves the bytes a pass waits for once the rows are on the card. `a_embd` is their input and
|
||||
* `a_fed` the same planes for the second projection, whose codes the first one's quantiser
|
||||
* wrote. */
|
||||
LinearFP8 key{}, value{};
|
||||
ActFP8 a_embd{}, a_fed{};
|
||||
|
||||
rad_kvgroup kv_tok = 0, kv_conv = 0;
|
||||
rad_buf b_ids = 0, b_emb = 0, b_embd = 0, b_k = 0, b_v = 0, b_gv = 0, b_gvn = 0, b_out = 0;
|
||||
rad_op op_ids = 0, op_gather = 0, op_embd = 0, op_key = 0, op_value = 0;
|
||||
rad_op op_ids = 0, op_gather = 0, op_embd = 0;
|
||||
rad_op op_gate = 0, op_conv = 0, op_add = 0;
|
||||
/* The draft passes' hint (hint_ids, hint_fetch), where a drafter and `ngram_hint` exist: the
|
||||
* per-slot tails the hash continues from, the hinted ids (host domain, as `ple_ids`) and the
|
||||
* rows fetched for them, which nothing reads. */
|
||||
rad_buf b_tail = 0, b_hint_ids = 0, b_hint_emb = 0;
|
||||
rad_op op_hint_hist = 0, op_hint_round = 0, op_hint_gather = 0;
|
||||
|
||||
int64_t hn() const { return c.hc * g.n_embd; }
|
||||
/* The read-ahead queue's depth in steps: batch.cpp's k_ahead_chunks steps of the following
|
||||
* prompt, whose rows the gather's reader thread prefetches. Clamped to what `b_ids` holds, so
|
||||
* a larger offer only shortens the queue. */
|
||||
static constexpr int64_t kAheadChunks = 2;
|
||||
/* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */
|
||||
int64_t ahead_rows(const RadBatch* batch) const {
|
||||
const int64_t a = batch->n_ahead;
|
||||
return a <= 0 ? 0 : (a < g.max_tok ? a : g.max_tok);
|
||||
if (a <= 0) return 0;
|
||||
const int64_t cap = kAheadChunks * g.max_tok;
|
||||
return a < cap ? a : cap;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg, int layer,
|
||||
@@ -117,6 +135,14 @@ struct PleLayer {
|
||||
/* The hash, issued at the top of the step; the rest at the layer (see ids()). */
|
||||
void ids(RadCtx* c_, const RadBatch* batch) const;
|
||||
void step(RadCtx* c_, const RadBatch* batch) const;
|
||||
/* On a draft head's pass: the ids of each sequence's newest token, first in the pass, and
|
||||
* the fetch of their rows, last in it (see hint_ids()). */
|
||||
void hint_ids(RadCtx* c_, const RadBatch* batch) const;
|
||||
void hint_fetch(RadCtx* c_, const RadBatch* batch) const;
|
||||
bool hints(const RadBatch* batch) const {
|
||||
return op_hint_gather != 0 &&
|
||||
(batch->draft_pass > 1 || (batch->draft_pass < 0 && batch->n_draft_out > 0));
|
||||
}
|
||||
};
|
||||
|
||||
inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg,
|
||||
@@ -172,7 +198,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
/* E4M3 with one scale for all 320 million rows (Qwen3.8-Flash-Next-FP8's choice; E4M3 has its
|
||||
* own exponent, a row's dynamic range is 2.3x, and the scale sits on a three-octave plateau).
|
||||
* One stored weight, `fp8_e4m3*bf16[*x*]`: codes plus a one-element scale plane, made by the
|
||||
* recipe (data/recipes/qwen4exp-w4.recipe); the gather takes them as two operands. The name map
|
||||
* recipe (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe) or read as that release ships it (its shards under
|
||||
* one `weight_scale`); the gather takes them as two operands. The name map
|
||||
* joins the shards along rows and is declared first, since the encoding is looked up through
|
||||
* it. RAD_ACCESS_VOCAB: it is a vocabulary table, just not the token one. */
|
||||
const char* tn = nm.f("blk.%d.ple_ngram.weight", layer);
|
||||
@@ -205,13 +232,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* ---- the projections and the three gains ------------------------------------------------ */
|
||||
/* bf16: the FP8 checkpoint's `modules_to_not_convert` names both projections. */
|
||||
/* bf16 as shipped (the FP8 checkpoint's `modules_to_not_convert` names both projections); a
|
||||
* recipe may store them rotated int8. The name maps come first: the encodings, looked up
|
||||
* through them, say whether the input needs its int8 pair. They are declared below, with the
|
||||
* buffers they read and write. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_key.weight", layer), src.key_proj));
|
||||
w_key = decl_w(b, nm.f("blk.%d.ple_key.weight", layer), RAD_BF16, {HN, c.embed_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_value.weight", layer), src.value_proj));
|
||||
w_value = decl_w(b, nm.f("blk.%d.ple_value.weight", layer), RAD_BF16,
|
||||
{g.n_embd, c.embed_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_key.weight", layer), src.norm_key));
|
||||
w_nk = decl_w(b, nm.f("blk.%d.ple_norm_key.weight", layer), RAD_F32, {HN},
|
||||
@@ -229,7 +255,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
w_conv = decl_w(b, nm.f("blk.%d.ple_conv.weight", layer), RAD_BF16, {HN, c.conv_width},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off || !w_key || !w_value ||
|
||||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off ||
|
||||
!w_nk || !w_nq || !w_nc || !w_conv) return RAD_E_INVAL;
|
||||
|
||||
/* ---- the two rolling windows ------------------------------------------------------------ */
|
||||
@@ -275,10 +301,11 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
* follows declared order, where the two ops are adjacent, so a transient could be overwritten
|
||||
* in between. */
|
||||
{
|
||||
/* Twice the step's rows: the step's ids, then those of the prompt that follows
|
||||
* (RadBatch::n_ahead), which the gather's reader prefetches while the step runs. */
|
||||
/* The step's rows, then kAheadChunks further steps of the following prompt
|
||||
* (RadBatch::n_ahead) for the reader to prefetch. */
|
||||
RadBufDecl d{};
|
||||
d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * g.max_tok; d.shape[1] = c.heads;
|
||||
d.dtype = RAD_I32; d.rank = 2;
|
||||
d.shape[0] = (1 + kAheadChunks) * g.max_tok; d.shape[1] = c.heads;
|
||||
d.kind = RAD_BUF_PERSIST; d.domain = RAD_DOMAIN_HOST;
|
||||
b_ids = rad_decl_buffer(b, nm.f("ple_ids"), &d);
|
||||
|
||||
@@ -329,22 +356,83 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
{b_ids}, {b_emb});
|
||||
}
|
||||
|
||||
/* ---- the draft passes' hint. A verify step's rows are the token the last verify chose and
|
||||
* the drafter's proposals, each known a draft pass or more before the verify hashes it,
|
||||
* except the last. Each draft pass hashes its sequences' newest token (`ngram_hint`) and
|
||||
* gathers those rows through the same row source, which for a table on a drive reads them
|
||||
* into its row cache; the verify step's gather then waits for the last proposal's rows
|
||||
* only. All three ops or none: without a drafter, or where no library hashes the hint,
|
||||
* nothing is declared and the verify step reads every row itself, as before. */
|
||||
if (g.max_spec > 0 && rad_op_declared(b, "ngram_hint")) {
|
||||
const int64_t ctx = c.ngram - 1;
|
||||
b_tail = decl_b(b, nm.f("ple_hint_tail"), RAD_I32, {g.max_seqs, 2 * ctx}, RAD_BUF_PERSIST);
|
||||
RadBufDecl hi{};
|
||||
hi.dtype = RAD_I32; hi.rank = 2;
|
||||
hi.shape[0] = g.max_seqs; hi.shape[1] = c.heads;
|
||||
hi.kind = RAD_BUF_PERSIST; hi.domain = RAD_DOMAIN_HOST;
|
||||
b_hint_ids = rad_decl_buffer(b, nm.f("ple_hint_ids"), &hi);
|
||||
/* PERSIST although nothing reads it: a transient's bytes are shared by declared op
|
||||
* order, and the fetch runs on the host while the draft pass's other buffers are live. */
|
||||
RadBufDecl he{};
|
||||
he.dtype = g.act_dtype; he.rank = 2;
|
||||
he.shape[0] = g.max_seqs; he.shape[1] = c.embed_dim;
|
||||
he.kind = RAD_BUF_PERSIST; he.domain = RAD_DOMAIN_HOST;
|
||||
b_hint_emb = rad_decl_buffer(b, nm.f("ple_hint_emb"), &he);
|
||||
if (!b_tail || !b_hint_ids || !b_hint_emb) return RAD_E_INVAL;
|
||||
for (const int hist : { 1, 0 })
|
||||
(hist ? op_hint_hist : op_hint_round) =
|
||||
rw(b, RAD_OP(b, "ngram_hint",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("heads", c.heads),
|
||||
RAD_INT("ngram", c.ngram), RAD_INT("eos", c.eos),
|
||||
RAD_INT("hist", hist)),
|
||||
RAD_WEIGHTS(w_mult, w_vsz, w_off)),
|
||||
{b_tail}, {b_tail, b_hint_ids});
|
||||
const rad_weight wt[2] = { w_table, w_scale };
|
||||
op_hint_gather = rw(b, RAD_OP(b, "embed_lookup_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs * c.heads),
|
||||
RAD_INT("n_embd", HD), RAD_INT("n_vocab", c.rows),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
wt, table_bf16 ? 1 : 2),
|
||||
{b_hint_ids}, {b_hint_emb});
|
||||
if (!op_hint_hist || !op_hint_round || !op_hint_gather)
|
||||
op_hint_hist = op_hint_round = op_hint_gather = 0;
|
||||
}
|
||||
|
||||
op_embd = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_emb}, {b_embd});
|
||||
|
||||
op_key = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", HN),
|
||||
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_key)),
|
||||
{b_embd}, {b_k});
|
||||
op_value = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_value)),
|
||||
{b_embd}, {b_v});
|
||||
/* The projections. An int8 one reads the embedding's int8 codes at its own scale group; the
|
||||
* first such quantises the bf16 plane and a second reads those codes, so two int8 projections
|
||||
* must agree in rotation and group (LinearFP8 refuses the pair otherwise). */
|
||||
{
|
||||
const char* kb = nm.f("blk.%d.ple_key", layer);
|
||||
const char* vb = nm.f("blk.%d.ple_value", layer);
|
||||
RadEncoding ke{}, ve{};
|
||||
const bool kk = weight_enc(b, nm.f("%s.weight", kb), &ke);
|
||||
const bool vk = weight_enc(b, nm.f("%s.weight", vb), &ve);
|
||||
const bool k8 = !g.w_bf16 && kk && (linear_is_w8(ke) || linear_is_w8h(ke));
|
||||
const bool v8 = !g.w_bf16 && vk && (linear_is_w8(ve) || linear_is_w8h(ve));
|
||||
a_embd.x = b_embd;
|
||||
if (k8 || v8)
|
||||
RAD_ARCH_TRY(a_embd.declare_qs(b, nm, g, "ple_emb_dev", c.embed_dim, 0, true, false,
|
||||
linear_w8h_group(k8 ? ke : ve)));
|
||||
a_fed = a_embd;
|
||||
if (k8 && v8) {
|
||||
a_fed.q8_fed = true;
|
||||
a_fed.q8_rot = linear_is_w8h(ke);
|
||||
}
|
||||
key.mapped = value.mapped = true;
|
||||
/* Anything but an int8 form is the plain bf16 GEMM, in a quantised model too. */
|
||||
Geom gb = g;
|
||||
gb.w_bf16 = true;
|
||||
RAD_ARCH_TRY(key.declare(b, nm, k8 ? g : gb, kb, HN, c.embed_dim, RAD_SHARD_NONE,
|
||||
grp_model(), { src.key_proj }, a_embd, b_k));
|
||||
RAD_ARCH_TRY(value.declare(b, nm, v8 ? g : gb, vb, g.n_embd, c.embed_dim, RAD_SHARD_NONE,
|
||||
grp_model(), { src.value_proj }, a_fed, b_v));
|
||||
}
|
||||
|
||||
/* `q` is the incoming stream, un-normed; the op applies all three norms because the third is
|
||||
* over bytes it writes. */
|
||||
@@ -370,7 +458,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h, b_out}, {w.h});
|
||||
|
||||
if (!op_ids || !op_gather || !op_embd || !op_key || !op_value || !op_gate || !op_conv ||
|
||||
if (!op_ids || !op_gather || !op_embd || !key.op || !value.op || !op_gate || !op_conv ||
|
||||
!op_add)
|
||||
return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
@@ -425,6 +513,33 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* The hint of a draft head's pass. The history pass ends at the token the verify chose and each
|
||||
* later round reads the proposal before it (RadBatch::draft_pass), so the pass's newest token per
|
||||
* sequence is one the next verify step runs. hint_ids() hashes it first in the pass, so the ids
|
||||
* are in host memory as the pass starts; hint_fetch() goes last, where the host has issued the
|
||||
* whole pass and only waits for that one kernel, and the rows it reads arrive while the card
|
||||
* drafts. A history pass that drafts nothing gets neither. */
|
||||
inline void PleLayer::hint_ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
if (!hints(batch)) return;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadKVGroupBatch* tk = kv_batch(batch, kv_tok);
|
||||
const int32_t* tk_idx = tk ? tk->state_index : nullptr;
|
||||
RAD_ISSUE_N(c_, batch->draft_pass < 0 ? op_hint_hist : op_hint_round, S,
|
||||
praw(batch->token_ids, RAD_I32, T), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
|
||||
tk_idx ? praw(tk_idx, RAD_I32, S) : RAD_NONE,
|
||||
RAD_B(b_tail), brows(b_hint_ids, S));
|
||||
}
|
||||
|
||||
inline void PleLayer::hint_fetch(RadCtx* c_, const RadBatch* batch) const {
|
||||
if (!hints(batch)) return;
|
||||
const int64_t S = batch->n_seq;
|
||||
RAD_ISSUE_N(c_, op_hint_gather, S * c.heads,
|
||||
brows(b_hint_ids, S), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
|
||||
brows(b_hint_emb, S), RAD_NONE);
|
||||
}
|
||||
|
||||
inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
@@ -446,8 +561,8 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
|
||||
RAD_ISSUE_N(c_, op_embd, T, brows(b_emb, T), brows(b_embd, T));
|
||||
RAD_ISSUE_N(c_, op_key, T, brows(b_embd, T), RAD_W(w_key), brows(b_k, T));
|
||||
RAD_ISSUE_N(c_, op_value, T, brows(b_embd, T), RAD_W(w_value), brows(b_v, T));
|
||||
key.step(c_, a_embd, b_k, T, 0, T);
|
||||
value.step(c_, a_fed, b_v, T, 0, T);
|
||||
|
||||
RAD_ISSUE_N(c_, op_gate, T,
|
||||
brows(b_k, T), brows(w.h, T), brows(b_v, T),
|
||||
|
||||
@@ -78,16 +78,33 @@ struct VisionTower {
|
||||
return rad_meta_geti(m, "vision_config.depth", 0) > 0;
|
||||
}
|
||||
|
||||
/* With `gate_weights`, a checkpoint or container without the tower's weights declares nothing
|
||||
* and leaves `on` false, for a model whose config names a tower its weights may not have. */
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group, bool deepstack = false);
|
||||
int64_t model_embd, int first_group, bool deepstack = false,
|
||||
bool gate_weights = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
|
||||
Names& nm, int64_t model_embd, int first_group, bool deepstack) {
|
||||
Names& nm, int64_t model_embd, int first_group, bool deepstack,
|
||||
bool gate_weights) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
|
||||
/* Whether the stem is there: its map first, then its encoding, which convert answers from the
|
||||
* checkpoint and load from the container alike. A map left behind is inert. */
|
||||
if (gate_weights) {
|
||||
if (map_copy(b, nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight")) < 0)
|
||||
return RAD_E_INVAL;
|
||||
RadEncoding enc;
|
||||
if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) {
|
||||
std::fprintf(stderr, "radiance: vision_config names a tower the checkpoint does not "
|
||||
"ship; declaring without it\n");
|
||||
return RAD_OK;
|
||||
}
|
||||
}
|
||||
|
||||
depth = rad_meta_geti(m, "vision_config.depth", 0);
|
||||
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
|
||||
heads = rad_meta_geti(m, "vision_config.num_heads", 0);
|
||||
@@ -173,8 +190,12 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
|
||||
RAD_BF16, { width, patch_dim }, grp_model());
|
||||
/* Mapped above with `gate_weights`. */
|
||||
w_patch = gate_weights
|
||||
? decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim },
|
||||
RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_model())
|
||||
: bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
|
||||
RAD_BF16, { width, patch_dim }, grp_model());
|
||||
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("model.visual.patch_embed.proj.bias"),
|
||||
RAD_BF16, { width }, grp_model());
|
||||
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("model.visual.pos_embed.weight"),
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
/* rad_calib_full.h -- the whole Hessian of each linear's input in a dense bf16 trunk, under tensor
|
||||
* parallelism, recorded over a --calib-corpus run into --calib-dir (RadBuildCtx::calib_*).
|
||||
*
|
||||
* GPTQ needs H = sum over tokens of x x^T for the whole input x of a linear. A linear split by its
|
||||
* input columns across ranks (o_proj, the delta net's out_proj, down_proj) sees only its rank's
|
||||
* columns, and a Gram of those is one diagonal block of H: the products across ranks are never
|
||||
* formed on any card. So each such input is gathered to its whole width first (`all_gather`,
|
||||
* row-interleaved: rank r's columns land at r * width / world), and the Gram is taken of the whole
|
||||
* row. An input every rank holds whole (a norm's output) is read where it is.
|
||||
*
|
||||
* One rank records each layer (layer % world), so the Gram work and the host memory split
|
||||
* evenly. Its f32 scratch receives one step's sum for one input (`gram_accum` with `upper` 1: H is
|
||||
* symmetric and only k2 >= k1 is kept), whose upper triangle is copied to a pinned square and which
|
||||
* is zeroed for the next input, all in stream order. A worker thread waits on the copy's event and adds the square to a
|
||||
* host accumulator holding the upper triangle packed row by row (k(k+1)/2 f32), while the rank goes
|
||||
* on issuing the step: two squares alternate, so the rank waits only when the adds fall two Grams
|
||||
* behind. Syncing and adding on the rank's own thread instead left the card idle for every add, 16
|
||||
* of 1.2 GB a step on each rank of Qwen3.8-27B, and the ranks wait on each other at every
|
||||
* all-reduce. The host holds every recorded input of the rank: 786 MB a layer at Qwen3.8-27B,
|
||||
* which is what --calib-layers bounds. A step's sum is f32 over at most a step's
|
||||
* rows, and the host adds a few thousand of them; the consumer damps H by a percent of its trace,
|
||||
* far above that rounding.
|
||||
*
|
||||
* Files, written once the plugin has seen RadBuildCtx::calib_tokens rows (the whole corpus): one
|
||||
* safetensors file per input, <dir>/<stem>.safetensors, holding `hessian_upper`, f32
|
||||
* [k * (k + 1) / 2], row i's entries k2 = i .. k-1 after row i-1's, and metadata naming `k`, the
|
||||
* rows summed and the checkpoint linears that read the input. H is the raw sum; divide by `rows`
|
||||
* for the mean second moment.
|
||||
*
|
||||
* An int8 trunk (site_i8, one rank only) is recorded from the codes and scales its GEMMs actually
|
||||
* read, so H includes what the model's own quantisation did to the input -- the input a quantised
|
||||
* model feeds each layer, for GPTQ against the error it inherits. Codes a rotating producer wrote
|
||||
* are in the rotated domain; the file's metadata then names it (`domain`: the Hadamard width), as
|
||||
* RADGRAM2's header does, and the reader converts. */
|
||||
#pragma once
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace rad::arch {
|
||||
|
||||
struct CalibFull {
|
||||
struct Site {
|
||||
std::string stem; /* the file's name, without .safetensors */
|
||||
std::string linears; /* the checkpoint linears that read this input, comma-separated */
|
||||
rad_buf local = 0; /* this rank's part of the input (the whole input when replicated) */
|
||||
int64_t K = 0; /* the whole input's width */
|
||||
int64_t k_local = 0; /* this rank's columns; K when replicated */
|
||||
rad_op op_gather = 0; /* the columns of every rank into `gathered`; 0 when replicated */
|
||||
rad_op op_gram = 0; /* declared on the owner only */
|
||||
bool owner = false;
|
||||
rad_buf q8 = 0, s8 = 0; /* site_i8: the int8 codes and their f32 (row, 128) scales */
|
||||
uint32_t domain = 0; /* site_i8: the codes' rotation width, 0 for none */
|
||||
std::vector<float> tri; /* the owner's accumulator, upper triangle packed */
|
||||
};
|
||||
|
||||
bool on = false;
|
||||
const char* dir = nullptr;
|
||||
int rank = 0, world = 1;
|
||||
int64_t lo = 0, hi = 0; /* layers recorded */
|
||||
long long target = 0, seen = 0;
|
||||
bool written = false;
|
||||
rad_buf gathered = 0; /* [max_tok, widest split input] bf16 */
|
||||
int64_t gather_w = 0;
|
||||
rad_buf scratch = 0; /* [kmax, kmax] f32 on a rank that owns any input */
|
||||
int64_t kmax = 0;
|
||||
std::vector<Site> sites;
|
||||
|
||||
/* The host side of the taps (see the file comment). Created at the first tap and released once
|
||||
* the files are written; a run that ends before then leaks it, since its worker may still wait
|
||||
* on a card that is being torn down. */
|
||||
struct Async {
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
std::thread worker;
|
||||
float* square[2] = { nullptr, nullptr }; /* pinned, kmax * kmax f32 */
|
||||
RadEvent copied[2] = { nullptr, nullptr };
|
||||
int site[2] = { -1, -1 }; /* the site square s holds; -1 when free */
|
||||
std::deque<int> queue; /* squares copied and not yet added */
|
||||
int next = 0;
|
||||
bool stop = false, failed = false;
|
||||
};
|
||||
Async* async = nullptr;
|
||||
|
||||
/* Whether this run records layer l. */
|
||||
bool records(int64_t l) const { return on && l >= lo && l < hi; }
|
||||
int owner_of(int64_t l) const { return (int)(l % world); }
|
||||
|
||||
/* From the build context: nothing unless --calib-dir is set. `widest_split` and `widest` are
|
||||
* the largest split input and the largest input of any recorded site, which size the gather
|
||||
* buffer and the scratch. */
|
||||
int begin(RadBuilder* b, Names& nm, const Geom& g, const RadBuildCtx* ctx, int64_t n_layer,
|
||||
int64_t widest_split, int64_t widest) {
|
||||
if (!ctx->calib_dir || !*ctx->calib_dir) return RAD_OK;
|
||||
on = true;
|
||||
dir = ctx->calib_dir;
|
||||
rank = g.rank;
|
||||
world = g.world;
|
||||
lo = ctx->calib_layer_hi ? ctx->calib_layer_lo : 0;
|
||||
hi = ctx->calib_layer_hi ? std::min<int64_t>(ctx->calib_layer_hi, n_layer) : n_layer;
|
||||
target = ctx->calib_tokens;
|
||||
if (lo >= hi) {
|
||||
std::fprintf(stderr, "radiance: --calib-layers %lld:%lld names no layer of %lld\n",
|
||||
(long long)lo, (long long)hi, (long long)n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (target <= 0) {
|
||||
std::fprintf(stderr, "radiance: --calib-dir records over a --calib-corpus run, which "
|
||||
"states the corpus's size\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (world > 1) {
|
||||
gather_w = widest_split;
|
||||
gathered = decl_b(b, nm.f("calib.gathered"), RAD_BF16, { g.max_tok, gather_w });
|
||||
if (!gathered) return RAD_E_INVAL;
|
||||
}
|
||||
kmax = widest;
|
||||
scratch = decl_b(b, nm.f("calib.scratch"), RAD_F32, { kmax, kmax }, RAD_BUF_PERSIST);
|
||||
return scratch ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* One input of layer `layer` (-1: the lm_head's, recorded by rank 0). `local` is the rank's
|
||||
* part, `k_local` its width; the input is split across ranks when k_local * world == K. */
|
||||
int site(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
|
||||
rad_buf local, int64_t k_local, int64_t K) {
|
||||
Site s;
|
||||
s.stem = std::move(stem);
|
||||
s.linears = std::move(linears);
|
||||
s.local = local;
|
||||
s.K = K;
|
||||
s.k_local = k_local;
|
||||
s.owner = (layer < 0 ? 0 : owner_of(layer)) == rank;
|
||||
const bool split = k_local != K;
|
||||
if (split) {
|
||||
if (k_local * world != K || !gathered || K > gather_w) return RAD_E_INVAL;
|
||||
s.op_gather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", world),
|
||||
RAD_RANGE("numel", k_local, g.max_tok * k_local),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("row", k_local)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ local }, { gathered });
|
||||
if (!s.op_gather) return RAD_E_INVAL;
|
||||
}
|
||||
if (s.owner) {
|
||||
if (K > kmax) return RAD_E_INVAL;
|
||||
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
RAD_INT("group", 128), RAD_STR("dtype", "bf16"), /* group: unread at bf16 */
|
||||
RAD_INT("upper", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ split ? gathered : local, scratch }, { scratch });
|
||||
if (!s.op_gram) return RAD_E_INVAL;
|
||||
}
|
||||
sites.push_back(std::move(s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One input of layer `layer` from an int8 trunk's codes `q8` and scales `s8` (see the file
|
||||
* comment): the whole input on one rank, `domain` the Hadamard width the codes were rotated by
|
||||
* (0 for none). */
|
||||
int site_i8(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
|
||||
rad_buf q8, rad_buf s8, int64_t K, uint32_t domain) {
|
||||
if (world > 1 || !q8 || !s8 || K > kmax) return RAD_E_INVAL;
|
||||
Site s;
|
||||
s.stem = std::move(stem);
|
||||
s.linears = std::move(linears);
|
||||
s.K = s.k_local = K;
|
||||
s.owner = true;
|
||||
s.q8 = q8;
|
||||
s.s8 = s8;
|
||||
s.domain = domain;
|
||||
(void)layer;
|
||||
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
RAD_INT("group", 128), RAD_STR("dtype", "i8a8"),
|
||||
RAD_INT("upper", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ q8, s8, scratch }, { scratch });
|
||||
if (!s.op_gram) return RAD_E_INVAL;
|
||||
sites.push_back(std::move(s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Site `i` over a step's T rows: gather (every rank), then on the owner the Gram into the
|
||||
* scratch, copied to a free square, the scratch zeroed, and the square handed to the worker. */
|
||||
void tap(RadCtx* c, size_t i, int64_t T) {
|
||||
Site& s = sites[i];
|
||||
RadOperand a = brows(s.local, T);
|
||||
if (s.op_gather) {
|
||||
RAD_ISSUE_N(c, s.op_gather, T * s.k_local, brows(s.local, T), bcol(gathered, 0, s.K, T));
|
||||
a = bcol(gathered, 0, s.K, T);
|
||||
}
|
||||
if (!s.owner) return;
|
||||
float* dev = static_cast<float*>(rad_buf_ptr(c, scratch));
|
||||
if (!dev || (!async && !start())) {
|
||||
rad_step_fail(c, "calibration: no scratch or pinned squares");
|
||||
return;
|
||||
}
|
||||
/* Allocated at the first step, not at declare: the engine may declare more than once. */
|
||||
if (s.tri.empty()) s.tri.assign((size_t)(s.K * (s.K + 1) / 2), 0.0f);
|
||||
Async& q = *async;
|
||||
const int k = q.next;
|
||||
q.next ^= 1;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(q.mu);
|
||||
q.cv.wait(lk, [&] { return q.site[k] < 0 || q.failed; });
|
||||
if (q.failed) {
|
||||
lk.unlock();
|
||||
rad_step_fail(c, "calibration: waiting on a Gram's copy failed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
const int64_t K = s.K;
|
||||
if (s.q8)
|
||||
RAD_ISSUE_N(c, s.op_gram, T, brows(s.q8, T), brows(s.s8, T), praw2(dev, RAD_F32, K, K));
|
||||
else
|
||||
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
|
||||
/* `upper` 1 writes no entry below the diagonal, so only the upper triangle comes back:
|
||||
* band by band of kBand rows, each from its first row's diagonal on, about half the
|
||||
* square's bytes. The link is what a step's taps wait on, 25 GB a step on each rank of
|
||||
* Qwen3.8-27B as whole squares. */
|
||||
constexpr int64_t kBand = 512;
|
||||
bool ok = true;
|
||||
for (int64_t r = 0; r < K && ok; r += kBand)
|
||||
ok = rad_memcpy_2d_async(q.square[k] + r * K + r, K * 4, dev + r * K + r, K * 4,
|
||||
(K - r) * 4, std::min(kBand, K - r), rad_stream(c)) >= 0;
|
||||
if (!ok || rad_memset_async(dev, 0, K * K * 4, rad_stream(c)) < 0 ||
|
||||
rad_event_record(q.copied[k], rad_stream(c)) < 0) {
|
||||
rad_step_fail(c, "calibration: copying a Gram back failed");
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(q.mu);
|
||||
q.site[k] = (int)i;
|
||||
q.queue.push_back(k);
|
||||
}
|
||||
q.cv.notify_all();
|
||||
}
|
||||
|
||||
/* After a step: once the corpus is through, every owned input to its file. */
|
||||
void after_step(RadCtx* c, int64_t T) {
|
||||
if (!on || written) return;
|
||||
seen += T;
|
||||
if (seen < target) return;
|
||||
written = true;
|
||||
int n = 0, bad = finish() ? 0 : 1;
|
||||
for (const Site& s : sites) {
|
||||
if (!s.owner || s.tri.empty()) continue;
|
||||
++n;
|
||||
if (!write(s)) ++bad;
|
||||
}
|
||||
std::fprintf(stderr, "radiance: calibration: rank %d wrote %d Hessian(s) of layers %lld:%lld "
|
||||
"after %lld rows to %s%s\n", rad_rank(c), n, (long long)lo, (long long)hi,
|
||||
seen, dir, bad ? ", with errors" : "");
|
||||
if (seen != target)
|
||||
std::fprintf(stderr, "radiance: calibration: %lld rows seen and the corpus has %lld\n",
|
||||
seen, target);
|
||||
}
|
||||
|
||||
private:
|
||||
bool start() {
|
||||
Async* q = new Async;
|
||||
bool ok = true;
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
q->square[k] = static_cast<float*>(rad_dev_alloc(kmax * kmax * 4, RAD_MEM_HOST_PINNED));
|
||||
ok = ok && q->square[k] && rad_event_create(&q->copied[k]) >= 0;
|
||||
}
|
||||
if (!ok) {
|
||||
std::fprintf(stderr, "radiance: calibration could not pin 2 x %lld MiB of host squares "
|
||||
"on rank %d\n", (long long)((kmax * kmax * 4) >> 20), rank);
|
||||
release(q);
|
||||
return false;
|
||||
}
|
||||
async = q;
|
||||
q->worker = std::thread([this] { work(); });
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The worker: each copied square, in the order the rank issued them, into its site. */
|
||||
void work() {
|
||||
Async& q = *async;
|
||||
for (;;) {
|
||||
int k;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(q.mu);
|
||||
q.cv.wait(lk, [&] { return q.stop || !q.queue.empty(); });
|
||||
if (q.queue.empty()) return;
|
||||
k = q.queue.front();
|
||||
q.queue.pop_front();
|
||||
}
|
||||
Site& s = sites[(size_t)q.site[k]];
|
||||
const bool ok = rad_event_sync(q.copied[k]) >= 0;
|
||||
if (ok) add_upper(s.tri.data(), q.square[k], s.K);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(q.mu);
|
||||
q.site[k] = -1;
|
||||
if (!ok) q.failed = true;
|
||||
}
|
||||
q.cv.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/* Every square added and the worker gone; false if a copy failed. */
|
||||
bool finish() {
|
||||
if (!async) return true;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(async->mu);
|
||||
async->stop = true;
|
||||
}
|
||||
async->cv.notify_all();
|
||||
async->worker.join();
|
||||
const bool ok = !async->failed;
|
||||
if (!ok) std::fprintf(stderr, "radiance: calibration: a Gram's copy failed on rank %d\n", rank);
|
||||
release(async);
|
||||
async = nullptr;
|
||||
return ok;
|
||||
}
|
||||
|
||||
static void release(Async* q) {
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
if (q->square[k]) rad_dev_free(q->square[k], RAD_MEM_HOST_PINNED);
|
||||
if (q->copied[k]) rad_event_destroy(q->copied[k]);
|
||||
}
|
||||
delete q;
|
||||
}
|
||||
|
||||
/* acc's upper triangle, packed row by row, += the upper triangle of the k x k row-major `full`. */
|
||||
static void add_upper(float* acc, const float* full, int64_t k) {
|
||||
const unsigned nt = std::max(1u, std::min(16u, std::thread::hardware_concurrency() / 2));
|
||||
std::vector<std::thread> th;
|
||||
for (unsigned t = 0; t < nt; ++t)
|
||||
th.emplace_back([=] {
|
||||
for (int64_t i = t; i < k; i += nt) {
|
||||
float* d = acc + (i * k - i * (i - 1) / 2);
|
||||
const float* s = full + i * k + i;
|
||||
for (int64_t j = 0; j < k - i; ++j) d[j] += s[j];
|
||||
}
|
||||
});
|
||||
for (std::thread& x : th) x.join();
|
||||
}
|
||||
|
||||
bool write(const Site& s) const {
|
||||
char path[1024];
|
||||
std::snprintf(path, sizeof path, "%s/%s.safetensors", dir, s.stem.c_str());
|
||||
const uint64_t bytes = (uint64_t)s.tri.size() * 4;
|
||||
std::string hdr = "{\"__metadata__\":{\"k\":\"" + std::to_string(s.K) + "\",\"rows\":\"" +
|
||||
std::to_string(seen) + "\",\"layout\":\"upper triangle, row-major, packed\","
|
||||
"\"linears\":\"" + s.linears + "\"" +
|
||||
(s.domain ? ",\"domain\":\"" + std::to_string(s.domain) + "\"" : std::string()) +
|
||||
"},\"hessian_upper\":{\"dtype\":\"F32\","
|
||||
"\"shape\":[" + std::to_string(s.tri.size()) + "],\"data_offsets\":[0," +
|
||||
std::to_string(bytes) + "]}}";
|
||||
while (hdr.size() % 8) hdr += ' ';
|
||||
const uint64_t hl = hdr.size();
|
||||
FILE* f = std::fopen(path, "wb");
|
||||
if (!f) { std::fprintf(stderr, "radiance: calibration cannot write %s\n", path); return false; }
|
||||
bool ok = std::fwrite(&hl, 8, 1, f) == 1 && std::fwrite(hdr.data(), 1, hl, f) == hl &&
|
||||
std::fwrite(s.tri.data(), 4, s.tri.size(), f) == s.tri.size();
|
||||
ok = std::fclose(f) == 0 && ok;
|
||||
if (!ok) std::fprintf(stderr, "radiance: calibration write to %s was short\n", path);
|
||||
return ok;
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace rad::arch */
|
||||
@@ -0,0 +1,63 @@
|
||||
/* rad_deepseek41_chat.h -- DeepSeek-V4.1's reply format (reasoning and DSML tool calls) as data.
|
||||
*
|
||||
* The model's own encoder (encoding/encoding.py in the checkpoint) writes an assistant turn as
|
||||
*
|
||||
* [reasoning</think>]content\n\n<|DSML| calls>
|
||||
* <|DSML| invoke name="NAME">
|
||||
* <|DSML| parameter name="ARG" string="true">raw text</|DSML| parameter>
|
||||
* <|DSML| parameter name="ARG" string="false">JSON</|DSML| parameter>
|
||||
* </|DSML| invoke>
|
||||
* ...
|
||||
* </|DSML| calls><|end▁of▁sentence|>
|
||||
*
|
||||
* Every call sits in one section, each argument's tag says whether its value is a string or JSON,
|
||||
* and the tag names carry a leading space (V4 wrote `<|DSML|tool_calls>`, V3.2
|
||||
* `<|DSML|function_calls>`). The generation prompt ends in `<think>` with thinking on and in a
|
||||
* bare `</think>` with it off, so the reply starts inside the block only when the prompt opened
|
||||
* it.
|
||||
*
|
||||
* The template analysis cannot state the typed argument tags, so the plugin declares the format;
|
||||
* the reply-format tests read this same declaration. */
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
inline const RadChatFormat* deepseek41_chat_format() {
|
||||
static const char* const kBreaks[] = { "<|DSML| calls>" };
|
||||
static const char* const kTriggers[] = { "<|DSML| calls>" };
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat c{};
|
||||
c.struct_size = (uint32_t)sizeof(RadChatFormat);
|
||||
c.name = "plugin:deepseek41";
|
||||
c.reasoning_open = "<think>";
|
||||
c.reasoning_close = "</think>";
|
||||
/* A section that starts inside an unclosed reasoning block ends it there. */
|
||||
c.reasoning_breaks = kBreaks;
|
||||
c.n_reasoning_breaks = 1;
|
||||
c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
|
||||
|
||||
c.section_open = "<|DSML| calls>";
|
||||
c.section_close = "</|DSML| calls>";
|
||||
c.name_prefix = "<|DSML| invoke name=\"";
|
||||
c.name_suffix = "\">\n";
|
||||
c.call_end = "</|DSML| invoke>";
|
||||
c.arg_prefix = "<|DSML| parameter name=\"";
|
||||
c.arg_name_suffix = "\"";
|
||||
c.arg_value_prefix = " string=\"true\">";
|
||||
c.arg_json_value_prefix = " string=\"false\">";
|
||||
c.arg_value_suffix = "</|DSML| parameter>";
|
||||
c.string_value = RAD_CHAT_VALUE_RAW;
|
||||
c.other_value = RAD_CHAT_VALUE_JSON;
|
||||
c.value_newlines = 0;
|
||||
|
||||
c.triggers = kTriggers;
|
||||
c.n_triggers = 1;
|
||||
return c;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
+736
-276
File diff suppressed because it is too large.
Load diff
@@ -40,7 +40,8 @@
|
||||
* The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
|
||||
* four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
|
||||
* layers and `False` on the full one, so this block declares two attention ops and issues the one
|
||||
* each layer's type names.
|
||||
* each layer's type names. A config that states `dflash_config.causal` (NVIDIA's E4B drafter:
|
||||
* false, all five layers sliding) sets the sliding layers' causality.
|
||||
*
|
||||
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
|
||||
* cap * tanh(x / cap) is strictly increasing.
|
||||
@@ -187,6 +188,10 @@ inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
out->draft_depth = (int)(bs - 1);
|
||||
out->draft_depth_fixed = 1;
|
||||
out->chain_pays = 1;
|
||||
/* Its proposals verified as a tree of the same node count (dflash_tree, rad_drafter_tree): on
|
||||
* 4x R9700 +7% single-stream decode and +6-9% aggregate at 1-16 users over the selector's
|
||||
* chain (BetterBench, thinking off; on two cards +4% and +6-12%). */
|
||||
out->tree_pays = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -235,6 +240,7 @@ struct Dflash1 {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */
|
||||
int64_t window = 0; /* the sliding layers' window; 0 for none */
|
||||
int causal = 1; /* the sliding layers: causal (z-lab) or not (dflash_config.causal) */
|
||||
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
|
||||
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
|
||||
int64_t kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */
|
||||
@@ -616,6 +622,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
"window\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* z-lab's configs state no causality and train the sliding layers causal; NVIDIA's
|
||||
* (Nemotron-3.5-Bolt-E4B's DFlash) states `dflash_config.causal: false`, every layer
|
||||
* sliding and non-causal over its window. */
|
||||
dc.causal = rad_meta_geti(meta, "draft.dflash_config.causal",
|
||||
rad_meta_geti(meta, "draft.is_causal", 1)) != 0 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
if (!head_sharded(dg) && dg.world > 1) {
|
||||
@@ -670,11 +681,12 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
int nfull = 0;
|
||||
for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l];
|
||||
rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld "
|
||||
"sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the "
|
||||
"sliding over %lld, %s), %lld heads / %lld kv x %lld, ffn %lld, reading the "
|
||||
"trunk at %lld tap(s); linears %s. One forward over %lld rows proposes %lld "
|
||||
"tokens; the head is %s, argmax %s",
|
||||
(long long)dg.n_layer, t.base_layer, t.base_layer + (int)dg.n_layer - 1, nfull,
|
||||
(long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head,
|
||||
(long long)(dg.n_layer - nfull), (long long)dc.window,
|
||||
dc.causal ? "causal" : "non-causal", (long long)dg.n_head,
|
||||
(long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff,
|
||||
(long long)t.n_taps,
|
||||
df->i8 ? "int8 (w8a8, an int8 activation per row)" : "on the E4M3 grid (fp8a8 / mxfp4a8)",
|
||||
@@ -855,7 +867,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
};
|
||||
bool any_full = false, any_swa = false;
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
|
||||
if (any_swa) op_attn_swa = attn(1, cfg.window);
|
||||
if (any_swa) op_attn_swa = attn(cfg.causal, cfg.window);
|
||||
if (any_full) op_attn_full = attn(0, 0);
|
||||
|
||||
/* The copies into the cache's layout (rep_kv), a head-wide strided row copy each. Each pass's
|
||||
|
||||
@@ -13,9 +13,10 @@
|
||||
* row-interleaved all_gather, bit for bit the replicated projection
|
||||
*
|
||||
* The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered
|
||||
* row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside
|
||||
* its page tables, so its runs are multiples of four rows. The last rank's run may be short, or
|
||||
* lie wholly past a small step (`run_of`). */
|
||||
* row, because an all_gather moves whole words. The MLA gathers 4096-wide bf16 rows, so its runs
|
||||
* are ceil(T / world); the indexer gathers one i32 length a row beside its page tables, so its
|
||||
* runs are multiples of four rows. The last rank's run may be short, or lie wholly past a small
|
||||
* step (`run_of`). */
|
||||
#ifndef RAD_GLM_TP_H
|
||||
#define RAD_GLM_TP_H
|
||||
#include "rad_arch.h"
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/* Muse Glimmer's reply format: the ATEM channel protocol its chat template renders.
|
||||
*
|
||||
* The template's generation prompt ends at `<|start|>assistant`, so the model opens its own
|
||||
* channels: `<to=self>` reasoning first, then the answer:
|
||||
*
|
||||
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=user<|message|> ...answer...
|
||||
*
|
||||
* `reasoning_close` carries the whole channel transition, so the answer's own header is consumed
|
||||
* with the reasoning block's close and the content begins at the answer's first byte. A reply
|
||||
* that skips the reasoning opens on the answer's channel directly (`to=user<|message|> ...`);
|
||||
* `content_open` names that header so it is dropped there too.
|
||||
*
|
||||
* Tool calls are the template's ATEM dialect, emitted as their own assistant turn whose channel
|
||||
* names the tool (chat_template.jinja, render_atem):
|
||||
*
|
||||
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=NAME<|message|>
|
||||
* <atem:function_calls>
|
||||
* <atem:invoke name="NAME">
|
||||
* <atem:parameter name="k">value</atem:parameter>
|
||||
* </atem:invoke>
|
||||
* </atem:function_calls>
|
||||
*
|
||||
* String parameters are written raw, everything else as JSON (the template's `tojson`); the
|
||||
* section opener is the constrained-decoding trigger, and it is also the reasoning break: a call
|
||||
* turn's channel header names the tool rather than `user`, so the answer's `reasoning_close`
|
||||
* does not match there and the reasoning block runs to the section, swallowing the `<|eom|>` and
|
||||
* the header.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace museglimmer {
|
||||
|
||||
inline const RadChatFormat* muse_chat_format() {
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat x{};
|
||||
x.struct_size = sizeof(x);
|
||||
x.name = "plugin:museglimmer";
|
||||
x.reasoning_open = "to=self<|message|>";
|
||||
x.reasoning_close = "<|eom|><|start|>assistant to=user<|message|>";
|
||||
static const char* const kBreaks[] = {"<atem:function_calls>"};
|
||||
x.reasoning_breaks = kBreaks;
|
||||
x.n_reasoning_breaks = 1;
|
||||
/* The model opens its own channel; the prompt carries none. */
|
||||
x.reasoning_in_prompt = RAD_CHAT_THINK_NEVER;
|
||||
x.content_open = "to=user<|message|>";
|
||||
x.section_open = "<atem:function_calls>";
|
||||
x.section_close = "</atem:function_calls>";
|
||||
x.call_open = "<atem:invoke ";
|
||||
x.name_prefix = "name=\"";
|
||||
x.name_suffix = "\">";
|
||||
x.call_end = "</atem:invoke>";
|
||||
x.arg_prefix = "<atem:parameter name=\"";
|
||||
x.arg_name_suffix = "\">";
|
||||
x.arg_value_suffix = "</atem:parameter>";
|
||||
x.string_value = RAD_CHAT_VALUE_RAW; /* the template writes string arguments raw */
|
||||
x.other_value = RAD_CHAT_VALUE_JSON; /* booleans, numbers, arrays, objects as tojson */
|
||||
x.value_newlines = 1;
|
||||
/* No grammar triggers: the reference deployment (vLLM's --tool-call-parser muse) runs
|
||||
* unconstrained and parses whatever the model writes. A trigger arms the lazy tool-call
|
||||
* grammar, and with the DFlash drafter the trigger fires mid-verify -- inside drafted
|
||||
* text -- at the reasoning-to-call boundary, which spins the sampler and loops the
|
||||
* channel header (measured: drafter on = the header repeats 3-4x and the reply stalls;
|
||||
* drafter off = one header, clean call). The streaming parser reads natural ATEM as
|
||||
* it is. */
|
||||
return x;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace museglimmer */
|
||||
+86
-21
@@ -9,7 +9,8 @@
|
||||
* Contents: the projection and query path, the block-key path with its two states, and the score
|
||||
* and selection. Below `budget + ratio - 1` tokens of context every visible block is selected, so
|
||||
* the sparse path must reproduce the dense path's text byte for byte; that is the test for any
|
||||
* change here.
|
||||
* change here. A step entirely at or below that bound therefore needs no selection at all, and
|
||||
* step() issues only the block-key path for it (its `use`; docs/QSA.md, "Below the bound").
|
||||
*/
|
||||
#ifndef RAD_QSA_H
|
||||
#define RAD_QSA_H
|
||||
@@ -121,13 +122,43 @@ struct QsaIndexer {
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
|
||||
const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
|
||||
/* `win_cu`, device: {0, plane_rows}, the one sequence of a window of a step wider than the
|
||||
* score plane (Config::plane_rows); null where no step is. */
|
||||
* score plane (Config::plane_rows); null where no step is.
|
||||
*
|
||||
* `use` is what the layer's attention reads of the selection this step (QsaUse, rad_arch.h;
|
||||
* AttnGatedFP8::qsa_use): the default issues the query, the scores and the selection as every
|
||||
* step did before. `first` is whether this is the first full-attention layer the pass issues:
|
||||
* at or below the bound the selection is made there once and read by every layer after it (the
|
||||
* buffers are the model's, live across its layers, and nothing else writes them). The default
|
||||
* makes it at every layer. */
|
||||
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch,
|
||||
const int32_t* win_cu = nullptr) const;
|
||||
const int32_t* win_cu = nullptr, int use = kQsaSelect, bool first = true) const;
|
||||
/* Stores the pass's block keys and tail exactly as step() does, with no query, score or
|
||||
* selection (see AttnGatedFP8::store_kv). */
|
||||
void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
|
||||
bool store_keys(RadCtx* c, const RadBatch* batch) const;
|
||||
/* `part` 0 issues all of it; 1, 2 and 3 its three stages apart and in that order (the work
|
||||
* list, the block keys, the tail store), for a caller that issues them behind another block's
|
||||
* launches (deferrable, below). */
|
||||
bool store_keys(RadCtx* c, const RadBatch* batch, int part = 0) const;
|
||||
/* Whether this step's keys and tail may be issued behind the attention block's launches
|
||||
* instead of in front of them (SideOps, rad_arch.h): nothing reads a selection of this
|
||||
* layer's (`use` as step() resolves it), so the attention reads nothing the three ops write.
|
||||
* The caller answers for the buffers (Wire: qk, stage, page, bpos, nc excluded from
|
||||
* sharing). */
|
||||
bool deferrable(const RadBatch* batch, int use, bool first) const {
|
||||
if (!on() || qsa_eager()) return false;
|
||||
/* step() stores no keys for a batch without the attention's group; leave that to it. */
|
||||
if (!kv_batch(batch, c.kv_attn)) return false;
|
||||
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
|
||||
return use == kQsaUnread;
|
||||
}
|
||||
/* What step() issues on a deferrable step, a piece at a time: the projection, then
|
||||
* store_keys's stages 1..3. */
|
||||
void step_proj(RadCtx* c, const ActFP8& in, const RadBatch* batch) const {
|
||||
proj.step(c, in, w.qk, batch->n_tok);
|
||||
}
|
||||
void step_part(RadCtx* c, const RadBatch* batch, int part) const {
|
||||
(void)store_keys(c, batch, part);
|
||||
}
|
||||
};
|
||||
|
||||
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
@@ -216,6 +247,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
d.head_dim = c.head_dim / (2 * c.ratio);
|
||||
*bk = rad_decl_kv_group(b, nm.f("kv_qsa_bkey"), &d);
|
||||
if (!*bk) return RAD_E_INVAL;
|
||||
/* qsa_score reads every complete block of the history each step, so this group stays resident
|
||||
* and holds every sequence's context while a sibling streams (kvstream/carve.h). */
|
||||
RAD_ARCH_TRY(rad_kv_group_dense_read(b, *bk));
|
||||
}
|
||||
kv_bk = *bk;
|
||||
/* Under M-RoPE a block key rotates at its first token's three components, which qsa_work
|
||||
@@ -255,13 +289,16 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("seqs", g.max_seqs)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.score, w.nc}, {w.sel, w.nsel, w.sequ});
|
||||
|
||||
/* When the attention group streams, the attention block resolves `sel` to ring slots after its
|
||||
* layer's store (AttnGatedFP8::step); prefill runs on the stage and never resolves. */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Stores the block keys of the blocks the pass completes and the tail of raw keys after them,
|
||||
* from the projection's raw-key head. False when the step has no batch for the indexer's
|
||||
* groups. */
|
||||
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
|
||||
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch, int part) const {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t nw = (c.heads + 1) * c.head_dim;
|
||||
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
|
||||
@@ -283,20 +320,24 @@ inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
|
||||
const bool mc = g.rope_mc && batch->rope_pos;
|
||||
RadOperand bpos = g.rope_mc ? RAD_B_COL(w.bpos, 0, mc ? 3 : 1) : brows(w.bpos, work);
|
||||
if (g.rope_mc) bpos.rows = work;
|
||||
RAD_ISSUE_N(c_, op_work, T,
|
||||
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
kv_cache(c.kv_tail, layer),
|
||||
praw2(tlb->state_index, RAD_I32, S, tw),
|
||||
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
|
||||
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
|
||||
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
|
||||
brows(w.nc, S));
|
||||
RAD_ISSUE_N(c_, op_bkey, work,
|
||||
brows(w.stage, work * c.ratio), RAD_W(w_kn),
|
||||
brows(w.page, work), bpos,
|
||||
kv_cache(kv_bk, layer));
|
||||
if (part <= 1)
|
||||
RAD_ISSUE_N(c_, op_work, T,
|
||||
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
kv_cache(c.kv_tail, layer),
|
||||
praw2(tlb->state_index, RAD_I32, S, tw),
|
||||
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
|
||||
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
|
||||
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
|
||||
brows(w.nc, S));
|
||||
if (part == 1) return true;
|
||||
if (part == 0 || part == 2)
|
||||
RAD_ISSUE_N(c_, op_bkey, work,
|
||||
brows(w.stage, work * c.ratio), RAD_W(w_kn),
|
||||
brows(w.page, work), bpos,
|
||||
kv_cache(kv_bk, layer));
|
||||
if (part == 2) return true;
|
||||
RAD_ISSUE_N(c_, op_tail, T,
|
||||
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
@@ -313,13 +354,31 @@ inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batc
|
||||
}
|
||||
|
||||
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch,
|
||||
const int32_t* win_cu) const {
|
||||
const int32_t* win_cu, int use, bool first) const {
|
||||
if (!on()) return;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t qw = c.heads * c.head_dim;
|
||||
const int64_t nw = (c.heads + 1) * c.head_dim;
|
||||
|
||||
/* What the attention reads this step (QsaUse); anything asked of a step that cannot give it is
|
||||
* the full issue, which every reader accepts.
|
||||
*
|
||||
* kQsaOnce: the attention reads a selection on a step entirely at or below the exactness
|
||||
* bound. A row there has at most `topk` complete blocks, so qsa_select takes every one whose
|
||||
* key is not 0 -- every block with a page and a score that is a number, whatever the number --
|
||||
* and what it writes (the pages in block order, the partial page, their count, seqused) is a
|
||||
* function of the positions and the block table: the same bytes from every layer's scores. So
|
||||
* the pass's first full-attention layer issues the selection exactly as it always did, and
|
||||
* every later layer reads that one and issues none of its own: no query, no score. */
|
||||
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
|
||||
if (use != kQsaUnread) use = kQsaSelect;
|
||||
/* RADIANCE_DEBUG_QSA_EAGER: the issue sequence as it was, every layer its own. */
|
||||
if (qsa_eager()) use = kQsaSelect;
|
||||
|
||||
/* The projection always: its raw-key head is the block keys' and the tail's. */
|
||||
proj.step(c_, in, w.qk, T);
|
||||
/* The query heads are read by the score alone. */
|
||||
if (use == kQsaSelect) {
|
||||
/* One fused launch or `heads` + 1 unfused. The fused form takes the whole projection at its
|
||||
* row pitch and writes the query heads contiguous and rotated. `n_head` 0 is the k-only form:
|
||||
* no q_gate, q_w or q_out, and `gate_out` absent. `T <= qprep_rows` is a correctness bound
|
||||
@@ -336,8 +395,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
|
||||
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
|
||||
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
}
|
||||
|
||||
/* The keys first: the selection below reads the blocks they complete. */
|
||||
/* The keys first: the selection below reads the blocks they complete. The stateful half runs
|
||||
* whatever the attention reads: later steps score the block keys and build on the tail. */
|
||||
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
|
||||
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
|
||||
if (!atb || !store_keys(c_, batch)) return;
|
||||
@@ -346,6 +407,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
|
||||
* is a query row, so each query of a prefill chunk selects from the shared history, as the
|
||||
* checkpoint does. */
|
||||
if (!c.emit_sel) return;
|
||||
/* Nothing reads a selection of this layer's: the step is at or below the exactness bound and
|
||||
* its attention reads the block table, or the selection the pass's first full-attention layer
|
||||
* made (AttnGatedFP8::qsa_use). */
|
||||
if (use == kQsaUnread) return;
|
||||
|
||||
/* Narrow the score columns to the live history. Both kernels size their grid from the
|
||||
* operand's width (the live count is device data), so the full `max_ctx` width would make a
|
||||
|
||||
+14
-439
@@ -28,9 +28,10 @@
|
||||
* `dimensions` first), so the pooled row here is the unnormalised mean.
|
||||
*
|
||||
* Everything the checkpoint carries is declared: the text model, the vision tower
|
||||
* (rad_block_gemma4_vision.h) and the audio encoder.
|
||||
* (rad_block_gemma4_vision.h) and the audio encoder (rad_block_gemma4_audio.h).
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_gemma4_audio.h>
|
||||
#include <arch/rad_block_gemma4_vision.h>
|
||||
|
||||
#include <cmath>
|
||||
@@ -65,435 +66,6 @@ struct Layer {
|
||||
rad_op op_post_ple = 0, op_add_ple = 0, op_scale = 0;
|
||||
};
|
||||
|
||||
/* ============================== THE AUDIO ENCODER (Gemma 4's USM conformer) ==============================
|
||||
*
|
||||
* a frame is 128 log-mel bins (the processor's), four frames an output row
|
||||
* subsampling: two 3x3 stride-2 convolutions over (time, frequency) -- 1 -> 128 -> 32 channels,
|
||||
* each input masked to the clip's real frames first, each followed by a channel LayerNorm (no
|
||||
* bias) and a ReLU -- then 32 x 32 features a row through a 1024 linear
|
||||
* 12 conformer blocks: a feed-forward at half weight, local attention (11 frames back, a
|
||||
* relative-position term, a softplus per-dimension query scale, a softcap of 50), a gated
|
||||
* depthwise causal convolution, a second half-weight feed-forward, a norm; their linears are
|
||||
* clipped: input and output clamped to bounds the checkpoint stores
|
||||
* 1024 -> 1536 with a bias, then the multimodal embedder: an RMS norm with no gain, 1536 -> 512.
|
||||
*
|
||||
* The blocks' clamps at +-1e10 ("gradient clipping") are omitted: they are ten orders of magnitude
|
||||
* beyond the activations' range and change nothing. One clip is one segment; a pass carries up to
|
||||
* RadBuildCtx::max_audio_frames frames. */
|
||||
struct Audio {
|
||||
/* A clipped linear: the weight and its four bounds. */
|
||||
struct Clip {
|
||||
rad_weight w = 0, in_lo = 0, in_hi = 0, out_lo = 0, out_hi = 0;
|
||||
rad_op op_in = 0, op_mm = 0, op_out = 0;
|
||||
};
|
||||
struct FF {
|
||||
rad_weight pre = 0, post = 0;
|
||||
Clip l1, l2;
|
||||
rad_op op_pre = 0, op_act = 0, op_post = 0, op_add = 0;
|
||||
};
|
||||
struct Layer {
|
||||
FF ff1, ff2;
|
||||
rad_weight n_pre_attn = 0, n_post_attn = 0, n_out = 0, w_rel = 0, pds = 0;
|
||||
Clip q, k, v, post;
|
||||
rad_weight lc_pre = 0, lc_dw = 0, lc_norm = 0;
|
||||
Clip lc_start, lc_end;
|
||||
rad_op op_npa = 0, op_rel = 0, op_attn = 0, op_npo = 0, op_add_attn = 0;
|
||||
rad_op op_lc_pre = 0, op_glu = 0, op_dw = 0, op_lc_norm = 0, op_lc_act = 0, op_lc_add = 0;
|
||||
rad_op op_out = 0;
|
||||
};
|
||||
bool on = false;
|
||||
int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffw = 0, n_embd = 0, out_dims = 0;
|
||||
int64_t c0 = 0, c1 = 0, nmel = 0, merge = 4, left = 0, chunk = 0, n_rel = 0;
|
||||
double eps = 1e-6, softcap = 0;
|
||||
rad_weight w_c0 = 0, w_c1 = 0, w_n0 = 0, w_n1 = 0, w_in = 0, w_out = 0, b_outw = 0, w_emb = 0;
|
||||
rad_op op_c0 = 0, op_n0 = 0, op_r0 = 0, op_c1 = 0, op_n1 = 0, op_r1 = 0, op_in = 0;
|
||||
rad_op op_relpos = 0, op_outp = 0, op_en = 0, op_emb = 0;
|
||||
rad_buf b_s0 = 0, b_s1 = 0, b_x = 0, b_h = 0, b_hc = 0, b_f = 0, b_q = 0, b_k = 0, b_v = 0;
|
||||
rad_buf b_att = 0, b_o = 0, b_g = 0, b_u = 0, b_relpos = 0, b_relk = 0, b_o2 = 0, b_on = 0;
|
||||
rad_buf b_out = 0;
|
||||
std::vector<Layer> L;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_audio");
|
||||
}
|
||||
/* The longest clip in frames: 30 s at the extractor's 10 ms hop, rounded up to whole rows. */
|
||||
static int64_t frames_for(const RadModelMeta* m) {
|
||||
const int64_t rate = rad_meta_geti(m, "preprocessor.sampling_rate", 16000);
|
||||
const int64_t fl = rad_meta_geti(m, "preprocessor.frame_length", 320);
|
||||
const int64_t hop = rad_meta_geti(m, "preprocessor.hop_length", 160);
|
||||
if (rate <= 0 || hop <= 0) return 0;
|
||||
const int64_t n = 30 * rate;
|
||||
const int64_t real = (n + fl / 2 - fl - 1) / hop + 1;
|
||||
return (real + 3) / 4 * 4;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
|
||||
const char* A = "audio_config";
|
||||
auto gi = [&](const char* k, int64_t d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_geti(m, key, d);
|
||||
};
|
||||
auto gf = [&](const char* k, double d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_getf(m, key, d);
|
||||
};
|
||||
H = gi("hidden_size", 0);
|
||||
heads = gi("num_attention_heads", 0);
|
||||
out_dims = gi("output_proj_dims", 0);
|
||||
chunk = gi("attention_chunk_size", 0);
|
||||
/* transformers masks a key unless 0 <= q - k < attention_context_left - 1, so the
|
||||
* furthest key back is context_left - 2 frames: 11 for this checkpoint, the query and
|
||||
* eleven before it. */
|
||||
left = gi("attention_context_left", 0) - 2;
|
||||
softcap = gf("attention_logit_cap", 0.0);
|
||||
eps = gf("rms_norm_eps", 1e-6);
|
||||
const int64_t depth = gi("num_hidden_layers", 0);
|
||||
const int64_t kconv = gi("conv_kernel_size", 0);
|
||||
const int64_t right = gi("attention_context_right", 0);
|
||||
const double resw = gf("residual_weight", 0.0);
|
||||
const char* act = rad_meta_gets(m, "audio_config.hidden_act", "");
|
||||
const char* chs = rad_meta_gets(m, "audio_config.subsampling_conv_channels", "");
|
||||
nmel = rad_meta_geti(m, "preprocessor.feature_size", 0);
|
||||
if (std::sscanf(chs ? chs : "", "%lld %lld", (long long*)&c0, (long long*)&c1) != 2)
|
||||
c0 = c1 = 0;
|
||||
hd = heads > 0 ? H / heads : 0;
|
||||
ffw = 4 * H;
|
||||
n_rel = left + 1;
|
||||
if (H <= 0 || heads <= 0 || hd * heads != H || out_dims <= 0 || depth <= 0 || kconv <= 0 ||
|
||||
chunk <= 0 || left < 0 || right != 0 || !(softcap > 0) || resw != 0.5 ||
|
||||
std::strcmp(act ? act : "", "silu") || c0 <= 0 || c1 <= 0 || nmel != 128 ||
|
||||
(nmel / 4) * c1 != H) {
|
||||
fprintf(stderr, "radiance: embgemma2: the container's audio_config is not the "
|
||||
"conformer this plugin serves (hidden %lld, heads %lld, output %lld, "
|
||||
"layers %lld, conv %lld, left %lld right %lld, residual %g, act %s, "
|
||||
"subsampling %lld/%lld over %lld bins)\n", (long long)H,
|
||||
(long long)heads, (long long)out_dims, (long long)depth, (long long)kconv,
|
||||
(long long)left, (long long)right, resw, act ? act : "", (long long)c0,
|
||||
(long long)c1, (long long)nmel);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
P = ctx->max_audio_frames;
|
||||
if (P % merge) return RAD_E_SHAPE;
|
||||
R = P / merge;
|
||||
const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
const char* T = "audio_tower";
|
||||
|
||||
/* ---- weights */
|
||||
auto w = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
|
||||
};
|
||||
auto clip = [&](Clip& c, const char* dn, const char* src, int64_t out, int64_t in,
|
||||
RadWeightGroup g) {
|
||||
char d1[160], s1[200];
|
||||
std::snprintf(d1, sizeof d1, "%s.w", dn); std::snprintf(s1, sizeof s1, "%s.linear.weight", src);
|
||||
c.w = w(nm.f("%s", d1), nm.ckpt("%s", s1), {out, in}, g);
|
||||
const char* bn[4] = { "input_min", "input_max", "output_min", "output_max" };
|
||||
rad_weight* dst[4] = { &c.in_lo, &c.in_hi, &c.out_lo, &c.out_hi };
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
std::snprintf(d1, sizeof d1, "%s.%s", dn, bn[i]);
|
||||
std::snprintf(s1, sizeof s1, "%s.%s", src, bn[i]);
|
||||
*dst[i] = w(nm.f("%s", d1), nm.ckpt("%s", s1), {1}, g);
|
||||
}
|
||||
};
|
||||
w_c0 = w(nm.f("a.sscp.c0"), nm.ckpt("%s.subsample_conv_projection.layer0.conv.weight", T), {c0, 1, 3, 3}, grp_model());
|
||||
w_n0 = w(nm.f("a.sscp.n0"), nm.ckpt("%s.subsample_conv_projection.layer0.norm.weight", T), {c0}, grp_model());
|
||||
w_c1 = w(nm.f("a.sscp.c1"), nm.ckpt("%s.subsample_conv_projection.layer1.conv.weight", T), {c1, c0, 3, 3}, grp_model());
|
||||
w_n1 = w(nm.f("a.sscp.n1"), nm.ckpt("%s.subsample_conv_projection.layer1.norm.weight", T), {c1}, grp_model());
|
||||
w_in = w(nm.f("a.sscp.proj"), nm.ckpt("%s.subsample_conv_projection.input_proj_linear.weight", T), {H, H}, grp_model());
|
||||
w_out = w(nm.f("a.out.w"), nm.ckpt("%s.output_proj.weight", T), {out_dims, H}, grp_model());
|
||||
b_outw = w(nm.f("a.out.b"), nm.ckpt("%s.output_proj.bias", T), {out_dims}, grp_model());
|
||||
w_emb = w(nm.f("a.embed"), nm.ckpt("embed_audio.embedding_projection.weight"), {n_embd, out_dims}, grp_model());
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const long long li = (long long)i;
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
char d[96], s[160];
|
||||
auto D = [&](const char* x) { std::snprintf(d, sizeof d, "a.blk.%lld.%s", li, x); return nm.f("%s", d); };
|
||||
auto S = [&](const char* x) { std::snprintf(s, sizeof s, "%s.layers.%lld.%s", T, li, x); return nm.ckpt("%s", s); };
|
||||
for (int f = 0; f < 2; ++f) {
|
||||
FF& ff = f ? l.ff2 : l.ff1;
|
||||
const char* fn = f ? "feed_forward2" : "feed_forward1";
|
||||
char px[64]; std::snprintf(px, sizeof px, "%s.pre_layer_norm.weight", fn);
|
||||
ff.pre = w(D(px), S(px), {H}, g);
|
||||
std::snprintf(px, sizeof px, "%s.post_layer_norm.weight", fn);
|
||||
ff.post = w(D(px), S(px), {H}, g);
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l1", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_1", T, li, fn);
|
||||
clip(ff.l1, dn, sn, ffw, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l2", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_2", T, li, fn);
|
||||
clip(ff.l2, dn, sn, H, ffw, g);
|
||||
}
|
||||
l.n_pre_attn = w(D("norm_pre_attn"), S("norm_pre_attn.weight"), {H}, g);
|
||||
l.n_post_attn = w(D("norm_post_attn"), S("norm_post_attn.weight"), {H}, g);
|
||||
l.n_out = w(D("norm_out"), S("norm_out.weight"), {H}, g);
|
||||
l.w_rel = w(D("rel_k"), S("self_attn.relative_k_proj.weight"), {H, H}, g);
|
||||
l.pds = w(D("per_dim_scale"), S("self_attn.per_dim_scale"), {hd}, g);
|
||||
const char* qn[4] = { "q_proj", "k_proj", "v_proj", "post" };
|
||||
Clip* qc[4] = { &l.q, &l.k, &l.v, &l.post };
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.attn.%s", li, qn[j]);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.self_attn.%s", T, li, qn[j]);
|
||||
clip(*qc[j], dn, sn, H, H, g);
|
||||
}
|
||||
l.lc_pre = w(D("lconv.pre"), S("lconv1d.pre_layer_norm.weight"), {H}, g);
|
||||
l.lc_dw = w(D("lconv.dw"), S("lconv1d.depthwise_conv1d.weight"), {H, 1, kconv}, g);
|
||||
l.lc_norm = w(D("lconv.norm"), S("lconv1d.conv_norm.weight"), {H}, g);
|
||||
{
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.start", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_start", T, li);
|
||||
clip(l.lc_start, dn, sn, 2 * H, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.end", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_end", T, li);
|
||||
clip(l.lc_end, dn, sn, H, H, g);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- activations: the subsampler's planes at their own widths, the blocks' at R rows */
|
||||
b_s0 = decl_b(b, nm.f("a.s0"), RAD_BF16, {P / 2, (nmel / 2) * c0});
|
||||
b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {R, (nmel / 4) * c1});
|
||||
b_x = decl_b(b, nm.f("a.x"), RAD_BF16, {R, H});
|
||||
b_h = decl_b(b, nm.f("a.h"), RAD_BF16, {R, H});
|
||||
b_hc = decl_b(b, nm.f("a.hc"), RAD_BF16, {R, H});
|
||||
b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffw});
|
||||
b_q = decl_b(b, nm.f("a.q"), RAD_BF16, {R, H});
|
||||
b_k = decl_b(b, nm.f("a.k"), RAD_BF16, {R, H});
|
||||
b_v = decl_b(b, nm.f("a.v"), RAD_BF16, {R, H});
|
||||
b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
|
||||
b_o = decl_b(b, nm.f("a.o"), RAD_BF16, {R, H});
|
||||
b_g = decl_b(b, nm.f("a.g"), RAD_BF16, {R, 2 * H});
|
||||
b_u = decl_b(b, nm.f("a.u"), RAD_BF16, {R, H});
|
||||
b_relpos = decl_b(b, nm.f("a.relpos"), RAD_BF16, {n_rel, H});
|
||||
b_relk = decl_b(b, nm.f("a.relk"), RAD_BF16, {n_rel, H});
|
||||
b_o2 = decl_b(b, nm.f("a.o2"), RAD_BF16, {R, out_dims});
|
||||
b_on = decl_b(b, nm.f("a.on"), RAD_BF16, {R, out_dims});
|
||||
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
|
||||
|
||||
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight wt) {
|
||||
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
|
||||
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto rms = [&](int64_t rows, int64_t n, rad_weight wt, double mult) {
|
||||
if (!wt)
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("mult", mult)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto clamp = [&](int64_t rows, int64_t n, rad_weight lo, rad_weight hi) {
|
||||
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(lo, hi));
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto add = [&](int64_t rows, int64_t n) { return unary("add", rows, n); };
|
||||
auto lnorm = [&](int64_t rows, int64_t n, rad_weight g) {
|
||||
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(g));
|
||||
};
|
||||
auto conv = [&](int64_t rows, int64_t width, int64_t ci, int64_t co, int64_t cu_div,
|
||||
int64_t vstride, rad_weight wt) {
|
||||
return RAD_OP(b, "conv2d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
|
||||
RAD_INT("cin", ci), RAD_INT("cout", co),
|
||||
RAD_INT("kh", 3), RAD_INT("kw", 3),
|
||||
RAD_INT("stride", 2), RAD_INT("pad", 1),
|
||||
RAD_INT("cu_div", cu_div),
|
||||
RAD_INT("valid_stride", vstride),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
/* A clipped linear over rows of `in` into `out`: the input clamp writes a copy (the input
|
||||
* feeds several projections, each with its own bounds), the output clamp is in place. The
|
||||
* copy is a whole [R, n_in] buffer, since a GEMM's input must be contiguous. */
|
||||
auto clipped = [&](Clip& c, int64_t n_out, int64_t n_in, rad_buf in, rad_buf tmp,
|
||||
rad_buf out) {
|
||||
c.op_in = rw(b, clamp(R, n_in, c.in_lo, c.in_hi), {in}, {tmp});
|
||||
c.op_mm = rw(b, gemm(R, n_out, n_in, c.w), {tmp}, {out});
|
||||
c.op_out = rw(b, clamp(R, n_out, c.out_lo, c.out_hi), {out}, {out});
|
||||
};
|
||||
|
||||
op_c0 = rw(b, conv(P, nmel, 1, c0, 1, 1, w_c0), {}, {b_s0});
|
||||
op_n0 = rw(b, lnorm(P / 2 * (nmel / 2), c0, w_n0), {b_s0}, {b_s0});
|
||||
op_r0 = rw(b, unary("relu", P / 2 * (nmel / 2), c0), {b_s0}, {b_s0});
|
||||
op_c1 = rw(b, conv(P / 2, nmel / 2, c0, c1, 2, 2, w_c1), {b_s0}, {b_s1});
|
||||
op_n1 = rw(b, lnorm(R * (nmel / 4), c1, w_n1), {b_s1}, {b_s1});
|
||||
op_r1 = rw(b, unary("relu", R * (nmel / 4), c1), {b_s1}, {b_s1});
|
||||
op_in = rw(b, gemm(R, H, H, w_in), {b_s1}, {b_x});
|
||||
op_relpos = rw(b, RAD_OP(b, "rel_sinusoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, n_rel), RAD_INT("n", H),
|
||||
RAD_F64("max_timescale", 10000.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_relpos});
|
||||
for (Layer& l : L) {
|
||||
auto ffw_block = [&](FF& ff) {
|
||||
ff.op_pre = rw(b, rms(R, H, ff.pre, 1.0), {b_x}, {b_h});
|
||||
clipped(ff.l1, ffw, H, b_h, b_hc, b_f);
|
||||
ff.op_act = rw(b, unary("silu", R, ffw), {b_f}, {b_f});
|
||||
/* the activation's only reader is this linear, so its clamp is in place */
|
||||
clipped(ff.l2, H, ffw, b_f, b_f, b_o);
|
||||
ff.op_post = rw(b, rms(R, H, ff.post, 0.5), {b_o}, {b_o});
|
||||
ff.op_add = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
l.op_npa = rw(b, rms(R, H, l.n_pre_attn, 1.0), {b_x}, {b_h});
|
||||
clipped(l.q, H, H, b_h, b_hc, b_q);
|
||||
clipped(l.k, H, H, b_h, b_hc, b_k);
|
||||
clipped(l.v, H, H, b_h, b_hc, b_v);
|
||||
l.op_rel = rw(b, gemm(n_rel, H, H, l.w_rel), {b_relpos}, {b_relk});
|
||||
l.op_attn = rw(b, RAD_OP(b, "attn_local_rel",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head", heads), RAD_INT("left", left),
|
||||
RAD_INT("right", 0), RAD_F64("softcap", softcap),
|
||||
RAD_INT("cu_div", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.pds)),
|
||||
{b_q, b_k, b_v, b_relk}, {b_att});
|
||||
clipped(l.post, H, H, b_att, b_hc, b_o);
|
||||
l.op_npo = rw(b, rms(R, H, l.n_post_attn, 1.0), {b_o}, {b_o});
|
||||
l.op_add_attn = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
l.op_lc_pre = rw(b, rms(R, H, l.lc_pre, 1.0), {b_x}, {b_h});
|
||||
clipped(l.lc_start, 2 * H, H, b_h, b_hc, b_g);
|
||||
/* GLU: the first half times the sigmoid of the second. */
|
||||
l.op_glu = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_g}, {b_u});
|
||||
l.op_dw = rw(b, RAD_OP(b, "conv1d_dw",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_INT("k", kconv), RAD_INT("cu_div", merge),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.lc_dw)),
|
||||
{b_u}, {b_o});
|
||||
l.op_lc_norm = rw(b, rms(R, H, l.lc_norm, 1.0), {b_o}, {b_o});
|
||||
l.op_lc_act = rw(b, unary("silu", R, H), {b_o}, {b_o});
|
||||
clipped(l.lc_end, H, H, b_o, b_hc, b_u);
|
||||
l.op_lc_add = rw(b, add(R, H), {b_x, b_u}, {b_x});
|
||||
ffw_block(l.ff2);
|
||||
l.op_out = rw(b, rms(R, H, l.n_out, 1.0), {b_x}, {b_x});
|
||||
}
|
||||
op_outp = rw(b, RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", out_dims),
|
||||
RAD_INT("K", H), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(w_out, b_outw)),
|
||||
{b_x}, {b_o2});
|
||||
op_en = rw(b, rms(R, out_dims, 0, 1.0), {b_o2}, {b_on});
|
||||
op_emb = rw(b, gemm(R, n_embd, out_dims, w_emb), {b_on}, {b_out});
|
||||
|
||||
RadEncoderDecl e{};
|
||||
e.name = "audio";
|
||||
e.modalities = RAD_MM_AUDIO;
|
||||
e.patch_dim = nmel;
|
||||
e.merge = merge;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "audio encoder: %lld conformer blocks of %lld (%lld heads x %lld), "
|
||||
"subsampling %lld/%lld channels, local attention %lld back; %lld frames a "
|
||||
"pass -> %lld rows of %lld", (long long)depth, (long long)H, (long long)heads,
|
||||
(long long)hd, (long long)c0, (long long)c1, (long long)left, (long long)P,
|
||||
(long long)R, (long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % merge || S <= 0) {
|
||||
rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none "
|
||||
"declared, more frames than it was declared for, or not whole rows");
|
||||
return;
|
||||
}
|
||||
const int64_t Rn = Pn / merge;
|
||||
const int32_t* crd = batch->enc_coord;
|
||||
const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
|
||||
const RadOperand valid = praw(crd + Pn, RAD_I32, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
auto clipped = [&](const Clip& cl, rad_buf in, int64_t n_in, rad_buf tmp, rad_buf out,
|
||||
int64_t n_out) {
|
||||
RAD_ISSUE_N(c, cl.op_in, Rn, bcol(in, 0, n_in, Rn), RAD_W(cl.in_lo), RAD_W(cl.in_hi),
|
||||
bcol(tmp, 0, n_in, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_mm, Rn, bcol(tmp, 0, n_in, Rn), RAD_W(cl.w), bcol(out, 0, n_out, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_out, Rn, bcol(out, 0, n_out, Rn), RAD_W(cl.out_lo), RAD_W(cl.out_hi),
|
||||
bcol(out, 0, n_out, Rn));
|
||||
};
|
||||
|
||||
RAD_ISSUE_N(c, op_c0, Pn, frames, RAD_W(w_c0), cu, valid, brows(b_s0, Pn / 2), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_n0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), RAD_W(w_n0), RAD_NONE,
|
||||
brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_r0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_c1, Pn / 2, brows(b_s0, Pn / 2), RAD_W(w_c1), cu, valid, brows(b_s1, Rn),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_n1, Rn * (nmel / 4), brows(b_s1, Rn), RAD_W(w_n1), RAD_NONE,
|
||||
brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_r1, Rn * (nmel / 4), brows(b_s1, Rn), brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_in, Rn, brows(b_s1, Rn), RAD_W(w_in), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, op_relpos, n_rel, brows(b_relpos, n_rel));
|
||||
for (const Layer& l : L) {
|
||||
auto ffw_block = [&](const FF& ff) {
|
||||
RAD_ISSUE_N(c, ff.op_pre, Rn, brows(b_x, Rn), RAD_W(ff.pre), brows(b_h, Rn));
|
||||
clipped(ff.l1, b_h, H, b_hc, b_f, ffw);
|
||||
RAD_ISSUE_N(c, ff.op_act, Rn, brows(b_f, Rn), brows(b_f, Rn));
|
||||
clipped(ff.l2, b_f, ffw, b_f, b_o, H);
|
||||
RAD_ISSUE_N(c, ff.op_post, Rn, brows(b_o, Rn), RAD_W(ff.post), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, ff.op_add, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
RAD_ISSUE_N(c, l.op_npa, Rn, brows(b_x, Rn), RAD_W(l.n_pre_attn), brows(b_h, Rn));
|
||||
clipped(l.q, b_h, H, b_hc, b_q, H);
|
||||
clipped(l.k, b_h, H, b_hc, b_k, H);
|
||||
clipped(l.v, b_h, H, b_hc, b_v, H);
|
||||
RAD_ISSUE_N(c, l.op_rel, n_rel, brows(b_relpos, n_rel), RAD_W(l.w_rel),
|
||||
brows(b_relk, n_rel));
|
||||
RAD_ISSUE_N(c, l.op_attn, Rn, brows(b_q, Rn), brows(b_k, Rn), brows(b_v, Rn),
|
||||
brows(b_relk, n_rel), RAD_W(l.pds), cu, brows(b_att, Rn));
|
||||
clipped(l.post, b_att, H, b_hc, b_o, H);
|
||||
RAD_ISSUE_N(c, l.op_npo, Rn, brows(b_o, Rn), RAD_W(l.n_post_attn), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_add_attn, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_pre, Rn, brows(b_x, Rn), RAD_W(l.lc_pre), brows(b_h, Rn));
|
||||
clipped(l.lc_start, b_h, H, b_hc, b_g, 2 * H);
|
||||
RAD_ISSUE_N(c, l.op_glu, Rn, bcol(b_g, H, H, Rn), bcol(b_g, 0, H, Rn), brows(b_u, Rn));
|
||||
RAD_ISSUE_N(c, l.op_dw, Rn, brows(b_u, Rn), RAD_W(l.lc_dw), cu, brows(b_o, Rn),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, l.op_lc_norm, Rn, brows(b_o, Rn), RAD_W(l.lc_norm), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_act, Rn, brows(b_o, Rn), brows(b_o, Rn));
|
||||
clipped(l.lc_end, b_o, H, b_hc, b_u, H);
|
||||
RAD_ISSUE_N(c, l.op_lc_add, Rn, brows(b_x, Rn), brows(b_u, Rn), brows(b_x, Rn));
|
||||
ffw_block(l.ff2);
|
||||
RAD_ISSUE_N(c, l.op_out, Rn, brows(b_x, Rn), RAD_W(l.n_out), brows(b_x, Rn));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_outp, Rn, brows(b_x, Rn), RAD_W(w_out), RAD_W(b_outw), RAD_NONE,
|
||||
brows(b_o2, Rn));
|
||||
RAD_ISSUE_N(c, op_en, Rn, brows(b_o2, Rn), RAD_NONE, brows(b_on, Rn));
|
||||
RAD_ISSUE_N(c, op_emb, Rn, brows(b_on, Rn), RAD_W(w_emb), brows(b_out, Rn));
|
||||
}
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
@@ -511,10 +83,10 @@ struct Model {
|
||||
|
||||
std::vector<Layer> layers;
|
||||
Gemma4Vision vis;
|
||||
Audio aud;
|
||||
Gemma4Audio aud;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The layer schedule, read rather than derived: layer_types states which layers attend to the
|
||||
* whole input, and an assumed pattern would silently be wrong for a sibling checkpoint that
|
||||
@@ -551,7 +123,8 @@ static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector<
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
/* A 270M encoder fits easily on one card; tensor parallelism would only add an all-reduce per
|
||||
* layer, so it is not offered. */
|
||||
if (ctx->world_size > 1) {
|
||||
@@ -560,7 +133,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -700,7 +273,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* A media part's rows overwrite its placeholders' embeddings before anything reads them, so an
|
||||
* image token's per-layer inputs come from its image row (declared only with a tower). */
|
||||
if ((Gemma4Vision::present(meta) && ctx->max_enc_patches > 0) ||
|
||||
(Audio::present(meta) && ctx->max_audio_frames > 0))
|
||||
(Gemma4Audio::present(meta) && ctx->max_audio_frames > 0))
|
||||
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
@@ -816,8 +389,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{m.b_proj}, {m.b_pooled});
|
||||
|
||||
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, E, (int)g.n_layer, "", "embgemma2"));
|
||||
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, E,
|
||||
(int)g.n_layer + (int)m.vis.L.size()));
|
||||
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, E, (int)g.n_layer + (int)m.vis.L.size(), "",
|
||||
"embgemma2"));
|
||||
|
||||
int n_full = 0;
|
||||
for (int f : full) n_full += f;
|
||||
@@ -840,12 +413,12 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0);
|
||||
if (k > 0) out->enc_merge = k * k;
|
||||
}
|
||||
if (Audio::present(meta)) out->audio_frames = Audio::frames_for(meta);
|
||||
if (Gemma4Audio::present(meta)) out->audio_frames = Gemma4Audio::frames_for(meta);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
|
||||
if (batch->enc) {
|
||||
@@ -908,6 +481,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace embgemma2 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(embgemma2, "embeddinggemma2", "", "0.1.0",
|
||||
"EmbeddingGemma 2: a bidirectional Gemma encoder with per-layer embeddings, "
|
||||
"mean-pooled to one vector an input; bf16")
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/fishomni -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(fishomni LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(fishomni architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/fishomni.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(flint LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(flint architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flint.cpp)
|
||||
@@ -0,0 +1,542 @@
|
||||
/* flint -- Recursive Flint (39.8B-A2.5B): two dense layers then 47 sigmoid-routed MoE layers,
|
||||
* grouped-query attention with per-head Q/K RMSNorm, a learned per-head softmax sink, and a
|
||||
* 513-token sliding window on 35 of the 49 layers (the other 14 are full attention and NoPE).
|
||||
*
|
||||
* 2 dense layers: rmsnorm -> q/k/v -> qk-norm -> [rope] -> paged attention + sink -> o
|
||||
* rmsnorm -> gate_up -> silu_mul -> down
|
||||
* 47 MoE layers: same attention; rmsnorm -> router -> top-6 of 256 (sigmoid)
|
||||
* -> grouped gate_up -> silu_mul -> down -> gather
|
||||
* + ungated shared expert (2 x 512)
|
||||
*
|
||||
* Weights come from a BF16 or recipe-quantized Flint checkpoint; the blocks probe the stored
|
||||
* encoding. Two trunk forms, read from layer 0's q projection:
|
||||
*
|
||||
* - a rotated int8 trunk (data/recipes/flint-iq8r.recipe: IQ8R linears, i8 codes rotated by a
|
||||
* 128-wide Hadamard): the norms, the gated products and the attention output write
|
||||
* had_quant_act_i8g's codes themselves, every linear reads them at i8a8h, and the routed
|
||||
* experts are rotated int8 (or another form with an int8 row) read by the grouped GEMM's int8
|
||||
* rows from the same codes (MoeFP8::a8), as qwen35moe_w8a8 serves Qwen3.6-35B-A3B;
|
||||
* - any other (bf16, the four-bit attention of data/recipes/flint-bf16-q4.recipe, plain int8
|
||||
* linears): each linear reads the bf16 plane or quantises it itself, and four-bit experts read
|
||||
* the block input's E4M3 pair, as hyv3_bf16 serves its W4 and W8 recipes.
|
||||
*
|
||||
* No MTP head.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include "flint_attention.h"
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include "rad_abi_layout.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace flint {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool dense = false;
|
||||
bool sliding = false;
|
||||
FlintAttn attn{};
|
||||
MlpFP8 dense_mlp{};
|
||||
MoeFP8 moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
int64_t n_ff_expert = 0, n_ff_shared = 0;
|
||||
rad_kvgroup kv_full = 0, kv_win = 0;
|
||||
/* Whether layer 0's probe found a rotated-int8 trunk, and its activation scale group: see
|
||||
* rad_fp8.h's trunk_rotation. */
|
||||
bool trunk_rot = false;
|
||||
int64_t trunk_g8 = RAD_FP8_BLOCK;
|
||||
|
||||
rad_buf x = 0, h_out = 0, logits = 0;
|
||||
ActFP8 h{};
|
||||
/* The routed experts' rotated int8 copy of the block input, where a rotated trunk's norms do
|
||||
* not write the codes themselves (MoeFP8::Wire::hr). */
|
||||
ActFP8 hr{};
|
||||
rad_buf q = 0, k = 0, v = 0;
|
||||
ActFP8 attn{};
|
||||
rad_buf dense_gate_up = 0;
|
||||
ActFP8 dense_ffn{};
|
||||
MoeFP8::Wire mw{};
|
||||
|
||||
rad_weight token = 0, final_norm = 0, lm_head = 0;
|
||||
rad_op embed = 0, embed_ar = 0, shared_one = 0, final_rms = 0, gather = 0, logits_op = 0;
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
/* Every per-instance state is indexed by slot (rad_build_slot at declare, rad_slot in step). */
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* Flint's layer schedule: full attention (and NoPE) at 0, 1, 5, 9, ..., 45, 48; the other 35
|
||||
* layers are sliding (window 513) and carry RoPE. */
|
||||
static bool is_full(int64_t l) {
|
||||
return l == 0 || l == 1 || l == 48 || (l >= 5 && l <= 45 && (l - 5) % 4 == 0);
|
||||
}
|
||||
|
||||
static int64_t meta_i(const RadModelMeta* meta, const char* a, const char* b, int64_t def) {
|
||||
int64_t v = meta_text_geti(meta, a, INT64_MIN);
|
||||
if (v == INT64_MIN && b) v = meta_text_geti(meta, b, INT64_MIN);
|
||||
return v == INT64_MIN ? def : v;
|
||||
}
|
||||
|
||||
static int check_model(const RadModelMeta* meta, const Geom& g, Model& m) {
|
||||
const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513);
|
||||
const int64_t n_expert = meta_text_geti(meta, "num_experts", meta->n_expert);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
|
||||
const int64_t moe_ff = meta_i(meta, "moe_intermediate_size",
|
||||
"flint.expert_feed_forward_length", 512);
|
||||
const int64_t shared = meta_i(meta, "shared_expert_intermediate_size",
|
||||
"flint.expert_shared_feed_forward_length", 1024);
|
||||
const int64_t dense_ff = meta_i(meta, "intermediate_size",
|
||||
"flint.feed_forward_length", 6144);
|
||||
|
||||
if (g.n_layer != 49 || g.n_embd != 2048 || g.n_head_all != 32 || g.n_head_kv_all != 4 ||
|
||||
g.head_dim != 128 || g.n_vocab_all != 150144 || dense_ff != 6144 ||
|
||||
sliding != 513 || n_expert != 256 || top_k != 6 || moe_ff != 512 || shared != 1024) {
|
||||
fprintf(stderr, "radiance: flint: unsupported geometry (49 layers, 2048-wide, 32/4 "
|
||||
"heads x 128, vocab 150144, 256 experts top-6, expert width 512, shared "
|
||||
"1024, sliding 513); got %lld layers, %lld-wide, %lld/%lld heads, "
|
||||
"vocab %lld, %lld experts top-%lld, expert %lld, shared %lld, "
|
||||
"sliding %lld, dense %lld\n",
|
||||
(long long)g.n_layer, (long long)g.n_embd, (long long)g.n_head_all,
|
||||
(long long)g.n_head_kv_all, (long long)g.n_vocab_all, (long long)n_expert,
|
||||
(long long)top_k, (long long)moe_ff, (long long)shared, (long long)sliding,
|
||||
(long long)dense_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (g.world != 1 && g.world != 2) {
|
||||
fprintf(stderr, "radiance: flint supports tensor-parallel world sizes 1 and 2\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.n_ff_expert = moe_ff;
|
||||
m.n_ff_shared = shared;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
|
||||
const int64_t blocks = width / RAD_FP8_BLOCK;
|
||||
const int64_t base = blocks / world, rem = blocks % world;
|
||||
const int64_t first = rank * base + std::min<int64_t>(rank, rem);
|
||||
const int64_t count = base + (rank < rem ? 1 : 0);
|
||||
*lo = first * RAD_FP8_BLOCK;
|
||||
*hi = (first + count) * RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
|
||||
int status = geom_from(m.g, meta, ctx, "bf16", RAD_BF16);
|
||||
if (status < 0) return status;
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
status = check_model(meta, g, m);
|
||||
if (status < 0) return status;
|
||||
|
||||
if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) {
|
||||
fprintf(stderr, "radiance: flint serves a bf16 or an int8 KV cache, not %s\n",
|
||||
rad_dtype_name((uint32_t)ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
status = yarn_from(g, meta, "", g.head_dim);
|
||||
if (status < 0) return status;
|
||||
|
||||
const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513);
|
||||
const int64_t n_expert_all = meta_text_geti(meta, "num_experts", meta->n_expert);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
|
||||
if (n_expert_all % g.world != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_expert_local = n_expert_all / g.world;
|
||||
|
||||
/* Two paged groups: the 14 full layers grow with the context, the 35 sliding layers keep
|
||||
* only 513 tokens. That is what makes 262K affordable. Both take the deployment's cache
|
||||
* dtype: bf16, or with --kv-cache-dtype i8 the int8 cache (abi/rad_builder.h), K and V as
|
||||
* int8 codes with one f16 scale each per token and head. */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
kd.n_head_kv = g.n_head_kv;
|
||||
kd.head_dim = g.head_dim;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_full"), &kd);
|
||||
if (!m.kv_full) return RAD_E_INVAL;
|
||||
|
||||
RadKVGroupDecl kw = kd;
|
||||
kw.kind = RAD_KV_WINDOW;
|
||||
kw.window = sliding;
|
||||
m.kv_win = rad_decl_kv_group(b, nm.f("kv_win"), &kw);
|
||||
if (!m.kv_win) return RAD_E_INVAL;
|
||||
g.kv_dtype = rad_dtype_name(kd.dtype);
|
||||
|
||||
const int64_t T = g.max_tok, qd = g.q_dim(), kvd = g.kv_dim();
|
||||
|
||||
/* The trunk's stored form, probed from layer 0's q projection: rad_fp8.h's trunk_rotation
|
||||
* answers whether it is rotated int8 and how wide the activation codes' scale group is. */
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
RAD_ARCH_TRY(m.layers[0].attn.q.probe(b, nm, g, nm.f("blk.0.attn_q"),
|
||||
{ nm.ckpt("model.layers.0.self_attn.q_proj.weight") }));
|
||||
{
|
||||
RadEncoding enc{};
|
||||
m.trunk_rot = weight_enc(b, nm.f("blk.0.attn_q.weight"), &enc) &&
|
||||
trunk_rotation(enc, &m.trunk_g8);
|
||||
}
|
||||
|
||||
MoeFP8::Config mc{};
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.n_expert = n_expert_local;
|
||||
mc.expert_base = n_expert_local * g.rank;
|
||||
mc.probed_expert = mc.expert_base;
|
||||
mc.top_k = top_k;
|
||||
mc.n_ff_exp = m.n_ff_expert;
|
||||
mc.norm_topk = 1;
|
||||
mc.sigmoid_router = 1;
|
||||
mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0);
|
||||
mc.shared_ungated = 1;
|
||||
/* One combine at the gather, not two separately reduced arms: TP2 then matches the TP1
|
||||
* arithmetic (the local routed+shared sum is rounded to bf16 once and the closing
|
||||
* all-reduce reduces it), and that single collective folds into the next block's norm. */
|
||||
mc.shared_fp32_combine = 0;
|
||||
mc.shared_one_external = g.world == 1;
|
||||
mc.router_fuse = 1;
|
||||
mc.rows = T < 2048 ? T : 2048;
|
||||
block_slice_128(m.n_ff_shared, g.world, g.rank, &mc.shared_lo, &mc.shared_hi);
|
||||
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
|
||||
|
||||
/* ---- the routed experts' stored form, read from the first routed layer's first owned
|
||||
* expert; every layer is declared with it (MoeFP8::declare checks each layer's own). */
|
||||
const int64_t l_moe = 2;
|
||||
MoeFP8::Src probe_src{};
|
||||
probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l_moe);
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)l_moe, probe_src, &mc));
|
||||
if (m.trunk_rot && (mc.expert_bf16 || !mc.expert_rot)) {
|
||||
fprintf(stderr, "radiance: flint: the trunk is rotated int8 and the routed experts are "
|
||||
"%s; a rotated trunk's experts read its int8 codes and are stored rotated "
|
||||
"(data/recipes/flint-iq8r.recipe)\n",
|
||||
mc.expert_bf16 ? "plain bf16" : "unrotated");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!m.trunk_rot && (mc.expert_i8 || mc.expert_iqr)) {
|
||||
fprintf(stderr, "radiance: flint: the routed experts are rotated int8 and the trunk is "
|
||||
"not; they read the trunk's rotated int8 codes, so convert the trunk with "
|
||||
"them (data/recipes/flint-iq8r.recipe)\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- activation buffers. A rotated trunk's producers write had_quant_act_i8g's codes and
|
||||
* its linears declare no quantiser: the norms (rmsnorm_had_quant_i8g and, at two ranks, its
|
||||
* all-reduce form) where a loaded library serves them, the attention output (q_attn), and the
|
||||
* gated products (gated_had_quant_i8g). Where the norms are not served, each linear
|
||||
* quantises `h` itself and the experts read `hr`, written once a layer. Any other trunk keeps
|
||||
* both code pairs on `h`: E4M3 for four-bit experts, int8 for a plain int8 linear's own
|
||||
* quantiser. */
|
||||
const bool rot = m.trunk_rot;
|
||||
const int64_t g8 = m.trunk_g8;
|
||||
const bool h_fed = rot && rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g"));
|
||||
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, g.n_embd});
|
||||
m.h.x = decl_b(b, nm.f("h"), RAD_BF16, {T, g.n_embd});
|
||||
RAD_ARCH_TRY(m.h.declare_qs(b, nm, g, "h", g.n_embd, 0, true, !h_fed,
|
||||
rot ? g8 : (int64_t)RAD_FP8_BLOCK));
|
||||
m.h.q8_fed = m.h.q8_rot = h_fed;
|
||||
if (rot && !h_fed) {
|
||||
RAD_ARCH_TRY(m.hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
m.hr.q8_fed = m.hr.q8_rot = true;
|
||||
}
|
||||
m.q = decl_b(b, nm.f("attn_q"), RAD_BF16, {T, qd});
|
||||
m.k = decl_b(b, nm.f("attn_k"), RAD_BF16, {T, kvd});
|
||||
m.v = decl_b(b, nm.f("attn_v"), RAD_BF16, {T, kvd});
|
||||
m.attn.x = decl_b(b, nm.f("attn_out"), RAD_BF16, {T, qd});
|
||||
RAD_ARCH_TRY(m.attn.declare_qs(b, nm, g, "attn_out", qd, 0, true, false,
|
||||
rot ? g8 : (int64_t)RAD_FP8_BLOCK));
|
||||
m.attn.q8_fed = m.attn.q8_rot = rot;
|
||||
m.dense_gate_up = decl_b(b, nm.f("dense_gate_up"), RAD_BF16, {T, 2 * g.n_ff});
|
||||
m.dense_ffn.x = decl_b(b, nm.f("dense_ffn"), RAD_BF16, {T, g.n_ff});
|
||||
if (rot)
|
||||
RAD_ARCH_TRY(m.dense_ffn.declare_pair(b, nm, g, "dense_ffn", g.n_ff, 0, true, g8,
|
||||
"gated_had_quant_i8g"));
|
||||
else
|
||||
RAD_ARCH_TRY(m.dense_ffn.declare_qs(b, nm, g, "dense_ffn", g.n_ff, 0, true));
|
||||
m.h_out = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
|
||||
|
||||
const int64_t R = T, S = mc.rows * top_k;
|
||||
m.mw.x = m.x;
|
||||
m.mw.h = m.h;
|
||||
m.mw.hr = m.hr;
|
||||
m.mw.logits = decl_b(b, nm.f("moe_logits"), RAD_F32, {R, n_expert_all});
|
||||
m.mw.ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, top_k});
|
||||
m.mw.ew = decl_b(b, nm.f("moe_weights"), RAD_F32, {R, top_k});
|
||||
m.mw.eoff = decl_b(b, nm.f("moe_offsets"), RAD_I32, {n_expert_local + 1});
|
||||
m.mw.ecnt = decl_b(b, nm.f("moe_counts"), RAD_I32, {n_expert_local}, RAD_BUF_PERSIST);
|
||||
m.mw.sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {S});
|
||||
m.mw.egu = decl_b(b, nm.f("moe_gate_up"), RAD_BF16, {S, 2 * mc.n_ff_exp});
|
||||
m.mw.eff.x = decl_b(b, nm.f("moe_ffn"), RAD_BF16, {S, mc.n_ff_exp});
|
||||
if (rot) {
|
||||
/* The routed arm of a rotated trunk is int8 throughout: the gated product's rotated codes
|
||||
* at one scale a 128 of K, which the grouped GEMM's int8 rows read (MoeFP8::a8). */
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
m.mw.eff.q8_fed = m.mw.eff.q8_rot = true;
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true));
|
||||
}
|
||||
m.mw.edn = decl_b(b, nm.f("moe_down"), RAD_BF16, {S, g.n_embd});
|
||||
m.mw.sgu = decl_b(b, nm.f("shared_gate_up"), RAD_BF16, {T, 2 * mc.n_ff_shared});
|
||||
m.mw.sff.x = decl_b(b, nm.f("shared_ffn"), RAD_BF16, {T, mc.n_ff_shared});
|
||||
if (rot) {
|
||||
/* The shared expert's down projection is a trunk linear whose input codes take the group
|
||||
* its own weight is stored at, read from the first routed layer's through that layer's
|
||||
* own LinearFP8 (which then maps it once). */
|
||||
LinearFP8& sd = m.layers[(size_t)l_moe].moe.sh_down;
|
||||
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.%lld.ffn_down_shexp", (long long)l_moe),
|
||||
{ nm.ckpt("model.layers.%lld.mlp.shared_expert.down_proj.weight",
|
||||
(long long)l_moe) }));
|
||||
const int64_t sg = sd.probed_i8 ? sd.probed_g8 : g8;
|
||||
RAD_ARCH_TRY(m.mw.sff.declare_pair(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true, sg,
|
||||
"gated_had_quant_i8g"));
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.mw.sff.declare_qs(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true));
|
||||
}
|
||||
m.mw.sout = decl_b(b, nm.f("shared_out"), RAD_BF16, {T, g.n_embd});
|
||||
m.mw.sgate = decl_b(b, nm.f("shared_one"), RAD_BF16, {T, 1});
|
||||
if (mc.shared_one_external) {
|
||||
m.shared_one = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 1),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
|
||||
RAD_NOWEIGHTS), {}, {m.mw.sgate});
|
||||
if (!m.shared_one) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.embed_tokens.weight")));
|
||||
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.final_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.token)),
|
||||
{}, {m.x});
|
||||
if (g.world > 1)
|
||||
m.embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.x}, {m.x});
|
||||
|
||||
FlintAttn::Wire aw{};
|
||||
aw.x = m.x; aw.h = m.h; aw.q = m.q; aw.k = m.k; aw.v = m.v; aw.attn = m.attn;
|
||||
MlpFP8::Wire dw{};
|
||||
dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn;
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.dense = (l < 2);
|
||||
lay.sliding = !is_full(l);
|
||||
const char* pre = nm.ckpt("model.layers.%lld", (long long)l);
|
||||
|
||||
FlintAttn::Src as{};
|
||||
as.norm = nm.ckpt("%s.input_layernorm.weight", pre);
|
||||
as.q = nm.ckpt("%s.self_attn.q_proj.weight", pre);
|
||||
as.k = nm.ckpt("%s.self_attn.k_proj.weight", pre);
|
||||
as.v = nm.ckpt("%s.self_attn.v_proj.weight", pre);
|
||||
as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre);
|
||||
as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre);
|
||||
as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre);
|
||||
as.sink = nm.ckpt("%s.self_attn.softmax_offset", pre);
|
||||
as.use_rope = lay.sliding;
|
||||
as.window = lay.sliding ? sliding : 0;
|
||||
|
||||
const rad_kvgroup grp = lay.sliding ? m.kv_win : m.kv_full;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, grp));
|
||||
/* Every block after the first folds the previous block's delta and, at two ranks,
|
||||
* absorbs its all-reduce into its own norm; the last block keeps its add for the plain
|
||||
* final norm and issues its own collective. */
|
||||
const LayerFold f = layer_fold(g, l, g.n_layer, nullptr, 0, false);
|
||||
status = lay.attn.declare(b, nm, g, (int)l, grp, aw, as, f.mix_fold, false, f.mix_ar_in,
|
||||
f.mix_ar_out);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: flint: attention layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{};
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ds.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.gate_proj.weight", mlp);
|
||||
ds.up = nm.ckpt("%s.up_proj.weight", mlp);
|
||||
ds.down = nm.ckpt("%s.down_proj.weight", mlp);
|
||||
status = lay.dense_mlp.declare(b, nm, g, (int)l, dw, ds, true, f.mlp_add,
|
||||
f.mlp_ar_in, f.mlp_ar_out);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: flint: dense layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
} else {
|
||||
MoeFP8::Src ms{};
|
||||
ms.cfg = mc;
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.gate.weight", mlp);
|
||||
/* Flint has no router correction bias. The sigmoid router's bias is
|
||||
* selection-only, so the converter merges a zero [n_expert] tensor under this
|
||||
* name (data/flint-zero-bias.safetensors, `rad-convert --add`). */
|
||||
ms.router_bias = nm.ckpt("%s.expert_bias", mlp);
|
||||
ms.experts = nm.ckpt("%s.experts", mlp);
|
||||
ms.shared = nm.ckpt("%s.shared_expert", mlp);
|
||||
status = lay.moe.declare(b, nm, g, (int)l, m.mw, ms, true, f.mlp_add, f.mlp_ar_in,
|
||||
f.mlp_ar_out);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: flint: MoE layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m.final_rms = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.final_norm)),
|
||||
{m.x}, {m.h.x});
|
||||
m.gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.h.x}, {m.h_out});
|
||||
m.logits_op = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.lm_head)),
|
||||
{m.h_out}, {m.logits});
|
||||
|
||||
rad_note(b, "Flint: %lld layers (2 dense, 47 top-%lld/%lld sigmoid MoE), %lld/%lld "
|
||||
"attention/KV heads x %lld; expert width %lld, shared %lld, window %lld on %s; "
|
||||
"per-head sink on every layer; %s trunk, %s KV cache",
|
||||
(long long)g.n_layer, (long long)top_k, (long long)n_expert_all,
|
||||
(long long)g.n_head_all, (long long)g.n_head_kv_all, (long long)g.head_dim,
|
||||
(long long)m.n_ff_expert, (long long)mc.n_ff_shared, (long long)sliding,
|
||||
g.world == 2 ? "both cards" : "one card",
|
||||
rot ? (g8 == RAD_I8_GROUP_WIDE ? "IQ8R (rotated int8)" : "rotated int8") : "unrotated",
|
||||
g.kv_dtype);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
RAD_ISSUE(c, m.embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token),
|
||||
brows(m.x, batch->n_tok));
|
||||
if (m.embed_ar)
|
||||
RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.x, batch->n_tok), RAD_NONE);
|
||||
|
||||
if (m.shared_one)
|
||||
RAD_ISSUE_N(c, m.shared_one, batch->n_tok, brows(m.mw.sgate, batch->n_tok));
|
||||
for (Layer& layer : m.layers) {
|
||||
layer.attn.step(c, batch);
|
||||
if (layer.dense) layer.dense_mlp.step(c, batch);
|
||||
else layer.moe.step(c, batch);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.final_rms, brows(m.x, batch->n_tok), RAD_W(m.final_norm),
|
||||
brows(m.h.x, batch->n_tok));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.gather, batch->n_out,
|
||||
brows(m.h.x, batch->n_tok), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.h_out, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.logits_op, batch->n_out,
|
||||
brows(m.h_out, batch->n_out), RAD_W(m.lm_head),
|
||||
brows(m.logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace flint
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(flint)
|
||||
static const char* const kFlintTriggers[] = { "<tool_call>" };
|
||||
static const RadChatFormat kFlintChatFormat = {
|
||||
.struct_size = sizeof(RadChatFormat),
|
||||
.name = "flint",
|
||||
.reasoning_open = "<think>",
|
||||
.reasoning_close = "</think>",
|
||||
.reasoning_breaks = kFlintTriggers,
|
||||
.n_reasoning_breaks = 1,
|
||||
.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT,
|
||||
.section_open = nullptr,
|
||||
.section_close = nullptr,
|
||||
.call_separator = nullptr,
|
||||
.call_open = nullptr,
|
||||
.call_close = nullptr,
|
||||
.name_prefix = "<tool_call>",
|
||||
.name_suffix = "",
|
||||
.call_end = "</tool_call>",
|
||||
.arg_prefix = "<arg_key>",
|
||||
.arg_name_suffix = "</arg_key>",
|
||||
.arg_value_prefix = "<arg_value>",
|
||||
.arg_value_suffix = "</arg_value>",
|
||||
.string_value = RAD_CHAT_VALUE_RAW,
|
||||
.other_value = RAD_CHAT_VALUE_JSON,
|
||||
.value_newlines = 1,
|
||||
.triggers = kFlintTriggers,
|
||||
.n_triggers = 1,
|
||||
.args_form = RAD_CHAT_ARGS_TAGGED,
|
||||
};
|
||||
extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
|
||||
return &kFlintChatFormat;
|
||||
}
|
||||
extern "C" const char* rad_arch_id(void) { return "flint"; }
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
extern "C" const char* rad_arch_quant(void) { return ""; }
|
||||
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
|
||||
return flint::declare(b, m, c);
|
||||
}
|
||||
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
|
||||
flint::step(c, batch);
|
||||
}
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
RAD_PLUGIN_ABI_LAYOUT_EXPORT
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) {
|
||||
static const RadPluginInfo info = {
|
||||
RAD_PLUGIN_ARCH, "flint", "0.1.0",
|
||||
"Recursive Flint: 2 dense + 47 sigmoid MoE layers, sink attention, 513 window", ""
|
||||
};
|
||||
return &info;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,272 @@
|
||||
/* flint_attention.h -- Flint's grouped-query attention: per-head Q/K RMSNorm, optional NeoX
|
||||
* RoPE (sliding layers) or no positional encoding (full layers), a learned per-head softmax
|
||||
* sink, a paged bf16 or int8 KV cache, and an optional sliding window.
|
||||
*
|
||||
* Derived from arch/hyv3_common/hyv3_attention.h (the same linears and activation plumbing); the
|
||||
* differences are Flint's:
|
||||
*
|
||||
* - every layer has `self_attn.softmax_offset` (GGUF `attn_sinks`), one learned logit a query
|
||||
* head added to the scaled scores before the softmax;
|
||||
* - the full-attention layers are NoPE, the sliding layers carry NeoX RoPE;
|
||||
* - the sliding layers bound the paged attention with `window` (513).
|
||||
*
|
||||
* The sink and the window ride in attn_paged_sink, which libr4d serves at h128/gqa8 on both
|
||||
* caches. The block's closing all-reduce may be taken by the next block's norm (ar_out).
|
||||
*/
|
||||
#ifndef FLINT_ATTENTION_H
|
||||
#define FLINT_ATTENTION_H
|
||||
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct FlintAttn {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */
|
||||
rad_buf q = 0; /* [max_tok, q_dim], projected, normed and rotated */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim] */
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* q = nullptr;
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
const char* o = nullptr;
|
||||
/* `self_attn.softmax_offset` (no `.weight` suffix). Null declares no sink. */
|
||||
const char* sink = nullptr;
|
||||
bool use_rope = true;
|
||||
int64_t window = 0; /* 0: full attention */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0, w_sink = 0;
|
||||
LinearFP8 q{}, k{}, v{}, o{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
rad_op op_q_norm = 0, op_k_norm = 0;
|
||||
rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0;
|
||||
rad_op op_qkr_store = 0; /* Q/K norms, NeoX rotary (or none) and cache store, decode band */
|
||||
int64_t qkr_rows = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* The next block's norm absorbs this block's closing all-reduce (NormQuantFP8::fuse_ar), so
|
||||
* this one must not issue it. Counterpart of `ar_in`; both sides ask ar_taken(g, T, ...) on
|
||||
* the same facts, so they agree. */
|
||||
bool ar_out = false;
|
||||
int ar_out_take = kArOutNorm;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int FlintAttn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, const Wire& wire, const Src& src,
|
||||
bool fold, bool add_out, int ar_in, bool ar_out_) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
layer = l;
|
||||
kv = group;
|
||||
ar_out = ar_out_;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: flint declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld\n", g.world, (long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
if (!w_norm || !w_q_norm || !w_k_norm) return RAD_E_INVAL;
|
||||
|
||||
/* The learned softmax offset, one f32 a query head, sharded with the heads. */
|
||||
if (src.sink) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_sinks", l), src.sink));
|
||||
w_sink = decl_w(b, nm.f("blk.%d.attn_sinks", l), RAD_F32, {g.n_head},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
if (!w_sink) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
// As in the other pre-norm blocks, absorb a preceding delta into the residual stream.
|
||||
// The fused kernel normalizes the BF16-rounded sum, not an unrounded FP32 substitute.
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0, 0, ar_in));
|
||||
RAD_ARCH_TRY(q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), q_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.q}, w.h, w.q));
|
||||
RAD_ARCH_TRY(k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.k}, w.h, w.k));
|
||||
RAD_ARCH_TRY(v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.v}, w.h, w.v));
|
||||
|
||||
auto head_norm = [&](int64_t heads, rad_weight wt) {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q});
|
||||
op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
|
||||
if (src.use_rope) {
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
|
||||
"neox"),
|
||||
{w.k}, {w.k});
|
||||
}
|
||||
|
||||
const rad_op attn = w_sink
|
||||
? rw(b, RAD_OP(b, "attn_paged_sink",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", src.window), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_WEIGHTS(w_sink)),
|
||||
{w.q}, {w.attn.x})
|
||||
: rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", src.window), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn.x});
|
||||
op_attn = attn;
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* The fused prologue serves the rope layers and, with `rotary_dim` 0, the NoPE ones: the
|
||||
* kernel then only copies the normed head through the rotary stage. Rows exist for the bf16
|
||||
* and the int8 cache (qkv_norm_rope_kv_store_h128_bf16, _i8); prefill heights and libraries
|
||||
* without the fold take the standalone norms, ropes and kv_store. */
|
||||
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
|
||||
(!std::strcmp(g.kv_dtype, "bf16") || !std::strcmp(g.kv_dtype, "i8")) &&
|
||||
!g.rope_mc && g.yarn.factor == 0.0f &&
|
||||
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
|
||||
qkr_rows = qk_fuse_rows(g);
|
||||
op_qkr_store = RAD_OP(b, "qkv_norm_rope_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qkr_rows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
|
||||
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("v_norm", 0),
|
||||
RAD_INT("rotary_dim", src.use_rope ? g.head_dim : 0),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm));
|
||||
if (!op_qkr_store || !rad_op_resolved(b, op_qkr_store)) op_qkr_store = 0;
|
||||
if (op_qkr_store)
|
||||
op_qkr_store = rw(b, op_qkr_store, {w.q, w.k, w.v}, {w.q, w.k, w.v});
|
||||
}
|
||||
|
||||
/* The out projection's input codes: where the model feeds them (a rotated int8 trunk,
|
||||
* ActFP8::q8_fed), q_attn writes had_quant_act_i8g's pair and the projection declares no
|
||||
* quantiser. Otherwise every form the out projection can take reads the bf16 plane or
|
||||
* quantises it itself (LinearFP8 refuses the E4M3-pair formats), so no quantiser runs here. */
|
||||
if (w.attn.q8_fed) RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
|
||||
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), {src.o}, w.attn, w.h.x));
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
if (add_out) op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
/* A rope layer needs either the fused prologue or both standalone rope ops; without this,
|
||||
* step() would silently skip the rotation. */
|
||||
const bool rope_ok = !src.use_rope || op_qkr_store || (op_rope_q && op_rope_k);
|
||||
return op_attn && op_kv_store && rope_ok && (!add_out || op_add) &&
|
||||
(op_qkr_store || (op_q_norm && op_k_norm))
|
||||
? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
inline void FlintAttn::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
nq_h.step(c, T);
|
||||
q.step(c, w.h, w.q, T);
|
||||
k.step(c, w.h, w.k, T);
|
||||
v.step(c, w.h, w.v, T);
|
||||
if (op_qkr_store && T <= qkr_rows) {
|
||||
RAD_ISSUE_N(c, op_qkr_store, T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
rope_posmc(g, batch, T), RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
if (op_rope_q) {
|
||||
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
RAD_ISSUE(c, op_kv_store, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, layer));
|
||||
}
|
||||
if (w_sink)
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
RAD_W(w_sink), brows(w.attn.x, T));
|
||||
else
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
q_attn.step(c, T);
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (issues_ar(T)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
|
||||
#endif /* FLINT_ATTENTION_H */
|
||||
+109
-57
@@ -39,7 +39,11 @@
|
||||
*
|
||||
* Every linear of the language model and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16
|
||||
* throughout when the first joint block's projection is plain; the embedders, the timestep MLPs,
|
||||
* the modulations, the output layer and the VAE stay bf16.
|
||||
* the modulations, the output layer and the VAE stay bf16. That projection also says whether the
|
||||
* linears are rotated int8 (IQ8R): the activations they read then carry int8 codes in place of the
|
||||
* E4M3 pair, which a block's modulated norm writes in its own pass where a library serves the
|
||||
* rotating twin (rms_mod_had_quant_i8g) and the rotating quantiser behind the plain norm
|
||||
* elsewhere.
|
||||
*
|
||||
* ============================== TENSOR PARALLEL ==============================
|
||||
*
|
||||
@@ -69,18 +73,25 @@ namespace FLUX3_NS {
|
||||
using namespace rad::arch;
|
||||
|
||||
/* ================================================================== the model's constants */
|
||||
/* The largest image: 2048 x 2048 pixels, 16384 latent tokens; 1024 x 1024 is the default. */
|
||||
/* The largest image: 2048 x 2048 pixels, 16384 latent tokens; 1024 x 1024 is the default.
|
||||
* --image-gen-max-pixels lowers it (Model::max_img), and the buffers sized for it with it. */
|
||||
enum { kMaxImageTokens = 16384 };
|
||||
/* Reference pictures: ten at most, each shrunk to 1024 x 1024 pixels of area when larger. */
|
||||
/* Reference pictures: ten at most, each shrunk to 1024 x 1024 pixels of area when larger;
|
||||
* --image-gen-max-refs lowers the count (Model::max_refs). */
|
||||
enum { kMaxRefs = 10, kRefArea = 1024 * 1024 };
|
||||
/* The prompt with its padding, at most; the pipeline pads to a multiple of 80. */
|
||||
enum { kMaxText = 1040, kPadMultiple = 80 };
|
||||
/* A reference picture's latent tokens at most: its area over 16 x 16 and the slack of its sides'
|
||||
* rounding (the driver's bound). */
|
||||
static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 10 + 64; }
|
||||
/* The longest conditioning: the text and every reference picture's tokens. */
|
||||
static inline int64_t cond_rows() { return kMaxText + kMaxRefs * ref_tokens_max(); }
|
||||
/* Images in flight. Each lane keeps both branches' conditioning (cond_rows() rows apiece). */
|
||||
/* The largest image's latent tokens under --image-gen-max-pixels `px` (0: the model's own). */
|
||||
static inline int64_t image_tokens(int64_t px) {
|
||||
return px > 0 ? std::clamp<int64_t>(px / 256, 1, kMaxImageTokens) : (int64_t)kMaxImageTokens;
|
||||
}
|
||||
/* The longest conditioning with `refs` reference pictures: the text and every picture's tokens. */
|
||||
static inline int64_t cond_rows(int64_t refs) { return kMaxText + refs * ref_tokens_max(); }
|
||||
/* Images in flight, at most; --max-num-seqs lowers it (Model::lanes). Each lane keeps both
|
||||
* branches' conditioning (cond_rows() rows apiece). */
|
||||
enum { kMaxLanes = 4 };
|
||||
/* The language model's hidden states read: hidden_states[i], the output of layer i - 1. */
|
||||
static const int kTaps[] = { 4, 8, 12, 16, 20, 24, 28, 32 };
|
||||
@@ -106,6 +117,9 @@ struct Block {
|
||||
LinearFP8 qkv{}, o{}, ff_in{}, ff_out{};
|
||||
GateQuantFP8 gq{};
|
||||
QuantFP8 q_attn{};
|
||||
/* The normed rows' quantiser for a rotated int8 model whose norm is the unquantised one
|
||||
* (Model::norm_i8 false). */
|
||||
QuantFP8 q_n{};
|
||||
rad_op op_n = 0, op_qkr = 0, op_attn = 0, op_sum = 0, op_ar = 0;
|
||||
};
|
||||
|
||||
@@ -120,6 +134,10 @@ struct Model {
|
||||
Names nm{""};
|
||||
Geom gt{}, gd{};
|
||||
bool flow_map = false;
|
||||
/* The deployment's bounds (declare, from RadBuildCtx): the largest image in latent tokens, the
|
||||
* reference pictures a request and the images in flight. Every per-image, conditioning and
|
||||
* lane buffer is sized for them. */
|
||||
int64_t max_img = kMaxImageTokens, max_refs = kMaxRefs, lanes = kMaxLanes;
|
||||
std::string te_pre;
|
||||
|
||||
/* ---- the language model and context_embedder */
|
||||
@@ -161,6 +179,14 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
std::vector<Block> mode[3], single;
|
||||
LinearFP8 qkv0{};
|
||||
/* The linears of both networks are rotated int8 (IQ8R, or the 128-group int8 before it), read
|
||||
* off qkv0's probe: the activations then carry int8 code pairs with one scale per (token, `g8`
|
||||
* columns) in place of the E4M3 pair. */
|
||||
bool i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
/* A block's modulated norm writes those int8 codes in its own pass (rms_mod_had_quant_i8g),
|
||||
* where a library serves it. */
|
||||
bool norm_i8 = false;
|
||||
rad_weight w_pout = 0;
|
||||
|
||||
/* ---- per-image state and conditioning store (PERSIST) */
|
||||
@@ -173,7 +199,7 @@ struct Model {
|
||||
rad_buf b_dl = 0, b_decin = 0, b_cu4 = 0, b_img = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
std::vector<double> v;
|
||||
@@ -265,14 +291,16 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, E });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, E });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", E, T));
|
||||
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", E, T, m.i8, m.g8, "had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T));
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, E });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T));
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, T, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { T, kNTaps * E });
|
||||
m.b_tidx = decl_b(b, nm.f("te.rows"), RAD_I32, { T });
|
||||
|
||||
@@ -386,7 +414,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.b_ctx, &m.w_ctx, RAD_ACCESS_PER_REQUEST, kGrpCtx);
|
||||
m.op_store_t = rw(b, RAD_OP(b, "lane_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D),
|
||||
RAD_INT("stride", 2 * cond_rows()),
|
||||
RAD_INT("stride", 2 * cond_rows(m.max_refs)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_ctx, m.b_store }, { m.b_store });
|
||||
@@ -403,8 +431,8 @@ static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
v.scope = "venc";
|
||||
v.down = true;
|
||||
v.first_group = kGrpVaeEnc;
|
||||
v.base_px = ref_tokens_max() * 256 > (int64_t)kMaxImageTokens * 256
|
||||
? ref_tokens_max() * 256 : (int64_t)kMaxImageTokens * 256;
|
||||
v.base_px = ref_tokens_max() * 256 > m.max_img * 256
|
||||
? ref_tokens_max() * 256 : m.max_img * 256;
|
||||
/* The mid-block attends over the 8x grid: four of the pass's 16x tokens a 16x token. */
|
||||
m.b_ecu = decl_b(b, nm.f("venc.cu"), RAD_I32, { 2 });
|
||||
m.op_ecu = rw(b, RAD_OP(b, "cu_repeat", RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)),
|
||||
@@ -483,21 +511,21 @@ static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
tok, m.b_elat, m.b_eemb, &m.w_xc, RAD_ACCESS_PER_REQUEST, kGrpDit);
|
||||
m.op_store_r = rw(b, RAD_OP(b, "lane_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("n", m.gd.n_embd),
|
||||
RAD_INT("stride", 2 * cond_rows()),
|
||||
RAD_INT("stride", 2 * cond_rows(m.max_refs)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_eemb, m.b_store }, { m.b_store });
|
||||
m.op_lstore_lat = rw(b, RAD_OP(b, "lane_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, m.max_img),
|
||||
RAD_INT("n", 4 * zc),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_elat, m.b_inp }, { m.b_inp });
|
||||
m.op_lstore_mask = rw(b, RAD_OP(b, "lane_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, m.max_img),
|
||||
RAD_INT("n", 1),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_mask }, { m.b_mask });
|
||||
@@ -519,11 +547,16 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), RAD_F32,
|
||||
{ hd }, RAD_ACCESS_PER_TOKEN, grp);
|
||||
if (!B.w_qn || !B.w_kn) return RAD_E_INVAL;
|
||||
const bool q = !g.w_bf16;
|
||||
/* The norm with the quantiser in it: E4M3 for block-fp8 linears, the rotating int8 twin for
|
||||
* rotated int8 ones where a library serves it. bf16 linears read its bf16 rows, and rotated
|
||||
* int8 ones without the twin quantise those with the rotating quantiser (q_n). */
|
||||
m.norm_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "rms_mod_had_quant_i8g") != 0;
|
||||
const bool q = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
auto norm = [&](bool gt) {
|
||||
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
|
||||
rad_op op = q ? RAD_OP(b, m.norm_i8 ? "rms_mod_had_quant_i8g" : "rms_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D),
|
||||
RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_F64("eps", eps),
|
||||
RAD_INT("group", m.norm_i8 ? m.g8 : RAD_FP8_BLOCK),
|
||||
RAD_INT("gated", gt ? 1 : 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("norm", "layer")),
|
||||
RAD_NOWEIGHTS)
|
||||
@@ -535,7 +568,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
if (!op) return op;
|
||||
/* The residual, the modulation table and, gated, the branch sum. */
|
||||
rad_buf rd[4] = { m.b_xc, m.b_h, mod, m.b_sum };
|
||||
rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h };
|
||||
rad_buf wq[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h };
|
||||
rad_buf wb[2] = { m.a_hm.x, m.b_h };
|
||||
rad_op_reads(b, op, rd, gt ? 4 : 3);
|
||||
if (q) rad_op_writes(b, op, wq, 3);
|
||||
@@ -543,6 +576,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
return op;
|
||||
};
|
||||
B.op_n = norm(gated);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n.declare(b, g, m.a_hm, D));
|
||||
RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW,
|
||||
grp_layer(grp),
|
||||
{ nm.ckpt("%s.attn.to_q.weight", pre),
|
||||
@@ -585,7 +619,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
Names& nm = m.nm;
|
||||
const int64_t T = g.max_tok, S = g.max_seqs, D = g.n_embd, C = m.C;
|
||||
const int gx = kGrpDit;
|
||||
const int64_t NI = std::min<int64_t>(T, 2 * (int64_t)kMaxImageTokens);
|
||||
const int64_t NI = std::min<int64_t>(T, 2 * m.max_img);
|
||||
const int64_t te = rad_meta_geti(meta, "transformer.timestep_channels", 256);
|
||||
m.t_ch = te;
|
||||
|
||||
@@ -695,13 +729,13 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D });
|
||||
m.op_randn = rw(b, RAD_OP(b, "randn_lanes",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_state }, { m.b_state });
|
||||
m.op_lgather = rw(b, RAD_OP(b, "lane_gather",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_state }, { m.b_lat });
|
||||
@@ -717,14 +751,16 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
/* ---- the blocks' buffers */
|
||||
const int64_t qd = g.q_dim();
|
||||
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
|
||||
RAD_ARCH_TRY(m.a_hm.declare_pair(b, nm, g, "dit.hm", D, 0, m.i8, m.g8, "had_quant_act_i8g"));
|
||||
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd });
|
||||
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_pair(b, nm, g, "dit.attn", qd, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_o = decl_b(b, nm.f("dit.o"), RAD_BF16, { T, D });
|
||||
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_pair(b, nm, g, "dit.ffn", g.n_ff, 0, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_f = decl_b(b, nm.f("dit.f"), RAD_BF16, { T, D });
|
||||
m.b_sum = decl_b(b, nm.f("dit.sum"), RAD_BF16, { T, D });
|
||||
|
||||
@@ -799,7 +835,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
&m.w_pout, RAD_ACCESS_PER_TOKEN, gx);
|
||||
m.op_euler = rw(b, RAD_OP(b, "flow_euler",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_v, m.b_inp, m.b_mask, m.b_state, m.b_prev }, { m.b_state, m.b_prev });
|
||||
@@ -818,7 +854,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
v.scope = "vdec";
|
||||
v.down = false;
|
||||
v.first_group = kGrpVaeDec;
|
||||
v.base_px = (int64_t)kMaxImageTokens * 4;
|
||||
v.base_px = m.max_img * 4;
|
||||
std::vector<double> ch = meta_list(meta, "vae.decoder_block_out_channels");
|
||||
if (ch.empty()) ch = meta_list(meta, "vae.block_out_channels");
|
||||
if (ch.empty()) ch = { 128, 256, 512, 512 };
|
||||
@@ -826,7 +862,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const int64_t groups = rad_meta_geti(meta, "vae.norm_num_groups", 32);
|
||||
const int64_t zc = rad_meta_geti(meta, "vae.latent_channels", 32);
|
||||
const double eps = 1e-6;
|
||||
const int64_t NT = kMaxImageTokens;
|
||||
const int64_t NT = m.max_img;
|
||||
m.b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, 4 * zc });
|
||||
m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zc });
|
||||
m.b_cu4 = decl_b(b, nm.f("vdec.cu"), RAD_I32, { 2 });
|
||||
@@ -872,7 +908,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "vae.decoder.conv_out");
|
||||
if (!m.dec_out.buf) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(v.attn_reads(m.b_cu4));
|
||||
const int64_t px = (int64_t)kMaxImageTokens * 256;
|
||||
const int64_t px = m.max_img * 256;
|
||||
m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST);
|
||||
m.op_rgb = rw(b, RAD_OP(b, "to_rgba8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3),
|
||||
@@ -884,8 +920,9 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -894,6 +931,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.te_pre = std::strstr(rad_meta_gets(meta, "architectures", ""), "ForConditionalGeneration")
|
||||
? "model.language_model" : "language_model";
|
||||
m.flow_map = rad_meta_geti(meta, "transformer.flow_map", 0) != 0;
|
||||
/* The deployment's bounds: --image-gen-max-pixels in latent tokens of 16 x 16 pixels,
|
||||
* --image-gen-max-refs, and --max-num-seqs's images in flight (0: the model's own). */
|
||||
m.max_img = image_tokens(ctx->gen_max_pixels);
|
||||
if (ctx->gen_max_refs > 0) m.max_refs = std::min<int64_t>(ctx->gen_max_refs, kMaxRefs);
|
||||
if (ctx->max_seqs > 0) m.lanes = std::min<int64_t>(ctx->max_seqs, kMaxLanes);
|
||||
|
||||
Geom& gd = m.gd;
|
||||
gd = m.gt;
|
||||
@@ -925,18 +967,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.single_transformer_blocks.0.attn.to_k.weight",
|
||||
"transformer.single_transformer_blocks.0.attn.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
const bool known = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e);
|
||||
const bool plain = known && rad_enc_is(&e, "plain");
|
||||
gd.w_bf16 = m.gt.w_bf16 = plain;
|
||||
/* Or rotated int8 (IQ8R): the activations then carry int8 codes at the weights' scale
|
||||
* group in place of the E4M3 pair (ActFP8::declare_pair). */
|
||||
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
|
||||
if (m.i8) m.g8 = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens;
|
||||
const int64_t lane_rows = m.lanes * m.max_img;
|
||||
m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST);
|
||||
m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST);
|
||||
m.b_inp = decl_b(b, nm.f("lat_repaint"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST);
|
||||
m.b_mask = decl_b(b, nm.f("lat_mask"), RAD_F32, { lane_rows, 1 }, RAD_BUF_PERSIST);
|
||||
m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16,
|
||||
{ 2 * (int64_t)kMaxLanes * cond_rows(), gd.n_embd }, RAD_BUF_PERSIST);
|
||||
{ 2 * m.lanes * cond_rows(m.max_refs), gd.n_embd }, RAD_BUF_PERSIST);
|
||||
/* ---- adapter key names. LoRA files name the blocks by Black Forest Labs' modules, as
|
||||
* ComfyUI loads them (comfy/ldm/flux3): `single_blocks.N.q_proj` or a fused `qkv`,
|
||||
* `attn_out`, `mlp_in`, `mlp_out`, and the mode blocks under `content_mode_blocks`. */
|
||||
@@ -980,12 +1026,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.size_multiple = 16;
|
||||
d.pixel_channels = 3;
|
||||
d.slot_rows = 1;
|
||||
d.max_tokens = kMaxImageTokens;
|
||||
d.max_refs = kMaxRefs;
|
||||
d.max_tokens = m.max_img;
|
||||
d.max_refs = m.max_refs;
|
||||
d.ref_area = kRefArea;
|
||||
d.ref_shrink_only = 1;
|
||||
d.default_width = 1024;
|
||||
d.default_height = 1024;
|
||||
/* 1024 x 1024, or the largest square under --image-gen-max-pixels. */
|
||||
const int64_t side = std::min<int64_t>(64, (int64_t)std::sqrt((double)m.max_img));
|
||||
d.default_width = side * 16;
|
||||
d.default_height = side * 16;
|
||||
d.default_steps = m.flow_map ? 16 : 50;
|
||||
d.shift = rad_meta_getf(meta, "scheduler.shift", 6.93);
|
||||
d.dyn_shift = (int32_t)rad_meta_geti(meta, "scheduler.use_dynamic_shifting", 0);
|
||||
@@ -998,9 +1046,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.shift_terminal = rad_meta_getf(meta, "scheduler.shift_terminal", 0.0);
|
||||
d.default_cfg = m.flow_map ? 1.0 : 3.5;
|
||||
d.default_negative = "";
|
||||
d.max_lanes = kMaxLanes;
|
||||
d.max_lanes = m.lanes;
|
||||
d.image_out = m.b_img;
|
||||
d.cond_rows = cond_rows();
|
||||
d.cond_rows = cond_rows(m.max_refs);
|
||||
d.rope_hw_scale = 0.5;
|
||||
d.rope_text_l = 1;
|
||||
d.pad_multiple = kPadMultiple;
|
||||
@@ -1012,7 +1060,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"+ %zu joint blocks (%lld heads a rank, ff %lld), %s linears",
|
||||
m.gt.rank, m.gt.world, m.flow_map ? " (flow map)" : " base", kTaps[kNTaps - 1],
|
||||
(long long)m.gt.n_layer, m.mode[0].size(), m.single.size(), (long long)gd.n_head,
|
||||
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : "block-fp8");
|
||||
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1073,8 +1121,8 @@ static int64_t step_encode(RadCtx* c, const Model& m, const uint16_t* px, int64_
|
||||
static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadGenBatch* G = batch->gen_b;
|
||||
const int64_t T = batch->n_tok, D = m.gd.n_embd;
|
||||
const int64_t base = (int64_t)G->branch * cond_rows();
|
||||
const int64_t store_rows = 2 * (int64_t)kMaxLanes * cond_rows();
|
||||
const int64_t base = (int64_t)G->branch * cond_rows(m.max_refs);
|
||||
const int64_t store_rows = 2 * m.lanes * cond_rows(m.max_refs);
|
||||
const RadOperand lanes = praw(G->lane, RAD_I32, G->n_lane);
|
||||
step_te(c, batch, m);
|
||||
RAD_ISSUE_N(c, m.op_ctx, T, brows(m.b_taps, T), RAD_W(m.w_ctx), brows(m.b_ctx, T));
|
||||
@@ -1092,7 +1140,7 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
brow_slice(m.b_store, base + row, store_rows - base - row, D));
|
||||
row += n;
|
||||
} else {
|
||||
const int64_t L = (int64_t)kMaxLanes * kMaxImageTokens;
|
||||
const int64_t L = m.lanes * m.max_img;
|
||||
RAD_ISSUE_N(c, m.op_lstore_lat, n, brows(m.b_elat, n), lanes, brows(m.b_inp, L));
|
||||
RAD_ISSUE_N(c, m.op_lstore_mask, n, praw2(G->inp_mask, RAD_F32, n, 1), lanes,
|
||||
brows(m.b_mask, L));
|
||||
@@ -1107,17 +1155,19 @@ static void step_blocks(RadCtx* c, const Model& m, const std::vector<Block>& sta
|
||||
const RadOperand& s, const RadOperand& gt, const RadOperand& pos) {
|
||||
const Geom& g = m.gd;
|
||||
const int64_t D = g.n_embd, qd = g.q_dim(), nD = D / RAD_FP8_BLOCK;
|
||||
const bool q8 = !g.w_bf16;
|
||||
const bool q8 = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
const RadOperand xv = brow_slice(x, r0, R, D);
|
||||
for (size_t i = 0; i < stack.size(); ++i) {
|
||||
const Block& B = stack[i];
|
||||
const bool gated = i > 0;
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.q, R), brows(m.a_hm.s, R), RAD_NONE);
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.cq(), R), brows(m.a_hm.cs(), R),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.x, R));
|
||||
B.q_n.step(c, R);
|
||||
B.qkv.step(c, m.a_hm, m.b_qkv, R);
|
||||
RAD_ISSUE_N(c, B.op_qkr, R, brows(m.b_qkv, R), pos, RAD_W(B.w_qn), RAD_W(B.w_kn));
|
||||
RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R),
|
||||
@@ -1141,7 +1191,7 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1);
|
||||
const RadOperand lanes = praw(G->lane, RAD_I32, S);
|
||||
const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens;
|
||||
const int64_t LR = m.lanes * m.max_img;
|
||||
|
||||
/* ---- the timestep embeddings and every modulation */
|
||||
RAD_ISSUE_N(c, m.op_tp, S, praw(G->sigma, RAD_F32, S), brows(m.b_tp, S));
|
||||
@@ -1180,7 +1230,7 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
RAD_ISSUE_N(c, m.op_xi, NI, brows(m.b_lat, NI), RAD_W(m.w_xi),
|
||||
brow_slice(m.b_xc, nt + nr, NI, D));
|
||||
if (nt + nr > 0)
|
||||
RAD_ISSUE_N(c, m.op_gtxt, nt + nr, brows(m.b_store, 2 * (int64_t)kMaxLanes * cond_rows()),
|
||||
RAD_ISSUE_N(c, m.op_gtxt, nt + nr, brows(m.b_store, 2 * m.lanes * cond_rows(m.max_refs)),
|
||||
praw(G->mode_src, RAD_I32, nt + nr), brows(m.b_xc, nt + nr));
|
||||
|
||||
/* ---- each mode's early blocks over its own rows, the last sum gated in */
|
||||
@@ -1222,7 +1272,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadGenBatch* G = batch->gen_b;
|
||||
const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W, C = m.C;
|
||||
const rad_buf src = G->dec_preview ? m.b_prev : m.b_state;
|
||||
RAD_ISSUE_N(c, m.op_dbn, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C),
|
||||
RAD_ISSUE_N(c, m.op_dbn, n, brow_slice(src, (int64_t)G->dec_lane * m.max_img, n, C),
|
||||
RAD_W(m.w_bnm), RAD_W(m.w_bnv), brows(m.b_dl, n));
|
||||
const int64_t zc = C / 4, H0 = 2 * H, W0 = 2 * W;
|
||||
RAD_ISSUE_N(c, m.op_dzero, H0 * W0, brows(m.b_decin, H0 * W0));
|
||||
@@ -1236,7 +1286,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "flux3 is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1250,11 +1300,11 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
|
||||
/* ================================================================== the probe */
|
||||
/* The rows a pass carries: an image at the largest size with one reference picture and its
|
||||
* longest text, both branches of guidance. */
|
||||
/* The rows a pass carries: an image at the largest size (under --image-gen-max-pixels) with one
|
||||
* reference picture and its longest text, both branches of guidance. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kMaxText + ref_tokens_max());
|
||||
out->gen_rows = 2 * (image_tokens(out->gen_max_pixels) + kMaxText + ref_tokens_max());
|
||||
out->gen_patches = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1265,6 +1315,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
/* One more level of expansion so `#NS` sees the expanded namespace. */
|
||||
#define FLUX3_PROBE_X(NS) RAD_ARCH_PROBE(NS)
|
||||
#define FLUX3_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
FLUX3_PROBE_X(FLUX3_NS)
|
||||
FLUX3_PLUGIN_X(FLUX3_NS, FLUX3_ID, "", "0.1.0",
|
||||
"FLUX.3 [klein] and its base: Qwen3-VL-4B's stacked layers, a 5.6B three-mode "
|
||||
|
||||
+600
-82
File diff suppressed because it is too large.
Load diff
+240
-90
@@ -1,6 +1,6 @@
|
||||
/* gemma4 -- Gemma 4 text decoders (26B-A4B MoE, and the dense members of the family): a bf16
|
||||
* trunk, routed experts bf16 or block fp8 (see FP8 EXPERTS), and the DFlash block-diffusion
|
||||
* drafter.
|
||||
* trunk, routed experts bf16, block fp8 or rotated int8 (see FP8 EXPERTS), and the DFlash
|
||||
* block-diffusion drafter.
|
||||
*
|
||||
* ============================== THE SHAPE (gemma-4-26B-A4B-it) ==============================
|
||||
*
|
||||
@@ -77,7 +77,17 @@
|
||||
* blocks, which 704 is not. It stays bf16 -- unless the checkpoint is padded to 768
|
||||
* first, outside the engine: zero rows of gate and up give gelu(0) * 0 = 0 in the
|
||||
* padded columns, which meet zero columns of down, so the function is unchanged, and
|
||||
* then both projections are fp8 (data/recipes/gemma4-26b-a4b-df-pad768.recipe).
|
||||
* then both projections are fp8.
|
||||
*
|
||||
* Rotated int8 experts (`rtn codes=i8 group=128 scale=bf16 transform=fwht128`) take the same
|
||||
* tables and the same widths through `moe_gemm_q` at i8a8h, over int8 codes of the experts' input
|
||||
* that the attention join's fused route writes (`norm_add_norm_route_i8g`), or the rotating norm
|
||||
* (`rmsnorm_had_quant_i8g`) where that is not served. A model's quantised experts are all one or
|
||||
* all the other.
|
||||
*
|
||||
* The cache is bf16 or int8 with an f16 scale of K and of V per token and head
|
||||
* (--kv-cache-dtype i8, libr4d's windowed kernels' int8 rows and kv_store_i8), the drafter's
|
||||
* with it.
|
||||
*
|
||||
* ============================== NOT DECLARED ==============================
|
||||
*
|
||||
@@ -157,7 +167,9 @@ struct Layer {
|
||||
* w_egus/w_edns, so each parity is one run (see declare). */
|
||||
rad_weight w_rscale = 0, w_router = 0, w_escale = 0, w_enorm = 0, w_fpost2 = 0;
|
||||
std::vector<rad_weight> w_egu, w_edn, w_egus, w_edns;
|
||||
bool gu_fp8 = false, dn_fp8 = false;
|
||||
/* A projection's experts are quantised (block fp8 or rotated int8: the table GEMM over a code
|
||||
* pair), else plain bf16. */
|
||||
bool gu_q = false, dn_q = false;
|
||||
rad_op op_rnorm = 0, op_router = 0, op_topk = 0, op_escale = 0, op_emul = 0, op_enorm = 0;
|
||||
rad_op op_scatter = 0, op_egu = 0, op_eact = 0, op_eq = 0, op_edn = 0, op_gather = 0;
|
||||
/* libr4d's fused forms of the router, its top-k and the sort, where they resolve: the pair
|
||||
@@ -177,8 +189,9 @@ struct Layer {
|
||||
* then declared and issued instead. */
|
||||
rad_op op_join_a = 0, op_join_f = 0;
|
||||
/* op_join_r: op_join_a writing the routed arm's two inputs as well -- the router's norm into
|
||||
* b_rn and the experts' fp8 codes into b_hq / b_hqs (norm_add_norm_route) -- where the
|
||||
* layer's gate_up is block fp8. op_rnorm and op_enorm are then declared and not issued. */
|
||||
* b_rn and the experts' codes into b_hq / b_hqs (norm_add_norm_route's E4M3, or
|
||||
* norm_add_norm_route_i8g's rotated int8) -- where the layer's gate_up is quantised. op_rnorm
|
||||
* and op_enorm are then declared and not issued. */
|
||||
rad_op op_join_r = 0;
|
||||
/* op_join_f also writes the next norm (the following layer's input norm, or the final norm
|
||||
* after the last layer) into `h`, with that norm's gain `w_next`; the replaced norm is then
|
||||
@@ -187,6 +200,10 @@ struct Layer {
|
||||
rad_weight w_next = 0;
|
||||
/* the drafter's tap, on a layer the drafter reads (see declare) */
|
||||
rad_op op_tap = 0;
|
||||
/* Calibration: the attention's input (q, k and v share it), its output (this rank's columns,
|
||||
* o_proj's input), the dense arm's input and its gated product (this rank's columns, down's
|
||||
* input). */
|
||||
CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_dn{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -216,7 +233,10 @@ struct Model {
|
||||
/* the experts' E4M3 inputs, declared only where some layer's projection is fp8: gate_up's
|
||||
* (the normed block input, a row a token) and down's (the gated product, a row a slot) */
|
||||
rad_buf b_hq = 0, b_hqs = 0, b_eq = 0, b_eqs = 0;
|
||||
int n_gu_fp8 = 0, n_dn_fp8 = 0; /* layers whose projection is fp8 */
|
||||
int n_gu_q = 0, n_dn_q = 0; /* layers whose projection is quantised */
|
||||
/* The quantised experts are rotated int8 against int8 activations (EXP_I8), every layer's:
|
||||
* the code pairs are one buffer each for the whole model. */
|
||||
bool exp_i8 = false, exp_seen = false;
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_onorm = 0;
|
||||
@@ -227,6 +247,12 @@ struct Model {
|
||||
int tap_layer[MAX_TAPS] = {};
|
||||
rad_buf b_dfsrc = 0;
|
||||
|
||||
/* The calibration tap: on while `tap_live`, over layers [calib_lo, calib_hi). Written by step,
|
||||
* which owns the corpus count. */
|
||||
bool calib = false, tap_live = false;
|
||||
int64_t calib_lo = 0, calib_hi = 0;
|
||||
long long calib_rows = 0;
|
||||
|
||||
Dflash1 df{};
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_df = false;
|
||||
@@ -235,7 +261,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ============================================================== geometry */
|
||||
|
||||
@@ -321,7 +347,7 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
* plan, rad_weight_encoding), which picks the GEMM: plain bf16 is `moe_gemm`, block fp8 (fp8_e4m3
|
||||
* codes, a bf16 scale per 128x128 block) is `moe_gemm_q` at fp8a8. Anything else is refused by
|
||||
* name. A builder with no model behind it answers nothing, and the declared dtype bf16 is read. */
|
||||
enum { EXP_BF16 = 0, EXP_FP8 = 1 };
|
||||
enum { EXP_BF16 = 0, EXP_FP8 = 1, EXP_I8 = 2 };
|
||||
static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
|
||||
RadEncoding e{};
|
||||
*fmt = EXP_BF16;
|
||||
@@ -331,11 +357,22 @@ static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
|
||||
*fmt = EXP_FP8;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Rotated int8: codes with a bf16 scale per (row, 128 of K), each 128 of K rotated by the
|
||||
* Hadamard (libquant's `codes=i8 group=128 scale=bf16 transform=fwht128`). */
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
if (rad_enc_is(&e, "affine") && e.n_planes == 2 && e.plane[0].dtype == RAD_I8 && sc &&
|
||||
sc->dtype == RAD_BF16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
|
||||
std::strcmp(e.transform, "fwht128") == 0) {
|
||||
*fmt = EXP_I8;
|
||||
return RAD_OK;
|
||||
}
|
||||
char en[256];
|
||||
rad_enc_format(&e, en, sizeof en);
|
||||
fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16 or "
|
||||
"block fp8 (fp8_e4m3*bf16[128x128]). Convert with no rule for them, or with "
|
||||
"`rtn codes=fp8_e4m3 block=128x128 scale=bf16`.\n", wn, en);
|
||||
fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16, "
|
||||
"block fp8 (fp8_e4m3*bf16[128x128]) or rotated int8 "
|
||||
"(i8*bf16[1x128]/fwht128). Convert with no rule for them, or with `rtn "
|
||||
"codes=fp8_e4m3 block=128x128 scale=bf16` or `rtn codes=i8 group=128 "
|
||||
"scale=bf16 transform=fwht128 clamp=sym rule=search`.\n", wn, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
@@ -350,11 +387,11 @@ static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base
|
||||
RAD_ARCH_TRY(expert_format(b, wn, &f));
|
||||
if (e == 0) { *fmt = f; continue; }
|
||||
if (f != *fmt) {
|
||||
static const char* const kName[3] = { "bf16", "block fp8", "rotated int8" };
|
||||
fprintf(stderr, "radiance: gemma4: '%s' is %s and expert %lld of the same layer is %s; "
|
||||
"one layer's %s experts take one encoding (a recipe rule for them "
|
||||
"matches all of a layer's or none)\n", wn,
|
||||
f == EXP_FP8 ? "block fp8" : "bf16", (long long)base,
|
||||
*fmt == EXP_FP8 ? "block fp8" : "bf16", what);
|
||||
"matches all of a layer's or none)\n", wn, kName[f], (long long)base,
|
||||
kName[*fmt], what);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
@@ -365,7 +402,8 @@ static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->is_draft) {
|
||||
fprintf(stderr, "radiance: gemma4: this plugin has no draft scope\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -378,7 +416,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -531,24 +569,45 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* ---- the KV groups, one per geometry: the sliding layers' (256-wide heads) and the full
|
||||
* layers' (512).
|
||||
*
|
||||
* The sliding layers' group is RAD_KV_FULL, not RAD_KV_WINDOW; the window lives on the
|
||||
* attention op (`window` 1024), which reads only keys inside it. A window group is not
|
||||
* prefix-cached (core/mem/prefix.cpp), so a prefix hit on a model with one reuses nothing and
|
||||
* re-prefills (core/sched). As FULL the group is cached with the others and the drafter's KV
|
||||
* has no hole. The only loss is recycling below the window, which gains nothing here: the
|
||||
* planner gives every paged group the same block count, so the full group bounds the tokens a
|
||||
* card holds anyway. */
|
||||
* The sliding layers' group is RAD_KV_WINDOW, sized to the attention window, which is what
|
||||
* the kernel reads anyway: attn_paged takes `window` 1024 on those layers and never looks at
|
||||
* a key older than it. As a window group the pool is capped at the window plus one block per
|
||||
* sequence (core/mem/kv.cpp), so 25 sliding layers cost ~1k tokens of cache each instead of
|
||||
* the whole context -- at 32k and fp8 KV, 0.4 GiB a sequence where FULL costs 3.5. The full
|
||||
* layers' group stays RAD_KV_FULL: it is the only one whose keys outlive a window.
|
||||
*
|
||||
|
||||
* A windowed group is not prefix-cached (core/mem/prefix.cpp): its rows below the window are
|
||||
* recycled, and adopt() would overfill a table capped at window_blocks. What that costs on
|
||||
* a prefix hit is only the windowed rows; the full layers' rows still come back from the
|
||||
* store. The window itself resumes from the deepest retained checkpoint at or below the
|
||||
* matched end — that checkpoint's slot carries the window behind it — and only the gap between
|
||||
* that checkpoint and the match end is recomputed. Only where no retained checkpoint sits at
|
||||
* or below the match do the windowed layers start their cache where the hit ended
|
||||
* (the re-prefill case); that is the regime gemma3 runs with a DFlash drafter on the
|
||||
* same core, and it declares its sliding group exactly this way.
|
||||
*
|
||||
|
||||
* The drafter does not read the trunk's cache. DFlash keeps its own windowed draft KV (2048),
|
||||
* rebuilt each context pass from the trunk's residual taps; its rows live inside that window
|
||||
* like every other draft query's, and it has no stake in the trunk's windowed rows outliving
|
||||
* the window. A windowed trunk group therefore costs the drafter nothing. */
|
||||
|
||||
{
|
||||
const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
d.kind = RAD_KV_WINDOW;
|
||||
d.window = m.ks.window; /* the same 1024 the attention op reads */
|
||||
d.dtype = kvdt;
|
||||
d.n_head_kv = m.ks.nkv;
|
||||
d.head_dim = m.ks.hd;
|
||||
m.ks.kv = rad_decl_kv_group(b, nm.f("kv_swa"), &d);
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.window = 0;
|
||||
d.n_head_kv = m.kf.nkv;
|
||||
d.head_dim = m.kf.hd;
|
||||
m.kf.kv = rad_decl_kv_group(b, nm.f("kv_full"), &d);
|
||||
g.kv_dtype = rad_dtype_name(d.dtype);
|
||||
g.kv_dtype = rad_dtype_name(kvdt);
|
||||
}
|
||||
|
||||
/* Gemma4ForConditionalGeneration keeps the text model under model.language_model;
|
||||
@@ -577,26 +636,40 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
int fgu = EXP_BF16, fdn = EXP_BF16;
|
||||
RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "gate_up", &fgu));
|
||||
RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "down", &fdn));
|
||||
y.gu_fp8 = fgu == EXP_FP8;
|
||||
y.dn_fp8 = fdn == EXP_FP8;
|
||||
y.gu_q = fgu != EXP_BF16;
|
||||
y.dn_q = fdn != EXP_BF16;
|
||||
/* One quantised format for the model: the experts' code pairs are shared buffers. */
|
||||
for (const int f : { fgu, fdn }) {
|
||||
if (f == EXP_BF16) continue;
|
||||
const bool i8 = f == EXP_I8;
|
||||
if (m.exp_seen && i8 != m.exp_i8) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's experts are %s and an earlier "
|
||||
"projection's %s; a model's quantised experts are all block "
|
||||
"fp8 or all rotated int8\n", ll,
|
||||
i8 ? "rotated int8" : "block fp8", i8 ? "block fp8" : "rotated int8");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
m.exp_seen = true;
|
||||
m.exp_i8 = i8;
|
||||
}
|
||||
/* moe_gemm_q's geometry, refused here by name rather than as a kernel miss. It takes
|
||||
* experts as two tables by parity, so a rank must hold an even count. */
|
||||
if ((y.gu_fp8 || y.dn_fp8) && NL % 2) {
|
||||
fprintf(stderr, "radiance: gemma4: block fp8 experts come in pairs on a rank (the "
|
||||
"fp8 grouped GEMM takes them as two tables by parity); this rank "
|
||||
if ((y.gu_q || y.dn_q) && NL % 2) {
|
||||
fprintf(stderr, "radiance: gemma4: quantised experts come in pairs on a rank (the "
|
||||
"grouped GEMM takes them as two tables by parity); this rank "
|
||||
"holds %lld\n", (long long)NL);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (y.gu_fp8 && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are block fp8 at "
|
||||
"%lld x %lld; the fp8 grouped GEMM takes N in 64s and K in whole "
|
||||
if (y.gu_q && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are quantised at "
|
||||
"%lld x %lld; the grouped GEMM takes N in 64s and K in whole "
|
||||
"%d-column blocks\n", ll, (long long)(2 * m.n_ffe), (long long)E,
|
||||
RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (y.dn_fp8 && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's down experts are block fp8, and "
|
||||
"the experts are %lld wide: the fp8 grouped GEMM reads K in whole "
|
||||
if (y.dn_q && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's down experts are quantised, and "
|
||||
"the experts are %lld wide: the grouped GEMM reads K in whole "
|
||||
"%d-column scale blocks. Keep `ffn_down_exps` bf16 (no recipe "
|
||||
"rule for it), or pad the experts to a multiple of %d (zero rows "
|
||||
"of gate and up, zero columns of down) and convert the padded "
|
||||
@@ -604,8 +677,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
(long long)m.n_ffe, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
m.n_gu_fp8 += y.gu_fp8;
|
||||
m.n_dn_fp8 += y.dn_fp8;
|
||||
m.n_gu_q += y.gu_q;
|
||||
m.n_dn_q += y.dn_q;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -630,10 +703,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {T, K});
|
||||
m.b_ew = decl_b(b, nm.f("moe_w"), RAD_BF16, {T, K});
|
||||
m.b_es = decl_b(b, nm.f("moe_es"), RAD_BF16, {T, K});
|
||||
if (m.n_gu_fp8 < m.n_layer)
|
||||
if (m.n_gu_q < m.n_layer)
|
||||
m.b_hx = decl_b(b, nm.f("moe_h"), RAD_BF16, {T, E});
|
||||
if (m.n_gu_fp8 > 0) {
|
||||
m.b_hq = decl_b(b, nm.f("moe_hq"), RAD_F8E4M3, {T, E});
|
||||
if (m.n_gu_q > 0) {
|
||||
m.b_hq = decl_b(b, nm.f("moe_hq"), m.exp_i8 ? RAD_I8 : RAD_F8E4M3, {T, E});
|
||||
m.b_hqs = decl_b(b, nm.f("moe_hqs"), RAD_F32, {T, fp8_blocks(E)});
|
||||
}
|
||||
m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {P * K});
|
||||
@@ -641,8 +714,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.n_local});
|
||||
m.b_egu = decl_b(b, nm.f("moe_egu"), RAD_BF16, {P * K, 2 * m.n_ffe});
|
||||
m.b_eact = decl_b(b, nm.f("moe_eact"), RAD_BF16, {P * K, m.n_ffe});
|
||||
if (m.n_dn_fp8 > 0) {
|
||||
m.b_eq = decl_b(b, nm.f("moe_eq"), RAD_F8E4M3, {P * K, m.n_ffe});
|
||||
if (m.n_dn_q > 0) {
|
||||
m.b_eq = decl_b(b, nm.f("moe_eq"), m.exp_i8 ? RAD_I8 : RAD_F8E4M3, {P * K, m.n_ffe});
|
||||
m.b_eqs = decl_b(b, nm.f("moe_eqs"), RAD_F32, {P * K, fp8_blocks(m.n_ffe)});
|
||||
}
|
||||
m.b_edn = decl_b(b, nm.f("moe_edn"), RAD_BF16, {P * K, E});
|
||||
@@ -759,7 +832,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* (libr4d/r4d_norm_join_bf16.hip); on a card they differ from libr4d's chain only in reduction
|
||||
* order. libref deliberately has no row for them, so the chain path stays tested. */
|
||||
const bool has_join_a = rad_op_declared(b, "norm_add_norm") != 0;
|
||||
const bool has_join_r = rad_op_declared(b, "norm_add_norm_route") != 0;
|
||||
const char* const join_r = m.exp_i8 ? "norm_add_norm_route_i8g" : "norm_add_norm_route";
|
||||
const bool has_join_r = rad_op_declared(b, join_r) != 0;
|
||||
const bool has_join_f = rad_op_declared(b, "join_add_scale") != 0;
|
||||
const bool has_escale = rad_op_declared(b, "expert_scale") != 0;
|
||||
const bool has_qrow = rad_op_declared(b, "attn_paged_qrow") != 0;
|
||||
@@ -914,12 +988,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl);
|
||||
}
|
||||
|
||||
/* The attention join. On a layer whose gate_up is block fp8 it also writes the routed
|
||||
/* The attention join. On a layer whose gate_up is quantised it also writes the routed
|
||||
* arm's two inputs: the router's norm (rmsnorm with mult hidden^-0.5) and the experts'
|
||||
* E4M3 codes (as rmsnorm_quant_fp8), saving two launches and two reads of x per layer.
|
||||
* Otherwise norm_add_norm, else the chain. */
|
||||
if (has_join_r && m.moe && y.gu_fp8)
|
||||
y.op_join_r = rw(b, RAD_OP(b, "norm_add_norm_route",
|
||||
* codes (as rmsnorm_quant_fp8, or for rotated int8 experts rmsnorm_had_quant_i8g),
|
||||
* saving two launches and two reads of x per layer. Otherwise norm_add_norm, else the
|
||||
* chain. */
|
||||
if (has_join_r && m.moe && y.gu_q)
|
||||
y.op_join_r = rw(b, RAD_OP(b, join_r,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("mult", 1.0 / std::sqrt((double)E)),
|
||||
@@ -962,10 +1037,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The experts: this rank's run of whole experts (name maps and encodings were settled
|
||||
* before the buffers). Each projection's handles are declared in its GEMM's table
|
||||
* order, since a table is a run of consecutively declared handles: bf16 is one run in
|
||||
* expert order; block fp8 is the even local experts' codes, then the odd ones', then
|
||||
* the scale views in the same two runs (`moe_gemm_q` takes two tables by parity). Codes
|
||||
* expert order; block fp8 or int8 is the even local experts' codes, then the odd ones',
|
||||
* then the scale views in the same two runs (`moe_gemm_q` takes two tables by parity;
|
||||
* an int8 expert's scale is per row, block fp8's per 128 rows). Codes
|
||||
* and scale plane are two views of one stored weight and one movement unit (slot 0
|
||||
* gate_up, 1 down). */
|
||||
const uint32_t cdt = m.exp_i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
|
||||
auto experts = [&](bool fp8, const char* what, int slot, int64_t rows, int64_t cols,
|
||||
std::vector<rad_weight>& wc, std::vector<rad_weight>& ws) {
|
||||
wc.assign((size_t)NL, 0);
|
||||
@@ -991,18 +1068,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_weight& h = (pass ? ws : wc)[(size_t)(par * half + i)];
|
||||
h = pass ? decl_view(b, nm.f("blk.%lld.ffn_%s_exps.%lld.scale", ll, what, ge),
|
||||
wn, "scale", RAD_BF16,
|
||||
{fp8_blocks(rows), fp8_blocks(cols)},
|
||||
{m.exp_i8 ? rows : fp8_blocks(rows),
|
||||
fp8_blocks(cols)},
|
||||
RAD_ACCESS_CONDITIONAL, N,
|
||||
grp_expert_slot(li, (int)e, slot))
|
||||
: decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, {rows, cols},
|
||||
: decl_view(b, wn, nullptr, "codes", cdt, {rows, cols},
|
||||
RAD_ACCESS_CONDITIONAL, N,
|
||||
grp_expert_slot(li, (int)e, slot));
|
||||
if (!h) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
RAD_ARCH_TRY(experts(y.gu_fp8, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus));
|
||||
RAD_ARCH_TRY(experts(y.dn_fp8, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns));
|
||||
RAD_ARCH_TRY(experts(y.gu_q, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus));
|
||||
RAD_ARCH_TRY(experts(y.dn_q, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns));
|
||||
/* An fp8 projection's op takes its weights in its table operands' order: even codes,
|
||||
* even scales, odd codes, odd scales. */
|
||||
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
|
||||
@@ -1041,11 +1119,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{m.b_ids}, {m.b_es});
|
||||
y.op_emul = binop("mul", P, K, m.b_ew, m.b_es, m.b_ew);
|
||||
}
|
||||
/* The experts' input, pre_feedforward_layernorm_2 of the stream. For an fp8 gate_up it
|
||||
* is normed and quantised in one pass (`rmsnorm_quant_fp8`) with no bf16 copy, since
|
||||
* the fp8 GEMM reads only codes and scales. */
|
||||
if (y.gu_fp8) {
|
||||
y.op_enorm = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
/* The experts' input, pre_feedforward_layernorm_2 of the stream. For a quantised
|
||||
* gate_up it is normed and quantised in one pass (`rmsnorm_quant_fp8`, or for int8
|
||||
* experts the rotating `rmsnorm_had_quant_i8g`) with no bf16 copy, since the table
|
||||
* GEMM reads only codes and scales. */
|
||||
if (y.gu_q) {
|
||||
y.op_enorm = RAD_OP(b, m.exp_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", E),
|
||||
RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("wadd", 0.0)),
|
||||
@@ -1098,13 +1177,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The two grouped GEMMs use different a_order: gate_up reads the block input, one row
|
||||
* per token, gathered through sorted_tok; down reads gate_up's product, already one row
|
||||
* per (token, slot) in scatter order (rad_block_moe_fp8.h). */
|
||||
if (y.gu_fp8) {
|
||||
if (y.gu_q) {
|
||||
const std::vector<rad_weight> tab = tables(y.w_egu, y.w_egus);
|
||||
y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe),
|
||||
RAD_INT("K", E), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", "fp8a8")),
|
||||
/* `a_group` is stated to the int8 rows alone, last and cut off otherwise. */
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe),
|
||||
RAD_INT("K", E), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"),
|
||||
RAD_STR("dtype", m.exp_i8 ? "i8a8h" : "fp8a8"),
|
||||
RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q", ps,
|
||||
(int)(sizeof ps / sizeof *ps) - (m.exp_i8 ? 0 : 1),
|
||||
tab.data(), (int)tab.size()),
|
||||
{m.b_hq, m.b_hqs, m.b_sorted, m.b_eoff}, {m.b_egu});
|
||||
} else {
|
||||
@@ -1119,19 +1202,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* gelu_tanh(gate) * up over the two column halves. An fp8 down then quantises the
|
||||
* product on its own launch: libr4d's fused gated quantiser is compiled for silu. */
|
||||
y.op_eact = act_mul(P * K, m.n_ffe, m.b_egu, m.b_eact);
|
||||
if (y.dn_fp8) {
|
||||
y.op_eq = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
if (y.dn_q) {
|
||||
y.op_eq = rw(b, RAD_OP(b, m.exp_i8 ? "had_quant_act_i8g" : "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n", m.n_ffe),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_eact}, {m.b_eq, m.b_eqs});
|
||||
const std::vector<rad_weight> tab = tables(y.w_edn, y.w_edns);
|
||||
y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", E),
|
||||
RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", "fp8a8")),
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, P), RAD_INT("N", E),
|
||||
RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"),
|
||||
RAD_STR("dtype", m.exp_i8 ? "i8a8h" : "fp8a8"),
|
||||
RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q", ps,
|
||||
(int)(sizeof ps / sizeof *ps) - (m.exp_i8 ? 0 : 1),
|
||||
tab.data(), (int)tab.size()),
|
||||
{m.b_eq, m.b_eqs, m.b_sorted, m.b_eoff}, {m.b_edn});
|
||||
} else {
|
||||
@@ -1155,7 +1241,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_op_reads(b, y.op_gather, rd, 3);
|
||||
rad_op_writes(b, y.op_gather, wr, 1);
|
||||
}
|
||||
if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_fp8 && !y.op_eq)) return RAD_E_INVAL;
|
||||
if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_q && !y.op_eq)) return RAD_E_INVAL;
|
||||
if (W > 1) y.op_ar_f = allreduce(2 * T * E, m.b_ff2);
|
||||
if (has_join_f)
|
||||
{
|
||||
@@ -1223,6 +1309,30 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* ~120 us per layer on 4x R9700), so it hides behind the experts' bandwidth. No collective
|
||||
* rides it, so the reductions stay on lane 0. Its buffers leave the arena's sharing. */
|
||||
m.arms = m.moe;
|
||||
/* ---- the calibration tap. It reads each dense linear's bf16 input where trunk issues the
|
||||
* linear, so a calibration runs every step whole and on one lane. The files are named after
|
||||
* the weights the 31B's w4a8 container quantises (gemma4_bf16: blk.N.attn_qkv, attn_o,
|
||||
* ffn_gate_up, ffn_down), which a GPTQ recipe reads with calib=DIR: the Hessians of the bf16
|
||||
* model, whose activations a quantised container's own tap would see through its quantisers.
|
||||
* The routed arm is not tapped. */
|
||||
if (calib_dir()) {
|
||||
m.overlap = false;
|
||||
m.arms = false;
|
||||
RAD_ARCH_TRY(calib_layers("gemma4", "RADIANCE_G4_CALIB_LAYERS", (int64_t)m.layers.size(),
|
||||
&m.calib_lo, &m.calib_hi));
|
||||
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
|
||||
Layer& y = m.layers[(size_t)l];
|
||||
const Kind& k = y.full ? m.kf : m.ks;
|
||||
const int i = (int)l;
|
||||
RAD_ARCH_TRY(y.tap_in.declare(b, nm, T, nm.f("blk.%d.attn_in", i), m.b_h, E));
|
||||
RAD_ARCH_TRY(y.tap_o.declare(b, nm, T, nm.f("blk.%d.attn_o", i),
|
||||
y.full ? m.b_attf : m.b_atts, k.q()));
|
||||
RAD_ARCH_TRY(y.tap_gu.declare(b, nm, T, nm.f("blk.%d.ffn_gate_up", i), m.b_h, E));
|
||||
RAD_ARCH_TRY(y.tap_dn.declare(b, nm, T, nm.f("blk.%d.ffn_down", i), m.b_act, m.n_ff));
|
||||
}
|
||||
m.calib = true;
|
||||
m.tap_live = true;
|
||||
}
|
||||
if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o));
|
||||
if (m.overlap || m.arms) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2));
|
||||
if (m.arms)
|
||||
@@ -1275,24 +1385,27 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_note(b, "sandwich joins: %d of %lld fused (norm_add_norm / join_add_scale)%s",
|
||||
n_joins, (long long)(m.moe ? 2 * m.n_layer : m.n_layer),
|
||||
n_joins == 0 ? " -- not served, the rmsnorm / add / mul_weight chain" : "");
|
||||
if (m.moe && m.n_gu_fp8 > 0)
|
||||
rad_note(b, "routed inputs: %d of %d fp8 layers take the router's norm and the experts' "
|
||||
"codes from the attention join (norm_add_norm_route)%s",
|
||||
n_route, m.n_gu_fp8,
|
||||
n_route ? "" : " -- the rmsnorm and rmsnorm_quant_fp8 launches instead");
|
||||
if (m.moe && m.n_gu_q > 0)
|
||||
rad_note(b, "routed inputs: %d of %d quantised layers take the router's norm and the "
|
||||
"experts' codes from the attention join (%s)%s",
|
||||
n_route, m.n_gu_q, join_r,
|
||||
n_route ? "" : m.exp_i8 ? " -- the rmsnorm and rmsnorm_had_quant_i8g launches instead"
|
||||
: " -- the rmsnorm and rmsnorm_quant_fp8 launches instead");
|
||||
if (m.ks.nh > 0)
|
||||
rad_note(b, "sliding attention: q %s", m.qrow == 1
|
||||
? "read in the fused qkv row (attn_paged_qrow)"
|
||||
: "lifted into a dense block for attn_paged (attn_paged_qrow not served)");
|
||||
if (m.moe) {
|
||||
auto how = [&](int n_fp8) {
|
||||
return n_fp8 == m.n_layer ? "block fp8" : n_fp8 == 0 ? "bf16" : "mixed";
|
||||
return n_fp8 == 0 ? "bf16" : n_fp8 < m.n_layer ? "mixed"
|
||||
: m.exp_i8 ? "rotated int8" : "block fp8";
|
||||
};
|
||||
rad_note(b, "routed arm: %lld local experts from %lld of %lld, top %lld, %lld wide; "
|
||||
"gate_up %s (%d of %lld layers fp8), down %s (%d fp8); passes of %lld tokens",
|
||||
"gate_up %s (%d of %lld layers quantised), down %s (%d quantised); passes of "
|
||||
"%lld tokens",
|
||||
(long long)m.n_local, (long long)m.expert_base, (long long)m.n_expert,
|
||||
(long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_fp8), m.n_gu_fp8,
|
||||
(long long)m.n_layer, how(m.n_dn_fp8), m.n_dn_fp8, (long long)m.moe_rows);
|
||||
(long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_q), m.n_gu_q,
|
||||
(long long)m.n_layer, how(m.n_dn_q), m.n_dn_q, (long long)m.moe_rows);
|
||||
if (W > 1)
|
||||
rad_note(b, "prefill overlap: %s", m.overlap
|
||||
? "a chunk of two routed passes or more runs as two slices, each slice's "
|
||||
@@ -1360,11 +1473,11 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
|
||||
}
|
||||
/* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent);
|
||||
* issued only where the attention join did not already write the codes. */
|
||||
if (y.gu_fp8 && !y.op_join_r)
|
||||
if (y.gu_q && !y.op_join_r)
|
||||
RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm),
|
||||
brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK),
|
||||
RAD_NONE);
|
||||
else if (!y.gu_fp8)
|
||||
else if (!y.gu_q)
|
||||
RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_enorm),
|
||||
brow_slice(m.b_hx, r0, n, E));
|
||||
if (!rfused && !pair)
|
||||
@@ -1373,7 +1486,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
|
||||
/* An fp8 projection's tables: the first handle of each parity's run and its length --
|
||||
* even codes, even scales, odd codes, odd scales (declare). */
|
||||
const int64_t H = NL / 2;
|
||||
if (y.gu_fp8)
|
||||
if (y.gu_q)
|
||||
RAD_ISSUE_N(c, y.op_egu, n, brow_slice(m.b_hq, r0, n, E),
|
||||
brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK),
|
||||
RAD_WTAB(y.w_egu[0], H), RAD_WTAB(y.w_egus[0], H),
|
||||
@@ -1385,7 +1498,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
|
||||
brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), brows(m.b_egu, n * K));
|
||||
RAD_ISSUE_N(c, y.op_eact, n * K, bcol(m.b_egu, 0, m.n_ffe, n * K),
|
||||
bcol(m.b_egu, m.n_ffe, m.n_ffe, n * K), brows(m.b_eact, n * K));
|
||||
if (y.dn_fp8) {
|
||||
if (y.dn_q) {
|
||||
RAD_ISSUE_N(c, y.op_eq, n * K, brows(m.b_eact, n * K), brows(m.b_eq, n * K),
|
||||
brows(m.b_eqs, n * K));
|
||||
RAD_ISSUE_N(c, y.op_edn, n, brows(m.b_eq, n * K), brows(m.b_eqs, n * K),
|
||||
@@ -1464,8 +1577,10 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) {
|
||||
RAD_ISSUE(c, y.op_q, brows(m.b_h, T), RAD_W(y.w_q), brows(m.b_qf, T));
|
||||
RAD_ISSUE(c, y.op_k, brows(m.b_h, T), RAD_W(y.w_k), brows(m.b_kf, T));
|
||||
}
|
||||
y.tap_in.step(c, m.b_h, T, m.tap_live);
|
||||
attend(c, m, y, li, batch);
|
||||
RAD_ISSUE(c, y.op_o, brows(y.full ? m.b_attf : m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T));
|
||||
y.tap_o.step(c, y.full ? m.b_attf : m.b_atts, T, m.tap_live);
|
||||
if (y.op_ar_o) RAD_ISSUE_N(c, y.op_ar_o, T * E, brows(m.b_o, T), RAD_NONE);
|
||||
if (y.op_join_r) {
|
||||
RAD_ISSUE(c, y.op_join_r, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T),
|
||||
@@ -1485,9 +1600,11 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) {
|
||||
if (m.arms)
|
||||
lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK;
|
||||
RAD_ISSUE(c, y.op_gu, brows(m.b_h, T), RAD_W(y.w_gu), brows(m.b_gu, T));
|
||||
y.tap_gu.step(c, m.b_h, T, m.tap_live);
|
||||
RAD_ISSUE(c, y.op_act, bcol(m.b_gu, 0, m.n_ff, T), bcol(m.b_gu, m.n_ff, m.n_ff, T),
|
||||
brows(m.b_act, T));
|
||||
RAD_ISSUE(c, y.op_dn, brows(m.b_act, T), RAD_W(y.w_dn), brows(m.b_ff2, T));
|
||||
y.tap_dn.step(c, m.b_act, T, m.tap_live);
|
||||
if (m.arms) lanes_ok = rad_lane(c, 0) == RAD_OK && lanes_ok;
|
||||
if (m.moe) {
|
||||
routed(c, m, y, T, 0, T, T);
|
||||
@@ -1668,8 +1785,38 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
|
||||
"the first");
|
||||
}
|
||||
|
||||
/* The tap's rows, and its files once the corpus reached RADIANCE_CALIB_TOKENS. The input of q|k|v
|
||||
* and of gate|up is whole on every rank, so rank 0 writes it, under the name of the linear that
|
||||
* reads it. The column-split linears (o, down) see this rank's columns only: each rank writes its
|
||||
* block as `<stem>.part`, which libquant's calib_sum places on the diagonal in rank order (the
|
||||
* cross-rank products are never formed on one card). */
|
||||
static void calib_count(RadCtx* c, Model& m, int64_t T) {
|
||||
m.calib_rows += T;
|
||||
if (m.calib_rows < calib_target()) return;
|
||||
const int rk = rad_rank(c);
|
||||
bool ok = true;
|
||||
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
|
||||
const Layer& y = m.layers[(size_t)l];
|
||||
char stem[96];
|
||||
if (rk == 0) {
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.attn_qkv", (int)l);
|
||||
ok = calib_write(c, y.tap_in.h, y.tap_in.K, m.calib_rows, stem, 0) && ok;
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.ffn_gate_up", (int)l);
|
||||
ok = calib_write(c, y.tap_gu.h, y.tap_gu.K, m.calib_rows, stem, 0) && ok;
|
||||
}
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.attn_o.part", (int)l);
|
||||
ok = calib_write(c, y.tap_o.h, y.tap_o.K, m.calib_rows, stem, 0) && ok;
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.ffn_down.part", (int)l);
|
||||
ok = calib_write(c, y.tap_dn.h, y.tap_dn.K, m.calib_rows, stem, 0) && ok;
|
||||
}
|
||||
m.tap_live = false;
|
||||
std::fprintf(stderr, "radiance: gemma4: rank %d wrote the Hessians of layers %lld:%lld after "
|
||||
"%lld tokens to %s%s\n", rk, (long long)m.calib_lo, (long long)m.calib_hi,
|
||||
m.calib_rows, calib_dir(), ok ? "" : ", with errors");
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (batch->draft_pass != 0) {
|
||||
if (!m.have_df) {
|
||||
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
|
||||
@@ -1695,6 +1842,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const int64_t cut = split_at(m, T);
|
||||
if (cut > 0) trunk_overlap(c, m, batch, cut);
|
||||
else trunk(c, m, batch);
|
||||
if (m.calib && m.tap_live) calib_count(c, g_model[rad_slot(c)], T);
|
||||
|
||||
if (m.op_onorm) RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T));
|
||||
if (batch->n_out > 0) {
|
||||
@@ -1727,6 +1875,8 @@ static const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_cha
|
||||
} /* namespace gemma4 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(gemma4, "gemma4", "", "0.1.0",
|
||||
"Gemma 4 text decoders (26B-A4B MoE, dense 31B), bf16: sliding and full attention "
|
||||
"with proportional rope and K = V, a dense and a routed feed-forward side by side, "
|
||||
|
||||
+976
-129
File diff suppressed because it is too large.
Load diff
+126
-24
@@ -46,6 +46,16 @@ struct Layer {
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
/* The MLA's split of a prefill-sized step under TP (RadBuildCtx::tp_attn_rows). The head
|
||||
* form declares none of the row form's full-width weights (1.29 GiB a card at eight ranks);
|
||||
* the row form is opt-in because it is not bit-identical to it (docs/ARCHITECTURES.md). */
|
||||
GlmMla::Form form = GlmMla::Form::heads;
|
||||
/* Routed experts whole on their rank (288/world of them) instead of split by width across
|
||||
* every rank. Whole experts can be read from the drive, which two cards need; at four and
|
||||
* eight the width split is the shape the MXFP4 kernels are tuned for (prefill runs about three
|
||||
* times faster), so all-MXFP4 experts take it unless --weights-disk-tier asks for the drive.
|
||||
* Anything else stays whole: a plain bf16 expert cannot be sliced at all. */
|
||||
bool whole_experts = false;
|
||||
std::vector<Layer> layers;
|
||||
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
|
||||
/* The streams and the step's stream-wide buffers. */
|
||||
@@ -69,9 +79,26 @@ struct Model {
|
||||
GlmVision vit{};
|
||||
MediaRows mrows{};
|
||||
};
|
||||
static std::unique_ptr<Model> models[MAX_RANKS];
|
||||
static std::unique_ptr<Model> models[MAX_SLOTS];
|
||||
static thread_local std::unique_ptr<Model> probe_model;
|
||||
|
||||
/* Whether every routed expert is MXFP4, asked before any buffer is sized and of the same experts on
|
||||
* every rank, so all ranks reach the same layout. It reads the container's entries and declares no
|
||||
* name map, so it leaves the graph as it was. One expert in another format settles it: a protected
|
||||
* bf16 expert is served only whole. No answer means no container entry, and what is not known to
|
||||
* be MXFP4 stays whole. */
|
||||
static bool experts_are_mxfp4(RadBuilder* b, Names& nm) {
|
||||
for (int l = 3; l < 45; ++l)
|
||||
for (int ge = 0; ge < 288; ++ge)
|
||||
for (const char* fmt : { "blk.%d.ffn_gate_up_exps.%d.weight",
|
||||
"blk.%d.ffn_down_exps.%d.weight" }) {
|
||||
RadEncoding e{};
|
||||
if (!weight_enc(b, nm.f(fmt, l, ge), &e) || MoeFP8::format_of(e) != 8)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
|
||||
char nested[160];
|
||||
std::snprintf(nested, sizeof nested, "text_config.%s", key);
|
||||
@@ -102,7 +129,11 @@ static int stream_buffers(RadBuilder* b, Model& m) {
|
||||
m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 });
|
||||
m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 });
|
||||
m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 });
|
||||
m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, { T, 4096 });
|
||||
/* The MLA row form gathers every rank's run at full length, so its output is rounded up to
|
||||
* whole runs; the head form keeps the step's rows. */
|
||||
const bool rows = g.world > 1 && m.form == GlmMla::Form::rows;
|
||||
m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16,
|
||||
{ rows ? g.world * GlmMla::rows_for(T, g.world) : T, 4096 });
|
||||
m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 });
|
||||
m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 });
|
||||
m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 });
|
||||
@@ -132,9 +163,9 @@ static int kda_buffers(RadBuilder* b, Model& m) {
|
||||
kw.core.out = bf("recurrent_out", W);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. Under
|
||||
* TP the selection planes hold every rank's run of rows, which can reach past the step
|
||||
* (DsaCache::part_rows). */
|
||||
/* The head form's buffers, then the selection planes the indexer writes and the MLA reads, then
|
||||
* the row form's (Model::form). Under TP the selection planes hold every rank's run of rows,
|
||||
* which can reach past the step (DsaCache::part_rows). */
|
||||
static int mla_buffers(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
@@ -160,6 +191,16 @@ static int mla_buffers(RadBuilder* b, Model& m) {
|
||||
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
|
||||
aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 });
|
||||
aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ });
|
||||
if (g.world > 1 && m.form == GlmMla::Form::rows) {
|
||||
auto& rows = aw.rows;
|
||||
const int64_t R = GlmMla::rows_for(T, g.world);
|
||||
rows.q = decl_b(b, nm.f("rows_query"), RAD_BF16, { R, 16384 });
|
||||
rows.q_latent = decl_b(b, nm.f("rows_q_latent"), RAD_BF16, { R, 64, 512 });
|
||||
rows.attn_latent = decl_b(b, nm.f("rows_attn_latent"), RAD_BF16, { R, 64, 512 });
|
||||
rows.attn.x = decl_b(b, nm.f("rows_expanded"), RAD_BF16, { R, 16384 });
|
||||
RAD_ARCH_TRY(rows.attn.declare_qs(b, nm, g, "rows_expanded", 16384, R));
|
||||
rows.out = decl_b(b, nm.f("rows_out"), RAD_BF16, { R, 4096 });
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
static int indexer_buffers(RadBuilder* b, Model& m) {
|
||||
@@ -193,9 +234,12 @@ static int indexer_buffers(RadBuilder* b, Model& m) {
|
||||
* at 64k of context the whole step's plane would be 256 MiB. */
|
||||
const int64_t scored = g.world > 1 ? std::min(T, std::max(part, GlmTp::kSplitRows)) : T;
|
||||
c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { scored, blocks });
|
||||
c.unscored = decl_b(b, nm.f("index_unscored"), RAD_F32, { T, std::min<int64_t>(513, blocks) });
|
||||
c.selected = m.aw.core.selected;
|
||||
c.length = m.aw.core.length;
|
||||
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
|
||||
/* The MLA block's resolve count: qsa_select's second output, never `length`. */
|
||||
m.aw.core.nsel = c.nsel;
|
||||
if (g.world > 1) {
|
||||
c.cu_part = decl_b(b, nm.f("index_part_bounds"), RAD_I32, { g.max_seqs + 1 });
|
||||
c.sel_part = decl_b(b, nm.f("selected_part"), RAD_I32, { part, 513 });
|
||||
@@ -223,12 +267,21 @@ static int ffn_buffers(RadBuilder* b, Model& m) {
|
||||
mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 });
|
||||
mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 });
|
||||
mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 });
|
||||
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 });
|
||||
/* PERSIST, as every other MoE here declares it: the router writes the counts and no declared
|
||||
* op reads them (rad_route_report is a handoff), so as a transient a later buffer could share
|
||||
* their bytes and an arena level would move them, while the core copies them at the block's
|
||||
* end and the file stager reads them, through the address the last pass reported, at the
|
||||
* layer's first expert op. */
|
||||
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }, RAD_BUF_PERSIST);
|
||||
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 });
|
||||
mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 });
|
||||
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * F });
|
||||
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, F });
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * 8));
|
||||
// FE: the routed experts' intermediate. Under expert parallelism a rank owns whole experts,
|
||||
// so the routed arm's buffers are full-width (2048); split by width they are F. The SHARED
|
||||
// expert stays width-sharded (F) either way. The two coincide at world 1.
|
||||
const int64_t FE = m.whole_experts ? 2048 : F;
|
||||
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * FE });
|
||||
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, FE });
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", FE, T * 8));
|
||||
mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { T * 8, 4096 });
|
||||
mw.sgu = bf("shared_gate_up", 2 * F);
|
||||
mw.sff.x = bf("shared_ff", F);
|
||||
@@ -242,7 +295,8 @@ static int kv_groups(RadBuilder* b, Model& m) {
|
||||
auto& nm = m.nm;
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_BF16;
|
||||
// bf16, or E4M3 under --kv-cache-dtype fp8 (geometry); the other groups keep their own.
|
||||
d.dtype = rad_dtype_parse(g.kv_dtype);
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = 256;
|
||||
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
|
||||
@@ -292,7 +346,10 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096));
|
||||
if (lay.full) {
|
||||
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true));
|
||||
// The MTP layer keeps the head form: its row form would cost another 126 MB a card.
|
||||
auto aw = m.aw;
|
||||
if (draft) aw.rows = {};
|
||||
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, aw, ap, m.latent, true, true));
|
||||
DsaCache::Config c;
|
||||
c.blocks = (g.max_ctx + 3) / 4 + 1;
|
||||
c.work = (g.max_tok + 3) / 4 + g.max_seqs;
|
||||
@@ -334,9 +391,31 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
s.router_bias = nm.ckpt("%s.mlp.gate.e_score_correction_bias", pre);
|
||||
s.experts = nm.ckpt("%s.mlp.experts", pre);
|
||||
s.shared = nm.ckpt("%s.mlp.shared_experts", pre);
|
||||
s.cfg.n_expert = s.cfg.n_expert_all = 288;
|
||||
// EXPERT PARALLELISM AT TP: each rank owns 288/world WHOLE experts (the contiguous
|
||||
// window [expert_base, expert_base+n_expert) of the checkpoint's numbering), which the
|
||||
// helper declares RAD_SHARD_NONE -- unsharded, so an expert unit is file-direct and can
|
||||
// live in the container's mapping or the file tier
|
||||
// instead of needing VRAM+pinned-pool residency for all 151 GiB of them. The router
|
||||
// stays replicated over n_expert_all; moe_scatter/router_topk_scatter drop slots
|
||||
// outside the window (moe_scatter schema: "which is how EXPERT PARALLELISM is
|
||||
// expressed"); the shared expert stays width-sharded on its own declaration path; the
|
||||
// block's all-reduce sums the partials exactly as width TP did. At world 1 this
|
||||
// degenerates to the old whole-model declaration (n_expert == n_expert_all, no spans).
|
||||
s.cfg.n_expert_all = 288;
|
||||
s.cfg.top_k = 8;
|
||||
s.cfg.n_ff_exp = s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
|
||||
s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
|
||||
if (m.whole_experts) {
|
||||
s.cfg.n_expert = 288 / g.world;
|
||||
// A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4);
|
||||
// old code tolerated that because expert_base stayed 0, so clamp to rank 0's window.
|
||||
const int ep_rank = g.rank < g.world ? g.rank : 0;
|
||||
s.cfg.expert_base = ep_rank * (288 / g.world);
|
||||
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
|
||||
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
|
||||
} else {
|
||||
s.cfg.n_expert = 288;
|
||||
s.cfg.n_ff_exp = GlmTp::expert_width(g.world);
|
||||
}
|
||||
s.cfg.rows = g.max_tok;
|
||||
s.cfg.sigmoid_router = 1;
|
||||
s.cfg.route_scale = 2.5;
|
||||
@@ -344,9 +423,14 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
s.cfg.shared_ungated = 1;
|
||||
s.cfg.router_fuse = 1;
|
||||
s.cfg.swiglu_quant = 1;
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
|
||||
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
|
||||
// At world 1 the width-slice declaration IS the whole model: keep the spans so the
|
||||
// graph stays the pinned one. Whole experts need no width spans (split && ep is refused
|
||||
// by the helper).
|
||||
if (!m.whole_experts) {
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
|
||||
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg));
|
||||
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, w, s, false, draft));
|
||||
@@ -375,15 +459,22 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i
|
||||
g.max_ctx = ctx->max_ctx;
|
||||
g.max_seqs = ctx->max_seqs;
|
||||
g.max_spec = ctx->max_spec;
|
||||
/* Filled by hand here, not by geom_from: without it kv_resolve would declare the whole context as
|
||||
* the ring. */
|
||||
g.kv_resident = ctx->kv_resident_blocks;
|
||||
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1));
|
||||
if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
|
||||
g.eps = meta->rms_eps;
|
||||
/* --kv-cache-dtype names the latent cache's dtype only (kv_groups); declare refuses all but
|
||||
* bf16 and fp8. */
|
||||
g.kv_dtype = rad_dtype_name(rad_kv_cache_dtype(ctx, RAD_BF16));
|
||||
g.wire_exact = !ctx->tp_wire_lossy;
|
||||
g.wire_min_bytes = ctx->tp_wire_min_bytes;
|
||||
return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK;
|
||||
}
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
if (!GlmTp::world_ok(world)) {
|
||||
@@ -416,20 +507,24 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ctx->max_spec);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) {
|
||||
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin keeps its latent "
|
||||
"attention, index tail and KDA caches in bf16 and has no fp8 cache, so "
|
||||
"run it with --kv-cache-dtype bf16\n",
|
||||
ctx->kv_dtype == RAD_F8E4M3 ? "fp8" : rad_dtype_name(ctx->kv_dtype));
|
||||
/* fp8 narrows the latent attention cache to E4M3 at a descale of 1 (kv_groups); the index
|
||||
* tail, the DSA index and the KDA caches keep their dtypes. */
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_F8E4M3) {
|
||||
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin serves its latent "
|
||||
"attention cache in bf16 or fp8 only\n",
|
||||
rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[rad_build_slot(ctx)];
|
||||
slot = std::make_unique<Model>();
|
||||
auto& m = *slot;
|
||||
auto& g = m.g;
|
||||
m.nm = Names(ctx->scope);
|
||||
auto& nm = m.nm;
|
||||
m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads;
|
||||
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
|
||||
m.whole_experts = world == 2 || (world > 2 && (ctx->expert_file_tier ||
|
||||
!experts_are_mxfp4(b, nm)));
|
||||
RAD_ARCH_TRY(stream_buffers(b, m));
|
||||
RAD_ARCH_TRY(kda_buffers(b, m));
|
||||
RAD_ARCH_TRY(mla_buffers(b, m));
|
||||
@@ -531,7 +626,7 @@ static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
|
||||
m.mtp.step_head(c, batch);
|
||||
}
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
auto& m = *models[rad_rank(c)];
|
||||
auto& m = *models[rad_slot(c)];
|
||||
const int64_t T = batch->n_tok;
|
||||
// An encoder pass runs only the vision tower (RadBatch::enc).
|
||||
if (batch->enc) {
|
||||
@@ -571,6 +666,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
/* The MLA block declares the streamed store and the resolve (rad_block_glm_mla.h). */
|
||||
out->kv_stream_ok = 1;
|
||||
if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth;
|
||||
// The tower's merged block, so a pass size the core picks itself is whole output rows.
|
||||
if (GlmVision::present(meta)) {
|
||||
@@ -578,11 +675,16 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (k > 0) out->enc_merge = k * k;
|
||||
}
|
||||
out->shape_probe_ok = 1;
|
||||
out->tp_attn_rows_ok = 1;
|
||||
/* --kv-cache-dtype fp8: the latent attention cache as E4M3 (declare, kv_groups). */
|
||||
out->kv_fp8_ok = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
} // namespace glm5next
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(glm5next)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(glm5next, "glm5next", "", "0.1.0",
|
||||
"GLM-5.3-Flash mixed MXFP4/FP8, mHC/KDA/MLA and native serial MTP")
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/hunyuan3d2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hunyuan3d2 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hunyuan3d2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hunyuan3d2.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hyv3_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hyv3_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_bf16.cpp)
|
||||
@@ -0,0 +1,5 @@
|
||||
#define HYV3_NS hyv3_bf16
|
||||
#define HYV3_QUANT ""
|
||||
#define HYV3_FP8_SOURCE 0
|
||||
#define HYV3_PLUGIN_NAME "hyv3_bf16"
|
||||
#include "../hyv3_common/hyv3_impl.cpp"
|
||||
@@ -0,0 +1,208 @@
|
||||
/* HYV3 full GQA attention with block-scaled FP8 projections and per-head
|
||||
* Q/K RMSNorm before NeoX RoPE (the HYV3 attention path).
|
||||
*
|
||||
* rmsnorm -> q/k/v gemm_nt_q -> per-head q/k RMSNorm -> rope -> kv_store -> attn_paged
|
||||
* -> quant_act_fp8 -> o gemm_nt_q -> [all_reduce] -> residual add
|
||||
*
|
||||
* Unlike AttnFP8, the projections stay separate so Q and K can be normalized independently before
|
||||
* rotation. The weights and all non-attention activations use the same contracts as the other FP8
|
||||
* blocks in rad_fp8.h.
|
||||
*/
|
||||
#ifndef HYV3_ATTENTION_H
|
||||
#define HYV3_ATTENTION_H
|
||||
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnQKFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */
|
||||
rad_buf q = 0; /* [max_tok, q_dim], projected, normed and rotated */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim], projected, normed and rotated */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim], projected */
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* q = nullptr;
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
const char* o = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
LinearFP8 q{}, k{}, v{}, o{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
rad_op op_q_norm = 0, op_k_norm = 0;
|
||||
rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0;
|
||||
rad_op op_qkr_store = 0; /* Q/K norms, NeoX rotary and BF16 cache store, decode band */
|
||||
int64_t qkr_rows = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
const Wire& wire, const Src& src, bool fold = false, bool add_out = true);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, const Wire& wire, const Src& src,
|
||||
bool fold, bool add_out) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
layer = l;
|
||||
kv = group;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld\n", __func__, g.world,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
if (!w_norm || !w_q_norm || !w_k_norm) return RAD_E_INVAL;
|
||||
|
||||
// As in the other pre-norm blocks, absorb a preceding delta into the residual stream.
|
||||
// The fused kernel normalises the BF16-rounded sum, not an unrounded FP32 substitute.
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0));
|
||||
RAD_ARCH_TRY(q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), q_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.q}, w.h, w.q));
|
||||
RAD_ARCH_TRY(k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.k}, w.h, w.k));
|
||||
RAD_ARCH_TRY(v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.v}, w.h, w.v));
|
||||
|
||||
auto head_norm = [&](int64_t heads, rad_weight wt) {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q});
|
||||
op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, "neox"),
|
||||
{w.k}, {w.k});
|
||||
|
||||
const rad_op attn = rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS);
|
||||
op_attn = rw(b, attn, {w.q}, {w.attn.x});
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* The standalone chain stays available for prefill, scaled/multicomponent rotary, the int8
|
||||
* cache and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five tiny
|
||||
* launches; the fused kernel preserves the BF16 norm rounding before the rotary. */
|
||||
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
|
||||
!std::strcmp(g.kv_dtype, "bf16") &&
|
||||
!g.rope_mc && g.yarn.factor == 0.0f &&
|
||||
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
|
||||
qkr_rows = qk_fuse_rows(g);
|
||||
op_qkr_store = RAD_OP(b, "qkv_norm_rope_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qkr_rows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
|
||||
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("v_norm", 0), RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm));
|
||||
if (!op_qkr_store || !rad_op_resolved(b, op_qkr_store)) op_qkr_store = 0;
|
||||
if (op_qkr_store)
|
||||
op_qkr_store = rw(b, op_qkr_store, {w.q, w.k, w.v}, {w.q, w.k, w.v});
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
|
||||
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), {src.o}, w.attn, w.h.x));
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
if (add_out) op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
return op_attn && op_kv_store && (!add_out || op_add) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
nq_h.step(c, T);
|
||||
q.step(c, w.h, w.q, T);
|
||||
k.step(c, w.h, w.k, T);
|
||||
v.step(c, w.h, w.v, T);
|
||||
if (op_qkr_store && T <= qkr_rows) {
|
||||
RAD_ISSUE_N(c, op_qkr_store, T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
rope_posmc(g, batch, T), RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_kv_store, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, layer));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
|
||||
q_attn.step(c, T);
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
|
||||
#endif /* HYV3_ATTENTION_H */
|
||||
@@ -0,0 +1,535 @@
|
||||
/* Shared HYV3 graph. Thin architecture wrappers select the source descriptor and source format. */
|
||||
#ifndef HYV3_NS
|
||||
#define HYV3_NS hyv3_fp8
|
||||
#endif
|
||||
#ifndef HYV3_QUANT
|
||||
#define HYV3_QUANT "fp8"
|
||||
#endif
|
||||
#ifndef HYV3_FP8_SOURCE
|
||||
#define HYV3_FP8_SOURCE 1
|
||||
#endif
|
||||
#ifndef HYV3_PLUGIN_NAME
|
||||
#define HYV3_PLUGIN_NAME "hyv3_fp8"
|
||||
#endif
|
||||
#ifndef HYV3_GGUF_SOURCE
|
||||
#define HYV3_GGUF_SOURCE 0
|
||||
#endif
|
||||
#include <arch/rad_arch.h>
|
||||
#include "hyv3_attention.h"
|
||||
#include "rad_abi_layout.h"
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace HYV3_NS {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool dense = false;
|
||||
AttnQKFP8 attn{};
|
||||
MlpFP8 dense_mlp{};
|
||||
MoeFP8 moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
int64_t n_ff_expert = 0, n_ff_shared = 0;
|
||||
rad_kvgroup kv_full = 0;
|
||||
|
||||
rad_buf x = 0, h_out = 0, logits = 0;
|
||||
ActFP8 h{};
|
||||
rad_buf q = 0, k = 0, v = 0;
|
||||
ActFP8 attn{};
|
||||
rad_buf dense_gate_up = 0;
|
||||
ActFP8 dense_ffn{};
|
||||
MoeFP8::Wire mw{};
|
||||
|
||||
rad_weight token = 0, final_norm = 0, lm_head = 0;
|
||||
rad_op embed = 0, embed_ar = 0, shared_one = 0, final_rms = 0, gather = 0, logits_op = 0;
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model models[MAX_SLOTS];
|
||||
|
||||
static int check_format(const RadModelMeta* meta) {
|
||||
const char* q = meta && meta->quant ? meta->quant : "";
|
||||
#if HYV3_GGUF_SOURCE
|
||||
if (std::strcmp(q, "gguf_ftype_15") != 0) {
|
||||
fprintf(stderr, "radiance: HYV3 GGUF adapter expects quant descriptor 'gguf_ftype_15'; "
|
||||
"got '%s'\n", *q ? q : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#elif HYV3_FP8_SOURCE
|
||||
if (std::strcmp(q, "fp8") != 0) {
|
||||
fprintf(stderr, "radiance: HYV3 FP8 expects quant descriptor 'fp8'; got '%s'\n",
|
||||
*q ? q : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* fmt = rad_meta_gets(meta, "quantization_config.fmt", nullptr);
|
||||
if (fmt && std::strcmp(fmt, "e4m3") != 0) return RAD_E_UNSUPPORTED;
|
||||
const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr);
|
||||
if (method && std::strcmp(method, "fp8") != 0) return RAD_E_UNSUPPORTED;
|
||||
#else
|
||||
if (*q) {
|
||||
fprintf(stderr, "radiance: HYV3 BF16 expects an unquantized checkpoint; got '%s'\n", q);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#endif
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int check_model_config(const RadModelMeta* meta, const Geom& g, Model& model) {
|
||||
if (meta_text_geti(meta, "qk_norm", 0) != 1 ||
|
||||
meta_text_geti(meta, "moe_router_use_sigmoid", 0) != 1 ||
|
||||
meta_text_geti(meta, "moe_router_enable_expert_bias", 0) != 1 ||
|
||||
meta_text_geti(meta, "route_norm", 0) != 1 ||
|
||||
meta_text_geti(meta, "enable_moe_fp32_combine", 0) != 1 ||
|
||||
meta_text_geti(meta, "attention_bias", 0) != 0 ||
|
||||
meta_text_geti(meta, "mlp_bias", 0) != 0) {
|
||||
fprintf(stderr, "radiance: hyv3 requires QK norm, sigmoid routing with correction bias, "
|
||||
"route normalization, FP32 MoE combine, and bias-free projections\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
const int64_t first_dense = meta_text_geti(meta, "first_k_dense_replace", -1);
|
||||
const int64_t n_expert = meta_text_geti(meta, "num_experts", 0);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", 0);
|
||||
const int64_t n_shared = meta_text_geti(meta, "num_shared_experts", 0);
|
||||
const int64_t moe_intermediate = meta_text_geti(meta, "moe_intermediate_size", 0);
|
||||
const int64_t n_ff_shared = meta_text_geti(meta, "expert_hidden_dim", 0);
|
||||
model.n_ff_expert = meta_text_geti(meta, "expert_hidden_dim", 0);
|
||||
const int64_t route_norm = meta_text_geti(meta, "route_norm", 0);
|
||||
const double route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0);
|
||||
const char* schedule = meta_text_gets(meta, "mlp_layer_types", nullptr);
|
||||
std::vector<int> kinds;
|
||||
|
||||
if (first_dense != 1 || n_expert != meta->n_expert || top_k != meta->n_expert_used ||
|
||||
n_expert != 128 || top_k != 8 || n_shared != 1 || model.n_ff_expert != 768 ||
|
||||
n_ff_shared != 768 || moe_intermediate != 1536 || route_norm != 1 ||
|
||||
!std::isfinite(route_scale) || route_scale <= 0 ||
|
||||
std::fabs(route_scale - 2.826) > 1e-6 || model.n_ff_expert % RAD_FP8_BLOCK != 0) {
|
||||
fprintf(stderr, "radiance: hyv3: unsupported MoE geometry/config; expected 128 experts, "
|
||||
"top-8, 768-wide routed and shared experts, normalized "
|
||||
"sigmoid routing scaled by 2.826, and one dense first layer\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (schedule && *schedule) {
|
||||
RAD_ARCH_TRY(parse_layer_kinds("hyv3", schedule, {"sparse"}, "dense", &kinds));
|
||||
if ((int64_t)kinds.size() != g.n_layer) {
|
||||
fprintf(stderr, "radiance: hyv3: mlp_layer_types names %zu layers; the model has %lld\n",
|
||||
kinds.size(), (long long)g.n_layer);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int want = l == 0 ? 0 : 1;
|
||||
if (kinds[(size_t)l] != want) {
|
||||
fprintf(stderr, "radiance: hyv3: layer %lld has an unsupported MLP kind; expected "
|
||||
"dense at layer 0 and sparse afterwards\n", (long long)l);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int64_t shared_width = n_ff_shared * n_shared;
|
||||
if (shared_width <= 0 || shared_width % RAD_FP8_BLOCK != 0) return RAD_E_SHAPE;
|
||||
model.n_ff_shared = shared_width;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
|
||||
const int64_t blocks = width / RAD_FP8_BLOCK;
|
||||
const int64_t base = blocks / world, rem = blocks % world;
|
||||
const int64_t first = rank * base + std::min<int64_t>(rank, rem);
|
||||
const int64_t count = base + (rank < rem ? 1 : 0);
|
||||
*lo = first * RAD_FP8_BLOCK;
|
||||
*hi = (first + count) * RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = models[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
int status = check_format(meta);
|
||||
if (status < 0) return status;
|
||||
status = geom_from(m.g, meta, ctx, "bf16", RAD_BF16);
|
||||
if (status < 0) return status;
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
if (g.n_layer < 2 || g.n_embd != 2048 || g.n_head_all != 32 || g.n_head_kv_all != 4 ||
|
||||
g.head_dim != 128 || g.n_vocab_all != 120832 ||
|
||||
(g.world != 1 && g.world != 2)) {
|
||||
fprintf(stderr, "radiance: hyv3 supports Hy-Memory's 2048-wide, 32/4-head, "
|
||||
"head_dim=128 geometry at tensor-parallel world sizes 1 or 2\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
status = check_model_config(meta, g, m);
|
||||
if (status < 0) return status;
|
||||
if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) {
|
||||
fprintf(stderr, "radiance: HYV3 serves a bf16 or an int8 KV cache, not %s\n",
|
||||
rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
status = yarn_from(g, meta, "", g.head_dim);
|
||||
if (status < 0) return status;
|
||||
|
||||
const int64_t n_expert_all = meta_text_geti(meta, "num_experts", meta->n_expert);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
|
||||
if (n_expert_all % g.world != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_expert_local = n_expert_all / g.world;
|
||||
|
||||
/* ---- Full-attention KV cache. All layers share one group. */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
kd.n_head_kv = g.n_head_kv;
|
||||
kd.head_dim = g.head_dim;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &kd);
|
||||
if (!m.kv_full) return RAD_E_INVAL;
|
||||
g.kv_dtype = rad_dtype_name(kd.dtype);
|
||||
|
||||
const int64_t T = g.max_tok, qd = g.q_dim(), kvd = g.kv_dim();
|
||||
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, g.n_embd});
|
||||
m.h.x = decl_b(b, nm.f("h"), RAD_BF16, {T, g.n_embd});
|
||||
RAD_ARCH_TRY(m.h.declare_qs(b, nm, g, "h", g.n_embd, 0, !HYV3_FP8_SOURCE));
|
||||
m.q = decl_b(b, nm.f("attn_q"), RAD_BF16, {T, qd});
|
||||
m.k = decl_b(b, nm.f("attn_k"), RAD_BF16, {T, kvd});
|
||||
m.v = decl_b(b, nm.f("attn_v"), RAD_BF16, {T, kvd});
|
||||
m.attn.x = decl_b(b, nm.f("attn_out"), RAD_BF16, {T, qd});
|
||||
RAD_ARCH_TRY(m.attn.declare_qs(b, nm, g, "attn_out", qd, 0, !HYV3_FP8_SOURCE));
|
||||
m.dense_gate_up = decl_b(b, nm.f("dense_gate_up"), RAD_BF16, {T, 2 * g.n_ff});
|
||||
m.dense_ffn.x = decl_b(b, nm.f("dense_ffn"), RAD_BF16, {T, g.n_ff});
|
||||
RAD_ARCH_TRY(m.dense_ffn.declare_qs(b, nm, g, "dense_ffn", g.n_ff, 0, !HYV3_FP8_SOURCE));
|
||||
m.h_out = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
|
||||
|
||||
/* The router is replicated, while the routed experts are expert-parallel. The shared expert
|
||||
* is split only on whole FP8 scale blocks; the final block remainder is assigned to early
|
||||
* ranks. At TP2, routed and shared BF16 outputs are all-reduced separately before FP32 combine. */
|
||||
MoeFP8::Config mc{};
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.n_expert = n_expert_local;
|
||||
mc.expert_base = n_expert_local * g.rank;
|
||||
mc.probed_expert = mc.expert_base;
|
||||
mc.top_k = top_k;
|
||||
mc.n_ff_exp = m.n_ff_expert;
|
||||
mc.norm_topk = 1;
|
||||
mc.sigmoid_router = 1;
|
||||
mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 2.826);
|
||||
mc.shared_ungated = 1;
|
||||
mc.shared_fp32_combine = 1;
|
||||
mc.shared_one_external = g.world == 1;
|
||||
mc.router_fuse = 1;
|
||||
mc.rows = T < 2048 ? T : 2048;
|
||||
block_slice_128(m.n_ff_shared, g.world, g.rank, &mc.shared_lo, &mc.shared_hi);
|
||||
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
|
||||
|
||||
#if HYV3_FP8_SOURCE
|
||||
/* The source's per-tensor scales are imported by the recipe to format 9 (block FP8 with F32
|
||||
* 128x128 scales). The model probes the source before recipe planning, so state that encoding
|
||||
* explicitly here. */
|
||||
mc.expert_f32_scale = 1;
|
||||
#endif
|
||||
|
||||
const int64_t R = T, S = mc.rows * top_k;
|
||||
m.mw.x = m.x;
|
||||
m.mw.h = m.h;
|
||||
m.mw.logits = decl_b(b, nm.f("moe_logits"), RAD_F32, {R, n_expert_all});
|
||||
m.mw.ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, top_k});
|
||||
m.mw.ew = decl_b(b, nm.f("moe_weights"), RAD_F32, {R, top_k});
|
||||
m.mw.eoff = decl_b(b, nm.f("moe_offsets"), RAD_I32, {n_expert_local + 1});
|
||||
m.mw.ecnt = decl_b(b, nm.f("moe_counts"), RAD_I32, {n_expert_local}, RAD_BUF_PERSIST);
|
||||
m.mw.sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {S});
|
||||
m.mw.egu = decl_b(b, nm.f("moe_gate_up"), RAD_BF16, {S, 2 * mc.n_ff_exp});
|
||||
m.mw.eff.x = decl_b(b, nm.f("moe_ffn"), RAD_BF16, {S, mc.n_ff_exp});
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, !HYV3_FP8_SOURCE));
|
||||
m.mw.edn = decl_b(b, nm.f("moe_down"), RAD_BF16, {S, g.n_embd});
|
||||
m.mw.moe = decl_b(b, nm.f("moe_routed"), RAD_BF16, {T, g.n_embd});
|
||||
m.mw.sgu = decl_b(b, nm.f("shared_gate_up"), RAD_BF16, {T, 2 * mc.n_ff_shared});
|
||||
m.mw.sff.x = decl_b(b, nm.f("shared_ffn"), RAD_BF16, {T, mc.n_ff_shared});
|
||||
RAD_ARCH_TRY(m.mw.sff.declare_qs(b, nm, g, "shared_ffn", mc.n_ff_shared, 0,
|
||||
!HYV3_FP8_SOURCE));
|
||||
m.mw.sout = decl_b(b, nm.f("shared_out"), RAD_BF16, {T, g.n_embd});
|
||||
m.mw.sgate = decl_b(b, nm.f("shared_one"), RAD_BF16, {T, 1});
|
||||
if (mc.shared_one_external) {
|
||||
m.shared_one = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 1),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
|
||||
RAD_NOWEIGHTS), {}, {m.mw.sgate});
|
||||
if (!m.shared_one) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- Token embedding and head. */
|
||||
#if HYV3_GGUF_SOURCE
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("token_embd.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("output_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("output.weight"),
|
||||
nm.ckpt("token_embd.weight")));
|
||||
#else
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.embed_tokens.weight")));
|
||||
#endif
|
||||
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.final_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.token)),
|
||||
{}, {m.x});
|
||||
if (g.world > 1)
|
||||
m.embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.x}, {m.x});
|
||||
|
||||
AttnQKFP8::Wire aw{};
|
||||
aw.x = m.x; aw.h = m.h; aw.q = m.q; aw.k = m.k; aw.v = m.v; aw.attn = m.attn;
|
||||
MlpFP8::Wire dw{};
|
||||
dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn;
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.dense = (l == 0);
|
||||
#if HYV3_GGUF_SOURCE
|
||||
const char* pre = nm.ckpt("blk.%lld", (long long)l);
|
||||
#else
|
||||
const char* pre = nm.ckpt("model.layers.%lld", (long long)l);
|
||||
#endif
|
||||
AttnQKFP8::Src as{};
|
||||
#if HYV3_GGUF_SOURCE
|
||||
as.norm = nm.ckpt("%s.attn_norm.weight", pre);
|
||||
as.q = nm.ckpt("%s.attn_q.weight", pre);
|
||||
as.k = nm.ckpt("%s.attn_k.weight", pre);
|
||||
as.v = nm.ckpt("%s.attn_v.weight", pre);
|
||||
as.q_norm = nm.ckpt("%s.attn_q_norm.weight", pre);
|
||||
as.k_norm = nm.ckpt("%s.attn_k_norm.weight", pre);
|
||||
as.o = nm.ckpt("%s.attn_output.weight", pre);
|
||||
#else
|
||||
as.norm = nm.ckpt("%s.input_layernorm.weight", pre);
|
||||
as.q = nm.ckpt("%s.self_attn.q_proj.weight", pre);
|
||||
as.k = nm.ckpt("%s.self_attn.k_proj.weight", pre);
|
||||
as.v = nm.ckpt("%s.self_attn.v_proj.weight", pre);
|
||||
as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre);
|
||||
as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre);
|
||||
as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre);
|
||||
#endif
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
|
||||
// Each norm folds its predecessor's residual add. The first attention reads the
|
||||
// embedding directly; the final feed-forward keeps its add for the plain output norm.
|
||||
// Keep collective placement and both routed/shared BF16 rounding points.
|
||||
status = lay.attn.declare(b, nm, g, (int)l, m.kv_full, aw, as, l > 0, false);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: hyv3: attention layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{};
|
||||
#if HYV3_GGUF_SOURCE
|
||||
ds.norm = nm.ckpt("%s.ffn_norm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.ffn_gate.weight", pre);
|
||||
ds.up = nm.ckpt("%s.ffn_up.weight", pre);
|
||||
ds.down = nm.ckpt("%s.ffn_down.weight", pre);
|
||||
#else
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ds.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.gate_proj.weight", mlp);
|
||||
ds.up = nm.ckpt("%s.up_proj.weight", mlp);
|
||||
ds.down = nm.ckpt("%s.down_proj.weight", mlp);
|
||||
#endif
|
||||
status = lay.dense_mlp.declare(b, nm, g, (int)l, dw, ds, true,
|
||||
l + 1 == g.n_layer);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: hyv3: dense MLP declaration failed (%d)\n", status);
|
||||
return status;
|
||||
}
|
||||
} else {
|
||||
MoeFP8::Src ms{};
|
||||
ms.cfg = mc;
|
||||
#if HYV3_GGUF_SOURCE
|
||||
ms.norm = nm.ckpt("%s.ffn_norm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.ffn_gate_inp.weight", pre);
|
||||
ms.router_bias = nm.ckpt("%s.exp_probs_b", pre);
|
||||
ms.experts_gate = nm.ckpt("%s.ffn_gate_exps.weight", pre);
|
||||
ms.experts_up = nm.ckpt("%s.ffn_up_exps.weight", pre);
|
||||
ms.experts_down = nm.ckpt("%s.ffn_down_exps.weight", pre);
|
||||
ms.shared_mlp_gate = nm.ckpt("%s.ffn_gate_shexp.weight", pre);
|
||||
ms.shared_mlp_up = nm.ckpt("%s.ffn_up_shexp.weight", pre);
|
||||
ms.shared_mlp_down = nm.ckpt("%s.ffn_down_shexp.weight", pre);
|
||||
#else
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.router.gate.weight", mlp);
|
||||
ms.router_bias = nm.ckpt("%s.expert_bias", mlp);
|
||||
ms.experts = nm.ckpt("%s.experts", mlp);
|
||||
ms.shared = nm.ckpt("%s.shared_mlp", mlp);
|
||||
#endif
|
||||
#if !HYV3_FP8_SOURCE
|
||||
status = MoeFP8::probe(b, nm, (int)l, ms, &ms.cfg);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: HYV3: expert format probe failed at layer %lld (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
#endif
|
||||
status = lay.moe.declare(b, nm, g, (int)l, m.mw, ms, true, l + 1 == g.n_layer);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: hyv3: MoE layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m.final_rms = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.final_norm)),
|
||||
{m.x}, {m.h.x});
|
||||
m.gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.h.x}, {m.h_out});
|
||||
m.logits_op = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.lm_head)),
|
||||
{m.h_out}, {m.logits});
|
||||
|
||||
rad_note(b, "HYV3: %lld layers (dense first, then top-%lld/%lld sigmoid MoE), %lld/%lld "
|
||||
"attention/KV heads x %lld; expert width %lld, shared width %lld, router scale %.3f",
|
||||
(long long)g.n_layer, (long long)top_k, (long long)n_expert_all,
|
||||
(long long)g.n_head_all, (long long)g.n_head_kv_all, (long long)g.head_dim,
|
||||
(long long)m.n_ff_expert, (long long)m.n_ff_shared, mc.route_scale);
|
||||
#if HYV3_FP8_SOURCE
|
||||
rad_note(b, "E4M3 per-tensor scales are imported to 128x128 F32 planes; Q/K RMSNorm precedes "
|
||||
"NeoX RoPE and shared/routed outputs combine in FP32");
|
||||
#elif HYV3_GGUF_SOURCE
|
||||
rad_note(b, "GGUF-source HYV3; Q4_K/Q6_K tensors are decoded and recipe-converted to native "
|
||||
"Radiance weights, adding quantization loss to an already-lossy source");
|
||||
#else
|
||||
rad_note(b, "BF16-source HYV3; per-weight recipes may quantize linears or routed experts; "
|
||||
"Q/K RMSNorm precedes NeoX RoPE and shared/routed outputs combine in FP32");
|
||||
#endif
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_slot(c)];
|
||||
RAD_ISSUE(c, m.embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token),
|
||||
brows(m.x, batch->n_tok));
|
||||
if (m.embed_ar)
|
||||
RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.x, batch->n_tok), RAD_NONE);
|
||||
|
||||
// All TP1 ungated gathers read this same ones plane; no per-layer fill or combine launch.
|
||||
if (m.shared_one)
|
||||
RAD_ISSUE_N(c, m.shared_one, batch->n_tok, brows(m.mw.sgate, batch->n_tok));
|
||||
for (Layer& layer : m.layers) {
|
||||
layer.attn.step(c, batch);
|
||||
if (layer.dense) layer.dense_mlp.step(c, batch);
|
||||
else layer.moe.step(c, batch);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.final_rms, brows(m.x, batch->n_tok), RAD_W(m.final_norm),
|
||||
brows(m.h.x, batch->n_tok));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.gather, batch->n_out,
|
||||
brows(m.h.x, batch->n_tok), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.h_out, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.logits_op, batch->n_out,
|
||||
brows(m.h_out, batch->n_out), RAD_W(m.lm_head),
|
||||
brows(m.logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace HYV3_NS
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(HYV3_NS)
|
||||
static const char* const kHyv3ToolTriggers[] = { "<tool_calls>" };
|
||||
static const RadChatFormat kHyv3ChatFormat = {
|
||||
.struct_size = sizeof(RadChatFormat),
|
||||
.name = "hyv3",
|
||||
.reasoning_open = "<think>",
|
||||
.reasoning_close = "</think>",
|
||||
.reasoning_breaks = kHyv3ToolTriggers,
|
||||
.n_reasoning_breaks = 1,
|
||||
.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT,
|
||||
.section_open = "<tool_calls>",
|
||||
.section_close = "</tool_calls>",
|
||||
.name_prefix = "<tool_call>",
|
||||
.name_suffix = "<tool_sep>",
|
||||
.call_end = "</tool_call>",
|
||||
.arg_prefix = "<arg_key>",
|
||||
.arg_name_suffix = "</arg_key>\n",
|
||||
.arg_value_prefix = "<arg_value>",
|
||||
.arg_value_suffix = "</arg_value>",
|
||||
.string_value = RAD_CHAT_VALUE_RAW,
|
||||
.other_value = RAD_CHAT_VALUE_JSON,
|
||||
.triggers = kHyv3ToolTriggers,
|
||||
.n_triggers = 1,
|
||||
.args_form = RAD_CHAT_ARGS_TAGGED,
|
||||
};
|
||||
extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
|
||||
return &kHyv3ChatFormat;
|
||||
}
|
||||
extern "C" const char* rad_arch_id(void) { return "hyv3"; }
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
extern "C" const char* rad_arch_quant(void) { return HYV3_QUANT; }
|
||||
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
|
||||
return HYV3_NS::declare(b, m, c);
|
||||
}
|
||||
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
|
||||
HYV3_NS::step(c, batch);
|
||||
}
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
RAD_PLUGIN_ABI_LAYOUT_EXPORT
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) {
|
||||
static const RadPluginInfo info = {
|
||||
RAD_PLUGIN_ARCH, HYV3_PLUGIN_NAME, "0.2.0",
|
||||
"Tencent Hy-Memory HYV3: Q/K-normalized full attention and sigmoid MoE", ""
|
||||
};
|
||||
return &info;
|
||||
}
|
||||
#endif
|
||||
|
||||
#undef HYV3_NS
|
||||
#undef HYV3_QUANT
|
||||
#undef HYV3_FP8_SOURCE
|
||||
#undef HYV3_PLUGIN_NAME
|
||||
#undef HYV3_GGUF_SOURCE
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hyv3_fp8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hyv3_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_fp8.cpp)
|
||||
@@ -0,0 +1,5 @@
|
||||
#define HYV3_NS hyv3_fp8
|
||||
#define HYV3_QUANT "fp8"
|
||||
#define HYV3_FP8_SOURCE 1
|
||||
#define HYV3_PLUGIN_NAME "hyv3_fp8"
|
||||
#include "../hyv3_common/hyv3_impl.cpp"
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hyv3_gguf LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hyv3_gguf architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_gguf.cpp)
|
||||
@@ -0,0 +1,7 @@
|
||||
#define HYV3_NS hyv3_gguf
|
||||
#define HYV3_QUANT "gguf_ftype_15"
|
||||
#define HYV3_FP8_SOURCE 0
|
||||
#define HYV3_GGUF_SOURCE 1
|
||||
#define HYV3_PLUGIN_NAME "hyv3_gguf"
|
||||
#include "../hyv3_common/hyv3_impl.cpp"
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
+169
-67
@@ -33,10 +33,15 @@
|
||||
*
|
||||
* ============================== WHAT IS QUANTISED ==============================
|
||||
*
|
||||
* One plugin serves bf16 and block-fp8 containers: every linear of the language model, of the
|
||||
* text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16 throughout when the first
|
||||
* DiT projection is plain. txt_in, img_in, the timestep MLP and modulation, the final layer and
|
||||
* the VAE stay bf16.
|
||||
* One plugin serves bf16, block-fp8 and rotated int8 (IQ8R) containers: every linear of the
|
||||
* language model, of the text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16
|
||||
* throughout when the first DiT projection is plain. That projection also says whether the
|
||||
* linears are rotated int8: the activations they read then carry int8 codes in place of the E4M3
|
||||
* pair, written by the rotating twins of the fused ops where a library serves them
|
||||
* (rms_mod_had_quant_i8g for a modulated norm, gate_had_quant_i8g for an attention's output
|
||||
* gate); elsewhere the norm, or the sigmoid and multiply pair, is followed by the rotating
|
||||
* quantiser. txt_in, img_in, the timestep MLP and modulation, the final layer and the VAE stay
|
||||
* bf16.
|
||||
*
|
||||
* ============================== TENSOR PARALLEL ==============================
|
||||
*
|
||||
@@ -73,10 +78,30 @@ enum { kMaxLanes = 8 };
|
||||
static const int kTaps[] = { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 };
|
||||
enum { kNTaps = 12 };
|
||||
|
||||
/* The rebalance a request may ask for (`rebalance`, RAD_GEN_COND_REBALANCE): every tap times a fixed
|
||||
* gain before the text fusion, ComfyUI's ConditioningKrea2Rebalance (nova452) at its defaults --
|
||||
* multiplier 4 times the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1. */
|
||||
static const double kRebalance[] = { 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 };
|
||||
/* The rebalance presets a request may ask for (`rebalance`, RAD_GEN_COND_REBALANCE with the row in
|
||||
* RAD_GEN_COND_REBALANCE_PRESET): every tap times a fixed gain before the text fusion.
|
||||
* legacy ComfyUI's ConditioningKrea2Rebalance (nova452) at its defaults -- multiplier 4 times
|
||||
* the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1, about 9x the taps' RMS.
|
||||
* balanced, detail, subtle
|
||||
* comfyui-krea2-conditioning's presets (huwhitememes) with renormalize on, multiplier 1:
|
||||
* the weights times s = sqrt(sum m_t / sum w_t^2 m_t), m_t the mean square of tap t over
|
||||
* the prompt's rows. The node measures s per prompt; here it is a constant, m_t averaged
|
||||
* over twenty prompts through krea/Krea-2-Turbo's text encoder
|
||||
* (scripts/krea2_rebalance_calib.py), and per prompt s stayed within 1.7 % of it.
|
||||
* A preset row the plugin does not know scales nothing: the plain model. */
|
||||
enum { kNPresets = 4 };
|
||||
static const double kRebalance[kNPresets][kNTaps] = {
|
||||
{ 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 },
|
||||
/* balanced: 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1 at s 0.44109 */
|
||||
{ 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 1.1027, 2.2055, 0.4852,
|
||||
1.7644, 0.44109 },
|
||||
/* detail: 0.8, 0.8, 0.9, 0.9, 1, 1, 1.2, 3, 6, 1.5, 5, 1.2 at s 0.35702 */
|
||||
{ 0.28562, 0.28562, 0.32132, 0.32132, 0.35702, 0.35702, 0.42842, 1.0711, 2.1421, 0.53553,
|
||||
1.7851, 0.42842 },
|
||||
/* subtle: 1, 1, 1, 1, 1, 1, 1, 1.5, 2, 1, 1.5, 1 at s 0.84759 */
|
||||
{ 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 1.2714, 1.6952, 0.84759,
|
||||
1.2714, 0.84759 },
|
||||
};
|
||||
|
||||
static const char* kSysPrompt =
|
||||
"Describe the image by detailing the color, shape, size, texture, quantity, text, spatial "
|
||||
@@ -90,7 +115,7 @@ struct TeLayer {
|
||||
GateQuantFP8 gq{};
|
||||
rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0;
|
||||
rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0;
|
||||
rad_op op_gain = 0; /* the tap's rebalance gain into te.h2 */
|
||||
rad_op op_gain[kNPresets] = {}; /* the tap's rebalance gain into te.h2, a preset each */
|
||||
rad_op op_tap_g = 0; /* the scatter from te.h2, when rebalanced */
|
||||
int tap = -1; /* this layer's output is tap `tap`, or none */
|
||||
};
|
||||
@@ -112,6 +137,9 @@ struct DitLayer {
|
||||
rad_op op_tab = 0; /* the shared modulation plus this block's table, into its columns */
|
||||
LinearFP8 qkv{}, gate{}, o{}, gate_up{}, down{};
|
||||
QuantFP8 q_attn{};
|
||||
/* The two modulated norms' quantisers for a rotated int8 model whose norms are the
|
||||
* unquantised form (Model::norm_i8 false). */
|
||||
QuantFP8 q_n1{}, q_n2{};
|
||||
GateQuantFP8 gq{};
|
||||
rad_op op_n1 = 0, op_n2 = 0, op_qkr = 0, op_attn = 0, op_gq = 0, op_sig = 0;
|
||||
rad_op op_ar1 = 0, op_ar2 = 0;
|
||||
@@ -138,7 +166,7 @@ struct Model {
|
||||
ActFP8 a_th{}, a_tattn{}, a_tffn{};
|
||||
std::vector<TeLayer> te;
|
||||
rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */
|
||||
std::string tap_mul[kNTaps]; /* chan_affine's `mul` for each tap's rebalance gain */
|
||||
std::string tap_mul[kNPresets][kNTaps]; /* chan_affine's `mul` for each preset's tap gain */
|
||||
std::string tap_add; /* chan_affine's `add`: zeros */
|
||||
|
||||
/* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks
|
||||
@@ -169,6 +197,15 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
std::vector<DitLayer> dit;
|
||||
LinearFP8 qkv0{};
|
||||
/* The linears of every network are rotated int8 (IQ8R, or the 128-group int8 before it), read
|
||||
* off qkv0's probe: the activations then carry int8 code pairs with one scale per (token, `g8`
|
||||
* columns) in place of the E4M3 pair. */
|
||||
bool i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
/* Where a library serves the rotating twins, a DiT block's modulated norms write those int8
|
||||
* codes in their own pass (rms_mod_had_quant_i8g: norm_i8) and an attention's output gate
|
||||
* writes the out projection's (gate_had_quant_i8g: gate_i8, and fgate_i8 for the fusion blocks'). */
|
||||
bool norm_i8 = false, gate_i8 = false, fgate_i8 = false;
|
||||
rad_weight w_fn = 0, w_pout = 0, b_pout = 0;
|
||||
rad_op op_fn = 0, op_pout = 0, op_euler = 0;
|
||||
rad_buf b_fz = 0, b_v = 0;
|
||||
@@ -185,7 +222,7 @@ struct Model {
|
||||
std::string inv_std, mean, ones, zeros;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A space-separated list off the container (rad-convert flattens arrays that way). */
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
@@ -261,14 +298,27 @@ static rad_op zc_norm(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_we
|
||||
}
|
||||
|
||||
/* The attention's sigmoid output gate: `gate_quant_fp8` (gate, multiply and the out projection's
|
||||
* quantiser in one pass) over fp8 linears, or `sigmoid` then `mul` over bf16 ones and wherever no
|
||||
* loaded library declares the fused op (the out projection's quantiser then runs on its own).
|
||||
* Rows are (token, head) pairs of `head_dim` columns. Returns the gate op; `sig` is the pair's
|
||||
* sigmoid, written into `g` itself. */
|
||||
* quantiser in one pass) over fp8 linears, rows (token, head) pairs of `head_dim` columns; over
|
||||
* rotated int8 ones (`pair`) its rotating twin `gate_had_quant_i8g`, a token a row, since one
|
||||
* scale covers the codes' group across heads (`fused_i8` says so); or `sigmoid` then `mul` over
|
||||
* bf16 ones and wherever no loaded library declares the fused op (the out projection's quantiser
|
||||
* then runs on its own). Returns the gate op; `sig` is the pair's sigmoid, written into `g`
|
||||
* itself. */
|
||||
static rad_op out_gate(RadBuilder* b, const Geom& g, int64_t rows, int64_t width, rad_buf gate,
|
||||
const ActFP8& attn, rad_op* sig) {
|
||||
const ActFP8& attn, rad_op* sig, bool pair, bool* fused_i8) {
|
||||
const int64_t hd = g.head_dim;
|
||||
if (g.w_bf16 || !rad_op_declared(b, "gate_quant_fp8")) {
|
||||
*fused_i8 = false;
|
||||
if (pair && !g.w_bf16 && attn.q8_fed && attn.q8_rot && rad_op_declared(b, "gate_had_quant_i8g")) {
|
||||
*sig = 0;
|
||||
*fused_i8 = true;
|
||||
return rw(b, RAD_OP(b, "gate_had_quant_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_INT("group", attn.cg()), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ gate, attn.x }, { attn.cq(), attn.cs(), attn.x });
|
||||
}
|
||||
if (g.w_bf16 || pair || !rad_op_declared(b, "gate_quant_fp8")) {
|
||||
*sig = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
@@ -349,14 +399,17 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd, T));
|
||||
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", g.n_embd, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T));
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T));
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, T, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { (int64_t)kTeRows * kNTaps, g.n_embd });
|
||||
m.b_tidx = decl_b(b, nm.f("te.tap_idx"), RAD_I32, { T });
|
||||
|
||||
@@ -390,15 +443,17 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
(int)kGainCh);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int t = 0; t < kNTaps; ++t) {
|
||||
char v[32];
|
||||
std::snprintf(v, sizeof v, "%.9g", kRebalance[t]);
|
||||
m.tap_mul[t].clear();
|
||||
for (int k = 0; k < kGainCh; ++k) {
|
||||
if (k) m.tap_mul[t] += ' ';
|
||||
m.tap_mul[t] += v;
|
||||
for (int p = 0; p < kNPresets; ++p)
|
||||
for (int t = 0; t < kNTaps; ++t) {
|
||||
char v[32];
|
||||
std::snprintf(v, sizeof v, "%.9g", kRebalance[p][t]);
|
||||
std::string& s = m.tap_mul[p][t];
|
||||
s.clear();
|
||||
for (int k = 0; k < kGainCh; ++k) {
|
||||
if (k) s += ' ';
|
||||
s += v;
|
||||
}
|
||||
}
|
||||
}
|
||||
m.tap_add.clear();
|
||||
for (int k = 0; k < kGainCh; ++k) m.tap_add += k ? " 0" : "0";
|
||||
|
||||
@@ -482,14 +537,18 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
L.op_add2 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx);
|
||||
if (L.tap >= 0) {
|
||||
/* f32 arithmetic, rounded once into bf16 (`round` 0) */
|
||||
L.op_gain = rw(b, RAD_OP(b, "chan_affine",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", kGainCh),
|
||||
RAD_STR("mul", m.tap_mul[L.tap].c_str()),
|
||||
RAD_STR("add", m.tap_add.c_str()),
|
||||
RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("round", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_tx }, { m.b_th2 });
|
||||
for (int p = 0; p < kNPresets; ++p) {
|
||||
L.op_gain[p] = rw(b, RAD_OP(b, "chan_affine",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows),
|
||||
RAD_INT("n", kGainCh),
|
||||
RAD_STR("mul", m.tap_mul[p][L.tap].c_str()),
|
||||
RAD_STR("add", m.tap_add.c_str()),
|
||||
RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("round", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_tx }, { m.b_th2 });
|
||||
if (!L.op_gain[p]) return RAD_E_INVAL;
|
||||
}
|
||||
L.op_tap_g = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows),
|
||||
RAD_INT("n", g.n_embd), RAD_STR("dtype", "bf16")),
|
||||
@@ -503,7 +562,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_tx, m.b_tidx, m.b_taps }, { m.b_taps });
|
||||
if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2 ||
|
||||
(L.tap >= 0 && (!L.op_tap || !L.op_gain || !L.op_tap_g)))
|
||||
(L.tap >= 0 && (!L.op_tap || !L.op_tap_g)))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return m.op_embed && m.op_iota ? RAD_OK : RAD_E_INVAL;
|
||||
@@ -553,7 +612,7 @@ static int declare_fuse_block(RadBuilder* b, Model& m, FuseBlock& F, const char*
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_fqkv }, { m.a_fattn.x });
|
||||
F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig);
|
||||
F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig, m.i8, &m.fgate_i8);
|
||||
if (F.op_sig) RAD_ARCH_TRY(F.q_attn.declare(b, g, m.a_fattn, qd));
|
||||
RAD_ARCH_TRY(F.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL,
|
||||
grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) },
|
||||
@@ -584,15 +643,35 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const int64_t D = g.n_embd, qd = g.q_dim();
|
||||
const int64_t RL = (int64_t)kCondRows * kNTaps; /* the layer-wise blocks' rows */
|
||||
m.a_fh.x = decl_b(b, nm.f("fuse.h"), RAD_BF16, { RL, D });
|
||||
RAD_ARCH_TRY(m.a_fh.declare_qs(b, nm, g, "fuse.h", D, RL));
|
||||
RAD_ARCH_TRY(m.a_fh.declare_pair(b, nm, g, "fuse.h", D, RL, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_fqkv = decl_b(b, nm.f("fuse.qkv"), RAD_BF16, { RL, 3 * qd });
|
||||
m.b_fg = decl_b(b, nm.f("fuse.gate"), RAD_BF16, { RL, qd });
|
||||
m.a_fattn.x = decl_b(b, nm.f("fuse.attn"), RAD_BF16, { RL, qd });
|
||||
RAD_ARCH_TRY(m.a_fattn.declare_qs(b, nm, g, "fuse.attn", qd, RL));
|
||||
RAD_ARCH_TRY(m.a_fattn.declare_pair(b, nm, g, "fuse.attn", qd, RL, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_fo = decl_b(b, nm.f("fuse.o"), RAD_BF16, { RL, D });
|
||||
m.b_fgu = decl_b(b, nm.f("fuse.gate_up"), RAD_BF16, { RL, 2 * g.n_ff });
|
||||
m.a_fffn.x = decl_b(b, nm.f("fuse.ffn"), RAD_BF16, { RL, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_fffn.declare_qs(b, nm, g, "fuse.ffn", g.n_ff, RL));
|
||||
/* The feed-forward product's scale group is its reader's, the first block's down projection,
|
||||
* which a recipe may keep narrower than the other linears: the fusion's 6912-wide product is
|
||||
* 3456 a rank at two, which whole 128s tile and whole 256s do not (krea-2-iq8r.recipe). The
|
||||
* probe maps the weight through the block's own LinearFP8, which then does not map it again;
|
||||
* the resizes here keep the blocks the loops below declare. */
|
||||
const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2);
|
||||
const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2);
|
||||
m.lw.resize((size_t)nlw);
|
||||
m.rf.resize((size_t)nrf);
|
||||
int64_t ffn_g8 = m.g8;
|
||||
if (m.i8 && nlw + nrf > 0) {
|
||||
LinearFP8& d0 = nlw > 0 ? m.lw[0].down : m.rf[0].down;
|
||||
RAD_ARCH_TRY(d0.probe(b, nm, g, nm.f("fuse.0.ffn_down"),
|
||||
{ nm.ckpt("transformer.text_fusion.%s.0.ff.down.weight",
|
||||
nlw > 0 ? "layerwise_blocks" : "refiner_blocks") }));
|
||||
ffn_g8 = d0.probed_g8;
|
||||
}
|
||||
RAD_ARCH_TRY(m.a_fffn.declare_pair(b, nm, g, "fuse.ffn", g.n_ff, RL, m.i8, ffn_g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_fcu = decl_b(b, nm.f("fuse.cu"), RAD_I32, { kCondRows + 1 });
|
||||
m.b_ft = decl_b(b, nm.f("fuse.out"), RAD_BF16, { kCondRows, D });
|
||||
|
||||
@@ -602,10 +681,6 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_INT("step", kNTaps)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { m.b_fcu });
|
||||
const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2);
|
||||
const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2);
|
||||
m.lw.resize((size_t)nlw);
|
||||
m.rf.resize((size_t)nrf);
|
||||
for (int i = 0; i < nlw; ++i) {
|
||||
RAD_ARCH_TRY(declare_fuse_block(b, m, m.lw[(size_t)i],
|
||||
nm.f("transformer.text_fusion.layerwise_blocks.%d", i),
|
||||
@@ -619,7 +694,7 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
* served bf16 as diffusers runs them: a recipe casts them. */
|
||||
if (weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16) != RAD_BF16) {
|
||||
fprintf(stderr, "radiance: krea2: 'fuse.mix.weight' is stored %s; convert with "
|
||||
"data/recipes/krea-2-bf16.recipe or krea-2-fp8.recipe, which cast the "
|
||||
"data/recipes/krea-2-bf16.recipe or krea-2-iq8r.recipe, which cast the "
|
||||
"release's f32 tensors\n",
|
||||
rad_dtype_name(weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16)));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -763,15 +838,18 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
/* ---- the blocks */
|
||||
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
|
||||
RAD_ARCH_TRY(m.a_hm.declare_pair(b, nm, g, "dit.hm", D, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, qd + 2 * kvd });
|
||||
m.b_g = decl_b(b, nm.f("dit.gate"), RAD_BF16, { T, qd });
|
||||
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_pair(b, nm, g, "dit.attn", qd, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D });
|
||||
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_pair(b, nm, g, "dit.ffn", g.n_ff, 0, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
|
||||
const std::vector<double> ax = meta_list(meta, "transformer.axes_dims_rope");
|
||||
const int64_t a0 = ax.size() == 3 ? (int64_t)ax[0] : 32, a1 = ax.size() == 3 ? (int64_t)ax[1] : 48,
|
||||
@@ -785,12 +863,15 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const double theta = rad_meta_getf(meta, "transformer.rope_theta", 1000.0);
|
||||
|
||||
/* The modulated norm, gated by the branch before it when `gated`, into the next linear's
|
||||
* input (codes for fp8, the bf16 plane for bf16). */
|
||||
* input: codes for fp8 and, where the rotating twin is served, for rotated int8; the bf16
|
||||
* plane for bf16 and for rotated int8 without the twin, whose codes the rotating quantiser
|
||||
* then takes from it (DitLayer::q_n1 / q_n2). */
|
||||
m.norm_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "rms_mod_had_quant_i8g") != 0;
|
||||
auto mod_norm = [&](rad_weight w, bool gated) {
|
||||
const bool q = !g.w_bf16;
|
||||
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
|
||||
const bool q = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
rad_op op = q ? RAD_OP(b, m.norm_i8 ? "rms_mod_had_quant_i8g" : "rms_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("group", m.norm_i8 ? m.g8 : RAD_FP8_BLOCK),
|
||||
RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)),
|
||||
RAD_WEIGHTS(w))
|
||||
@@ -801,7 +882,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_WEIGHTS(w));
|
||||
if (!op) return op;
|
||||
rad_buf rd[3] = { m.b_mods, m.b_h, m.b_ao };
|
||||
rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h };
|
||||
rad_buf wq[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h };
|
||||
rad_buf wb[2] = { m.a_hm.x, m.b_h };
|
||||
rad_op_reads(b, op, rd, gated ? 3 : 2);
|
||||
if (q) rad_op_writes(b, op, wq, 3);
|
||||
@@ -840,6 +921,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
if (!B.w_tab || !B.op_tab) return RAD_E_INVAL;
|
||||
}
|
||||
B.op_n1 = mod_norm(B.w_n1, l > 0);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n1.declare(b, g, m.a_hm, D));
|
||||
if (l == 0) B.qkv = m.qkv0;
|
||||
RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), qd + 2 * kvd, D,
|
||||
RAD_SHARD_ROW, grp_layer(grp),
|
||||
@@ -867,13 +949,14 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_qkv }, { m.a_attn.x });
|
||||
B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig);
|
||||
B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig, m.i8, &m.gate_i8);
|
||||
if (B.op_sig) RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd));
|
||||
RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL,
|
||||
grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) },
|
||||
m.a_attn, m.b_ao));
|
||||
B.op_ar1 = all_reduce(b, g, m.b_ao, T);
|
||||
B.op_n2 = mod_norm(B.w_n2, true);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n2.declare(b, g, m.a_hm, D));
|
||||
RAD_ARCH_TRY(B.gate_up.declare(b, nm, g, nm.f("%s.ffn_gate_up", dn), 2 * g.n_ff, D,
|
||||
RAD_SHARD_ROW, grp_layer(grp),
|
||||
{ nm.ckpt("%s.ff.gate.weight", pre),
|
||||
@@ -1064,8 +1147,9 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -1124,9 +1208,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.transformer_blocks.0.attn.to_k.weight",
|
||||
"transformer.transformer_blocks.0.attn.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
const bool known = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e);
|
||||
const bool plain = known && rad_enc_is(&e, "plain");
|
||||
gd.w_bf16 = gf.w_bf16 = m.gt.w_bf16 = plain;
|
||||
/* Or rotated int8 (IQ8R): the activations then carry int8 codes at the weights' scale
|
||||
* group in place of the E4M3 pair (ActFP8::declare_pair). */
|
||||
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
|
||||
if (m.i8) m.g8 = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
/* ---- the per-image state, the conditioning store, and in issue order the language model,
|
||||
@@ -1186,7 +1274,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.cond_rows = kCondRows;
|
||||
d.rope_hw_scale = 1.0;
|
||||
d.rope_text_l = 0;
|
||||
d.cond_opts = RAD_GEN_COND_REBALANCE;
|
||||
d.cond_opts = RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET;
|
||||
RAD_ARCH_TRY(rad_declare_generator(b, &d));
|
||||
}
|
||||
rad_note(b, "rank %d/%d: Krea 2%s -- text encoder %d of %lld layers, text fusion %zu + %zu "
|
||||
@@ -1194,7 +1282,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.gt.rank, m.gt.world, m.turbo ? " Turbo" : "", kTaps[kNTaps - 1],
|
||||
(long long)m.gt.n_layer, m.lw.size(), m.rf.size(), (long long)gd.n_layer,
|
||||
(long long)gd.n_head, (long long)gd.n_head_kv, (long long)gd.n_ff,
|
||||
gd.w_bf16 ? "bf16" : "block-fp8");
|
||||
gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1205,7 +1293,9 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const Geom& g = m.gt;
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
const bool rebalance = batch->gen_b && (batch->gen_b->cond_opts & RAD_GEN_COND_REBALANCE);
|
||||
const int32_t opts = batch->gen_b ? batch->gen_b->cond_opts : 0;
|
||||
const int preset = (opts & RAD_GEN_COND_REBALANCE_PRESET) >> RAD_GEN_COND_REBALANCE_PRESET_SHIFT;
|
||||
const bool rebalance = (opts & RAD_GEN_COND_REBALANCE) && preset < kNPresets;
|
||||
RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok),
|
||||
brows(m.b_tx, T));
|
||||
RAD_ISSUE_N(c, m.op_iota, T, brows(m.b_tidx, T));
|
||||
@@ -1230,7 +1320,7 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T));
|
||||
if (L.tap >= 0 && rebalance)
|
||||
RAD_ISSUE_N(c, L.op_gain, T, brows(m.b_tx, T), brows(m.b_th2, T));
|
||||
RAD_ISSUE_N(c, L.op_gain[preset], T, brows(m.b_tx, T), brows(m.b_th2, T));
|
||||
if (L.tap >= 0)
|
||||
RAD_ISSUE_N(c, rebalance ? L.op_tap_g : L.op_tap, T,
|
||||
brows(rebalance ? m.b_th2 : m.b_tx, T), brows(m.b_tidx, T),
|
||||
@@ -1256,6 +1346,9 @@ static void step_fuse(RadCtx* c, const Model& m, const FuseBlock& F, int64_t r0,
|
||||
RAD_ISSUE_N(c, F.op_sig, R, brows(m.b_fg, R), brows(m.b_fg, R));
|
||||
RAD_ISSUE_N(c, F.op_gq, R, brows(m.a_fattn.x, R), brows(m.b_fg, R), brows(m.a_fattn.x, R));
|
||||
F.q_attn.step(c, R);
|
||||
} else if (m.fgate_i8) {
|
||||
RAD_ISSUE_N(c, F.op_gq, R, brows(m.b_fg, R), brows(m.a_fattn.x, R),
|
||||
brows(m.a_fattn.cq(), R), brows(m.a_fattn.cs(), R), brows(m.a_fattn.x, R));
|
||||
} else {
|
||||
const int64_t rh = R * (qd / hd), nb = hd / RAD_FP8_BLOCK;
|
||||
RAD_ISSUE_N(c, F.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_fg), RAD_BF16, rh, hd),
|
||||
@@ -1340,7 +1433,7 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadOperand pos = praw2(G->rope_f, RAD_F32, 4, N);
|
||||
auto mod = [&](int64_t l, int k, int width) { return bcol_at(m.b_mods, 0, W, (6 * l + k) * D,
|
||||
width * D, S); };
|
||||
const bool q8 = !g.w_bf16;
|
||||
const bool q8 = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
const DitLayer& B = m.dit[(size_t)l];
|
||||
/* The block's modulation: the shared projection plus its own table, into its columns. */
|
||||
@@ -1349,11 +1442,13 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE,
|
||||
l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu,
|
||||
brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE);
|
||||
brows(m.b_h, N), brows(m.a_hm.cq(), N), brows(m.a_hm.cs(), N),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE,
|
||||
l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu,
|
||||
brows(m.b_h, N), brows(m.a_hm.x, N));
|
||||
B.q_n1.step(c, N);
|
||||
B.qkv.step(c, m.a_hm, m.b_qkv, N);
|
||||
B.gate.step(c, m.a_hm, m.b_g, N);
|
||||
RAD_ISSUE_N(c, B.op_qkr, N, brows(m.b_qkv, N), pos, RAD_W(B.w_qn), RAD_W(B.w_kn));
|
||||
@@ -1363,6 +1458,9 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
RAD_ISSUE_N(c, B.op_sig, N, brows(m.b_g, N), brows(m.b_g, N));
|
||||
RAD_ISSUE_N(c, B.op_gq, N, brows(m.a_attn.x, N), brows(m.b_g, N), brows(m.a_attn.x, N));
|
||||
B.q_attn.step(c, N);
|
||||
} else if (m.gate_i8) {
|
||||
RAD_ISSUE_N(c, B.op_gq, N, brows(m.b_g, N), brows(m.a_attn.x, N),
|
||||
brows(m.a_attn.cq(), N), brows(m.a_attn.cs(), N), brows(m.a_attn.x, N));
|
||||
} else {
|
||||
const int64_t rh = N * (qd / hd), nb = hd / RAD_FP8_BLOCK;
|
||||
RAD_ISSUE_N(c, B.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_g), RAD_BF16, rh, hd),
|
||||
@@ -1375,10 +1473,12 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
if (B.op_ar1) RAD_ISSUE_N(c, B.op_ar1, N * D, brows(m.b_ao, N), RAD_NONE);
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2),
|
||||
cu, brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE);
|
||||
cu, brows(m.b_h, N), brows(m.a_hm.cq(), N), brows(m.a_hm.cs(), N),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2),
|
||||
cu, brows(m.b_h, N), brows(m.a_hm.x, N));
|
||||
B.q_n2.step(c, N);
|
||||
B.gate_up.step(c, m.a_hm, m.b_gu, N);
|
||||
B.gq.step(c, m.b_gu, N);
|
||||
B.down.step(c, m.a_ffn, m.b_ao, N);
|
||||
@@ -1439,7 +1539,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "krea2 is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1465,6 +1565,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(krea2)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(krea2, "krea2", "", "0.1.0",
|
||||
"Krea 2 / Krea 2 Turbo: Qwen3-VL-4B taps through a text-fusion transformer, a 12.9B "
|
||||
"single-stream diffusion transformer over the joint text and image, and Wan 2.1's "
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/laya -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(laya LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(laya architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/laya.cpp)
|
||||
@@ -0,0 +1,533 @@
|
||||
/* laya -- Convai Innovations' Laya decision models (laya, laya-typed-decisions,
|
||||
* laya-multilingual), served on /v1/systemone. bf16 weights and activations, f32 norms and biases.
|
||||
*
|
||||
* A Laya checkpoint is a ModernBERT encoder and a small decision head (DecisionModel in laya's
|
||||
* common.py). It reads one sequence a question,
|
||||
* [CLS] <type> question: <instructions> [SEP] [MASK] opt0 [MASK] opt1 ... [SEP] <state> [SEP]
|
||||
* which the server builds (core/server/laya.cpp), and scores each option at its [MASK]. Like
|
||||
* nomicbert it declares a pooled output and no logits, so the engine runs it with no sampler and
|
||||
* no KV cache, every sequence whole in one step, and returns each sequence's pooled row: here one
|
||||
* logit an option (abi/rad_laya.h). The request's words carry what the tokens do not: the
|
||||
* question's type and where its markers sit.
|
||||
*
|
||||
* ============================== THE SHAPE ==============================
|
||||
*
|
||||
* encoder (ModernBERT): token embedding, then LayerNorm; every norm has no bias, no linear has one
|
||||
* h += Wo attn(rope(Wqkv LN_a(h))) no LN_a on layer 0
|
||||
* h += Wo (gelu(Wi_in LN_m(h)) * Wi_gate LN_m(h)) Wi is one [2 ff, E] tensor, [in | gate]
|
||||
* a final LayerNorm
|
||||
* attention: a `full_attention` layer (layer_types) attends over the whole sequence with the full
|
||||
* rotary theta, the others over |i - j| <= local_attention / 2 with the sliding one; NeoX rotary
|
||||
* over the whole head, scale 1 / sqrt(head_dim)
|
||||
* head: h + type_emb[type]; head_layers pre-norm transformer layers (torch's
|
||||
* TransformerEncoderLayer with norm_first: E / 64 heads, a ReLU feed-forward of 4 E, every
|
||||
* linear and norm with a bias); the rows at the markers; LayerNorm, Linear + gelu, Linear to
|
||||
* one logit an option
|
||||
*
|
||||
* The release's escalation head (act_head) and its stored temperatures are not declared: the
|
||||
* answer is the option logits, and the server applies the fitted temperatures rad-convert writes
|
||||
* into the header from rl_agent_config.json.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <rad_laya.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace laya {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool sliding = false;
|
||||
rad_weight w_attn_norm = 0, w_qkv = 0, w_out = 0, w_mlp_norm = 0, w_wi = 0, w_wo = 0;
|
||||
rad_op op_attn_norm = 0, op_qkv = 0, op_rope = 0, op_attn = 0, op_out = 0, op_add_attn = 0;
|
||||
rad_op op_mlp_norm = 0, op_wi = 0, op_act = 0, op_wo = 0, op_add_mlp = 0;
|
||||
};
|
||||
|
||||
struct HeadLayer {
|
||||
rad_weight n1_w = 0, n1_b = 0, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
|
||||
rad_weight n2_w = 0, n2_b = 0, l1_w = 0, l1_b = 0, l2_w = 0, l2_b = 0;
|
||||
rad_op op_n1 = 0, op_qkv = 0, op_attn = 0, op_out = 0, op_n2 = 0, op_l1 = 0, op_relu = 0,
|
||||
op_l2 = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
int64_t F = 0; /* the encoder's feed-forward width */
|
||||
int64_t head_dim_h = 0; /* the head's attention width, E / max(1, E / 64) */
|
||||
|
||||
rad_buf b_o = 0, b_x = 0, b_h = 0, b_t = 0, b_qkv = 0, b_att = 0, b_wi = 0, b_ff = 0,
|
||||
b_hff = 0, b_trow = 0, b_m = 0, b_m2 = 0, b_sc = 0, b_pooled = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_emb_norm = 0, w_final_norm = 0, w_type = 0;
|
||||
rad_weight w_sn = 0, b_sn = 0, w_s1 = 0, b_s1 = 0, w_s2 = 0, b_s2 = 0;
|
||||
rad_op op_embed = 0, op_emb_norm = 0, op_final_norm = 0, op_type = 0, op_add_type = 0;
|
||||
rad_op op_gather = 0, op_sn = 0, op_s1 = 0, op_s2 = 0, op_fill = 0, op_out = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
std::vector<HeadLayer> head;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
const char* dt = rad_meta_gets(meta, "decision.type", nullptr);
|
||||
if (!dt || std::strcmp(dt, "laya")) {
|
||||
fprintf(stderr, "radiance: laya: the container declares no Laya decision head "
|
||||
"(decision.type=laya); convert the checkpoint directory with rad-convert, "
|
||||
"which reads rl_agent_config.json beside it\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Which layers attend over the sliding window: `layer_types` as the config states it, or every
|
||||
* layer but each global_attn_every_n_layers-th in configs written before transformers 5. */
|
||||
static int sliding_layers(const RadModelMeta* meta, int64_t n_layer, std::vector<bool>* out) {
|
||||
out->assign((size_t)n_layer, false);
|
||||
if (const char* lt = rad_meta_gets(meta, "layer_types", nullptr)) {
|
||||
int64_t l = 0;
|
||||
for (const char* p = lt; *p;) {
|
||||
while (*p == ' ') ++p;
|
||||
const char* e = p;
|
||||
while (*e && *e != ' ') ++e;
|
||||
if (e == p) break;
|
||||
const std::string t(p, e);
|
||||
if (l >= n_layer || (t != "full_attention" && t != "sliding_attention")) return RAD_E_INVAL;
|
||||
(*out)[(size_t)l++] = t == "sliding_attention";
|
||||
p = e;
|
||||
}
|
||||
return l == n_layer ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
const int64_t every = rad_meta_geti(meta, "global_attn_every_n_layers", 0);
|
||||
if (every <= 0) return RAD_E_INVAL;
|
||||
for (int64_t l = 0; l < n_layer; ++l) (*out)[(size_t)l] = l % every != 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: laya runs on one card (--tp 1); the largest checkpoint is "
|
||||
"0.4B parameters\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RadArchProbe pr{};
|
||||
RAD_ARCH_TRY(probe(meta, &pr));
|
||||
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
const int64_t T = g.max_tok, E = g.n_embd, S = g.max_seqs, P = RAD_LAYA_POOLED;
|
||||
m.F = g.n_ff;
|
||||
const int64_t F = m.F;
|
||||
|
||||
/* The variant flags this plugin does not serve, refused by name. */
|
||||
for (const char* k : { "norm_bias", "attention_bias", "mlp_bias" })
|
||||
if (rad_meta_geti(meta, k, 0) != 0) {
|
||||
fprintf(stderr, "radiance: laya: the encoder sets %s; ModernBERT as Laya ships it has "
|
||||
"no bias there\n", k);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* act = rad_meta_gets(meta, "hidden_activation", "gelu");
|
||||
if (std::strcmp(act, "gelu")) {
|
||||
fprintf(stderr, "radiance: laya: hidden_activation '%s'; this plugin serves exact gelu\n", act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (g.n_head_kv != g.n_head || g.head_dim * g.n_head != E) {
|
||||
fprintf(stderr, "radiance: laya: %lld heads of %lld (%lld for keys) do not tile hidden %lld\n",
|
||||
(long long)g.n_head, (long long)g.head_dim, (long long)g.n_head_kv, (long long)E);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::vector<bool> sliding;
|
||||
if (sliding_layers(meta, g.n_layer, &sliding) != RAD_OK) {
|
||||
fprintf(stderr, "radiance: laya: neither layer_types (%lld entries of full_attention or "
|
||||
"sliding_attention) nor global_attn_every_n_layers says which layers "
|
||||
"attend locally\n", (long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t local = rad_meta_geti(meta, "local_attention", 128);
|
||||
/* transformers masks the local layers to |i - j| <= local_attention / 2; attn_dense's window
|
||||
* keeps |i - j| < window. */
|
||||
const int64_t window = local / 2 + 1;
|
||||
const double theta_full = rad_meta_getf(meta, "rope_parameters.full_attention.rope_theta",
|
||||
rad_meta_getf(meta, "global_rope_theta", 160000.0));
|
||||
const double theta_slide = rad_meta_getf(meta, "rope_parameters.sliding_attention.rope_theta",
|
||||
rad_meta_getf(meta, "local_rope_theta", 10000.0));
|
||||
const int64_t n_head_layers = rad_meta_geti(meta, "decision.laya.head_layers", -1);
|
||||
if (local < 2 || !(theta_full > 0.0) || !(theta_slide > 0.0) || n_head_layers < 0) {
|
||||
fprintf(stderr, "radiance: laya: local_attention %lld, rotary thetas %g and %g, or "
|
||||
"decision.laya.head_layers %lld is not a Laya model\n", (long long)local,
|
||||
theta_full, theta_slide, (long long)n_head_layers);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* torch's MultiheadAttention in the head: E / 64 heads, at least one. */
|
||||
const int64_t hh = std::max<int64_t>(1, E / 64);
|
||||
m.head_dim_h = E / hh;
|
||||
if (m.head_dim_h * hh != E) {
|
||||
fprintf(stderr, "radiance: laya: hidden %lld does not split into %lld head heads\n",
|
||||
(long long)E, (long long)hh);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_plugin_words(b, RAD_LAYA_MAX_WORDS));
|
||||
|
||||
/* ---- activations. b_sc is P rows longer than any step's markers: the last sequence's pooled
|
||||
* row is copied from P scores, its own and then filler. */
|
||||
m.b_o = decl_b(b, nm.f("o"), RAD_BF16, { T, E });
|
||||
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, { T, E });
|
||||
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, { T, E });
|
||||
m.b_t = decl_b(b, nm.f("t"), RAD_BF16, { T, E });
|
||||
m.b_qkv = decl_b(b, nm.f("qkv"), RAD_BF16, { T, 3 * E });
|
||||
m.b_att = decl_b(b, nm.f("attn"), RAD_BF16, { T, E });
|
||||
m.b_wi = decl_b(b, nm.f("wi"), RAD_BF16, { T, 2 * F });
|
||||
m.b_ff = decl_b(b, nm.f("ff"), RAD_BF16, { T, F });
|
||||
m.b_hff = decl_b(b, nm.f("hff"), RAD_BF16, { T, 4 * E });
|
||||
m.b_trow = decl_b(b, nm.f("type"), RAD_BF16, { S, E });
|
||||
m.b_m = decl_b(b, nm.f("mark"), RAD_BF16, { T, E });
|
||||
m.b_m2 = decl_b(b, nm.f("mark2"), RAD_BF16, { T, E });
|
||||
m.b_sc = decl_b(b, nm.f("score"), RAD_BF16, { T + P, 1 });
|
||||
m.b_pooled = decl_b(b, nm.f("pooled"), RAD_F32, { S, P }, RAD_BUF_PERSIST);
|
||||
if (!m.b_o || !m.b_x || !m.b_h || !m.b_t || !m.b_qkv || !m.b_att || !m.b_wi || !m.b_ff ||
|
||||
!m.b_hff || !m.b_trow || !m.b_m || !m.b_m2 || !m.b_sc || !m.b_pooled)
|
||||
return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_declare_pooled(b, m.b_pooled));
|
||||
|
||||
/* ---- weights. Linears and tables bf16, norms and biases f32. */
|
||||
const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE;
|
||||
auto w_model = [&](const char* name, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shape, int access = RAD_ACCESS_PER_TOKEN) {
|
||||
if (map_copy(b, nm.f("%s", name), nm.ckpt("%s", src)) != RAD_OK) return (rad_weight)0;
|
||||
return decl_w(b, nm.f("%s", name), dt, shape, access, N, grp_model());
|
||||
};
|
||||
m.w_tok = w_model("token_embd.weight", "encoder.embeddings.tok_embeddings.weight",
|
||||
RAD_BF16, { g.n_vocab, E }, RAD_ACCESS_VOCAB);
|
||||
m.w_emb_norm = w_model("emb_norm.weight", "encoder.embeddings.norm.weight", RAD_F32, { E });
|
||||
m.w_final_norm = w_model("output_norm.weight", "encoder.final_norm.weight", RAD_F32, { E });
|
||||
m.w_type = w_model("type_emb.weight", "type_emb.weight", RAD_BF16, { 3, E });
|
||||
m.w_sn = w_model("scorer.norm.weight", "scorer.0.weight", RAD_F32, { E });
|
||||
m.b_sn = w_model("scorer.norm.bias", "scorer.0.bias", RAD_F32, { E });
|
||||
m.w_s1 = w_model("scorer.fc1.weight", "scorer.1.weight", RAD_BF16, { E, E });
|
||||
m.b_s1 = w_model("scorer.fc1.bias", "scorer.1.bias", RAD_F32, { E });
|
||||
m.w_s2 = w_model("scorer.fc2.weight", "scorer.3.weight", RAD_BF16, { 1, E });
|
||||
m.b_s2 = w_model("scorer.fc2.bias", "scorer.3.bias", RAD_F32, { 1 });
|
||||
if (!m.w_tok || !m.w_emb_norm || !m.w_final_norm || !m.w_type || !m.w_sn || !m.b_sn ||
|
||||
!m.w_s1 || !m.b_s1 || !m.w_s2 || !m.b_s2)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- ops, each kind stated once. */
|
||||
auto lnorm = [&](int64_t rows, bool bias, rad_weight w, rad_weight bw) {
|
||||
return bias ? RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bw))
|
||||
: RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t n_out, int64_t n_in, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n_out), RAD_INT("K", n_in),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gemmb = [&](int64_t rows, int64_t n_out, int64_t n_in, const char* act_name, rad_weight w,
|
||||
rad_weight bw) {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n_out), RAD_INT("K", n_in),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", act_name)),
|
||||
RAD_WEIGHTS(w, bw));
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto attn = [&](int64_t head_dim, double scale, int64_t win) {
|
||||
return win > 0 ? RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("scale", scale),
|
||||
RAD_INT("max_seqlen", T), RAD_INT("window", win)),
|
||||
RAD_NOWEIGHTS)
|
||||
: RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("scale", scale),
|
||||
RAD_INT("max_seqlen", T)),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto rope = [&](double theta) {
|
||||
return RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", theta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, { m.b_o });
|
||||
m.op_emb_norm = rw(b, lnorm(T, false, m.w_emb_norm, 0), { m.b_o }, { m.b_x });
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& y = m.layers[(size_t)l];
|
||||
y.sliding = sliding[(size_t)l];
|
||||
const long long ll = (long long)l;
|
||||
const RadWeightGroup gl = grp_layer((int)l);
|
||||
auto src = [&](const char* s) { return nm.ckpt("encoder.layers.%lld.%s", ll, s); };
|
||||
if (l > 0) RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), src("attn_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_qkv.weight", ll), src("attn.Wqkv.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_out.weight", ll), src("attn.Wo.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm.weight", ll), src("mlp_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_in_gate.weight", ll), src("mlp.Wi.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_down.weight", ll), src("mlp.Wo.weight")));
|
||||
if (l > 0)
|
||||
y.w_attn_norm = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, { E }, A, N, gl);
|
||||
y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16, { 3 * E, E }, A, N, gl);
|
||||
y.w_out = decl_w(b, nm.f("blk.%lld.attn_out.weight", ll), RAD_BF16, { E, E }, A, N, gl);
|
||||
y.w_mlp_norm = decl_w(b, nm.f("blk.%lld.ffn_norm.weight", ll), RAD_F32, { E }, A, N, gl);
|
||||
y.w_wi = decl_w(b, nm.f("blk.%lld.ffn_in_gate.weight", ll), RAD_BF16, { 2 * F, E }, A, N, gl);
|
||||
y.w_wo = decl_w(b, nm.f("blk.%lld.ffn_down.weight", ll), RAD_BF16, { E, F }, A, N, gl);
|
||||
if ((l > 0 && !y.w_attn_norm) || !y.w_qkv || !y.w_out || !y.w_mlp_norm || !y.w_wi || !y.w_wo)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
const rad_buf att_in = l > 0 ? m.b_h : m.b_x;
|
||||
if (l > 0) y.op_attn_norm = rw(b, lnorm(T, false, y.w_attn_norm, 0), { m.b_x }, { m.b_h });
|
||||
y.op_qkv = rw(b, gemm(T, 3 * E, E, y.w_qkv), { att_in }, { m.b_qkv });
|
||||
y.op_rope = rw(b, rope(y.sliding ? theta_slide : theta_full), { m.b_qkv }, { m.b_qkv });
|
||||
y.op_attn = rw(b, attn(g.head_dim, 1.0 / std::sqrt((double)g.head_dim), y.sliding ? window : 0),
|
||||
{ m.b_qkv }, { m.b_att });
|
||||
y.op_out = rw(b, gemm(T, E, E, y.w_out), { m.b_att }, { m.b_o });
|
||||
y.op_add_attn = rw(b, unary("add", T, E), { m.b_x, m.b_o }, { m.b_x });
|
||||
y.op_mlp_norm = rw(b, lnorm(T, false, y.w_mlp_norm, 0), { m.b_x }, { m.b_h });
|
||||
y.op_wi = rw(b, gemm(T, 2 * F, E, y.w_wi), { m.b_h }, { m.b_wi });
|
||||
y.op_act = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F),
|
||||
RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_wi }, { m.b_ff });
|
||||
y.op_wo = rw(b, gemm(T, E, F, y.w_wo), { m.b_ff }, { m.b_o });
|
||||
y.op_add_mlp = rw(b, unary("add", T, E), { m.b_x, m.b_o }, { m.b_x });
|
||||
if ((l > 0 && !y.op_attn_norm) || !y.op_qkv || !y.op_rope || !y.op_attn || !y.op_out ||
|
||||
!y.op_add_attn || !y.op_mlp_norm || !y.op_wi || !y.op_act || !y.op_wo || !y.op_add_mlp)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
m.op_final_norm = rw(b, lnorm(T, false, m.w_final_norm, 0), { m.b_x }, { m.b_h });
|
||||
|
||||
/* ---- the head, over the encoder's rows in b_h. */
|
||||
m.op_type = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n_embd", E), RAD_INT("n_vocab", 3),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("vocab_offset", 0)),
|
||||
RAD_WEIGHTS(m.w_type)),
|
||||
{}, { m.b_trow });
|
||||
m.op_add_type = rw(b, unary("add", T, E), { m.b_h, m.b_trow }, { m.b_h });
|
||||
m.head.resize((size_t)n_head_layers);
|
||||
for (int64_t j = 0; j < n_head_layers; ++j) {
|
||||
HeadLayer& h = m.head[(size_t)j];
|
||||
const long long jj = (long long)j;
|
||||
auto hw = [&](const char* name, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shape) {
|
||||
if (map_copy(b, nm.f("head.%lld.%s", jj, name), nm.ckpt("head.layers.%lld.%s", jj, src)) != RAD_OK)
|
||||
return (rad_weight)0;
|
||||
return decl_w(b, nm.f("head.%lld.%s", jj, name), dt, shape, A, N, grp_model());
|
||||
};
|
||||
h.n1_w = hw("norm1.weight", "norm1.weight", RAD_F32, { E });
|
||||
h.n1_b = hw("norm1.bias", "norm1.bias", RAD_F32, { E });
|
||||
h.qkv_w = hw("attn_qkv.weight", "self_attn.in_proj_weight", RAD_BF16, { 3 * E, E });
|
||||
h.qkv_b = hw("attn_qkv.bias", "self_attn.in_proj_bias", RAD_F32, { 3 * E });
|
||||
h.out_w = hw("attn_out.weight", "self_attn.out_proj.weight", RAD_BF16, { E, E });
|
||||
h.out_b = hw("attn_out.bias", "self_attn.out_proj.bias", RAD_F32, { E });
|
||||
h.n2_w = hw("norm2.weight", "norm2.weight", RAD_F32, { E });
|
||||
h.n2_b = hw("norm2.bias", "norm2.bias", RAD_F32, { E });
|
||||
h.l1_w = hw("ffn_up.weight", "linear1.weight", RAD_BF16, { 4 * E, E });
|
||||
h.l1_b = hw("ffn_up.bias", "linear1.bias", RAD_F32, { 4 * E });
|
||||
h.l2_w = hw("ffn_down.weight", "linear2.weight", RAD_BF16, { E, 4 * E });
|
||||
h.l2_b = hw("ffn_down.bias", "linear2.bias", RAD_F32, { E });
|
||||
if (!h.n1_w || !h.n1_b || !h.qkv_w || !h.qkv_b || !h.out_w || !h.out_b || !h.n2_w ||
|
||||
!h.n2_b || !h.l1_w || !h.l1_b || !h.l2_w || !h.l2_b)
|
||||
return RAD_E_INVAL;
|
||||
h.op_n1 = rw(b, lnorm(T, true, h.n1_w, h.n1_b), { m.b_h }, { m.b_t });
|
||||
h.op_qkv = rw(b, gemmb(T, 3 * E, E, "none", h.qkv_w, h.qkv_b), { m.b_t }, { m.b_qkv });
|
||||
h.op_attn = rw(b, attn(m.head_dim_h, 1.0 / std::sqrt((double)m.head_dim_h), 0),
|
||||
{ m.b_qkv }, { m.b_att });
|
||||
h.op_out = rw(b, gemmb(T, E, E, "none", h.out_w, h.out_b), { m.b_att, m.b_h }, { m.b_h });
|
||||
h.op_n2 = rw(b, lnorm(T, true, h.n2_w, h.n2_b), { m.b_h }, { m.b_t });
|
||||
h.op_l1 = rw(b, gemmb(T, 4 * E, E, "none", h.l1_w, h.l1_b), { m.b_t }, { m.b_hff });
|
||||
h.op_relu = rw(b, unary("relu", T, 4 * E), { m.b_hff }, { m.b_hff });
|
||||
h.op_l2 = rw(b, gemmb(T, E, 4 * E, "none", h.l2_w, h.l2_b), { m.b_hff, m.b_h }, { m.b_h });
|
||||
if (!h.op_n1 || !h.op_qkv || !h.op_attn || !h.op_out || !h.op_n2 || !h.op_l1 ||
|
||||
!h.op_relu || !h.op_l2)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The rows at the markers, a sequence at a time, then the scorer over all of them. */
|
||||
m.op_gather = rw(b, unary("gather_rows", RAD_LAYA_MAX_OPTIONS, E), { m.b_h }, { m.b_m });
|
||||
m.op_sn = rw(b, lnorm(T, true, m.w_sn, m.b_sn), { m.b_m }, { m.b_t });
|
||||
m.op_s1 = rw(b, gemmb(T, E, E, "gelu", m.w_s1, m.b_s1), { m.b_t }, { m.b_m2 });
|
||||
m.op_s2 = rw(b, gemmb(T, 1, E, "none", m.w_s2, m.b_s2), { m.b_m2 }, { m.b_sc });
|
||||
/* Past the last marker's score, P filler rows the last pooled row's copy may read. */
|
||||
m.op_fill = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", P),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("value", -1e4)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { m.b_sc });
|
||||
m.op_out = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", P),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_sc }, { m.b_pooled });
|
||||
if (!m.op_embed || !m.op_emb_norm || !m.op_final_norm || !m.op_type || !m.op_add_type ||
|
||||
!m.op_gather || !m.op_sn || !m.op_s1 || !m.op_s2 || !m.op_fill || !m.op_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
int64_t n_sliding = 0;
|
||||
for (bool s : sliding) n_sliding += s ? 1 : 0;
|
||||
rad_note(b, "laya decision model: ModernBERT %lld layers (%lld sliding over %lld, rotary %g "
|
||||
"and %g), hidden %lld, ffn %lld, %lld heads of %lld; head %lld layers of %lld "
|
||||
"heads; at most %d options a question, one logit each in the pooled row",
|
||||
(long long)g.n_layer, (long long)n_sliding, (long long)local, theta_full, theta_slide,
|
||||
(long long)E, (long long)F, (long long)g.n_head, (long long)g.head_dim,
|
||||
(long long)n_head_layers, (long long)hh, (int)RAD_LAYA_MAX_OPTIONS);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd, F = m.F;
|
||||
const int64_t P = RAD_LAYA_POOLED;
|
||||
if (T <= 0 || S <= 0) return;
|
||||
if (!batch->plugin_cu_h || !batch->plugin_words_h || !batch->plugin_words) {
|
||||
rad_step_fail(c, "laya: the step carries no words; every Laya sequence comes from "
|
||||
"/v1/systemone with its question's type and markers");
|
||||
return;
|
||||
}
|
||||
/* Each sequence's first row from the words: an embedding input runs whole in one step, so
|
||||
* the sequences' token counts add up to the step's. */
|
||||
std::vector<int64_t> first((size_t)S + 1, 0);
|
||||
for (int64_t s = 0; s < S; ++s) {
|
||||
const int32_t w0 = batch->plugin_cu_h[s], w1 = batch->plugin_cu_h[s + 1];
|
||||
const int32_t* hw = batch->plugin_words_h + w0;
|
||||
const int64_t n = w1 - w0 > RAD_LAYA_W_K ? hw[RAD_LAYA_W_N] : -1;
|
||||
const int64_t k = w1 - w0 > RAD_LAYA_W_K ? hw[RAD_LAYA_W_K] : -1;
|
||||
const int64_t type = w1 - w0 > RAD_LAYA_W_K ? hw[RAD_LAYA_W_TYPE] : -1;
|
||||
bool ok = n > 0 && k >= 1 && k <= RAD_LAYA_MAX_OPTIONS && w1 - w0 >= RAD_LAYA_W_MARKERS + k &&
|
||||
type >= RAD_LAYA_CHOICE && type <= RAD_LAYA_NOUL;
|
||||
for (int64_t i = 0; ok && i < k; ++i) {
|
||||
const int32_t at = hw[RAD_LAYA_W_MARKERS + i];
|
||||
ok = at >= 0 && at < n;
|
||||
}
|
||||
if (!ok) {
|
||||
rad_step_fail(c, "laya: a sequence's words are not a Laya question's (type, markers)");
|
||||
return;
|
||||
}
|
||||
first[(size_t)s + 1] = first[(size_t)s] + n;
|
||||
}
|
||||
if (first[(size_t)S] != T) {
|
||||
rad_step_fail(c, "laya: the words' token counts do not add up to the step's tokens");
|
||||
return;
|
||||
}
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
|
||||
/* ---- the encoder over every sequence at once. */
|
||||
RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_o, T));
|
||||
RAD_ISSUE_N(c, m.op_emb_norm, T, brows(m.b_o, T), RAD_W(m.w_emb_norm), RAD_NONE, brows(m.b_x, T));
|
||||
for (size_t l = 0; l < m.layers.size(); ++l) {
|
||||
const Layer& y = m.layers[l];
|
||||
rad_buf att_in = m.b_x;
|
||||
if (l > 0) {
|
||||
RAD_ISSUE_N(c, y.op_attn_norm, T, brows(m.b_x, T), RAD_W(y.w_attn_norm), RAD_NONE,
|
||||
brows(m.b_h, T));
|
||||
att_in = m.b_h;
|
||||
}
|
||||
RAD_ISSUE_N(c, y.op_qkv, T, brows(att_in, T), RAD_W(y.w_qkv), brows(m.b_qkv, T));
|
||||
RAD_ISSUE_N(c, y.op_rope, T, brows(m.b_qkv, T), pos);
|
||||
RAD_ISSUE_N(c, y.op_attn, T, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
|
||||
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
|
||||
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), brows(m.b_o, T));
|
||||
RAD_ISSUE_N(c, y.op_add_attn, T, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
|
||||
RAD_ISSUE_N(c, y.op_mlp_norm, T, brows(m.b_x, T), RAD_W(y.w_mlp_norm), RAD_NONE,
|
||||
brows(m.b_h, T));
|
||||
RAD_ISSUE_N(c, y.op_wi, T, brows(m.b_h, T), RAD_W(y.w_wi), brows(m.b_wi, T));
|
||||
RAD_ISSUE_N(c, y.op_act, T, bcol(m.b_wi, 0, F, T), bcol(m.b_wi, F, F, T), brows(m.b_ff, T));
|
||||
RAD_ISSUE_N(c, y.op_wo, T, brows(m.b_ff, T), RAD_W(y.w_wo), brows(m.b_o, T));
|
||||
RAD_ISSUE_N(c, y.op_add_mlp, T, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_final_norm, T, brows(m.b_x, T), RAD_W(m.w_final_norm), RAD_NONE,
|
||||
brows(m.b_h, T));
|
||||
|
||||
/* ---- the head: each sequence's type row added over its rows, then the head's layers. */
|
||||
for (int64_t s = 0; s < S; ++s) {
|
||||
const int32_t* dw = batch->plugin_words + batch->plugin_cu_h[s];
|
||||
const int64_t r0 = first[(size_t)s], n = first[(size_t)s + 1] - r0;
|
||||
RAD_ISSUE_N(c, m.op_type, 1, praw(dw + RAD_LAYA_W_TYPE, RAD_I32, 1), RAD_W(m.w_type),
|
||||
brow_slice(m.b_trow, s, 1, E));
|
||||
RAD_ISSUE_N(c, m.op_add_type, n, brow_slice(m.b_h, r0, n, E), brow_slice(m.b_trow, s, 1, E),
|
||||
brow_slice(m.b_h, r0, n, E));
|
||||
}
|
||||
for (const HeadLayer& h : m.head) {
|
||||
RAD_ISSUE_N(c, h.op_n1, T, brows(m.b_h, T), RAD_W(h.n1_w), RAD_W(h.n1_b), brows(m.b_t, T));
|
||||
RAD_ISSUE_N(c, h.op_qkv, T, brows(m.b_t, T), RAD_W(h.qkv_w), RAD_W(h.qkv_b), RAD_NONE,
|
||||
brows(m.b_qkv, T));
|
||||
RAD_ISSUE_N(c, h.op_attn, T, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
|
||||
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
|
||||
RAD_ISSUE_N(c, h.op_out, T, brows(m.b_att, T), RAD_W(h.out_w), RAD_W(h.out_b),
|
||||
brows(m.b_h, T), brows(m.b_h, T));
|
||||
RAD_ISSUE_N(c, h.op_n2, T, brows(m.b_h, T), RAD_W(h.n2_w), RAD_W(h.n2_b), brows(m.b_t, T));
|
||||
RAD_ISSUE_N(c, h.op_l1, T, brows(m.b_t, T), RAD_W(h.l1_w), RAD_W(h.l1_b), RAD_NONE,
|
||||
brows(m.b_hff, T));
|
||||
RAD_ISSUE_N(c, h.op_relu, T, brows(m.b_hff, T), brows(m.b_hff, T));
|
||||
RAD_ISSUE_N(c, h.op_l2, T, brows(m.b_hff, T), RAD_W(h.l2_w), RAD_W(h.l2_b),
|
||||
brows(m.b_h, T), brows(m.b_h, T));
|
||||
}
|
||||
|
||||
/* ---- the markers' rows, consecutive across sequences, and one score each. */
|
||||
std::vector<int64_t> mark((size_t)S + 1, 0);
|
||||
for (int64_t s = 0; s < S; ++s) {
|
||||
const int32_t* dw = batch->plugin_words + batch->plugin_cu_h[s];
|
||||
const int64_t k = batch->plugin_words_h[batch->plugin_cu_h[s] + RAD_LAYA_W_K];
|
||||
const int64_t r0 = first[(size_t)s], n = first[(size_t)s + 1] - r0;
|
||||
RAD_ISSUE_N(c, m.op_gather, k, brow_slice(m.b_h, r0, n, E),
|
||||
praw(dw + RAD_LAYA_W_MARKERS, RAD_I32, k), brow_slice(m.b_m, mark[(size_t)s], k, E));
|
||||
mark[(size_t)s + 1] = mark[(size_t)s] + k;
|
||||
}
|
||||
const int64_t K = mark[(size_t)S];
|
||||
RAD_ISSUE_N(c, m.op_sn, K, brows(m.b_m, K), RAD_W(m.w_sn), RAD_W(m.b_sn), brows(m.b_t, K));
|
||||
RAD_ISSUE_N(c, m.op_s1, K, brows(m.b_t, K), RAD_W(m.w_s1), RAD_W(m.b_s1), RAD_NONE, brows(m.b_m2, K));
|
||||
RAD_ISSUE_N(c, m.op_s2, K, brows(m.b_m2, K), RAD_W(m.w_s2), RAD_W(m.b_s2), RAD_NONE, brows(m.b_sc, K));
|
||||
RAD_ISSUE_N(c, m.op_fill, 1, brow_slice(m.b_sc, K, P, 1));
|
||||
/* Each sequence's pooled row: its k scores and, past them, the next scores or filler, which
|
||||
* the server does not read. */
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
RAD_ISSUE_N(c, m.op_out, 1, brow_slice(m.b_sc, mark[(size_t)s], P, 1),
|
||||
bcol_at(m.b_pooled, s, P, 0, P, 1));
|
||||
}
|
||||
|
||||
} /* namespace laya */
|
||||
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(laya, "laya", "", "0.1.0",
|
||||
"Convai Innovations' Laya (laya, laya-typed-decisions, laya-multilingual): a "
|
||||
"ModernBERT encoder and a decision head scoring each option at its [MASK], one "
|
||||
"sequence a question, served on /v1/systemone; bf16")
|
||||
RAD_ARCH_PROBE(laya)
|
||||
+291
-79
@@ -21,14 +21,36 @@
|
||||
* under `model`. Which one this is comes from the config (a VL checkpoint has a `text_config`),
|
||||
* not the model's name.
|
||||
*
|
||||
* ============================== 8-BIT LINEARS ==============================
|
||||
*
|
||||
* Every linear is a LinearFP8 (rad_fp8.h), so the container's encoding of each weight decides the
|
||||
* GEMM: plain bf16 is `gemm_nt` over the bf16 activation, exactly as a bf16 model runs; a recipe's
|
||||
* block E4M3 (`codes=fp8_e4m3 block=128x128 scale=bf16`) is `gemm_nt_q` at fp8a8 over the
|
||||
* activation quantised per 128 columns (one quant_act_fp8 per activation, shared by the linears
|
||||
* that read it); int8 (`codes=i8 group=128 scale=bf16`) is `gemm_nt_q` at i8a8, each linear
|
||||
* quantising its input, and IQ8R (rotated int8 with a scale per 256 of K,
|
||||
* data/recipes/d1-3b-iq8r.recipe) the same at i8a8h with the activation pairs at the weights'
|
||||
* group. The trunk's format is read off layer 0's first linear and every linear must match it. The convolution, the norms and attention stay bf16; the lm_head is read at its
|
||||
* stored codes (bf16, or E4M3 / int8 where a recipe made it so; logits_gemm_fp8 / _i8). At d1-3B
|
||||
* the linears are 5.8 of the 6.3 GB a token reads, so 8-bit codes nearly halve decode and short
|
||||
* prefill, both bound by that read.
|
||||
*
|
||||
* A block-fp8 trunk also takes the fused producers (rad_fp8.h), which matter once the GEMMs are
|
||||
* this cheap: each norm quantises in its own pass and does the preceding block's residual add
|
||||
* (rmsnorm_quant_fp8 with a fold), and the feed-forward is MlpFP8, whose gate|up GEMM applies
|
||||
* SiLU(gate) * up and quantises in its epilogue at decode and short-prompt rows. Six launches a
|
||||
* layer become two; the last layer's feed-forward keeps its add for the final norm. The fused
|
||||
* kernels are byte-identical to the chains they replace.
|
||||
*
|
||||
* ============================== WHAT IT DOES NOT SERVE ==============================
|
||||
*
|
||||
* Tensor parallelism (a 3B model needs one card). A drafter, MoE (LFM2-8B-A1B), conv bias, or a
|
||||
* checkpoint without the rotary: each is refused by name.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include "siglip2.h"
|
||||
|
||||
@@ -42,17 +64,32 @@ using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool attention = false;
|
||||
MlpBF16 mlp;
|
||||
rad_weight w_norm = 0, w_in = 0, w_out = 0;
|
||||
rad_weight w_norm = 0;
|
||||
/* in is q (attention) or the convolution's in_proj; out is the mixer's out-projection */
|
||||
LinearFP8 in, out;
|
||||
/* conv */
|
||||
rad_weight w_conv = 0;
|
||||
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
|
||||
/* attention: w_in is q, these are k, v and the two head norms */
|
||||
rad_weight w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
rad_op op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
/* `gate_quant_fp8` at act none: C * conv(B * x) and its E4M3 codes in one pass. Absent
|
||||
* (bf16, int8, or no library serving it), op_gate_out and q_mix run the pair. */
|
||||
rad_op op_gate_q = 0;
|
||||
/* attention: k, v and the two head norms */
|
||||
LinearFP8 k, v;
|
||||
rad_weight w_q_norm = 0, w_k_norm = 0;
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_store = 0, op_attn = 0;
|
||||
/* both */
|
||||
rad_op op_norm = 0, op_in = 0, op_out = 0, op_add = 0;
|
||||
rad_op op_norm = 0, op_add = 0;
|
||||
/* the feed-forward: norm, gate|up (w1 | w3), SiLU(gate) * up, down (w2), residual add */
|
||||
rad_weight w_ffn_norm = 0;
|
||||
LinearFP8 gate_up, down;
|
||||
rad_op op_ffn_norm = 0, op_act = 0, op_ffn_add = 0;
|
||||
/* fp8a8 only: the activation quantisers, one per activation the linears read */
|
||||
QuantFP8 q_h, q_mix, q_ffn_h, q_ffn;
|
||||
/* fp8a8 fused: the mixer's norm (quantising, and adding the previous feed-forward's delta
|
||||
* from layer 1 on) and the whole feed-forward */
|
||||
NormQuantFP8 nq_mix;
|
||||
MlpFP8 mlp8;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -64,6 +101,14 @@ struct Model {
|
||||
rad_buf b_x = 0, b_h = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
|
||||
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate_up = 0, b_ffn = 0;
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
/* The linears' inputs: the bf16 plane plus, for an 8-bit trunk, its codes. a_mix is the
|
||||
* mixer's output (attention or convolution), the out-projection's input. */
|
||||
ActFP8 a_h{}, a_attn{}, a_conv{}, a_ffn{};
|
||||
/* The trunk's format, read off layer 0's first linear. `fused`: the fp8 trunk's fused
|
||||
* producers (see the head of the file). */
|
||||
bool q_fp8 = false, q_i8 = false, fused = false;
|
||||
/* An int8 trunk's scale group along K, which its activation pairs share (ActFP8::g8). */
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
|
||||
@@ -76,7 +121,7 @@ struct Model {
|
||||
MediaRows mrows{};
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A text_config key first, then the top level: a VL checkpoint nests the text model's settings
|
||||
* and a text checkpoint does not. */
|
||||
@@ -124,7 +169,9 @@ static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Lay
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: lfm2_bf16 serves one rank; run it with --tp 1\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -136,7 +183,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -215,8 +262,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
/* The head at its codes' dtype: bf16, or E4M3 / int8 where a recipe quantised it. */
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
@@ -227,66 +276,133 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0;
|
||||
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
|
||||
|
||||
MlpBF16::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
|
||||
|
||||
auto gemm = [&](int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w)),
|
||||
{in}, {out});
|
||||
/* ---- the trunk's format, from layer 0's first linear: q, or the convolution's in_proj
|
||||
* (probe() makes its name map and reads its encoding). Plain bf16, or no encoding yet, is a
|
||||
* bf16 trunk; an int8 weight makes the activations carry int8 codes, any other 8-bit weight
|
||||
* E4M3 ones. */
|
||||
const char* ffn_fmt = "%s.layers.%d.feed_forward.%s";
|
||||
{
|
||||
Layer& L0 = m.layers[0];
|
||||
const char* base0 = nm.f(L0.attention ? "blk.%d.attn_q" : "blk.%d.conv_in", 0);
|
||||
RAD_ARCH_TRY(L0.in.probe(b, nm, g, base0,
|
||||
{ nm.ckpt(L0.attention ? "%s.layers.%d.self_attn.%s"
|
||||
: "%s.layers.%d.conv.%s",
|
||||
pre, 0, L0.attention ? "q_proj.weight"
|
||||
: "in_proj.weight") }));
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, nm.f("%s.weight", base0), &enc);
|
||||
const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16);
|
||||
g.w_bf16 = plain;
|
||||
m.q_i8 = !plain && L0.in.probed_i8;
|
||||
if (m.q_i8) m.g8 = L0.in.probed_g8;
|
||||
m.q_fp8 = !plain && !m.q_i8;
|
||||
m.fused = m.q_fp8;
|
||||
}
|
||||
if (m.q_i8 && (g.n_embd % m.g8 || g.q_dim() % m.g8 || g.n_ff % m.g8)) {
|
||||
fprintf(stderr, "radiance: lfm2: the int8 trunk keeps one scale a %lld of K, which does not "
|
||||
"divide this model's widths (hidden %lld, attention %lld, feed-forward "
|
||||
"%lld)\n",
|
||||
(long long)m.g8, (long long)g.n_embd, (long long)g.q_dim(), (long long)g.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.a_h.x = m.b_h; m.a_attn.x = m.b_attn; m.a_conv.x = m.b_conv_out; m.a_ffn.x = m.b_ffn;
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8, true, m.g8));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8, true, m.g8));
|
||||
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8, true, m.g8));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8, true, m.g8));
|
||||
/* An E4M3 activation is quantised once by the model and read by every linear on it; an int8
|
||||
* linear quantises its own input (LinearFP8::op_q), and a bf16 one reads the bf16 plane. */
|
||||
auto quant = [&](QuantFP8& q, const ActFP8& a, int64_t n) {
|
||||
return m.q_fp8 ? q.declare(b, g, a, n) : RAD_OK;
|
||||
};
|
||||
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out) {
|
||||
return rw(b, RAD_OP(b, "rmsnorm",
|
||||
|
||||
/* `op`: "rmsnorm", or "rmsnorm_rows" for the head norms, whose short-row form a prefill's
|
||||
* thousands of head_dim-wide rows take. */
|
||||
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out,
|
||||
const char* op = "rmsnorm") {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w)),
|
||||
{in}, {out});
|
||||
};
|
||||
auto add = [&](rad_buf x, rad_buf h) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{x, h}, {x});
|
||||
};
|
||||
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
|
||||
uint32_t dtype) {
|
||||
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
};
|
||||
/* One linear: `base` is the declared name without `.weight`. Every linear must have the
|
||||
* trunk's format; LinearFP8 refuses a bf16 weight in an 8-bit trunk with no bf16 plane, and
|
||||
* this refuses the other mixes. */
|
||||
auto linear = [&](LinearFP8& lin, int l, const char* base_fmt, int64_t N, int64_t K,
|
||||
std::initializer_list<const char*> src, const ActFP8& a, rad_buf y,
|
||||
std::initializer_list<int64_t> parts) -> int {
|
||||
const char* base = nm.f(base_fmt, l);
|
||||
RAD_ARCH_TRY(lin.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(l), src, a, y, 0,
|
||||
parts));
|
||||
const bool ok = g.w_bf16 ? lin.bf16 : m.q_i8 ? lin.i8 : (!lin.bf16 && !lin.i8);
|
||||
if (!ok) {
|
||||
fprintf(stderr, "radiance: lfm2: '%s.weight' is not in the trunk's format (%s); quantise "
|
||||
"every linear of the trunk alike\n",
|
||||
base, g.w_bf16 ? "bf16" : m.q_i8 ? "int8" : "block fp8");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
Layer& L = m.layers[(size_t)l];
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
|
||||
nm.ckpt("%s.layers.%d.operator_norm.weight", pre, l)));
|
||||
L.w_norm = layer_w("blk.%d.attn_norm.weight", l, {g.n_embd}, RAD_F32);
|
||||
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
|
||||
if (m.fused) {
|
||||
/* From layer 1 on the previous feed-forward's delta is still in h: the norm adds it
|
||||
* into the stream, then normalises and quantises. */
|
||||
const bool fold = l > 0;
|
||||
RAD_ARCH_TRY(L.nq_mix.declare(b, g, L.w_norm, fold ? m.b_h : m.b_x, m.a_h, g.n_embd,
|
||||
fold ? m.b_x : 0));
|
||||
} else {
|
||||
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
|
||||
RAD_ARCH_TRY(quant(L.q_h, m.a_h, g.n_embd));
|
||||
}
|
||||
|
||||
if (L.attention) {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn));
|
||||
const char* a = "%s.layers.%d.self_attn.%s";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), nm.ckpt(a, pre, l, "q_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), nm.ckpt(a, pre, l, "k_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), nm.ckpt(a, pre, l, "v_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l),
|
||||
nm.ckpt(a, pre, l, "q_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l),
|
||||
nm.ckpt(a, pre, l, "k_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
|
||||
nm.ckpt(a, pre, l, "out_proj.weight")));
|
||||
L.w_in = layer_w("blk.%d.attn_q.weight", l, {g.q_dim(), g.n_embd}, RAD_BF16);
|
||||
L.w_k = layer_w("blk.%d.attn_k.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
|
||||
L.w_v = layer_w("blk.%d.attn_v.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
|
||||
RAD_ARCH_TRY(linear(L.in, l, "blk.%d.attn_q", g.q_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "q_proj.weight") }, m.a_h, m.b_q, {}));
|
||||
/* k and v are the trunk's narrowest linears: past 40 rows the narrow fp8 row's split
|
||||
* leaves each slice too few waves, so they ask for the short-prompt split rule. */
|
||||
L.k.short_split = L.v.short_split = true;
|
||||
RAD_ARCH_TRY(linear(L.k, l, "blk.%d.attn_k", g.kv_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "k_proj.weight") }, m.a_h, m.b_k, {}));
|
||||
RAD_ARCH_TRY(linear(L.v, l, "blk.%d.attn_v", g.kv_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "v_proj.weight") }, m.a_h, m.b_v, {}));
|
||||
L.w_q_norm = layer_w("blk.%d.attn_q_norm.weight", l, {g.head_dim}, RAD_F32);
|
||||
L.w_k_norm = layer_w("blk.%d.attn_k_norm.weight", l, {g.head_dim}, RAD_F32);
|
||||
L.w_out = layer_w("blk.%d.attn_output.weight", l, {g.n_embd, g.q_dim()}, RAD_BF16);
|
||||
|
||||
L.op_in = gemm(g.q_dim(), g.n_embd, L.w_in, m.b_h, m.b_q);
|
||||
L.op_k = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k);
|
||||
L.op_v = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v);
|
||||
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
|
||||
* T * heads rows. */
|
||||
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q);
|
||||
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k);
|
||||
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q,
|
||||
"rmsnorm_rows");
|
||||
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k,
|
||||
"rmsnorm_rows");
|
||||
L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim,
|
||||
"neox"), {m.b_q}, {m.b_q});
|
||||
"neox", "rope_rows"), {m.b_q}, {m.b_q});
|
||||
L.op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
|
||||
"neox"), {m.b_k}, {m.b_k});
|
||||
"neox", "rope_rows"), {m.b_k}, {m.b_k});
|
||||
/* attn_paged before kv_store: the cache's block size is read from the resolved
|
||||
* attention kernel. */
|
||||
L.op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
@@ -309,21 +425,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_k, m.b_v}, {});
|
||||
L.op_out = gemm(g.n_embd, g.q_dim(), L.w_out, m.b_attn, m.b_h);
|
||||
RAD_ARCH_TRY(quant(L.q_mix, m.a_attn, g.q_dim()));
|
||||
RAD_ARCH_TRY(linear(L.out, l, "blk.%d.attn_output", g.n_embd, g.q_dim(),
|
||||
{ nm.ckpt(a, pre, l, "out_proj.weight") }, m.a_attn, m.b_h, {}));
|
||||
} else {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
|
||||
const char* c = "%s.layers.%d.conv.%s";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_in.weight", l), nm.ckpt(c, pre, l, "in_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_out.weight", l), nm.ckpt(c, pre, l, "out_proj.weight")));
|
||||
L.w_in = layer_w("blk.%d.conv_in.weight", l, {3 * g.n_embd, g.n_embd}, RAD_BF16);
|
||||
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
|
||||
RAD_ARCH_TRY(linear(L.in, l, "blk.%d.conv_in", 3 * g.n_embd, g.n_embd,
|
||||
{ nm.ckpt(c, pre, l, "in_proj.weight") }, m.a_h, m.b_bcx, {}));
|
||||
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
|
||||
* convert, as the gated delta net's conv1d is. */
|
||||
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
|
||||
L.w_out = layer_w("blk.%d.conv_out.weight", l, {g.n_embd, g.n_embd}, RAD_BF16);
|
||||
|
||||
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
|
||||
L.op_in = gemm(3 * g.n_embd, g.n_embd, L.w_in, m.b_h, m.b_bcx);
|
||||
L.op_gate_in = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
@@ -334,25 +449,78 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(L.w_conv)),
|
||||
{m.b_conv_in}, {m.b_conv_out});
|
||||
L.op_gate_out = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
|
||||
L.op_out = gemm(g.n_embd, g.n_embd, L.w_out, m.b_conv_out, m.b_h);
|
||||
/* C * conv(B * x), then the codes the out projection reads, in one pass. The kernel
|
||||
* rounds the product to bf16 before taking the codes, so it is byte-identical to the
|
||||
* mul + quant_act_fp8 pair; the bf16 product has no reader in a block-fp8 trunk. */
|
||||
if (m.q_fp8 && rad_op_declared(b, "gate_quant_fp8"))
|
||||
L.op_gate_q = rw(b, RAD_OP(b, "gate_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", g.dtype),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_bcx, m.b_conv_out}, {m.a_conv.cq(), m.a_conv.cs()});
|
||||
if (!L.op_gate_q) {
|
||||
L.op_gate_out = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
|
||||
RAD_ARCH_TRY(quant(L.q_mix, m.a_conv, g.n_embd));
|
||||
}
|
||||
RAD_ARCH_TRY(linear(L.out, l, "blk.%d.conv_out", g.n_embd, g.n_embd,
|
||||
{ nm.ckpt(c, pre, l, "out_proj.weight") }, m.a_conv, m.b_h, {}));
|
||||
}
|
||||
L.op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
if (m.fused) {
|
||||
/* The feed-forward's norm adds the mixer's delta; its own add is left to the next
|
||||
* layer's norm, except after the last layer, whose output the final norm reads. */
|
||||
MlpFP8::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
|
||||
MlpFP8::Src ms{};
|
||||
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
|
||||
ms.gate = nm.ckpt(ffn_fmt, pre, l, "w1.weight");
|
||||
ms.up = nm.ckpt(ffn_fmt, pre, l, "w3.weight");
|
||||
ms.down = nm.ckpt(ffn_fmt, pre, l, "w2.weight");
|
||||
const bool last = l + 1 == (int)m.layers.size();
|
||||
/* The whole prompt in the fold (`wide_fold`): its row serves every M, so a prefill
|
||||
* chunk does not fall back to the pair past 64 rows. */
|
||||
RAD_ARCH_TRY(L.mlp8.declare(b, nm, g, l, mw, ms, /*fold=*/true, /*add_out=*/last,
|
||||
0, false, 0, /*wide_fold=*/true));
|
||||
if (L.mlp8.gate_up.bf16 || L.mlp8.gate_up.i8 || L.mlp8.down.bf16 || L.mlp8.down.i8) {
|
||||
fprintf(stderr, "radiance: lfm2: layer %d's feed-forward is not block fp8 like the "
|
||||
"rest of the trunk; quantise every linear alike\n", l);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
L.op_add = add(m.b_x, m.b_h);
|
||||
|
||||
/* ---- the feed-forward */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l),
|
||||
nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l)));
|
||||
L.w_ffn_norm = layer_w("blk.%d.ffn_norm.weight", l, {g.n_embd}, RAD_F32);
|
||||
L.op_ffn_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(L.w_ffn_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
RAD_ARCH_TRY(quant(L.q_ffn_h, m.a_h, g.n_embd));
|
||||
RAD_ARCH_TRY(linear(L.gate_up, l, "blk.%d.ffn_gate_up", 2 * g.n_ff, g.n_embd,
|
||||
{ nm.ckpt(ffn_fmt, pre, l, "w1.weight"),
|
||||
nm.ckpt(ffn_fmt, pre, l, "w3.weight") },
|
||||
m.a_h, m.b_gate_up, { g.n_ff, g.n_ff }));
|
||||
L.op_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x, m.b_h}, {m.b_x});
|
||||
|
||||
MlpBF16::Src ms{};
|
||||
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
|
||||
ms.gate = nm.ckpt("%s.layers.%d.feed_forward.w1.weight", pre, l);
|
||||
ms.up = nm.ckpt("%s.layers.%d.feed_forward.w3.weight", pre, l);
|
||||
ms.down = nm.ckpt("%s.layers.%d.feed_forward.w2.weight", pre, l);
|
||||
RAD_ARCH_TRY(L.mlp.declare(b, nm, g, l, mw, ms));
|
||||
{m.b_gate_up}, {m.b_ffn});
|
||||
RAD_ARCH_TRY(quant(L.q_ffn, m.a_ffn, g.n_ff));
|
||||
RAD_ARCH_TRY(linear(L.down, l, "blk.%d.ffn_down", g.n_embd, g.n_ff,
|
||||
{ nm.ckpt(ffn_fmt, pre, l, "w2.weight") }, m.a_ffn, m.b_h, {}));
|
||||
L.op_ffn_add = add(m.b_x, m.b_h);
|
||||
}
|
||||
|
||||
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
|
||||
@@ -363,6 +531,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_hout});
|
||||
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, m.b_hout);
|
||||
/* A tied head is the bf16 embedding table, whatever codes the head itself is read at: a
|
||||
* scored step (/v1/systemone) leaves the final-normed rows in h_out and the core takes the
|
||||
* candidates' logits from the table on the host (rad_declare_scores), with no head read. */
|
||||
if (text_bool(meta, "tie_word_embeddings", false))
|
||||
RAD_ARCH_TRY(rad_declare_scores(b, m.b_hout, m.w_tok));
|
||||
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
@@ -412,7 +585,7 @@ static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch*
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
if (batch->draft_pass || batch->spec_parent ||
|
||||
(!m.media && (batch->enc || batch->n_mm_rows > 0))) {
|
||||
@@ -431,12 +604,17 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
const Layer& L = m.layers[(size_t)l];
|
||||
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
|
||||
if (m.fused) {
|
||||
L.nq_mix.step(c, T);
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
|
||||
L.q_h.step(c, T);
|
||||
}
|
||||
if (L.attention) {
|
||||
const RadKVGroupBatch* kv = kv_batch(batch, m.kv_attn);
|
||||
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_q, T));
|
||||
RAD_ISSUE(c, L.op_k, brows(m.b_h, T), RAD_W(L.w_k), brows(m.b_k, T));
|
||||
RAD_ISSUE(c, L.op_v, brows(m.b_h, T), RAD_W(L.w_v), brows(m.b_v, T));
|
||||
L.in.step(c, m.a_h, m.b_q, T);
|
||||
L.k.step(c, m.a_h, m.b_k, T);
|
||||
L.v.step(c, m.a_h, m.b_v, T);
|
||||
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
|
||||
brows(m.b_q, T));
|
||||
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
|
||||
@@ -453,18 +631,36 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(m.b_attn, T));
|
||||
RAD_ISSUE(c, L.op_out, brows(m.b_attn, T), RAD_W(L.w_out), brows(m.b_h, T));
|
||||
L.q_mix.step(c, T);
|
||||
L.out.step(c, m.a_attn, m.b_h, T);
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_bcx, T));
|
||||
L.in.step(c, m.a_h, m.b_bcx, T);
|
||||
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
|
||||
brows(m.b_conv_in, T));
|
||||
conv_step(m, L, c, batch, l);
|
||||
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
|
||||
brows(m.b_conv_out, T));
|
||||
RAD_ISSUE(c, L.op_out, brows(m.b_conv_out, T), RAD_W(L.w_out), brows(m.b_h, T));
|
||||
if (L.op_gate_q) {
|
||||
RAD_ISSUE(c, L.op_gate_q, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
|
||||
brows(m.a_conv.cq(), T), brows(m.a_conv.cs(), T), RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
|
||||
brows(m.b_conv_out, T));
|
||||
L.q_mix.step(c, T);
|
||||
}
|
||||
L.out.step(c, m.a_conv, m.b_h, T);
|
||||
}
|
||||
if (m.fused) {
|
||||
L.mlp8.step(c, batch);
|
||||
continue;
|
||||
}
|
||||
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
|
||||
L.mlp.step(c, batch);
|
||||
|
||||
RAD_ISSUE(c, L.op_ffn_norm, brows(m.b_x, T), RAD_W(L.w_ffn_norm), brows(m.b_h, T));
|
||||
L.q_ffn_h.step(c, T);
|
||||
L.gate_up.step(c, m.a_h, m.b_gate_up, T);
|
||||
RAD_ISSUE(c, L.op_act, brows(m.b_gate_up, T), brows(m.b_ffn, T));
|
||||
L.q_ffn.step(c, T);
|
||||
L.down.step(c, m.a_ffn, m.b_h, T);
|
||||
RAD_ISSUE(c, L.op_ffn_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
|
||||
}
|
||||
|
||||
/* The lm_head runs only on the rows the sampler asked for; a prefill chunk that finishes no
|
||||
@@ -474,15 +670,31 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_out_norm), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
|
||||
if (!batch->score_only)
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
/* Chained launches pay on the plain-bf16 trunk: its GEMMs, norms and elementwise kernels have
|
||||
* chained forms (libr4d's rad_kernel_chain); the head norms, the rotary and the convolution keep
|
||||
* their plain rows, with which the long GEMMs between them run faster. The 3B text model on one
|
||||
* R9700, ms a decode step unchained / chained: 12.14 / 11.31 at one sequence and 12.54 / 11.60 at
|
||||
* four. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace lfm2_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.1.0",
|
||||
"LiquidAI LFM2 / LFM2-VL, bf16: short gated convolutions and GQA attention in the "
|
||||
"checkpoint's own schedule, one rank; LFM2-VL's SigLIP2 tower for images")
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PROBE(lfm2_bf16)
|
||||
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.2.0",
|
||||
"LiquidAI LFM2 / LFM2-VL, bf16, or with block-fp8 or int8 linears from a recipe: "
|
||||
"short gated convolutions and GQA attention in the checkpoint's own schedule, one "
|
||||
"rank; LFM2-VL's SigLIP2 tower for images")
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/lfm3_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(lfm3_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(lfm3_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/lfm3_bf16.cpp)
|
||||
@@ -0,0 +1,779 @@
|
||||
/* lfm3_bf16 -- LiquidAI's LFM3, bf16 activations over bf16 or int8 (IQ8R) linears, one rank.
|
||||
*
|
||||
* ============================== THE SHAPE ==============================
|
||||
*
|
||||
* LFM2's hybrid with a third layer kind, in the order the checkpoint's `layer_types` lists them
|
||||
* (read, not derived):
|
||||
*
|
||||
* conv in_proj -> [B | C | x], y = out_proj(C * conv(B * x)), where conv is a
|
||||
* depthwise causal convolution of width `conv_L_cache` with no activation
|
||||
* full_attention GQA with per-head RMS norms on q and k, a partial NeoX rotary on the "head"
|
||||
* ladder (the first `partial_rotary_factor * head_dim` channels rotate, at the
|
||||
* frequencies of the whole head; the rest do not), and a gate per query head
|
||||
* sliding_attention the same attention over the last `sliding_window` tokens, its rotary over
|
||||
* the whole head at its own theta
|
||||
*
|
||||
* each followed by a SwiGLU feed-forward (w1 the gate, w3 the up, w2 the down). The norms are a
|
||||
* sandwich: `operator_norm` before the mixer and `post_operator_norm` on its output, before the
|
||||
* residual add; `ffn_norm` and `post_ffn_norm` likewise. Every norm is a plain RMSNorm
|
||||
* (`x_hat * w`), and the final one is `embedding_norm`. A post norm, its add and the norm that
|
||||
* reads the sum are one `norm_add_norm` where a library serves it (Gemma's sandwich join; see
|
||||
* declare). At 1.7B: 24 layers (13 conv, 6 full, 5
|
||||
* sliding with a window of 256), hidden 2048, 16 heads over 4 at head_dim 128, ffn 7680,
|
||||
* vocabulary 128000 with the lm_head tied to the embedding, conv width 7; theta 1e6 over half the
|
||||
* head on the full layers, 1e4 on the sliding ones.
|
||||
*
|
||||
* ============================== THE GATE ==============================
|
||||
*
|
||||
* The attention output of each query head is multiplied by sigmoid(gate_proj(h)), one scalar a
|
||||
* (token, head), before the out projection. `mul` multiplies planes of equal width, so the gate
|
||||
* is computed at the output's width: the name map repeats each of gate_proj's n_head rows head_dim
|
||||
* times (RAD_MAP_ROWS), and `gemm_nt` + `sigmoid` + `mul` then give every channel of a head that
|
||||
* head's gate, with the reference's rounding (the gate and the product are each a bf16 tensor
|
||||
* there). It costs n_embd * (q_dim - n_head) stored weights an attention layer, 2.6% of the
|
||||
* container at 1.7B.
|
||||
*
|
||||
* ============================== 8-BIT LINEARS ==============================
|
||||
*
|
||||
* Every linear but the gate is a LinearFP8 (rad_fp8.h), as lfm2_bf16's are, so the container's
|
||||
* encoding of each weight decides the GEMM: plain bf16 is `gemm_nt` over the bf16 activation,
|
||||
* exactly as a bf16 model runs; int8 (`codes=i8 group=128 scale=bf16`) is `gemm_nt_q` at i8a8, and
|
||||
* the rotated form (those codes under the 128-wide Hadamard, data/recipes/lfm3-1.7b-iq8r.recipe,
|
||||
* or IQ8R's scale per 256 of K) the same at i8a8h, each linear quantising its input from
|
||||
* the bf16 plane. The trunk's format is read off layer 0's first linear and every linear must
|
||||
* match it. The gate stays bf16 in every container (n_head distinct rows; its product is a hard
|
||||
* multiplier on a whole head), as do the convolution, the norms, the joins and attention. The
|
||||
* lm_head is read at its stored codes.
|
||||
*
|
||||
* ============================== WHAT IT DOES NOT SERVE ==============================
|
||||
*
|
||||
* Tensor parallelism (the model needs one card), block-fp8 or narrower linears, a trunk that mixes
|
||||
* formats, a quantised gate, a drafter, media, conv bias, a checkpoint without the sandwich norms,
|
||||
* or a rotary other than the default type: each is refused by name.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace lfm3_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
enum Kind { kConv = 0, kFull = 1, kSliding = 2 };
|
||||
|
||||
/* One plain bf16 linear: its weight and the gemm_nt over it. The attention gate is the one linear
|
||||
* declared this way: its weight is gate_proj's rows repeated, which the shared LinearFP8 that
|
||||
* serves every other linear does not map. */
|
||||
struct Linear {
|
||||
rad_weight w = 0;
|
||||
rad_op op = 0;
|
||||
};
|
||||
|
||||
/* What differs between the two attention classes. */
|
||||
struct AttnClass {
|
||||
double theta = 0.0;
|
||||
int64_t rot = 0; /* rotary_dim */
|
||||
int64_t window = 0; /* 0: full */
|
||||
rad_kvgroup kv = 0;
|
||||
};
|
||||
|
||||
struct Layer {
|
||||
Kind kind = kConv;
|
||||
rad_weight w_norm = 0, w_post_norm = 0, w_ffn_norm = 0, w_ffn_post_norm = 0;
|
||||
rad_op op_norm = 0, op_post_norm = 0, op_add = 0;
|
||||
/* conv */
|
||||
LinearFP8 conv_in, conv_out;
|
||||
rad_weight w_conv = 0;
|
||||
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
|
||||
/* attention */
|
||||
LinearFP8 q, k, v, out;
|
||||
Linear gate;
|
||||
rad_weight w_q_norm = 0, w_k_norm = 0;
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_store = 0, op_attn = 0, op_sigmoid = 0, op_gate_mul = 0;
|
||||
/* the feed-forward: norm, gate|up (w1 | w3), SiLU(gate) * up, down (w2), norm, residual add */
|
||||
LinearFP8 gate_up, down;
|
||||
rad_op op_ffn_norm = 0, op_act = 0, op_ffn_post_norm = 0, op_ffn_add = 0;
|
||||
/* The sandwich joins, fused: op_join is post_norm + add + ffn_norm, and op_ffn_join is
|
||||
* ffn_post_norm + ffn_add + the next layer's norm, which that layer then does not declare. */
|
||||
rad_op op_join = 0, op_ffn_join = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
int64_t width = 0; /* conv_L_cache: the convolution's taps */
|
||||
AttnClass full{}, sliding{};
|
||||
rad_kvgroup kv_conv = 0;
|
||||
|
||||
rad_buf b_x = 0, b_h = 0, b_arm = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
|
||||
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate = 0, b_gate_up = 0, b_ffn = 0;
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
/* The four activations a linear reads, as LinearFP8 takes them: the bf16 plane is the buffer
|
||||
* above. */
|
||||
ActFP8 a_h{}, a_attn{}, a_conv{}, a_ffn{};
|
||||
/* An int8 trunk (i8a8, or IQ8R at i8a8h), and its scale group along K, which the activations'
|
||||
* int8 pairs share (ActFP8::g8). */
|
||||
bool q_i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
const AttnClass& cls(const Layer& L) const { return L.kind == kSliding ? sliding : full; }
|
||||
};
|
||||
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int64_t meta_int(const RadModelMeta* m, const char* key, int64_t dflt) {
|
||||
const char* v = rad_meta_gets(m, key, nullptr);
|
||||
return v ? std::strtoll(v, nullptr, 10) : dflt;
|
||||
}
|
||||
static double meta_f64(const RadModelMeta* m, const char* key, double dflt) {
|
||||
const char* v = rad_meta_gets(m, key, nullptr);
|
||||
return v ? std::strtod(v, nullptr) : dflt;
|
||||
}
|
||||
static bool meta_bool(const RadModelMeta* m, const char* key, bool dflt) {
|
||||
const char* v = rad_meta_gets(m, key, nullptr);
|
||||
if (!v) return dflt;
|
||||
return std::strcmp(v, "true") == 0 || std::strcmp(v, "1") == 0;
|
||||
}
|
||||
|
||||
/* `layer_types`, one word per layer, space-separated in the container. */
|
||||
static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Layer>* out) {
|
||||
const char* s = rad_meta_gets(m, "layer_types", nullptr);
|
||||
if (!s || !*s) {
|
||||
fprintf(stderr, "radiance: lfm3: the container has no layer_types; this family's schedule "
|
||||
"is read, not derived\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
std::istringstream in(s);
|
||||
std::string kind;
|
||||
while (in >> kind) {
|
||||
Layer l;
|
||||
if (kind == "conv") l.kind = kConv;
|
||||
else if (kind == "full_attention") l.kind = kFull;
|
||||
else if (kind == "sliding_attention") l.kind = kSliding;
|
||||
else {
|
||||
fprintf(stderr, "radiance: lfm3: layer_types[%zu] is '%s'; this plugin knows 'conv', "
|
||||
"'full_attention' and 'sliding_attention'\n", out->size(), kind.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
out->push_back(l);
|
||||
}
|
||||
if ((int64_t)out->size() != n_layer) {
|
||||
fprintf(stderr, "radiance: lfm3: layer_types names %zu layers and the model has %lld\n",
|
||||
out->size(), (long long)n_layer);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One class's rotary from `rope_parameters.<type>`: theta is required (the typed rope_theta is a
|
||||
* top-level key this family does not write), the type must be the default, and the partial factor
|
||||
* gives an even rotary width inside the head. */
|
||||
static int read_rotary(const RadModelMeta* m, const char* type, int64_t head_dim, AttnClass* c) {
|
||||
const std::string pre = std::string("rope_parameters.") + type + ".";
|
||||
const char* rt = rad_meta_gets(m, (pre + "rope_type").c_str(), "default");
|
||||
if (std::strcmp(rt, "default") != 0) {
|
||||
fprintf(stderr, "radiance: lfm3: rope_parameters.%s.rope_type '%s' is not 'default'\n",
|
||||
type, rt);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
c->theta = meta_f64(m, (pre + "rope_theta").c_str(), 0.0);
|
||||
if (!(c->theta > 0.0)) {
|
||||
fprintf(stderr, "radiance: lfm3: rope_parameters.%s.rope_theta is required\n", type);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const double prf = meta_f64(m, (pre + "partial_rotary_factor").c_str(), 1.0);
|
||||
/* the reference's int(prf * head_dim) // 2 angles */
|
||||
c->rot = 2 * ((int64_t)(prf * (double)head_dim) / 2);
|
||||
if (!(prf > 0.0) || c->rot < 2 || c->rot > head_dim) {
|
||||
fprintf(stderr, "radiance: lfm3: rope_parameters.%s.partial_rotary_factor %g gives a "
|
||||
"rotary width %lld outside 2..head_dim\n", type, prf, (long long)c->rot);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: lfm3_bf16 serves one rank; run it with --tp 1\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (meta->n_expert > 0 || meta_bool(meta, "conv_bias", false) ||
|
||||
!meta_bool(meta, "use_sandwich_norm", true)) {
|
||||
fprintf(stderr, "radiance: lfm3_bf16 serves the dense SwiGLU model with sandwich norms, "
|
||||
"gated attention and bias-free convolutions; this checkpoint is not that\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &m.layers));
|
||||
m.width = meta_int(meta, "conv_L_cache", 0);
|
||||
if (m.width < 2 || m.width > 8) {
|
||||
fprintf(stderr, "radiance: lfm3: conv_L_cache %lld is outside the 2..8 the convolution "
|
||||
"kernels serve\n", (long long)m.width);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
bool has_full = false, has_sliding = false, has_conv = false;
|
||||
for (const Layer& L : m.layers) {
|
||||
has_full |= L.kind == kFull;
|
||||
has_sliding |= L.kind == kSliding;
|
||||
has_conv |= L.kind == kConv;
|
||||
}
|
||||
if (has_full) RAD_ARCH_TRY(read_rotary(meta, "full_attention", g.head_dim, &m.full));
|
||||
if (has_sliding) {
|
||||
RAD_ARCH_TRY(read_rotary(meta, "sliding_attention", g.head_dim, &m.sliding));
|
||||
m.sliding.window = meta_int(meta, "sliding_window", 0);
|
||||
if (m.sliding.window < 1) {
|
||||
fprintf(stderr, "radiance: lfm3: the sliding_attention layers need a sliding_window, "
|
||||
"and the container has %lld\n", (long long)m.sliding.window);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
const char* pre = "model";
|
||||
|
||||
/* ---- the state groups: paged KV for the full layers, the same bounded by the window for the
|
||||
* sliding ones, and a rolling window of the convolution's last width-1 inputs (plus the
|
||||
* speculative slack the manager adds) for the conv layers. The conv group's channels are
|
||||
* n_head_kv * head_dim: one "head" of n_embd. */
|
||||
const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
g.kv_dtype = rad_dtype_name(kvdt);
|
||||
if (has_full) {
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = RAD_KV_FULL;
|
||||
fd.dtype = kvdt;
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
m.full.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
if (!m.full.kv) return RAD_E_INVAL;
|
||||
}
|
||||
if (has_sliding) {
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_WINDOW;
|
||||
sd.dtype = kvdt;
|
||||
sd.window = m.sliding.window;
|
||||
sd.n_head_kv = g.n_head_kv;
|
||||
sd.head_dim = g.head_dim;
|
||||
m.sliding.kv = rad_decl_kv_group(b, nm.f("kv_sliding"), &sd);
|
||||
if (!m.sliding.kv) return RAD_E_INVAL;
|
||||
}
|
||||
if (has_conv) {
|
||||
RadKVGroupDecl cd{};
|
||||
cd.kind = RAD_KV_CONV;
|
||||
cd.dtype = RAD_BF16;
|
||||
cd.n_head_kv = 1;
|
||||
cd.head_dim = g.n_embd;
|
||||
cd.conv_width = m.width;
|
||||
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_conv"), &cd);
|
||||
if (!m.kv_conv) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
/* a mixer's or a feed-forward's output, before its post norm: a join reads it beside x and
|
||||
* writes h, so it is not h */
|
||||
m.b_arm = decl_b(b, nm.f("arm"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_bcx = decl_b(b, nm.f("conv_bcx"), RAD_BF16, {g.max_tok, 3 * g.n_embd});
|
||||
m.b_conv_in = decl_b(b, nm.f("conv_in"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_conv_out = decl_b(b, nm.f("conv_out"), RAD_BF16, {g.max_tok, g.n_embd});
|
||||
m.b_q = decl_b(b, nm.f("attn_q"), RAD_BF16, {g.max_tok, g.q_dim()});
|
||||
m.b_k = decl_b(b, nm.f("attn_k"), RAD_BF16, {g.max_tok, g.kv_dim()});
|
||||
m.b_v = decl_b(b, nm.f("attn_v"), RAD_BF16, {g.max_tok, g.kv_dim()});
|
||||
m.b_attn = decl_b(b, nm.f("attn_out"), RAD_BF16, {g.max_tok, g.q_dim()});
|
||||
m.b_gate = decl_b(b, nm.f("attn_gate"), RAD_BF16, {g.max_tok, g.q_dim()});
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), RAD_BF16, {g.max_tok, 2 * g.n_ff});
|
||||
m.b_ffn = decl_b(b, nm.f("ffn"), RAD_BF16, {g.max_tok, g.n_ff});
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
|
||||
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
|
||||
/* ---- the trunk's format, read off layer 0's first linear before any activation is declared
|
||||
* (probe() makes its name map and reads its encoding). Plain bf16, or no encoding yet, is a
|
||||
* bf16 trunk: every linear is `gemm_nt` over its input's bf16 plane. An int8 weight makes the
|
||||
* activations carry int8 codes beside it. */
|
||||
{
|
||||
Layer& L0 = m.layers[0];
|
||||
const bool at = L0.kind != kConv;
|
||||
LinearFP8& first = at ? L0.q : L0.conv_in;
|
||||
const char* base0 = nm.f(at ? "blk.%d.attn_q" : "blk.%d.conv_in", 0);
|
||||
RAD_ARCH_TRY(first.probe(b, nm, g, base0,
|
||||
{ nm.ckpt(at ? "%s.layers.%d.self_attn.%s" : "%s.layers.%d.conv.%s",
|
||||
pre, 0, at ? "q_proj.weight" : "in_proj.weight") }));
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, nm.f("%s.weight", base0), &enc);
|
||||
const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16);
|
||||
g.w_bf16 = plain;
|
||||
m.q_i8 = !plain && first.probed_i8;
|
||||
if (m.q_i8) m.g8 = first.probed_g8;
|
||||
if (!plain && !m.q_i8) {
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
fprintf(stderr, "radiance: lfm3: '%s.weight' is %s; this plugin serves a bf16 trunk or "
|
||||
"an int8 one (codes=i8 group=128, or IQ8R)\n", base0, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
if (m.q_i8 && (g.n_embd % m.g8 || g.q_dim() % m.g8 || g.n_ff % m.g8)) {
|
||||
fprintf(stderr, "radiance: lfm3: the int8 trunk keeps one scale a %lld of K, which does not "
|
||||
"divide this model's widths (hidden %lld, attention %lld, feed-forward "
|
||||
"%lld)\n",
|
||||
(long long)m.g8, (long long)g.n_embd, (long long)g.q_dim(), (long long)g.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.a_h.x = m.b_h; m.a_attn.x = m.b_attn; m.a_conv.x = m.b_conv_out; m.a_ffn.x = m.b_ffn;
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8, false, m.g8));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8, false, m.g8));
|
||||
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8, false, m.g8));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8, false, m.g8));
|
||||
|
||||
/* ---- the vocabulary edges. The lm_head is tied but declared as its own weight: the
|
||||
* embedding may live in host memory (--embedding-placement) and the head on the card. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.embedding_norm.weight", pre)));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("%s.embed_tokens.weight", pre)));
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
/* The head at its codes' dtype: bf16, or int8 where a recipe made it so. */
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
|
||||
/* `op`: "rmsnorm", or "rmsnorm_rows" for the head norms, whose short-row form a prefill's
|
||||
* thousands of head_dim-wide rows take. */
|
||||
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out,
|
||||
const char* op = "rmsnorm") {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w)),
|
||||
{in}, {out});
|
||||
};
|
||||
auto add = [&](rad_buf x, rad_buf h) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{x, h}, {x});
|
||||
};
|
||||
auto mul = [&](std::initializer_list<rad_buf> rd, rad_buf out, int64_t n) {
|
||||
return rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
rd, {out});
|
||||
};
|
||||
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
|
||||
uint32_t dtype) {
|
||||
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
};
|
||||
/* A norm's gain: mapped, and declared f32. */
|
||||
auto norm_w = [&](rad_weight* w, const char* name, int l, const char* src, int64_t n) -> int {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f(name, l), src));
|
||||
*w = layer_w(name, l, {n}, RAD_F32);
|
||||
return *w ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
/* The gate: one plain bf16 linear over an already mapped weight, in every container. */
|
||||
auto plain_linear = [&](Linear& lin, int l, const char* name, int64_t N, int64_t K, rad_buf in,
|
||||
rad_buf out) -> int {
|
||||
RadEncoding enc{};
|
||||
if (weight_enc(b, nm.f(name, l), &enc) &&
|
||||
!(rad_enc_is(&enc, "plain") && enc.n_planes == 1 && enc.plane[0].dtype == RAD_BF16)) {
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
fprintf(stderr, "radiance: lfm3: '%s' is %s; the attention gate stays bf16 (leave "
|
||||
"gate_proj out of the recipe)\n", nm.f(name, l), en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
lin.w = decl_w(b, nm.f(name, l), RAD_BF16, {N, K}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
if (!lin.w) return RAD_E_INVAL;
|
||||
lin.op = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lin.w)),
|
||||
{in}, {out});
|
||||
return lin.op ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
/* One linear: `base` is the declared name without `.weight`, `src` its checkpoint tensor (or
|
||||
* the tensors stacked along its rows, `parts` their row counts), `a` the activation it reads. */
|
||||
auto linear = [&](LinearFP8& lin, int l, const char* base_fmt, int64_t N, int64_t K,
|
||||
std::initializer_list<const char*> src, const ActFP8& a, rad_buf y,
|
||||
std::initializer_list<int64_t> parts) -> int {
|
||||
const char* base = nm.f(base_fmt, l);
|
||||
RAD_ARCH_TRY(lin.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(l), src, a, y, 0,
|
||||
parts));
|
||||
/* Every linear has the trunk's format. LinearFP8 refuses a quantised weight in a bf16
|
||||
* trunk; this refuses a bf16 or narrower one in an int8 trunk. */
|
||||
if (g.w_bf16 ? !lin.bf16 : !(lin.i8 && !lin.iqr)) {
|
||||
fprintf(stderr, "radiance: lfm3: '%s.weight' is not in the trunk's format (%s); "
|
||||
"quantise every linear of the trunk alike\n",
|
||||
base, g.w_bf16 ? "bf16" : "int8");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
/* q names its query heads; k is rotated as a q-only row of the kv heads (its own buffer).
|
||||
* The partial rotary is on the "head" ladder; over the whole head the ladders coincide and
|
||||
* the parameter is left out. */
|
||||
auto rope = [&](const AttnClass& c, int64_t heads, rad_buf buf) {
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", c.theta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", "neox"), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_STR("ladder", "head") };
|
||||
const int n = (int)(sizeof ps / sizeof ps[0]) - (c.rot < g.head_dim ? 0 : 1);
|
||||
return rw(b, rad_decl_op(b, "rope_rows", ps, n, nullptr, 0), {buf}, {buf});
|
||||
};
|
||||
|
||||
|
||||
/* ---- the sandwich joins. `norm_add_norm` is a post norm, the residual add and the norm that
|
||||
* reads the sum in one launch: post_norm + add + ffn_norm inside a layer, and ffn_post_norm +
|
||||
* add + the next layer's norm between two. It rounds where the chain rounds. The device
|
||||
* libraries serve it and libref and libavx do not, and declaring an op no loaded library
|
||||
* declares is an error, so it is asked for first; without it, or where it does not resolve,
|
||||
* the rmsnorm / add / rmsnorm chain runs. The last layer's feed-forward keeps the chain: the
|
||||
* final norm is on the gathered rows. */
|
||||
const bool has_join = rad_op_declared(b, "norm_add_norm") != 0;
|
||||
auto join = [&](rad_weight w_a, rad_weight w_y) {
|
||||
return rw(b, RAD_OP(b, "norm_add_norm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_a, w_y)),
|
||||
{m.b_arm, m.b_x}, {m.b_x, m.b_h});
|
||||
};
|
||||
int n_joins = 0;
|
||||
|
||||
/* Every layer's input norm gain, ahead of the layers: a feed-forward join names the next
|
||||
* layer's, and an op can only name weights already declared. */
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l)
|
||||
RAD_ARCH_TRY(norm_w(&m.layers[(size_t)l].w_norm, "blk.%d.attn_norm.weight", l,
|
||||
nm.ckpt("%s.layers.%d.%s", pre, l, "operator_norm.weight"), g.n_embd));
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
Layer& L = m.layers[(size_t)l];
|
||||
const char* lay = "%s.layers.%d.%s";
|
||||
RAD_ARCH_TRY(norm_w(&L.w_post_norm, "blk.%d.attn_post_norm.weight", l,
|
||||
nm.ckpt(lay, pre, l, "post_operator_norm.weight"), g.n_embd));
|
||||
RAD_ARCH_TRY(norm_w(&L.w_ffn_norm, "blk.%d.ffn_norm.weight", l,
|
||||
nm.ckpt(lay, pre, l, "ffn_norm.weight"), g.n_embd));
|
||||
RAD_ARCH_TRY(norm_w(&L.w_ffn_post_norm, "blk.%d.ffn_post_norm.weight", l,
|
||||
nm.ckpt(lay, pre, l, "post_ffn_norm.weight"), g.n_embd));
|
||||
/* written by the layer before, where its feed-forward join is fused */
|
||||
if (!(l > 0 && m.layers[(size_t)l - 1].op_ffn_join))
|
||||
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
|
||||
|
||||
if (L.kind != kConv) {
|
||||
const AttnClass& c = m.cls(L);
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, c.kv));
|
||||
const char* a = "%s.layers.%d.self_attn.%s";
|
||||
/* The gate at the output's width: row h of gate_proj, head_dim times, for each head
|
||||
* in turn (see the head of the file). Successive ROWS maps extend the weight. */
|
||||
{
|
||||
const std::string dst = nm.f("blk.%d.attn_gate.weight", l);
|
||||
const std::string src = nm.ckpt(a, pre, l, "gate_proj.weight");
|
||||
for (int64_t h = 0; h < g.n_head; ++h)
|
||||
for (int64_t d = 0; d < g.head_dim; d += 8) {
|
||||
RadNameMap mp = map_base(dst.c_str(), RAD_MAP_ROWS);
|
||||
for (int64_t i = d; i < g.head_dim && i < d + 8; ++i) {
|
||||
mp.src[mp.n_src] = src.c_str();
|
||||
mp.src_index[mp.n_src] = (int)h;
|
||||
mp.src_rows[mp.n_src] = 1;
|
||||
++mp.n_src;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_decl_name_map(b, &mp));
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(linear(L.q, l, "blk.%d.attn_q", g.q_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "q_proj.weight") }, m.a_h, m.b_q, {}));
|
||||
RAD_ARCH_TRY(linear(L.k, l, "blk.%d.attn_k", g.kv_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "k_proj.weight") }, m.a_h, m.b_k, {}));
|
||||
RAD_ARCH_TRY(linear(L.v, l, "blk.%d.attn_v", g.kv_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "v_proj.weight") }, m.a_h, m.b_v, {}));
|
||||
RAD_ARCH_TRY(plain_linear(L.gate, l, "blk.%d.attn_gate.weight", g.q_dim(), g.n_embd,
|
||||
m.b_h, m.b_gate));
|
||||
RAD_ARCH_TRY(norm_w(&L.w_q_norm, "blk.%d.attn_q_norm.weight", l,
|
||||
nm.ckpt(a, pre, l, "q_norm.weight"), g.head_dim));
|
||||
RAD_ARCH_TRY(norm_w(&L.w_k_norm, "blk.%d.attn_k_norm.weight", l,
|
||||
nm.ckpt(a, pre, l, "k_norm.weight"), g.head_dim));
|
||||
|
||||
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
|
||||
* T * heads rows. */
|
||||
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q,
|
||||
"rmsnorm_rows");
|
||||
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k,
|
||||
"rmsnorm_rows");
|
||||
L.op_rope_q = rope(c, g.n_head, m.b_q);
|
||||
L.op_rope_k = rope(c, g.n_head_kv, m.b_k);
|
||||
/* attn_paged before kv_store: the cache's block size is read from the resolved
|
||||
* attention kernel. */
|
||||
L.op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()),
|
||||
RAD_INT("causal", 1), RAD_INT("window", c.window),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs),
|
||||
RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_q}, {m.b_attn});
|
||||
L.op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, c.kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_k, m.b_v}, {});
|
||||
L.op_sigmoid = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.q_dim()),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_gate}, {m.b_gate});
|
||||
L.op_gate_mul = mul({m.b_gate, m.b_attn}, m.b_attn, g.q_dim());
|
||||
RAD_ARCH_TRY(linear(L.out, l, "blk.%d.attn_output", g.n_embd, g.q_dim(),
|
||||
{ nm.ckpt(a, pre, l, "o_proj.weight") }, m.a_attn, m.b_arm, {}));
|
||||
} else {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
|
||||
const char* c = "%s.layers.%d.conv.%s";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
|
||||
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
|
||||
RAD_ARCH_TRY(linear(L.conv_in, l, "blk.%d.conv_in", 3 * g.n_embd, g.n_embd,
|
||||
{ nm.ckpt(c, pre, l, "in_proj.weight") }, m.a_h, m.b_bcx, {}));
|
||||
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
|
||||
* convert, as LFM2's is. */
|
||||
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
|
||||
L.op_gate_in = mul({m.b_bcx}, m.b_conv_in, g.n_embd);
|
||||
L.op_conv = rw(b, RAD_OP(b, "causal_conv1d",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(L.w_conv)),
|
||||
{m.b_conv_in}, {m.b_conv_out});
|
||||
L.op_gate_out = mul({m.b_bcx, m.b_conv_out}, m.b_conv_out, g.n_embd);
|
||||
RAD_ARCH_TRY(linear(L.conv_out, l, "blk.%d.conv_out", g.n_embd, g.n_embd,
|
||||
{ nm.ckpt(c, pre, l, "out_proj.weight") }, m.a_conv, m.b_arm, {}));
|
||||
}
|
||||
/* the sandwich: the mixer's output is normed before it joins the stream, and the
|
||||
* feed-forward reads the norm of the sum */
|
||||
if (has_join) L.op_join = join(L.w_post_norm, L.w_ffn_norm);
|
||||
if (!L.op_join) {
|
||||
L.op_post_norm = rmsnorm(g.max_tok, g.n_embd, L.w_post_norm, m.b_arm, m.b_arm);
|
||||
L.op_add = add(m.b_x, m.b_arm);
|
||||
L.op_ffn_norm = rmsnorm(g.max_tok, g.n_embd, L.w_ffn_norm, m.b_x, m.b_h);
|
||||
}
|
||||
|
||||
/* ---- the feed-forward */
|
||||
const char* ffn = "%s.layers.%d.feed_forward.%s";
|
||||
RAD_ARCH_TRY(linear(L.gate_up, l, "blk.%d.ffn_gate_up", 2 * g.n_ff, g.n_embd,
|
||||
{ nm.ckpt(ffn, pre, l, "w1.weight"), nm.ckpt(ffn, pre, l, "w3.weight") },
|
||||
m.a_h, m.b_gate_up, { g.n_ff, g.n_ff }));
|
||||
L.op_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_gate_up}, {m.b_ffn});
|
||||
RAD_ARCH_TRY(linear(L.down, l, "blk.%d.ffn_down", g.n_embd, g.n_ff,
|
||||
{ nm.ckpt(ffn, pre, l, "w2.weight") }, m.a_ffn, m.b_arm, {}));
|
||||
if (has_join && l + 1 < (int)m.layers.size())
|
||||
L.op_ffn_join = join(L.w_ffn_post_norm, m.layers[(size_t)l + 1].w_norm);
|
||||
if (!L.op_ffn_join) {
|
||||
L.op_ffn_post_norm = rmsnorm(g.max_tok, g.n_embd, L.w_ffn_post_norm, m.b_arm, m.b_arm);
|
||||
L.op_ffn_add = add(m.b_x, m.b_arm);
|
||||
}
|
||||
n_joins += (L.op_join ? 1 : 0) + (L.op_ffn_join ? 1 : 0);
|
||||
}
|
||||
|
||||
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
|
||||
* lm_head reads. */
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_hout});
|
||||
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, m.b_hout);
|
||||
/* A tied head is the bf16 embedding table: a scored step leaves the final-normed rows in
|
||||
* h_out and the core takes the candidates' logits from the table on the host. */
|
||||
if (meta_bool(meta, "tie_word_embeddings", false))
|
||||
RAD_ARCH_TRY(rad_declare_scores(b, m.b_hout, m.w_tok));
|
||||
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_lm_head)),
|
||||
{m.b_hout}, {m.b_logits});
|
||||
|
||||
int64_t n_full = 0, n_sliding = 0;
|
||||
for (const Layer& L : m.layers) {
|
||||
n_full += L.kind == kFull ? 1 : 0;
|
||||
n_sliding += L.kind == kSliding ? 1 : 0;
|
||||
}
|
||||
rad_note(b, "lfm3: %lld layers, %lld full attention + %lld sliding (window %lld) + %lld short "
|
||||
"convolution of width %lld; %lld heads over %lld at head_dim %lld, ffn %lld, "
|
||||
"vocab %lld",
|
||||
(long long)g.n_layer, (long long)n_full, (long long)n_sliding,
|
||||
(long long)m.sliding.window, (long long)(g.n_layer - n_full - n_sliding),
|
||||
(long long)m.width, (long long)g.n_head, (long long)g.n_head_kv,
|
||||
(long long)g.head_dim, (long long)g.n_ff, (long long)g.n_vocab);
|
||||
rad_note(b, "sandwich joins: %d of %lld fused (norm_add_norm)%s", n_joins,
|
||||
(long long)(2 * g.n_layer - 1),
|
||||
n_joins == 0 ? " -- not served, the rmsnorm / add / rmsnorm chain" : "");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void lin_step(RadCtx* c, const Linear& lin, rad_buf in, rad_buf out, int64_t T) {
|
||||
RAD_ISSUE(c, lin.op, brows(in, T), RAD_W(lin.w), brows(out, T));
|
||||
}
|
||||
|
||||
/* The convolution is issued once per half of the step, as LFM2's is: the decode rows [0, D) with
|
||||
* `num_accepted`, leaving the window in the layout a partly rejected verify reads back from, and
|
||||
* the prefill chunks [D, S) without it, each leaving its tail at offset zero. `has_init` is
|
||||
* `ctx_lens` (a sequence with earlier tokens has a history). The prefill half's per-sequence
|
||||
* arrays start at `+ D`; the token operands stay at their base, since the kernel reads rows at the
|
||||
* absolute offsets in `cu`. */
|
||||
static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch* batch, int l) {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadKVGroupBatch* cv = kv_batch(batch, m.kv_conv);
|
||||
const int32_t* idx = cv ? cv->state_index : nullptr;
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
const int64_t P = S - D;
|
||||
if (D > 0)
|
||||
RAD_ISSUE_N(c, L.op_conv, DT,
|
||||
brows(m.b_conv_in, DT), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1), praw(idx, RAD_I32, D),
|
||||
praw(batch->ctx_lens, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
|
||||
brows(m.b_conv_out, DT));
|
||||
if (P > 0)
|
||||
RAD_ISSUE_N(c, L.op_conv, T,
|
||||
brows(m.b_conv_in, T), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
|
||||
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
praw(idx ? idx + D : nullptr, RAD_I32, P),
|
||||
praw(batch->ctx_lens + D, RAD_I32, P), RAD_NONE,
|
||||
brows(m.b_conv_out, T));
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
if (batch->draft_pass || batch->spec_parent || batch->enc || batch->n_mm_rows > 0) {
|
||||
rad_step_fail(c, "lfm3_bf16: this step asks for an encoder, a draft pass or media rows, "
|
||||
"and the program declares none of them");
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok, n = g.n_embd;
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
const Layer& L = m.layers[(size_t)l];
|
||||
if (!(l > 0 && m.layers[(size_t)l - 1].op_ffn_join))
|
||||
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
|
||||
if (L.kind != kConv) {
|
||||
const rad_kvgroup grp = m.cls(L).kv;
|
||||
const RadKVGroupBatch* kv = kv_batch(batch, grp);
|
||||
L.q.step(c, m.a_h, m.b_q, T);
|
||||
L.k.step(c, m.a_h, m.b_k, T);
|
||||
L.v.step(c, m.a_h, m.b_v, T);
|
||||
lin_step(c, L.gate, m.b_h, m.b_gate, T);
|
||||
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
|
||||
brows(m.b_q, T));
|
||||
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
|
||||
brows(m.b_k, T));
|
||||
RAD_ISSUE(c, L.op_rope_q, brows(m.b_q, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE(c, L.op_rope_k, brows(m.b_k, T), rope_pos1(batch, T));
|
||||
RAD_ISSUE(c, L.op_store, brows(m.b_k, T), brows(m.b_v, T),
|
||||
praw(kv ? kv->slot_mapping : nullptr, RAD_I32, T), kv_cache(grp, l));
|
||||
RAD_ISSUE_N(c, L.op_attn, batch->max_q_len,
|
||||
brows(m.b_q, T), kv_cache(grp, l),
|
||||
praw2(kv ? kv->block_table : nullptr, RAD_I32, batch->n_seq,
|
||||
kv ? kv->block_table_pitch : 0),
|
||||
praw(kv ? kv->seqused : nullptr, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(m.b_attn, T));
|
||||
RAD_ISSUE(c, L.op_sigmoid, brows(m.b_gate, T), brows(m.b_gate, T));
|
||||
RAD_ISSUE(c, L.op_gate_mul, brows(m.b_gate, T), brows(m.b_attn, T), brows(m.b_attn, T));
|
||||
L.out.step(c, m.a_attn, m.b_arm, T);
|
||||
} else {
|
||||
L.conv_in.step(c, m.a_h, m.b_bcx, T);
|
||||
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
|
||||
brows(m.b_conv_in, T));
|
||||
conv_step(m, L, c, batch, l);
|
||||
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
|
||||
brows(m.b_conv_out, T));
|
||||
L.conv_out.step(c, m.a_conv, m.b_arm, T);
|
||||
}
|
||||
if (L.op_join) {
|
||||
RAD_ISSUE(c, L.op_join, brows(m.b_arm, T), RAD_W(L.w_post_norm), brows(m.b_x, T),
|
||||
RAD_W(L.w_ffn_norm), brows(m.b_h, T));
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_post_norm, brows(m.b_arm, T), RAD_W(L.w_post_norm),
|
||||
brows(m.b_arm, T));
|
||||
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_arm, T), brows(m.b_x, T));
|
||||
RAD_ISSUE(c, L.op_ffn_norm, brows(m.b_x, T), RAD_W(L.w_ffn_norm), brows(m.b_h, T));
|
||||
}
|
||||
L.gate_up.step(c, m.a_h, m.b_gate_up, T);
|
||||
RAD_ISSUE(c, L.op_act, brows(m.b_gate_up, T), brows(m.b_ffn, T));
|
||||
L.down.step(c, m.a_ffn, m.b_arm, T);
|
||||
if (L.op_ffn_join) {
|
||||
/* y is the next layer's input norm */
|
||||
RAD_ISSUE(c, L.op_ffn_join, brows(m.b_arm, T), RAD_W(L.w_ffn_post_norm),
|
||||
brows(m.b_x, T), RAD_W(m.layers[(size_t)l + 1].w_norm), brows(m.b_h, T));
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_ffn_post_norm, brows(m.b_arm, T), RAD_W(L.w_ffn_post_norm),
|
||||
brows(m.b_arm, T));
|
||||
RAD_ISSUE(c, L.op_ffn_add, brows(m.b_x, T), brows(m.b_arm, T), brows(m.b_x, T));
|
||||
}
|
||||
}
|
||||
|
||||
/* The lm_head runs only on the rows the sampler asked for; a prefill chunk that finishes no
|
||||
* sequence skips it. */
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_x, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_out_norm), brows(m.b_hout, batch->n_out));
|
||||
if (!batch->score_only)
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace lfm3_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(lfm3_bf16, "lfm3", "", "0.1.0",
|
||||
"LiquidAI LFM3, bf16 or IQ8R: short gated convolutions, full and sliding-window GQA "
|
||||
"attention with a partial rotary and a gate per head, sandwich norms, in the "
|
||||
"checkpoint's own schedule, one rank")
|
||||
#endif
|
||||
Loaded 100 of 1495 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user