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
use crate::{
CubeRuntime, CubeTuneId,
kernel::attention::{AttentionStrategy, attention, bounds::with_attention_bounds},
tensor::CubeTensor,
};
use burn_backend::DType;
use burn_backend::cubecl::{dtype_to_elem_type, dtype_to_storage_type};
use burn_backend::ops::AttentionModuleOptions;
use cubecl::tune::{LocalTuner, Tunable, TunableSet, TuneGroup, local_tuner};
use cubek::attention::forward::{
launch::AttentionAutotuneKey, routines::blackbox_accelerated::BlackboxAcceleratedStrategy,
};
/// Executes autotune on attention operations
pub fn attention_autotune<R: CubeRuntime>(
query: CubeTensor<R>,
key: CubeTensor<R>,
value: CubeTensor<R>,
mask: Option<CubeTensor<R>>,
attn_bias: Option<CubeTensor<R>>,
options: AttentionModuleOptions,
) -> CubeTensor<R> {
let client = query.client.clone();
let accelerated_client = client.clone();
static TUNER: LocalTuner<AttentionAutotuneKey, CubeTuneId> = local_tuner!();
let tunables = TUNER.init(move || {
const PRIORITY_MAX: i8 = 3;
const PRIORITY_MIN: i8 = 0;
let flash_attention =
TuneGroup::<AttentionAutotuneKey>::new("flash_attention", |_key| PRIORITY_MAX);
let fallback = TuneGroup::<AttentionAutotuneKey>::new("fallback", |key| {
// The fallback materializes the full (total_batches, seq_q, seq_kv)
// score matrix, which the flash kernels never allocate — and even
// *benchmarking* it pays that allocation. Let it compete only while
// that matrix is no bigger than an activation the model already
// produces — `[batch, seq_kv, d_model]`, a full-head K/V-sized
// tensor — so it fits a memory budget sized for the model's own
// activations. With `total_batches = batch · heads` and
// `d_model = heads · head_dim`, the bound reduces to
// `seq_q <= head_dim`: decode-like and short-chunk shapes qualify,
// long-prefill shapes never do; for those it is strictly a last
// resort for shapes no flash kernel can run, since an
// O(seq_q · seq_kv) spike can exceed a flash-sized memory budget.
if key.seq_q > key.head_dim {
PRIORITY_MIN
} else {
PRIORITY_MAX
}
});
let mut set = with_attention_bounds(TunableSet::new(create_key::<R>, input_gen::<R>));
// First entry should always work, since it is considered the fallback.
set = set.with(
Tunable::new(
"fallback",
|(query, key, value, mask, attn_bias, options)| {
attention::<R>(
query,
key,
value,
mask,
attn_bias,
options,
AttentionStrategy::Fallback,
)
.map_err(|err| std::format!("{err:?}"))
},
)
.group(&fallback, |_key| PRIORITY_MAX),
);
let seq_q = 1;
let seq_kv = 1;
for num_planes in [2, 4, 8] {
let name = format!("blackbox_accelerated_{num_planes}_planes_p_{seq_q}-{seq_kv}");
let client_accelerated = client.clone();
set = set.with(
Tunable::new(
&name,
move |(query, key, value, mask, attn_bias, options)| {
attention::<R>(
query,
key,
value,
mask,
attn_bias,
options,
AttentionStrategy::FlashBlackboxAccelerated(
BlackboxAcceleratedStrategy {
num_planes,
seq_q,
seq_kv,
},
),
)
.map_err(|err| std::format!("{err:?}"))
},
)
.group(&flash_attention, move |_key| {
// The blackbox routine runs its tile matmuls on f16 fragments whatever the
// problem dtype is, and validates them against the `cmma` feature list, so
// that's what has to be available here — `mma` or `tma` support alone
// wouldn't let the kernel run.
let f16 = dtype_to_storage_type(DType::F16);
let has_accelerated = client_accelerated
.properties()
.features
.matmul
.cmma
.iter()
.any(|config| config.a_type == f16 && config.b_type == f16);
// Unsupported kernels keep the minimum priority rather than being
// discarded, so they remain a last resort and the tune plan can never end
// up empty.
if has_accelerated {
PRIORITY_MAX
} else {
PRIORITY_MIN
}
}),
);
}
set = set.with(
Tunable::new("unit", |(query, key, value, mask, attn_bias, options)| {
attention::<R>(
query,
key,
value,
mask,
attn_bias,
options,
AttentionStrategy::FlashUnit,
)
.map_err(|err| std::format!("{err:?}"))
})
.group(&flash_attention, |_key| PRIORITY_MIN),
);
set
});
TUNER.execute(
&CubeTuneId::new(&accelerated_client, &query.device),
&accelerated_client,
tunables,
(query, key, value, mask, attn_bias, options),
)
}
#[allow(clippy::type_complexity)]
fn create_key<R: CubeRuntime>(
(query, key, value, mask, _attn_bias, _options): &(
CubeTensor<R>,
CubeTensor<R>,
CubeTensor<R>,
Option<CubeTensor<R>>,
Option<CubeTensor<R>>,
AttentionModuleOptions,
),
) -> AttentionAutotuneKey {
let total_batches = query.meta.shape[0] * query.meta.shape[1];
let seq_q = query.meta.shape[2];
let head_dim = query.meta.shape[3];
let seq_kv = value.meta.shape[2];
let val_dim = value.meta.shape[3];
AttentionAutotuneKey::generate(
dtype_to_elem_type(query.dtype),
dtype_to_elem_type(key.dtype),
dtype_to_elem_type(value.dtype),
dtype_to_elem_type(query.dtype),
total_batches,
seq_q,
head_dim,
seq_kv,
val_dim,
mask.is_some(),
)
}
#[allow(clippy::type_complexity)]
fn input_gen<R: CubeRuntime>(
_key: &AttentionAutotuneKey,
(query, key, value, mask, attn_bias, options): &(
CubeTensor<R>,
CubeTensor<R>,
CubeTensor<R>,
Option<CubeTensor<R>>,
Option<CubeTensor<R>>,
AttentionModuleOptions,
),
) -> (
CubeTensor<R>,
CubeTensor<R>,
CubeTensor<R>,
Option<CubeTensor<R>>,
Option<CubeTensor<R>>,
AttentionModuleOptions,
) {
(
query.clone(),
key.clone(),
value.clone(),
mask.clone(),
attn_bias.clone(),
*options,
)
}