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
33impl<M: DialectWmmaCompiler<Self>> Dialect for HipDialect<M> {
36 type Architecture = AMDArchitecture;
37}
38
39impl<M: DialectWmmaCompiler<Self>> DialectWarpReduceCompiler<Self> for HipDialect<M> {}
40
41impl<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) -> 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
218impl<M: DialectWmmaCompiler<Self>> DialectTypes<Self> for HipDialect<M> {
221 fn item_can_be_optimized() -> bool {
222 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,
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::Atomic(inner) => inner.fmt(f),
289 shared::Elem::_Dialect(_) => Ok(()),
290 }
291 }
292 }
293
294 fn compile_item(f: &mut std::fmt::Formatter<'_>, item: &Item<Self>) -> std::fmt::Result {
295 if 1 == item.vectorization {
296 return write!(f, "{}", item.elem);
297 }
298 if item.native {
299 Self::compile_elem(f, &item.elem, true)?;
301 write!(f, "{}", item.vectorization)
302 } else {
303 write!(f, "{}_{}", item.elem, item.vectorization)
304 }
305 }
306
307 fn compile_local_memory_qualifier(_f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308 Ok(())
309 }
310}
311
312impl<M: DialectWmmaCompiler<Self>> DialectBindings<Self> for HipDialect<M> {
315 fn compile_kernel_signature(
316 f: &mut std::fmt::Formatter<'_>,
317 kernel_name: &str,
318 tensor_maps: &[Binding<Self>],
319 buffers: &[Binding<Self>],
320 scalars: &[(Elem<Self>, usize)],
321 flags: &Flags,
322 ) -> std::fmt::Result {
323 write!(
324 f,
325 "
326
327extern \"C\" __global__ void __launch_bounds__({}) {kernel_name}(
328",
329 flags.cube_dim.num_elems()
330 )?;
331 shared::compile_bindings::<Self>(f, tensor_maps, buffers, !scalars.is_empty(), flags)?;
332 shared::compile_scalars_dynamic::<Self>(f, scalars)?;
333 f.write_str("\n)")?;
334
335 Ok(())
336 }
337
338 fn compile_bindings_body(
339 f: &mut std::fmt::Formatter<'_>,
340 body: &shared::Body<Self>,
341 ) -> std::fmt::Result {
342 if !body.shared_memories.is_empty() {
343 let max_align = body
344 .shared_memories
345 .iter()
346 .map(|smem| smem.align)
347 .max()
348 .unwrap();
349 writeln!(
352 f,
353 "extern __shared__ __align__({max_align}) uchar dynamic_shared_mem[];"
354 )?;
355 }
356 Ok(())
357 }
358}
359
360impl<M: DialectWmmaCompiler<Self>> DialectCubeBuiltins<Self> for HipDialect<M> {}
363
364impl<M: DialectWmmaCompiler<Self>> DialectInstructions<Self> for HipDialect<M> {
367 fn compile_instruction_sync_threads(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368 writeln!(f, "__syncthreads();\n")
369 }
370
371 fn compile_instruction_sync_warp(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372 writeln!(f, "#error Sync warp is unimplemented on hip\n")
373 }
374
375 fn compile_instruction_thread_fence(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376 writeln!(f, "__threadfence();")
377 }
378
379 fn compile_instruction_find_first_set<T: Component<Self>>(
381 f: &mut std::fmt::Formatter<'_>,
382 input: T,
383 out_elem: Elem<Self>,
384 ) -> std::fmt::Result {
385 write!(f, "{out_elem}(")?;
386 match input.elem() {
387 Elem::I32 | Elem::U32 => write!(f, "__ffs({input})"),
388 Elem::I64 | Elem::U64 => write!(f, "__ffsll({input})"),
389 _ => write!(f, "__ffs({}({input}))", Elem::<Self>::U32),
390 }?;
391 write!(f, ")")
392 }
393
394 fn compile_instruction_leading_zeros_scalar<T: Component<Self>>(
395 f: &mut std::fmt::Formatter<'_>,
396 input: T,
397 out_elem: Elem<Self>,
398 ) -> std::fmt::Result {
399 write!(f, "{out_elem}(")?;
400 match input.elem() {
401 Elem::I32 | Elem::U32 => write!(f, "__clz({input})"),
402 Elem::I64 | Elem::U64 => write!(f, "__clzll({input})"),
403 in_elem => write!(
404 f,
405 "__clz({}) - {}",
406 unary::zero_extend(input),
407 (size_of::<u32>() - in_elem.size()) * 8
408 ),
409 }?;
410 write!(f, ")")
411 }
412
413 fn compile_saturating_add(
414 f: &mut std::fmt::Formatter<'_>,
415 _lhs: impl Display,
416 _rhs: impl Display,
417 _item: Item<Self>,
418 ) -> std::fmt::Result {
419 f.write_str(
420 "#error No native saturating add exists, TODO: Should be replaced in a preprocessor\n",
421 )
422 }
423
424 fn compile_saturating_sub(
425 f: &mut std::fmt::Formatter<'_>,
426 _lhs: impl Display,
427 _rhs: impl Display,
428 _item: Item<Self>,
429 ) -> std::fmt::Result {
430 f.write_str(
431 "#error No native saturating sub exists, TODO: Should be replaced in a preprocessor\n",
432 )
433 }
434
435 fn compile_instruction_max_function_name(
437 f: &mut std::fmt::Formatter<'_>,
438 item: Item<Self>,
439 ) -> std::fmt::Result {
440 let max = match item.elem() {
441 Elem::F16 => "__hmax",
442 Elem::BF16 => "max_bfloat16",
443 _ => "max",
444 };
445 write!(f, "{max}")
446 }
447
448 fn compile_instruction_min_function_name(
449 f: &mut std::fmt::Formatter<'_>,
450 item: Item<Self>,
451 ) -> std::fmt::Result {
452 let min = match item.elem() {
453 Elem::F16 => "__hmin",
454 Elem::BF16 => "min_bfloat16",
455 _ => "min",
456 };
457 write!(f, "{min}")
458 }
459
460 fn compile_warp_shuffle(
462 f: &mut std::fmt::Formatter<'_>,
463 var: &str,
464 source: &str,
465 ) -> std::fmt::Result {
466 write!(f, "__shfl({var}, {source})")
467 }
468 fn compile_warp_shuffle_xor(
469 f: &mut std::fmt::Formatter<'_>,
470 var: &str,
471 elem: &Elem<Self>,
472 offset: &str,
473 ) -> std::fmt::Result {
474 match elem {
475 Elem::BF16 => write!(
476 f,
477 "half_to_bfloat16(__shfl_xor(reinterpret_cast<__half&>({var}), {offset}))"
478 ),
479 _ => write!(f, "__shfl_xor({var}, {offset})"),
480 }
481 }
482 fn compile_warp_shuffle_up(
483 f: &mut std::fmt::Formatter<'_>,
484 var: &str,
485 offset: &str,
486 ) -> std::fmt::Result {
487 write!(f, "__shfl_up({var}, {offset})")
488 }
489 fn compile_warp_shuffle_down(
490 f: &mut std::fmt::Formatter<'_>,
491 var: &str,
492 offset: &str,
493 ) -> std::fmt::Result {
494 write!(f, "__shfl_down({var}, {offset})")
495 }
496 fn compile_warp_all<T: Component<Self>>(
497 f: &mut std::fmt::Formatter<'_>,
498 input: &T,
499 ) -> std::fmt::Result {
500 let item = input.item();
501 let elem = item.elem;
502 write!(f, "static_cast<{elem}>(__all({input}))")
503 }
504 fn compile_warp_any<T: Component<Self>>(
505 f: &mut std::fmt::Formatter<'_>,
506 input: &T,
507 ) -> std::fmt::Result {
508 let item = input.item();
509 let elem = item.elem;
510 write!(f, "static_cast<{elem}>(__any({input}))")
511 }
512 fn compile_warp_ballot(
513 f: &mut std::fmt::Formatter<'_>,
514 input: &Variable<Self>,
515 out_elem: &Elem<Self>,
516 ) -> std::fmt::Result {
517 write!(f, "{out_elem}(__ballot({input}))")
518 }
519}
520
521impl<M: DialectWmmaCompiler<Self>> DialectWmmaCompiler<Self> for HipDialect<M> {
524 fn compile_wmma_includes(f: &mut std::fmt::Formatter<'_>, flags: &Flags) -> std::fmt::Result {
525 M::compile_wmma_includes(f, flags)
526 }
527
528 fn compile_wmma_type_definitions(
529 f: &mut std::fmt::Formatter<'_>,
530 flags: &Flags,
531 ) -> std::fmt::Result {
532 M::compile_wmma_type_definitions(f, flags)
533 }
534
535 fn compile_wmma_local_variables(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
536 M::compile_wmma_local_variables(f)
537 }
538
539 fn compile_wmma_fragment_declaration(
540 f: &mut std::fmt::Formatter<'_>,
541 var: &Variable<Self>,
542 ) -> std::fmt::Result {
543 M::compile_wmma_fragment_declaration(f, var)
544 }
545
546 fn compile_wwma_fragment_ident(
547 f: &mut std::fmt::Formatter<'_>,
548 ident: &crate::shared::FragmentIdent<Self>,
549 ) -> std::fmt::Result {
550 M::compile_wwma_fragment_ident(f, ident)
551 }
552
553 fn compile_wmma_fragment_layout(
554 f: &mut std::fmt::Formatter<'_>,
555 layout: &crate::shared::FragmentLayout<Self>,
556 ) -> std::fmt::Result {
557 M::compile_wmma_fragment_layout(f, layout)
558 }
559
560 fn compile_wmma_fragment(
561 f: &mut std::fmt::Formatter<'_>,
562 fragment: &crate::shared::Fragment<Self>,
563 ) -> std::fmt::Result {
564 M::compile_wmma_fragment(f, fragment)
565 }
566
567 fn compile_wmma_instruction(
568 f: &mut std::fmt::Formatter<'_>,
569 instruction: &crate::shared::WmmaInstruction<Self>,
570 ) -> std::fmt::Result {
571 M::compile_wmma_instruction(f, instruction)
572 }
573
574 fn compile_manual_mma(
575 f: &mut std::fmt::Formatter<'_>,
576 mma: ManualMma<Self>,
577 ) -> std::fmt::Result {
578 M::compile_manual_mma(f, mma)
579 }
580
581 fn supported_wmma_combinations(
582 arch: &AMDArchitecture,
583 ) -> crate::shared::SupportedMmaCombinations {
584 M::supported_wmma_combinations(arch)
585 }
586
587 fn supported_mma_combinations(arch: &AMDArchitecture) -> shared::SupportedMmaCombinations {
588 M::supported_mma_combinations(arch)
589 }
590
591 fn compile_scaled_mma(
592 _f: &mut std::fmt::Formatter<'_>,
593 _mma: ManualMma<Self>,
594 _scales_a: Variable<Self>,
595 _scales_b: Variable<Self>,
596 _scales_factor: u32,
597 ) -> std::fmt::Result {
598 panic!("Scaled MMA not supporter in HIP")
599 }
600}
601
602impl<M: DialectWmmaCompiler<Self>> DialectProcessors<Self> for HipDialect<M> {
603 fn processors() -> Vec<Box<dyn Processor>> {
604 vec![
605 Box::new(HipMmaProcessor),
606 Box::new(SaturatingArithmeticProcessor::new(true)),
607 ]
608 }
609}