cubecl-wgpu 0.11.0

WGPU runtime for the CubeCL
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
use cubecl_server::kernel::BufferIOAttr;
use cubecl_server::kernel::CompiledKernel;
use std::fmt::Display;

use cubecl_core::{
    Compiler, WgpuCompilationOptions,
    prelude::{CubeKernel, KernelDefinition},
    server::{LaunchError, ResourceLimitError},
};
#[cfg(feature = "msl")]
use cubecl_cpp::shared::MslComputeKernel;
use cubecl_environment::backtrace::BackTrace;
use cubecl_ir::DeviceProperties;
use cubecl_server::compiler::CompilationError;
use derive_more::derive::From;
use thiserror::Error;

#[cfg(feature = "spirv")]
use crate::ParamsTransfer;
use crate::{CompilerInfo, WgpuBackend, WgpuServer};

use super::wgsl;

#[cfg(feature = "msl")]
pub use cubecl_cpp::MslCompiler;
#[cfg(feature = "spirv")]
pub use cubecl_spirv::SpirvCompiler;
pub use wgsl::WgslCompiler;

/// Compiler that dispatches to the most appropriate shader language backend for the active
/// `wgpu` backend.
///
/// The variant is selected at runtime by [`WgpuCompiler::init`] based on the `wgpu::Backend`
/// in use and the enabled cargo features (`spirv`, `msl`).
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum AutoCompiler {
    /// WGSL backend, available on every `wgpu` backend.
    Wgsl(WgslCompiler),
    /// SPIR-V backend used on Vulkan when the device supports the required features.
    #[cfg(feature = "spirv")]
    SpirV(cubecl_spirv::SpirvCompiler),
    /// Metal Shading Language backend used on the Metal backend.
    #[cfg(feature = "msl")]
    Msl(MslCompiler),
}

/// Owned compiled kernel representation matching the variants of [`AutoCompiler`].
#[derive(From)]
#[allow(clippy::large_enum_variant)]
pub enum AutoRepresentation {
    /// WGSL compute shader source.
    Wgsl(wgsl::ComputeShader),
    /// Compiled SPIR-V kernel.
    #[cfg(feature = "spirv")]
    SpirV(cubecl_spirv::SpirvKernel),
    /// Compiled Metal Shading Language kernel.
    #[cfg(feature = "msl")]
    Msl(MslComputeKernel),
}

/// Borrowed counterpart of [`AutoRepresentation`], useful when only read access is needed.
#[derive(From, Clone, Copy)]
#[allow(clippy::large_enum_variant)]
pub enum AutoRepresentationRef<'a> {
    /// Borrowed WGSL compute shader.
    Wgsl(&'a wgsl::ComputeShader),
    /// Borrowed SPIR-V kernel.
    #[cfg(feature = "spirv")]
    SpirV(&'a cubecl_spirv::SpirvKernel),
    /// Borrowed Metal Shading Language kernel.
    #[cfg(feature = "msl")]
    Msl(&'a MslComputeKernel),
}

#[cfg(feature = "spirv")]
impl AutoRepresentation {
    /// Returns the SPIR-V kernel if this representation is the SPIR-V variant.
    pub fn as_spirv(&self) -> Option<&cubecl_spirv::SpirvKernel> {
        match self {
            AutoRepresentation::SpirV(repr) => Some(repr),
            _ => None,
        }
    }
}

#[cfg(feature = "msl")]
impl AutoRepresentation {
    /// Returns the MSL kernel if this representation is the MSL variant.
    pub fn as_msl(&self) -> Option<&MslComputeKernel> {
        match self {
            AutoRepresentation::Msl(repr) => Some(repr),
            _ => None,
        }
    }
}

impl AutoRepresentation {
    /// Borrow this representation as an [`AutoRepresentationRef`].
    pub fn as_ref(&self) -> AutoRepresentationRef<'_> {
        match self {
            AutoRepresentation::Wgsl(compute_shader) => AutoRepresentationRef::Wgsl(compute_shader),
            #[cfg(feature = "spirv")]
            AutoRepresentation::SpirV(spirv_kernel) => AutoRepresentationRef::SpirV(spirv_kernel),
            #[cfg(feature = "msl")]
            AutoRepresentation::Msl(compute_shader) => AutoRepresentationRef::Msl(compute_shader),
        }
    }
}

impl Display for AutoRepresentation {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AutoRepresentation::Wgsl(compute_shader) => compute_shader.fmt(f),
            #[cfg(feature = "spirv")]
            AutoRepresentation::SpirV(spirv_kernel) => spirv_kernel.fmt(f),
            #[cfg(feature = "msl")]
            AutoRepresentation::Msl(compute_shader) => compute_shader.fmt(f),
        }
    }
}

impl Compiler for AutoCompiler {
    type Representation = AutoRepresentation;

    type CompilationOptions = WgpuCompilationOptions;

    fn compile(
        &mut self,
        kernel: KernelDefinition,
        compilation_options: &Self::CompilationOptions,
    ) -> Result<Self::Representation, CompilationError> {
        let kernel = match self {
            AutoCompiler::Wgsl(wgsl_compiler) => {
                Compiler::compile(wgsl_compiler, kernel, compilation_options)?.into()
            }
            #[cfg(feature = "spirv")]
            AutoCompiler::SpirV(spirv_compiler) => {
                Compiler::compile(spirv_compiler, kernel, compilation_options)?.into()
            }
            #[cfg(feature = "msl")]
            AutoCompiler::Msl(msl_compiler) => {
                // override compilation options with cpp compiler options for metal
                use cubecl_cpp;
                let compilation_options = cubecl_cpp::shared::CompilationOptions::default();
                Compiler::compile(msl_compiler, kernel, &compilation_options)?.into()
            }
        };

        Ok(kernel)
    }

    fn buffer_io(repr: &Self::Representation) -> Option<Vec<BufferIOAttr>> {
        match repr {
            AutoRepresentation::Wgsl(shader) => WgslCompiler::buffer_io(shader),
            #[cfg(feature = "spirv")]
            AutoRepresentation::SpirV(kernel) => cubecl_spirv::SpirvCompiler::buffer_io(kernel),
            #[cfg(feature = "msl")]
            AutoRepresentation::Msl(kernel) => MslCompiler::buffer_io(kernel),
        }
    }

    fn extension(&self) -> &'static str {
        match self {
            AutoCompiler::Wgsl(_) => "wgsl",
            #[cfg(feature = "spirv")]
            AutoCompiler::SpirV(_) => "spv",
            #[cfg(feature = "msl")]
            AutoCompiler::Msl(_) => "msl",
        }
    }

    fn lang_tag(&self) -> &'static str {
        match self {
            AutoCompiler::Wgsl(compiler) => compiler.lang_tag(),
            #[cfg(feature = "spirv")]
            AutoCompiler::SpirV(compiler) => compiler.lang_tag(),
            #[cfg(feature = "msl")]
            AutoCompiler::Msl(compiler) => compiler.lang_tag(),
        }
    }
}

impl WgpuCompiler for AutoCompiler {
    #[cfg(feature = "msl")]
    fn validate_runtime(
        backend: wgpu::Backend,
        options: &WgpuCompilationOptions,
        requested_backend: WgpuBackend,
    ) -> Result<(), WgpuCompilerInitError> {
        if requested_backend == WgpuBackend::Metal {
            MslCompiler::validate_runtime(backend, options, requested_backend)?;
        }

        Ok(())
    }

    fn init(backend: wgpu::Backend, options: &WgpuCompilationOptions) -> Self {
        let _ = options; // Unused without `spirv` feature
        match backend {
            #[cfg(feature = "spirv")]
            wgpu::Backend::Vulkan if options.supports_vulkan_compiler => {
                AutoCompiler::SpirV(Default::default())
            }
            #[cfg(feature = "msl")]
            wgpu::Backend::Metal if options.supports_msl_compiler => {
                AutoCompiler::Msl(Default::default())
            }
            _ => AutoCompiler::Wgsl(Default::default()),
        }
    }

    fn compile_kernel(
        &mut self,
        server: &mut WgpuServer<AutoCompiler>,
        kernel: Box<dyn CubeKernel>,
        definition: KernelDefinition,
    ) -> Result<CompiledKernel<Self>, CompilationError> {
        match self {
            AutoCompiler::Wgsl(_) => {
                CompiledKernel::compile(&*kernel, definition, self, &server.compilation_options)
            }
            #[cfg(feature = "spirv")]
            AutoCompiler::SpirV(_) => crate::vulkan::compile(self, server, kernel, definition),
            #[cfg(feature = "msl")]
            AutoCompiler::Msl(_) => {
                CompiledKernel::compile(&*kernel, definition, self, &server.compilation_options)
            }
        }
    }

    fn validate_ir(
        &self,
        repr: &Option<Self::Representation>,
        props: &DeviceProperties,
    ) -> Result<(), LaunchError> {
        let shared_bytes = repr.as_ref().map(|repr| match repr {
            AutoRepresentation::Wgsl(repr) => repr.shared_memory_size,
            #[cfg(feature = "msl")]
            AutoRepresentation::Msl(repr) => repr.shared_memory_size,
            #[cfg(feature = "spirv")]
            AutoRepresentation::SpirV(repr) => repr.shared_size,
        });
        check_shared_memory(shared_bytes, props)
    }

    fn normalize_repr(
        &self,
        repr: Option<Self::Representation>,
    ) -> (CompilerInfo, Option<AutoRepresentation>) {
        let compiler_info = match &repr {
            #[cfg(feature = "spirv")]
            Some(AutoRepresentation::SpirV(repr)) => CompilerInfo::Vulkan {
                params_transfer: match repr.immediate_size {
                    Some(_) => ParamsTransfer::Immediate,
                    None => ParamsTransfer::Uniform,
                },
            },
            #[cfg(feature = "msl")]
            Some(AutoRepresentation::Msl(_)) => CompilerInfo::Metal,
            Some(AutoRepresentation::Wgsl(_)) => CompilerInfo::WGSL,
            None => CompilerInfo::None,
        };

        (compiler_info, repr)
    }
}

impl WgpuCompiler for WgslCompiler {
    fn init(_backend: wgpu::Backend, _options: &WgpuCompilationOptions) -> Self {
        Self
    }

    fn compile_kernel(
        &mut self,
        server: &mut WgpuServer<Self>,
        kernel: Box<dyn CubeKernel>,
        definition: KernelDefinition,
    ) -> Result<CompiledKernel<Self>, CompilationError> {
        CompiledKernel::compile(&*kernel, definition, self, &server.compilation_options)
    }

    fn validate_ir(
        &self,
        repr: &Option<Self::Representation>,
        props: &DeviceProperties,
    ) -> Result<(), LaunchError> {
        let shared_bytes = repr.as_ref().map(|repr| repr.shared_memory_size);
        check_shared_memory(shared_bytes, props)
    }

    fn normalize_repr(
        &self,
        repr: Option<Self::Representation>,
    ) -> (CompilerInfo, Option<AutoRepresentation>) {
        (CompilerInfo::WGSL, repr.map(|r| r.into()))
    }
}

#[cfg(feature = "msl")]
impl WgpuCompiler for MslCompiler {
    fn validate_runtime(
        backend: wgpu::Backend,
        options: &WgpuCompilationOptions,
        _requested_backend: WgpuBackend,
    ) -> Result<(), WgpuCompilerInitError> {
        if backend != wgpu::Backend::Metal {
            return Err(WgpuCompilerInitError::BackendMismatch {
                compiler: "MslCompiler",
                expected: wgpu::Backend::Metal,
                actual: backend,
            });
        }

        if !options.supports_msl_compiler {
            return Err(WgpuCompilerInitError::Unavailable {
                compiler: "MslCompiler",
                backend,
            });
        }

        Ok(())
    }

    fn init(_backend: wgpu::Backend, _options: &WgpuCompilationOptions) -> Self {
        Self::default()
    }

    fn compile_kernel(
        &mut self,
        _server: &mut WgpuServer<Self>,
        kernel: Box<dyn CubeKernel>,
        definition: KernelDefinition,
    ) -> Result<CompiledKernel<Self>, CompilationError> {
        // The MSL compiler uses its own CompilationOptions, not WgpuCompilationOptions.
        let compilation_options = cubecl_cpp::shared::CompilationOptions::default();
        CompiledKernel::compile(&*kernel, definition, self, &compilation_options)
    }

    fn validate_ir(
        &self,
        repr: &Option<Self::Representation>,
        props: &DeviceProperties,
    ) -> Result<(), LaunchError> {
        let shared_bytes = repr.as_ref().map(|repr| repr.shared_memory_size);
        check_shared_memory(shared_bytes, props)
    }

    fn normalize_repr(
        &self,
        repr: Option<Self::Representation>,
    ) -> (CompilerInfo, Option<AutoRepresentation>) {
        (CompilerInfo::Metal, repr.map(|r| r.into()))
    }
}

#[cfg(feature = "spirv")]
impl WgpuCompiler for cubecl_spirv::SpirvCompiler {
    fn init(_backend: wgpu::Backend, _options: &WgpuCompilationOptions) -> Self {
        Self
    }

    fn compile_kernel(
        &mut self,
        server: &mut WgpuServer<Self>,
        kernel: Box<dyn CubeKernel>,
        definition: KernelDefinition,
    ) -> Result<CompiledKernel<Self>, CompilationError> {
        crate::vulkan::compile(self, server, kernel, definition)
    }

    fn validate_ir(
        &self,
        repr: &Option<Self::Representation>,
        props: &DeviceProperties,
    ) -> Result<(), LaunchError> {
        let shared_bytes = repr.as_ref().map(|repr| repr.shared_size);
        check_shared_memory(shared_bytes, props)
    }

    fn normalize_repr(
        &self,
        repr: Option<Self::Representation>,
    ) -> (CompilerInfo, Option<AutoRepresentation>) {
        let params_transfer = match repr.as_ref().and_then(|r| r.immediate_size) {
            Some(_) => ParamsTransfer::Immediate,
            None => ParamsTransfer::Uniform,
        };
        (
            CompilerInfo::Vulkan { params_transfer },
            repr.map(|r| r.into()),
        )
    }
}

fn check_shared_memory(
    shared_bytes: Option<usize>,
    props: &DeviceProperties,
) -> Result<(), LaunchError> {
    let max_smem = props.hardware.max_shared_memory_size;
    if let Some(shared_bytes) = shared_bytes
        && shared_bytes > max_smem
    {
        return Err(ResourceLimitError::SharedMemory {
            requested: shared_bytes,
            max: max_smem,
            backtrace: BackTrace::capture(),
        }
        .into());
    }
    Ok(())
}

/// An explicitly selected wgpu compiler cannot serve the selected graphics backend or device.
#[non_exhaustive]
#[derive(Debug, Error, PartialEq, Eq)]
pub enum WgpuCompilerInitError {
    /// The compiler only emits shaders for a different graphics backend.
    #[error("`{compiler}` requires the {expected:?} wgpu backend, but {actual:?} was selected")]
    BackendMismatch {
        compiler: &'static str,
        expected: wgpu::Backend,
        actual: wgpu::Backend,
    },
    /// The selected device does not meet the compiler's requirements.
    #[error(
        "`{compiler}` was requested explicitly, but it is unavailable on the selected {backend:?} device; use `AutoCompiler` with an automatic device to allow WGSL fallback"
    )]
    Unavailable {
        compiler: &'static str,
        backend: wgpu::Backend,
    },
}

/// Extension trait implemented by every compiler usable with the `wgpu` runtime.
///
/// The base [`Compiler`] trait already exposes a `compile` method that turns a
/// [`KernelDefinition`] into a backend representation. [`WgpuCompiler`] sits one level
/// higher: it owns the wgpu-specific lifecycle around a [`CubeKernel`](cubecl_server::kernel::CubeKernel)
/// kernel — initializing the compiler for a given `wgpu::Backend`, compiling a kernel using
/// the server's [`WgpuCompilationOptions`], validating the resulting IR against the device,
/// and projecting the typed representation into the runtime-erased [`AutoRepresentation`].
pub trait WgpuCompiler: Compiler {
    /// Check that this compiler can serve the selected graphics backend and device.
    ///
    /// Explicit compilers should return an error instead of silently selecting another shader
    /// language. `requested_backend` preserves the unresolved selection; [`WgpuBackend::Auto`]
    /// allows automatic API selection. With `msl` enabled, [`AutoCompiler`] requires native MSL
    /// for an explicit Metal request; otherwise it permits WGSL fallback. Explicit compilers apply
    /// their own requirements.
    fn validate_runtime(
        _backend: wgpu::Backend,
        _options: &WgpuCompilationOptions,
        _requested_backend: WgpuBackend,
    ) -> Result<(), WgpuCompilerInitError> {
        Ok(())
    }

    /// Build the compiler instance appropriate for the given `wgpu` backend.
    ///
    /// `options` is consulted to decide between alternative implementations (for example, to
    /// opt into the SPIR-V compiler on Vulkan when the device advertises the required
    /// features).
    fn init(backend: wgpu::Backend, options: &WgpuCompilationOptions) -> Self;

    /// Validate that the compiled representation fits within the device's resource limits.
    ///
    /// Today this checks shared memory usage; additional checks may be added without
    /// breaking the contract.
    fn validate_ir(
        &self,
        repr: &Option<Self::Representation>,
        props: &DeviceProperties,
    ) -> Result<(), LaunchError>;

    /// Compile a runtime kernel into a [`CompiledKernel`] ready for pipeline creation.
    ///
    /// Distinct from [`Compiler::compile`], which only translates a [`KernelDefinition`].
    /// This entry point operates on a full server-level kernel and pulls compilation
    /// options from `server`, so its signature cannot collide with the base trait method.
    fn compile_kernel(
        &mut self,
        server: &mut WgpuServer<Self>,
        kernel: Box<dyn CubeKernel>,
        definition: KernelDefinition,
    ) -> Result<CompiledKernel<Self>, CompilationError>;

    /// Normalize the backend-specific representation into the [`AutoRepresentation`] shared
    /// by every wgpu compiler, and report the [`CompilerInfo`] derived from it.
    ///
    /// The [`CompilerInfo`] tells the server which parameter-passing strategy to use for
    /// the resulting pipeline.
    fn normalize_repr(
        &self,
        repr: Option<Self::Representation>,
    ) -> (CompilerInfo, Option<AutoRepresentation>);
}

#[cfg(all(test, feature = "msl"))]
mod tests {
    use super::*;

    #[test]
    fn auto_compiler_falls_back_to_wgsl_when_msl_is_unavailable() {
        let options = WgpuCompilationOptions::default();
        assert!(
            AutoCompiler::validate_runtime(wgpu::Backend::Metal, &options, WgpuBackend::Auto)
                .is_ok()
        );
        let compiler = AutoCompiler::init(wgpu::Backend::Metal, &options);

        assert!(matches!(compiler, AutoCompiler::Wgsl(_)));
    }

    #[test]
    fn explicit_msl_compiler_rejects_wgsl_fallback() {
        for requested_backend in [WgpuBackend::Auto, WgpuBackend::Metal] {
            let result = MslCompiler::validate_runtime(
                wgpu::Backend::Metal,
                &WgpuCompilationOptions::default(),
                requested_backend,
            );

            assert_eq!(
                result,
                Err(WgpuCompilerInitError::Unavailable {
                    compiler: "MslCompiler",
                    backend: wgpu::Backend::Metal,
                })
            );
        }
    }

    #[test]
    fn explicit_msl_compiler_rejects_non_metal_backend() {
        let options = WgpuCompilationOptions {
            supports_msl_compiler: true,
            ..Default::default()
        };
        let result =
            MslCompiler::validate_runtime(wgpu::Backend::Vulkan, &options, WgpuBackend::Auto);

        assert_eq!(
            result,
            Err(WgpuCompilerInitError::BackendMismatch {
                compiler: "MslCompiler",
                expected: wgpu::Backend::Metal,
                actual: wgpu::Backend::Vulkan,
            })
        );
    }

    #[test]
    fn explicit_msl_compiler_accepts_supported_metal_device() {
        let options = WgpuCompilationOptions {
            supports_msl_compiler: true,
            ..Default::default()
        };

        assert!(
            MslCompiler::validate_runtime(wgpu::Backend::Metal, &options, WgpuBackend::Auto)
                .is_ok()
        );
    }

    #[test]
    fn explicit_wgsl_on_metal_does_not_require_native_msl() {
        for supports_msl_compiler in [false, true] {
            let options = WgpuCompilationOptions {
                supports_msl_compiler,
                ..Default::default()
            };
            assert!(
                WgslCompiler::validate_runtime(wgpu::Backend::Metal, &options, WgpuBackend::Metal)
                    .is_ok()
            );
        }
    }

    #[test]
    fn auto_compiler_on_explicit_metal_requires_native_msl() {
        let options = WgpuCompilationOptions::default();
        assert_eq!(
            AutoCompiler::validate_runtime(wgpu::Backend::Metal, &options, WgpuBackend::Metal),
            Err(WgpuCompilerInitError::Unavailable {
                compiler: "MslCompiler",
                backend: wgpu::Backend::Metal,
            })
        );
        let supported = WgpuCompilationOptions {
            supports_msl_compiler: true,
            ..options
        };
        assert!(
            AutoCompiler::validate_runtime(wgpu::Backend::Metal, &supported, WgpuBackend::Metal)
                .is_ok()
        );
    }
}