torsh-backend 0.1.2

Backend abstraction layer for ToRSh
Documentation
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
//! WGSL Kernel Library for ToRSh WebGPU Backend

#[cfg(feature = "webgpu")]
use crate::webgpu::wgpu;
//!
//! This module provides a comprehensive collection of WGSL compute shaders
//! for common tensor operations, optimized for wgpu 26.0.1.

use std::collections::HashMap;

/// Collection of WGSL compute shaders for tensor operations
pub struct WgslKernels;

impl WgslKernels {
    /// Get all available kernels as a map
    pub fn all_kernels() -> HashMap<&'static str, &'static str> {
        let mut kernels = HashMap::new();

        // Arithmetic operations
        kernels.insert("add_f32", Self::ADD_F32);
        kernels.insert("mul_f32", Self::MUL_F32);
        kernels.insert("sub_f32", Self::SUB_F32);
        kernels.insert("div_f32", Self::DIV_F32);

        // Unary operations
        kernels.insert("relu_f32", Self::RELU_F32);
        kernels.insert("sigmoid_f32", Self::SIGMOID_F32);
        kernels.insert("tanh_f32", Self::TANH_F32);
        kernels.insert("exp_f32", Self::EXP_F32);
        kernels.insert("log_f32", Self::LOG_F32);
        kernels.insert("sqrt_f32", Self::SQRT_F32);

        // Matrix operations
        kernels.insert("matmul_f32", Self::MATMUL_F32);
        kernels.insert("transpose_f32", Self::TRANSPOSE_F32);

        // Reduction operations
        kernels.insert("sum_f32", Self::SUM_F32);
        kernels.insert("max_f32", Self::MAX_F32);
        kernels.insert("min_f32", Self::MIN_F32);

        // Utility operations
        kernels.insert("fill_f32", Self::FILL_F32);
        kernels.insert("copy_f32", Self::COPY_F32);

        kernels
    }

    /// Element-wise addition of two f32 arrays
    pub const ADD_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input_a: array<f32>;
@group(0) @binding(1) var<storage, read> input_b: array<f32>;
@group(0) @binding(2) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = input_a[index] + input_b[index];
}
"#;

    /// Element-wise multiplication of two f32 arrays
    pub const MUL_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input_a: array<f32>;
@group(0) @binding(1) var<storage, read> input_b: array<f32>;
@group(0) @binding(2) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = input_a[index] * input_b[index];
}
"#;

    /// Element-wise subtraction of two f32 arrays
    pub const SUB_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input_a: array<f32>;
@group(0) @binding(1) var<storage, read> input_b: array<f32>;
@group(0) @binding(2) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = input_a[index] - input_b[index];
}
"#;

    /// Element-wise division of two f32 arrays
    pub const DIV_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input_a: array<f32>;
@group(0) @binding(1) var<storage, read> input_b: array<f32>;
@group(0) @binding(2) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = input_a[index] / input_b[index];
}
"#;

    /// ReLU activation function
    pub const RELU_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = max(0.0, input[index]);
}
"#;

    /// Sigmoid activation function
    pub const SIGMOID_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = 1.0 / (1.0 + exp(-input[index]));
}
"#;

    /// Tanh activation function
    pub const TANH_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = tanh(input[index]);
}
"#;

    /// Element-wise exponential
    pub const EXP_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = exp(input[index]);
}
"#;

    /// Element-wise natural logarithm
    pub const LOG_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = log(input[index]);
}
"#;

    /// Element-wise square root
    pub const SQRT_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = sqrt(input[index]);
}
"#;

    /// Matrix multiplication (optimized for small-medium matrices)
    pub const MATMUL_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> matrix_a: array<f32>;
@group(0) @binding(1) var<storage, read> matrix_b: array<f32>;
@group(0) @binding(2) var<storage, read_write> result: array<f32>;
@group(0) @binding(3) var<uniform> dims: vec4<u32>; // [M, N, K, _]

var<workgroup> tile_a: array<array<f32, 16>, 16>;
var<workgroup> tile_b: array<array<f32, 16>, 16>;

@compute @workgroup_size(16, 16)
fn main(
    @builtin(global_invocation_id) global_id: vec3<u32>,
    @builtin(local_invocation_id) local_id: vec3<u32>,
    @builtin(workgroup_id) group_id: vec3<u32>
) {
    let M = dims.x;
    let N = dims.y;
    let K = dims.z;

    let row = global_id.y;
    let col = global_id.x;

    if (row >= M || col >= N) {
        return;
    }

    var sum = 0.0;

    for (var tile = 0u; tile < (K + 15u) / 16u; tile++) {
        // Load tiles into workgroup memory
        let a_idx = row * K + tile * 16u + local_id.x;
        let b_idx = (tile * 16u + local_id.y) * N + col;

        if (tile * 16u + local_id.x < K) {
            tile_a[local_id.y][local_id.x] = matrix_a[a_idx];
        } else {
            tile_a[local_id.y][local_id.x] = 0.0;
        }

        if (tile * 16u + local_id.y < K) {
            tile_b[local_id.y][local_id.x] = matrix_b[b_idx];
        } else {
            tile_b[local_id.y][local_id.x] = 0.0;
        }

        workgroupBarrier();

        // Compute partial sum
        for (var k = 0u; k < 16u; k++) {
            sum += tile_a[local_id.y][k] * tile_b[k][local_id.x];
        }

        workgroupBarrier();
    }

    result[row * N + col] = sum;
}
"#;

    /// Matrix transpose
    pub const TRANSPOSE_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;
@group(0) @binding(2) var<uniform> dims: vec2<u32>; // [rows, cols]

@compute @workgroup_size(16, 16)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let rows = dims.x;
    let cols = dims.y;

    let src_row = global_id.y;
    let src_col = global_id.x;

    if (src_row >= rows || src_col >= cols) {
        return;
    }

    let src_idx = src_row * cols + src_col;
    let dst_idx = src_col * rows + src_row;

    output[dst_idx] = input[src_idx];
}
"#;

    /// Sum reduction along the last dimension
    pub const SUM_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;
@group(0) @binding(2) var<uniform> size: u32;

var<workgroup> shared_sum: array<f32, 256>;

@compute @workgroup_size(256)
fn main(
    @builtin(global_invocation_id) global_id: vec3<u32>,
    @builtin(local_invocation_id) local_id: vec3<u32>,
    @builtin(workgroup_id) group_id: vec3<u32>
) {
    let tid = local_id.x;
    let gid = global_id.x;

    // Load data into shared memory
    if (gid < size) {
        shared_sum[tid] = input[gid];
    } else {
        shared_sum[tid] = 0.0;
    }

    workgroupBarrier();

    // Tree reduction in shared memory
    for (var s = 128u; s > 0u; s >>= 1u) {
        if (tid < s) {
            shared_sum[tid] += shared_sum[tid + s];
        }
        workgroupBarrier();
    }

    // Write result
    if (tid == 0u) {
        output[group_id.x] = shared_sum[0];
    }
}
"#;

    /// Max reduction along the last dimension
    pub const MAX_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;
@group(0) @binding(2) var<uniform> size: u32;

var<workgroup> shared_max: array<f32, 256>;

@compute @workgroup_size(256)
fn main(
    @builtin(global_invocation_id) global_id: vec3<u32>,
    @builtin(local_invocation_id) local_id: vec3<u32>,
    @builtin(workgroup_id) group_id: vec3<u32>
) {
    let tid = local_id.x;
    let gid = global_id.x;

    // Load data into shared memory
    if (gid < size) {
        shared_max[tid] = input[gid];
    } else {
        shared_max[tid] = -3.40282347e+38; // -f32::MAX
    }

    workgroupBarrier();

    // Tree reduction in shared memory
    for (var s = 128u; s > 0u; s >>= 1u) {
        if (tid < s) {
            shared_max[tid] = max(shared_max[tid], shared_max[tid + s]);
        }
        workgroupBarrier();
    }

    // Write result
    if (tid == 0u) {
        output[group_id.x] = shared_max[0];
    }
}
"#;

    /// Min reduction along the last dimension
    pub const MIN_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;
@group(0) @binding(2) var<uniform> size: u32;

var<workgroup> shared_min: array<f32, 256>;

@compute @workgroup_size(256)
fn main(
    @builtin(global_invocation_id) global_id: vec3<u32>,
    @builtin(local_invocation_id) local_id: vec3<u32>,
    @builtin(workgroup_id) group_id: vec3<u32>
) {
    let tid = local_id.x;
    let gid = global_id.x;

    // Load data into shared memory
    if (gid < size) {
        shared_min[tid] = input[gid];
    } else {
        shared_min[tid] = 3.40282347e+38; // f32::MAX
    }

    workgroupBarrier();

    // Tree reduction in shared memory
    for (var s = 128u; s > 0u; s >>= 1u) {
        if (tid < s) {
            shared_min[tid] = min(shared_min[tid], shared_min[tid + s]);
        }
        workgroupBarrier();
    }

    // Write result
    if (tid == 0u) {
        output[group_id.x] = shared_min[0];
    }
}
"#;

    /// Fill array with a constant value
    pub const FILL_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read_write> output: array<f32>;
@group(0) @binding(1) var<uniform> value: f32;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = value;
}
"#;

    /// Copy array elements
    pub const COPY_F32: &'static str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = input[index];
}
"#;
}