Skip to main content

tvm_tirx/tirx/
op.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! Operators of the dialect. The functions build calls of its operators, such as [`logaddexp`]
21//! and [`reinterpret`]; a [`CallFFIKernelAttr`] holds the launch metadata of a `call_ffi_kernel`
22//! call.
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// Names the hand-written wrappers use: the import section keeps them even when no generated block
26// does.
27// tvm-ffi-stubgen(import): crate::ir::expr::Expr
28// tvm-ffi-stubgen(import): crate::ir::location::Location
29// tvm-ffi-stubgen(import): crate::ir::r#type::Type
30// tvm-ffi-stubgen(import): tvm_ffi::Result
31// tvm-ffi-stubgen(import): crate::ir::expr::Call
32// tvm-ffi-stubgen(import): crate::ir::expr::FloatImm
33// tvm-ffi-stubgen(import): crate::ir::expr::StringImmObj
34// tvm-ffi-stubgen(import): crate::ir::location::UNKNOWN_LOC
35// tvm-ffi-stubgen(import): crate::ir::prim::op::ExprResult
36// tvm-ffi-stubgen(import): crate::ir::prim::op::PrimOps
37// tvm-ffi-stubgen(import): crate::ir::prim::op::add
38// tvm-ffi-stubgen(import): crate::ir::prim::op::exp
39// tvm-ffi-stubgen(import): crate::ir::prim::op::log
40// tvm-ffi-stubgen(import): crate::ir::prim::op::match_types_at
41// tvm-ffi-stubgen(import): crate::ir::r#type::PrimType
42// tvm-ffi-stubgen(import): crate::ir::r#type::PtrTypeObj
43// tvm-ffi-stubgen(import): crate::ir::support
44// tvm-ffi-stubgen(import): tvm_ffi::DLDataTypeCode
45// tvm-ffi-stubgen(import): tvm_ffi::INTERNAL_ERROR
46// tvm-ffi-stubgen(import): tvm_ffi::ObjectRefCore
47// tvm-ffi-stubgen(import): tvm_ffi::TYPE_ERROR
48// tvm-ffi-stubgen(import): crate::ir::expr::IntoExpr
49// tvm-ffi-stubgen(import): crate::ir::expr::PrimExpr
50// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
51// tvm-ffi-stubgen(import): std::borrow::Borrow
52
53// tvm-ffi-stubgen(begin): import-section
54use crate::ir::attrs::Attrs;
55use crate::ir::attrs::AttrsObj;
56use crate::ir::expr::Call;
57use crate::ir::expr::Expr;
58use crate::ir::expr::FloatImm;
59use crate::ir::expr::IntoExpr;
60use crate::ir::expr::PrimExpr;
61use crate::ir::expr::StringImmObj;
62use crate::ir::location::Location;
63use crate::ir::location::UNKNOWN_LOC;
64use crate::ir::prim::op::ExprResult;
65use crate::ir::prim::op::PrimOps;
66use crate::ir::prim::op::add;
67use crate::ir::prim::op::exp;
68use crate::ir::prim::op::log;
69use crate::ir::prim::op::match_types_at;
70use crate::ir::r#type::PrimType;
71use crate::ir::r#type::PtrTypeObj;
72use crate::ir::r#type::Type;
73use crate::ir::support;
74use std::borrow::Borrow;
75use std::ops::Deref;
76use tvm_ffi::Array;
77use tvm_ffi::DLDataTypeCode;
78use tvm_ffi::INTERNAL_ERROR;
79use tvm_ffi::IntoArg;
80use tvm_ffi::Map;
81use tvm_ffi::ObjectArc;
82use tvm_ffi::ObjectRefCore;
83use tvm_ffi::Result;
84use tvm_ffi::String;
85use tvm_ffi::TYPE_ERROR;
86// tvm-ffi-stubgen(end)
87
88/// The launch metadata of a `call_ffi_kernel` call, whose arguments are the kernel symbol, the
89/// kernel operands and then the launch values.
90///
91/// `launch_params` tags the launch values in order (a flag-only tag takes no value, and the dynamic
92/// shared-memory size, when present, comes last), `launch_fields` names the CUDA launch
93/// configuration field each launch value sets, `num_kernel_args` counts the kernel operands, and
94/// `kernel_attrs` holds the compile-time requirements of the kernel.
95// tvm-ffi-stubgen(begin): object/tirx.CallFFIKernelAttr
96#[allow(missing_docs)]
97#[repr(C)]
98#[derive(tvm_ffi::derive::ObjectRef, Clone)]
99pub struct CallFFIKernelAttr {
100    data_: ObjectArc<CallFFIKernelAttrObj>,
101}
102
103/// The object behind [`CallFFIKernelAttr`].
104// Complete: reflected fields fill [24, 56) exactly.
105#[allow(missing_docs)]
106#[repr(C)]
107#[derive(tvm_ffi::derive::Object)]
108#[object(type_key = "tirx.CallFFIKernelAttr", final, immutable)]
109pub struct CallFFIKernelAttrObj {
110    base_: AttrsObj,
111    pub launch_params: Array<String>,
112    pub launch_fields: Array<String>,
113    pub num_kernel_args: i64,
114    pub kernel_attrs: Map<String, i64>,
115}
116
117const _: () = {
118    assert!(::core::mem::size_of::<CallFFIKernelAttrObj>() == 56);
119    assert!(::core::mem::align_of::<CallFFIKernelAttrObj>() == 8);
120};
121
122impl Deref for CallFFIKernelAttrObj {
123    type Target = AttrsObj;
124    fn deref(&self) -> &AttrsObj {
125        &self.base_
126    }
127}
128
129#[allow(missing_docs)]
130impl CallFFIKernelAttrObj {
131    pub(crate) fn new(
132        launch_params: Array<String>,
133        launch_fields: Array<String>,
134        num_kernel_args: i64,
135        kernel_attrs: Map<String, i64>,
136    ) -> Self {
137        let base_ = AttrsObj::new();
138        Self { base_, launch_params, launch_fields, num_kernel_args, kernel_attrs }
139    }
140}
141
142#[allow(missing_docs)]
143impl CallFFIKernelAttr {
144    /// Create a `CallFFIKernelAttr` from its field values.
145    pub fn new(
146        launch_params: impl Into<Array<String>>,
147        launch_fields: impl Into<Array<String>>,
148        num_kernel_args: i64,
149        kernel_attrs: impl Into<Map<String, i64>>,
150    ) -> Self {
151        let obj = CallFFIKernelAttrObj::new(
152            launch_params.into(),
153            launch_fields.into(),
154            num_kernel_args,
155            kernel_attrs.into(),
156        );
157        Self { data_: ObjectArc::new(obj) }
158    }
159}
160
161tvm_ffi::impl_object_ref_upcast!(CallFFIKernelAttr => Attrs);
162// tvm-ffi-stubgen(end)
163
164// The native `tirx.CallFFIKernelAttr` stores its fields as given, as the generated
165// `CallFFIKernelAttr::new` does.
166
167/// Build `log(exp(a) + exp(b))` of the floating-point `a` and `b`, matched to one type.
168///
169/// # Errors
170///
171/// Returns an error if an operand is not floating-point.
172pub fn logaddexp(a: impl IntoExpr<PrimExpr>, b: impl IntoExpr<PrimExpr>) -> Result<PrimExpr> {
173    logaddexp_at(a, b, UNKNOWN_LOC)
174}
175
176/// Build [`logaddexp`] with the casts at `loc`.
177pub fn logaddexp_at(
178    a: impl IntoExpr<PrimExpr>,
179    b: impl IntoExpr<PrimExpr>,
180    loc: impl IntoArg<Location>,
181) -> Result<PrimExpr> {
182    let (a, b) = (a.into_owned_expr()?, b.into_owned_expr()?);
183    for (operand, side) in [(&a, "a"), (&b, "b")] {
184        if !operand.prim_ty().matches_code(&[DLDataTypeCode::kDLFloat]) {
185            let condition = format!("{side}.ty().MatchesCode(DLDataTypeCode::kDLFloat)");
186            let message = operand.to_string();
187            return Err(support::check_failed(INTERNAL_ERROR, &condition, &message));
188        }
189    }
190    let (a, b) = match_types_at(a, b, loc)?;
191    log(add(exp(a)?, exp(b)?)?)
192}
193
194/// Reinterpret `value` bit for bit as the primitive or pointer type `ty` (`tirx.reinterpret`).
195///
196/// Besides primitive types of the same size, a string reinterprets as a pointer and a pointer as a
197/// scalar `int64`, and back.
198///
199/// # Examples
200///
201/// ```
202/// use tvm_tirx::ir::{PrimType, PrimVar, UNKNOWN_LOC};
203/// use tvm_tirx::script::script;
204/// use tvm_tirx::tirx::reinterpret;
205///
206/// let x = PrimVar::new("x", PrimType::float(32), UNKNOWN_LOC);
207/// assert_eq!(script(&reinterpret(PrimType::int(32), &x)?)?, "T.reinterpret(x, ty=T.int32)");
208/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
209/// ```
210///
211/// # Errors
212///
213/// Returns an error for any other pair of types, or two primitive types of different sizes.
214pub fn reinterpret(ty: impl IntoArg<Type>, value: impl IntoExpr) -> Result<Expr> {
215    reinterpret_at(ty, value, UNKNOWN_LOC)
216}
217
218/// Build [`reinterpret`] at `loc`.
219pub fn reinterpret_at(
220    ty: impl IntoArg<Type>,
221    value: impl IntoExpr,
222    loc: impl IntoArg<Location>,
223) -> Result<Expr> {
224    let (ty, value) = (ty.into_arg(), value.into_owned_expr()?);
225    let ty: &Type = ty.borrow();
226    let target_is_pointer = ty.downcast_ref::<PtrTypeObj>().is_some();
227    let source_is_pointer = value.ty.downcast_ref::<PtrTypeObj>().is_some();
228    let type_error = |condition: &str, message: std::string::String| {
229        Err(support::check_failed(TYPE_ERROR, condition, &message))
230    };
231    if value.downcast_ref::<StringImmObj>().is_some() {
232        if !target_is_pointer {
233            let message = format!("String reinterpret requires a pointer target, but got {ty}");
234            return type_error("target_ty.as<PtrTypeObj>()", message);
235        }
236    } else if let Some(target) = ty.downcast_ref::<PrimType>() {
237        if let Some(source) = value.ty.downcast_ref::<PrimType>() {
238            if source.dtype == target.dtype {
239                return Ok(value);
240            }
241            if !target.is_scalable_vector() && !source.is_scalable_vector() {
242                let bits =
243                    |ty: &PrimType| ty.lanes().map(|lanes| u32::from(ty.bits()) * u32::from(lanes));
244                let float4 = [DLDataTypeCode::kDLFloat4_e2m1fn];
245                let same_size = bits(source) == bits(target)
246                    || ((source.matches_code(&float4) || target.matches_code(&float4))
247                        && source.storage_bytes() == target.storage_bytes());
248                if !same_size {
249                    let condition = "value_bits == target_bits || \
250                                     ((value_dtype.MatchesCode(DLDataTypeCode::kDLFloat4_e2m1fn) || \
251                                     target_prim.MatchesCode(DLDataTypeCode::kDLFloat4_e2m1fn)) && \
252                                     value_dtype.StorageBytes() == target_prim.StorageBytes())";
253                    let message = format!("Reinterpret requires size match {} vs {}", ty, value.ty);
254                    return Err(support::check_failed(INTERNAL_ERROR, condition, &message));
255                }
256            }
257        } else {
258            if !source_is_pointer {
259                let message =
260                    format!("Reinterpret source must be PrimType or PtrType, but got {}", value.ty);
261                return type_error("value->ty.as<PtrTypeObj>()", message);
262            }
263            if !is_scalar_int64(target) {
264                let condition = "target_dtype.value().IsScalar() && target_dtype.value().bits() == 64 && \
265                                 target_dtype.value().MatchesCode(DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt)";
266                let message = format!(
267                    "Pointer reinterpret requires a scalar 64-bit integer target, but got {ty}"
268                );
269                return type_error(condition, message);
270            }
271        }
272    } else {
273        if !target_is_pointer {
274            let message = format!("Reinterpret target must be PrimType or PtrType, but got {ty}");
275            return type_error("target_ty.as<PtrTypeObj>()", message);
276        }
277        if let Some(source) = value.ty.downcast_ref::<PrimType>() {
278            if !is_scalar_int64(source) {
279                let condition = "source_dtype.value().IsScalar() && source_dtype.value().bits() == 64 && \
280                                 source_dtype.value().MatchesCode(DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt)";
281                let message = format!(
282                    "Pointer reinterpret requires a scalar 64-bit integer source, but got {}",
283                    value.ty
284                );
285                return type_error(condition, message);
286            }
287        } else if !source_is_pointer {
288            let message =
289                format!("Reinterpret source must be PrimType or PtrType, but got {}", value.ty);
290            return type_error("value->ty.as<PtrTypeObj>()", message);
291        }
292    }
293    let op = support::cached_op("tirx.reinterpret")?;
294    Ok(Call::new(Some(ty), op, vec![value], None, Vec::<Type>::new(), loc)?.into())
295}
296
297/// Build a rational approximation of `erf(arg)` on `[-4, 4]` in `bits`-bit floats, as the Metal and
298/// WebGPU backends lower `erf`.
299pub fn fast_erf_float_expr(arg: impl IntoExpr<PrimExpr>, bits: u8) -> Result<PrimExpr> {
300    let ty = PrimType::float(bits);
301    // The coefficients are single-precision values.
302    let constant =
303        |value: f32| -> ExprResult { FloatImm::new(&ty, f64::from(value), UNKNOWN_LOC).into() };
304    // alpha_1, alpha_3, ..., alpha_13: the odd coefficients of the numerator.
305    #[allow(clippy::excessive_precision)]
306    let alpha: [f32; 7] = [
307        -1.60960333262415e-02,
308        -2.95459980854025e-03,
309        -7.34990630326855e-04,
310        -5.69250639462346e-05,
311        -2.10102402082508e-06,
312        2.77068142495902e-08,
313        -2.72614225801306e-10,
314    ];
315    // beta_0, beta_2, ..., beta_8: the even coefficients of the denominator.
316    #[allow(clippy::excessive_precision)]
317    let beta: [f32; 5] = [
318        -1.42647390514189e-02,
319        -7.37332916720468e-03,
320        -1.68282697438203e-03,
321        -2.13374055278905e-04,
322        -1.45660718464996e-05,
323    ];
324    let x = arg.into_owned_expr()?.min(constant(4.0)).max(constant(-4.0));
325    let x2 = &x * &x;
326    // Horner's rule from the highest coefficient down.
327    let mut p = &x2 * constant(alpha[6]) + constant(alpha[5]);
328    for coefficient in alpha[..5].iter().rev() {
329        p = &x2 * p + constant(*coefficient);
330    }
331    p = &x * p;
332    let mut q = &x2 * constant(beta[4]) + constant(beta[3]);
333    for coefficient in beta[..3].iter().rev() {
334        q = &x2 * q + constant(*coefficient);
335    }
336    p.div(q).try_into()
337}
338
339/// Build a return from the current GPU thread, without a value (`tirx.gpu_thread_return`).
340pub fn gpu_thread_return() -> Result<PrimExpr> {
341    gpu_thread_return_at(UNKNOWN_LOC)
342}
343
344/// Build [`gpu_thread_return`] at `loc`.
345pub fn gpu_thread_return_at(loc: impl IntoArg<Location>) -> Result<PrimExpr> {
346    tvm_ffi::cached_global_func!("tirx.gpu_thread_return")
347        .call_tuple((loc.into_arg().borrow(),))?
348        .try_into()
349}
350
351/// Whether `ty` is a scalar 64-bit integer, which a pointer reinterprets as.
352fn is_scalar_int64(ty: &PrimType) -> bool {
353    ty.is_scalar()
354        && ty.bits() == 64
355        && ty.matches_code(&[DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt])
356}