cubecl_cpp/shared/
unary.rs

1use super::{Component, Dialect, Elem, FmtLeft, Variable};
2use std::fmt::Display;
3
4pub trait Unary<D: Dialect> {
5    fn format(
6        f: &mut std::fmt::Formatter<'_>,
7        input: &Variable<D>,
8        out: &Variable<D>,
9    ) -> std::fmt::Result {
10        let out_item = out.item();
11
12        if out_item.vectorization == 1 {
13            write!(f, "{} = ", out.fmt_left())?;
14            Self::format_scalar(f, *input, out_item.elem)?;
15            f.write_str(";\n")
16        } else {
17            Self::unroll_vec(f, input, out, out_item.elem, out_item.vectorization)
18        }
19    }
20
21    fn format_scalar<Input: Component<D>>(
22        f: &mut std::fmt::Formatter<'_>,
23        input: Input,
24        out_elem: Elem<D>,
25    ) -> std::fmt::Result;
26
27    fn unroll_vec(
28        f: &mut std::fmt::Formatter<'_>,
29        input: &Variable<D>,
30        out: &Variable<D>,
31        out_elem: Elem<D>,
32        index: usize,
33    ) -> std::fmt::Result {
34        let mut write_op = |index, out_elem, input: &Variable<D>, out: &Variable<D>| {
35            let out_item = out.item();
36            let out = out.fmt_left();
37            writeln!(f, "{out} = {out_item}{{")?;
38
39            for i in 0..index {
40                let inputi = input.index(i);
41
42                Self::format_scalar(f, inputi, out_elem)?;
43                f.write_str(",")?;
44            }
45
46            f.write_str("};\n")
47        };
48
49        if Self::can_optimize() {
50            let optimized = Variable::optimized_args([*input, *out]);
51            let [input, out_optimized] = optimized.args;
52
53            let item_out_original = out.item();
54            let item_out_optimized = out_optimized.item();
55
56            let (index, out_elem) = match optimized.optimization_factor {
57                Some(factor) => (index / factor, out_optimized.elem()),
58                None => (index, out_elem),
59            };
60
61            if item_out_original != item_out_optimized {
62                let out_tmp = Variable::tmp(item_out_optimized);
63
64                write_op(index, out_elem, &input, &out_tmp)?;
65                let qualifier = out.const_qualifier();
66                let addr_space = D::address_space_for_variable(out);
67                let out_fmt = out.fmt_left();
68                writeln!(
69                    f,
70                    "{out_fmt} = reinterpret_cast<{addr_space}{item_out_original}{qualifier}&>({out_tmp});\n"
71                )
72            } else {
73                write_op(index, out_elem, &input, &out_optimized)
74            }
75        } else {
76            write_op(index, out_elem, input, out)
77        }
78    }
79
80    fn can_optimize() -> bool {
81        true
82    }
83}
84
85pub trait FunctionFmt<D: Dialect> {
86    fn base_function_name() -> &'static str;
87    fn function_name(elem: Elem<D>) -> String {
88        if Self::half_support() {
89            let prefix = match elem {
90                Elem::F16 | Elem::BF16 => D::compile_instruction_half_function_name_prefix(),
91                Elem::F16x2 | Elem::BF16x2 => D::compile_instruction_half2_function_name_prefix(),
92                _ => "",
93            };
94            format!("{prefix}{}", Self::base_function_name())
95        } else {
96            Self::base_function_name().into()
97        }
98    }
99    fn format_unary<Input: Display>(
100        f: &mut std::fmt::Formatter<'_>,
101        input: Input,
102        elem: Elem<D>,
103    ) -> std::fmt::Result {
104        if Self::half_support() {
105            write!(f, "{}({input})", Self::function_name(elem))
106        } else {
107            match elem {
108                Elem::F16 | Elem::F16x2 | Elem::BF16 | Elem::BF16x2 => {
109                    write!(f, "{}({}(float({input})))", elem, Self::function_name(elem))
110                }
111                _ => write!(f, "{}({input})", Self::function_name(elem)),
112            }
113        }
114    }
115
116    fn half_support() -> bool;
117}
118
119macro_rules! function {
120    ($name:ident, $func:expr) => {
121        function!($name, $func, true);
122    };
123    ($name:ident, $func:expr, $half_support:expr) => {
124        pub struct $name;
125
126        impl<D: Dialect> FunctionFmt<D> for $name {
127            fn base_function_name() -> &'static str {
128                $func
129            }
130            fn half_support() -> bool {
131                $half_support
132            }
133        }
134
135        impl<D: Dialect> Unary<D> for $name {
136            fn format_scalar<Input: Display>(
137                f: &mut std::fmt::Formatter<'_>,
138                input: Input,
139                elem: Elem<D>,
140            ) -> std::fmt::Result {
141                Self::format_unary(f, input, elem)
142            }
143
144            fn can_optimize() -> bool {
145                $half_support
146            }
147        }
148    };
149}
150
151function!(Log, "log");
152function!(FastLog, "__logf", false);
153function!(Sin, "sin");
154function!(Cos, "cos");
155function!(Tan, "tan", false);
156function!(Sinh, "sinh", false);
157function!(Cosh, "cosh", false);
158// Tanh is separate below, idk why
159function!(ArcCos, "acos", false);
160function!(ArcSin, "asin", false);
161function!(ArcTan, "atan", false);
162function!(ArcSinh, "asinh", false);
163function!(ArcCosh, "acosh", false);
164function!(ArcTanh, "atanh", false);
165function!(FastSin, "__sinf", false);
166function!(FastCos, "__cosf", false);
167function!(Sqrt, "sqrt");
168function!(InverseSqrt, "rsqrt");
169function!(FastSqrt, "__fsqrt_rn", false);
170function!(FastInverseSqrt, "__frsqrt_rn", false);
171function!(Exp, "exp");
172function!(FastExp, "__expf", false);
173function!(Ceil, "ceil");
174function!(Trunc, "trunc");
175function!(Floor, "floor");
176function!(Round, "rint");
177function!(FastRecip, "__frcp_rn", false);
178function!(FastTanh, "__tanhf", false);
179
180function!(Erf, "erf", false);
181function!(Abs, "abs", false);
182
183pub struct Log1p;
184
185impl<D: Dialect> Unary<D> for Log1p {
186    fn format_scalar<Input: Component<D>>(
187        f: &mut std::fmt::Formatter<'_>,
188        input: Input,
189        _out_elem: Elem<D>,
190    ) -> std::fmt::Result {
191        D::compile_instruction_log1p_scalar(f, input)
192    }
193
194    fn can_optimize() -> bool {
195        false
196    }
197}
198
199pub struct Tanh;
200
201impl<D: Dialect> Unary<D> for Tanh {
202    fn format_scalar<Input: Component<D>>(
203        f: &mut std::fmt::Formatter<'_>,
204        input: Input,
205        _out_elem: Elem<D>,
206    ) -> std::fmt::Result {
207        D::compile_instruction_tanh_scalar(f, input)
208    }
209
210    fn can_optimize() -> bool {
211        false
212    }
213}
214
215pub struct Degrees;
216
217impl<D: Dialect> Unary<D> for Degrees {
218    fn format_scalar<Input: Component<D>>(
219        f: &mut std::fmt::Formatter<'_>,
220        input: Input,
221        elem: Elem<D>,
222    ) -> std::fmt::Result {
223        write!(f, "{input}*{elem}(57.29577951308232f)")
224    }
225
226    fn can_optimize() -> bool {
227        false
228    }
229}
230
231pub struct Radians;
232
233impl<D: Dialect> Unary<D> for Radians {
234    fn format_scalar<Input: Component<D>>(
235        f: &mut std::fmt::Formatter<'_>,
236        input: Input,
237        elem: Elem<D>,
238    ) -> std::fmt::Result {
239        write!(f, "{input}*{elem}(0.017453292519943295f)")
240    }
241
242    fn can_optimize() -> bool {
243        false
244    }
245}
246
247pub fn zero_extend<D: Dialect>(input: impl Component<D>) -> String {
248    match input.elem() {
249        Elem::I8 => format!("{}({}({input}))", Elem::<D>::U32, Elem::<D>::U8),
250        Elem::I16 => format!("{}({}({input}))", Elem::<D>::U32, Elem::<D>::U16),
251        Elem::U8 => format!("{}({input})", Elem::<D>::U32),
252        Elem::U16 => format!("{}({input})", Elem::<D>::U32),
253        _ => unreachable!("zero extend only supports integer < 32 bits"),
254    }
255}
256
257pub struct CountBits;
258
259impl<D: Dialect> Unary<D> for CountBits {
260    fn format_scalar<Input: Component<D>>(
261        f: &mut std::fmt::Formatter<'_>,
262        input: Input,
263        elem: Elem<D>,
264    ) -> std::fmt::Result {
265        D::compile_instruction_popcount_scalar(f, input, elem)
266    }
267}
268
269pub struct ReverseBits;
270
271impl<D: Dialect> Unary<D> for ReverseBits {
272    fn format_scalar<Input: Component<D>>(
273        f: &mut std::fmt::Formatter<'_>,
274        input: Input,
275        elem: Elem<D>,
276    ) -> std::fmt::Result {
277        D::compile_instruction_reverse_bits_scalar(f, input, elem)
278    }
279}
280
281pub struct LeadingZeros;
282
283impl<D: Dialect> Unary<D> for LeadingZeros {
284    fn format_scalar<Input: Component<D>>(
285        f: &mut std::fmt::Formatter<'_>,
286        input: Input,
287        elem: Elem<D>,
288    ) -> std::fmt::Result {
289        D::compile_instruction_leading_zeros_scalar(f, input, elem)
290    }
291}
292
293pub struct FindFirstSet;
294
295impl<D: Dialect> Unary<D> for FindFirstSet {
296    fn format_scalar<Input: Component<D>>(
297        f: &mut std::fmt::Formatter<'_>,
298        input: Input,
299        out_elem: Elem<D>,
300    ) -> std::fmt::Result {
301        D::compile_instruction_find_first_set(f, input, out_elem)
302    }
303}
304
305pub struct BitwiseNot;
306
307impl<D: Dialect> Unary<D> for BitwiseNot {
308    fn format_scalar<Input>(
309        f: &mut std::fmt::Formatter<'_>,
310        input: Input,
311        _out_elem: Elem<D>,
312    ) -> std::fmt::Result
313    where
314        Input: Component<D>,
315    {
316        write!(f, "~{input}")
317    }
318}
319
320pub struct Not;
321
322impl<D: Dialect> Unary<D> for Not {
323    fn format_scalar<Input>(
324        f: &mut std::fmt::Formatter<'_>,
325        input: Input,
326        _out_elem: Elem<D>,
327    ) -> std::fmt::Result
328    where
329        Input: Component<D>,
330    {
331        write!(f, "!{input}")
332    }
333}
334
335pub struct Assign;
336
337impl<D: Dialect> Unary<D> for Assign {
338    fn format(
339        f: &mut std::fmt::Formatter<'_>,
340        input: &Variable<D>,
341        out: &Variable<D>,
342    ) -> std::fmt::Result {
343        let item = out.item();
344
345        if item.vectorization == 1 || input.item() == item {
346            write!(f, "{} = ", out.fmt_left())?;
347            Self::format_scalar(f, *input, item.elem)?;
348            f.write_str(";\n")
349        } else {
350            Self::unroll_vec(f, input, out, item.elem, item.vectorization)
351        }
352    }
353
354    fn format_scalar<Input>(
355        f: &mut std::fmt::Formatter<'_>,
356        input: Input,
357        elem: Elem<D>,
358    ) -> std::fmt::Result
359    where
360        Input: Component<D>,
361    {
362        // Cast only when necessary.
363        if elem != input.elem() {
364            match elem {
365                Elem::TF32 => write!(f, "nvcuda::wmma::__float_to_tf32({input})"),
366                elem => write!(f, "{elem}({input})"),
367            }
368        } else {
369            write!(f, "{input}")
370        }
371    }
372}
373
374fn elem_function_name<D: Dialect>(base_name: &'static str, elem: Elem<D>) -> String {
375    // Math functions prefix (no leading underscores)
376    let prefix = match elem {
377        Elem::F16 | Elem::BF16 => D::compile_instruction_half_function_name_prefix(),
378        Elem::F16x2 | Elem::BF16x2 => D::compile_instruction_half2_function_name_prefix(),
379        _ => "",
380    };
381    if prefix.is_empty() {
382        base_name.to_string()
383    } else if prefix == "h" || prefix == "h2" {
384        format!("__{prefix}{base_name}")
385    } else {
386        panic!("Unknown prefix '{prefix}'");
387    }
388}
389
390// `isnan` / `isinf` are defined for cuda/hip/metal with same prefixes for half/bf16 on cuda/hip
391pub struct IsNan;
392
393impl<D: Dialect> Unary<D> for IsNan {
394    fn format_scalar<Input: Component<D>>(
395        f: &mut std::fmt::Formatter<'_>,
396        input: Input,
397        _elem: Elem<D>,
398    ) -> std::fmt::Result {
399        // Format unary function name based on *input* elem dtype
400        let elem = input.elem();
401        write!(f, "{}({input})", elem_function_name("isnan", elem))
402    }
403
404    fn can_optimize() -> bool {
405        true
406    }
407}
408
409pub struct IsInf;
410
411impl<D: Dialect> Unary<D> for IsInf {
412    fn format_scalar<Input: Component<D>>(
413        f: &mut std::fmt::Formatter<'_>,
414        input: Input,
415        _elem: Elem<D>,
416    ) -> std::fmt::Result {
417        // Format unary function name based on *input* elem dtype
418        let elem = input.elem();
419        write!(f, "{}({input})", elem_function_name("isinf", elem))
420    }
421
422    fn can_optimize() -> bool {
423        true
424    }
425}