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
//! Bounded validated pipeline cache for portable wgpu tensor kernels.
use std::collections::VecDeque;
use std::sync::Arc;
use sim_kernel::Symbol;
use crate::{WgpuAdapterProbe, kernels::kernel_wgsl_for_op};
/// Portable operation implemented by a wgpu tensor kernel.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WgpuKernelOp {
/// Element-wise addition.
Add,
/// Element-wise subtraction.
Sub,
/// Element-wise multiplication.
Mul,
/// Element-wise division.
Div,
/// Element-wise negation.
Neg,
/// Element-wise square root.
Sqrt,
/// Element-wise exponential.
Exp,
/// Element-wise natural logarithm.
Log,
/// Element-wise sine.
Sin,
/// Element-wise cosine.
Cos,
/// Whole-tensor sum reduction.
Sum,
/// Whole-tensor minimum reduction.
Min,
/// Whole-tensor maximum reduction.
Max,
/// Whole-tensor Euclidean norm.
Norm,
/// Matrix transpose.
Transpose,
/// Vector dot product.
Dot,
/// Vector or matrix multiplication.
Matmul,
}
impl WgpuKernelOp {
/// Returns true when the kernel consumes two input tensors.
pub fn is_binary(self) -> bool {
matches!(self, Self::Add | Self::Sub | Self::Mul | Self::Div)
}
/// Returns true when the kernel consumes exactly one input tensor.
pub fn is_unary(self) -> bool {
matches!(
self,
Self::Sqrt
| Self::Neg
| Self::Exp
| Self::Log
| Self::Sin
| Self::Cos
| Self::Sum
| Self::Min
| Self::Max
| Self::Norm
| Self::Transpose
)
}
/// Returns true when the kernel performs fixed-tree accumulation.
pub fn is_reduction(self) -> bool {
matches!(self, Self::Sum | Self::Min | Self::Max | Self::Norm)
}
/// Returns true when the kernel performs a linalg memory/product primitive.
pub fn is_linalg(self) -> bool {
matches!(self, Self::Transpose | Self::Dot | Self::Matmul)
}
fn symbol_name(self) -> &'static str {
match self {
Self::Add => "add",
Self::Sub => "sub",
Self::Mul => "mul",
Self::Div => "div",
Self::Neg => "neg",
Self::Sqrt => "sqrt",
Self::Exp => "exp",
Self::Log => "log",
Self::Sin => "sin",
Self::Cos => "cos",
Self::Sum => "sum",
Self::Min => "min",
Self::Max => "max",
Self::Norm => "norm",
Self::Transpose => "transpose",
Self::Dot => "dot",
Self::Matmul => "matmul",
}
}
fn wgsl_bytes(self) -> usize {
kernel_wgsl_for_op(self).len()
}
}
/// A compiled pipeline paired with its stable evidence record.
#[derive(Clone, Debug)]
pub struct WgpuCompiledPipeline {
/// Public evidence for this validated pipeline.
pub record: WgpuPipelineRecord,
/// Retained native compute pipeline.
pub pipeline: Arc<wgpu::ComputePipeline>,
}
/// Dtype strategy selected for a portable kernel.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WgpuKernelDType {
/// Native f32 arithmetic.
F32,
/// Native f16 arithmetic, only when the adapter granted shader f16.
F16Native,
/// bf16/unsupported half inputs widened to f32 arithmetic.
Bf16WidenedToF32,
}
impl WgpuKernelDType {
fn symbol_name(self) -> &'static str {
match self {
Self::F32 => "f32",
Self::F16Native => "f16",
Self::Bf16WidenedToF32 => "f32-widened-half",
}
}
}
/// Cache key for a validated portable pipeline.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WgpuPipelineKey {
/// Adapter ordinal from discovery evidence.
pub adapter_ordinal: usize,
/// Portable kernel operation.
pub op: WgpuKernelOp,
/// Kernel dtype strategy.
pub dtype: WgpuKernelDType,
/// Output rank.
pub rank: usize,
/// Bounded planner profile selected from granted limits.
pub tile: WgpuTileProfile,
}
/// Portable tile profile selected from granted adapter limits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WgpuTileProfile {
/// Workgroup width for one-dimensional kernels.
pub workgroup_width: u32,
/// Square matrix tile edge used by transpose and matmul.
pub matrix_tile: u32,
/// Number of workgroup-local reduction lanes.
pub reduction_lanes: u32,
/// Maximum resident bytes accepted by one planned dispatch.
pub max_dispatch_bytes: u64,
}
impl WgpuTileProfile {
/// Selects conservative portable tiles from granted adapter limits.
pub fn from_probe(probe: &WgpuAdapterProbe) -> Self {
let limits = &probe.adapter.granted_limits;
let max_x = limits.max_compute_workgroup_size_x.max(1);
let max_invocations = limits.max_compute_invocations_per_workgroup.max(1);
let workgroup_width = max_x.min(max_invocations).clamp(1, 256);
let matrix_tile = 16_u32.min(workgroup_width).min(max_invocations).max(1);
let reduction_lanes = workgroup_width.clamp(1, 256);
Self {
workgroup_width,
matrix_tile,
reduction_lanes,
max_dispatch_bytes: limits.max_buffer_size.max(4),
}
}
}
/// Validated pipeline evidence retained in the cache.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WgpuPipelineRecord {
/// Cache key.
pub key: WgpuPipelineKey,
/// Stable symbol for this validated pipeline.
pub symbol: Symbol,
/// WGSL source byte length.
pub wgsl_bytes: usize,
}
/// Snapshot of cache pressure and reuse.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WgpuPipelineCacheSnapshot {
/// Cached pipeline count.
pub entries: usize,
/// Number of cache hits.
pub hits: usize,
/// Number of cache misses.
pub misses: usize,
/// Number of oldest-entry evictions.
pub evictions: usize,
}
/// Small FIFO cache for validated pipelines.
#[derive(Clone, Debug)]
pub struct WgpuPipelineCache {
capacity: usize,
entries: VecDeque<WgpuPipelineRecord>,
compiled: VecDeque<(WgpuPipelineKey, Arc<wgpu::ComputePipeline>)>,
hits: usize,
misses: usize,
evictions: usize,
}
impl WgpuPipelineCache {
/// Builds a cache with a bounded entry count.
pub fn new(capacity: usize) -> Self {
Self {
capacity: capacity.max(1),
entries: VecDeque::new(),
compiled: VecDeque::new(),
hits: 0,
misses: 0,
evictions: 0,
}
}
/// Returns an existing pipeline or validates and inserts one.
pub fn get_or_insert(
&mut self,
probe: &WgpuAdapterProbe,
op: WgpuKernelOp,
dtype: WgpuKernelDType,
rank: usize,
) -> WgpuPipelineRecord {
let tile = WgpuTileProfile::from_probe(probe);
let key = WgpuPipelineKey {
adapter_ordinal: probe.adapter.ordinal,
op,
dtype,
rank,
tile,
};
if let Some(record) = self.entries.iter().find(|record| record.key == key) {
self.hits += 1;
return record.clone();
}
self.misses += 1;
if self.entries.len() == self.capacity {
if let Some(evicted) = self.entries.pop_front() {
self.compiled
.retain(|(compiled_key, _)| *compiled_key != evicted.key);
}
self.evictions += 1;
}
let record = WgpuPipelineRecord {
symbol: Symbol::qualified(
"compute.pipeline.wgpu",
format!(
"{}/{}/{}/rank-{}",
probe.adapter.ordinal,
op.symbol_name(),
dtype.symbol_name(),
rank
),
),
key,
wgsl_bytes: op.wgsl_bytes(),
};
self.entries.push_back(record.clone());
record
}
/// Returns an existing compiled pipeline or validates, compiles, and inserts one.
pub fn get_or_insert_compiled(
&mut self,
device: &wgpu::Device,
probe: &WgpuAdapterProbe,
op: WgpuKernelOp,
dtype: WgpuKernelDType,
rank: usize,
) -> WgpuCompiledPipeline {
let record = self.get_or_insert(probe, op, dtype, rank);
if let Some((_, pipeline)) = self
.compiled
.iter()
.find(|(compiled_key, _)| *compiled_key == record.key)
{
return WgpuCompiledPipeline {
record,
pipeline: pipeline.clone(),
};
}
let label = if op.is_reduction() {
"sim-compute-wgpu-reduction"
} else if op.is_linalg() {
"sim-compute-wgpu-linalg"
} else {
"sim-compute-wgpu-pointwise"
};
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(label),
source: wgpu::ShaderSource::Wgsl(kernel_wgsl_for_op(op).into()),
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some(label),
layout: None,
module: &shader,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
let pipeline = Arc::new(pipeline);
self.compiled
.push_back((record.key.clone(), pipeline.clone()));
WgpuCompiledPipeline { record, pipeline }
}
/// Returns cache pressure and reuse counters.
pub fn snapshot(&self) -> WgpuPipelineCacheSnapshot {
WgpuPipelineCacheSnapshot {
entries: self.entries.len(),
hits: self.hits,
misses: self.misses,
evictions: self.evictions,
}
}
}
impl Default for WgpuPipelineCache {
fn default() -> Self {
Self::new(16)
}
}