Skip to main content

cubecl_cpp/hip/
dialect.rs

1use core::any::TypeId;
2use std::fmt::Display;
3use std::{collections::HashSet, marker::PhantomData};
4
5use cubecl_core::{ir::Processor, post_processing::saturating::SaturatingArithmeticProcessor};
6
7use crate::shared::DialectWarpReduceCompiler;
8use crate::{
9    Dialect,
10    shared::{
11        self, Binding, DialectBindings, DialectCubeBuiltins, DialectIncludes, DialectTypes,
12        DialectWmmaCompiler, Flags, Item, ManualMma,
13    },
14};
15use crate::{
16    hip::processors::HipMmaProcessor,
17    shared::{
18        Component, DialectInstructions, DialectProcessors, Elem, Instruction, Variable, unary,
19        variable_to_frag,
20    },
21};
22
23use super::Extension;
24use super::arch::AMDArchitecture;
25use super::extension::{WmmaExtension, format_f162bf16, format_max, format_min};
26use super::mma::{WmmaCast, WmmaExecute, WmmaFill, WmmaIntrinsicCompiler, WmmaLoad, WmmaStore};
27
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub struct HipDialect<M> {
30    _wmma_compiler: PhantomData<M>,
31}
32
33// Base dialect
34
35impl<M: DialectWmmaCompiler<Self>> Dialect for HipDialect<M> {
36    type Architecture = AMDArchitecture;
37}
38
39impl<M: DialectWmmaCompiler<Self>> DialectWarpReduceCompiler<Self> for HipDialect<M> {}
40
41// Includes
42
43impl<M: DialectWmmaCompiler<Self>> DialectIncludes<Self> for HipDialect<M> {
44    type Extension = Extension<Self>;
45
46    fn compile_includes(f: &mut std::fmt::Formatter<'_>, flags: &Flags<Self>) -> std::fmt::Result {
47        f.write_str("#include <hip/hip_runtime.h>\n")?;
48        if flags.elem_bf16 {
49            f.write_str("#include <hip/hip_bf16.h>\n")?;
50        }
51        if flags.elem_f16 {
52            f.write_str("#include <hip/hip_fp16.h>\n")?;
53        }
54        if flags.inst_wmma {
55            Self::compile_wmma_includes(f, flags)?;
56        }
57        Ok(())
58    }
59
60    fn compile_extensions(
61        f: &mut std::fmt::Formatter<'_>,
62        extensions: &[Self::Extension],
63    ) -> std::fmt::Result {
64        for extension in extensions {
65            match extension {
66                Extension::F162BF16 => format_f162bf16(f)?,
67                Extension::Max(var) => format_max::<Self>(f, var)?,
68                Extension::Min(var) => format_min::<Self>(f, var)?,
69                Extension::NoExtension => {}
70                Extension::Wmma(inst) => inst.format_wmma(f)?,
71            }
72        }
73        Ok(())
74    }
75
76    fn register_instruction_extension(
77        extensions: &mut Vec<Self::Extension>,
78        instruction: &Instruction<Self>,
79    ) {
80        let mut register_extension = |extension: Self::Extension| {
81            if !extensions.contains(&extension) {
82                extensions.push(extension);
83            }
84        };
85        #[allow(clippy::single_match)]
86        match instruction {
87            shared::Instruction::<Self>::Max(op) => {
88                register_extension(Extension::Max(*op.lhs.item().elem()));
89            }
90            shared::Instruction::<Self>::Min(op) => {
91                register_extension(Extension::Min(*op.lhs.item().elem()));
92            }
93            _ => {}
94        }
95    }
96
97    fn register_warp_instruction_extension(
98        extensions: &mut Vec<Self::Extension>,
99        instruction: &shared::WarpInstruction<Self>,
100    ) {
101        let mut register_extension = |extension: Self::Extension| {
102            if !extensions.contains(&extension) {
103                extensions.push(extension);
104            }
105        };
106
107        #[allow(clippy::single_match)]
108        match instruction {
109            shared::WarpInstruction::<Self>::ReduceMax { input, .. } => {
110                let input_item = input.item();
111                let input_elem = input_item.elem();
112                if *input_elem == Elem::<Self>::BF16 {
113                    register_extension(Extension::F162BF16);
114                }
115                register_extension(Extension::Max(*input_elem));
116            }
117            shared::WarpInstruction::<Self>::ReduceMin { input, .. } => {
118                let input_item = input.item();
119                let input_elem = input_item.elem();
120                if *input_elem == Elem::<Self>::BF16 {
121                    register_extension(Extension::F162BF16);
122                }
123                register_extension(Extension::Min(*input_elem));
124            }
125            shared::WarpInstruction::<Self>::ReduceProd { input, .. } => {
126                let input_item = input.item();
127                let input_elem = input_item.elem();
128                if *input_elem == Elem::<Self>::BF16 {
129                    register_extension(Extension::F162BF16);
130                }
131            }
132            shared::WarpInstruction::<Self>::ReduceSum { input, .. } => {
133                let input_item = input.item();
134                let input_elem = input_item.elem();
135                if *input_elem == Elem::<Self>::BF16 {
136                    register_extension(Extension::F162BF16);
137                }
138            }
139            _ => {}
140        }
141    }
142
143    fn register_wmma_instruction_extension(
144        extensions: &mut Vec<Self::Extension>,
145        instruction: &shared::WmmaInstruction<Self>,
146    ) {
147        if TypeId::of::<M>() == TypeId::of::<WmmaIntrinsicCompiler>() {
148            let extension = match instruction {
149                shared::WmmaInstruction::Fill { frag, .. } => {
150                    Extension::Wmma(WmmaExtension::Fill(WmmaFill::new(variable_to_frag(frag))))
151                }
152                shared::WmmaInstruction::Load { frag, layout, .. } => Extension::Wmma(
153                    WmmaExtension::Load(WmmaLoad::new(variable_to_frag(frag), *layout)),
154                ),
155                shared::WmmaInstruction::LdMatrix { .. }
156                | shared::WmmaInstruction::StMatrix { .. } => {
157                    panic!("Invalid extension: StMatrix & LdMatrix not supported for HIP");
158                }
159                shared::WmmaInstruction::Execute {
160                    frag_a,
161                    frag_b,
162                    frag_c,
163                    frag_d,
164                    warp_size: _,
165                } => Extension::Wmma(WmmaExtension::Execute(WmmaExecute::new(
166                    variable_to_frag(frag_a),
167                    variable_to_frag(frag_b),
168                    variable_to_frag(frag_c),
169                    variable_to_frag(frag_d),
170                ))),
171                shared::WmmaInstruction::ExecuteManual {
172                    shape,
173                    frag_a,
174                    frag_c,
175                    ..
176                } => Extension::Wmma(WmmaExtension::Execute(WmmaExecute::from_manual(
177                    *shape,
178                    frag_a.elem(),
179                    frag_c.elem(),
180                ))),
181                shared::WmmaInstruction::ExecuteScaled { .. } => {
182                    panic!("Invalid extension: ExecuteScaled not supported for HIP");
183                }
184                shared::WmmaInstruction::Store { frag, layout, .. } => Extension::Wmma(
185                    WmmaExtension::Store(WmmaStore::new(variable_to_frag(frag), *layout)),
186                ),
187                shared::WmmaInstruction::Cast { input, output } => {
188                    Extension::Wmma(WmmaExtension::Cast(WmmaCast::new(
189                        variable_to_frag(input),
190                        variable_to_frag(output),
191                    )))
192                }
193            };
194
195            if !extensions.contains(&extension) {
196                extensions.push(extension);
197            }
198        } else if let shared::WmmaInstruction::ExecuteManual {
199            shape,
200            frag_a,
201            frag_c,
202            ..
203        } = instruction
204        {
205            let extension = Extension::Wmma(WmmaExtension::Execute(WmmaExecute::from_manual(
206                *shape,
207                frag_a.elem(),
208                frag_c.elem(),
209            )));
210
211            if !extensions.contains(&extension) {
212                extensions.push(extension);
213            }
214        }
215    }
216}
217
218// Types
219
220impl<M: DialectWmmaCompiler<Self>> DialectTypes<Self> for HipDialect<M> {
221    fn item_can_be_optimized() -> bool {
222        // for now deactivate support for half2 and bfloat162 because the HIP API lack support for it.
223        false
224    }
225
226    fn compile_type_definitions(
227        f: &mut std::fmt::Formatter<'_>,
228        items: &HashSet<Item<Self>>,
229        _scalars: &[(Elem<Self>, usize)],
230        flags: &Flags<Self>,
231    ) -> std::fmt::Result {
232        shared::type_definitions::<Self>(f)?;
233        shared::type_vectorized_definitions::<Self>(f, items)?;
234
235        if flags.inst_wmma {
236            Self::compile_wmma_type_definitions(f, flags)?;
237        }
238
239        Ok(())
240    }
241
242    fn compile_elem(
243        f: &mut std::fmt::Formatter<'_>,
244        elem: &shared::Elem<Self>,
245        words: bool,
246    ) -> std::fmt::Result {
247        if words {
248            match elem {
249                shared::Elem::F32 => f.write_str("float"),
250                shared::Elem::F64 => f.write_str("double"),
251                shared::Elem::TF32 => f.write_str("float"),
252                shared::Elem::I8 => f.write_str("char"),
253                shared::Elem::I16 => f.write_str("short"),
254                shared::Elem::I32 => f.write_str("int"),
255                shared::Elem::I64 => f.write_str("long"),
256                shared::Elem::U8 => f.write_str("uchar"),
257                shared::Elem::U16 => f.write_str("ushort"),
258                shared::Elem::U32 => f.write_str("uint"),
259                shared::Elem::U64 => f.write_str("ulong"),
260                _ => Self::compile_elem(f, elem, false),
261            }
262        } else {
263            match elem {
264                shared::Elem::FP4(_)
265                | shared::Elem::FP4x2(_)
266                | shared::Elem::FP6(_)
267                | shared::Elem::FP6x2(_)
268                | shared::Elem::FP8(_)
269                | shared::Elem::FP8x2(_) => {
270                    f.write_str("#error FP4/FP6/FP8 not supported in HIP\n")
271                }
272                shared::Elem::F16 => f.write_str("__half"),
273                shared::Elem::F16x2 => f.write_str("__half2"),
274                shared::Elem::F32 => f.write_str("float"),
275                shared::Elem::F64 => f.write_str("double"),
276                shared::Elem::BF16 => f.write_str("__bf16"),
277                shared::Elem::BF16x2 => f.write_str("__bf162"),
278                shared::Elem::TF32 => f.write_str("float"),
279                shared::Elem::I8 => f.write_str("int8"),
280                shared::Elem::I16 => f.write_str("int16"),
281                shared::Elem::I32 => f.write_str("int32"),
282                shared::Elem::I64 => f.write_str("int64"),
283                shared::Elem::U8 => f.write_str("uint8"),
284                shared::Elem::U16 => f.write_str("uint16"),
285                shared::Elem::U32 => f.write_str("uint32"),
286                shared::Elem::U64 => f.write_str("uint64"),
287                shared::Elem::Bool => f.write_str("bool"),
288                shared::Elem::Barrier(_) => panic!("Barrier object not supported in HIP"),
289                shared::Elem::Atomic(inner) => inner.fmt(f),
290                shared::Elem::_Dialect(_) => Ok(()),
291            }
292        }
293    }
294
295    fn compile_item(f: &mut std::fmt::Formatter<'_>, item: &Item<Self>) -> std::fmt::Result {
296        if 1 == item.vectorization {
297            return write!(f, "{}", item.elem);
298        }
299        if item.native {
300            // native types use the word form of types only
301            Self::compile_elem(f, &item.elem, true)?;
302            write!(f, "{}", item.vectorization)
303        } else {
304            write!(f, "{}_{}", item.elem, item.vectorization)
305        }
306    }
307
308    fn compile_local_memory_qualifier(_f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
309        Ok(())
310    }
311}
312
313// Kernel argument bindings
314
315impl<M: DialectWmmaCompiler<Self>> DialectBindings<Self> for HipDialect<M> {
316    fn compile_kernel_signature(
317        f: &mut std::fmt::Formatter<'_>,
318        kernel_name: &str,
319        tensor_maps: &[Binding<Self>],
320        buffers: &[Binding<Self>],
321        scalars: &[(Elem<Self>, usize)],
322        flags: &Flags<Self>,
323    ) -> std::fmt::Result {
324        write!(
325            f,
326            "
327
328extern \"C\" __global__ void __launch_bounds__({}) {kernel_name}(
329",
330            flags.cube_dim.num_elems()
331        )?;
332        shared::compile_bindings::<Self>(f, tensor_maps, buffers, !scalars.is_empty(), flags)?;
333        shared::compile_scalars_dynamic::<Self>(f, scalars)?;
334        f.write_str("\n)")?;
335
336        Ok(())
337    }
338
339    fn compile_bindings_body(
340        f: &mut std::fmt::Formatter<'_>,
341        body: &shared::Body<Self>,
342    ) -> std::fmt::Result {
343        if !body.shared_memories.is_empty() {
344            let max_align = body
345                .shared_memories
346                .iter()
347                .map(|smem| smem.align())
348                .max()
349                .unwrap();
350            // The `__align__` instead of `alignas` is on purpose - the compiler is currently bugged
351            // with `extern __shared__ alignas` and doesn't properly parse it.
352            writeln!(
353                f,
354                "extern __shared__ __align__({max_align}) uchar dynamic_shared_mem[];"
355            )?;
356        }
357        Ok(())
358    }
359}
360
361// Cube builtins dialect
362
363impl<M: DialectWmmaCompiler<Self>> DialectCubeBuiltins<Self> for HipDialect<M> {}
364
365// Instructions
366
367impl<M: DialectWmmaCompiler<Self>> DialectInstructions<Self> for HipDialect<M> {
368    fn compile_instruction_sync_threads(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
369        writeln!(f, "__syncthreads();\n")
370    }
371
372    fn compile_instruction_sync_warp(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373        writeln!(f, "#error Sync warp is unimplemented on hip\n")
374    }
375
376    fn compile_instruction_thread_fence(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377        writeln!(f, "__threadfence();")
378    }
379
380    // unary
381    fn compile_instruction_find_first_set<T: Component<Self>>(
382        f: &mut std::fmt::Formatter<'_>,
383        input: T,
384        out_elem: Elem<Self>,
385    ) -> std::fmt::Result {
386        write!(f, "{out_elem}(")?;
387        match input.elem() {
388            Elem::I32 | Elem::U32 => write!(f, "__ffs({input})"),
389            Elem::I64 | Elem::U64 => write!(f, "__ffsll({input})"),
390            _ => write!(f, "__ffs({}({input}))", Elem::<Self>::U32),
391        }?;
392        write!(f, ")")
393    }
394
395    fn compile_instruction_leading_zeros_scalar<T: Component<Self>>(
396        f: &mut std::fmt::Formatter<'_>,
397        input: T,
398        out_elem: Elem<Self>,
399    ) -> std::fmt::Result {
400        write!(f, "{out_elem}(")?;
401        match input.elem() {
402            Elem::I32 | Elem::U32 => write!(f, "__clz({input})"),
403            Elem::I64 | Elem::U64 => write!(f, "__clzll({input})"),
404            in_elem => write!(
405                f,
406                "__clz({}) - {}",
407                unary::zero_extend(input),
408                (size_of::<u32>() - in_elem.size()) * 8
409            ),
410        }?;
411        write!(f, ")")
412    }
413
414    fn compile_instruction_trailing_zeros_scalar<T: Component<Self>>(
415        f: &mut std::fmt::Formatter<'_>,
416        input: T,
417        out_elem: Elem<Self>,
418    ) -> std::fmt::Result {
419        // trailing_zeros = ffs - 1 for non-zero, or bit_width for zero
420        // __ffs returns 1-based index of least significant set bit, or 0 if input is 0
421        write!(f, "{out_elem}(")?;
422        match input.elem() {
423            Elem::I32 | Elem::U32 => {
424                write!(f, "({input} == 0 ? 32 : __ffs({input}) - 1)")
425            }
426            Elem::I64 | Elem::U64 => {
427                write!(f, "({input} == 0 ? 64 : __ffsll({input}) - 1)")
428            }
429            in_elem => {
430                let bits = in_elem.size() * 8;
431                let extended = unary::zero_extend(input);
432                write!(f, "({extended} == 0 ? {bits} : __ffs({extended}) - 1)")
433            }
434        }?;
435        write!(f, ")")
436    }
437
438    fn compile_saturating_add(
439        f: &mut std::fmt::Formatter<'_>,
440        _lhs: impl Display,
441        _rhs: impl Display,
442        _item: Item<Self>,
443    ) -> std::fmt::Result {
444        f.write_str(
445            "#error No native saturating add exists, TODO: Should be replaced in a preprocessor\n",
446        )
447    }
448
449    fn compile_saturating_sub(
450        f: &mut std::fmt::Formatter<'_>,
451        _lhs: impl Display,
452        _rhs: impl Display,
453        _item: Item<Self>,
454    ) -> std::fmt::Result {
455        f.write_str(
456            "#error No native saturating sub exists, TODO: Should be replaced in a preprocessor\n",
457        )
458    }
459
460    // others
461    fn compile_instruction_max_function_name(
462        f: &mut std::fmt::Formatter<'_>,
463        item: Item<Self>,
464    ) -> std::fmt::Result {
465        let max = match item.elem() {
466            Elem::F16 => "__hmax",
467            Elem::BF16 => "max_bfloat16",
468            _ => "max",
469        };
470        write!(f, "{max}")
471    }
472
473    fn compile_instruction_min_function_name(
474        f: &mut std::fmt::Formatter<'_>,
475        item: Item<Self>,
476    ) -> std::fmt::Result {
477        let min = match item.elem() {
478            Elem::F16 => "__hmin",
479            Elem::BF16 => "min_bfloat16",
480            _ => "min",
481        };
482        write!(f, "{min}")
483    }
484
485    // Warp
486    fn compile_warp_shuffle(
487        f: &mut std::fmt::Formatter<'_>,
488        var: &str,
489        source: &str,
490    ) -> std::fmt::Result {
491        write!(f, "__shfl({var}, {source})")
492    }
493    fn compile_warp_shuffle_xor(
494        f: &mut std::fmt::Formatter<'_>,
495        var: &str,
496        elem: &Elem<Self>,
497        offset: &str,
498    ) -> std::fmt::Result {
499        match elem {
500            Elem::BF16 => write!(
501                f,
502                "half_to_bfloat16(__shfl_xor(reinterpret_cast<__half&>({var}), {offset}))"
503            ),
504            _ => write!(f, "__shfl_xor({var}, {offset})"),
505        }
506    }
507    fn compile_warp_shuffle_up(
508        f: &mut std::fmt::Formatter<'_>,
509        var: &str,
510        offset: &str,
511    ) -> std::fmt::Result {
512        write!(f, "__shfl_up({var}, {offset})")
513    }
514    fn compile_warp_shuffle_down(
515        f: &mut std::fmt::Formatter<'_>,
516        var: &str,
517        offset: &str,
518    ) -> std::fmt::Result {
519        write!(f, "__shfl_down({var}, {offset})")
520    }
521    fn compile_warp_all<T: Component<Self>>(
522        f: &mut std::fmt::Formatter<'_>,
523        input: &T,
524    ) -> std::fmt::Result {
525        let item = input.item();
526        let elem = item.elem;
527        write!(f, "static_cast<{elem}>(__all({input}))")
528    }
529    fn compile_warp_any<T: Component<Self>>(
530        f: &mut std::fmt::Formatter<'_>,
531        input: &T,
532    ) -> std::fmt::Result {
533        let item = input.item();
534        let elem = item.elem;
535        write!(f, "static_cast<{elem}>(__any({input}))")
536    }
537    fn compile_warp_ballot(
538        f: &mut std::fmt::Formatter<'_>,
539        input: &Variable<Self>,
540        out_elem: &Elem<Self>,
541    ) -> std::fmt::Result {
542        write!(f, "{out_elem}(__ballot({input}))")
543    }
544}
545
546// Coop Matrices dialect
547
548impl<M: DialectWmmaCompiler<Self>> DialectWmmaCompiler<Self> for HipDialect<M> {
549    fn compile_wmma_includes(
550        f: &mut std::fmt::Formatter<'_>,
551        flags: &Flags<Self>,
552    ) -> std::fmt::Result {
553        M::compile_wmma_includes(f, flags)
554    }
555
556    fn compile_wmma_type_definitions(
557        f: &mut std::fmt::Formatter<'_>,
558        flags: &Flags<Self>,
559    ) -> std::fmt::Result {
560        M::compile_wmma_type_definitions(f, flags)
561    }
562
563    fn compile_wmma_local_variables(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
564        M::compile_wmma_local_variables(f)
565    }
566
567    fn compile_wmma_fragment_declaration(
568        f: &mut std::fmt::Formatter<'_>,
569        var: &Variable<Self>,
570    ) -> std::fmt::Result {
571        M::compile_wmma_fragment_declaration(f, var)
572    }
573
574    fn compile_wwma_fragment_ident(
575        f: &mut std::fmt::Formatter<'_>,
576        ident: &crate::shared::FragmentIdent<Self>,
577    ) -> std::fmt::Result {
578        M::compile_wwma_fragment_ident(f, ident)
579    }
580
581    fn compile_wmma_fragment_layout(
582        f: &mut std::fmt::Formatter<'_>,
583        layout: &crate::shared::FragmentLayout<Self>,
584    ) -> std::fmt::Result {
585        M::compile_wmma_fragment_layout(f, layout)
586    }
587
588    fn compile_wmma_fragment(
589        f: &mut std::fmt::Formatter<'_>,
590        fragment: &crate::shared::Fragment<Self>,
591    ) -> std::fmt::Result {
592        M::compile_wmma_fragment(f, fragment)
593    }
594
595    fn compile_wmma_instruction(
596        f: &mut std::fmt::Formatter<'_>,
597        instruction: &crate::shared::WmmaInstruction<Self>,
598    ) -> std::fmt::Result {
599        M::compile_wmma_instruction(f, instruction)
600    }
601
602    fn compile_manual_mma(
603        f: &mut std::fmt::Formatter<'_>,
604        mma: ManualMma<Self>,
605    ) -> std::fmt::Result {
606        M::compile_manual_mma(f, mma)
607    }
608
609    fn supported_wmma_combinations(
610        arch: &AMDArchitecture,
611    ) -> crate::shared::SupportedMmaCombinations {
612        M::supported_wmma_combinations(arch)
613    }
614
615    fn supported_mma_combinations(arch: &AMDArchitecture) -> shared::SupportedMmaCombinations {
616        M::supported_mma_combinations(arch)
617    }
618
619    fn compile_scaled_mma(
620        _f: &mut std::fmt::Formatter<'_>,
621        _mma: ManualMma<Self>,
622        _scales_a: Variable<Self>,
623        _scales_b: Variable<Self>,
624        _scales_factor: u32,
625    ) -> std::fmt::Result {
626        panic!("Scaled MMA not supporter in HIP")
627    }
628}
629
630impl<M: DialectWmmaCompiler<Self>> DialectProcessors<Self> for HipDialect<M> {
631    fn processors() -> Vec<Box<dyn Processor>> {
632        vec![
633            Box::new(HipMmaProcessor),
634            Box::new(SaturatingArithmeticProcessor::new(true)),
635        ]
636    }
637}