Repository navigation
Expand file tree
/
Copy pathtune.rs
More file actions
2880 lines (2780 loc) · 114 KB
/
Copy pathtune.rs
File metadata and controls
2880 lines (2780 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Bounded, opt-in kernel selection. See [`crate::Session::tune_with`].
//!
//! The search space is deliberately small: scalar and native-f32 cooperative
//! tiles for unpacked dense matmuls, typed subgroup/workgroup tiles and K
//! partitions, shape-specialized scalar convolutions,
//! workgroup geometry and cross-lane reduction for the K-split GEMV family, and
//! cached-attention split/combine sequences. Precision remains unchanged.
//! Measurements use synthetic, private scratch, not a live training step.
//! Explicit split-K probes measure complete sequences without installing them.
//! Scalar tile and GEMV shape changes leave packed-weight decoding intact, so
//! reduced-storage kernels participate without changing their arithmetic.
use crate::codegen::CoopConfig;
use crate::compile::{Dispatch, ShaderEntry};
use serde::{Deserialize, Serialize};
use std::time::Duration;
/// Complete key within the supported contiguous-row-major, non-aliasing domain.
/// No winner is transferred between shapes, directions, or memory placements.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TuneClass {
pub shader: ShaderEntry,
pub m: u32,
pub n: u32,
pub k: u32,
/// Physical NCHW convolution contract; absent for dense matrices.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conv2d: Option<TuneConv2d>,
pub requires_full_precision: bool,
/// Storage format of B. Part of the key because it changes both the
/// kernel and the bytes behind the binding, so no winner transfers
/// between an f32 weight and a packed one of the same extents.
#[serde(default)]
pub weight_format: crate::compile::WeightFormat,
/// The dispatch quantizes its activation and uses integer dot products.
///
/// Part of the key even though the weight format is already here,
/// because the format no longer identifies the kernel: an ordinary Q4_0
/// GEMV and an activation-quantized one of the same extents read the same
/// bytes and compute different things. Coalescing them would measure the
/// first member's variants and install the winner on both, leaving the
/// other with a shape it has no pipeline for.
#[serde(default)]
pub gemv_int_dot: bool,
/// RmsNorm is folded into this GEMV. A different kernel (second
/// reduction + extra binding), so winners do not transfer from the
/// unfused class of the same extents.
#[serde(default)]
pub gemv_rmsnorm: bool,
/// `f32::to_bits` of the folded norm's epsilon. Ignored unless
/// [`Self::gemv_rmsnorm`].
#[serde(default)]
pub gemv_rmsnorm_eps_bits: u32,
/// The output holds K partitions that a following SumRows adds. Such a
/// product keeps its reduction: candidates write two or more partitions
/// into the partial buffer, whose size is the output binding's.
#[serde(default)]
pub split_k: bool,
/// Operand, multiplication and output types of a checked typed product.
/// Part of the key: they change the kernel and the bytes behind each
/// binding, so no winner transfers between precisions.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub matrix_types: Option<crate::codegen::MatrixTypes>,
/// Automatic F32 storage with F16 multiplication, already permitted by
/// the session policy. Separate from explicit types for cache fallback.
#[serde(default)]
pub cooperative_f16: bool,
/// Placement of A, B, addend (false if absent), and output, respectively.
pub device_local: [bool; 4],
/// Declared bytes for A, B, optional addend, output, in binding order.
/// Candidates cannot borrow unused capacity from an aliased allocation.
pub binding_bytes: Vec<usize>,
}
/// Exact convolution shape, including both spatial padding dimensions.
/// Small and large scalar tiles share this key, but directions never do.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TuneConv2d {
pub batch: u32,
pub in_channels: u32,
pub in_h: u32,
pub in_w: u32,
pub out_channels: u32,
pub kernel_h: u32,
pub kernel_w: u32,
pub stride: u32,
pub padding_h: u32,
pub out_h: u32,
pub out_w: u32,
pub padding_w: u32,
}
impl TuneConv2d {
fn from_params(params: &[u32]) -> Option<Self> {
let &[
batch,
in_channels,
in_h,
in_w,
out_channels,
kernel_h,
kernel_w,
stride,
padding_h,
out_h,
out_w,
padding_w,
] = params
else {
return None;
};
let shape = Self {
batch,
in_channels,
in_h,
in_w,
out_channels,
kernel_h,
kernel_w,
stride,
padding_h,
out_h,
out_w,
padding_w,
};
if [
batch,
in_channels,
in_h,
in_w,
out_channels,
kernel_h,
kernel_w,
stride,
out_h,
out_w,
]
.contains(&0)
|| stride > i32::MAX as u32
{
return None;
}
for (input, kernel, padding, output) in [
(in_h, kernel_h, padding_h, out_h),
(in_w, kernel_w, padding_w, out_w),
] {
let padded = input.checked_add(padding.checked_mul(2)?)?;
// Both gather directions convert coordinates to signed shader integers.
if padded > i32::MAX as u32
|| kernel > i32::MAX as u32
|| padded
.checked_sub(kernel)?
.checked_div(stride)?
.checked_add(1)?
!= output
{
return None;
}
}
shape.elements()?;
Some(shape)
}
/// Input, weight, upstream gradient: physical elements, not an im2col matrix.
fn elements(self) -> Option<[u32; 3]> {
Some([
self.batch
.checked_mul(self.in_channels)?
.checked_mul(self.in_h)?
.checked_mul(self.in_w)?,
self.out_channels
.checked_mul(self.in_channels)?
.checked_mul(self.kernel_h)?
.checked_mul(self.kernel_w)?,
self.batch
.checked_mul(self.out_channels)?
.checked_mul(self.out_h)?
.checked_mul(self.out_w)?,
])
}
}
/// The GEMV group a shader entry belongs to, if any.
pub(crate) fn gemv_group(entry: &ShaderEntry) -> Option<crate::codegen::ShaderGroup> {
use crate::codegen::ShaderGroup;
match *entry {
ShaderEntry::MatMulGemv => Some(ShaderGroup::MatMulGemv),
ShaderEntry::MatMulGemvAdd => Some(ShaderGroup::MatMulGemvAdd),
ShaderEntry::MatMulGemvBT => Some(ShaderGroup::MatMulGemvBT),
ShaderEntry::MatMulGemvBTAdd => Some(ShaderGroup::MatMulGemvBTAdd),
_ => None,
}
}
/// Implementations with identical bindings and logical extents.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MatmulTile {
Tile16,
Tile32,
Tile64,
Scalar(crate::codegen::ScalarMatmulShape),
/// Scalar convolution with immutable parameters and native integer division.
/// Spatial tiles, K-stage sizes and column assignment are measured.
SpecializedConv {
tile_size: u32,
k_tile: u32,
/// Give adjacent lanes adjacent columns of the register tile.
#[serde(default)]
interleave_columns: bool,
},
/// Hardware-native f32 operands/accumulators, never f16 staging.
CooperativeF32 {
tile_size: u32,
},
CooperativeF16 {
tile_size: u32,
},
CooperativeWorkgroup {
shape: crate::codegen::WorkgroupMatmulShape,
splits: u32,
},
/// Aligned native 16x16 f32 products sharing a larger workgroup tile.
/// More than one K partition writes partials that a following SumRows
/// adds, which only a split product has.
CooperativeTiled {
shape: crate::codegen::CooperativeMatmulShape,
splits: u32,
},
/// Checked typed cooperative tiles at a K partition count. The class key
/// holds the types. More than one partition writes F32 partials that a
/// following SumRows adds, which only a split product has.
CooperativeChecked {
splits: u32,
},
/// A K-split GEMV at one workgroup width and cross-lane reduction.
///
/// Keeps the shader entry and buffer layout. Width and reduction apply
/// to every storage format; contiguous row grouping also changes the
/// workgroup count for transposed-B kernels.
Gemv(crate::codegen::GemvShape),
}
fn conv_launched_tile(shader: &ShaderEntry) -> Option<u32> {
match *shader {
ShaderEntry::Conv2dGemm16
| ShaderEntry::Conv2dGradInputGemm16
| ShaderEntry::Conv2dGradWeightGemm16
| ShaderEntry::Conv2dGradWeightGemmSplit16 => Some(16),
ShaderEntry::Conv2dGemmSmall
| ShaderEntry::Conv2dGradInputGemmSmall
| ShaderEntry::Conv2dGradWeightGemmSmall
| ShaderEntry::Conv2dGradWeightGemmSplitSmall => Some(32),
ShaderEntry::Conv2dGemm
| ShaderEntry::Conv2dGradInputGemm
| ShaderEntry::Conv2dGradWeightGemm
| ShaderEntry::Conv2dGradWeightGemmSplit => Some(64),
_ => None,
}
}
fn conv_tile_entry(entry: &ShaderEntry, tile: u32) -> Option<ShaderEntry> {
let split = matches!(
*entry,
ShaderEntry::Conv2dGradWeightGemmSplit
| ShaderEntry::Conv2dGradWeightGemmSplitSmall
| ShaderEntry::Conv2dGradWeightGemmSplit16
);
enum Family {
Basic,
Input,
Weight,
}
let family = match *entry {
ShaderEntry::Conv2dGemm | ShaderEntry::Conv2dGemmSmall | ShaderEntry::Conv2dGemm16 => {
Family::Basic
}
ShaderEntry::Conv2dGradInputGemm
| ShaderEntry::Conv2dGradInputGemmSmall
| ShaderEntry::Conv2dGradInputGemm16 => Family::Input,
ShaderEntry::Conv2dGradWeightGemm
| ShaderEntry::Conv2dGradWeightGemmSmall
| ShaderEntry::Conv2dGradWeightGemm16
| ShaderEntry::Conv2dGradWeightGemmSplit
| ShaderEntry::Conv2dGradWeightGemmSplitSmall
| ShaderEntry::Conv2dGradWeightGemmSplit16 => Family::Weight,
_ => return None,
};
Some(match (family, split, tile) {
(Family::Basic, _, 16) => ShaderEntry::Conv2dGemm16,
(Family::Basic, _, 32) => ShaderEntry::Conv2dGemmSmall,
(Family::Basic, _, _) => ShaderEntry::Conv2dGemm,
(Family::Input, _, 16) => ShaderEntry::Conv2dGradInputGemm16,
(Family::Input, _, 32) => ShaderEntry::Conv2dGradInputGemmSmall,
(Family::Input, _, _) => ShaderEntry::Conv2dGradInputGemm,
(Family::Weight, false, 16) => ShaderEntry::Conv2dGradWeightGemm16,
(Family::Weight, false, 32) => ShaderEntry::Conv2dGradWeightGemmSmall,
(Family::Weight, false, _) => ShaderEntry::Conv2dGradWeightGemm,
(Family::Weight, true, 16) => ShaderEntry::Conv2dGradWeightGemmSplit16,
(Family::Weight, true, 32) => ShaderEntry::Conv2dGradWeightGemmSplitSmall,
(Family::Weight, true, _) => ShaderEntry::Conv2dGradWeightGemmSplit,
})
}
impl MatmulTile {
pub(crate) fn native_cooperative(config: Option<&CoopConfig>) -> Option<Self> {
let config = config?;
if config.use_f16_input || config.compensated || !matches!(config.tile_size, 8 | 16) {
return None;
}
Some(Self::CooperativeF32 {
tile_size: config.tile_size,
})
}
pub(crate) fn selected(dispatch: &Dispatch, config: Option<&CoopConfig>) -> Option<Self> {
use crate::compile::Kernel;
let small = dispatch.use_small_tiles();
if let Some(group) = gemv_group(&dispatch.shader) {
match dispatch.kernel {
Kernel::Default => Some(Self::Gemv(crate::codegen::GemvShape::initial(group))),
Kernel::Gemv { shape, .. } => Some(Self::Gemv(shape)),
_ => None,
}
} else if let Some(launched) = conv_launched_tile(&dispatch.shader) {
match dispatch.kernel {
Kernel::Default | Kernel::SmallTile => Some(match launched {
16 => Self::Tile16,
32 => Self::Tile32,
_ => Self::Tile64,
}),
Kernel::SpecializedConv {
k_tile,
interleave_columns,
} => Some(Self::SpecializedConv {
tile_size: launched,
k_tile,
interleave_columns,
}),
Kernel::Cooperative => Self::native_cooperative(config),
_ => None,
}
} else {
match dispatch.kernel {
Kernel::Default | Kernel::SmallTile => {
Some(if small { Self::Tile32 } else { Self::Tile64 })
}
Kernel::ScalarMatmul(shape) => Some(Self::Scalar(shape)),
Kernel::SpecializedConv {
k_tile,
interleave_columns,
} => Some(Self::SpecializedConv {
tile_size: if small { 32 } else { 64 },
k_tile,
interleave_columns,
}),
Kernel::Cooperative => config
.filter(|c| c.use_f16_input && !c.compensated)
.map(|c| Self::CooperativeF16 {
tile_size: c.tile_size,
})
.or_else(|| Self::native_cooperative(config)),
Kernel::CooperativeWorkgroup { shape, splits, .. } => {
Some(Self::CooperativeWorkgroup { shape, splits })
}
Kernel::CooperativeTiled { shape, splits }
if config.is_some_and(|c| {
c.tile_size == 16 && !c.use_f16_input && !c.compensated
}) =>
{
Some(Self::CooperativeTiled { shape, splits })
}
Kernel::CooperativeTyped { splits, .. } => {
Some(Self::CooperativeChecked { splits })
}
_ => None,
}
}
}
pub(crate) fn coop_config(self) -> Option<CoopConfig> {
match self {
Self::CooperativeF16 { tile_size } => Some(CoopConfig {
tile_size,
use_f16_input: true,
compensated: false,
}),
Self::CooperativeTiled { .. } => Some(CoopConfig {
tile_size: 16,
use_f16_input: false,
compensated: false,
}),
Self::CooperativeF32 { tile_size } => Some(CoopConfig {
tile_size,
use_f16_input: false,
compensated: false,
}),
_ => None,
}
}
pub(crate) fn apply(self, dispatch: &mut Dispatch, class: &TuneClass) {
self.configure(dispatch);
dispatch.workgroups = self.workgroups(class);
}
/// K partitions a split tile writes for its SumRows; `None` when unsplit.
pub(crate) fn partitions(self) -> Option<u32> {
match self {
Self::CooperativeTiled { splits, .. }
| Self::CooperativeWorkgroup { splits, .. }
| Self::CooperativeChecked { splits } => Some(splits),
_ => None,
}
}
/// Kernels whose measured-to-predicted ratio is shared across classes.
pub(crate) fn family(self) -> TileFamily {
match self {
Self::Tile16
| Self::Tile32
| Self::Tile64
| Self::Scalar(_)
| Self::SpecializedConv { .. } => TileFamily::Scalar,
Self::CooperativeF32 { .. }
| Self::CooperativeF16 { .. }
| Self::CooperativeWorkgroup { .. }
| Self::CooperativeTiled { .. }
| Self::CooperativeChecked { .. } => TileFamily::Cooperative,
Self::Gemv(_) => TileFamily::Gemv,
}
}
pub(crate) fn configure(self, dispatch: &mut Dispatch) {
if let Self::CooperativeWorkgroup { shape, splits } = self {
let types = match dispatch.kernel {
crate::compile::Kernel::CooperativeTyped { types, .. } => Some(types),
crate::compile::Kernel::CooperativeWorkgroup { types, .. } => types,
_ => None,
};
dispatch.kernel = crate::compile::Kernel::CooperativeWorkgroup {
shape,
types,
splits,
};
return;
}
if let Self::CooperativeChecked { splits } = self {
let types = match dispatch.kernel {
crate::compile::Kernel::CooperativeTyped { types, .. }
| crate::compile::Kernel::CooperativeWorkgroup {
types: Some(types), ..
} => types,
_ => unreachable!("checked tiles apply to typed products"),
};
dispatch.kernel = crate::compile::Kernel::CooperativeTyped { types, splits };
return;
}
if let Self::Gemv(shape) = self {
dispatch.kernel = crate::compile::Kernel::Gemv {
shape,
integer_dot: dispatch.gemv_int_dot(),
};
return;
}
dispatch.shader = self.shader(&dispatch.shader);
dispatch.kernel = match self {
Self::Tile16 => crate::compile::Kernel::Default,
Self::Tile32
if !matches!(
dispatch.shader,
ShaderEntry::Conv2dGemmSmall
| ShaderEntry::Conv2dGradInputGemmSmall
| ShaderEntry::Conv2dGradWeightGemmSmall
) =>
{
crate::compile::Kernel::SmallTile
}
Self::Tile32 | Self::Tile64 => crate::compile::Kernel::Default,
Self::Scalar(shape) => crate::compile::Kernel::ScalarMatmul(shape),
Self::CooperativeF32 { .. } | Self::CooperativeF16 { .. } => {
crate::compile::Kernel::Cooperative
}
Self::CooperativeTiled { shape, splits } => {
crate::compile::Kernel::CooperativeTiled { shape, splits }
}
Self::SpecializedConv {
k_tile,
interleave_columns,
..
} => crate::compile::Kernel::SpecializedConv {
k_tile,
interleave_columns,
},
Self::Gemv(_) | Self::CooperativeChecked { .. } | Self::CooperativeWorkgroup { .. } => {
unreachable!()
}
};
}
pub(crate) fn shader(self, entry: &ShaderEntry) -> ShaderEntry {
let tile = match self {
Self::Tile16 | Self::SpecializedConv { tile_size: 16, .. } => 16,
Self::Tile32 | Self::SpecializedConv { tile_size: 32, .. } => 32,
Self::Tile64 | Self::SpecializedConv { tile_size: 64, .. } => 64,
Self::SpecializedConv { tile_size, .. } => tile_size,
_ => return entry.clone(),
};
conv_tile_entry(entry, tile).unwrap_or_else(|| entry.clone())
}
pub(crate) fn workgroups(self, class: &TuneClass) -> [u32; 3] {
let tile = match self {
Self::Gemv(shape) => return class.gemv_workgroups(shape),
Self::Tile16 => 16,
Self::Tile32 => 32,
Self::Tile64 => 64,
Self::Scalar(shape) => {
return [
class.n.div_ceil(shape.cols()),
class.m.div_ceil(shape.rows()),
class.batch_dispatches(),
];
}
Self::SpecializedConv { tile_size, .. } => tile_size,
Self::CooperativeTiled { shape, splits } => {
return [class.m / 64, class.n / shape.columns, splits];
}
Self::CooperativeWorkgroup { shape, splits } => {
return [class.m / shape.rows, class.n / shape.columns, splits];
}
// Checked tiles use X for rows, Y for columns, over 32x32 blocks.
Self::CooperativeChecked { splits } => {
return [class.m.div_ceil(32), class.n.div_ceil(32), splits];
}
Self::CooperativeF32 { .. } | Self::CooperativeF16 { .. } => {
let tile = self.coop_config().unwrap().matmul_output_tile();
// Cooperative tiles use X for rows, Y for columns.
return [class.m.div_ceil(tile), class.n.div_ceil(tile), 1];
}
};
// Scalar tiled kernels use X for columns, Y for rows. Derive exact
// geometry; doubling rounded 64-tile counts overdispatches edges.
[
class.n.div_ceil(tile),
class.m.div_ceil(tile),
class.batch_dispatches(),
]
}
pub(crate) fn buffer_sizes(self, class: &TuneClass) -> Option<Vec<usize>> {
if let Self::CooperativeWorkgroup { shape, splits } = self {
let types = class.effective_matrix_types()?;
if !matches!(types.multiply, crate::DType::F16 | crate::DType::BF16)
|| class.conv2d.is_some()
|| !class.shader.is_matmul()
|| class.weight_format != crate::compile::WeightFormat::F32
|| !shape.fits(class.m, class.n, class.k)
|| splits == 0
|| splits > class.k / shape.k_stage
|| (splits > 1) != class.split_k
|| (splits > 1 && (class.has_addend() || types.output != crate::DType::F32))
{
return None;
}
let mut sizes = class.buffer_sizes()?;
*sizes.last_mut()? = sizes.last()?.checked_mul(splits as usize)?;
return crate::compile::workgroups_within_portable_limits(self.workgroups(class))
.then_some(sizes);
}
if matches!(self, Self::CooperativeF16 { .. }) != class.cooperative_f16 {
return None;
}
if let Some(types) = class.matrix_types {
// Workgroup candidates were handled above; subgroup candidates
// preserve storage too, with F32 partials when split.
let Self::CooperativeChecked { splits } = self else {
return None;
};
if splits == 0
|| (splits > 1) != class.split_k
|| (splits > 1
&& (splits > class.k.div_ceil(32)
|| class.has_addend()
|| types.output != crate::DType::F32))
{
return None;
}
let mut sizes = class.buffer_sizes()?;
*sizes.last_mut()? = sizes.last()?.checked_mul(splits as usize)?;
return crate::compile::workgroups_within_portable_limits(self.workgroups(class))
.then_some(sizes);
}
if matches!(self, Self::CooperativeChecked { .. })
|| (class.split_k && !matches!(self, Self::CooperativeTiled { .. }))
{
return None;
}
if let Self::Scalar(shape) = self {
if class.conv2d.is_some()
|| gemv_group(&class.shader).is_some()
|| class.weight_format.is_quantized()
|| !shape.legal()
{
return None;
}
}
if let Self::Gemv(shape) = self {
if gemv_group(&class.shader).is_none()
|| !matches!(shape.threads, 32 | 64 | 128 | 256)
|| !matches!(shape.bt_rows, 1 | 2 | 4)
|| !shape.valid_columns()
|| (shape.column_groups > 1
&& (!matches!(
class.shader,
ShaderEntry::MatMulGemv | ShaderEntry::MatMulGemvAdd
) || !matches!(
class.weight_format,
crate::compile::WeightFormat::F32 | crate::compile::WeightFormat::F16
)))
{
return None;
}
let sizes = class.buffer_sizes()?;
// The default forward GEMV workgroup count is N/4.
// Vocab-width decode (N=262144) needs 65536 groups — one past the
// Vulkan *minimum* maxComputeWorkGroupCount. The live plan already
// dispatches that on devices that advertise more; applying the
// portable 65535 cap here would drop the kernel that dominates
// Gemma 4 logits from `tune_with`.
if self.workgroups(class).contains(&0) {
return None;
}
return Some(sizes);
}
if let Self::SpecializedConv {
tile_size, k_tile, ..
} = self
{
if class.conv2d.is_none()
|| !matches!(tile_size, 16 | 32 | 64)
|| !matches!(k_tile, 16 | 32)
{
return None;
}
}
let mut sizes = class.buffer_sizes()?;
if let Self::CooperativeTiled { shape, splits } = self {
if class.conv2d.is_some()
|| !class.shader.is_matmul()
|| class.weight_format != crate::compile::WeightFormat::F32
|| !shape.fits_dimensions(class.m, class.n, class.k)
|| splits == 0
|| splits > class.k / shape.k_stage
|| (splits > 1) != class.split_k
{
return None;
}
// Each partition writes a whole output of partial sums.
*sizes.last_mut()? = sizes.last()?.checked_mul(splits as usize)?;
}
if let Self::CooperativeF32 { tile_size } | Self::CooperativeF16 { tile_size } = self {
use crate::kernels::matmul;
if class.conv2d.is_some() || !matches!(tile_size, 8 | 16) {
return None;
}
let problem = matmul::Problem::plain(
matmul::Layout::of(class.shader.shader_group())?,
[class.m, class.n, class.k],
class.weight_format.uses_reduced_storage(),
);
// The same legality session construction applies.
let geometry = matmul::cooperative_geometry(&problem, &self.coop_config()?).ok()?;
*sizes.last_mut()? = geometry.output_bytes;
if geometry.pad_addend {
sizes[2] = geometry.output_bytes;
}
}
if !crate::compile::workgroups_within_portable_limits(self.workgroups(class)) {
return None;
}
Some(sizes)
}
pub(crate) fn fits(self, class: &TuneClass) -> bool {
let Some(sizes) = self.buffer_sizes(class) else {
return false;
};
sizes.len() == class.binding_bytes.len()
&& sizes
.iter()
.zip(&class.binding_bytes)
.all(|(required, available)| required <= available)
}
}
impl TuneClass {
pub(crate) fn effective_matrix_types(&self) -> Option<crate::codegen::MatrixTypes> {
self.matrix_types.or_else(|| {
self.cooperative_f16
.then_some(crate::codegen::MatrixTypes::F32_AS_F16)
})
}
pub(crate) fn from_dispatch(dispatch: &Dispatch, config: Option<&CoopConfig>) -> Option<Self> {
let addend = matches!(
dispatch.shader,
ShaderEntry::FusedMatMulAdd
| ShaderEntry::FusedMatMulATAdd
| ShaderEntry::FusedMatMulBTAdd
| ShaderEntry::MatMulGemvAdd
| ShaderEntry::MatMulGemvBTAdd
);
if !matches!(
dispatch.shader,
ShaderEntry::MatMul
| ShaderEntry::FusedMatMulAdd
| ShaderEntry::MatMulAT
| ShaderEntry::MatMulBT
| ShaderEntry::FusedMatMulATAdd
| ShaderEntry::FusedMatMulBTAdd
| ShaderEntry::MatMulGemv
| ShaderEntry::MatMulGemvAdd
| ShaderEntry::MatMulGemvBT
| ShaderEntry::MatMulGemvBTAdd
| ShaderEntry::Conv2dGemm
| ShaderEntry::Conv2dGemmSmall
| ShaderEntry::Conv2dGemm16
| ShaderEntry::Conv2dGradInputGemm
| ShaderEntry::Conv2dGradInputGemmSmall
| ShaderEntry::Conv2dGradInputGemm16
| ShaderEntry::Conv2dGradWeightGemm
| ShaderEntry::Conv2dGradWeightGemmSmall
| ShaderEntry::Conv2dGradWeightGemm16
) || dispatch.use_coop_compensated()
|| (dispatch.use_coop() && dispatch.weight_format.uses_reduced_storage())
|| dispatch.horizontal_batch >= 2
|| dispatch.matmul_prologue.is_some()
|| dispatch.matmul_epilogue.is_some()
|| !dispatch.extra_outputs.is_empty()
|| dispatch.pointwise().is_some()
|| dispatch.reduction().is_some()
|| dispatch.input_buffers.len() != if addend { 3 } else { 2 }
|| dispatch.schedule_locked
{
return None;
}
// Tiled and typed products dispatch one Z layer per K partition.
let (partitions, matrix_types) = match dispatch.kernel {
crate::compile::Kernel::CooperativeTiled { splits, .. } => (splits, None),
crate::compile::Kernel::CooperativeTyped { types, splits } => (splits, Some(types)),
crate::compile::Kernel::CooperativeWorkgroup { types, splits, .. } => (splits, types),
_ => (1, None),
};
let shader = match dispatch.shader {
ShaderEntry::Conv2dGemmSmall | ShaderEntry::Conv2dGemm16 => ShaderEntry::Conv2dGemm,
ShaderEntry::Conv2dGradInputGemmSmall | ShaderEntry::Conv2dGradInputGemm16 => {
ShaderEntry::Conv2dGradInputGemm
}
ShaderEntry::Conv2dGradWeightGemmSmall | ShaderEntry::Conv2dGradWeightGemm16 => {
ShaderEntry::Conv2dGradWeightGemm
}
_ => dispatch.shader.clone(),
};
let conv2d = if matches!(
shader,
ShaderEntry::Conv2dGemm
| ShaderEntry::Conv2dGradInputGemm
| ShaderEntry::Conv2dGradWeightGemm
) {
if dispatch.use_coop()
|| dispatch.use_small_tiles()
|| dispatch.weight_format.uses_reduced_storage()
{
return None;
}
Some(TuneConv2d::from_params(&dispatch.params)?)
} else {
if dispatch.conv_k_tile().is_some()
|| dispatch.workgroups[2] != partitions
|| dispatch.params.len() != 4
|| dispatch.params[3] != 0
{
return None;
}
None
};
let (m, n, k) = if let Some(s) = conv2d {
let kernel = s.kernel_h.checked_mul(s.kernel_w)?;
if shader == ShaderEntry::Conv2dGemm {
(
s.out_channels,
s.out_h.checked_mul(s.out_w)?,
s.in_channels.checked_mul(kernel)?,
)
} else if shader == ShaderEntry::Conv2dGradInputGemm {
let n = s.in_h.checked_mul(s.in_w)?;
let k = s.out_channels.checked_mul(kernel)?;
(s.in_channels, n, k)
} else {
let n = s.in_channels.checked_mul(kernel)?;
let spatial = s.out_h.checked_mul(s.out_w)?;
let k = s.batch.checked_mul(spatial)?;
(s.out_channels, n, k)
}
} else if matches!(
shader,
ShaderEntry::MatMul
| ShaderEntry::FusedMatMulAdd
// The forward GEMV pair carries `[m, k, n]` like the tiled
// forward matmul; only the transposed form is `[m, n, k]`.
| ShaderEntry::MatMulGemv
| ShaderEntry::MatMulGemvAdd
) {
(dispatch.params[0], dispatch.params[2], dispatch.params[1])
} else {
(dispatch.params[0], dispatch.params[1], dispatch.params[2])
};
// Scalar K loops advance by at most 32, including the final padded tile.
if m == 0
|| n == 0
|| k == 0
|| k > u32::MAX - 31
|| m.div_ceil(32) > 65_535
|| n.div_ceil(32) > 65_535
{
return None;
}
let class = Self {
shader,
m,
n,
k,
conv2d,
requires_full_precision: dispatch.requires_full_precision,
weight_format: dispatch.weight_format,
gemv_int_dot: dispatch.gemv_int_dot(),
gemv_rmsnorm: dispatch.gemv_rmsnorm.is_some(),
gemv_rmsnorm_eps_bits: dispatch
.gemv_rmsnorm
.as_ref()
.map(|rn| rn.eps_bits)
.unwrap_or(0),
split_k: partitions > 1,
matrix_types,
cooperative_f16: matches!(
dispatch.kernel,
crate::compile::Kernel::CooperativeWorkgroup { types: None, .. }
) || (dispatch.kernel == crate::compile::Kernel::Cooperative
&& config.is_some_and(|c| c.use_f16_input && !c.compensated)),
device_local: [false; 4],
binding_bytes: Vec::new(),
};
let initial = MatmulTile::selected(dispatch, config)?;
// A packed B's byte count comes from the plan, and the caller fills
// `binding_bytes` in after this returns, so its extents cannot be
// checked here. `collect_classes` settles them with `fits` once the
// bytes are known; the geometry check below still applies to every
// class.
let extents_derivable = !class.weight_format.uses_reduced_storage();
((!extents_derivable || initial.buffer_sizes(&class).is_some())
&& dispatch.workgroups == initial.workgroups(&class))
.then_some(class)
}
pub(crate) fn has_addend(&self) -> bool {
matches!(
self.shader,
ShaderEntry::FusedMatMulAdd
| ShaderEntry::FusedMatMulATAdd
| ShaderEntry::FusedMatMulBTAdd
| ShaderEntry::MatMulGemvAdd
| ShaderEntry::MatMulGemvBTAdd
)
}
pub(crate) fn batch_dispatches(&self) -> u32 {
if matches!(
self.shader,
ShaderEntry::Conv2dGemm | ShaderEntry::Conv2dGradInputGemm
) {
self.conv2d.expect("convolution class").batch
} else {
1
}
}
pub(crate) fn output_elements(&self) -> usize {
self.m as usize * self.n as usize * self.batch_dispatches() as usize
}
/// Predicted milliseconds of one member dispatch running `tile`, scaled by
/// a measured-to-predicted `correction` for the tile's family.
pub(crate) fn predict_ms(
&self,
profile: &MachineProfile,
tile: MatmulTile,
correction: f64,
) -> Option<f64> {
let flops = 2.0
* f64::from(self.m)
* f64::from(self.n)
* f64::from(self.k)
* f64::from(self.batch_dispatches());
let bytes = self.binding_bytes.iter().sum::<usize>() as f64;
let workgroups = tile
.workgroups(self)
.iter()
.map(|&count| u64::from(count))
.product();
profile
.predict_ms(flops, bytes, workgroups, None)
.map(|ms| ms * correction)
}
/// A, B, optional addend, output sizes. Reject u32 shader-index overflow,
/// not just host allocation overflow.
pub(crate) fn buffer_sizes(&self) -> Option<Vec<usize>> {
let bytes = |a: u32, b: u32| usize::try_from(a.checked_mul(b)?).ok()?.checked_mul(4);
if let Some(types) = self.matrix_types {
// Logical extents: an odd count of halfwords is not word-padded.
let typed = |a: u32, b: u32, ty| {
usize::try_from(a.checked_mul(b)?)
.ok()?
.checked_mul(crate::codegen::MatrixTypes::bytes(ty))
};
let mut sizes = vec![
typed(self.m, self.k, types.a)?,
typed(self.k, self.n, types.b)?,
];
if self.has_addend() {
sizes.push(bytes(self.m, self.n)?);
}
sizes.push(typed(self.m, self.n, types.output)?);
return Some(sizes);
}
if let Some(s) = self.conv2d {
let [input, weight, upstream] = s.elements()?;
if self.shader == ShaderEntry::Conv2dGemm {
return Some(vec![
bytes(input, 1)?,
bytes(weight, 1)?,
bytes(upstream, 1)?,
]);
}
let (b, output) = if self.shader == ShaderEntry::Conv2dGradInputGemm {
(weight, input)
} else {
(input, weight)
};
return Some(vec![bytes(upstream, 1)?, bytes(b, 1)?, bytes(output, 1)?]);
}
// A packed B holds blocks, not a `k * n` f32 grid, so its byte count
// comes from the plan rather than the extents. Everything else in the
// class is still f32 and still derived.
let b_bytes = if self.weight_format.uses_reduced_storage() {
*self.binding_bytes.get(1)?
} else {
bytes(self.k, self.n)?
};
let mut sizes = vec![bytes(self.m, self.k)?, b_bytes];
if self.gemv_rmsnorm {
sizes.push(bytes(self.m, self.k)?);
}
if self.has_addend() {
sizes.push(bytes(self.m, self.n)?);
}
sizes.push(bytes(self.m, self.n)?);
Some(sizes)
}
/// Workgroups per output vec4, or per group of transposed B rows.
pub(crate) fn gemv_workgroups(&self, shape: crate::codegen::GemvShape) -> [u32; 3] {
if matches!(
self.shader,
ShaderEntry::MatMulGemvBT | ShaderEntry::MatMulGemvBTAdd
) {
crate::compile::row_gemv_workgroups(self.n.div_ceil(shape.bt_rows))
} else {
crate::compile::gemv_workgroups(self.n, shape)
}
}
/// A bounded tournament over scalar layouts and native f32 where it fits.
/// Capability/precision/padding are legality;
/// occupancy and the static large-shape veto do not exclude candidates.
pub(crate) fn challengers(
&self,
initial: MatmulTile,
config: Option<&CoopConfig>,
) -> Vec<MatmulTile> {
if let MatmulTile::Gemv(shape) = initial {
use crate::codegen::{GemvReduction, GemvShape};
let mut out = Vec::new();
for column_groups in [4, 8] {
out.push(MatmulTile::Gemv(GemvShape {
threads: 32,
reduction: GemvReduction::Tree,
bt_rows: 1,
column_groups,
}));