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::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 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
313impl<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,
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 writeln!(
353 f,
354 "extern __shared__ __align__({max_align}) uchar dynamic_shared_mem[];"
355 )?;
356 }
357 Ok(())
358 }
359}
360
361impl<M: DialectWmmaCompiler<Self>> DialectCubeBuiltins<Self> for HipDialect<M> {}
364
365impl<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 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_saturating_add(
415 f: &mut std::fmt::Formatter<'_>,
416 _lhs: impl Display,
417 _rhs: impl Display,
418 _item: Item<Self>,
419 ) -> std::fmt::Result {
420 f.write_str(
421 "#error No native saturating add exists, TODO: Should be replaced in a preprocessor\n",
422 )
423 }
424
425 fn compile_saturating_sub(
426 f: &mut std::fmt::Formatter<'_>,
427 _lhs: impl Display,
428 _rhs: impl Display,
429 _item: Item<Self>,
430 ) -> std::fmt::Result {
431 f.write_str(
432 "#error No native saturating sub exists, TODO: Should be replaced in a preprocessor\n",
433 )
434 }
435
436 fn compile_instruction_max_function_name(
438 f: &mut std::fmt::Formatter<'_>,
439 item: Item<Self>,
440 ) -> std::fmt::Result {
441 let max = match item.elem() {
442 Elem::F16 => "__hmax",
443 Elem::BF16 => "max_bfloat16",
444 _ => "max",
445 };
446 write!(f, "{max}")
447 }
448
449 fn compile_instruction_min_function_name(
450 f: &mut std::fmt::Formatter<'_>,
451 item: Item<Self>,
452 ) -> std::fmt::Result {
453 let min = match item.elem() {
454 Elem::F16 => "__hmin",
455 Elem::BF16 => "min_bfloat16",
456 _ => "min",
457 };
458 write!(f, "{min}")
459 }
460
461 fn compile_warp_shuffle(
463 f: &mut std::fmt::Formatter<'_>,
464 var: &str,
465 source: &str,
466 ) -> std::fmt::Result {
467 write!(f, "__shfl({var}, {source})")
468 }
469 fn compile_warp_shuffle_xor(
470 f: &mut std::fmt::Formatter<'_>,
471 var: &str,
472 elem: &Elem<Self>,
473 offset: &str,
474 ) -> std::fmt::Result {
475 match elem {
476 Elem::BF16 => write!(
477 f,
478 "half_to_bfloat16(__shfl_xor(reinterpret_cast<__half&>({var}), {offset}))"
479 ),
480 _ => write!(f, "__shfl_xor({var}, {offset})"),
481 }
482 }
483 fn compile_warp_shuffle_up(
484 f: &mut std::fmt::Formatter<'_>,
485 var: &str,
486 offset: &str,
487 ) -> std::fmt::Result {
488 write!(f, "__shfl_up({var}, {offset})")
489 }
490 fn compile_warp_shuffle_down(
491 f: &mut std::fmt::Formatter<'_>,
492 var: &str,
493 offset: &str,
494 ) -> std::fmt::Result {
495 write!(f, "__shfl_down({var}, {offset})")
496 }
497 fn compile_warp_all<T: Component<Self>>(
498 f: &mut std::fmt::Formatter<'_>,
499 input: &T,
500 ) -> std::fmt::Result {
501 let item = input.item();
502 let elem = item.elem;
503 write!(f, "static_cast<{elem}>(__all({input}))")
504 }
505 fn compile_warp_any<T: Component<Self>>(
506 f: &mut std::fmt::Formatter<'_>,
507 input: &T,
508 ) -> std::fmt::Result {
509 let item = input.item();
510 let elem = item.elem;
511 write!(f, "static_cast<{elem}>(__any({input}))")
512 }
513 fn compile_warp_ballot(
514 f: &mut std::fmt::Formatter<'_>,
515 input: &Variable<Self>,
516 out_elem: &Elem<Self>,
517 ) -> std::fmt::Result {
518 write!(f, "{out_elem}(__ballot({input}))")
519 }
520}
521
522impl<M: DialectWmmaCompiler<Self>> DialectWmmaCompiler<Self> for HipDialect<M> {
525 fn compile_wmma_includes(f: &mut std::fmt::Formatter<'_>, flags: &Flags) -> std::fmt::Result {
526 M::compile_wmma_includes(f, flags)
527 }
528
529 fn compile_wmma_type_definitions(
530 f: &mut std::fmt::Formatter<'_>,
531 flags: &Flags,
532 ) -> std::fmt::Result {
533 M::compile_wmma_type_definitions(f, flags)
534 }
535
536 fn compile_wmma_local_variables(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537 M::compile_wmma_local_variables(f)
538 }
539
540 fn compile_wmma_fragment_declaration(
541 f: &mut std::fmt::Formatter<'_>,
542 var: &Variable<Self>,
543 ) -> std::fmt::Result {
544 M::compile_wmma_fragment_declaration(f, var)
545 }
546
547 fn compile_wwma_fragment_ident(
548 f: &mut std::fmt::Formatter<'_>,
549 ident: &crate::shared::FragmentIdent<Self>,
550 ) -> std::fmt::Result {
551 M::compile_wwma_fragment_ident(f, ident)
552 }
553
554 fn compile_wmma_fragment_layout(
555 f: &mut std::fmt::Formatter<'_>,
556 layout: &crate::shared::FragmentLayout<Self>,
557 ) -> std::fmt::Result {
558 M::compile_wmma_fragment_layout(f, layout)
559 }
560
561 fn compile_wmma_fragment(
562 f: &mut std::fmt::Formatter<'_>,
563 fragment: &crate::shared::Fragment<Self>,
564 ) -> std::fmt::Result {
565 M::compile_wmma_fragment(f, fragment)
566 }
567
568 fn compile_wmma_instruction(
569 f: &mut std::fmt::Formatter<'_>,
570 instruction: &crate::shared::WmmaInstruction<Self>,
571 ) -> std::fmt::Result {
572 M::compile_wmma_instruction(f, instruction)
573 }
574
575 fn compile_manual_mma(
576 f: &mut std::fmt::Formatter<'_>,
577 mma: ManualMma<Self>,
578 ) -> std::fmt::Result {
579 M::compile_manual_mma(f, mma)
580 }
581
582 fn supported_wmma_combinations(
583 arch: &AMDArchitecture,
584 ) -> crate::shared::SupportedMmaCombinations {
585 M::supported_wmma_combinations(arch)
586 }
587
588 fn supported_mma_combinations(arch: &AMDArchitecture) -> shared::SupportedMmaCombinations {
589 M::supported_mma_combinations(arch)
590 }
591
592 fn compile_scaled_mma(
593 _f: &mut std::fmt::Formatter<'_>,
594 _mma: ManualMma<Self>,
595 _scales_a: Variable<Self>,
596 _scales_b: Variable<Self>,
597 _scales_factor: u32,
598 ) -> std::fmt::Result {
599 panic!("Scaled MMA not supporter in HIP")
600 }
601}
602
603impl<M: DialectWmmaCompiler<Self>> DialectProcessors<Self> for HipDialect<M> {
604 fn processors() -> Vec<Box<dyn Processor>> {
605 vec![
606 Box::new(HipMmaProcessor),
607 Box::new(SaturatingArithmeticProcessor::new(true)),
608 ]
609 }
610}