diff --git a/include/LICENSE b/include/LICENSE new file mode 100644 index 0000000..c16e596 --- /dev/null +++ b/include/LICENSE @@ -0,0 +1,37 @@ +BSD License + +For "ExecuTorch" software + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright 2023 Arm Limited and/or its affiliates. +Copyright (c) Qualcomm Innovation Center, Inc. +Copyright (c) 2023 Apple Inc. +Copyright (c) 2024 MediaTek Inc. +Copyright 2023 NXP +Copyright (c) 2025 Samsung Electronics Co. LTD +Copyright (c) Intel Corporation + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Meta nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/include/c10/macros/Export.h b/include/c10/macros/Export.h new file mode 100644 index 0000000..1b8a681 --- /dev/null +++ b/include/c10/macros/Export.h @@ -0,0 +1 @@ +#include diff --git a/include/c10/macros/Macros.h b/include/c10/macros/Macros.h new file mode 100644 index 0000000..87ebc4f --- /dev/null +++ b/include/c10/macros/Macros.h @@ -0,0 +1 @@ +#include diff --git a/include/c10/util/BFloat16-inl.h b/include/c10/util/BFloat16-inl.h new file mode 100644 index 0000000..6d3510c --- /dev/null +++ b/include/c10/util/BFloat16-inl.h @@ -0,0 +1 @@ +#include diff --git a/include/c10/util/BFloat16-math.h b/include/c10/util/BFloat16-math.h new file mode 100644 index 0000000..4410002 --- /dev/null +++ b/include/c10/util/BFloat16-math.h @@ -0,0 +1,3 @@ +#pragma once + +#include diff --git a/include/c10/util/BFloat16.h b/include/c10/util/BFloat16.h new file mode 100644 index 0000000..6d3510c --- /dev/null +++ b/include/c10/util/BFloat16.h @@ -0,0 +1 @@ +#include diff --git a/include/c10/util/Half-inl.h b/include/c10/util/Half-inl.h new file mode 100644 index 0000000..fe66779 --- /dev/null +++ b/include/c10/util/Half-inl.h @@ -0,0 +1 @@ +#include diff --git a/include/c10/util/Half.h b/include/c10/util/Half.h new file mode 100644 index 0000000..98480b2 --- /dev/null +++ b/include/c10/util/Half.h @@ -0,0 +1,8 @@ +#include + +// need to keep the following for BC because the APIs in here were exposed +// before migrating Half to torch/headeronly +#if (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) +#include +#endif diff --git a/include/c10/util/TypeSafeSignMath.h b/include/c10/util/TypeSafeSignMath.h new file mode 100644 index 0000000..2852022 --- /dev/null +++ b/include/c10/util/TypeSafeSignMath.h @@ -0,0 +1 @@ +#include diff --git a/include/c10/util/bit_cast.h b/include/c10/util/bit_cast.h new file mode 100644 index 0000000..49d0822 --- /dev/null +++ b/include/c10/util/bit_cast.h @@ -0,0 +1 @@ +#include diff --git a/include/c10/util/complex.h b/include/c10/util/complex.h new file mode 100644 index 0000000..f9849a9 --- /dev/null +++ b/include/c10/util/complex.h @@ -0,0 +1,73 @@ +#pragma once + +#include + +#include +#include +#include + +// std functions +// +// The implementation of these functions also follow the design of C++20 + +namespace std { + +template +constexpr T real(const c10::complex& z) { + return z.real(); +} + +template +constexpr T imag(const c10::complex& z) { + return z.imag(); +} + +template +C10_HOST_DEVICE T abs(const c10::complex& z) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return thrust::abs(static_cast>(z)); +#else + return std::abs(static_cast>(z)); +#endif +} + +template +C10_HOST_DEVICE T arg(const c10::complex& z) { + return std::atan2(std::imag(z), std::real(z)); +} + +template +constexpr T norm(const c10::complex& z) { + return z.real() * z.real() + z.imag() * z.imag(); +} + +// For std::conj, there are other versions of it: +// constexpr std::complex conj( float z ); +// template< class DoubleOrInteger > +// constexpr std::complex conj( DoubleOrInteger z ); +// constexpr std::complex conj( long double z ); +// These are not implemented +// TODO(@zasdfgbnm): implement them as c10::conj +template +constexpr c10::complex conj(const c10::complex& z) { + return c10::complex(z.real(), -z.imag()); +} + +// Thrust does not have complex --> complex version of thrust::proj, +// so this function is not implemented at c10 right now. +// TODO(@zasdfgbnm): implement it by ourselves + +// There is no c10 version of std::polar, because std::polar always +// returns std::complex. Use c10::polar instead; + +} // namespace std + +#define C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H +// math functions are included in a separate file +#include // IWYU pragma: keep +#undef C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H + +namespace c10 { +using torch::headeronly::is_complex; +using torch::headeronly::scalar_value_type; +} // namespace c10 diff --git a/include/c10/util/complex_math.h b/include/c10/util/complex_math.h new file mode 100644 index 0000000..2b9bbea --- /dev/null +++ b/include/c10/util/complex_math.h @@ -0,0 +1,441 @@ +#if !defined(C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H) +#error \ + "c10/util/complex_math.h is not meant to be individually included. Include c10/util/complex.h instead." +#endif + +namespace c10_complex_math { + +// Exponential functions + +template +C10_HOST_DEVICE inline c10::complex exp(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::exp(static_cast>(x))); +#else + return static_cast>( + std::exp(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex log(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::log(static_cast>(x))); +#else + return static_cast>( + std::log(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex log10(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::log10(static_cast>(x))); +#else + return static_cast>( + std::log10(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex log2(const c10::complex& x) { + const c10::complex log2 = c10::complex(::log(2.0), 0.0); + return c10_complex_math::log(x) / log2; +} + +// Power functions +// +#if defined(_LIBCPP_VERSION) || \ + (defined(__GLIBCXX__) && !defined(_GLIBCXX11_USE_C99_COMPLEX)) +namespace _detail { +C10_API c10::complex sqrt(const c10::complex& in); +C10_API c10::complex sqrt(const c10::complex& in); +C10_API c10::complex acos(const c10::complex& in); +C10_API c10::complex acos(const c10::complex& in); +} // namespace _detail +#endif + +template +C10_HOST_DEVICE inline c10::complex sqrt(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::sqrt(static_cast>(x))); +#elif !( \ + defined(_LIBCPP_VERSION) || \ + (defined(__GLIBCXX__) && !defined(_GLIBCXX11_USE_C99_COMPLEX))) + return static_cast>( + std::sqrt(static_cast>(x))); +#else + return _detail::sqrt(x); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const c10::complex& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>(thrust::pow( + static_cast>(x), static_cast>(y))); +#else + return static_cast>(std::pow( + static_cast>(x), static_cast>(y))); +#endif +} + +// Regression in ROCm 7.2. See https://github.com/ROCm/rocm-libraries/pull/3836. +// Specialized version for complex on AMD GPUs to use FMA-based +// multiplication +#if defined(__HIPCC__) +namespace detail { +// FMA-aware complex multiplication for float precision on AMD GPUs. +// This prevents SLP vectorizer from breaking FMA formation, which causes +// numerical precision loss in complex arithmetic. +// The issue occurs when vectorizer packs scalar multiplies before backend +// can form FMA instructions, resulting in double rounding instead of single. +C10_HOST_DEVICE inline thrust::complex complex_mul_fma( + thrust::complex a, + thrust::complex b) { + // Complex multiplication: (a.r + a.i*i) * (b.r + b.i*i) + // = (a.r*b.r - a.i*b.i) + (a.r*b.i + a.i*b.r)*i + // Using __builtin_fmaf ensures FMA at source level: + // real: a.r*b.r + (-(a.i*b.i)) = FMA(a.r, b.r, -(a.i*b.i)) + // imag: a.i*b.r + a.r*b.i = FMA(a.r, b.i, a.i*b.r) + float real_part = __builtin_fmaf(a.real(), b.real(), -(a.imag() * b.imag())); + float imag_part = __builtin_fmaf(a.real(), b.imag(), a.imag() * b.real()); + return thrust::complex(real_part, imag_part); +} +} // namespace detail + +template <> +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const c10::complex& y) { + auto log_x = thrust::log(static_cast>(x)); + auto y_log_x = + detail::complex_mul_fma(static_cast>(y), log_x); + return static_cast>(thrust::exp(y_log_x)); +} +#endif + +template +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const T& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::pow(static_cast>(x), y)); +#else + return static_cast>( + std::pow(static_cast>(x), y)); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const T& x, + const c10::complex& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::pow(x, static_cast>(y))); +#else + return static_cast>( + std::pow(x, static_cast>(y))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const c10::complex& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>(thrust::pow( + static_cast>(x), static_cast>(y))); +#else + return static_cast>(std::pow( + static_cast>(x), static_cast>(y))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const U& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::pow(static_cast>(x), y)); +#else + return static_cast>( + std::pow(static_cast>(x), y)); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const T& x, + const c10::complex& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::pow(x, static_cast>(y))); +#else + return static_cast>( + std::pow(x, static_cast>(y))); +#endif +} + +// Trigonometric functions + +template +C10_HOST_DEVICE inline c10::complex sin(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::sin(static_cast>(x))); +#else + return static_cast>( + std::sin(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex cos(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::cos(static_cast>(x))); +#else + return static_cast>( + std::cos(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex tan(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::tan(static_cast>(x))); +#else + return static_cast>( + std::tan(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex asin(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::asin(static_cast>(x))); +#else + return static_cast>( + std::asin(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex acos(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::acos(static_cast>(x))); +#elif !defined(_LIBCPP_VERSION) + return static_cast>( + std::acos(static_cast>(x))); +#else + return _detail::acos(x); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex atan(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::atan(static_cast>(x))); +#else + return static_cast>( + std::atan(static_cast>(x))); +#endif +} + +// Hyperbolic functions + +template +C10_HOST_DEVICE inline c10::complex sinh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::sinh(static_cast>(x))); +#else + return static_cast>( + std::sinh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex cosh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::cosh(static_cast>(x))); +#else + return static_cast>( + std::cosh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex tanh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::tanh(static_cast>(x))); +#else + return static_cast>( + std::tanh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex asinh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::asinh(static_cast>(x))); +#else + return static_cast>( + std::asinh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex acosh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::acosh(static_cast>(x))); +#else + return static_cast>( + std::acosh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex atanh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::atanh(static_cast>(x))); +#else + return static_cast>( + std::atanh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex log1p(const c10::complex& z) { +#if defined(__APPLE__) || defined(__MACOSX) || defined(__CUDACC__) || \ + defined(__HIPCC__) || defined(__SYCL_DEVICE_ONLY__) + // For Mac, the new implementation yielded a high relative error. Falling back + // to the old version for now. + // See https://github.com/numpy/numpy/pull/22611#issuecomment-1667945354 + // For CUDA we also use this one, as thrust::log(thrust::complex) takes + // *forever* to compile + + // log1p(z) = log(1 + z) + // Let's define 1 + z = r * e ^ (i * a), then we have + // log(r * e ^ (i * a)) = log(r) + i * a + // With z = x + iy, the term r can be written as + // r = ((1 + x) ^ 2 + y ^ 2) ^ 0.5 + // = (1 + x ^ 2 + 2 * x + y ^ 2) ^ 0.5 + // So, log(r) is + // log(r) = 0.5 * log(1 + x ^ 2 + 2 * x + y ^ 2) + // = 0.5 * log1p(x * (x + 2) + y ^ 2) + // we need to use the expression only on certain condition to avoid overflow + // and underflow from `(x * (x + 2) + y ^ 2)` + T x = z.real(); + T y = z.imag(); + T zabs = std::abs(z); + T theta = std::atan2(y, x + T(1)); + if (zabs < 0.5) { + T r = x * (T(2) + x) + y * y; + if (r == 0) { // handle underflow + return {x, theta}; + } + return {T(0.5) * std::log1p(r), theta}; + } else { + T z0 = std::hypot(x + 1, y); + return {std::log(z0), theta}; + } +#else + // CPU path + // Based on https://github.com/numpy/numpy/pull/22611#issuecomment-1667945354 + c10::complex u = z + T(1); + if (u == T(1)) { + return z; + } else { + auto log_u = log(u); + if (u - T(1) == z) { + return log_u; + } + return log_u * (z / (u - T(1))); + } +#endif +} + +template +C10_HOST_DEVICE inline c10::complex expm1(const c10::complex& z) { + // expm1(z) = exp(z) - 1 + // Define z = x + i * y + // f = e ^ (x + i * y) - 1 + // = e ^ x * e ^ (i * y) - 1 + // = (e ^ x * cos(y) - 1) + i * (e ^ x * sin(y)) + // = (e ^ x - 1) * cos(y) - (1 - cos(y)) + i * e ^ x * sin(y) + // = expm1(x) * cos(y) - 2 * sin(y / 2) ^ 2 + i * e ^ x * sin(y) + T x = z.real(); + T y = z.imag(); + T a = std::sin(y / 2); + T er = std::expm1(x) * std::cos(y) - T(2) * a * a; + T ei = std::exp(x) * std::sin(y); + return {er, ei}; +} + +} // namespace c10_complex_math + +using c10_complex_math::acos; +using c10_complex_math::acosh; +using c10_complex_math::asin; +using c10_complex_math::asinh; +using c10_complex_math::atan; +using c10_complex_math::atanh; +using c10_complex_math::cos; +using c10_complex_math::cosh; +using c10_complex_math::exp; +using c10_complex_math::expm1; +using c10_complex_math::log; +using c10_complex_math::log10; +using c10_complex_math::log1p; +using c10_complex_math::log2; +using c10_complex_math::pow; +using c10_complex_math::sin; +using c10_complex_math::sinh; +using c10_complex_math::sqrt; +using c10_complex_math::tan; +using c10_complex_math::tanh; + +namespace std { + +using c10_complex_math::acos; +using c10_complex_math::acosh; +using c10_complex_math::asin; +using c10_complex_math::asinh; +using c10_complex_math::atan; +using c10_complex_math::atanh; +using c10_complex_math::cos; +using c10_complex_math::cosh; +using c10_complex_math::exp; +using c10_complex_math::expm1; +using c10_complex_math::log; +using c10_complex_math::log10; +using c10_complex_math::log1p; +using c10_complex_math::log2; +using c10_complex_math::pow; +using c10_complex_math::sin; +using c10_complex_math::sinh; +using c10_complex_math::sqrt; +using c10_complex_math::tan; +using c10_complex_math::tanh; + +} // namespace std diff --git a/include/c10/util/floating_point_utils.h b/include/c10/util/floating_point_utils.h new file mode 100644 index 0000000..10aa67c --- /dev/null +++ b/include/c10/util/floating_point_utils.h @@ -0,0 +1 @@ +#include diff --git a/include/c10/util/irange.h b/include/c10/util/irange.h new file mode 100644 index 0000000..c9dd7e5 --- /dev/null +++ b/include/c10/util/irange.h @@ -0,0 +1,3 @@ +#pragma once + +#include diff --git a/include/c10/util/llvmMathExtras.h b/include/c10/util/llvmMathExtras.h new file mode 100644 index 0000000..8ae5cde --- /dev/null +++ b/include/c10/util/llvmMathExtras.h @@ -0,0 +1,906 @@ +//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains some functions that are useful for math stuff. +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __ANDROID_NDK__ +#include +#endif + +#ifndef __has_builtin +#define __has_builtin(x) 0 +#endif + +#ifndef LLVM_GNUC_PREREQ +#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) +#define LLVM_GNUC_PREREQ(maj, min, patch) \ + ((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) + __GNUC_PATCHLEVEL__ >= \ + ((maj) << 20) + ((min) << 10) + (patch)) +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) +#define LLVM_GNUC_PREREQ(maj, min, patch) \ + ((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) >= ((maj) << 20) + ((min) << 10)) +#else +#define LLVM_GNUC_PREREQ(maj, min, patch) 0 +#endif +#endif + +#ifdef _MSC_VER +// Declare these intrinsics manually rather including intrin.h. It's very +// expensive, and MathExtras.h is popular. +// #include +extern "C" { +unsigned char _BitScanForward(unsigned long* _Index, unsigned long _Mask); +unsigned char _BitScanForward64(unsigned long* _Index, unsigned __int64 _Mask); +unsigned char _BitScanReverse(unsigned long* _Index, unsigned long _Mask); +unsigned char _BitScanReverse64(unsigned long* _Index, unsigned __int64 _Mask); +} +#endif + +namespace c10::llvm { +/// The behavior an operation has on an input of 0. +enum ZeroBehavior { + /// The returned value is undefined. + ZB_Undefined, + /// The returned value is numeric_limits::max() + ZB_Max, + /// The returned value is numeric_limits::digits + ZB_Width +}; + +namespace detail { +template +struct TrailingZerosCounter { + static std::size_t count(T Val, ZeroBehavior /*unused*/) { + if (!Val) + return std::numeric_limits::digits; + if (Val & 0x1) + return 0; + + // Bisection method. + std::size_t ZeroBits = 0; + T Shift = std::numeric_limits::digits >> 1; + T Mask = std::numeric_limits::max() >> Shift; + while (Shift) { + if ((Val & Mask) == 0) { + Val >>= Shift; + ZeroBits |= Shift; + } + Shift >>= 1; + Mask >>= Shift; + } + return ZeroBits; + } +}; + +#if (defined(__GNUC__) && __GNUC__ >= 4) || defined(_MSC_VER) +template +struct TrailingZerosCounter { + static std::size_t count(T Val, ZeroBehavior ZB) { + if (ZB != ZB_Undefined && Val == 0) + return 32; + +#if __has_builtin(__builtin_ctz) || LLVM_GNUC_PREREQ(4, 0, 0) + return __builtin_ctz(Val); +#elif defined(_MSC_VER) + unsigned long Index; + _BitScanForward(&Index, Val); + return Index; +#endif + } +}; + +#if !defined(_MSC_VER) || defined(_M_X64) +template +struct TrailingZerosCounter { + static std::size_t count(T Val, ZeroBehavior ZB) { + if (ZB != ZB_Undefined && Val == 0) + return 64; + +#if __has_builtin(__builtin_ctzll) || LLVM_GNUC_PREREQ(4, 0, 0) + return __builtin_ctzll(Val); +#elif defined(_MSC_VER) + unsigned long Index; + _BitScanForward64(&Index, Val); + return Index; +#endif + } +}; +#endif +#endif +} // namespace detail + +/// Count number of 0's from the least significant bit to the most +/// stopping at the first 1. +/// +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are +/// valid arguments. +template +std::size_t countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return llvm::detail::TrailingZerosCounter::count(Val, ZB); +} + +namespace detail { +template +struct LeadingZerosCounter { + static std::size_t count(T Val, ZeroBehavior /*unused*/) { + if (!Val) + return std::numeric_limits::digits; + + // Bisection method. + std::size_t ZeroBits = 0; + for (T Shift = std::numeric_limits::digits >> 1; Shift; Shift >>= 1) { + T Tmp = Val >> Shift; + if (Tmp) + Val = Tmp; + else + ZeroBits |= Shift; + } + return ZeroBits; + } +}; + +#if (defined(__GNUC__) && __GNUC__ >= 4) || defined(_MSC_VER) +template +struct LeadingZerosCounter { + static std::size_t count(T Val, ZeroBehavior ZB) { + if (ZB != ZB_Undefined && Val == 0) + return 32; + +#if __has_builtin(__builtin_clz) || LLVM_GNUC_PREREQ(4, 0, 0) + return __builtin_clz(Val); +#elif defined(_MSC_VER) + unsigned long Index; + _BitScanReverse(&Index, Val); + return Index ^ 31; +#endif + } +}; + +#if !defined(_MSC_VER) || defined(_M_X64) +template +struct LeadingZerosCounter { + static std::size_t count(T Val, ZeroBehavior ZB) { + if (ZB != ZB_Undefined && Val == 0) + return 64; + +#if __has_builtin(__builtin_clzll) || LLVM_GNUC_PREREQ(4, 0, 0) + return __builtin_clzll(Val); +#elif defined(_MSC_VER) + unsigned long Index; + _BitScanReverse64(&Index, Val); + return Index ^ 63; +#endif + } +}; +#endif +#endif +} // namespace detail + +/// Count number of 0's from the most significant bit to the least +/// stopping at the first 1. +/// +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are +/// valid arguments. +template +std::size_t countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return llvm::detail::LeadingZerosCounter::count(Val, ZB); +} + +/// Get the index of the first set bit starting from the least +/// significant bit. +/// +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are +/// valid arguments. +template +T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) { + if (ZB == ZB_Max && Val == 0) + return std::numeric_limits::max(); + + return countTrailingZeros(Val, ZB_Undefined); +} + +/// Create a bitmask with the N right-most bits set to 1, and all other +/// bits set to 0. Only unsigned types are allowed. +template +T maskTrailingOnes(unsigned N) { + static_assert(std::is_unsigned_v, "Invalid type!"); + const unsigned Bits = CHAR_BIT * sizeof(T); + assert(N <= Bits && "Invalid bit index"); + return N == 0 ? 0 : (T(-1) >> (Bits - N)); +} + +/// Create a bitmask with the N left-most bits set to 1, and all other +/// bits set to 0. Only unsigned types are allowed. +template +T maskLeadingOnes(unsigned N) { + return ~maskTrailingOnes(CHAR_BIT * sizeof(T) - N); +} + +/// Create a bitmask with the N right-most bits set to 0, and all other +/// bits set to 1. Only unsigned types are allowed. +template +T maskTrailingZeros(unsigned N) { + return maskLeadingOnes(CHAR_BIT * sizeof(T) - N); +} + +/// Create a bitmask with the N left-most bits set to 0, and all other +/// bits set to 1. Only unsigned types are allowed. +template +T maskLeadingZeros(unsigned N) { + return maskTrailingOnes(CHAR_BIT * sizeof(T) - N); +} + +/// Get the index of the last set bit starting from the least +/// significant bit. +/// +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are +/// valid arguments. +template +T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) { + if (ZB == ZB_Max && Val == 0) + return std::numeric_limits::max(); + + // Use ^ instead of - because both gcc and llvm can remove the associated ^ + // in the __builtin_clz intrinsic on x86. + return countLeadingZeros(Val, ZB_Undefined) ^ + (std::numeric_limits::digits - 1); +} + +/// Macro compressed bit reversal table for 256 bits. +/// +/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable +/// NOLINTNEXTLINE(*c-arrays*) +static constexpr unsigned char BitReverseTable256[256] = { +#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64 +#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16) +#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4) + R6(0), + R6(2), + R6(1), + R6(3) +#undef R2 +#undef R4 +#undef R6 +}; + +/// Reverse the bits in \p Val. +template +T reverseBits(T Val) { + // NOLINTNEXTLINE(*c-arrays*) + unsigned char in[sizeof(Val)]; + // NOLINTNEXTLINE(*c-arrays*) + unsigned char out[sizeof(Val)]; + std::memcpy(in, &Val, sizeof(Val)); + for (unsigned i = 0; i < sizeof(Val); ++i) + out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]]; + std::memcpy(&Val, out, sizeof(Val)); + return Val; +} + +// NOTE: The following support functions use the _32/_64 extensions instead of +// type overloading so that signed and unsigned integers can be used without +// ambiguity. + +/// Return the high 32 bits of a 64 bit value. +constexpr inline uint32_t Hi_32(uint64_t Value) { + return static_cast(Value >> 32); +} + +/// Return the low 32 bits of a 64 bit value. +constexpr inline uint32_t Lo_32(uint64_t Value) { + return static_cast(Value); +} + +/// Make a 64-bit integer from a high / low pair of 32-bit integers. +constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) { + return ((uint64_t)High << 32) | (uint64_t)Low; +} + +/// Checks if an integer fits into the given bit width. +template +constexpr inline bool isInt(int64_t x) { + return N >= 64 || + (-(INT64_C(1) << (N - 1)) <= x && x < (INT64_C(1) << (N - 1))); +} +// Template specializations to get better code for common cases. +template <> +constexpr inline bool isInt<8>(int64_t x) { + return static_cast(x) == x; +} +template <> +constexpr inline bool isInt<16>(int64_t x) { + return static_cast(x) == x; +} +template <> +constexpr inline bool isInt<32>(int64_t x) { + return static_cast(x) == x; +} + +/// Checks if a signed integer is an N bit number shifted left by S. +template +constexpr inline bool isShiftedInt(int64_t x) { + static_assert( + N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number."); + static_assert(N + S <= 64, "isShiftedInt with N + S > 64 is too wide."); + return isInt(x) && (x % (UINT64_C(1) << S) == 0); +} + +/// Checks if an unsigned integer fits into the given bit width. +/// +/// This is written as two functions rather than as simply +/// +/// return N >= 64 || X < (UINT64_C(1) << N); +/// +/// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting +/// left too many places. +template +constexpr inline std::enable_if_t<(N < 64), bool> isUInt(uint64_t X) { + static_assert(N > 0, "isUInt<0> doesn't make sense"); + return X < (UINT64_C(1) << N); +} +template +constexpr inline std::enable_if_t= 64, bool> isUInt(uint64_t /*X*/) { + return true; +} + +// Template specializations to get better code for common cases. +template <> +constexpr inline bool isUInt<8>(uint64_t x) { + return static_cast(x) == x; +} +template <> +constexpr inline bool isUInt<16>(uint64_t x) { + return static_cast(x) == x; +} +template <> +constexpr inline bool isUInt<32>(uint64_t x) { + return static_cast(x) == x; +} + +/// Checks if a unsigned integer is an N bit number shifted left by S. +template +constexpr inline bool isShiftedUInt(uint64_t x) { + static_assert( + N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)"); + static_assert( + N + S <= 64, "isShiftedUInt with N + S > 64 is too wide."); + // Per the two static_asserts above, S must be strictly less than 64. So + // 1 << S is not undefined behavior. + // NOLINTNEXTLINE(bugprone-chained-comparison) + return isUInt(x) && (x % (UINT64_C(1) << S) == 0); +} + +/// Gets the maximum value for a N-bit unsigned integer. +inline uint64_t maxUIntN(uint64_t N) { + assert(N > 0 && N <= 64 && "integer width out of range"); + + // uint64_t(1) << 64 is undefined behavior, so we can't do + // (uint64_t(1) << N) - 1 + // without checking first that N != 64. But this works and doesn't have a + // branch. + return UINT64_MAX >> (64 - N); +} + +// Ignore the false warning "Arithmetic overflow" for MSVC +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4146) +#endif + +/// Gets the minimum value for a N-bit signed integer. +inline int64_t minIntN(int64_t N) { + assert(N > 0 && N <= 64 && "integer width out of range"); + // NOLINTNEXTLINE(*-narrowing-conversions) + return -(UINT64_C(1) << (N - 1)); +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +/// Gets the maximum value for a N-bit signed integer. +inline int64_t maxIntN(int64_t N) { + assert(N > 0 && N <= 64 && "integer width out of range"); + + // This relies on two's complement wraparound when N == 64, so we convert to + // int64_t only at the very end to avoid UB. + // NOLINTNEXTLINE(*-narrowing-conversions) + return (UINT64_C(1) << (N - 1)) - 1; +} + +/// Checks if an unsigned integer fits into the given (dynamic) bit width. +inline bool isUIntN(unsigned N, uint64_t x) { + return N >= 64 || x <= maxUIntN(N); +} + +/// Checks if an signed integer fits into the given (dynamic) bit width. +inline bool isIntN(unsigned N, int64_t x) { + return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N)); +} + +/// Return true if the argument is a non-empty sequence of ones starting at the +/// least significant bit with the remainder zero (32 bit version). +/// Ex. isMask_32(0x0000FFFFU) == true. +constexpr inline bool isMask_32(uint32_t Value) { + return Value && ((Value + 1) & Value) == 0; +} + +/// Return true if the argument is a non-empty sequence of ones starting at the +/// least significant bit with the remainder zero (64 bit version). +constexpr inline bool isMask_64(uint64_t Value) { + return Value && ((Value + 1) & Value) == 0; +} + +/// Return true if the argument contains a non-empty sequence of ones with the +/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true. +constexpr inline bool isShiftedMask_32(uint32_t Value) { + return Value && isMask_32((Value - 1) | Value); +} + +/// Return true if the argument contains a non-empty sequence of ones with the +/// remainder zero (64 bit version.) +constexpr inline bool isShiftedMask_64(uint64_t Value) { + return Value && isMask_64((Value - 1) | Value); +} + +/// Return true if the argument is a power of two > 0. +/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.) +constexpr inline bool isPowerOf2_32(uint32_t Value) { + return Value && !(Value & (Value - 1)); +} + +/// Return true if the argument is a power of two > 0 (64 bit edition.) +constexpr inline bool isPowerOf2_64(uint64_t Value) { + return Value && !(Value & (Value - 1)); +} + +/// Count the number of ones from the most significant bit to the first +/// zero bit. +/// +/// Ex. countLeadingOnes(0xFF0FFF00) == 8. +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of all ones. Only ZB_Width and +/// ZB_Undefined are valid arguments. +template +std::size_t countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return countLeadingZeros(~Value, ZB); +} + +/// Count the number of ones from the least significant bit to the first +/// zero bit. +/// +/// Ex. countTrailingOnes(0x00FF00FF) == 8. +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of all ones. Only ZB_Width and +/// ZB_Undefined are valid arguments. +template +std::size_t countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return countTrailingZeros(~Value, ZB); +} + +namespace detail { +template +struct PopulationCounter { + static unsigned count(T Value) { + // Generic version, forward to 32 bits. + static_assert(SizeOfT <= 4, "Not implemented!"); +#if defined(__GNUC__) && __GNUC__ >= 4 + return __builtin_popcount(Value); +#else + uint32_t v = Value; + v = v - ((v >> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >> 2) & 0x33333333); + return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; +#endif + } +}; + +template +struct PopulationCounter { + static unsigned count(T Value) { +#if defined(__GNUC__) && __GNUC__ >= 4 + return __builtin_popcountll(Value); +#else + uint64_t v = Value; + v = v - ((v >> 1) & 0x5555555555555555ULL); + v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL); + v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL; + return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56); +#endif + } +}; +} // namespace detail + +/// Count the number of set bits in a value. +/// Ex. countPopulation(0xF000F000) = 8 +/// Returns 0 if the word is zero. +template +inline unsigned countPopulation(T Value) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return detail::PopulationCounter::count(Value); +} + +/// Return the log base 2 of the specified value. +inline double Log2(double Value) { +#if defined(__ANDROID_API__) && __ANDROID_API__ < 18 + return __builtin_log(Value) / __builtin_log(2.0); +#else + return log2(Value); +#endif +} + +/// Return the floor log base 2 of the specified value, -1 if the value is zero. +/// (32 bit edition.) +/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2 +inline unsigned Log2_32(uint32_t Value) { + return static_cast(31 - countLeadingZeros(Value)); +} + +/// Return the floor log base 2 of the specified value, -1 if the value is zero. +/// (64 bit edition.) +inline unsigned Log2_64(uint64_t Value) { + return static_cast(63 - countLeadingZeros(Value)); +} + +/// Return the ceil log base 2 of the specified value, 32 if the value is zero. +/// (32 bit edition). +/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3 +inline unsigned Log2_32_Ceil(uint32_t Value) { + return static_cast(32 - countLeadingZeros(Value - 1)); +} + +/// Return the ceil log base 2 of the specified value, 64 if the value is zero. +/// (64 bit edition.) +inline unsigned Log2_64_Ceil(uint64_t Value) { + return static_cast(64 - countLeadingZeros(Value - 1)); +} + +/// Return the greatest common divisor of the values using Euclid's algorithm. +inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) { + while (B) { + uint64_t T = B; + B = A % B; + A = T; + } + return A; +} + +/// This function takes a 64-bit integer and returns the bit equivalent double. +inline double BitsToDouble(uint64_t Bits) { + double D = 0; + static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes"); + memcpy(&D, &Bits, sizeof(Bits)); + return D; +} + +/// This function takes a 32-bit integer and returns the bit equivalent float. +inline float BitsToFloat(uint32_t Bits) { + // TODO: Use std::bit_cast once C++20 becomes available. + return c10::bit_cast(Bits); +} + +/// This function takes a double and returns the bit equivalent 64-bit integer. +/// Note that copying doubles around changes the bits of NaNs on some hosts, +/// notably x86, so this routine cannot be used if these bits are needed. +inline uint64_t DoubleToBits(double Double) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + uint64_t Bits; + static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes"); + memcpy(&Bits, &Double, sizeof(Double)); + return Bits; +} + +/// This function takes a float and returns the bit equivalent 32-bit integer. +/// Note that copying floats around changes the bits of NaNs on some hosts, +/// notably x86, so this routine cannot be used if these bits are needed. +inline uint32_t FloatToBits(float Float) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + uint32_t Bits; + static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes"); + memcpy(&Bits, &Float, sizeof(Float)); + return Bits; +} + +/// A and B are either alignments or offsets. Return the minimum alignment that +/// may be assumed after adding the two together. +constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) { + // The largest power of 2 that divides both A and B. + // + // Replace "-Value" by "1+~Value" in the following commented code to avoid + // MSVC warning C4146 + // return (A | B) & -(A | B); + return (A | B) & (1 + ~(A | B)); +} + +/// Aligns \c Addr to \c Alignment bytes, rounding up. +/// +/// Alignment should be a power of two. This method rounds up, so +/// alignAddr(7, 4) == 8 and alignAddr(8, 4) == 8. +inline uintptr_t alignAddr(const void* Addr, size_t Alignment) { + assert( + Alignment && isPowerOf2_64((uint64_t)Alignment) && + "Alignment is not a power of two!"); + + assert((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr); + + return (((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1)); +} + +/// Returns the necessary adjustment for aligning \c Ptr to \c Alignment +/// bytes, rounding up. +inline size_t alignmentAdjustment(const void* Ptr, size_t Alignment) { + return alignAddr(Ptr, Alignment) - (uintptr_t)Ptr; +} + +/// Returns the next power of two (in 64-bits) that is strictly greater than A. +/// Returns zero on overflow. +inline uint64_t NextPowerOf2(uint64_t A) { + A |= (A >> 1); + A |= (A >> 2); + A |= (A >> 4); + A |= (A >> 8); + A |= (A >> 16); + A |= (A >> 32); + return A + 1; +} + +/// Returns the power of two which is less than or equal to the given value. +/// Essentially, it is a floor operation across the domain of powers of two. +inline uint64_t PowerOf2Floor(uint64_t A) { + if (!A) + return 0; + return 1ull << (63 - countLeadingZeros(A, ZB_Undefined)); +} + +/// Returns the power of two which is greater than or equal to the given value. +/// Essentially, it is a ceil operation across the domain of powers of two. +inline uint64_t PowerOf2Ceil(uint64_t A) { + if (!A) + return 0; + return NextPowerOf2(A - 1); +} + +/// Returns the next integer (mod 2**64) that is greater than or equal to +/// \p Value and is a multiple of \p Align. \p Align must be non-zero. +/// +/// If non-zero \p Skew is specified, the return value will be a minimal +/// integer that is greater than or equal to \p Value and equal to +/// \p Align * N + \p Skew for some integer N. If \p Skew is larger than +/// \p Align, its value is adjusted to '\p Skew mod \p Align'. +/// +/// Examples: +/// \code +/// alignTo(5, 8) = 8 +/// alignTo(17, 8) = 24 +/// alignTo(~0LL, 8) = 0 +/// alignTo(321, 255) = 510 +/// +/// alignTo(5, 8, 7) = 7 +/// alignTo(17, 8, 1) = 17 +/// alignTo(~0LL, 8, 3) = 3 +/// alignTo(321, 255, 42) = 552 +/// \endcode +inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) { + assert(Align != 0u && "Align can't be 0."); + Skew %= Align; + return (Value + Align - 1 - Skew) / Align * Align + Skew; +} + +/// Returns the next integer (mod 2**64) that is greater than or equal to +/// \p Value and is a multiple of \c Align. \c Align must be non-zero. +template +constexpr inline uint64_t alignTo(uint64_t Value) { + static_assert(Align != 0u, "Align must be non-zero"); + return (Value + Align - 1) / Align * Align; +} + +/// Returns the integer ceil(Numerator / Denominator). +inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) { + return alignTo(Numerator, Denominator) / Denominator; +} + +/// \c alignTo for contexts where a constant expression is required. +/// \sa alignTo +/// +/// \todo FIXME: remove when \c constexpr becomes really \c constexpr +template +struct AlignTo { + static_assert(Align != 0u, "Align must be non-zero"); + template + struct from_value { + static const uint64_t value = (Value + Align - 1) / Align * Align; + }; +}; + +/// Returns the largest uint64_t less than or equal to \p Value and is +/// \p Skew mod \p Align. \p Align must be non-zero +inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) { + assert(Align != 0u && "Align can't be 0."); + Skew %= Align; + return (Value - Skew) / Align * Align + Skew; +} + +/// Returns the offset to the next integer (mod 2**64) that is greater than +/// or equal to \p Value and is a multiple of \p Align. \p Align must be +/// non-zero. +inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) { + return alignTo(Value, Align) - Value; +} + +/// Sign-extend the number in the bottom B bits of X to a 32-bit integer. +/// Requires 0 < B <= 32. +template +constexpr inline int32_t SignExtend32(uint32_t X) { + static_assert(B > 0, "Bit width can't be 0."); + static_assert(B <= 32, "Bit width out of range."); + return int32_t(X << (32 - B)) >> (32 - B); +} + +/// Sign-extend the number in the bottom B bits of X to a 32-bit integer. +/// Requires 0 < B < 32. +inline int32_t SignExtend32(uint32_t X, unsigned B) { + assert(B > 0 && "Bit width can't be 0."); + assert(B <= 32 && "Bit width out of range."); + return int32_t(X << (32 - B)) >> (32 - B); +} + +/// Sign-extend the number in the bottom B bits of X to a 64-bit integer. +/// Requires 0 < B < 64. +template +constexpr inline int64_t SignExtend64(uint64_t x) { + static_assert(B > 0, "Bit width can't be 0."); + static_assert(B <= 64, "Bit width out of range."); + return int64_t(x << (64 - B)) >> (64 - B); +} + +/// Sign-extend the number in the bottom B bits of X to a 64-bit integer. +/// Requires 0 < B < 64. +inline int64_t SignExtend64(uint64_t X, unsigned B) { + assert(B > 0 && "Bit width can't be 0."); + assert(B <= 64 && "Bit width out of range."); + return int64_t(X << (64 - B)) >> (64 - B); +} + +/// Subtract two unsigned integers, X and Y, of type T and return the absolute +/// value of the result. +template +std::enable_if_t, T> AbsoluteDifference(T X, T Y) { + return std::max(X, Y) - std::min(X, Y); +} + +/// Add two unsigned integers, X and Y, of type T. Clamp the result to the +/// maximum representable value of T on overflow. ResultOverflowed indicates if +/// the result is larger than the maximum representable value of type T. +template +std::enable_if_t, T> SaturatingAdd( + T X, + T Y, + bool* ResultOverflowed = nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + bool Dummy; + bool& Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy; + // Hacker's Delight, p. 29 + T Z = X + Y; + Overflowed = (Z < X || Z < Y); + if (Overflowed) + return std::numeric_limits::max(); + else + return Z; +} + +/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the +/// maximum representable value of T on overflow. ResultOverflowed indicates if +/// the result is larger than the maximum representable value of type T. +template +std::enable_if_t, T> SaturatingMultiply( + T X, + T Y, + bool* ResultOverflowed = nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + bool Dummy; + bool& Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy; + + // Hacker's Delight, p. 30 has a different algorithm, but we don't use that + // because it fails for uint16_t (where multiplication can have undefined + // behavior due to promotion to int), and requires a division in addition + // to the multiplication. + + Overflowed = false; + + // Log2(Z) would be either Log2Z or Log2Z + 1. + // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z + // will necessarily be less than Log2Max as desired. + int Log2Z = Log2_64(X) + Log2_64(Y); + const T Max = std::numeric_limits::max(); + int Log2Max = Log2_64(Max); + if (Log2Z < Log2Max) { + return X * Y; + } + if (Log2Z > Log2Max) { + Overflowed = true; + return Max; + } + + // We're going to use the top bit, and maybe overflow one + // bit past it. Multiply all but the bottom bit then add + // that on at the end. + T Z = (X >> 1) * Y; + if (Z & ~(Max >> 1)) { + Overflowed = true; + return Max; + } + Z <<= 1; + if (X & 1) + return SaturatingAdd(Z, Y, ResultOverflowed); + + return Z; +} + +/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to +/// the product. Clamp the result to the maximum representable value of T on +/// overflow. ResultOverflowed indicates if the result is larger than the +/// maximum representable value of type T. +template +std::enable_if_t, T> SaturatingMultiplyAdd( + T X, + T Y, + T A, + bool* ResultOverflowed = nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + bool Dummy; + bool& Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy; + + T Product = SaturatingMultiply(X, Y, &Overflowed); + if (Overflowed) + return Product; + + return SaturatingAdd(A, Product, &Overflowed); +} + +/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC. +extern const float huge_valf; +} // namespace c10::llvm diff --git a/include/c10/util/overflows.h b/include/c10/util/overflows.h new file mode 100644 index 0000000..1494e2c --- /dev/null +++ b/include/c10/util/overflows.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include diff --git a/include/c10/util/safe_numerics.h b/include/c10/util/safe_numerics.h new file mode 100644 index 0000000..f695fa2 --- /dev/null +++ b/include/c10/util/safe_numerics.h @@ -0,0 +1,112 @@ +#pragma once +#include + +#include +#include +#include + +// GCC has __builtin_mul_overflow from before it supported __has_builtin +#ifdef _MSC_VER +#define C10_HAS_BUILTIN_OVERFLOW() (0) +#include +#include +#else +#define C10_HAS_BUILTIN_OVERFLOW() (1) +#endif + +namespace c10 { + +template , int> = 0> +C10_ALWAYS_INLINE bool add_overflows(T a, T b, T* out) { +#if C10_HAS_BUILTIN_OVERFLOW() + return __builtin_add_overflow(a, b, out); +#else + if constexpr (std::is_signed_v) { + // For signed types, detect overflow by checking sign changes + volatile T tmp = a + b; + *out = tmp; + + // If both operands have the same sign, check if result changed sign + // unexpectedly. + if ((a > 0) == (b > 0)) { + if ((a > 0) && (tmp <= 0)) { + return true; // Positive overflow + } + if ((a < 0) && (tmp >= 0)) { + return true; // Negative overflow + } + } + return false; + } else { + // For unsigned types, overflow causes wrap-around + volatile T tmp = a + b; + *out = tmp; + return (tmp < a || tmp < b); + } +#endif +} + +C10_ALWAYS_INLINE bool add_overflows(uint64_t a, uint64_t b, uint64_t* out) { + return add_overflows(a, b, out); +} + +template , int> = 0> +C10_ALWAYS_INLINE bool mul_overflows(T a, T b, T* out) { +#if C10_HAS_BUILTIN_OVERFLOW() + return __builtin_mul_overflow(a, b, out); +#else + if constexpr (std::is_signed_v) { + // For signed types, use the division-based check + volatile T tmp = a * b; + *out = tmp; + if (a == 0 || b == 0) { + return false; + } + return !(a == tmp / b); + } else { + // For unsigned types, use leading zeros approach + // This test isn't exact, but avoids doing integer division + *out = a * b; + constexpr int bits = sizeof(T) * 8; + return (std::countl_zero(a) + std::countl_zero(b)) < bits; + } +#endif +} + +C10_ALWAYS_INLINE bool mul_overflows(uint64_t a, uint64_t b, uint64_t* out) { + return mul_overflows(a, b, out); +} + +template +bool safe_multiplies_u64(It first, It last, uint64_t* out) { +#if C10_HAS_BUILTIN_OVERFLOW() + uint64_t prod = 1; + bool overflow = false; + for (; first != last; ++first) { + overflow |= c10::mul_overflows(prod, *first, &prod); + } + *out = prod; + return overflow; +#else + uint64_t prod = 1; + uint64_t prod_log2 = 0; + bool is_zero = false; + for (; first != last; ++first) { + auto x = static_cast(*first); + prod *= x; + // log2(0) isn't valid, so need to track it specially + is_zero |= (x == 0); + prod_log2 += std::bit_width(x - 1); + } + *out = prod; + // This test isn't exact, but avoids doing integer division + return !is_zero && (prod_log2 >= 64); +#endif +} + +template +bool safe_multiplies_u64(const Container& c, uint64_t* out) { + return safe_multiplies_u64(c.begin(), c.end(), out); +} + +} // namespace c10 diff --git a/include/executorch/extension/data_loader/buffer_data_loader.h b/include/executorch/extension/data_loader/buffer_data_loader.h new file mode 100644 index 0000000..7f42115 --- /dev/null +++ b/include/executorch/extension/data_loader/buffer_data_loader.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace executorch { +namespace extension { + +/** + * A DataLoader that wraps a pre-allocated buffer. The FreeableBuffers + * that it returns do not actually free any data. + * + * This can be used to wrap data that is directly embedded into the firmware + * image, or to wrap data that was allocated elsewhere. + */ +class BufferDataLoader final : public executorch::runtime::DataLoader { + public: + BufferDataLoader(const void* data, size_t size) + : data_(reinterpret_cast(data)), size_(size) {} + + ET_NODISCARD + executorch::runtime::Result load( + size_t offset, + size_t size, + ET_UNUSED const DataLoader::SegmentInfo& segment_info) const override { + size_t total_size; + bool overflow = c10::add_overflows(offset, size, &total_size); + ET_CHECK_OR_RETURN_ERROR( + !overflow && total_size <= size_, + InvalidArgument, + "offset %zu + size %zu > size_ %zu, or overflow detected", + offset, + size, + size_); + return executorch::runtime::FreeableBuffer( + data_ + offset, size, /*free_fn=*/nullptr); + } + + ET_NODISCARD executorch::runtime::Result size() const override { + return size_; + } + + ET_NODISCARD executorch::runtime::Error load_into( + size_t offset, + size_t size, + ET_UNUSED const SegmentInfo& segment_info, + void* buffer) const override { + ET_CHECK_OR_RETURN_ERROR( + buffer != nullptr, + InvalidArgument, + "Destination buffer cannot be null"); + + auto result = load(offset, size, segment_info); + if (!result.ok()) { + return result.error(); + } + std::memcpy(buffer, result->data(), size); + return executorch::runtime::Error::Ok; + } + + private: + const uint8_t* const data_; // uint8 is easier to index into. + const size_t size_; +}; + +} // namespace extension +} // namespace executorch + +namespace torch { +namespace executor { +namespace util { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::extension::BufferDataLoader; +} // namespace util +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/backend/backend_execution_context.h b/include/executorch/runtime/backend/backend_execution_context.h new file mode 100644 index 0000000..e40d601 --- /dev/null +++ b/include/executorch/runtime/backend/backend_execution_context.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { + +/** + * BackendExecutionContext will be used to inject run time context. + */ +class BackendExecutionContext final { + public: + BackendExecutionContext( + EventTracer* event_tracer = nullptr, + MemoryAllocator* temp_allocator = nullptr, + const char* method_name = nullptr, + Span> scratch_buffers = {}) + : event_tracer_(event_tracer), + temp_allocator_(temp_allocator), + method_name_(method_name), + scratch_buffers_(scratch_buffers) {} + + /** + * Returns a pointer to an instance of EventTracer to do profiling/debugging + * logging inside the delegate backend. Users will need access to this pointer + * to use any of the event tracer APIs. + */ + EventTracer* event_tracer() { + return event_tracer_; + } + + /** + * Returns a pointer to the address allocated by temp allocator. This + * allocator will be reset after every delegate call during execution. + */ + void* allocate( + size_t size, + size_t alignment = MemoryAllocator::kDefaultAlignment) { + // TODO(chenlai): depends on the need, we may expose more functionality for + // memory allocation. + return temp_allocator_->allocate(size, alignment); + } + + /** + * Returns the temp allocator. This allocator will be reset every instruction. + */ + MemoryAllocator* get_temp_allocator() { + return temp_allocator_; + } + + /** + * Get the name of the executing method from the ExecuTorch runtime. + */ + const char* get_method_name() const { + return method_name_; + } + + /** + * The memory-planned scratch buffers this delegate declared when it was + * lowered, in declaration order. Check size() before indexing: a program + * that declares none, or one exported before this field existed, yields an + * empty span and the backend must fall back to the temp allocator. + * + * A buffer's address is fixed for the Method's lifetime, provided the + * planned buffers the integrator supplied outlive it. Its contents are not: + * they are uninitialized on entry and dead on return, because the memory + * plan may hand the same bytes to unrelated tensors between calls. Within + * one call the planner will not overlap a buffer with this delegate's own + * inputs and outputs, with anything live across the call, or with its + * siblings. + * + * Alignment is whatever the arena provides: the planner aligns each buffer's + * offset within its pool, to 16 bytes by default, but the pool's base + * address comes from the integrator and the runtime does not adjust it. A + * backend needing more must declare the slack and align the pointer itself. + */ + Span> scratch_buffers() const { + return scratch_buffers_; + } + + private: + EventTracer* event_tracer_ = nullptr; + MemoryAllocator* temp_allocator_ = nullptr; + const char* method_name_ = nullptr; + Span> scratch_buffers_; +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::BackendExecutionContext; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/backend/backend_init_context.h b/include/executorch/runtime/backend/backend_init_context.h new file mode 100644 index 0000000..0f649b3 --- /dev/null +++ b/include/executorch/runtime/backend/backend_init_context.h @@ -0,0 +1,149 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include + +#include + +#ifdef __GNUC__ +// Disable -Wdeprecated-declarations, as some builds use 'Werror'. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +/** + * BackendInitContext will be used to inject runtime info for to initialize + * delegate. + */ +class BackendInitContext final { + public: + explicit BackendInitContext( + MemoryAllocator* runtime_allocator, + EventTracer* event_tracer = nullptr, + const char* method_name = nullptr, + const NamedDataMap* named_data_map = nullptr, + Span runtime_specs = {}) + : runtime_allocator_(runtime_allocator), +#ifdef ET_EVENT_TRACER_ENABLED + event_tracer_(event_tracer), +#else + event_tracer_(nullptr), +#endif + method_name_(method_name), + named_data_map_(named_data_map), + runtime_specs_(runtime_specs) { + } + + /** Get the runtime allocator passed from Method. It's the same runtime + * executor used by the standard executor runtime and the life span is the + * same as the model. + */ + MemoryAllocator* get_runtime_allocator() { + return runtime_allocator_; + } + + /** + * Returns a pointer (null if not installed) to an instance of EventTracer to + * do profiling/debugging logging inside the delegate backend. Users will need + * access to this pointer to use any of the event tracer APIs. + */ + EventTracer* event_tracer() { + return event_tracer_; + } + + /** Get the loaded method name from ExecuTorch runtime. Usually it's + * "forward", however, if there are multiple methods in the .pte file, it can + * be different. One example is that we may have prefill and decode methods in + * the same .pte file. In this case, when client loads "prefill" method, the + * `get_method_name` function will return "prefill", when client loads + * "decode" method, the `get_method_name` function will return "decode". + */ + const char* get_method_name() const { + return method_name_; + } + + /** Get the named data map from ExecuTorch runtime. + * This provides a way for backends to retrieve data blobs by key. + */ + const NamedDataMap* get_named_data_map() const { + return named_data_map_; + } + + /** + * Get the runtime specs (load-time options) for this backend. + * These are per-delegate options passed at Module::load() time. + * + * @return Span of BackendOption containing the runtime specs, or empty span + * if no runtime specs were provided. + */ + Span runtime_specs() const { + return runtime_specs_; + } + + /** + * Get a runtime spec value by key and type. + * + * @tparam T The expected type (bool, int, or const char*) + * @param key The option key to look up. + * @return Result containing the value if found and type matches, + * Error::NotFound if key doesn't exist, + * Error::InvalidArgument if key exists but type doesn't match. + */ + template + Result get_runtime_spec(const char* key) const { + static_assert( + std::is_same_v || std::is_same_v || + std::is_same_v, + "get_runtime_spec only supports bool, int, and const char*"); + + for (size_t i = 0; i < runtime_specs_.size(); ++i) { + const auto& opt = runtime_specs_[i]; + if (std::strcmp(opt.key, key) == 0) { + if constexpr (std::is_same_v) { + if (auto* arr = std::get_if>( + &opt.value)) { + return arr->data(); + } + } else { + if (auto* val = std::get_if(&opt.value)) { + return *val; + } + } + return Error::InvalidArgument; + } + } + return Error::NotFound; + } + + private: + MemoryAllocator* runtime_allocator_ = nullptr; + EventTracer* event_tracer_ = nullptr; + const char* method_name_ = nullptr; + const NamedDataMap* named_data_map_ = nullptr; + Span runtime_specs_; +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::BackendInitContext; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/backend/backend_option_context.h b/include/executorch/runtime/backend/backend_option_context.h new file mode 100644 index 0000000..b3266e6 --- /dev/null +++ b/include/executorch/runtime/backend/backend_option_context.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once +#include +#include +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +/** + * BackendOptionContext will be used to inject runtime info for to initialize + * delegate. + */ +class BackendOptionContext final { + public: + explicit BackendOptionContext() {} +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::BackendOptionContext; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/backend/backend_options_map.h b/include/executorch/runtime/backend/backend_options_map.h new file mode 100644 index 0000000..f0c6a68 --- /dev/null +++ b/include/executorch/runtime/backend/backend_options_map.h @@ -0,0 +1,229 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include + +#include + +namespace executorch { +namespace runtime { + +/** + * Maps backend IDs to their load-time options. + * + * This class is used to provide per-delegate configuration at Module::load() + * time. Users can set options for multiple backends, and the runtime will + * route the appropriate options to each backend during initialization. + * + * Example usage: + * @code + * BackendOptions<4> coreml_opts; + * coreml_opts.set_option("compute_unit", "cpu_and_gpu"); + * + * LoadBackendOptionsMap map; + * map.set_options("CoreMLBackend", coreml_opts.view()); + * + * // Later, during backend init: + * auto opts = map.get_options("CoreMLBackend"); + * @endcode + * + * Note: This class does NOT take ownership of the option spans. The caller + * must ensure that the BackendOptions objects outlive the LoadBackendOptionsMap + * and any loaded models that use it. + */ +class LoadBackendOptionsMap final { + public: + /** + * Default constructor - creates an empty map. + */ + LoadBackendOptionsMap() : size_(0) { + for (size_t i = 0; i < kMaxBackends; ++i) { + entries_[i].backend_id[0] = '\0'; + } + } + + /** + * Sets options for a specific backend. + * + * If options for the given backend_id already exist, they will be replaced. + * + * @param backend_id The backend identifier (e.g., "CoreMLBackend", + * "XNNPACKBackend"). Must not be null or empty. + * @param options Span of BackendOption to associate with this backend. + * The span's underlying data must outlive this map and any + * models loaded with it. + * @return Error::Ok on success. + * Error::InvalidArgument if backend_id is null/empty or max backends + * exceeded. + */ + Error set_options(const char* backend_id, Span options) { + if (backend_id == nullptr || backend_id[0] == '\0') { + return Error::InvalidArgument; + } + + return set_options_impl(backend_id, options); + } + + /** + * Sets options from a backend options builder. + * + * This convenience overload accepts any builder type that provides + * backend_id() and view() methods, allowing simpler usage: + * + * @code + * ExampleBackendOptions opts; + * opts.setNumThreads(4).setEnableOptimization(true); + * map.set_options(opts); + * @endcode + * + * @param builder A backend options builder with backend_id() and view() + * methods. + * @return Error::Ok on success, Error::InvalidArgument on failure. + */ + template + Error set_options(Builder& builder) { + return set_options_impl(builder.backend_id(), builder.view()); + } + + private: + Error set_options_impl(const char* backend_id, Span options) { + // Check if backend already exists and update it + for (size_t i = 0; i < size_; ++i) { + if (std::strcmp(entries_[i].backend_id, backend_id) == 0) { + entries_[i].options = options; + return Error::Ok; + } + } + + // Add new entry if space available + if (size_ >= kMaxBackends) { + return Error::InvalidArgument; + } + + const size_t id_len = std::strlen(backend_id); + if (id_len >= kMaxBackendIdLength) { + return Error::InvalidArgument; + } + std::memcpy(entries_[size_].backend_id, backend_id, id_len); + entries_[size_].backend_id[id_len] = '\0'; + entries_[size_].options = options; + ++size_; + + return Error::Ok; + } + + public: + /** + * Gets options for a specific backend. + * + * @param backend_id The backend identifier to look up. + * @return Span of options for this backend, or an empty span if the backend + * has no options configured or backend_id is null. + */ + Span get_options(const char* backend_id) const { + if (backend_id == nullptr) { + return Span(nullptr, static_cast(0)); + } + + for (size_t i = 0; i < size_; ++i) { + if (std::strcmp(entries_[i].backend_id, backend_id) == 0) { + return Span( + entries_[i].options.data(), entries_[i].options.size()); + } + } + + return Span(nullptr, static_cast(0)); + } + + /** + * Checks if options have been configured for a specific backend. + * + * @param backend_id The backend identifier to check. + * @return true if options are set for this backend, false otherwise. + */ + bool has_options(const char* backend_id) const { + if (backend_id == nullptr) { + return false; + } + + for (size_t i = 0; i < size_; ++i) { + if (std::strcmp(entries_[i].backend_id, backend_id) == 0) { + return true; + } + } + + return false; + } + + /** + * Returns the number of backends with configured options. + */ + size_t size() const { + return size_; + } + + /** + * Non-owning view of a single (backend_id, options) entry, returned by + * entry_at(). The pointer / span are valid until the map is mutated or + * destroyed. + */ + struct EntryView { + const char* backend_id = nullptr; + Span options; + }; + + /** + * Returns the (backend_id, options) entry at the given index for + * enumeration over the map's contents. + * + * @param index The entry index. Must be < size(); behavior is undefined + * otherwise. Use this together with size() to walk every entry. + * @return EntryView referencing the entry's backend_id and options. The + * view is valid until the next mutation of, or destruction of, this + * map. + * + * Example: + * @code + * for (size_t i = 0; i < map.size(); ++i) { + * const auto entry = map.entry_at(i); + * // use entry.backend_id and entry.options ... + * } + * @endcode + */ + EntryView entry_at(size_t index) const { + ET_DCHECK_MSG( + index < size_, + "entry_at index %zu out of bounds (size=%zu)", + index, + size_); + return EntryView{ + entries_[index].backend_id, + Span( + entries_[index].options.data(), entries_[index].options.size())}; + } + + private: + static constexpr size_t kMaxBackends = 8; + static constexpr size_t kMaxBackendIdLength = 64; + + struct Entry { + char backend_id[kMaxBackendIdLength]; + Span options; + }; + + Entry entries_[kMaxBackends]; + size_t size_; +}; + +} // namespace runtime +} // namespace executorch diff --git a/include/executorch/runtime/backend/interface.h b/include/executorch/runtime/backend/interface.h new file mode 100644 index 0000000..d0e54c3 --- /dev/null +++ b/include/executorch/runtime/backend/interface.h @@ -0,0 +1,238 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { + +struct SizedBuffer { + void* buffer; + size_t nbytes; // number of bytes of buffer +}; + +struct CompileSpec { + const char* key; // spec key + SizedBuffer value; // spec value +}; + +/** + * An opaque handle managed by a backend. Typically points to a backend-private + * class/struct. + */ +using DelegateHandle = void; + +class BackendInterface { + public: + virtual ~BackendInterface() = 0; + + /** + * Returns true if the backend is available to process delegation calls. + */ + ET_NODISCARD virtual bool is_available() const = 0; + + /** + * Responsible to further process (compile/transform/optimize) the compiled + * unit that was produced, ahead-of-time, as well as perform any backend + * initialization to ready it for execution. This method is called every time + * the ExecuTorch program is initialized. Consequently, this is the place to + * perform any backend initialization as well as transformations, + * optimizations, and even compilation that depend on the target device. As + * such, it is strongly encouraged to push as much processing as possible to + * the ahead-of-time processing. + * + * @param[in] processed An opaque (to ExecuTorch) backend-specific compiled + * unit from the preprocessor. Can contain anything the backend needs to + * execute the equivalent semantics of the passed-in Module and its + * method. Often passed unmodified to `execute()` as a `DelegateHandle`, + * unless it needs further processing at init time to be fully executable. + * If the data is not needed after init(), calling processed->Free() can + * reclaim its memory. + * @param[in] compile_specs The exact same compiler specification that + * was used ahead-of-time to produce `processed`. + * + * @returns On success, an opaque handle representing the the method + * implemented by the delegate. This handle is passed to `execute()` and + * `destroy()`, and the memory it points to is owned by the backend. + * Typically points to a backend-private class/struct. + * @returns On error, returns an error code other than Error::Ok. If the + * compiled unit (the preprocessed result from ahead of time) is not + * compatible with the current backend runtime, return the error code + * Error::DelegateInvalidCompatibility. Other backend delegate + * specific error codes can be found in error.h. + */ + ET_NODISCARD virtual Result init( + BackendInitContext& context, + FreeableBuffer* processed, + ArrayRef compile_specs) const = 0; + + /** + * Responsible for executing the given method’s handle, as it was produced + * by compile. + * + * @param[in] handle An opaque handle returned by `init()`. Usually a backend + * executable unit. This executable unit should be ready to execute the + * delegate blobs. One handle can serve several calls in a method, each + * with its own `args`. The emitter does this when the backend set + * `PreprocessResult.share_handle_across_calls` and declared no scratch, + * and programs from ExecuTorch 0.7 and earlier can do it for any + * backend. Such programs rely on `execute()` reading `args` again on + * every call, keeping nothing on the handle that is tied to one call or + * that changes later results, and writing outputs only into the output + * tensors in `args`. Setting the flag promises this for every runtime + * version of the backend that may load the program. + * @param[in] args The method’s inputs and outputs. + * @retval Error::Ok if successful. + */ + ET_NODISCARD virtual Error execute( + BackendExecutionContext& context, + DelegateHandle* handle, + Span args) const = 0; + + /** + * Responsible update the backend status, if any. The backend options are + * passed in by users, and the backend can update its internal status based on + * the options. + * + * @param[in] context Runtime context if any. Currently it's not used. + * @param[in] args A list of BackendOptions passed in by users. + * @retval Error::Ok if successful. + */ + ET_NODISCARD virtual Error set_option( + __ET_UNUSED BackendOptionContext& context, + const executorch::runtime::Span& backend_options) { + return Error::Ok; + }; + + /** + * Responsible update the backend status, if any. The backend options are + * passed in by users, and the backend can update its internal status based on + * the options. + * + * @param[in] context Runtime context if any. Currently it's not used. + * @param[in] args A list of BackendOptions passed in by users, that will be + * filled by the backend + * @retval Error::Ok if successful. + */ + ET_NODISCARD virtual Error get_option( + __ET_UNUSED BackendOptionContext& context, + executorch::runtime::Span& backend_options) { + return Error::Ok; + }; + + /** + * Responsible for destroying a handle, if it's required for some backend. + * It may be needed for some backends. For example, resources associated with + * this handle needs to be released. This method is called when the execution + * plan is destroyed (i.e., the program is out of its lifespan). + * + * @param[in] handle The handle to be destroyed. An opaque handle returned by + * `init()`. + */ + virtual void destroy(ET_UNUSED DelegateHandle* handle) const {} +}; + +/** + * Returns the corresponding object pointer for a given string name. + * The mapping is populated using register_backend method. + * + * @param[in] name Name of the user-defined backend delegate. + * @retval Pointer to the appropriate object that implements BackendInterface. + * Nullptr if it can't find anything with the given name. + */ +BackendInterface* get_backend_class(const char* name); + +/** + * A named instance of a backend. + */ +struct Backend { + /// The name of the backend. Must match the string used in the PTE file. + const char* name; + /// The instance of the backend to use when loading and executing programs. + BackendInterface* backend; +}; + +/** + * Registers the Backend object (i.e. string name and BackendInterface pair) so + * that it could be called via the name during the runtime. + * + * @param[in] backend Backend object + * @retval Error code representing whether registration was successful. + */ +ET_NODISCARD Error register_backend(const Backend& backend); + +/** + * Returns the number of registered backends. + */ +size_t get_num_registered_backends(); + +/** + * Returns the backend name at the given index. + */ +Result get_backend_name(size_t index); + +/** + * Sets backend options for a specific backend. + * + * @param backend_name The name of the backend to set options for + * @param backend_options The backend option list containing the options + * to set + * @return Error::Ok on success, Error::NotFound if backend is not found, or + * other error codes on failure + */ +Error set_option( + const char* backend_name, + const executorch::runtime::Span + backend_options); + +/** + * Retrieves backend options for a specific backend. + * + * @param backend_name The name of the backend to get options from + * @param backend_options The backend option objects that will be filled with + * the populated values from the backend + * @return Error::Ok on success, Error::NotFound if backend is not found, or + * other error codes on failure + */ +Error get_option( + const char* backend_name, + executorch::runtime::Span + backend_options); + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::Backend; +using ::executorch::ET_RUNTIME_NAMESPACE::CompileSpec; +using ::executorch::ET_RUNTIME_NAMESPACE::DelegateHandle; +using ::executorch::ET_RUNTIME_NAMESPACE::get_backend_class; +using ::executorch::ET_RUNTIME_NAMESPACE::register_backend; +using ::executorch::ET_RUNTIME_NAMESPACE::SizedBuffer; +using PyTorchBackendInterface = + ::executorch::ET_RUNTIME_NAMESPACE::BackendInterface; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/backend/options.h b/include/executorch/runtime/backend/options.h new file mode 100644 index 0000000..7ff742f --- /dev/null +++ b/include/executorch/runtime/backend/options.h @@ -0,0 +1,208 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once +#include +#include +#include +#include +#include +#include + +namespace executorch { +namespace runtime { + +static constexpr size_t kMaxOptionKeyLength = 64; +static constexpr size_t kMaxOptionValueLength = 256; + +// All string keys and values must have static storage duration (string +// literals, static const char arrays, or global constants). The BackendOptions +// class does NOT take ownership of strings. +using OptionValue = + std::variant>; + +struct BackendOption { + // key is the name of the backend option, like num_threads, enable_profiling, + // etc + char key[kMaxOptionKeyLength]{}; + // value is the value of the backend option, like 4, true, etc + OptionValue value; +}; + +/** + * A template class for storing and managing backend-specific configuration + * options. + * + * This class provides a type-safe way to store key-value pairs for backend + * configuration, with compile-time capacity limits and runtime type checking. + * It supports bool, int, and const char* value types. + * + * @tparam MaxCapacity The maximum number of options that can be stored + */ +template +class BackendOptions { + public: + /** + * Copy constructor + */ + BackendOptions(const BackendOptions& other) : size_(other.size_) { + for (size_t i = 0; i < size_; ++i) { + options_[i] = other.options_[i]; + } + } + + /** + * Copy assignment operator + */ + BackendOptions& operator=(const BackendOptions& other) { + if (this != &other) { + size_ = other.size_; + for (size_t i = 0; i < size_; ++i) { + options_[i] = other.options_[i]; + } + } + return *this; + } + + /** + * Default constructor - initializes with zero options. + */ + BackendOptions() : size_(0) {} + + /** + * Returns a mutable view of all stored options as a Span. + * + * @return A mutable Span containing all BackendOption entries + */ + executorch::runtime::Span view() { + return executorch::runtime::Span(options_, size_); + } + + /** + * Sets a boolean option value for the given key. + * If the key already exists, updates its value. Otherwise, adds a new option. + * + * @tparam N The length of the key string (automatically deduced) + * @param key The option key (must be a string literal or array) + * @param value The boolean value to set + * @return Error::Ok on success, Error::InvalidArgument if storage is full + */ + template + Error set_option(const char (&key)[N], bool value) noexcept { + static_assert(N <= kMaxOptionKeyLength, "Option key is too long"); + return set_option_impl(key, value); + } + + /** + * Sets an integer option value for the given key. + * If the key already exists, updates its value. Otherwise, adds a new option. + * + * @tparam N The length of the key string (automatically deduced) + * @param key The option key (must be a string literal or array) + * @param value The integer value to set + * @return Error::Ok on success, Error::InvalidArgument if storage is full + */ + template + Error set_option(const char (&key)[N], int value) noexcept { + static_assert(N <= kMaxOptionKeyLength, "Option key is too long"); + return set_option_impl(key, value); + } + + /** + * Sets a string option value for the given key. + * If the key already exists, updates its value. Otherwise, adds a new option. + * + * Note: The string value must have static storage duration. This class does + * NOT take ownership of the string - it only stores the pointer. + * + * @tparam N The length of the key string (automatically deduced) + * @param key The option key (must be a string literal or array) + * @param value The string value to set (must have static storage duration) + * @return Error::Ok on success, Error::InvalidArgument if storage is full + */ + template + Error set_option(const char (&key)[N], const char* value) noexcept { + static_assert(N <= kMaxOptionKeyLength, "Option key is too long"); + // Create a fixed-size array and copy the string + std::array arr{}; + strncpy(arr.data(), value, kMaxOptionValueLength - 1); + arr[kMaxOptionValueLength - 1] = '\0'; // Ensure null termination + return set_option_impl(key, arr); + } + /** + * Retrieves an option value by key and type. + * + * @tparam T The expected type of the option value (bool, int, or const char*) + * @tparam KeyLen The length of the key string (automatically deduced) + * @param key The option key to look up + * @param out Reference to store the retrieved value + * @return Error::Ok if found and type matches, Error::NotFound if key doesn't + * exist, Error::InvalidArgument if type doesn't match + */ + template + Error get_option(const char (&key)[KeyLen], T& out) const { + static_assert(KeyLen <= kMaxOptionKeyLength, "Option key is too long"); + for (size_t i = 0; i < size_; ++i) { + if (std::strcmp(options_[i].key, key) == 0) { + // Special handling for string (convert array to const char*) + if constexpr (std::is_same_v) { + if (auto* arr = std::get_if>( + &options_[i].value)) { + out = arr->data(); // Return pointer to stored array + return Error::Ok; + } + } + // Default handling for bool/int + else if (auto* val = std::get_if(&options_[i].value)) { + out = *val; + return Error::Ok; + } + return Error::InvalidArgument; + } + } + return Error::NotFound; + } + + private: + BackendOption options_[MaxCapacity]{}; // Storage for backend options + size_t size_; // Current number of options + + /** + * Internal implementation for setting option values. + * Handles both updating existing options and adding new ones. + * + * @tparam T The type of the value (bool, int, or const char*) + * @param key The option key + * @param value The value to set + * @return Error::Ok on success, Error::InvalidArgument if storage is full + */ + template + Error set_option_impl(const char* key, T value) { + // Update existing if found + for (size_t i = 0; i < size_; ++i) { + if (strcmp(options_[i].key, key) == 0) { + options_[i].value = value; + return Error::Ok; + } + } + if (size_ < MaxCapacity) { + BackendOption new_option; + const size_t key_len = std::strlen(key); + const size_t copy_len = std::min(key_len, kMaxOptionKeyLength - 1); + std::memcpy(new_option.key, key, copy_len); + new_option.key[copy_len] = '\0'; + new_option.value = value; // Restored value assignment + options_[size_++] = new_option; // Store option and increment size + return Error::Ok; + } + return Error::InvalidArgument; + } +}; + +} // namespace runtime +} // namespace executorch diff --git a/include/executorch/runtime/core/array_ref.h b/include/executorch/runtime/core/array_ref.h new file mode 100644 index 0000000..d920761 --- /dev/null +++ b/include/executorch/runtime/core/array_ref.h @@ -0,0 +1,264 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +//===--- ArrayRef.h - Array Reference Wrapper -------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +// removed llvm-specific functionality +// removed some implicit const -> non-const conversions that rely on +// complicated std::enable_if meta-programming +// removed a bunch of slice variants for simplicity... +// remove constructors and operators for std::vector +// removed some prevention of accidental assignments from temporary that +// required std::enable_if meta-programming +// removed reverse iterator + +#pragma once + +#include +#include + +#include +#include +#include + +namespace executorch { +namespace runtime { + +/** + * Represents a constant reference to an array (0 or more elements + * consecutively in memory), i.e. a start pointer and a length. It allows + * various APIs to take consecutive elements easily and conveniently. + * + * This class does not own the underlying data, it is expected to be used in + * situations where the data resides in some other buffer, whose lifetime + * extends past that of the ArrayRef. For this reason, it is not in general + * safe to store an ArrayRef. + * + * Span and ArrayRef are extrememly similar with the difference being ArrayRef + * views a list of constant elements and Span views a list of mutable elements. + * Clients should decide between the two based on if the list elements for their + * use case should be mutable. + * + * This is intended to be trivially copyable, so it should be passed by + * value. + */ +template +class ArrayRef final { + public: + using iterator = const T*; + using const_iterator = const T*; + using size_type = size_t; + using value_type = T; + + private: + /// The start of the array, in an external buffer. + const T* Data; + + /// The number of elements. + size_type Length; + + public: + /// @name Constructors + /// @{ + + /// Construct an empty ArrayRef. + /* implicit */ constexpr ArrayRef() : Data(nullptr), Length(0) {} + + /// Construct a ArrayRef from a single element. Implicitly convert element + /// type. It is aligned with PyTorch's c10::ArrayRef. + /* implicit */ constexpr ArrayRef(const T& OneElt) + : Data(&OneElt), Length(1) {} + + /// Construct a ArrayRef from a pointer and length. + ArrayRef(const T* data, size_t length) : Data(data), Length(length) { + ET_DCHECK(Data != nullptr || Length == 0); + } + + /// Construct a ArrayRef from a range. + ArrayRef(const T* begin, const T* end) : Data(begin), Length(end - begin) {} + + /// Construct an ArrayRef from a std::array + template + /* implicit */ constexpr ArrayRef(const std::array& Arr) + : Data(Arr.data()), Length(N) {} + + /// Construct a ArrayRef from a C array. + template + /* implicit */ constexpr ArrayRef(const T (&Arr)[N]) : Data(Arr), Length(N) {} + + /// @} + /// @name Simple Operations + /// @{ + + constexpr iterator begin() const { + return Data; + } + constexpr iterator end() const { + return Data + Length; + } + + // These are actually the same as iterator, since ArrayRef only + // gives you const iterators. + constexpr const_iterator cbegin() const { + return Data; + } + constexpr const_iterator cend() const { + return Data + Length; + } + + /// empty - Check if the array is empty. + constexpr bool empty() const { + return Length == 0; + } + + constexpr const T* data() const { + return Data; + } + + /// size - Get the array size. + constexpr size_t size() const { + return Length; + } + + /// front - Get the first element. + const T& front() const { + // ArrayRef: attempted to access front() of empty list + ET_CHECK(!empty()); + return Data[0]; + } + + /// back - Get the last element. + const T& back() const { + // ArrayRef: attempted to access back() of empty list + ET_CHECK(!empty()); + return Data[Length - 1]; + } + + /// equals - Check for element-wise equality. + bool equals(ArrayRef RHS) const { + if (Length != RHS.Length) { + return false; + } + for (const auto i : c10::irange(this->Length)) { + if (Data[i] != RHS.Data[i]) { + return false; + } + } + return true; + } + + /// slice(n, m) - Take M elements of the array starting at element N + ArrayRef slice(size_t N, size_t M) const { + // cant slice longer then the array + size_t end = 0; + ET_CHECK(!c10::add_overflows(N, M, &end) && end <= size()); + return ArrayRef(data() + N, M); + } + + /// slice(n) - Chop off the first N elements of the array. + constexpr ArrayRef slice(size_t N) const { + return slice(N, size() - N); + } + + /// @} + /// @name Operator Overloads + /// @{ + constexpr const T& operator[](size_t Index) const { + return Data[Index]; + } + + /// Vector compatibility + const T& at(size_t Index) const { + // invalid index + ET_CHECK(Index < Length); + return Data[Index]; + } + + /// @} +}; + +/// @name ArrayRef Convenience constructors +/// @{ + +/// Construct an ArrayRef from a single element. +template +ArrayRef makeArrayRef(const T& OneElt) { + return OneElt; +} + +/// Construct an ArrayRef from a pointer and length. +template +ArrayRef makeArrayRef(const T* data, size_t length) { + return ArrayRef(data, length); +} + +/// Construct an ArrayRef from a range. +template +ArrayRef makeArrayRef(const T* begin, const T* end) { + return ArrayRef(begin, end); +} + +/// Construct an ArrayRef from a std::array. +template +ArrayRef makeArrayRef(const std::array& Arr) { + return Arr; +} + +/// Construct an ArrayRef from an ArrayRef (no-op) (const) +template +ArrayRef makeArrayRef(const ArrayRef& Vec) { + return Vec; +} + +/// Construct an ArrayRef from an ArrayRef (no-op) +template +ArrayRef& makeArrayRef(ArrayRef& Vec) { + return Vec; +} + +/// Construct an ArrayRef from a C array. +template +ArrayRef makeArrayRef(const T (&Arr)[N]) { + return ArrayRef(Arr); +} + +// WARNING: Template instantiation will NOT be willing to do an implicit +// conversions to get you to an ArrayRef, which is why we need so +// many overloads. + +template +bool operator==(ArrayRef a1, ArrayRef a2) { + return a1.equals(a2); +} + +template +bool operator!=(ArrayRef a1, ArrayRef a2) { + return !a1.equals(a2); +} + +using IntArrayRef = ArrayRef; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::ArrayRef; +using ::executorch::runtime::IntArrayRef; +using ::executorch::runtime::makeArrayRef; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/data_loader.h b/include/executorch/runtime/core/data_loader.h new file mode 100644 index 0000000..003f069 --- /dev/null +++ b/include/executorch/runtime/core/data_loader.h @@ -0,0 +1,206 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace executorch { +namespace runtime { + +/** + * Loads from a data source. + * + * See //executorch/extension/data_loader for common implementations. + */ +class DataLoader { + public: + /** + * Describes the content of the segment. + */ + struct SegmentInfo { + /** + * Represents the purpose of the segment. + */ + enum class Type { + /** + * Data for the actual program. + */ + Program, + /** + * Holds constant tensor data. + */ + Constant, + /** + * Data used for initializing a backend. + */ + Backend, + /** + * Data used for initializing mutable tensors. + */ + Mutable, + /** + * Data used for initializing external tensors. + */ + External, + }; + + /// Type of the segment. + Type segment_type; + + /// Index of the segment within the segment list. Undefined for program + /// segments. + size_t segment_index; + + /// An optional, null-terminated string describing the segment. For + /// `Backend` segments, this is the backend ID. Null for other segment + /// types. + const char* descriptor; + + SegmentInfo() = default; + + explicit SegmentInfo( + Type segment_type_, + size_t segment_index_ = 0, + const char* descriptor_ = nullptr) + : segment_type(segment_type_), + segment_index(segment_index_), + descriptor(descriptor_) {} + }; + + virtual ~DataLoader() = default; + + /** + * Loads data from the underlying data source. + * + * NOTE: This must be thread-safe. If this call modifies common state, the + * implementation must do its own locking. + * + * @param offset The byte offset in the data source to start loading from. + * @param size The number of bytes to load. + * @param segment_info Information about the segment being loaded. + * + * @returns a `FreeableBuffer` that owns the loaded data. + */ + ET_NODISCARD virtual Result + load(size_t offset, size_t size, const SegmentInfo& segment_info) const = 0; + + /** + * Loads data from the underlying data source into the provided buffer. + * + * NOTE: This must be thread-safe. If this call modifies common state, the + * implementation must do its own locking. + * + * @param offset The byte offset in the data source to start loading from. + * @param size The number of bytes to load. + * @param segment_info Information about the segment being loaded. + * @param buffer The buffer to load data into. Must point to at least `size` + * bytes of memory. + * + * @returns an Error indicating if the load was successful. + */ + ET_NODISCARD virtual Error load_into( + size_t offset, + size_t size, + const SegmentInfo& segment_info, + void* buffer) const { + // Using a stub implementation here instead of pure virtual to expand the + // data_loader interface in a backwards compatible way. + (void)buffer; + (void)offset; + (void)size; + (void)segment_info; + ET_LOG(Error, "load_into() not implemented for this data loader."); + return Error::NotImplemented; + } + + /** + * Returns the length of the underlying data source, typically the file size. + */ + ET_NODISCARD virtual Result size() const = 0; + + /** Loads data using a 64-bit source offset and size. */ + ET_NODISCARD virtual Result load_at_offset( + uint64_t offset, + uint64_t size, + const SegmentInfo& segment_info) const { +#if SIZE_MAX < UINT64_MAX + if (offset > std::numeric_limits::max()) { + ET_LOG( + Error, + "load_at_offset() source range cannot be represented by this data loader."); + return Error::NotSupported; + } +#endif + if (size > + static_cast(std::numeric_limits::max()) - offset) { + ET_LOG( + Error, + "load_at_offset() source range cannot be represented by this data loader."); + return Error::NotSupported; + } + return load( + static_cast(offset), static_cast(size), segment_info); + } + + /** Loads data from a 64-bit source offset into the provided buffer. */ + ET_NODISCARD virtual Error load_into_at_offset( + uint64_t offset, + size_t size, + const SegmentInfo& segment_info, + void* buffer) const { +#if SIZE_MAX < UINT64_MAX + if (offset > std::numeric_limits::max()) { + ET_LOG( + Error, + "load_into_at_offset() source range cannot be represented by this data loader."); + return Error::NotSupported; + } +#endif + if (static_cast(size) > + static_cast(std::numeric_limits::max()) - offset) { + ET_LOG( + Error, + "load_into_at_offset() source range cannot be represented by this data loader."); + return Error::NotSupported; + } + return load_into(static_cast(offset), size, segment_info, buffer); + } + + /** + * Returns the 64-bit length of the underlying data source. + * + * The default implementation widens the result from `size()`. Implementations + * that wrap sources larger than `size_t` can represent must override this + * method. + */ + ET_NODISCARD virtual Result source_size() const { + Result result = size(); + if (!result.ok()) { + return result.error(); + } + return static_cast(result.get()); + } +}; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::DataLoader; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/defines.h b/include/executorch/runtime/core/defines.h new file mode 100644 index 0000000..ee47126 --- /dev/null +++ b/include/executorch/runtime/core/defines.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * Contains preprocessor definitions used by ExecuTorch core. + */ + +#pragma once + +// Enable ET_ENABLE_ENUM_STRINGS by default. This option gates inclusion of +// enum string names and can be disabled by explicitly setting it to 0. +#ifndef ET_ENABLE_ENUM_STRINGS +#define ET_ENABLE_ENUM_STRINGS 1 +#endif diff --git a/include/executorch/runtime/core/device_allocator.h b/include/executorch/runtime/core/device_allocator.h new file mode 100644 index 0000000..4c5c561 --- /dev/null +++ b/include/executorch/runtime/core/device_allocator.h @@ -0,0 +1,215 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include +#include +#include +#include + +namespace executorch { +namespace runtime { + +/** + * Abstract interface for device-specific memory allocation. + * + * Each device type (CUDA, etc.) provides a concrete implementation + * that handles memory allocation on that device. Implementations are + * expected to be singletons with static lifetime, registered via + * DeviceAllocatorRegistry. + */ +class DeviceAllocator { + public: + /** + * Default alignment of memory returned by allocate(). Reuses + * MemoryAllocator::kDefaultAlignment so host- and device-side allocations + * share the same baseline contract. Backends whose underlying device APIs + * already provide stronger guarantees (e.g. cudaMalloc returns 256-byte + * aligned pointers) will trivially satisfy this. + */ + static constexpr size_t kDefaultAlignment = + MemoryAllocator::kDefaultAlignment; + + virtual ~DeviceAllocator() = default; + /** + * Allocate device memory. + * + * @param nbytes Number of bytes to allocate. + * @param index The device index. + * @param alignment Minimum alignment of the returned pointer in bytes. + * Must be a power of 2. Defaults to kDefaultAlignment. + * @return A Result containing the device pointer on success, or an error. + */ + virtual Result allocate( + size_t nbytes, + etensor::DeviceIndex index, + size_t alignment = kDefaultAlignment) = 0; + + /** + * Deallocate device memory previously allocated via allocate(). + * + * @param ptr Pointer to the memory to deallocate. + * @param index The device index. + */ + virtual void deallocate(void* ptr, etensor::DeviceIndex index) = 0; + + /** + * Copy data from host memory to device memory. + * + * @param dst Destination pointer (device memory). + * @param src Source pointer (host memory). + * @param nbytes Number of bytes to copy. + * @param index The device index. + * @return Error::Ok on success, or an appropriate error code on failure. + */ + virtual Error copy_host_to_device( + void* dst, + const void* src, + size_t nbytes, + etensor::DeviceIndex index) = 0; + + /** + * Copy data from device memory to host memory. + * + * @param dst Destination pointer (host memory). + * @param src Source pointer (device memory). + * @param nbytes Number of bytes to copy. + * @param index The device index. + * @return Error::Ok on success, or an appropriate error code on failure. + */ + virtual Error copy_device_to_host( + void* dst, + const void* src, + size_t nbytes, + etensor::DeviceIndex index) = 0; + + /** + * Returns the device type this allocator handles. + */ + virtual etensor::DeviceType device_type() const = 0; + + /** + * Waits until the copies to device `index` that this allocator made on the + * calling thread have finished, so that work on any stream of the device can + * read their results. Call it with the same per-thread settings the copies + * were made with: an allocator that copies on a stream chosen per thread + * waits for the stream chosen when this is called. + * The default does nothing, which suits allocators whose copies finish + * before they return. + * + * @param index The device index. + * @return Error::Ok on success, or an appropriate error code on failure. + */ + virtual Error synchronize(etensor::DeviceIndex index) { + (void)index; + return Error::Ok; + } +}; + +/** + * Registry for device allocators. + * + * Provides a global mapping from DeviceType to DeviceAllocator instances. + * Device allocators register themselves at static initialization time, + * and the runtime queries the registry to find the appropriate allocator + * for a given device type. + * + * Threading contract: + * - Registration is expected to happen once per device type during static + * initialization (single-threaded). The registry itself does not perform + * any locking around register_allocator()/get_allocator(), and concurrent + * registration is not supported. + * - After registration, get_allocator() is safe to call concurrently from + * multiple threads because the underlying array is never mutated again. + * - The DeviceAllocator implementation is responsible for its own + * thread-safety. When multiple Programs are loaded concurrently and each + * needs device memory, the allocator must serialize access to any shared + * state internally (similar to how XNNPACK's weight cache guards its + * internal state). The registry does not provide any synchronization on + * behalf of the allocator. + */ +class DeviceAllocatorRegistry { + public: + /** + * Returns the singleton instance of the registry. + */ + static DeviceAllocatorRegistry& instance(); + + /** + * Register an allocator. The device type is taken from + * alloc->device_type(). Each device type may only be registered once; + * attempting to register a second allocator for the same device type + * will abort. + * + * Not thread-safe. Expected to be called during static initialization. + * + * @param alloc Pointer to the allocator (must have static lifetime). + */ + void register_allocator(DeviceAllocator* alloc); + + /** + * Get the allocator for a specific device type. + * + * Safe to call concurrently with other get_allocator() calls. + * + * @param type The device type. + * @return Pointer to the allocator, or nullptr if not registered. + */ + DeviceAllocator* get_allocator(etensor::DeviceType type); + + private: + DeviceAllocatorRegistry() = default; + + // Singletons must not be copied or moved; instance() returns a reference, + // and silently shallow-copying the registry would lead to confusing bugs + // where modifications to the copy don't affect the real singleton. + DeviceAllocatorRegistry(const DeviceAllocatorRegistry&) = delete; + DeviceAllocatorRegistry& operator=(const DeviceAllocatorRegistry&) = delete; + DeviceAllocatorRegistry(DeviceAllocatorRegistry&&) = delete; + DeviceAllocatorRegistry& operator=(DeviceAllocatorRegistry&&) = delete; + + // Fixed-size array indexed by device type. This avoids dynamic allocation + // and is suitable for embedded environments. + DeviceAllocator* allocators_[etensor::kNumDeviceTypes] = {}; +}; + +// Convenience free functions + +/** + * Register a device allocator. The device type is taken from + * alloc->device_type(). See DeviceAllocatorRegistry::register_allocator() + * for the threading contract. + * + * @param alloc Pointer to the allocator (must have static lifetime). + */ +void register_device_allocator(DeviceAllocator* alloc); + +/** + * Get the device allocator for a specific device type. + * + * @param type The device type. + * @return Pointer to the allocator, or nullptr if not registered. + */ +DeviceAllocator* get_device_allocator(etensor::DeviceType type); + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::DeviceAllocator; +using ::executorch::runtime::DeviceAllocatorRegistry; +using ::executorch::runtime::get_device_allocator; +using ::executorch::runtime::register_device_allocator; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/device_memory_buffer.h b/include/executorch/runtime/core/device_memory_buffer.h new file mode 100644 index 0000000..929460c --- /dev/null +++ b/include/executorch/runtime/core/device_memory_buffer.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include + +#include +#include +#include + +namespace executorch::runtime { + +/** + * RAII wrapper that owns a single device memory allocation. + * + * On destruction, calls DeviceAllocator::deallocate() to free the memory. + * This mirrors the role of std::vector for CPU planned buffers, + * but for device memory (CUDA, etc.). + * + * Move-only: cannot be copied, but can be moved to transfer ownership. + */ +class DeviceMemoryBuffer final { + public: + /** + * Creates a DeviceMemoryBuffer by allocating device memory. + * + * Looks up the DeviceAllocator for the given device type via the + * DeviceAllocatorRegistry. If no allocator is registered for the type, + * returns Error::NotFound. + * + * @param size Number of bytes to allocate. + * @param type The device type (e.g., CUDA). + * @param index The device index (e.g., 0 for cuda:0). + * @param alignment Minimum alignment of the returned pointer in bytes. + * Must be a power of 2. Defaults to DeviceAllocator::kDefaultAlignment. + * @return A Result containing the DeviceMemoryBuffer on success, or an error. + */ + static Result create( + size_t size, + etensor::DeviceType type, + etensor::DeviceIndex index = 0, + size_t alignment = DeviceAllocator::kDefaultAlignment); + + DeviceMemoryBuffer() = default; + + ~DeviceMemoryBuffer() { + if (ptr_ != nullptr && allocator_ != nullptr) { + allocator_->deallocate(ptr_, device_index_); + } + } + + // Move constructor: transfer ownership. + DeviceMemoryBuffer(DeviceMemoryBuffer&& other) noexcept + : ptr_(other.ptr_), + size_(other.size_), + allocator_(other.allocator_), + device_index_(other.device_index_) { + other.ptr_ = nullptr; + other.size_ = 0; + other.allocator_ = nullptr; + } + + // Move assignment: release current, take ownership. + DeviceMemoryBuffer& operator=(DeviceMemoryBuffer&& other) noexcept { + if (this != &other) { + if (ptr_ != nullptr && allocator_ != nullptr) { + allocator_->deallocate(ptr_, device_index_); + } + ptr_ = other.ptr_; + size_ = other.size_; + allocator_ = other.allocator_; + device_index_ = other.device_index_; + other.ptr_ = nullptr; + other.size_ = 0; + other.allocator_ = nullptr; + } + return *this; + } + + // Non-copyable. + DeviceMemoryBuffer(const DeviceMemoryBuffer&) = delete; + DeviceMemoryBuffer& operator=(const DeviceMemoryBuffer&) = delete; + + /// Returns the device pointer, or nullptr if empty/moved-from. + void* data() const { + return ptr_; + } + + /// Returns the size in bytes of the allocation. + size_t size() const { + return size_; + } + + /** + * Returns a Span wrapping the device pointer. + * + * This is intended for use with HierarchicalAllocator, which only performs + * pointer arithmetic on the span data and never dereferences it. Device + * pointers are valid for pointer arithmetic from the CPU side. + */ + Span as_span() const { + return {static_cast(ptr_), size_}; + } + + private: + DeviceMemoryBuffer( + void* ptr, + size_t size, + DeviceAllocator* allocator, + etensor::DeviceIndex device_index) + : ptr_(ptr), + size_(size), + allocator_(allocator), + device_index_(device_index) {} + + void* ptr_ = nullptr; + size_t size_ = 0; + DeviceAllocator* allocator_ = nullptr; + etensor::DeviceIndex device_index_ = 0; +}; + +} // namespace executorch::runtime diff --git a/include/executorch/runtime/core/error.h b/include/executorch/runtime/core/error.h new file mode 100644 index 0000000..b923604 --- /dev/null +++ b/include/executorch/runtime/core/error.h @@ -0,0 +1,264 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * ExecuTorch Error declarations. + */ + +#pragma once + +#include + +#include + +namespace executorch { +namespace runtime { + +// Alias error code integral type to minimal platform width (32-bits for now). +typedef uint32_t error_code_t; + +/** + * ExecuTorch Error type. + */ +enum class Error : error_code_t { + /* + * System errors. + */ + + /// Status indicating a successful operation. + Ok = 0x00, + + /// An internal error occurred. + Internal = 0x01, + + /// Status indicating the executor is in an invalid state for a target + /// operation + InvalidState = 0x2, + + /// Status indicating there are no more steps of execution to run + EndOfMethod = 0x03, + + /// Status indicating a resource has already been loaded. + AlreadyLoaded = 0x04, + + /* + * Logical errors. + */ + + /// Operation is not supported in the current context. + NotSupported = 0x10, + + /// Operation is not yet implemented. + NotImplemented = 0x11, + + /// User provided an invalid argument. + InvalidArgument = 0x12, + + /// Object is an invalid type for the operation. + InvalidType = 0x13, + + /// Operator(s) missing in the operator registry. + OperatorMissing = 0x14, + + /// Registration error: Exceeding the maximum number of kernels. + RegistrationExceedingMaxKernels = 0x15, + + /// Registration error: The kernel is already registered. + RegistrationAlreadyRegistered = 0x16, + + /* + * Resource errors. + */ + + /// Requested resource could not be found. + NotFound = 0x20, + + /// Could not allocate the requested memory. + MemoryAllocationFailed = 0x21, + + /// Could not access a resource. + AccessFailed = 0x22, + + /// Error caused by the contents of a program. + InvalidProgram = 0x23, + + /// Error caused by the contents of external data. + InvalidExternalData = 0x24, + + /// Does not have enough resources to perform the requested operation. + OutOfResources = 0x25, + + /* + * Delegate errors. + */ + + /// Init stage: Backend receives an incompatible delegate version. + DelegateInvalidCompatibility = 0x30, + /// Init stage: Backend fails to allocate memory. + DelegateMemoryAllocationFailed = 0x31, + /// Execute stage: The handle is invalid. + DelegateInvalidHandle = 0x32, +}; + +// Stringify the Error enum. +constexpr const char* to_string(const Error error) { + switch (error) { + case Error::Ok: + return "Error::Ok"; + case Error::Internal: + return "Error::Internal"; + case Error::InvalidState: + return "Error::InvalidState"; + case Error::EndOfMethod: + return "Error::EndOfMethod"; + case Error::AlreadyLoaded: + return "Error::AlreadyLoaded"; + case Error::NotSupported: + return "Error::NotSupported"; + case Error::NotImplemented: + return "Error::NotImplemented"; + case Error::InvalidArgument: + return "Error::InvalidArgument"; + case Error::InvalidType: + return "Error::InvalidType"; + case Error::OperatorMissing: + return "Error::OperatorMissing"; + case Error::NotFound: + return "Error::NotFound"; + case Error::MemoryAllocationFailed: + return "Error::MemoryAllocationFailed"; + case Error::AccessFailed: + return "Error::AccessFailed"; + case Error::InvalidProgram: + return "Error::InvalidProgram"; + case Error::InvalidExternalData: + return "Error::InvalidExternalData"; + case Error::OutOfResources: + return "Error::OutOfResources"; + case Error::DelegateInvalidCompatibility: + return "Error::DelegateInvalidCompatibility"; + case Error::DelegateMemoryAllocationFailed: + return "Error::DelegateMemoryAllocationFailed"; + case Error::DelegateInvalidHandle: + return "Error::DelegateInvalidHandle"; + case Error::RegistrationExceedingMaxKernels: + return "Error::RegistrationExceedingMaxKernels"; + case Error::RegistrationAlreadyRegistered: + return "Error::RegistrationAlreadyRegistered"; + default: + return "Error::Unknown"; + } +} + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::Error; +using ::executorch::runtime::error_code_t; +} // namespace executor +} // namespace torch + +/** + * If cond__ is false, log the specified message and return the specified Error + * from the current function, which must be of return type + * executorch::runtime::Error. + * + * @param[in] cond__ The condition to be checked, asserted as true. + * @param[in] error__ Error enum value to return without the `Error::` prefix, + * like `InvalidArgument`. + * @param[in] message__ Format string for the log error message. + * @param[in] ... Optional additional arguments for the format string. + */ +#define ET_CHECK_OR_RETURN_ERROR(cond__, error__, message__, ...) \ + { \ + if (!(cond__)) { \ + ET_LOG(Error, message__, ##__VA_ARGS__); \ + return ::executorch::runtime::Error::error__; \ + } \ + } + +/** + * A convenience macro to be used in utility functions that check whether input + * tensor(s) are valid, which are expected to return a boolean. Checks whether + * `cond` is true; if not, log the failed check with `message` and return false. + * + * @param[in] cond the condition to check + * @param[in] message an additional message to log with `cond` + */ +#define ET_CHECK_OR_RETURN_FALSE(cond__, message__, ...) \ + { \ + if (!(cond__)) { \ + ET_LOG(Error, "Check failed (%s): " message__, #cond__, ##__VA_ARGS__); \ + return false; \ + } \ + } + +/** + * If error__ is not Error::Ok, optionally log a message and return the error + * from the current function, which must be of return type + * executorch::runtime::Error. + * + * @param[in] error__ Error enum value asserted to be Error::Ok. + * @param[in] ... Optional format string for the log error message and its + * arguments. + */ +#define ET_CHECK_OK_OR_RETURN_ERROR(...) \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR(__VA_ARGS__) + +/** + * Internal only: Use ET_CHECK_OK_OR_RETURN_ERROR() instead. + * This macro selects the correct version of + * ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR based on the number of arguments passed. + * It uses a helper that reliably picks the 1-arg or 2+-arg form on + * MSVC/Clang/GCC. + */ +#define ET_INTERNAL_EXPAND(x) x +#define ET_INTERNAL_GET_MACRO( \ + _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, NAME, ...) \ + NAME + +// Internal only: Use ET_CHECK_OK_OR_RETURN_ERROR() instead. +// Picks _2 for 2..10 args, _1 for exactly 1 arg. +#define ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR(...) \ + ET_INTERNAL_EXPAND(ET_INTERNAL_GET_MACRO( \ + __VA_ARGS__, \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2, /* 10 */ \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2, /* 9 */ \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2, /* 8 */ \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2, /* 7 */ \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2, /* 6 */ \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2, /* 5 */ \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2, /* 4 */ \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2, /* 3 */ \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2, /* 2 */ \ + ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_1 /* 1 */ \ + )(__VA_ARGS__)) + +// Internal only: Use ET_CHECK_OK_OR_RETURN_ERROR() instead. +#define ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_1(error__) \ + do { \ + const auto et_error__ = (error__); \ + if (et_error__ != ::executorch::runtime::Error::Ok) { \ + return et_error__; \ + } \ + } while (0) + +// Internal only: Use ET_CHECK_OK_OR_RETURN_ERROR() instead. +#define ET_INTERNAL_CHECK_OK_OR_RETURN_ERROR_2(error__, message__, ...) \ + do { \ + const auto et_error__ = (error__); \ + if (et_error__ != ::executorch::runtime::Error::Ok) { \ + ET_LOG(Error, message__, ##__VA_ARGS__); \ + return et_error__; \ + } \ + } while (0) diff --git a/include/executorch/runtime/core/evalue.h b/include/executorch/runtime/core/evalue.h new file mode 100644 index 0000000..8c12b89 --- /dev/null +++ b/include/executorch/runtime/core/evalue.h @@ -0,0 +1,877 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once +#include +#include +#include +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { + +struct EValue; + +namespace internal { + +// Tensor gets proper reference treatment because its expensive to copy in aten +// mode, all other types are just copied. +template +struct evalue_to_const_ref_overload_return { + using type = T; +}; + +template <> +struct evalue_to_const_ref_overload_return { + using type = const executorch::aten::Tensor&; +}; + +template +struct evalue_to_ref_overload_return { + using type = T; +}; + +template <> +struct evalue_to_ref_overload_return { + using type = executorch::aten::Tensor&; +}; + +} // namespace internal + +/* + * Helper class used to correlate EValues in the executor table, with the + * unwrapped list of the proper type. Because values in the runtime's values + * table can change during execution, we cannot statically allocate list of + * objects at deserialization. Imagine the serialized list says index 0 in the + * value table is element 2 in the list, but during execution the value in + * element 2 changes (in the case of tensor this means the TensorImpl* stored in + * the tensor changes). To solve this instead they must be created dynamically + * whenever they are used. + */ +template +class BoxedEvalueList { + public: + BoxedEvalueList() = default; + /* + * Wrapped_vals is a list of pointers into the values table of the runtime + * whose destinations correlate with the elements of the list, unwrapped_vals + * is a container of the same size whose serves as memory to construct the + * unwrapped vals. + */ + BoxedEvalueList(EValue** wrapped_vals, T* unwrapped_vals, int size) + : wrapped_vals_(checkWrappedVals(wrapped_vals, size), size), + unwrapped_vals_(checkUnwrappedVals(unwrapped_vals)) {} + + /* + * Constructs and returns the list of T specified by the EValue pointers + */ + executorch::aten::ArrayRef get() const; + + /** + * Result-returning counterpart of get(). Validates each wrapped EValue's + * tag before materializing; returns Error::InvalidType if any element's + * tag does not match T and Error::InvalidState if any element pointer is + * null. Use this when materializing lists from untrusted .pte data so that + * a malformed program cannot force a process abort inside to() / + * ET_CHECK. + */ + Result> tryGet() const; + + /** + * Destroys the unwrapped elements without re-dereferencing wrapped_vals_. + * This is safe to call during EValue destruction because it does not + * dereference wrapped_vals_, which may point to EValues mutated by + * MoveCall instructions. + */ + void destroy_elements() { + for (typename executorch::aten::ArrayRef::size_type i = 0; + i < wrapped_vals_.size(); + i++) { + unwrapped_vals_[i].~T(); + } + } + + private: + static EValue** checkWrappedVals(EValue** wrapped_vals, int size) { + ET_CHECK_MSG(wrapped_vals != nullptr, "wrapped_vals cannot be null"); + ET_CHECK_MSG(size >= 0, "size cannot be negative"); + return wrapped_vals; + } + + static T* checkUnwrappedVals(T* unwrapped_vals) { + ET_CHECK_MSG(unwrapped_vals != nullptr, "unwrapped_vals cannot be null"); + return unwrapped_vals; + } + + // Source of truth for the list + executorch::aten::ArrayRef wrapped_vals_; + // Same size as wrapped_vals + mutable T* unwrapped_vals_; +}; + +template <> +executorch::aten::ArrayRef> +BoxedEvalueList>::get() const; + +template <> +Result>> +BoxedEvalueList>::tryGet() const; + +// Aggregate typing system similar to IValue only slimmed down with less +// functionality, no dependencies on atomic, and fewer supported types to better +// suit embedded systems (ie no intrusive ptr) +struct EValue { + union Payload { + // When in ATen mode at::Tensor is not trivially copyable, this nested union + // lets us handle tensor as a special case while leaving the rest of the + // fields in a simple state instead of requiring a switch on tag everywhere. + union TriviallyCopyablePayload { + TriviallyCopyablePayload() : as_int(0) {} + // Scalar supported through these 3 types + int64_t as_int; + double as_double; + bool as_bool; + + executorch::aten::ArrayRef* as_string_ptr; + executorch::aten::ArrayRef* as_double_list_ptr; + executorch::aten::ArrayRef* as_bool_list_ptr; + BoxedEvalueList* as_int_list_ptr; + BoxedEvalueList* as_tensor_list_ptr; + BoxedEvalueList>* + as_list_optional_tensor_ptr; + } copyable_union; + + // Since a Tensor just holds a TensorImpl*, there's no value to use Tensor* + // here. + executorch::aten::Tensor as_tensor; + + Payload() {} + ~Payload() {} + }; + + // Data storage and type tag + Payload payload; + Tag tag; + + // Basic ctors and assignments + EValue(const EValue& rhs) : EValue(rhs.payload, rhs.tag) {} + + EValue(EValue&& rhs) noexcept : tag(rhs.tag) { + moveFrom(std::move(rhs)); + } + + EValue& operator=(EValue&& rhs) & noexcept { + if (&rhs == this) { + return *this; + } + + destroy(); + moveFrom(std::move(rhs)); + return *this; + } + + EValue& operator=(EValue const& rhs) & { + // Define copy assignment through copy ctor and move assignment + *this = EValue(rhs); + return *this; + } + + ~EValue() { + destroy(); + } + + /****** None Type ******/ + EValue() : tag(Tag::None) { + payload.copyable_union.as_int = 0; + } + + bool isNone() const { + return tag == Tag::None; + } + + /****** Int Type ******/ + /*implicit*/ EValue(int64_t i) : tag(Tag::Int) { + payload.copyable_union.as_int = i; + } + + bool isInt() const { + return tag == Tag::Int; + } + + int64_t toInt() const { + ET_CHECK_MSG(isInt(), "EValue is not an int."); + return payload.copyable_union.as_int; + } + + Result tryToInt() const { + if (!isInt()) { + return Error::InvalidType; + } + return payload.copyable_union.as_int; + } + + /****** Double Type ******/ + /*implicit*/ EValue(double d) : tag(Tag::Double) { + payload.copyable_union.as_double = d; + } + + bool isDouble() const { + return tag == Tag::Double; + } + + double toDouble() const { + ET_CHECK_MSG(isDouble(), "EValue is not a Double."); + return payload.copyable_union.as_double; + } + + Result tryToDouble() const { + if (!isDouble()) { + return Error::InvalidType; + } + return payload.copyable_union.as_double; + } + + /****** Bool Type ******/ + /*implicit*/ EValue(bool b) : tag(Tag::Bool) { + payload.copyable_union.as_bool = b; + } + + bool isBool() const { + return tag == Tag::Bool; + } + + bool toBool() const { + ET_CHECK_MSG(isBool(), "EValue is not a Bool."); + return payload.copyable_union.as_bool; + } + + Result tryToBool() const { + if (!isBool()) { + return Error::InvalidType; + } + return payload.copyable_union.as_bool; + } + + /****** Scalar Type ******/ + /// Construct an EValue using the implicit value of a Scalar. + /*implicit*/ EValue(executorch::aten::Scalar s) { + if (s.isIntegral(false)) { + tag = Tag::Int; + payload.copyable_union.as_int = s.to(); + } else if (s.isFloatingPoint()) { + tag = Tag::Double; + payload.copyable_union.as_double = s.to(); + } else if (s.isBoolean()) { + tag = Tag::Bool; + payload.copyable_union.as_bool = s.to(); + } else { + ET_CHECK_MSG(false, "Scalar passed to EValue is not initialized."); + } + } + + bool isScalar() const { + return tag == Tag::Int || tag == Tag::Double || tag == Tag::Bool; + } + + executorch::aten::Scalar toScalar() const { + // Convert from implicit value to Scalar using implicit constructors. + + if (isDouble()) { + return toDouble(); + } else if (isInt()) { + return toInt(); + } else if (isBool()) { + return toBool(); + } else { + ET_CHECK_MSG(false, "EValue is not a Scalar."); + } + } + + Result tryToScalar() const { + if (isDouble()) { + return executorch::aten::Scalar(payload.copyable_union.as_double); + } + if (isInt()) { + return executorch::aten::Scalar(payload.copyable_union.as_int); + } + if (isBool()) { + return executorch::aten::Scalar(payload.copyable_union.as_bool); + } + return Error::InvalidType; + } + + /****** Tensor Type ******/ + /*implicit*/ EValue(executorch::aten::Tensor t) : tag(Tag::Tensor) { + // When built in aten mode, at::Tensor has a non trivial constructor + // destructor, so regular assignment to a union field is UB. Instead we must + // go through placement new (which causes a refcount bump). + new (&payload.as_tensor) executorch::aten::Tensor(t); + } + + // Template constructor that allows construction from types that can be + // dereferenced to produce a type that EValue can be implicitly constructed + // from. + template < + typename T, + typename = typename std::enable_if(std::declval())), // declval to simulate + // forwarding + EValue>::value>::type> + /*implicit*/ EValue(T&& value) { + ET_CHECK_MSG(value != nullptr, "Pointer is null."); + // Note that this ctor does not initialize this->tag directly; it is set by + // moving in the new value. + moveFrom(*std::forward(value)); + } + + // Delete constructor for raw pointers to ensure they cannot be used. + template + explicit EValue(T* value) = delete; + + bool isTensor() const { + return tag == Tag::Tensor; + } + + executorch::aten::Tensor toTensor() && { + ET_CHECK_MSG(isTensor(), "EValue is not a Tensor."); + auto res = std::move(payload.as_tensor); + clearToNone(); + return res; + } + + executorch::aten::Tensor& toTensor() & { + ET_CHECK_MSG(isTensor(), "EValue is not a Tensor."); + return payload.as_tensor; + } + + const executorch::aten::Tensor& toTensor() const& { + ET_CHECK_MSG(isTensor(), "EValue is not a Tensor."); + return payload.as_tensor; + } + + // Returns a copy of the Tensor handle (one intrusive_ptr refcount bump in + // ATen mode; free in lean mode). Unlike toTensor()'s const& / & overloads, + // tryToTensor() cannot return a reference — Result wraps by value. + Result tryToTensor() const { + if (!isTensor()) { + return Error::InvalidType; + } + return payload.as_tensor; + } + + /****** String Type ******/ + /*implicit*/ EValue(executorch::aten::ArrayRef* s) : tag(Tag::String) { + ET_CHECK_MSG(s != nullptr, "ArrayRef pointer cannot be null"); + payload.copyable_union.as_string_ptr = s; + } + + bool isString() const { + return tag == Tag::String; + } + + std::string_view toString() const { + ET_CHECK_MSG(isString(), "EValue is not a String."); + ET_CHECK_MSG( + payload.copyable_union.as_string_ptr != nullptr, + "EValue string pointer is null."); + return std::string_view( + payload.copyable_union.as_string_ptr->data(), + payload.copyable_union.as_string_ptr->size()); + } + + Result tryToString() const { + if (!isString()) { + return Error::InvalidType; + } + if (payload.copyable_union.as_string_ptr == nullptr) { + return Error::InvalidState; + } + return std::string_view( + payload.copyable_union.as_string_ptr->data(), + payload.copyable_union.as_string_ptr->size()); + } + + /****** Int List Type ******/ + /*implicit*/ EValue(BoxedEvalueList* i) : tag(Tag::ListInt) { + ET_CHECK_MSG( + i != nullptr, "BoxedEvalueList pointer cannot be null"); + payload.copyable_union.as_int_list_ptr = i; + } + + bool isIntList() const { + return tag == Tag::ListInt; + } + + executorch::aten::ArrayRef toIntList() const { + ET_CHECK_MSG(isIntList(), "EValue is not an Int List."); + ET_CHECK_MSG( + payload.copyable_union.as_int_list_ptr != nullptr, + "EValue int list pointer is null."); + return (payload.copyable_union.as_int_list_ptr)->get(); + } + + Result> tryToIntList() const { + if (!isIntList()) { + return Error::InvalidType; + } + if (payload.copyable_union.as_int_list_ptr == nullptr) { + return Error::InvalidState; + } + return (payload.copyable_union.as_int_list_ptr)->tryGet(); + } + + /****** Bool List Type ******/ + /*implicit*/ EValue(executorch::aten::ArrayRef* b) + : tag(Tag::ListBool) { + ET_CHECK_MSG(b != nullptr, "ArrayRef pointer cannot be null"); + payload.copyable_union.as_bool_list_ptr = b; + } + + bool isBoolList() const { + return tag == Tag::ListBool; + } + + executorch::aten::ArrayRef toBoolList() const { + ET_CHECK_MSG(isBoolList(), "EValue is not a Bool List."); + ET_CHECK_MSG( + payload.copyable_union.as_bool_list_ptr != nullptr, + "EValue bool list pointer is null."); + return *(payload.copyable_union.as_bool_list_ptr); + } + + Result> tryToBoolList() const { + if (!isBoolList()) { + return Error::InvalidType; + } + if (payload.copyable_union.as_bool_list_ptr == nullptr) { + return Error::InvalidState; + } + return *(payload.copyable_union.as_bool_list_ptr); + } + + /****** Double List Type ******/ + /*implicit*/ EValue(executorch::aten::ArrayRef* d) + : tag(Tag::ListDouble) { + ET_CHECK_MSG(d != nullptr, "ArrayRef pointer cannot be null"); + payload.copyable_union.as_double_list_ptr = d; + } + + bool isDoubleList() const { + return tag == Tag::ListDouble; + } + + executorch::aten::ArrayRef toDoubleList() const { + ET_CHECK_MSG(isDoubleList(), "EValue is not a Double List."); + ET_CHECK_MSG( + payload.copyable_union.as_double_list_ptr != nullptr, + "EValue double list pointer is null."); + return *(payload.copyable_union.as_double_list_ptr); + } + + Result> tryToDoubleList() const { + if (!isDoubleList()) { + return Error::InvalidType; + } + if (payload.copyable_union.as_double_list_ptr == nullptr) { + return Error::InvalidState; + } + return *(payload.copyable_union.as_double_list_ptr); + } + + /****** Tensor List Type ******/ + /*implicit*/ EValue(BoxedEvalueList* t) + : tag(Tag::ListTensor) { + ET_CHECK_MSG( + t != nullptr, "BoxedEvalueList pointer cannot be null"); + payload.copyable_union.as_tensor_list_ptr = t; + } + + bool isTensorList() const { + return tag == Tag::ListTensor; + } + + executorch::aten::ArrayRef toTensorList() const { + ET_CHECK_MSG(isTensorList(), "EValue is not a Tensor List."); + ET_CHECK_MSG( + payload.copyable_union.as_tensor_list_ptr != nullptr, + "EValue tensor list pointer is null."); + return payload.copyable_union.as_tensor_list_ptr->get(); + } + + Result> tryToTensorList() + const { + if (!isTensorList()) { + return Error::InvalidType; + } + if (payload.copyable_union.as_tensor_list_ptr == nullptr) { + return Error::InvalidState; + } + return payload.copyable_union.as_tensor_list_ptr->tryGet(); + } + + /****** List Optional Tensor Type ******/ + /*implicit*/ EValue( + BoxedEvalueList>* t) + : tag(Tag::ListOptionalTensor) { + ET_CHECK_MSG( + t != nullptr, + "BoxedEvalueList> pointer cannot be null"); + payload.copyable_union.as_list_optional_tensor_ptr = t; + } + + bool isListOptionalTensor() const { + return tag == Tag::ListOptionalTensor; + } + + executorch::aten::ArrayRef> + toListOptionalTensor() const { + ET_CHECK_MSG( + isListOptionalTensor(), "EValue is not a List Optional Tensor."); + ET_CHECK_MSG( + payload.copyable_union.as_list_optional_tensor_ptr != nullptr, + "EValue list optional tensor pointer is null."); + return payload.copyable_union.as_list_optional_tensor_ptr->get(); + } + + Result>> + tryToListOptionalTensor() const { + if (!isListOptionalTensor()) { + return Error::InvalidType; + } + if (payload.copyable_union.as_list_optional_tensor_ptr == nullptr) { + return Error::InvalidState; + } + return payload.copyable_union.as_list_optional_tensor_ptr->tryGet(); + } + + /****** ScalarType Type ******/ + executorch::aten::ScalarType toScalarType() const { + ET_CHECK_MSG(isInt(), "EValue is not a ScalarType."); + return static_cast( + payload.copyable_union.as_int); + } + + Result tryToScalarType() const { + if (!isInt()) { + return Error::InvalidType; + } + return static_cast( + payload.copyable_union.as_int); + } + + /****** MemoryFormat Type ******/ + executorch::aten::MemoryFormat toMemoryFormat() const { + ET_CHECK_MSG(isInt(), "EValue is not a MemoryFormat."); + return static_cast( + payload.copyable_union.as_int); + } + + Result tryToMemoryFormat() const { + if (!isInt()) { + return Error::InvalidType; + } + return static_cast( + payload.copyable_union.as_int); + } + + /****** Layout Type ******/ + executorch::aten::Layout toLayout() const { + ET_CHECK_MSG(isInt(), "EValue is not a Layout."); + return static_cast(payload.copyable_union.as_int); + } + + Result tryToLayout() const { + if (!isInt()) { + return Error::InvalidType; + } + return static_cast(payload.copyable_union.as_int); + } + + /****** Device Type ******/ + executorch::aten::Device toDevice() const { + ET_CHECK_MSG(isInt(), "EValue is not a Device."); + return executorch::aten::Device( + static_cast( + payload.copyable_union.as_int), + -1); + } + + Result tryToDevice() const { + if (!isInt()) { + return Error::InvalidType; + } + return executorch::aten::Device( + static_cast( + payload.copyable_union.as_int), + -1); + } + + template + T to() &&; + template + typename internal::evalue_to_const_ref_overload_return::type to() const&; + template + typename internal::evalue_to_ref_overload_return::type to() &; + + /** + * Result-returning equivalent of `to()`. Tag mismatch returns + * `Error::InvalidType`; a null list/string payload returns + * `Error::InvalidState`. Specializations are defined below via + * `EVALUE_DEFINE_TRY_TO`. + */ + template + Result tryTo() const; + + /** + * Converts the EValue to an optional object that can represent both T and + * an uninitialized state. + */ + template + inline std::optional toOptional() const { + if (this->isNone()) { + return executorch::aten::nullopt; + } + return this->to(); + } + + /** + * Result-returning equivalent of `toOptional()`. None maps to an empty + * optional; any other tag that doesn't match T propagates `tryTo()`'s + * error (`Error::InvalidType`). + */ + template + inline Result> tryToOptional() const { + if (this->isNone()) { + return std::optional(std::nullopt); + } + auto r = this->tryTo(); + if (!r.ok()) { + return r.error(); + } + return std::optional(std::move(r.get())); + } + + private: + // Pre cond: the payload value has had its destructor called + void clearToNone() noexcept { + payload.copyable_union.as_int = 0; + tag = Tag::None; + } + + // Shared move logic + void moveFrom(EValue&& rhs) noexcept { + if (rhs.isTensor()) { + new (&payload.as_tensor) + executorch::aten::Tensor(std::move(rhs.payload.as_tensor)); + rhs.payload.as_tensor.~Tensor(); + } else { + payload.copyable_union = rhs.payload.copyable_union; + } + tag = rhs.tag; + rhs.clearToNone(); + } + + // Destructs stored tensor if there is one + void destroy() { + // Necessary for ATen tensor to refcount decrement the intrusive_ptr to + // tensorimpl that got a refcount increment when we placed it in the evalue, + // no-op if executorch tensor #ifdef could have a + // minor performance bump for a code maintainability hit + if (isTensor()) { + payload.as_tensor.~Tensor(); + } else if ( + isTensorList() && + payload.copyable_union.as_tensor_list_ptr != nullptr) { + payload.copyable_union.as_tensor_list_ptr->destroy_elements(); + } else if ( + isListOptionalTensor() && + payload.copyable_union.as_list_optional_tensor_ptr != nullptr) { + payload.copyable_union.as_list_optional_tensor_ptr->destroy_elements(); + } + } + + EValue(const Payload& p, Tag t) : tag(t) { + if (isTensor()) { + new (&payload.as_tensor) executorch::aten::Tensor(p.as_tensor); + } else { + payload.copyable_union = p.copyable_union; + } + } +}; + +#define EVALUE_DEFINE_TO(T, method_name) \ + template <> \ + inline T EValue::to()&& { \ + return static_cast(std::move(*this).method_name()); \ + } \ + template <> \ + inline ::executorch::ET_RUNTIME_NAMESPACE::internal:: \ + evalue_to_const_ref_overload_return::type \ + EValue::to() const& { \ + typedef ::executorch::ET_RUNTIME_NAMESPACE::internal:: \ + evalue_to_const_ref_overload_return::type return_type; \ + return static_cast(this->method_name()); \ + } \ + template <> \ + inline ::executorch::ET_RUNTIME_NAMESPACE::internal:: \ + evalue_to_ref_overload_return::type \ + EValue::to()& { \ + typedef ::executorch::ET_RUNTIME_NAMESPACE::internal:: \ + evalue_to_ref_overload_return::type return_type; \ + return static_cast(this->method_name()); \ + } + +EVALUE_DEFINE_TO(executorch::aten::Scalar, toScalar) +EVALUE_DEFINE_TO(int64_t, toInt) +EVALUE_DEFINE_TO(bool, toBool) +EVALUE_DEFINE_TO(double, toDouble) +EVALUE_DEFINE_TO(std::string_view, toString) +EVALUE_DEFINE_TO(executorch::aten::ScalarType, toScalarType) +EVALUE_DEFINE_TO(executorch::aten::MemoryFormat, toMemoryFormat) +EVALUE_DEFINE_TO(executorch::aten::Layout, toLayout) +EVALUE_DEFINE_TO(executorch::aten::Device, toDevice) +// Tensor and Optional Tensor +EVALUE_DEFINE_TO( + std::optional, + toOptional) +EVALUE_DEFINE_TO(executorch::aten::Tensor, toTensor) + +// IntList and Optional IntList +EVALUE_DEFINE_TO(executorch::aten::ArrayRef, toIntList) +EVALUE_DEFINE_TO( + std::optional>, + toOptional>) + +// DoubleList and Optional DoubleList +EVALUE_DEFINE_TO(executorch::aten::ArrayRef, toDoubleList) +EVALUE_DEFINE_TO( + std::optional>, + toOptional>) + +// BoolList and Optional BoolList +EVALUE_DEFINE_TO(executorch::aten::ArrayRef, toBoolList) +EVALUE_DEFINE_TO( + std::optional>, + toOptional>) + +// TensorList and Optional TensorList +EVALUE_DEFINE_TO( + executorch::aten::ArrayRef, + toTensorList) +EVALUE_DEFINE_TO( + std::optional>, + toOptional>) + +// List of Optional Tensor +EVALUE_DEFINE_TO( + executorch::aten::ArrayRef>, + toListOptionalTensor) +#undef EVALUE_DEFINE_TO + +#define EVALUE_DEFINE_TRY_TO(T, method_name) \ + template <> \ + inline Result EValue::tryTo() const { \ + return this->method_name(); \ + } + +EVALUE_DEFINE_TRY_TO(executorch::aten::Scalar, tryToScalar) +EVALUE_DEFINE_TRY_TO(int64_t, tryToInt) +EVALUE_DEFINE_TRY_TO(bool, tryToBool) +EVALUE_DEFINE_TRY_TO(double, tryToDouble) +EVALUE_DEFINE_TRY_TO(std::string_view, tryToString) +EVALUE_DEFINE_TRY_TO(executorch::aten::ScalarType, tryToScalarType) +EVALUE_DEFINE_TRY_TO(executorch::aten::MemoryFormat, tryToMemoryFormat) +EVALUE_DEFINE_TRY_TO(executorch::aten::Layout, tryToLayout) +EVALUE_DEFINE_TRY_TO(executorch::aten::Device, tryToDevice) +// Tensor and Optional Tensor +EVALUE_DEFINE_TRY_TO(executorch::aten::Tensor, tryToTensor) +EVALUE_DEFINE_TRY_TO( + std::optional, + tryToOptional) + +// IntList and Optional IntList +EVALUE_DEFINE_TRY_TO(executorch::aten::ArrayRef, tryToIntList) +EVALUE_DEFINE_TRY_TO( + std::optional>, + tryToOptional>) + +// DoubleList and Optional DoubleList +EVALUE_DEFINE_TRY_TO(executorch::aten::ArrayRef, tryToDoubleList) +EVALUE_DEFINE_TRY_TO( + std::optional>, + tryToOptional>) + +// BoolList and Optional BoolList +EVALUE_DEFINE_TRY_TO(executorch::aten::ArrayRef, tryToBoolList) +EVALUE_DEFINE_TRY_TO( + std::optional>, + tryToOptional>) + +// TensorList and Optional TensorList +EVALUE_DEFINE_TRY_TO( + executorch::aten::ArrayRef, + tryToTensorList) +EVALUE_DEFINE_TRY_TO( + std::optional>, + tryToOptional>) + +// List of Optional Tensor +EVALUE_DEFINE_TRY_TO( + executorch::aten::ArrayRef>, + tryToListOptionalTensor) +#undef EVALUE_DEFINE_TRY_TO + +template +executorch::aten::ArrayRef BoxedEvalueList::get() const { + for (typename executorch::aten::ArrayRef::size_type i = 0; + i < wrapped_vals_.size(); + i++) { + ET_CHECK(wrapped_vals_[i] != nullptr); + unwrapped_vals_[i] = wrapped_vals_[i]->template to(); + } + return executorch::aten::ArrayRef{unwrapped_vals_, wrapped_vals_.size()}; +} + +template +Result> BoxedEvalueList::tryGet() const { + for (typename executorch::aten::ArrayRef::size_type i = 0; + i < wrapped_vals_.size(); + i++) { + if (wrapped_vals_[i] == nullptr) { + return Error::InvalidState; + } + auto r = wrapped_vals_[i]->template tryTo(); + if (!r.ok()) { + return r.error(); + } + unwrapped_vals_[i] = std::move(r.get()); + } + return executorch::aten::ArrayRef{unwrapped_vals_, wrapped_vals_.size()}; +} + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +#ifdef USE_ATEN_LIB +namespace executorch { +namespace runtime { +// ATen-mode EValue lives in runtime::aten; keep the runtime:: spelling working. +using ::executorch::ET_RUNTIME_NAMESPACE::BoxedEvalueList; +using ::executorch::ET_RUNTIME_NAMESPACE::EValue; +} // namespace runtime +} // namespace executorch +#endif + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::BoxedEvalueList; +using ::executorch::ET_RUNTIME_NAMESPACE::EValue; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/event_tracer.h b/include/executorch/runtime/core/event_tracer.h new file mode 100644 index 0000000..5bcdd0c --- /dev/null +++ b/include/executorch/runtime/core/event_tracer.h @@ -0,0 +1,592 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include +#include +#include +#include +#include + +#pragma once + +namespace executorch { +namespace runtime { + +/// Represents an allocator id returned by track_allocator. +typedef uint32_t AllocatorID; +/// Represents the chain id that will be passed in by the user during +/// event logging. +typedef int32_t ChainID; +/// Represents the debug handle that is generally associated with each +/// op executed in the runtime. +typedef uint32_t DebugHandle; +// Represents the delegate debug id that is generally associated with each +// delegate event. +typedef int32_t DelegateDebugIntId; + +/// Default id's for chain id and debug handle. +constexpr ChainID kUnsetChainId = -1; +constexpr DebugHandle kUnsetDebugHandle = 0; +constexpr DelegateDebugIntId kUnsetDelegateDebugIntId = -1; +// Default bundled input index to indicate that it hasn't been set yet. +constexpr int kUnsetBundledInputIndex = -1; + +/// Different types of delegate debug identifiers that are supported currently. +enum class DelegateDebugIdType { + /// Default value, indicates that it's not a delegate event. + kNone, + /// Indicates a delegate event logged using an integer delegate debug + /// identifier. + kInt, + /// Indicates a delegate event logged using a string delegate debug + /// identifier i.e. the delegate debug id is a pointer to a string table + /// managed by the class implementing EventTracer functionality. + kStr +}; + +/// Indicates the type of the EValue that was logged. These values could be +/// serialized and should not be changed. +enum class LoggedEValueType { + /// Intermediate output from an operator. + kIntermediateOutput = 0, + /// Output at the program level. This is essentially the output + /// of the model. + kProgramOutput = 1, +}; + +/// Indicates the level of event tracer debug logging. Verbosity of the logging +/// increases as we go down the enum list. +enum class EventTracerDebugLogLevel { + /// No logging. + kNoLogging, + /// When set to this only the program level outputs will be logged. + kProgramOutputs, + /// When set to this all intermediate outputs and program level outputs + /// will be logged. + kIntermediateOutputs, +}; + +/** + * EventTracerFilterBase is an abstract base class that provides an interface + * for filtering events based on their name or delegate debug index. + * Derived classes should implement the filter method to define specific + * filtering logic. + */ +class EventTracerFilterBase { + public: + /** + * Filters events based on the given name or delegate debug index. + * + * Note that only one of either the name or delegate_debug_index should be + * passed in. + * + * @param[in] name A pointer to a string representing the `name` of the + * event. If `delegate_debug_index` is not set to kUnsetDebugHandle, `name` + * should be set to nullptr. + * + * @param[in] delegate_debug_index A DebugHandle representing the debug index + * of the delegate. If `name` is not nullptr, this should be set to + * kUnsetDebugHandle. + * + * @return A Result indicating whether the event matches the filter + * criteria. + * - True if the event matches the filter. + * - False if the event does not match or is unknown. + * - An error code if an error occurs during filtering. + */ + virtual Result filter( + const char* name, + DelegateDebugIntId delegate_debug_index) = 0; + + /** + * Virtual destructor for the EventTracerFilterBase class. + * Ensures proper cleanup of derived class objects. + */ + virtual ~EventTracerFilterBase() = default; +}; + +/** + * Indicates the level of profiling that should be enabled. Profiling + * events will be logged in increasing order of verbosity as we go down the + * enum list. Thus it is important to keep the enum values in the right order. + */ +enum class EventTracerProfilingLevel { + /// No operator profiling. + kProfileMethodOnly, + /// All profiling events enabled. + kProfileAllEvents, +}; + +/** + * This is the struct which should be returned when a profiling event is + * started. This is used to uniquely identify that profiling event and will be + * required to be passed into the end_profiling call to signal that the event + * identified by this struct has completed. + * + * TODO(gasoonjia): Now this struct is mix-used for both delegate and + *non-delegate events. In the future we should separate them into two different + *structs: EventTracerEntry for non-delegate events holding DebugHandle, and + *DelegateEventTracerEntry for delegate events holding DelegateDebugIntId. + **/ +struct EventTracerEntry { + /// An event id to uniquely identify this event that was generated during a + /// call to start the tracking of an event. + int64_t event_id; + /// The chain to which this event belongs to. + ChainID chain_id; + /// The debug handle corresponding to this event. + DebugHandle debug_handle; + /// The time at which this event was started to be tracked. + et_timestamp_t start_time; + /// When delegate_event_id_type != DelegateDebugIdType::kNone it indicates + /// that event_id represents a delegate event. If delegate_event_id_type is: + /// 1) kInt then event_id contains an integer delegate debug id. + /// 2) kStr then event_id contains a string table index into a string table + /// maintained by the class implementing EventTracer functionality that will + /// give us the string identifier of this delegate event. For more details + /// refer to the DelegateMappingBuilder library present in + /// executorch/exir/backend/utils.py. + DelegateDebugIdType delegate_event_id_type; +}; +/** + * EventTracer is a class that users can inherit and implement to + * log/serialize/stream etc. the profiling and debugging events that are + * generated at runtime for a model. An example of this is the ETDump + * implementation in the devtools codebase that serializes these events to a + * flatbuffer. + */ +class EventTracer { + public: + /** + * Start a new event block (can consist of profiling and/or debugging events.) + * identified by this name. A block is conceptually a set of events that we + * want to group together. e.g. all the events that occur during the call to + * execute() (i.e. model inference) could be categorized as a block. + * + * @param[in] name A human readable identifier for the event block. Users + * calling this interface do not need to keep the memory pointed to by this + * pointer around. The string must be copied over into internal memory during + * this call. + */ + virtual void create_event_block(const char* name) = 0; + + /** + * Start the profiling of the event identified by name and debug_handle. + * The user can pass in a chain_id and debug_handle to this call, or leave + * them empty (default values) which would then result in the chain_id and + * debug handle stored within (set by set_chain_debug_handle) this class to be + * used. + * @param[in] name Human readable name for the profiling event. Users calling + * this interface do not need to keep the memory pointed to by this pointer + * around. The string must be copied over into internal memory during this + * call. + * @param[in] chain_id The id of the chain to which this event belongs to. If + * kUnsetChainId is passed in the chain_id and kUnsetDebugHandle for + * debug_handle then the values stored in the class internally for these + * properties will be used. + * @param[in] debug_handle Debug handle generated ahead-of-time during model + * compilation. + * + * @return Returns an instance of EventTracerEntry which should be passed back + * into the end_profiling() call. + */ + virtual EventTracerEntry start_profiling( + const char* name, + ChainID chain_id = kUnsetChainId, + DebugHandle debug_handle = kUnsetDebugHandle) = 0; + + /** + * Start the profiling of a delegate event. Similar to start_profiling it will + * return an instance of EventTracerEntry that contains the details of this + * event. + * + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must be copied + * over into internal memory during this call. + * @param[in] delegate_debug_index The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then kUnsetDebugHandle should be passed in here. + */ + virtual EventTracerEntry start_profiling_delegate( + const char* name, + DelegateDebugIntId delegate_debug_index) = 0; + + /** + * Signal the end of the delegate profiling event contained in + * event_tracer_entry. Users also have the option to log some some free-from + * string based metadata along with this. + * + * @param[in] event_tracer_entry The EventTracerEntry returned by a call to + * start_profiling_delegate(). + * @param[in] metadata Optional data relevant to the execution that the user + * wants to log along with this event. Pointer to metadata doesn't need to be + * valid after the call to this function. The contents and format of the data + * are transparent to the event tracer. It will just pipe along the data and + * make it available for the user again in the post-processing stage. + * @param[in] metadata_len Length of the metadata buffer. + */ + virtual void end_profiling_delegate( + EventTracerEntry event_tracer_entry, + const void* metadata = nullptr, + size_t metadata_len = 0) = 0; + + /** + * Some delegates get access to the profiling details only after the complete + * graph has been executed. This interface is to support such use cases. It + * can be called in a loop etc. to log any number of profiling events that are + * part of this delegate. + * + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must be copied + * over into internal memory during this call. + * @param[in] delegate_debug_index The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then kUnsetDebugHandle should be passed in here. + * @param[in] start_time The timestamp when the delegate event started. + * @param[in] end_time The timestamp when the delegate event finished. + * @param[in] metadata Optional data relevant to the execution that the user + * wants to log along with this event. Pointer to metadata doesn't need to be + * valid after the call to this function. The contents and format of the data + * are transparent to the event tracer. It will just pipe along the data and + * make it available for the user again in the post-processing stage. + * @param[in] metadata_len Length of the metadata buffer. + */ + virtual void log_profiling_delegate( + const char* name, + DelegateDebugIntId delegate_debug_index, + et_timestamp_t start_time, + et_timestamp_t end_time, + const void* metadata = nullptr, + size_t metadata_len = 0) = 0; + + /** + * End the profiling of the event identified by prof_entry + * + * @param[in] prof_entry Value returned by a call to start_profiling + */ + virtual void end_profiling(EventTracerEntry prof_entry) = 0; + + /** + * Track this allocation done via a MemoryAllocator which had profiling + * enabled on it. + * + * @param[in] id Allocator id generated by a call to track_allocator. + * @param[in] size The size of the allocation done, in bytes. + */ + virtual void track_allocation(AllocatorID id, size_t size) = 0; + + /** + * Generate an allocator id for this memory allocator that will be used in the + * future to identify all the allocations done by this allocator. + * + * @param[in] name Human readable name for the allocator. Users calling + * this interface do not need to keep the memory pointed to by this pointer + * around. The string should be copied over into internal memory during this + * call. + * + * @return Identifier to uniquely identify this allocator. + */ + virtual AllocatorID track_allocator(const char* name) = 0; + + /** + * Log an evalue during the execution of the model. This is useful for + * debugging purposes. Model outputs are a special case of this and will + * be logged with the output bool enabled. + * + * Users of this should refer to the chain_id and debug_handle to get the + * context for these evalues and their corresponding op. + * + * @param[in] evalue The value to be logged. + * @param[in] evalue_type Indicates what type of output this is logging e.g. + * an intermediate output, program output etc. + * @return A Result indicating the status of the logging operation. + * - True if the evalue output was successfully logged. + * - An error code if an error occurs during logging. + */ + virtual Result log_evalue( + const EValue& evalue, + LoggedEValueType evalue_type) = 0; + + /** + * Log an intermediate tensor output from a delegate. + * + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must be copied + * over into internal memory during this call. + * @param[in] delegate_debug_index The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then kUnsetDebugHandle should be passed in here. + * @param[in] output The tensor type output to be logged. + * @return A Result indicating the status of the logging operation. + * - True if the tensor type output was successfully logged. + * - False if the tensor type output was filtered out and not logged. + * - An error code if an error occurs during logging. + */ + virtual Result log_intermediate_output_delegate( + const char* name, + DelegateDebugIntId delegate_debug_index, + const executorch::aten::Tensor& output) = 0; + + /** + * Log an intermediate tensor array output from a delegate. + * + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must be copied + * over into internal memory during this call. + * @param[in] delegate_debug_index The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then kUnsetDebugHandle should be passed in here. + * @param[in] output The tensor array type output to be logged. + * @return A Result indicating the status of the logging operation. + * - True if the tensor array type output was successfully logged. + * - False if the tensor array type output was filtered out and not + * logged. + * - An error code if an error occurs during logging. + */ + virtual Result log_intermediate_output_delegate( + const char* name, + DelegateDebugIntId delegate_debug_index, + const ArrayRef output) = 0; + + /** + * Log an intermediate int output from a delegate. + * + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must be copied + * over into internal memory during this call. + * @param[in] delegate_debug_index The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then kUnsetDebugHandle should be passed in here. + * @param[in] output The int type output to be logged. + * @return A Result indicating the status of the logging operation. + * - True if the int type output was successfully logged. + * - False if the int type output was filtered out and not logged. + * - An error code if an error occurs during logging. + */ + virtual Result log_intermediate_output_delegate( + const char* name, + DelegateDebugIntId delegate_debug_index, + const int& output) = 0; + + /** + * Log an intermediate bool output from a delegate. + * + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must be copied + * over into internal memory during this call. + * @param[in] delegate_debug_index The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then kUnsetDebugHandle should be passed in here. + * @param[in] output The bool type output to be logged. + * @return A Result indicating the status of the logging operation. + * - True if the bool type output was successfully logged. + * - False if the bool type output was filtered out and not logged. + * - An error code if an error occurs during logging. + */ + virtual Result log_intermediate_output_delegate( + const char* name, + DelegateDebugIntId delegate_debug_index, + const bool& output) = 0; + + /** + * Log an intermediate double output from a delegate. + * + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must be copied + * over into internal memory during this call. + * @param[in] delegate_debug_index The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then kUnsetDebugHandle should be passed in here. + * @param[in] output The double type output to be logged. + * @return A Result indicating the status of the logging operation. + * - True if the double type output was successfully logged. + * - False if the double type output was filtered out and not logged. + * - An error code if an error occurs during logging. + */ + virtual Result log_intermediate_output_delegate( + const char* name, + DelegateDebugIntId delegate_debug_index, + const double& output) = 0; + + /** + * Set the filter of event tracer for delegation intermediate outputs. + */ + virtual void set_delegation_intermediate_output_filter( + EventTracerFilterBase* event_tracer_filter) = 0; + + /** + * Helper function to set the chain id ands debug handle. Users have two + * options, the first is that they can directly pass in the chain id and debug + * handle to start_profiling or they can explicitly set them through this + * helper before calling start_profiling. + * + * The reason this helper exists is to + * solve a specific problem. We want to do profiling logging inside the + * codegen layer which calls the kernels. The problem though is that the + * codegen layer doesn't have access to these ids when calling + * start_profiling. + * + * Users should ideally use these within a RAII scope interface to make sure + * that these values are unset after the end_profiling call. If non-default + * values are passed into the start_profiling call they will always be given + * precedence over the values set by this interface. + * + * So what we do is call this helper in method.cpp before + * we hit the codegen layer and in the codegen layer we do a start_profiling + * call without passing in a chain_id or debug_handle. This ensures that the + * values set via this helper are the ones associated with that call. + * + * @param[in] chain_id Chain id of the current instruction being exectuted. + * @param[in] debug_handle Debug handle of the current instruction being + * executed. In this context debug handle and instruction id are the same + * thing. + */ + void set_chain_debug_handle(ChainID chain_id, DebugHandle debug_handle) { + chain_id_ = chain_id; + debug_handle_ = debug_handle; + } + + /** + * When running a program wrapped in a bundled program, log the bundled input + * index of the current bundled input being tested out on this method. + * If users want to unset the index back to the default value, they can call + * this method with kUnsetBundledInputIndex. + * + * @param[in] bundled_input_index Index of the current input being tested + */ + void set_bundled_input_index(int bundled_input_index) { + bundled_input_index_ = bundled_input_index; + } + + /** + * Return the current bundled input index. + */ + int bundled_input_index() { + return bundled_input_index_; + } + + /** + * Set the level of event tracer debug logging that is desired. + * + */ + void set_event_tracer_debug_level(EventTracerDebugLogLevel log_level) { + event_tracer_debug_level_ = log_level; + } + + /** + * Return the current level of event tracer debug logging. + */ + EventTracerDebugLogLevel event_tracer_debug_level() { + return event_tracer_debug_level_; + } + + /** + * Set the level of event tracer profiling that is desired. + */ + void set_event_tracer_profiling_level( + EventTracerProfilingLevel profiling_level) { + event_tracer_profiling_level_ = profiling_level; + } + + /** + * Return the current level of event tracer profiling. + */ + EventTracerProfilingLevel event_tracer_profiling_level() { + return event_tracer_profiling_level_; + } + + /** + * Return the current status of intermediate outputs logging mode. + */ + bool intermediate_outputs_logging_status() { + return log_intermediate_tensors_; + } + + /** + * Get the current chain id. + * + * @return Current chain id. + */ + ChainID current_chain_id() { + return chain_id_; + } + + /** + * Get the current debug handle. + * + * @return Current debug handle. + */ + DebugHandle current_debug_handle() { + return debug_handle_; + } + + virtual ~EventTracer() {} + + protected: + ChainID chain_id_ = kUnsetChainId; + DebugHandle debug_handle_ = kUnsetDebugHandle; + bool event_tracer_enable_debugging_ = false; + bool log_intermediate_tensors_ = false; + int bundled_input_index_ = kUnsetBundledInputIndex; + EventTracerDebugLogLevel event_tracer_debug_level_ = + EventTracerDebugLogLevel::kNoLogging; + EventTracerProfilingLevel event_tracer_profiling_level_ = + EventTracerProfilingLevel::kProfileAllEvents; +}; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::AllocatorID; +using ::executorch::runtime::ChainID; +using ::executorch::runtime::DebugHandle; +using ::executorch::runtime::DelegateDebugIdType; +using ::executorch::runtime::DelegateDebugIntId; +using ::executorch::runtime::EventTracer; +using ::executorch::runtime::EventTracerDebugLogLevel; +using ::executorch::runtime::EventTracerEntry; +using ::executorch::runtime::kUnsetBundledInputIndex; +using ::executorch::runtime::kUnsetChainId; +using ::executorch::runtime::kUnsetDebugHandle; +using ::executorch::runtime::kUnsetDelegateDebugIntId; +using ::executorch::runtime::LoggedEValueType; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/event_tracer_hooks.h b/include/executorch/runtime/core/event_tracer_hooks.h new file mode 100644 index 0000000..cd74b44 --- /dev/null +++ b/include/executorch/runtime/core/event_tracer_hooks.h @@ -0,0 +1,340 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +/** + * @file + * + * This file contains the hooks that are inserted across various parts of the + * core runtime code to call into the EventTracer class for logging of profiling + * and debugging events. Any calls made to the EventTracer from the runtime must + * be made via these hooks. + * Users shouldn't directly add these hooks in their code and it's meant only + * for usage in ExecuTorch internal code. + * + * The benefit of defining these hooks is that we can easily control whether or + * not we want to compile in the EventTracer code based on the status of the + * ET_EVENT_TRACER_ENABLED flag. + * + * TODO(dbort): Make this a private header of runtime/executor. It only contains + * runtime-internal functions and should not be part of the public set of + * headers. + */ + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +namespace internal { + +/** + * This class enables scope based profiling where needed using RAII for + * operators only. If operator profiling is disabled then this class is a no-op. + */ +class EventTracerProfileOpScope final { + public: + EventTracerProfileOpScope(EventTracer* event_tracer, const char* name) { +#ifdef ET_EVENT_TRACER_ENABLED + event_tracer_ = event_tracer; + if (event_tracer_ == nullptr) { + return; + } + if (event_tracer_->event_tracer_profiling_level() > + executorch::runtime::EventTracerProfilingLevel::kProfileMethodOnly) { + event_entry_ = event_tracer->start_profiling(name); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)name; +#endif + } + + ~EventTracerProfileOpScope() { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer_ == nullptr) { + return; + } + if (event_tracer_->event_tracer_profiling_level() > + executorch::runtime::EventTracerProfilingLevel::kProfileMethodOnly) { + event_tracer_->end_profiling(event_entry_); + } +#endif + } + + private: +#ifdef ET_EVENT_TRACER_ENABLED + EventTracer* event_tracer_; + EventTracerEntry event_entry_; +#endif +}; + +using EventTracerProfileScope = EventTracerProfileOpScope; + +/** + * This class enables scope based profiling where needed using RAII. + * Profiling will be started when the object is created and will end + * when the object goes out of scope. This is specifically intended to + * be used for profiling methods in the runtime. + */ +class EventTracerProfileMethodScope final { + public: + EventTracerProfileMethodScope(EventTracer* event_tracer, const char* name) { +#ifdef ET_EVENT_TRACER_ENABLED + event_tracer_ = event_tracer; + if (event_tracer_ == nullptr) { + return; + } + event_entry_ = event_tracer->start_profiling(name); +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)name; +#endif + } + + ~EventTracerProfileMethodScope() { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer_ == nullptr) { + return; + } + event_tracer_->end_profiling(event_entry_); +#endif + } + + private: +#ifdef ET_EVENT_TRACER_ENABLED + EventTracer* event_tracer_; + EventTracerEntry event_entry_; +#endif +}; + +/** + * This class helps us set and then clear out the chain id and debug handle + * values stored in the event tracer class using RAII. This is typically called + * in the executor loop before entering the codegen layer to configure the chain + * id and debug handle of the current instruction being executed. + * After we return from the kernel execution we can then reset the chain id and + * debug handle to defaults when this object goes out of scope. + */ +class EventTracerProfileInstructionScope final { + public: + EventTracerProfileInstructionScope( + EventTracer* event_tracer, + ChainID chain_idx, + DebugHandle debug_handle) { +#ifdef ET_EVENT_TRACER_ENABLED + event_tracer_ = event_tracer; + if (event_tracer_ == nullptr) { + return; + } + event_tracer_->set_chain_debug_handle(chain_idx, debug_handle); +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)chain_idx; + (void)debug_handle; +#endif + } + + ~EventTracerProfileInstructionScope() { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer_ == nullptr) { + return; + } + event_tracer_->set_chain_debug_handle(kUnsetChainId, kUnsetDebugHandle); +#endif + } + + private: +#ifdef ET_EVENT_TRACER_ENABLED + EventTracer* event_tracer_; +#endif +}; + +inline bool event_tracer_enabled() { +#ifdef ET_EVENT_TRACER_ENABLED + return true; +#else //! ET_EVENT_TRACER_ENABLED + return false; +#endif +} +/** + * Create a new event block with the specified name. Any events logged + * after this will be associated with this new event block. + */ +inline void event_tracer_create_event_block( + EventTracer* event_tracer, + char const* name) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + event_tracer->create_event_block(name); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)name; +#endif +} + +/** + * Explicitly mark the beginning of a new profiling event. This returns + * an instance of an EventTracerEntry object that the user needs to keep + * around and pass into the corresponding event_tracer_end_profiling_event + * call. + */ +inline EventTracerEntry event_tracer_begin_profiling_event( + EventTracer* event_tracer, + char const* name) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + return event_tracer->start_profiling(name); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)name; +#endif + // There is no active tracer; this value will be ignored. + return EventTracerEntry(); +} + +/** + * Mark the end of a profiling event passing in the entry token + * returned by a previous call to ET_EVENT_TRACER_BEGIN_PROFILING_EVENT. + */ +inline void event_tracer_end_profiling_event( + EventTracer* event_tracer, + EventTracerEntry event) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + event_tracer->end_profiling(event); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)event; +#endif +} + +/** + * Start the tracking of the allocator represented by this name and returns + * an AllocatorID that will be used to track all subsequent allocations done by + * this allocator. + */ +inline AllocatorID event_tracer_track_allocator( + EventTracer* event_tracer, + const char* name) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + return event_tracer->track_allocator(name); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)name; +#endif + // There is no active tracer; this value will be ignored. + return 0; +} + +/// Log the allocation event done via the allocator represented by id. +inline void event_tracer_track_allocation( + EventTracer* event_tracer, + AllocatorID id, + size_t size) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + event_tracer->track_allocation(id, size); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)id; + (void)size; +#endif +} + +/// Log an intermediate value. +inline void event_tracer_log_evalue(EventTracer* event_tracer, EValue& evalue) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + if (event_tracer->event_tracer_debug_level() >= + EventTracerDebugLogLevel::kIntermediateOutputs) { + event_tracer->log_evalue(evalue, LoggedEValueType::kIntermediateOutput); + } + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)evalue; +#endif +} + +/// Log a program output. +inline void event_tracer_log_evalue_output( + EventTracer* event_tracer, + const EValue& evalue) { +#ifdef ET_EVENT_TRACER_ENABLED + /* + * If debugging via event tracer is enabled but intermediate output logging is + * disabled then we want to only log the outputs. + */ + if (event_tracer) { + if (event_tracer->event_tracer_debug_level() >= + EventTracerDebugLogLevel::kProgramOutputs) { + event_tracer->log_evalue(evalue, LoggedEValueType::kProgramOutput); + } + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)evalue; +#endif +} + +// Set the bundled input index of the current bundled input being used by the +// method. +inline void event_tracer_set_bundled_input_index( + EventTracer* event_tracer, + int bundled_input_index) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + event_tracer->set_bundled_input_index(bundled_input_index); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer; + (void)bundled_input_index; +#endif +} + +} // namespace internal +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +namespace internal { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::internal:: + event_tracer_begin_profiling_event; +using ::executorch::ET_RUNTIME_NAMESPACE::internal:: + event_tracer_create_event_block; +using ::executorch::ET_RUNTIME_NAMESPACE::internal:: + event_tracer_end_profiling_event; +using ::executorch::ET_RUNTIME_NAMESPACE::internal::event_tracer_log_evalue; +using ::executorch::ET_RUNTIME_NAMESPACE::internal:: + event_tracer_log_evalue_output; +using ::executorch::ET_RUNTIME_NAMESPACE::internal:: + event_tracer_set_bundled_input_index; +using ::executorch::ET_RUNTIME_NAMESPACE::internal:: + event_tracer_track_allocation; +using ::executorch::ET_RUNTIME_NAMESPACE::internal:: + event_tracer_track_allocator; +using ::executorch::ET_RUNTIME_NAMESPACE::internal:: + EventTracerProfileInstructionScope; +using ::executorch::ET_RUNTIME_NAMESPACE::internal:: + EventTracerProfileMethodScope; +using ::executorch::ET_RUNTIME_NAMESPACE::internal::EventTracerProfileOpScope; +using ::executorch::ET_RUNTIME_NAMESPACE::internal::EventTracerProfileScope; + +} // namespace internal +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/event_tracer_hooks_delegate.h b/include/executorch/runtime/core/event_tracer_hooks_delegate.h new file mode 100644 index 0000000..b2369fc --- /dev/null +++ b/include/executorch/runtime/core/event_tracer_hooks_delegate.h @@ -0,0 +1,204 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +/** + * @file + * + * This file contains the hooks that can be used by runtime delegate backend + * authors to log profiling and debugging events from backend code. In order to + * use these hooks delegate authors would have needed to generate a delegate + * debug identifier mapping using the DelegateMappingBuilder library present in + * executorch/exir/backend/utils.py. The delegate debug identifiers generated by + * that library are the ones that need to be passed to these hooks to log + * events. Using any other identifiers will cause post-processing of the events + * data to not properly link back to the nodes in the original lowered graph. + * + * The benefit of defining these hooks is that we can easily control whether or + * not we want to compile in the EventTracer code based on the status of the + * ET_EVENT_TRACER_ENABLED flag. + */ + +namespace executorch { +namespace runtime { + +/** + * Start the profiling of a delegate event. Similar to start_profiling it will + * return an instance of EventTracerEntry that contains the details of this + * event. Can be left in production code as these hooks compile conditionally. + * + * @param[in] event_tracer The event tracer instance that is doing the logging. + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must be copied over + * into internal memory during this call. + * @param[in] delegate_debug_id The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then kUnsetDebugHandle should be passed in here. + */ +inline EventTracerEntry event_tracer_start_profiling_delegate( + EventTracer* event_tracer, + const char* name, + DebugHandle delegate_debug_id) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + return event_tracer->start_profiling_delegate(name, delegate_debug_id); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)name; + (void)delegate_debug_id; +#endif + // There is no active tracer; this value will be ignored. + return EventTracerEntry(); +} + +/** + * Signal the end of the delegate profiling event contained in + * event_tracer_entry. Users also have the option to log some some free-from + * string based metadata along with this. Can be left in production code as + * these hooks compile conditionally. + * + * @param[in] event_tracer The event tracer instance that is doing the logging. + * @param[in] event_tracer_entry The EventTracerEntry returned by a call to + * start_profiling_delegate(). + * @param[in] metadata Optional data relevant to the execution that the user + * wants to log along with this event. Pointer to metadata doesn't need to be + * valid after the call to this function. The contents and format of the data + * are transparent to the event tracer. It will just pipe along the data and + * make it available for the user again in the post-processing stage. + * @param[in] metadata_len Length of the metadata buffer. + */ +inline void event_tracer_end_profiling_delegate( + EventTracer* event_tracer, + EventTracerEntry event_tracer_entry, + const void* metadata = nullptr, + size_t metadata_len = 0) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + event_tracer->end_profiling_delegate( + event_tracer_entry, metadata, metadata_len); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)event_tracer_entry; + (void)metadata; + (void)metadata_len; +#endif +} + +/** + * Some delegates get access to the profiling details only after the complete + * graph has been executed. This interface is to support such use cases. It + * can be called in a loop etc. to log any number of profiling events that are + * part of this delegate. Can be left in production code as these hooks + * compile conditionally. + * + * @param[in] event_tracer The event tracer instance that is doing the logging. + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must + * be copied over into internal memory during this call. + * @param[in] delegate_debug_id The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then -1 should be passed in here. + * @param[in] start_time The timestamp when the delegate event started. + * @param[in] end_time The timestamp when the delegate event finished. + * @param[in] metadata Optional data relevant to the execution that the user + * wants to log along with this event. Pointer to metadata doesn't need to be + * valid after the call to this function. The contents and format of the data + * are transparent to the event tracer. It will just pipe along the data and + * make it available for the user again in the post-processing stage. + * @param[in] metadata_len Length of the metadata buffer. + */ +inline void event_tracer_log_profiling_delegate( + EventTracer* event_tracer, + const char* name, + DebugHandle delegate_debug_id, + et_timestamp_t start_time, + et_timestamp_t end_time, + const void* metadata = nullptr, + size_t metadata_len = 0) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + event_tracer->log_profiling_delegate( + name, delegate_debug_id, start_time, end_time, metadata, metadata_len); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)name; + (void)delegate_debug_id; + (void)start_time; + (void)end_time; + (void)metadata; + (void)metadata_len; +#endif +} + +/** + * This templated interfaces can be called in a loop etc. to log any number of + * debug events that are part of this delegate. Supported values types are int, + * bool, double, tensor and array of tensors. Can be left in production code as + * these hooks compile conditionally. + * + * @param[in] event_tracer The event tracer instance that is doing the logging. + * @param[in] name Human readable name for the delegate event. This name has + * to be the same name that was passed in during the Debug delegate mapping + * generation in the export/ahead-of-time process. If indices and not names + * are used by this delegate to identify ops executed in the backend then + * nullptr can be passed in. Users calling this interface do not need to keep + * the memory pointed to by this pointer around. The string must + * be copied over into internal memory during this call. + * @param[in] delegate_debug_id The id of the delegate event. If string + * based names are used by this delegate to identify ops executed in the + * backend then -1 should be passed in here. + * @param[in] output The output to be logged. + */ +template +inline void event_tracer_log_output_delegate( + EventTracer* event_tracer, + const char* name, + DebugHandle delegate_debug_id, + const T& output) { +#ifdef ET_EVENT_TRACER_ENABLED + if (event_tracer) { + static_assert( + std::is_same::value || std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same>::value, + "Unsupported type for intermediate output"); + event_tracer->log_intermediate_output_delegate( + name, delegate_debug_id, output); + } +#else //! ET_EVENT_TRACER_ENABLED + (void)name; + (void)delegate_debug_id; + (void)output; +#endif +} + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::event_tracer_end_profiling_delegate; +using ::executorch::runtime::event_tracer_log_output_delegate; +using ::executorch::runtime::event_tracer_log_profiling_delegate; +using ::executorch::runtime::event_tracer_start_profiling_delegate; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/exec_aten/exec_aten.h b/include/executorch/runtime/core/exec_aten/exec_aten.h new file mode 100644 index 0000000..ac4fb9a --- /dev/null +++ b/include/executorch/runtime/core/exec_aten/exec_aten.h @@ -0,0 +1,208 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include + +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include +#ifdef USE_ATEN_LIB +#include // @manual +#include +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include +#else // use executor +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual +#include // @manual + +#endif + +/** + * This hack is for separating out ATen mode vs non-ATen mode. In ATen mode, + * we use the ATen types directly. In non-ATen mode, we use the portable types. + * To avoid duplicate symbols and/or duplicate operator registration, when a + * user depends on both the ATen mode and non-ATen mode versions of the + * ExecuTorch library. + */ +#ifndef ET_RUNTIME_NAMESPACE +#if defined(USE_ATEN_LIB) +#define ET_RUNTIME_NAMESPACE runtime::aten +#else +#define ET_RUNTIME_NAMESPACE runtime +#endif +#endif + +namespace executorch { +namespace aten { + +using TensorShapeDynamism = executorch::runtime::TensorShapeDynamism; + +using std::nullopt; +using std::nullopt_t; +using std::optional; +using std::string_view; + +#ifdef USE_ATEN_LIB + +using Tensor = at::Tensor; +using TensorList = at::TensorList; +using TensorImpl = at::TensorImpl; +template +using ArrayRef = c10::ArrayRef; +using ScalarType = at::ScalarType; +using Scalar = c10::Scalar; +using MemoryFormat = c10::MemoryFormat; +using SizesType = int64_t; +using DimOrderType = uint8_t; +using StridesType = int64_t; +using Device = c10::Device; +using DeviceType = c10::DeviceType; +using Layout = c10::Layout; + +// Custom types that map to ScalarType +using Half = c10::Half; +template +using complex = c10::complex; +using qint8 = c10::qint8; +using quint8 = c10::quint8; +using qint32 = c10::qint32; +using BFloat16 = c10::BFloat16; +using quint4x2 = c10::quint4x2; +using quint2x4 = c10::quint2x4; +using IntArrayRef = at::IntArrayRef; + +template +using OptionalArrayRef = c10::OptionalArrayRef; +using OptionalIntArrayRef = OptionalArrayRef; + +inline ssize_t compute_numel(const SizesType* sizes, ssize_t dim) { + return static_cast( + c10::multiply_integers(c10::ArrayRef(sizes, dim))); +} + +inline ::executorch::runtime::Result safe_numel( + const SizesType* sizes, + ssize_t dim) { + ET_CHECK_OR_RETURN_ERROR( + dim == 0 || sizes != nullptr, + InvalidArgument, + "Sizes must be provided for non-scalar tensors"); + ssize_t numel = 1; + for (ssize_t i = 0; i < dim; i++) { + ET_CHECK_OR_RETURN_ERROR( + sizes[i] >= 0, + InvalidArgument, + "Size must be non-negative, got %zd at dimension %zd", + static_cast(sizes[i]), + i); + ssize_t next_numel; + ET_CHECK_OR_RETURN_ERROR( + !c10::mul_overflows(numel, static_cast(sizes[i]), &next_numel), + InvalidArgument, + "Overflow computing numel at dimension %zd", + i); + numel = next_numel; + } + return numel; +} + +#undef ET_PRI_TENSOR_SIZE +#define ET_PRI_TENSOR_SIZE PRId64 + +#undef ET_PRI_TENSOR_DIM +#define ET_PRI_TENSOR_DIM PRId64 + +#undef ET_PRI_TENSOR_NUMEL +#define ET_PRI_TENSOR_NUMEL PRId64 + +#undef ET_PRI_SIZES_AND_STRIDES +#define ET_PRI_SIZES_AND_STRIDES PRId64 + +#else // Use executor types + +using Tensor = torch::executor::Tensor; +using TensorImpl = torch::executor::TensorImpl; +template +using ArrayRef = torch::executor::ArrayRef; +using ScalarType = torch::executor::ScalarType; +using TensorList = ArrayRef; +using Scalar = torch::executor::Scalar; +using MemoryFormat = torch::executor::MemoryFormat; +using SizesType = torch::executor::Tensor::SizesType; +using DimOrderType = torch::executor::Tensor::DimOrderType; +using StridesType = torch::executor::Tensor::StridesType; +using Device = torch::executor::Device; +using DeviceType = torch::executor::DeviceType; +using Layout = torch::executor::Layout; + +// Custom types that map to ScalarType +using Half = torch::executor::Half; +template +using complex = torch::executor::complex; +using qint8 = torch::executor::qint8; +using quint8 = torch::executor::quint8; +using qint32 = torch::executor::qint32; +using BFloat16 = torch::executor::BFloat16; +using quint4x2 = torch::executor::quint4x2; +using quint2x4 = torch::executor::quint2x4; + +using IntArrayRef = torch::executor::IntArrayRef; + +template +using OptionalArrayRef = std::optional>; +using OptionalIntArrayRef = OptionalArrayRef; + +using torch::executor::compute_numel; +using torch::executor::safe_numel; + +#endif // Use ExecuTorch types + +} // namespace aten +} // namespace executorch + +// DEPRECATED: The exec_aten:: namespace is deprecated. Use executorch::aten:: +// instead. +namespace exec_aten = executorch::aten; + +namespace torch { +namespace executor { +using TensorList = ::executorch::aten::TensorList; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/exec_aten/testing_util/tensor_factory.h b/include/executorch/runtime/core/exec_aten/testing_util/tensor_factory.h new file mode 100644 index 0000000..79cfd59 --- /dev/null +++ b/include/executorch/runtime/core/exec_aten/testing_util/tensor_factory.h @@ -0,0 +1,1140 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +#ifdef USE_ATEN_LIB +#include +#else // !USE_ATEN_LIB +#include +#include +#include +#endif // !USE_ATEN_LIB + +namespace executorch { +namespace runtime { +namespace testing { + +namespace internal { + +/** + * Returns the number of elements in the tensor, given the dimension + * sizes, assuming contiguous data. + */ +inline size_t sizes_to_numel(const std::vector& sizes) { + size_t n = 1; + for (auto s : sizes) { + n *= s; + } + return n; +} + +/** + * Check if given strides is legal under given sizes. In the `make` function, + * the `strides` shall ensure: + * - a. strides.size() == sizes.size() + * - b. all strides are positive. + * - c. All underlying data be accessed. + * - d. All legal indexes can access an underlying data. + * - e. No two indexes access a same data. + * - f. No out of bounds data can be accessed. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] strides The desired strides for creating new tensor. + * @return The strides is legal or not + */ + +inline bool check_strides( + const std::vector sizes, + const std::vector strides) { + if (sizes.size() != strides.size()) { + // The length of stride vector shall equal to size vector. + return false; + } + + if (strides.size() == 0) { + // Both sizes and strides are empty vector. Legal! + return true; + } + + // Check if input non-empty strides is legal. The defination of legal is in + // the comment above function. To check it, we first reformat the strides into + // contiguous style, in where the strides should be sorted from high to low. + // Then rearrange the size based on same transformation. After that, we can + // check if strides[i] == strides[i + 1] * sizes[i + 1] for all i in + // [0, sizes.size() - 1) and strides[sizes.size() - 1] == 1 + + // Get the mapping between current strides and sorted strides (from high to + // low, if equal then check if correspond size is 1 or 0 in same dimension) + // e.g. a = tensor(3, 2, 1).permute(2, 1, 0), a.size() == (1, 2, 3) and + // a.strides == (1, 1, 2). We want to sort create a mapping to make the + // sorted_stride as (2, 1, 1) while sorted_size == (3, 2, 1) + std::vector sorted_idx(sizes.size()); + for (const auto i : c10::irange(sizes.size())) { + sorted_idx[i] = i; + } + std::sort( + sorted_idx.begin(), + sorted_idx.end(), + [&](const int32_t& a, const int32_t& b) { + if (strides[a] != strides[b]) { + return strides[a] > strides[b]; + } else { + // When strides equal to each other, put the index whose + // coresponding size equal to 0 or 1 to the right. Update the rule to + // the following comparsion to circumvent strict weak ordering. + return (sizes[a] ? sizes[a] : 1) > (sizes[b] ? sizes[b] : 1); + } + }); + + // Use the mapping to rearrange the sizes and strides + std::vector sorted_sizes(sizes.size()); + std::vector sorted_strides(sizes.size()); + for (const auto i : c10::irange(sizes.size())) { + sorted_sizes[i] = sizes[sorted_idx[i]] == 0 ? 1 : sizes[sorted_idx[i]]; + sorted_strides[i] = strides[sorted_idx[i]]; + } + + // All strides should be positive. We have sorted it mainly based on strides, + // so sorted_strides[-1] has lowest value. + if (sorted_strides[strides.size() - 1] <= 0) { + return false; + } + + // Check if strides is legal + bool legal = sorted_strides[strides.size() - 1] == 1; + for (size_t i = 0; i < strides.size() - 1 && legal; i++) { + legal = legal && + (sorted_strides[i] == sorted_strides[i + 1] * sorted_sizes[i + 1]); + } + + return legal; +} + +/** + * Check that a given dim order array is valid. A dim order array is valid if + * each value from 0 to sizes.size() - 1 appears exactly once in the dim_order + * array. + */ +inline bool check_dim_order( + const std::vector& sizes, + const std::vector& dim_order) { + if (sizes.size() != dim_order.size()) { + return false; + } + size_t gauss_sum = 0; + std::vector count(dim_order.size(), 0); + for (const auto i : c10::irange(dim_order.size())) { + if (dim_order[i] >= sizes.size()) { + return false; + } + gauss_sum += static_cast(dim_order[i]) + 1; + } + // Use the gaussian sum to verify each dim appears exactly once + size_t expected_sum = (sizes.size() * (sizes.size() + 1)) / 2; + if (gauss_sum != expected_sum) { + return false; + } + + return true; +} + +inline std::vector strides_from_dim_order( + const std::vector& sizes, + const std::vector& dim_order) { + bool legal = check_dim_order(sizes, dim_order); + ET_CHECK_MSG(legal, "The input dim_order variable is illegal."); + + size_t ndim = sizes.size(); + std::vector strides(ndim); + strides[dim_order[ndim - 1]] = 1; + for (int i = ndim - 2; i >= 0; --i) { + uint8_t cur_dim = dim_order[i]; + uint8_t next_dim = dim_order[i + 1]; + strides[cur_dim] = (!sizes[next_dim]) ? strides[next_dim] + : strides[next_dim] * sizes[next_dim]; + } + return strides; +} + +inline std::vector channels_last_dim_order(size_t dims) { + ET_CHECK_MSG( + dims >= 4 && dims <= 5, + "Channels last dim order only valid for 4-dim and 5-dim tensors!"); + + std::vector dim_order(dims); + // Channels is always assigned to dim 1 + dim_order[dims - 1] = 1; + + dim_order[0] = 0; + int d = 1; + while (d < dims - 1) { + dim_order[d] = d + 1; + d++; + } + return dim_order; +} + +} // namespace internal + +#ifdef USE_ATEN_LIB + +// Note that this USE_ATEN_LIB section uses ATen-specific namespaces instead of +// exec_aten because we know that we're working with ATen, and many of these +// names aren't mapped into executorch::aten::. + +namespace internal { + +// This wrapper lets us override the C type associated with some ScalarType +// values while using the defaults for everything else. +template +struct ScalarTypeToCppTypeWrapper { + using ctype = typename c10::impl::ScalarTypeToCPPTypeT; +}; + +// Use a C type of `uint8_t` instead of `bool`. The C type will be used to +// declare a `std::vector`, and `std::vector` is often optimized to +// store a single bit per entry instead of using an array of separate `bool` +// elements. Since the tensor data will point into the vector, it needs to use +// one byte per element. +template <> +struct ScalarTypeToCppTypeWrapper { + using ctype = uint8_t; +}; + +} // namespace internal + +template +class TensorFactory { + public: + /* + * The C types that backs the associated DTYPE. E.g., `float` for + * `ScalarType::Float`. + */ + + /** + * Used for the vector provided to the factory functions. May differ + * from the type usually associate with the ScalarType. + * + * Used for the vector<> parameters passed to the factory functions. + */ + using ctype = typename internal::ScalarTypeToCppTypeWrapper::ctype; + + /** + * The official C type for the scalar type. Used when accessing elements + * of a constructed Tensor. + */ + using true_ctype = typename c10::impl::ScalarTypeToCPPTypeT; + + TensorFactory() = default; + + /** + * Returns a new Tensor with the specified shape, data and stride. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] data The data that the Tensor should be initialized with. The + * size of this vector must be equal to the product of the elements of + * `sizes`. + * @param[in] strides The strides for each dimensions of the Tensor. If empty + * or not specificed, the function will return a contiguous tensor based + * on data and size. If not, the strides shall follow the rules: + * - a. strides.size() == sizes.size(). + * - b. all strides are positive. + * - c. All underlying data be accessed. + * - d. All legal indexes can access an underlying data. + * - e. No two indexes access a same data. + * - f. No out of bounds data can be accessed. + * + * @return A new Tensor with the specified shape and data. + */ + at::Tensor make( + const std::vector& sizes, + const std::vector& data, + const std::vector strides = {}, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + auto expected_numel = internal::sizes_to_numel(sizes); + ET_CHECK_MSG( + expected_numel == data.size(), + "Number of data elements %zd " + "does not match expected number of elements %zd", + data.size(), + expected_numel); + + at::Tensor t; + if (strides.empty()) { + t = zeros(sizes); + } else { + bool legal = internal::check_strides(sizes, strides); + ET_CHECK_MSG(legal, "The input strides variable is illegal."); + + t = empty_strided(sizes, strides); + } + if (t.nbytes() > 0) { + std::transform( + data.begin(), data.end(), t.template data(), [](auto x) { + return static_cast(x); + }); + } + return t; + } + + /** + * Returns a new Tensor with the specified shape, data and dim order. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] data The data that the Tensor should be initialized with. The + * size of this vector must be equal to the product of the elements of + * `sizes`. + * @param[in] dim_order The dim order describing how tensor memory is laid + * out. If empty or not specificed, the function will use a contiguous dim + * order of {0, 1, 2, 3, ...} + * + * @return A new Tensor with the specified shape and data. + */ + at::Tensor make_with_dimorder( + const std::vector& sizes, + const std::vector& data, + const std::vector dim_order = {}, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + auto expected_numel = internal::sizes_to_numel(sizes); + ET_CHECK_MSG( + expected_numel == data.size(), + "Number of data elements %zd " + "does not match expected number of elements %zd", + data.size(), + expected_numel); + + at::Tensor t; + if (dim_order.empty()) { + t = zeros(sizes); + } else { + auto strides = internal::strides_from_dim_order(sizes, dim_order); + t = empty_strided(sizes, strides); + } + if (t.nbytes() > 0) { + std::transform( + data.begin(), data.end(), t.template data(), [](auto x) { + return static_cast(x); + }); + } + return t; + } + + /** + * Returns a new Tensor with the specified shape and data in channels last + * memory layout. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] data The data that the Tensor should be initialized with. The + * size of this vector must be equal to the product of the elements of + * `sizes`. + * + * @return A new Tensor with the specified shape and data. + */ + at::Tensor make_channels_last( + const std::vector& sizes, + const std::vector& data, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + return make_with_dimorder( + sizes, data, internal::channels_last_dim_order(sizes.size()), dynamism); + } + + /** + * Given data in contiguous memory format, returns a new Tensor with the + * specified shape and the same data but in channels last memory format. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] data The data in contiguous memory format that the Tensor should + * be initialized with. The size of this vector must be equal to the product + * of the elements of `sizes`. + * + * @return A new Tensor with the specified shape and data in channls last + * memory format. + */ + at::Tensor channels_last_like( + const at::Tensor& input, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + ET_CHECK_MSG( + input.sizes().size() == 4 || input.sizes().size() == 5, + "Only 4D and 5D tensors can be channels last"); + + const std::vector sizes( + input.sizes().begin(), input.sizes().end()); + + std::vector contiguous_dim_order(sizes.size()); + for (uint8_t i = 0; i < sizes.size(); i++) { + contiguous_dim_order[i] = i; + } + std::vector contiguous_strides = + internal::strides_from_dim_order(sizes, contiguous_dim_order); + + for (const auto i : c10::irange(input.dim())) { + ET_CHECK_MSG( + input.strides()[i] == contiguous_strides[i], + "Input tensor is not contiguous"); + } + + int32_t N = sizes[0]; + int32_t C = sizes[1]; + // Depth and height are adjacent in both layouts, so a 5-D tensor is + // permuted like a 4-D one whose height covers both. + int32_t H = sizes.size() == 5 ? sizes[2] * sizes[3] : sizes[2]; + int32_t W = sizes.back(); + + std::vector contiguous_data( + input.data_ptr(), input.data_ptr() + input.numel()); + std::vector channels_last_data( + N * C * H * W); // Create a new blob with the same total size to contain + // channels_last data + for (const auto n : c10::irange(N)) { + for (const auto c : c10::irange(C)) { + for (const auto h : c10::irange(H)) { + for (const auto w : c10::irange(W)) { + // Calculate the index in the original blob + int32_t old_index = ((n * C + c) * H + h) * W + w; + // Calculate the index in the new blob + int32_t new_index = ((n * H + h) * W + w) * C + c; + // Copy the data + channels_last_data[new_index] = contiguous_data[old_index]; + } + } + } + } + + return make_with_dimorder( + sizes, + channels_last_data, + internal::channels_last_dim_order(sizes.size()), + dynamism); + } + + /** + * Returns a new Tensor with the specified shape, containing contiguous + * data will all elements set to `value`. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] value The value of all elements of the Tensor. + * @return A new Tensor with the specified shape. + */ + at::Tensor full( + const std::vector& sizes, + ctype value, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + auto sizes64 = vec_32_to_64(sizes); + return at::full(at::IntArrayRef(sizes64), value, at::dtype(DTYPE)); + } + + /** + * Returns a new Tensor with the specified shape, containing channels-last + * contiguous data will all elements set to `value`. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] value The value of all elements of the Tensor. + * @return A new Tensor with the specified shape. + */ + at::Tensor full_channels_last( + const std::vector& sizes, + ctype value, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + auto sizes64 = vec_32_to_64(sizes); + return at::full(at::IntArrayRef(sizes64), value, at::dtype(DTYPE)) + .to(at::MemoryFormat::ChannelsLast); + } + + /** + * Returns a new Tensor with the specified shape, containing channels-last + * contiguous data with all `0` elements. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @return A new Tensor with the specified shape. + */ + at::Tensor zeros( + const std::vector& sizes, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + auto sizes64 = vec_32_to_64(sizes); + return at::zeros(at::IntArrayRef(sizes64), at::dtype(DTYPE)); + } + + /** + * Returns a new Tensor with the specified shape, containing contiguous data + * with all `0` elements. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @return A new Tensor with the specified shape. + */ + at::Tensor zeros_channels_last( + const std::vector& sizes, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + auto sizes64 = vec_32_to_64(sizes); + return at::zeros(at::IntArrayRef(sizes64), at::dtype(DTYPE)) + .to(at::MemoryFormat::ChannelsLast); + } + + /** + * Returns a new Tensor with the specified shape, containing contiguous data + * with all `1` elements. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @return A new Tensor with the specified shape. + */ + at::Tensor ones( + const std::vector& sizes, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + auto sizes64 = vec_32_to_64(sizes); + return at::ones(at::IntArrayRef(sizes64), at::dtype(DTYPE)); + } + + /** + * Returns a new Tensor with the same shape as the input tensor, containing + * contiguous data with all `0` elements. + * + * @param[in] input The tensor that supplies the shape of the new Tensor. + * @return A new Tensor with the specified shape. + */ + at::Tensor zeros_like( + const at::Tensor& input, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + std::vector sizes64 = {input.sizes().begin(), input.sizes().end()}; + return at::full(at::IntArrayRef(sizes64), 0, at::dtype(DTYPE)); + } + + /** + * Returns a new Tensor with the same shape as the input tensor, containing + * contiguous data with all `1` elements. + * + * @param[in] input The tensor that supplies the shape of the new Tensor. + * @return A new Tensor with the specified shape. + */ + at::Tensor ones_like( + const at::Tensor& input, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + std::vector sizes64 = {input.sizes().begin(), input.sizes().end()}; + return at::full(at::IntArrayRef(sizes64), 1, at::dtype(DTYPE)); + } + + private: + /// Copies an int32_t vector into a new int64_t vector. + static std::vector vec_32_to_64(const std::vector& in) { + std::vector out{}; + out.reserve(in.size()); + for (auto i : in) { + out.push_back(i); + } + return out; + } + + /** + * Returns a new Tensor with the specified shape and stride. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] strides The strides for each dimensions of the Tensor + * @return A new Tensor with the specified shape and strides. + */ + at::Tensor empty_strided( + const std::vector& sizes, + const std::vector& strides, + ET_UNUSED TensorShapeDynamism dynamism = + TensorShapeDynamism::DYNAMIC_UNBOUND) { + auto sizes64 = vec_32_to_64(sizes); + return at::empty_strided( + sizes64, + strides, + DTYPE, + /*layout_opt=*/at::Layout::Strided, + /*device_opt=*/at::Device(at::DeviceType::CPU), + /*pin_memory_opt=*/false); + } +}; + +#else // !USE_ATEN_LIB + +namespace { +/* + * Dimension order represents how dimensions are laid out in memory, + * starting from the inner-most to the outer-most dimension. + * Thus, the conversion from strides is done by sorting the strides + * from larger to smaller since the dimension with the largest stride + * is the outer-most and the dimension with the smallest stride is the + inner-most. + * For example, tensor with sizes = (3, 5, 2) and strides = (5, 1, 15), implies + * dimension order of (2, 0, 1), because 2nd dimension has the biggest stride of + 15, + * followed by 0th dimension with stride of 5 and then innermost dimension being + the 1st + * dimension with size of 1. This order of (2, 0, 1) can be obtained + * by sorting strides from large to smaller. + + * When strides do not convey dimension order unambiguously, dimension order + * returned is dependent on stability of sort. We employ stable sort to preserve + * original order. Thus when strides = (4, 3, 1, 1) returned value is (0, 1, 2, + 3) + * Another example is: sizes = (1, 3, 1, 1) with strides = (3, 1, 3, 3), + returned + * value is (0, 2, 3, 1) +*/ +// copied from +// https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes +// TODO: Add assert for strides[i] != 0 because strides of 0 is really used, +// by pytorch/aten, to convey broadcasting dim. + +inline std::vector dim_order_from_stride( + const std::vector& v) { + std::vector indices(v.size()); + std::iota(indices.begin(), indices.end(), 0); + stable_sort(indices.begin(), indices.end(), [&v](size_t i1, size_t i2) { + return v[i1] > v[i2]; + }); + return indices; +} + +inline void validate_strides( + const std::vector& sizes, + const std::vector& strides) { + if (sizes.size() != strides.size()) { + ET_CHECK_MSG(false, "Stride and sizes are not equal in length"); + } + for (const auto& s : strides) { + if (s == 0) { + ET_CHECK_MSG(false, "Stride value of 0 is not supported"); + } + } + // No two dimensions can have same stride value + for (const auto i : c10::irange(strides.size())) { + for (int32_t j = i + 1; j < strides.size(); ++j) { + if ((sizes[i] == 0) || (sizes[j] == 0) || + ((sizes[i] == 1) || (sizes[j] == 1))) { + continue; + } + if ((strides[i] == strides[j])) { + ET_CHECK_MSG( + false, + "Stride value and size dont comply at index %d." + " strides[%d]: %d, strides[%d] = %d, sizes[%d] = %d, sizes[%d] = %d", + static_cast(i), + static_cast(i), + strides[i], + j, + strides[j], + static_cast(i), + sizes[i], + j, + sizes[j]); + } + } + } +} + +} // namespace + +// Note that this !USE_ATEN_LIB section uses ExecuTorch-specific namespaces +// instead of exec_aten to make it clear that we're dealing with ETensor, and +// because many of these names aren't mapped into executorch::aten::. + +namespace internal { + +// This wrapper lets us override the C type associated with some ScalarType +// values while using the defaults for everything else. +template +struct ScalarTypeToCppTypeWrapper { + using ctype = + typename ::executorch::runtime::ScalarTypeToCppType::type; +}; + +// Use a C type of `uint8_t` instead of `bool`. The C type will be used to +// declare a `std::vector`, and `std::vector` is often optimized to +// store a single bit per entry instead of using an array of separate `bool` +// elements. Since the tensor data will point into the vector, it needs to use +// one byte per element. +template <> +struct ScalarTypeToCppTypeWrapper { + using ctype = uint8_t; +}; + +// Use a C type of `uint16_t` instead of `Bits16` to simplify code reuse when +// testing multiple integer types. +template <> +struct ScalarTypeToCppTypeWrapper { + using ctype = uint16_t; +}; + +// Use a C type of `uint16_t` instead of `UInt16` to simplify code reuse when +// testing multiple integer types. +template <> +struct ScalarTypeToCppTypeWrapper { + using ctype = uint16_t; +}; + +// To allow implicit conversion between simple types to `ctype` +#define SPECIALIZE_ScalarTypeToCppTypeWrapper(CTYPE, DTYPE) \ + template <> \ + struct ScalarTypeToCppTypeWrapper { \ + using ctype = typename CTYPE::underlying; \ + }; + +ET_FORALL_QINT_TYPES(SPECIALIZE_ScalarTypeToCppTypeWrapper) + +#undef SPECIALIZE_ScalarTypeToCppTypeWrapper + +} // namespace internal + +/** + * A helper class for creating Tensors, simplifying memory management. + * + * NOTE: A given TensorFactory instance owns the memory pointed to by all + * Tensors that it creates, and must live longer than those Tensors. + * + * Example: + * @code{.cpp} + * // A factory instance will create Tensors of a single dtype. + * TensorFactory tf; + * + * // You can create more factories if you need tensors of multiple + * // dtypes. + * TensorFactory tf_float; + * + * // The factory will copy the vectors provided to it, letting callers provide + * // inline literals. + * Tensor t1 = tf.make( + * {2, 2}, // sizes + * {1, 2, 3, 4}); // data + * + * // There are helpers for creating Tensors with all 1 or 0 elements. + * Tensor z = tf.zeros({2, 2}); + * Tensor o = tf_float.ones({2, 2}); + * + * // Sometimes it's helpful to share parameters. + * std::vector sizes = {2, 2}; + * Tensor t3 = tf.make(sizes, {1, 2, 3, 4}); + * Tensor t4 = tf.ones(sizes); + * + * // But remember that the inputs are copied, so providing the same data vector + * // to two Tensors will not share the same underlying data. + * std::vector data = {1, 2, 3, 4}; + * Tensor t5 = tf.make(sizes, data); + * Tensor t6 = tf.make(sizes, data); + * t5.mutable_data_ptr()[0] = 99; + * EXPECT_NE(t5, t6); + * @endcode + * + * @tparam DTYPE The dtype of Tensors created by this factory, as a ScalarType + * value like `ScalarType::Int`. + */ +template +class TensorFactory { + public: + /** + * The C type that backs the associated DTYPE. E.g., `float` for + * `ScalarType::Float`. + */ + using ctype = typename internal::ScalarTypeToCppTypeWrapper::ctype; + + /** + * The official C type for the scalar type. Used when accessing elements + * of a constructed Tensor. + */ + using true_ctype = + typename executorch::runtime::ScalarTypeToCppType::type; + + TensorFactory() = default; + + /** + * Returns a new Tensor with the specified shape, data and stride. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] data The data that the Tensor should be initialized with. The + * size of this vector must be equal to the product of the elements of + * `sizes`. + * @param[in] strides The strides for each dimensions of the Tensor. If empty + * or not specificed, the function will return a contiguous tensor based + * on data and size. If not, the strides shall follow the rules: + * - a. strides.size() == sizes.size(). + * - b. all strides are positive. + * - c. All underlying data be accessed. + * - d. All legal indexes can access an underlying data. + * - e. No two indexes access a same data. + * - f. No out of bounds data can be accessed. + * + * @return A new Tensor with the specified shape and data. + */ + torch::executor::Tensor make( + const std::vector& sizes, + const std::vector& data, + const std::vector strides = {}, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + std::vector default_strides; + // Generate strides from the tensor dimensions, assuming contiguous data if + // given strides is empty. + if (!sizes.empty() && strides.empty()) { + default_strides.resize(sizes.size(), 1); + for (size_t i = sizes.size() - 1; i > 0; --i) { + // For sizes[i] == 0, treat it as 1 to be consistent with core Pytorch + auto sizes_i = sizes[i] ? sizes[i] : 1; + default_strides[i - 1] = default_strides[i] * sizes_i; + } + } + auto& actual_strides = default_strides.empty() ? strides : default_strides; + validate_strides(sizes, actual_strides); + auto dim_order = dim_order_from_stride(actual_strides); + + auto expected_numel = internal::sizes_to_numel(sizes); + ET_CHECK_MSG( + expected_numel == data.size(), + "Number of data elements %zd " + "does not match expected number of elements %zd", + data.size(), + expected_numel); + + bool legal = internal::check_strides(sizes, actual_strides); + ET_CHECK_MSG(legal, "The input strides variable is illegal."); + + memory_.emplace_back(std::make_unique( + sizes, data, dim_order, actual_strides, dynamism)); + return torch::executor::Tensor(&memory_.back()->impl_); + } + + /** + * Returns a new Tensor with the specified shape, data and dim order. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] data The data that the Tensor should be initialized with. The + * size of this vector must be equal to the product of the elements of + * `sizes`. + * @param[in] dim_order The dim order describing how tensor memory is laid + * out. If empty or not specificed, the function will use a contiguous dim + * order of {0, 1, 2, 3, ...} + * + * @return A new Tensor with the specified shape and data. + */ + torch::executor::Tensor make_with_dimorder( + const std::vector& sizes, + const std::vector& data, + const std::vector dim_order = {}, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + std::vector default_dim_order; + // Generate strides from the tensor dimensions, assuming contiguous data if + // given strides is empty. + if (!sizes.empty() && dim_order.empty()) { + default_dim_order.resize(sizes.size(), 1); + for (const auto i : c10::irange(sizes.size())) { + default_dim_order[i] = i; + } + } + auto& actual_dim_order = + default_dim_order.empty() ? dim_order : default_dim_order; + + auto strides = internal::strides_from_dim_order(sizes, actual_dim_order); + + auto expected_numel = internal::sizes_to_numel(sizes); + ET_CHECK_MSG( + expected_numel == data.size(), + "Number of data elements %zd " + "does not match expected number of elements %zd", + data.size(), + expected_numel); + + memory_.emplace_back(std::make_unique( + sizes, data, actual_dim_order, strides, dynamism)); + return torch::executor::Tensor(&memory_.back()->impl_); + } + + /** + * Returns a new Tensor with the specified shape and data in channels last + * memory format. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] data The data that the Tensor should be initialized with. The + * size of this vector must be equal to the product of the elements of + * `sizes`. + * + * @return A new Tensor with the specified shape and data. + */ + torch::executor::Tensor make_channels_last( + const std::vector& sizes, + const std::vector& data, + const std::vector dim_order = {}, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + return make_with_dimorder( + sizes, data, internal::channels_last_dim_order(sizes.size()), dynamism); + } + + /** + * Given data in contiguous memory format, returns a new Tensor with the + * specified shape and the same data but in channels last memory format. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] data The data in contiguous memory format that the Tensor should + * be initialized with. The size of this vector must be equal to the product + * of the elements of `sizes`. + * + * @return A new Tensor with the specified shape and data in channls last + * memory format. + */ + torch::executor::Tensor channels_last_like( + const torch::executor::Tensor& input, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + const std::vector sizes( + input.sizes().begin(), input.sizes().end()); + + ET_CHECK_MSG( + sizes.size() == 4 || sizes.size() == 5, + "Only 4D and 5D tensors can be channels last"); + ET_CHECK_MSG( + is_contiguous_dim_order(input.dim_order().data(), input.dim()) == true, + "Input tensor is not contiguous"); + int32_t N = sizes[0]; + int32_t C = sizes[1]; + // Depth and height are adjacent in both layouts, so a 5-D tensor is + // permuted like a 4-D one whose height covers both. + int32_t H = sizes.size() == 5 ? sizes[2] * sizes[3] : sizes[2]; + int32_t W = sizes.back(); + + std::vector contiguous_data( + input.data_ptr(), input.data_ptr() + input.numel()); + std::vector channels_last_data( + N * C * H * W); // Create a new blob with the same total size to contain + // channels_last data + for (const auto n : c10::irange(N)) { + for (const auto c : c10::irange(C)) { + for (const auto h : c10::irange(H)) { + for (const auto w : c10::irange(W)) { + // Calculate the index in the original blob + int32_t old_index = ((n * C + c) * H + h) * W + w; + // Calculate the index in the new blob + int32_t new_index = ((n * H + h) * W + w) * C + c; + // Copy the data + channels_last_data[new_index] = contiguous_data[old_index]; + } + } + } + } + + return make_with_dimorder( + sizes, + channels_last_data, + internal::channels_last_dim_order(sizes.size()), + dynamism); + } + + /** + * Returns a new Tensor with the specified shape, containing contiguous data + * will all elements set to `value`. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] value The value of all elements of the Tensor. + * @return A new Tensor with the specified shape. + */ + torch::executor::Tensor full( + const std::vector& sizes, + ctype value, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + std::vector data(internal::sizes_to_numel(sizes), value); + return make(sizes, data, /* empty strides */ {}, dynamism); + } + + /** + * Returns a new Tensor with the specified shape, containing channels last + * contiguous data will all elements set to `value`. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @param[in] value The value of all elements of the Tensor. + * @return A new Tensor with the specified shape. + */ + torch::executor::Tensor full_channels_last( + const std::vector& sizes, + ctype value, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + std::vector data(internal::sizes_to_numel(sizes), value); + return make_with_dimorder( + sizes, data, internal::channels_last_dim_order(sizes.size()), dynamism); + } + + /** + * Returns a new Tensor with the specified shape, containing contiguous data + * in channels last memory format with all `0` elements. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @return A new Tensor with the specified shape. + */ + torch::executor::Tensor zeros_channels_last( + const std::vector& sizes, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + return full_channels_last(sizes, 0, dynamism); + } + + /** + * Returns a new Tensor with the specified shape, containing contiguous data + * in contiguous memory format with all `0` elements. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @return A new Tensor with the specified shape. + */ + torch::executor::Tensor zeros( + const std::vector& sizes, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + return full(sizes, 0, dynamism); + } + + /** + * Returns a new Tensor with the specified shape, containing contiguous data + * with all `1` elements. + * + * @param[in] sizes The sizes of the dimensions of the Tensor. + * @return A new Tensor with the specified shape. + */ + torch::executor::Tensor ones( + const std::vector& sizes, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + return full(sizes, 1, dynamism); + } + + /** + * Returns a new Tensor with the same shape as the input tensor, containing + * contiguous data with all `0` elements. + * + * @param[in] input The tensor that supplies the shape of the new Tensor. + * @return A new Tensor with the specified shape. + */ + torch::executor::Tensor zeros_like( + const torch::executor::Tensor& input, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + std::vector sizes = {input.sizes().begin(), input.sizes().end()}; + return full(sizes, 0, dynamism); + } + + /** + * Returns a new Tensor with the same shape as the input tensor, containing + * contiguous data with all `1` elements. + * + * @param[in] input The tensor that supplies the shape of the new Tensor. + * @return A new Tensor with the specified shape. + */ + torch::executor::Tensor ones_like( + const torch::executor::Tensor& input, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) { + std::vector sizes = {input.sizes().begin(), input.sizes().end()}; + return full(sizes, 1, dynamism); + } + + private: + /** + * Owns all backing memory for a single Tensor. + */ + struct TensorMemory { + TensorMemory( + const std::vector& sizes, + const std::vector& data, + const std::vector& dim_order, + const std::vector& strides, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC) + : sizes_(sizes), + data_(data), + dim_order_(dim_order), + strides_(strides), + impl_( + DTYPE, + /*dim=*/sizes_.size(), + sizes_.data(), + data_.data(), + dim_order_.data(), + strides_.data(), + dynamism) { + // The only valid values for bool are 0 and 1; coerce! + if constexpr (std::is_same_v) { + for (auto& x : data_) { + x = static_cast(x); + } + } + } + + std::vector sizes_; + std::vector data_; + std::vector dim_order_; + std::vector strides_; + torch::executor::TensorImpl impl_; + }; + + /** + * The memory pointed to by Tensors created by this factory. This is a vector + * of pointers so that the TensorMemory objects won't move if the vector needs + * to resize/realloc. + */ + std::vector> memory_; +}; + +#endif // !USE_ATEN_LIB + +/** + * A helper class for creating TensorLists, simplifying memory management. + * + * NOTE: A given TensorListFactory owns the memory pointed to by all TensorLists + * (and Tensors they contain), and must live longer than those TensorLists and + * Tensors. + */ +template +class TensorListFactory final { + public: + TensorListFactory() = default; + ~TensorListFactory() = default; + + /** + * Returns a TensorList containing Tensors with the same shapes as the + * provided Tensors, but filled with zero elements. The dtypes of the template + * entries are ignored. + */ + executorch::aten::TensorList zeros_like( + const std::vector& templates) { + memory_.emplace_back( + std::make_unique>()); + auto& vec = memory_.back(); + std::for_each( + templates.begin(), + templates.end(), + [&](const executorch::aten::Tensor& t) { + vec->push_back(tf_.zeros_like(t)); + }); + return executorch::aten::TensorList(vec->data(), vec->size()); + } + + private: + TensorFactory tf_; + /** + * The memory pointed to by TensorLists created by this factory. This is a + * vector of pointers so that the elements won't move if the vector needs to + * resize/realloc. + */ + std::vector>> memory_; +}; + +} // namespace testing +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +namespace testing { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::testing::TensorFactory; +using ::executorch::runtime::testing::TensorListFactory; +} // namespace testing +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/exec_aten/testing_util/tensor_util.h b/include/executorch/runtime/core/exec_aten/testing_util/tensor_util.h new file mode 100644 index 0000000..4284176 --- /dev/null +++ b/include/executorch/runtime/core/exec_aten/testing_util/tensor_util.h @@ -0,0 +1,378 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include // For MATCHER_P + +#include + +namespace executorch { +namespace runtime { +namespace testing { + +namespace internal { +constexpr double kDefaultRtol = 1e-5; +constexpr double kDefaultAtol = 1e-8; +// Per +// https://en.wikipedia.org/wiki/Half-precision_floating-point_format, +// float16 has about 3.3 digits of precision. +constexpr double kDefaultHalfAtol = 1e-3; + +// Following similar reasoning to float16, BFloat16 has +// math.log10(2**8) = 2.4 digits of precision. +constexpr double kDefaultBFloat16Atol = 1e-2; +} // namespace internal + +/** + * Returns true if the tensors are of the same shape and dtype, and if all + * elements are close to each other. + * + * TODO(T132992348): This function will currently fail an ET_CHECK if the + * strides of the tensors are not identical. Add support for comparing + * tensors with different strides. + * + * Note that gtest users can write `EXPECT_THAT(tensor1, IsCloseTo(tensor2))` or + * `EXPECT_THAT(tensor1, Not(IsCloseTo(tensor2)))`, or use the helper macros + * `EXPECT_TENSOR_CLOSE()` and `EXPECT_TENSOR_NOT_CLOSE()`. + * + * For exact equality, use `EXPECT_THAT(tensor1, IsEqualTo(tensor2))` or + * `EXPECT_THAT(tensor1, Not(IsEqualTo(tensor2)))`, or the helper macros + * `EXPECT_TENSOR_EQ()` and `EXPECT_TENSOR_NE()`. + * + * An element A is close to B when one is true: + * + * (1) A is equal to B. + * (2) A and B are both NaN, are both -infinity, or are both +infinity. + * (3) The error abs(A - B) is finite and less than the max error + * (atol + abs(rtol * B)). + * + * If both rtol/atol are zero, this function checks for exact equality. + * + * NOTE: rtol/atol are ignored and treated as zero for non-floating-point + * dtypes. + * + * @param[in] a The first tensor to compare. + * @param[in] b The second tensor to compare. + * @param[in] rtol Relative tolerance; see note above. + * @param[in] atol Absolute tolerance; see note above. + * @retval true All corresponding elements of the two tensors are within the + * specified tolerance of each other. + * @retval false One or more corresponding elements of the two tensors are + * outside of the specified tolerance of each other. + */ +bool tensors_are_close( + const executorch::aten::Tensor& a, + const executorch::aten::Tensor& b, + double rtol = internal::kDefaultRtol, + std::optional opt_atol = std::nullopt); + +/** + * Returns true if the tensors are of the same numel and dtype, and if all + * elements are close to each other. The tensor shapes do not need to be same. + * + * Note that gtest users can write `EXPECT_THAT(tensor1, + * IsDataCloseTo(tensor2))` or `EXPECT_THAT(tensor1, + * Not(IsDataCloseTo(tensor2)))`, or use the helper macros + * `EXPECT_TENSOR_DATA_CLOSE()` and `EXPECT_TENSOR_DATA_NOT_CLOSE()`. + * + * For exact equality, use `EXPECT_THAT(tensor1, IsDataEqualTo(tensor2))` or + * `EXPECT_THAT(tensor1, Not(IsDataEqualTo(tensor2)))`, or the helper macros + * `EXPECT_TENSOR_DATA_EQ()` and `EXPECT_TENSOR_DATA_NE()`. + * + * The defination of an element A is close to B is in the comment of the + * function `tensors_are_close` + * + * @param[in] a The first tensor to compare. + * @param[in] b The second tensor to compare. + * @param[in] rtol Relative tolerance; see note above. + * @param[in] atol Absolute tolerance; see note above. + * @retval true All corresponding elements of the two tensors are within the + * specified tolerance of each other. + * @retval false One or more corresponding elements of the two tensors are + * outside of the specified tolerance of each other. + */ +bool tensor_data_is_close( + const executorch::aten::Tensor& a, + const executorch::aten::Tensor& b, + double rtol = internal::kDefaultRtol, + std::optional opt_atol = std::nullopt); + +/** + * Returns true if the two lists are of the same length, and + * tensor_data_is_close(tensors_a[i], tensors_b[i], rtol, atol) is true for all + * i. + */ +bool tensor_lists_are_close( + const executorch::aten::Tensor* tensors_a, + size_t num_tensors_a, + const executorch::aten::Tensor* tensors_b, + size_t num_tensors_b, + double rtol = internal::kDefaultRtol, + std::optional opt_atol = std::nullopt); + +/** + * Lets gtest users write `EXPECT_THAT(tensor1, IsCloseTo(tensor2))` or + * `EXPECT_THAT(tensor1, Not(IsCloseTo(tensor2)))`. + * + * See also `EXPECT_TENSOR_CLOSE()` and `EXPECT_TENSOR_NOT_CLOSE()`. + */ +MATCHER_P(IsCloseTo, other, "") { + return tensors_are_close(arg, other); +} + +/** + * Lets gtest users write + * `EXPECT_THAT(tensor1, IsCloseToWithTol(tensor2, rtol, atol))` + * or `EXPECT_THAT(tensor1, Not(IsCloseToWithTol(tensor2, rtol, atol)))`. + * + * See also `EXPECT_TENSOR_CLOSE_WITH_TOL()` and + * `EXPECT_TENSOR_NOT_CLOSE_WITH_TOL()`. + */ +MATCHER_P3(IsCloseToWithTol, other, rtol, atol, "") { + return tensors_are_close(arg, other, rtol, atol); +} + +/** + * Lets gtest users write `EXPECT_THAT(tensor1, IsEqualTo(tensor2))` or + * `EXPECT_THAT(tensor1, Not(IsEqualTo(tensor2)))`. + * + * See also `EXPECT_TENSOR_EQ()` and `EXPECT_TENSOR_NE()`. + */ +MATCHER_P(IsEqualTo, other, "") { + return tensors_are_close(arg, other, /*rtol=*/0, /*atol=*/0); +} + +/** + * Lets gtest users write `EXPECT_THAT(tensor1, IsDataCloseTo(tensor2))` or + * `EXPECT_THAT(tensor1, Not(IsDataCloseTo(tensor2)))`. + * + * See also `EXPECT_TENSOR_DATA_CLOSE()` and `EXPECT_TENSOR_DATA_NOT_CLOSE()`. + */ +MATCHER_P(IsDataCloseTo, other, "") { + return tensor_data_is_close(arg, other); +} + +/** + * Lets gtest users write + * `EXPECT_THAT(tensor1, IsDataCloseToWithTol(tensor2, rtol, atol))` + * or `EXPECT_THAT(tensor1, Not(IsDataCloseToWithTol(tensor2, rtol, atol)))`. + * + * See also `EXPECT_TENSOR_CLOSE_WITH_TOL()` and + * `EXPECT_TENSOR_NOT_CLOSE_WITH_TOL()`. + */ +MATCHER_P3(IsDataCloseToWithTol, other, rtol, atol, "") { + return tensor_data_is_close(arg, other, rtol, atol); +} + +/** + * Lets gtest users write `EXPECT_THAT(tensor1, IsDataEqualTo(tensor2))` or + * `EXPECT_THAT(tensor1, Not(IsDataEqualTo(tensor2)))`. + * + * See also `EXPECT_TENSOR_DATA_EQ()` and `EXPECT_TENSOR_DATA_NE()`. + */ +MATCHER_P(IsDataEqualTo, other, "") { + return tensor_data_is_close(arg, other, /*rtol=*/0, /*atol=*/0); +} + +/** + * Lets gtest users write `EXPECT_THAT(tensor_list1, + * IsListCloseTo(tensor_list2))` or `EXPECT_THAT(tensor_list1, + * Not(IsListCloseTo(tensor_list2)))`. + * + * The lists can be any container of Tensor that supports ::data() and ::size(). + * + * See also `EXPECT_TENSOR_LISTS_CLOSE()` and `EXPECT_TENSOR_LISTS_NOT_CLOSE()`. + */ +MATCHER_P(IsListCloseTo, other, "") { + return tensor_lists_are_close( + arg.data(), arg.size(), other.data(), other.size()); +} + +/** + * Lets gtest users write `EXPECT_THAT(tensor_list1, + * IsListEqualTo(tensor_list2))` or `EXPECT_THAT(tensor_list1, + * Not(IsListEqualTo(tensor_list2)))`. + * + * The lists can be any container of Tensor that supports ::data() and ::size(). + * + * See also `EXPECT_TENSOR_LISTS_EQ()` and `EXPECT_TENSOR_LISTS_NE()`. + */ +MATCHER_P(IsListEqualTo, other, "") { + return tensor_lists_are_close( + arg.data(), + arg.size(), + other.data(), + other.size(), + /*rtol=*/0, + /*atol=*/0); +} + +/* + * NOTE: Although it would be nice to make `EXPECT_EQ(t1, t2)` and friends work, + * that would require implementing `bool operator==(Tensor, Tensor)`. + * + * at::Tensor implements `Tensor operator==(Tensor, Tensor)`, returning an + * element-by-element comparison. This causes an ambiguous conflict with the + * `bool`-returning operator. + */ +#define EXPECT_TENSOR_EQ(t1, t2) \ + EXPECT_THAT((t1), ::executorch::runtime::testing::IsEqualTo(t2)) +#define EXPECT_TENSOR_NE(t1, t2) \ + EXPECT_THAT((t1), ::testing::Not(executorch::runtime::testing::IsEqualTo(t2))) +#define ASSERT_TENSOR_EQ(t1, t2) \ + ASSERT_THAT((t1), ::executorch::runtime::testing::IsEqualTo(t2)) +#define ASSERT_TENSOR_NE(t1, t2) \ + ASSERT_THAT((t1), ::testing::Not(executorch::runtime::testing::IsEqualTo(t2))) + +#define EXPECT_TENSOR_CLOSE(t1, t2) \ + EXPECT_THAT((t1), ::executorch::runtime::testing::IsCloseTo(t2)) +#define EXPECT_TENSOR_NOT_CLOSE(t1, t2) \ + EXPECT_THAT((t1), ::testing::Not(executorch::runtime::testing::IsCloseTo(t2))) +#define ASSERT_TENSOR_CLOSE(t1, t2) \ + ASSERT_THAT((t1), ::executorch::runtime::testing::IsCloseTo(t2)) +#define ASSERT_TENSOR_NOT_CLOSE(t1, t2) \ + ASSERT_THAT((t1), ::testing::Not(executorch::runtime::testing::IsCloseTo(t2))) + +#define EXPECT_TENSOR_CLOSE_WITH_TOL(t1, t2, rtol, atol) \ + EXPECT_THAT( \ + (t1), ::executorch::runtime::testing::IsCloseToWithTol(t2, rtol, atol)) +#define EXPECT_TENSOR_NOT_CLOSE_WITH_TOL(t1, t2, rtol, atol) \ + EXPECT_THAT( \ + (t1), \ + ::testing::Not( \ + executorch::runtime::testing::IsCloseToWithTol(t2, rtol, atol))) +#define ASSERT_TENSOR_CLOSE_WITH_TOL(t1, t2, rtol, atol) \ + ASSERT_THAT( \ + (t1), ::executorch::runtime::testing::IsCloseToWithTol(t2, rtol, atol)) +#define ASSERT_TENSOR_NOT_CLOSE_WITH_TOL(t1, t2, rtol, atol) \ + ASSERT_THAT( \ + (t1), \ + ::testing::Not( \ + executorch::runtime::testing::IsCloseToWithTol(t2, rtol, atol))) + +#define EXPECT_TENSOR_DATA_EQ(t1, t2) \ + EXPECT_THAT((t1), ::executorch::runtime::testing::IsDataEqualTo(t2)) +#define EXPECT_TENSOR_DATA_NE(t1, t2) \ + EXPECT_THAT( \ + (t1), ::testing::Not(executorch::runtime::testing::IsDataEqualTo(t2))) +#define ASSERT_TENSOR_DATA_EQ(t1, t2) \ + ASSERT_THAT((t1), ::executorch::runtime::testing::IsDataEqualTo(t2)) +#define ASSERT_TENSOR_DATA_NE(t1, t2) \ + ASSERT_THAT( \ + (t1), ::testing::Not(executorch::runtime::testing::IsDataEqualTo(t2))) + +#define EXPECT_TENSOR_DATA_CLOSE(t1, t2) \ + EXPECT_THAT((t1), ::executorch::runtime::testing::IsDataCloseTo(t2)) +#define EXPECT_TENSOR_DATA_NOT_CLOSE(t1, t2) \ + EXPECT_THAT( \ + (t1), ::testing::Not(executorch::runtime::testing::IsDataCloseTo(t2))) +#define ASSERT_TENSOR_DATA_CLOSE(t1, t2) \ + ASSERT_THAT((t1), ::executorch::runtime::testing::IsDataCloseTo(t2)) +#define ASSERT_TENSOR_DATA_NOT_CLOSE(t1, t2) \ + ASSERT_THAT( \ + (t1), ::testing::Not(executorch::runtime::testing::IsDataCloseTo(t2))) + +#define EXPECT_TENSOR_DATA_CLOSE_WITH_TOL(t1, t2, rtol, atol) \ + EXPECT_THAT( \ + (t1), \ + ::executorch::runtime::testing::IsDataCloseToWithTol(t2, rtol, atol)) +#define EXPECT_TENSOR_DATA_NOT_CLOSE_WITH_TOL(t1, t2, rtol, atol) \ + EXPECT_THAT( \ + (t1), \ + ::testing::Not( \ + executorch::runtime::testing::IsDataCloseToWithTol(t2, rtol, atol))) +#define ASSERT_TENSOR_DATA_CLOSE_WITH_TOL(t1, t2, rtol, atol) \ + ASSERT_THAT( \ + (t1), \ + ::executorch::runtime::testing::IsDataCloseToWithTol(t2, rtol, atol)) +#define ASSERT_TENSOR_DATA_NOT_CLOSE_WITH_TOL(t1, t2, rtol, atol) \ + ASSERT_THAT( \ + (t1), \ + ::testing::Not( \ + executorch::runtime::testing::IsDataCloseToWithTol(t2, rtol, atol))) + +/* + * Helpers for comparing lists of Tensors. + */ + +#define EXPECT_TENSOR_LISTS_EQ(t1, t2) \ + EXPECT_THAT((t1), ::executorch::runtime::testing::IsListEqualTo(t2)) +#define EXPECT_TENSOR_LISTS_NE(t1, t2) \ + EXPECT_THAT( \ + (t1), ::testing::Not(executorch::runtime::testing::IsListEqualTo(t2))) +#define ASSERT_TENSOR_LISTS_EQ(t1, t2) \ + ASSERT_THAT((t1), ::executorch::runtime::testing::IsListEqualTo(t2)) +#define ASSERT_TENSOR_LISTS_NE(t1, t2) \ + ASSERT_THAT( \ + (t1), ::testing::Not(executorch::runtime::testing::IsListEqualTo(t2))) + +#define EXPECT_TENSOR_LISTS_CLOSE(t1, t2) \ + EXPECT_THAT((t1), ::executorch::runtime::testing::IsListCloseTo(t2)) +#define EXPECT_TENSOR_LISTS_NOT_CLOSE(t1, t2) \ + EXPECT_THAT( \ + (t1), ::testing::Not(executorch::runtime::testing::IsListCloseTo(t2))) +#define ASSERT_TENSOR_LISTS_CLOSE(t1, t2) \ + ASSERT_THAT((t1), ::executorch::runtime::testing::IsListCloseTo(t2)) +#define ASSERT_TENSOR_LISTS_NOT_CLOSE(t1, t2) \ + ASSERT_THAT( \ + (t1), ::testing::Not(executorch::runtime::testing::IsListCloseTo(t2))) + +} // namespace testing +} // namespace runtime +} // namespace executorch + +// ATen already defines operator<<() for Tensor and ScalarType. +#ifndef USE_ATEN_LIB + +/* + * These functions must be declared in the original namespaces of their + * associated types so that C++ can find them. + */ +namespace executorch { +namespace runtime { +namespace etensor { + +/** + * Prints the ScalarType to the stream as a human-readable string. + * + * See also executorch::runtime::toString(ScalarType t) in ScalarTypeUtil.h. + */ +std::ostream& operator<<(std::ostream& os, const ScalarType& t); + +/** + * Prints the Tensor to the stream as a human-readable string. + */ +std::ostream& operator<<(std::ostream& os, const Tensor& t); + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +#endif // !USE_ATEN_LIB + +namespace torch { +namespace executor { +namespace testing { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::testing::IsCloseTo; +using ::executorch::runtime::testing::IsCloseToWithTol; +using ::executorch::runtime::testing::IsDataCloseTo; +using ::executorch::runtime::testing::IsDataCloseToWithTol; +using ::executorch::runtime::testing::IsDataEqualTo; +using ::executorch::runtime::testing::IsEqualTo; +using ::executorch::runtime::testing::IsListCloseTo; +using ::executorch::runtime::testing::IsListEqualTo; +using ::executorch::runtime::testing::tensor_data_is_close; +using ::executorch::runtime::testing::tensor_lists_are_close; +using ::executorch::runtime::testing::tensors_are_close; +} // namespace testing +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/exec_aten/util/dim_order_util.h b/include/executorch/runtime/core/exec_aten/util/dim_order_util.h new file mode 100644 index 0000000..ea56827 --- /dev/null +++ b/include/executorch/runtime/core/exec_aten/util/dim_order_util.h @@ -0,0 +1,290 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace executorch { +namespace runtime { + +namespace { +template +bool validate_dim_order(const DimOrderType* dim_order, const size_t dims) { + static_assert( + kTensorDimensionLimit <= 16, + "Bitmask-based validation requires kTensorDimensionLimit <= 16"); + if (dims > kTensorDimensionLimit) { + return false; + } + uint16_t seen = 0; + for (const auto i : c10::irange(dims)) { + if (dim_order[i] >= static_cast(dims)) { + return false; + } + const uint16_t mask = 1u << dim_order[i]; + if (seen & mask) { + return false; + } + seen |= mask; + } + return true; +} +} // namespace + +/** + * Check if a given dim_order array is equivalent to the contiguous dim order of + * {0, 1, 2, 3, ...} + * + * @param[in] dim_order pointer to dim_order array + * @param[in] dims length of the dim_order array + */ +template +inline bool is_contiguous_dim_order( + const DimOrderType* dim_order, + const size_t dims) { + for (const auto i : c10::irange(dims)) { + if (dim_order[i] != static_cast(i)) { + return false; + } + } + return true; +} + +/** + * Check if a given dim_order array is equivalent to a channels last dim order. + * Channels last dim order is only valid for 4-dim and 5-dim tensors. + * + * @param[in] dim_order pointer to dim_order array + * @param[in] dims length of the dim_order array + */ +template +bool is_channels_last_dim_order( + const DimOrderType* dim_order, + const size_t dims) { + if (dims != 4 && dims != 5) { + return false; + } + // 4-dim tensor is interpreted as NCHW, 5-dim tensor is interpreted as NCHWD + DimOrderType channels_dim = 1; + // Last value in the dim order should be the channels dim + if (dim_order[dims - 1] != channels_dim) { + return false; + } + + if (dim_order[0] != 0) { + return false; + } + DimOrderType d = 1; + while (d < static_cast(dims) - 1) { + if (dim_order[d] != d + 1) { + return false; + } + d++; + } + return true; +} + +/* + * This utility translated sizes to strides by using dimension order + * information. Dimension order specifies how the dimensions are laid out in the + * memory. For example for Size = [2, 3, 4, 5] dim_names = [N, C, H, W] + * dim_order = [0, 2, 3, 1] + * strides = [60, 1, 15, 3] + * param[in]: sizes, pointer to sizes array + * param[in]: dim_order, pointer to dimension order array + * param[in]: dims, number of dims. Sizes and dim_order must be sizes to dims + * param[out]: strides, pointer to strides array that is filled in + * + * NB: Reason for not using ArrayRef is the dependency on kernel_types.h + * This header cannot be included, because of circular dep it causes. + * kernel_types depends on executorch_kernel_types in lean mode, which compiles + * TensorImpl.cpp. executorch_kernel_types needs to depend on dim_order_utils + * in order to utilize dim_order_to_stride in its resize impl. If + * dim_order_utils depends on kernel_type, we have circular deps. This is also + * the reason for templatizing this function. Better ideas welcome! + * TODO(T148342910) + * + * Note that this function does not check that the provided dim order is valid. + * This function should only be used when the validity of the dim order has been + * checked beforehand. A safer version of this function is provided below as + * dim_order_to_stride which will check that the dim order is valid. + */ +template +inline void dim_order_to_stride_nocheck( + const SizesType* sizes, + const DimOrderType* dim_order, + const size_t dims, + StridesType* strides) { + // For 0 dim tensors, just return ok. + if (dims == 0) { + return; + } + // Fastest moving dim has stride of 1. + // For example: + // Size = [2, 3, 4, 5] dim_names = [N, C, H, W] + // dim_order = [0, 2, 3, 1] + // strides = [60, 1, 15, 3] + strides[dim_order[dims - 1]] = 1; + for (int32_t i = dims - 2; i >= 0; --i) { + if (sizes[dim_order[i + 1]] == 0) { + strides[dim_order[i]] = strides[dim_order[i + 1]]; + } else { + strides[dim_order[i]] = + strides[dim_order[i + 1]] * sizes[dim_order[i + 1]]; + } + } +} + +template +ET_NODISCARD inline Error dim_order_to_stride( + const SizesType* sizes, + const DimOrderType* dim_order, + const size_t dims, + StridesType* strides) { + // For 0 dim tensors, just return ok. + if (dims == 0) { + return Error::Ok; + } + ET_CHECK_OR_RETURN_ERROR( + validate_dim_order(dim_order, dims), + InvalidArgument, + "Invalid dim order: values must be a permutation of [0, %zu)", + dims); + + dim_order_to_stride_nocheck(sizes, dim_order, dims, strides); + return Error::Ok; +} + +namespace internal { + +template +struct StrideDimOrder { + StridesType stride; + DimOrderType dim_order; + + StrideDimOrder(StridesType stride_, DimOrderType dim_order_) + : stride(stride_), dim_order(dim_order_) {} + StrideDimOrder() = default; + bool operator>(const StrideDimOrder& other) const { + // descending order + return stride < other.stride; + } +}; + +template +struct Sorter { + public: + void quick_sort(ValueType arr[], int32_t low, int32_t high) { + if (low < high) { + ValueType pivot = arr[high]; + int32_t pos = partition(arr, low, high, pivot); + + quick_sort(arr, low, pos - 1); + quick_sort(arr, pos + 1, high); + } + } + + private: + void swap(ValueType arr[], int32_t pos1, int32_t pos2) noexcept { + ValueType temp = arr[pos1]; + arr[pos1] = arr[pos2]; + arr[pos2] = temp; + } + + int32_t + partition(ValueType arr[], int32_t low, int32_t high, ValueType pivot) { + int32_t i = low; + int32_t j = low; + while (i <= high) { + if (arr[i] > pivot) { + i++; + } else { + swap(arr, i++, j++); + } + } + return j - 1; + } +}; + +} // namespace internal + +/* + * This utility translated strides to dimension order + * information. Dimension order specifies how the dimensions are laid out in the + * memory. For example for tensor with sizes [3, 5, 2] and strides [5, 1, 15], + * dim order should be [2, 0, 1], which is obtained by sorting strides in + * descending order. param[in]: sizes, pointer to sizes array param[in]: + * dim_order, pointer to dimension order array param[in]: dims, number of dims. + * Sizes and dim_order must be sizes to dims param[out]: strides, pointer to + * strides array that is filled in + * + * NB: Reason for not using ArrayRef is the dependency on kernel_types.h + * This header cannot be included, because of circular dep it causes. + * kernel_types depends on executorch_kernel_types in lean mode, which compiles + * TensorImpl.cpp. executorch_kernel_types needs to depend on dim_order_utils + * in order to utilize dim_order_to_stride in its resize impl. If + * dim_order_utils depends on kernel_type, we have circular deps. This is also + * the reason for templatizing this function. Better ideas welcome! + * TODO(T148342910) + */ +template +ET_NODISCARD inline Error stride_to_dim_order( + const StridesType* strides, + const size_t dims, + DimOrderType* dim_order) { + const size_t kMaxNumOfDimensions = 16; + ET_CHECK_OR_RETURN_ERROR( + dim_order != nullptr, + MemoryAllocationFailed, + "Need memory to get dim_order."); + ET_CHECK_OR_RETURN_ERROR( + dims <= kMaxNumOfDimensions, + NotSupported, + "dims %zu exceeds maximum allowed %zu", + dims, + kMaxNumOfDimensions); + internal::StrideDimOrder + array[kMaxNumOfDimensions]; + for (DimOrderType i = 0; i < dims; i++) { + array[i].dim_order = i; + array[i].stride = strides[i]; + } + + internal::Sorter> sorter; + + sorter.quick_sort(array, 0, dims - 1); + + for (const auto i : c10::irange(dims)) { + dim_order[i] = array[i].dim_order; + } + return Error::Ok; +} + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::dim_order_to_stride; +using ::executorch::runtime::dim_order_to_stride_nocheck; +using ::executorch::runtime::is_channels_last_dim_order; +using ::executorch::runtime::is_contiguous_dim_order; +using ::executorch::runtime::stride_to_dim_order; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/exec_aten/util/scalar_type_util.h b/include/executorch/runtime/core/exec_aten/util/scalar_type_util.h new file mode 100644 index 0000000..3e8e36b --- /dev/null +++ b/include/executorch/runtime/core/exec_aten/util/scalar_type_util.h @@ -0,0 +1,1430 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * + * Forked from + * https://github.com/pytorch/pytorch/blob/master/c10/core/ScalarType.h + * + * See file comment in ../ScalarType.h. + * + * This file contains all of the non-critical parts of the original ScalarType.h + * that are not required for the core ExecuTorch runtime, but may be helpful for + * code that uses ScalarType. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wswitch-enum") + +#ifdef USE_ATEN_LIB +// Note that a lot of the macros/functions defined in this ScalarTypeUtil.h file +// are also defined in c10/core/ScalarType.h, which is included via +// kernel_types.h when building in ATen mode. They tend to use different names +// and a different namespace, but if there are conflicts they should be resolved +// here. +#define ET_FORALL_SCALAR_TYPES AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS +#include +namespace executorch { +namespace aten { +using ScalarType = at::ScalarType; +} // namespace aten +} // namespace executorch +#else // !USE_ATEN_LIB +#include +#include +namespace executorch { +namespace aten { +using ScalarType = torch::executor::ScalarType; +using string_view = std::string_view; +} // namespace aten +} // namespace executorch +#endif // USE_ATEN_LIB +// DEPRECATED: The executorch::aten:: namespace is deprecated. Use +// executorch::aten:: instead. +namespace exec_aten = ::executorch::aten; + +namespace executorch { +namespace runtime { + +#if !defined(USE_ATEN_LIB) +// Util to figure out if the scalar type if one of the +// supported floating point types. +// In aten mode, aten lib already has these utils as part of +// its vec_base.h +template +struct is_floating_point + : std::integral_constant< + bool, + std::is_floating_point::value || + std::is_same_v || + std::is_same_v> {}; + +// Util to figure out if the scalar type is one of the +// reduced precision floating point types. +template +struct is_reduced_floating_point + : std::integral_constant< + bool, + std::is_same_v || + std::is_same_v> {}; + +template +constexpr bool is_reduced_floating_point_v = + is_reduced_floating_point::value; +#endif + +/// Maps ScalarTypes to C++ types. +template <::executorch::aten::ScalarType N> +struct ScalarTypeToCppType; + +#define SPECIALIZE_ScalarTypeToCppType(cpp_type, scalar_type) \ + template <> \ + struct ScalarTypeToCppType<::executorch::aten::ScalarType::scalar_type> { \ + using type = cpp_type; \ + }; + +ET_FORALL_SCALAR_TYPES(SPECIALIZE_ScalarTypeToCppType) + +#undef SPECIALIZE_ScalarTypeToCppType + +/// Maps C++ types to ScalarTypes. +template +struct CppTypeToScalarType; + +#define SPECIALIZE_CppTypeToScalarType(cpp_type, scalar_type) \ + template <> \ + struct CppTypeToScalarType \ + : std::integral_constant< \ + ::executorch::aten::ScalarType, \ + ::executorch::aten::ScalarType::scalar_type> {}; + +ET_FORALL_SCALAR_TYPES(SPECIALIZE_CppTypeToScalarType) + +#undef SPECIALIZE_CppTypeToScalarType + +// +// Macros that iterate across different subsets of ScalarTypes. +// +// See ET_FORALL_SCALAR_TYPES in ScalarType.h to iterate across all ScalarType +// names and types. +// +// For all of these macros, the final `_` parameter is the name of another macro +// that takes two parameters: the name of a C type, and the name of the +// corresponding ScalarType enumerator. +// +// Note that these macros should use fully-qualified namespaces (starting with +// `::`) to ensure that they can be called safely in any arbitrary namespace. +// + +// In this context, "INT" means integer C types, which is why the quantized +// integer types are not included. +#define ET_FORALL_INT_TYPES(_) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int32_t, Int) \ + _(int64_t, Long) + +// Here `ANOTHER_INPUT` should be another variable to be forwarded to a given +// function. +#define ET_FORALL_INT_TYPES_WITH(ANOTHER_INPUT, _) \ + _(ANOTHER_INPUT, uint8_t, Byte) \ + _(ANOTHER_INPUT, int8_t, Char) \ + _(ANOTHER_INPUT, int16_t, Short) \ + _(ANOTHER_INPUT, int32_t, Int) \ + _(ANOTHER_INPUT, int64_t, Long) + +#define ET_FORALL_INT_TYPES_WITH2(ANOTHER_INPUT1, ANOTHER_INPUT2, _) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, uint8_t, Byte) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int8_t, Char) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int16_t, Short) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int32_t, Int) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int64_t, Long) + +#define ET_FORALL_INT_TYPES_AND(SCALARTYPE, _) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int32_t, Int) \ + _(int64_t, Long) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE>::type, \ + SCALARTYPE) + +// In this context, "FLOAT" means float C types, which is why BFloat16 is not +// included. +#define ET_FORALL_FLOAT_TYPES(_) \ + _(float, Float) \ + _(double, Double) + +#define ET_FORALL_FLOAT_TYPES_AND(SCALARTYPE, _) \ + _(float, Float) \ + _(double, Double) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE>::type, \ + SCALARTYPE) + +#define ET_FORALL_FLOAT_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, _) \ + _(float, Float) \ + _(double, Double) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE1>::type, \ + SCALARTYPE1) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE2>::type, \ + SCALARTYPE2) + +#define ET_FORALL_FLOATH_TYPES(_) ET_FORALL_FLOAT_TYPES_AND(Half, _) + +#define ET_FORALL_FLOATHBF16_TYPES(_) \ + ET_FORALL_FLOAT_TYPES_AND2(Half, BFloat16, _) + +// Here `ANOTHER_INPUT` should be another variable to be forwarded to a given +// function. Not to be confused with another scalar type as in +// `ET_FORALL_FLOAT_TYPES_AND`. +#define ET_FORALL_FLOAT_TYPES_WITH(ANOTHER_INPUT, _) \ + _(ANOTHER_INPUT, float, Float) \ + _(ANOTHER_INPUT, double, Double) + +#define ET_FORALL_FLOATH_TYPES_WITH(ANOTHER_INPUT, _) \ + _(ANOTHER_INPUT, float, Float) \ + _(ANOTHER_INPUT, double, Double) \ + _(ANOTHER_INPUT, ::executorch::aten::Half, Half) + +#define ET_FORALL_FLOAT_TYPES_WITH2(ANOTHER_INPUT1, ANOTHER_INPUT2, _) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, float, Float) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, double, Double) + +#define ET_FORALL_FLOATHBF16_TYPES_WITH2(ANOTHER_INPUT1, ANOTHER_INPUT2, _) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, float, Float) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, double, Double) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, ::executorch::aten::Half, Half) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, ::executorch::aten::BFloat16, BFloat16) + +// In this context, "REAL" means integer/float C types, which is why BFloat16 +// and Half are not included. +#define ET_FORALL_REAL_TYPES(_) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int32_t, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) + +// Here `ANOTHER_INPUT` should be another variable to be forwarded to a given +// function. Not to be confused with another scalar type as in +// `ET_FORALL_REAL_TYPES_AND`. +#define ET_FORALL_REAL_TYPES_WITH(ANOTHER_INPUT, _) \ + _(ANOTHER_INPUT, uint8_t, Byte) \ + _(ANOTHER_INPUT, int8_t, Char) \ + _(ANOTHER_INPUT, int16_t, Short) \ + _(ANOTHER_INPUT, int32_t, Int) \ + _(ANOTHER_INPUT, int64_t, Long) \ + _(ANOTHER_INPUT, float, Float) \ + _(ANOTHER_INPUT, double, Double) + +#define ET_FORALL_REAL_TYPES_WITH2(ANOTHER_INPUT1, ANOTHER_INPUT2, _) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, uint8_t, Byte) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int8_t, Char) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int16_t, Short) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int32_t, Int) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int64_t, Long) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, float, Float) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, double, Double) + +#define ET_FORALL_REALHBF16_TYPES_WITH2(ANOTHER_INPUT1, ANOTHER_INPUT2, _) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, uint8_t, Byte) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int8_t, Char) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int16_t, Short) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int32_t, Int) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, int64_t, Long) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, float, Float) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, double, Double) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, ::executorch::aten::Half, Half) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, ::executorch::aten::BFloat16, BFloat16) + +#define ET_FORALL_REALHBBF16_TYPES_WITH2(ANOTHER_INPUT1, ANOTHER_INPUT2, _) \ + ET_FORALL_REALHBF16_TYPES_WITH2(ANOTHER_INPUT2, ANOTHER_INPUT2, _) \ + _(ANOTHER_INPUT1, ANOTHER_INPUT2, bool, Bool) + +// For macros that take `SCALARTYPEn` parameters, those parameters should be +// an unquoted/unqualified enumerator name like `Int` or `Float`. +#define ET_FORALL_REAL_TYPES_AND(SCALARTYPE, _) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int32_t, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE>::type, \ + SCALARTYPE) + +#define ET_FORALL_REAL_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, _) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int32_t, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE1>::type, \ + SCALARTYPE1) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE2>::type, \ + SCALARTYPE2) + +#define ET_FORALL_REALH_TYPES(_) ET_FORALL_REAL_TYPES_AND(Half, _) + +#define ET_FORALL_REALHBF16_TYPES(_) \ + ET_FORALL_REAL_TYPES_AND2(Half, BFloat16, _) + +#define ET_FORALL_REALHBBF16_TYPES(_) \ + ET_FORALL_REAL_TYPES_AND3(Bool, Half, BFloat16, _) + +#define ET_FORALL_REAL_TYPES_AND_WITH(SCALARTYPE, ANOTHER_INPUT, _) \ + _(ANOTHER_INPUT, uint8_t, Byte) \ + _(ANOTHER_INPUT, int8_t, Char) \ + _(ANOTHER_INPUT, int16_t, Short) \ + _(ANOTHER_INPUT, int32_t, Int) \ + _(ANOTHER_INPUT, int64_t, Long) \ + _(ANOTHER_INPUT, float, Float) \ + _(ANOTHER_INPUT, double, Double) \ + _(ANOTHER_INPUT, \ + ::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE>::type, \ + SCALARTYPE) + +#define ET_FORALL_REAL_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, _) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int32_t, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE1>::type, \ + SCALARTYPE1) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE2>::type, \ + SCALARTYPE2) + +#define ET_FORALL_REAL_TYPES_AND3(SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, _) \ + _(uint8_t, Byte) \ + _(int8_t, Char) \ + _(int16_t, Short) \ + _(int32_t, Int) \ + _(int64_t, Long) \ + _(float, Float) \ + _(double, Double) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE1>::type, \ + SCALARTYPE1) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE2>::type, \ + SCALARTYPE2) \ + _(::executorch::runtime::ScalarTypeToCppType< \ + ::executorch::aten::ScalarType::SCALARTYPE3>::type, \ + SCALARTYPE3) + +#define ET_FORALL_QINT_TYPES(_) \ + _(::torch::executor::qint8, QInt8) \ + _(::torch::executor::quint8, QUInt8) \ + _(::torch::executor::qint32, QInt32) \ + _(::torch::executor::quint4x2, QUInt4x2) \ + _(::torch::executor::quint2x4, QUInt2x4) + +// In this context, "COMPLEX" means complex types based on primitive C types, +// which is why ComplexHalf is not included. +#define ET_FORALL_COMPLEX_TYPES(_) \ + _(::executorch::aten::complex, ComplexFloat) \ + _(::executorch::aten::complex, ComplexDouble) + +#define ET_FORALL_COMPLEXH_TYPES(_) \ + _(::executorch::aten::complex<::executorch::aten::Half>, ComplexHalf) \ + _(::executorch::aten::complex, ComplexFloat) \ + _(::executorch::aten::complex, ComplexDouble) + +// +// Utility functions to retrieve metadata for a given ScalarType +// + +/** + * Returns true if the parameter is one of the values covered by + * ET_FORALL_SCALAR_TYPES. + */ +inline bool isValid(::executorch::aten::ScalarType type) { + return static_cast(type) >= 0 && + type < ::executorch::aten::ScalarType::NumOptions && + type != ::executorch::aten::ScalarType::Undefined; +} + +/** + * Returns the name of a ScalarType as a C string. + * + * @param[in] t The type to get the name of. + * @return The name of the type, or "UNKNOWN_SCALAR" if the type is not known. + */ +inline const char* toString(::executorch::aten::ScalarType t) { +#define DEFINE_CASE(_, name) \ + case ::executorch::aten::ScalarType::name: \ + return #name; + + switch (t) { + ET_FORALL_SCALAR_TYPES(DEFINE_CASE) + case ::executorch::aten::ScalarType::Undefined: + return "Undefined"; + default: + return "UNKNOWN_SCALAR"; + } +#undef DEFINE_CASE +} + +/** + * Returns the size in bytes of the C type associated with the ScalarType. + * + * Calls ET_CHECK_MSG() if the type is unknown or is ScalarType::Undefined. + * + * @param[in] t The type to get the underlying C type size of. + * @return The size of the associated C type in bytes. + */ +inline size_t elementSize(::executorch::aten::ScalarType t) { +#define CASE_ELEMENTSIZE_CASE(ctype, name) \ + case ::executorch::aten::ScalarType::name: \ + return sizeof(ctype); + + switch (t) { + ET_FORALL_SCALAR_TYPES(CASE_ELEMENTSIZE_CASE) + default: + ET_CHECK_MSG(false, "Unknown ScalarType %" PRId8, static_cast(t)); + } +#undef CASE_ELEMENTSIZE_CASE +} + +inline constexpr bool isIntegralType( + ::executorch::aten::ScalarType t, + bool includeBool) { + return (includeBool && t == ::executorch::aten::ScalarType::Bool) || + (t == ::executorch::aten::ScalarType::Byte || + t == ::executorch::aten::ScalarType::Char || + t == ::executorch::aten::ScalarType::Int || + t == ::executorch::aten::ScalarType::Long || + t == ::executorch::aten::ScalarType::Short); +} + +template +struct is_integral_type + : public std::integral_constant< + bool, + isIntegralType(CppTypeToScalarType::value, includeBool)> {}; + +inline constexpr bool isFloatingType(::executorch::aten::ScalarType t) { + return ( + t == ::executorch::aten::ScalarType::Double || + t == ::executorch::aten::ScalarType::Float || + t == ::executorch::aten::ScalarType::Half || + t == ::executorch::aten::ScalarType::BFloat16); +} + +inline bool isRealType(::executorch::aten::ScalarType t) { + return ( + t == ::executorch::aten::ScalarType::Byte || + t == ::executorch::aten::ScalarType::Char || + t == ::executorch::aten::ScalarType::Short || + t == ::executorch::aten::ScalarType::Int || + t == ::executorch::aten::ScalarType::Long || + t == ::executorch::aten::ScalarType::Float || + t == ::executorch::aten::ScalarType::Double); +} + +inline bool isRealHType(::executorch::aten::ScalarType t) { + return ( + t == ::executorch::aten::ScalarType::Byte || + t == ::executorch::aten::ScalarType::Char || + t == ::executorch::aten::ScalarType::Short || + t == ::executorch::aten::ScalarType::Int || + t == ::executorch::aten::ScalarType::Long || + t == ::executorch::aten::ScalarType::Float || + t == ::executorch::aten::ScalarType::Double || + t == ::executorch::aten::ScalarType::Half); +} + +inline bool isRealHBType(::executorch::aten::ScalarType t) { + return (isRealHType(t) || t == ::executorch::aten::ScalarType::Bool); +} + +inline bool isRealHBF16Type(::executorch::aten::ScalarType t) { + return (isRealHType(t) || t == ::executorch::aten::ScalarType::BFloat16); +} + +inline bool isRealHBBF16Type(::executorch::aten::ScalarType t) { + return (isRealHBType(t) || t == ::executorch::aten::ScalarType::BFloat16); +} + +inline constexpr bool isComplexType(::executorch::aten::ScalarType t) { + return ( + t == ::executorch::aten::ScalarType::ComplexHalf || + t == ::executorch::aten::ScalarType::ComplexFloat || + t == ::executorch::aten::ScalarType::ComplexDouble); +} + +template +struct is_complex_type : std::integral_constant< + bool, + isComplexType(CppTypeToScalarType::value)> {}; + +constexpr bool isBitsType(::executorch::aten::ScalarType t) { + return t == ::executorch::aten::ScalarType::Bits1x8 || + t == ::executorch::aten::ScalarType::Bits2x4 || + t == ::executorch::aten::ScalarType::Bits4x2 || + t == ::executorch::aten::ScalarType::Bits8 || + t == ::executorch::aten::ScalarType::Bits16; +} + +template +struct is_bits_type + : std::integral_constant::value)> { +}; + +constexpr bool isQIntType(::executorch::aten::ScalarType t) { + // Don't forget to extend this when adding new QInt types + return t == ::executorch::aten::ScalarType::QInt8 || + t == ::executorch::aten::ScalarType::QUInt8 || + t == ::executorch::aten::ScalarType::QInt32 || + t == ::executorch::aten::ScalarType::QUInt4x2 || + t == ::executorch::aten::ScalarType::QUInt2x4; +} + +template +struct is_qint_type + : std::integral_constant::value)> { +}; + +constexpr bool isFloat8Type(::executorch::aten::ScalarType t) { + // Don't forget to extend this when adding new QInt types + return t == ::executorch::aten::ScalarType::Float8_e5m2 || + t == ::executorch::aten::ScalarType::Float8_e4m3fn || + t == ::executorch::aten::ScalarType::Float8_e5m2fnuz || + t == ::executorch::aten::ScalarType::Float8_e4m3fnuz; +} + +template +struct is_float8_type + : std:: + integral_constant::value)> { +}; + +constexpr bool isBarebonesUnsignedType(::executorch::aten::ScalarType t) { + // Don't forget to extend this when adding new QInt types + return t == ::executorch::aten::ScalarType::UInt16 || + t == ::executorch::aten::ScalarType::UInt32 || + t == ::executorch::aten::ScalarType::UInt64; +} + +template +struct is_barebones_unsigned_type + : std::integral_constant< + bool, + isBarebonesUnsignedType(CppTypeToScalarType::value)> {}; + +inline ::executorch::aten::ScalarType toQIntType( + ::executorch::aten::ScalarType t) { + switch (t) { + case ::executorch::aten::ScalarType::Byte: + return ::executorch::aten::ScalarType::QUInt8; + case ::executorch::aten::ScalarType::Char: + return ::executorch::aten::ScalarType::QInt8; + case ::executorch::aten::ScalarType::Int: + return ::executorch::aten::ScalarType::QInt32; + default: + return t; + } +} + +inline ::executorch::aten::ScalarType toUnderlying( + ::executorch::aten::ScalarType t) { + switch (t) { + case ::executorch::aten::ScalarType::QUInt8: + return ::executorch::aten::ScalarType::Byte; + case ::executorch::aten::ScalarType::QInt8: + return ::executorch::aten::ScalarType::Char; + case ::executorch::aten::ScalarType::QInt32: + return ::executorch::aten::ScalarType::Int; + case ::executorch::aten::ScalarType::QUInt4x2: + return ::executorch::aten::ScalarType::Byte; + case ::executorch::aten::ScalarType::QUInt2x4: + return ::executorch::aten::ScalarType::Byte; + default: + return t; + } +} + +inline bool isSignedType(::executorch::aten::ScalarType t) { + ET_CHECK_MSG( + !::executorch::runtime::isQIntType(t), + "isSignedType not supported for quantized types like %" PRId8, + static_cast(t)); +#define CASE_SIGNED(ctype, name) \ + case ::executorch::aten::ScalarType::name: \ + return std::numeric_limits::is_signed; + + switch (t) { + case ::executorch::aten::ScalarType::ComplexHalf: + case ::executorch::aten::ScalarType::ComplexFloat: + case ::executorch::aten::ScalarType::ComplexDouble: + return true; + ET_FORALL_REAL_TYPES_AND3(Half, Bool, BFloat16, CASE_SIGNED) + default: + ET_CHECK_MSG(false, "Unknown ScalarType %" PRId8, static_cast(t)); + } +#undef CASE_SIGNED +} + +inline bool isUnderlying( + ::executorch::aten::ScalarType type, + ::executorch::aten::ScalarType qtype) { + return type == ::executorch::runtime::toUnderlying(qtype); +} + +inline constexpr ::executorch::aten::ScalarType toRealValueType( + ::executorch::aten::ScalarType t) { + switch (t) { + case ::executorch::aten::ScalarType::ComplexHalf: + return ::executorch::aten::ScalarType::Half; + case ::executorch::aten::ScalarType::ComplexFloat: + return ::executorch::aten::ScalarType::Float; + case ::executorch::aten::ScalarType::ComplexDouble: + return ::executorch::aten::ScalarType::Double; + default: + return t; + } +} + +inline constexpr ::executorch::aten::ScalarType toComplexType( + ::executorch::aten::ScalarType t) { + switch (t) { + case ::executorch::aten::ScalarType::BFloat16: + // BFloat16 has range equivalent to Float, + // so we map it to ComplexFloat. + return ::executorch::aten::ScalarType::ComplexFloat; + case ::executorch::aten::ScalarType::Half: + return ::executorch::aten::ScalarType::ComplexHalf; + case ::executorch::aten::ScalarType::Float: + return ::executorch::aten::ScalarType::ComplexFloat; + case ::executorch::aten::ScalarType::Double: + return ::executorch::aten::ScalarType::ComplexDouble; + case ::executorch::aten::ScalarType::ComplexHalf: + return ::executorch::aten::ScalarType::ComplexHalf; + case ::executorch::aten::ScalarType::ComplexFloat: + return ::executorch::aten::ScalarType::ComplexFloat; + case ::executorch::aten::ScalarType::ComplexDouble: + return ::executorch::aten::ScalarType::ComplexDouble; + default: + ET_CHECK_MSG( + false, + "Unknown Complex ScalarType for %" PRId8, + static_cast(t)); + } +} + +/** + * Encodes type casting rules that are consistent with ATen behaviour. + */ +inline constexpr bool canCast( + const ::executorch::aten::ScalarType from, + const ::executorch::aten::ScalarType to) { + // Disallow complex -> non-complex + return !(::executorch::runtime::isComplexType(from) && + !::executorch::runtime::isComplexType(to)) && + // Disallow float -> integral + !(::executorch::runtime::isFloatingType(from) && + ::executorch::runtime::isIntegralType(to, /*includeBool=*/false)) && + // Treat bool as a special category. Disallow non-bool -> bool + !(from != ::executorch::aten::ScalarType::Bool && + to == ::executorch::aten::ScalarType::Bool); +} + +template +struct can_cast : std::integral_constant< + bool, + canCast( + CppTypeToScalarType::value, + CppTypeToScalarType::value)> {}; + +/** + * When casting from floating point to integral type, if the floating value is + * outside the integral type range, then an error is thrown if sanitization is + * enabled. To circumvent this, we cast the floating point to int64_t first. + */ +template < + typename To, + typename From, + std::enable_if_t< + (std::is_floating_point::value && std::is_integral::value), + int> = 0> +To convert(From val) { + return static_cast(static_cast(val)); +} + +template < + typename To, + typename From, + std::enable_if_t< + !(std::is_floating_point::value && std::is_integral::value), + int> = 0> +To convert(From val) { + return static_cast(val); +} + +namespace internal { +// This is generated according to NumPy's promote_types +inline constexpr auto u1 = ::executorch::aten::ScalarType::Byte; +inline constexpr auto i1 = ::executorch::aten::ScalarType::Char; +inline constexpr auto i2 = ::executorch::aten::ScalarType::Short; +inline constexpr auto i4 = ::executorch::aten::ScalarType::Int; +inline constexpr auto i8 = ::executorch::aten::ScalarType::Long; +inline constexpr auto f2 = ::executorch::aten::ScalarType::Half; +inline constexpr auto f4 = ::executorch::aten::ScalarType::Float; +inline constexpr auto f8 = ::executorch::aten::ScalarType::Double; +inline constexpr auto c2 = ::executorch::aten::ScalarType::ComplexHalf; +inline constexpr auto c4 = ::executorch::aten::ScalarType::ComplexFloat; +inline constexpr auto c8 = ::executorch::aten::ScalarType::ComplexDouble; +inline constexpr auto b1 = ::executorch::aten::ScalarType::Bool; +inline constexpr auto bf = ::executorch::aten::ScalarType::BFloat16; + +using U1 = + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Byte>::type; +using I1 = + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Char>::type; +using I2 = + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Short>::type; +using I4 = + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Int>::type; +using I8 = + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Long>::type; +using F2 = + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Half>::type; +using F4 = + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Float>::type; +using F8 = + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Double>::type; +using C2 = typename ScalarTypeToCppType< + ::executorch::aten::ScalarType::ComplexHalf>::type; +using C4 = typename ScalarTypeToCppType< + ::executorch::aten::ScalarType::ComplexFloat>::type; +using C8 = typename ScalarTypeToCppType< + ::executorch::aten::ScalarType::ComplexDouble>::type; +using B1 = + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Bool>::type; +using BF = typename ScalarTypeToCppType< + ::executorch::aten::ScalarType::BFloat16>::type; + +inline constexpr std::array<::executorch::aten::ScalarType, 13> index2dtype = { + {u1, i1, i2, i4, i8, f2, f4, f8, c2, c4, c8, b1, bf}}; + +constexpr std::array< + int64_t, + static_cast(::executorch::aten::ScalarType::NumOptions)> +calculate_dtype2index() { + std::array< + int64_t, + static_cast(::executorch::aten::ScalarType::NumOptions)> + inverse = {}; + for (int64_t i = 0; + i < static_cast(::executorch::aten::ScalarType::NumOptions); + i++) { + inverse[i] = -1; + } + for (int64_t i = 0; i < static_cast(index2dtype.size()); i++) { + inverse[static_cast(index2dtype[i])] = i; + } + return inverse; +} + +inline constexpr auto dtype2index = calculate_dtype2index(); +inline constexpr int NUM_PROMOTE_TYPES = 13; +// Should match _promoteTypesLookup in c10/core/ScalarType.cpp so that +// we match PyTorch core type promotion semantics. +inline constexpr ::executorch::aten::ScalarType + promoteTypesLookup[NUM_PROMOTE_TYPES][NUM_PROMOTE_TYPES] = { + /* u1 i1 i2 i4 i8 f2 f4 f8 c2 c4 c8 b1 bf*/ + /* u1 */ {u1, i2, i2, i4, i8, f2, f4, f8, c2, c4, c8, u1, bf}, + /* i1 */ {i2, i1, i2, i4, i8, f2, f4, f8, c2, c4, c8, i1, bf}, + /* i2 */ {i2, i2, i2, i4, i8, f2, f4, f8, c2, c4, c8, i2, bf}, + /* i4 */ {i4, i4, i4, i4, i8, f2, f4, f8, c2, c4, c8, i4, bf}, + /* i8 */ {i8, i8, i8, i8, i8, f2, f4, f8, c2, c4, c8, i8, bf}, + /* f2 */ {f2, f2, f2, f2, f2, f2, f4, f8, c2, c4, c8, f2, f4}, + /* f4 */ {f4, f4, f4, f4, f4, f4, f4, f8, c4, c4, c8, f4, f4}, + /* f8 */ {f8, f8, f8, f8, f8, f8, f8, f8, c8, c8, c8, f8, f8}, + /* c2 */ {c2, c2, c2, c2, c2, c2, c4, c8, c2, c4, c8, c2, c4}, + /* c4 */ {c4, c4, c4, c4, c4, c4, c4, c8, c4, c4, c8, c4, c4}, + /* c8 */ {c8, c8, c8, c8, c8, c8, c8, c8, c8, c8, c8, c8, c8}, + /* b1 */ {u1, i1, i2, i4, i8, f2, f4, f8, c2, c4, c8, b1, bf}, + /* bf */ {bf, bf, bf, bf, bf, f4, f4, f8, c4, c4, c8, bf, bf}, +}; + +} // namespace internal + +/** + * Implements type promotion rules that are consistent with ATen behaviour, + * which in turn is consistent with NumPy's promote_types. + * If half_to_float is set to true, then half and bfloat16 will be promoted to + * float instead + */ +inline constexpr ::executorch::aten::ScalarType promoteTypes( + ::executorch::aten::ScalarType a, + ::executorch::aten::ScalarType b, + bool half_to_float = false) { + // For QInt types, only allow exact match + if (::executorch::runtime::isQIntType(a) && a == b) { + return a; + } + if (::executorch::runtime::isQIntType(a) || + ::executorch::runtime::isQIntType(b)) { + ET_CHECK_MSG(false, "promoteTypes not valid for quantized dtypes"); + } + + // For Bits types, only allow exact match + if (::executorch::runtime::isBitsType(a) && a == b) { + return a; + } + if (::executorch::runtime::isBitsType(a) || + ::executorch::runtime::isBitsType(b)) { + ET_CHECK_MSG(false, "promoteTypes not valid for bits dtypes"); + } + + // For Float8 types, only allow exact match + if (::executorch::runtime::isFloat8Type(a) && a == b) { + return a; + } + if (::executorch::runtime::isFloat8Type(a) || + ::executorch::runtime::isFloat8Type(b)) { + ET_CHECK_MSG(false, "promoteTypes not valid for float8 dtypes"); + } + + // For barebones uint types, only allow exact match + if (::executorch::runtime::isBarebonesUnsignedType(a) && a == b) { + return a; + } + if (::executorch::runtime::isBarebonesUnsignedType(a) || + ::executorch::runtime::isBarebonesUnsignedType(b)) { + ET_CHECK_MSG(false, "promoteTypes not valid for barebone unsigned dtypes"); + } + + auto ix_a = ::executorch::runtime::internal::dtype2index[(int)a]; + ET_CHECK(ix_a != -1); + auto ix_b = ::executorch::runtime::internal::dtype2index[(int)b]; + ET_CHECK(ix_b != -1); + ::executorch::aten::ScalarType promoted_type = + ::executorch::runtime::internal::promoteTypesLookup[ix_a][ix_b]; + + if (half_to_float && + (promoted_type == ::executorch::aten::ScalarType::Half || + promoted_type == ::executorch::aten::ScalarType::BFloat16)) { + promoted_type = ::executorch::aten::ScalarType::Float; + } + + return promoted_type; +} + +template +struct promote_types { + private: + static_assert( + std::is_same_v || + (!is_qint_type::value && !is_qint_type::value), + "promote_types not valid for quantized dtypes"); + static_assert( + std::is_same_v || + (!is_bits_type::value && !is_bits_type::value), + "promote_types not valid for bits dtypes"); + static_assert( + std::is_same_v || + (!is_float8_type::value && !is_float8_type::value), + "promote_types not valid for float8 dtypes"); + static_assert( + std::is_same_v || + (!is_barebones_unsigned_type::value && + !is_barebones_unsigned_type::value), + "promote_types not valid for barebones unsigned dtypes"); + + using promoted_type_not_respecting_half_to_float = + typename ScalarTypeToCppType::value, + CppTypeToScalarType::value)>::type; + + public: + using type = std::conditional_t< + half_to_float && + (std::is_same_v< + promoted_type_not_respecting_half_to_float, + typename ScalarTypeToCppType< + ::executorch::aten::ScalarType::Half>::type> || + std::is_same_v< + promoted_type_not_respecting_half_to_float, + typename ScalarTypeToCppType< + ::executorch::aten::ScalarType::BFloat16>::type>), + typename ScalarTypeToCppType<::executorch::aten::ScalarType::Float>::type, + promoted_type_not_respecting_half_to_float>; +}; + +// +// Helper macros for switch case macros (see below) +// +// These macros are not meant to be used directly. They provide an easy way to +// generate a switch statement that can handle subsets of ScalarTypes supported +// by ExecuTorch. +// + +#ifdef ET_INTERNAL_CHECK_SELECTIVE_BUILD +#define ET_INTERNAL_SWITCH_CASE(enum_type, CTYPE_ALIAS, ...) \ + case enum_type: { \ + ET_INTERNAL_CHECK_SELECTIVE_BUILD(enum_type); \ + using CTYPE_ALIAS [[maybe_unused]] = \ + ::executorch::runtime::ScalarTypeToCppType::type; \ + return __VA_ARGS__(); \ + } +#else +#define ET_INTERNAL_SWITCH_CASE(enum_type, CTYPE_ALIAS, ...) \ + case enum_type: { \ + using CTYPE_ALIAS [[maybe_unused]] = \ + ::executorch::runtime::ScalarTypeToCppType::type; \ + return __VA_ARGS__(); \ + } +#endif + +#define ET_INTERNAL_SWITCH(TYPE, CONTEXT, NAME, ...) \ + [&] { \ + const auto& _st = TYPE; \ + const char* et_switch_name = NAME; \ + (void)et_switch_name; /* Suppress unused var */ \ + C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wswitch-enum") \ + switch (_st) { \ + __VA_ARGS__ \ + default: \ + CONTEXT.fail(torch::executor::Error::InvalidArgument); \ + ET_LOG( \ + Error, \ + "Unhandled dtype %s for %s", \ + ::executorch::runtime::toString(_st), \ + et_switch_name); \ + } \ + C10_DIAGNOSTIC_POP() \ + }() + +#define ET_INTERNAL_SWITCH_CASE_INT_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Byte, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Char, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Short, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Int, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Long, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_UINT_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::UInt16, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::UInt32, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::UInt64, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Float, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Double, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_REAL_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_INT_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES(CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_COMPLEX_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ComplexFloat, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ComplexDouble, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_COMPLEXH_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_COMPLEX_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ComplexHalf, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_QINT_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::QInt8, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::QUInt8, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::QInt32, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::QUInt4x2, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::QUInt2x4, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_BITS_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Bits1x8, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Bits2x4, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Bits4x2, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Bits8, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Bits16, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_ALL_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_REAL_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Half, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::BFloat16, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Bool, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE_COMPLEXH_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE_QINT_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE_BITS_TYPES(CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_REAL_TYPES_AND(ADDITIONAL, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_REAL_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_REAL_TYPES_AND2( \ + ADDITIONAL1, ADDITIONAL2, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_REAL_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL1, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL2, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_REAL_TYPES_AND3( \ + ADDITIONAL1, ADDITIONAL2, ADDITIONAL3, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_REAL_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL1, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL2, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL3, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_INT_TYPES_AND(ADDITIONAL, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_INT_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES_AND(ADDITIONAL, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES(CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES_AND2( \ + ADDITIONAL1, ADDITIONAL2, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES_AND( \ + ADDITIONAL1, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL2, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES_AND3( \ + ADDITIONAL1, ADDITIONAL2, ADDITIONAL3, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES_AND2( \ + ADDITIONAL1, ADDITIONAL2, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::ADDITIONAL3, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_SCALAR_OBJ_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Bool, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Long, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Double, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_SCALAR_OBJ_REAL_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Long, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Double, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_SCALAR_OBJ_INTB_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Bool, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Long, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_INTERNAL_SWITCH_CASE_SCALAR_OBJ_FLOATB_TYPES(CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Bool, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::Double, CTYPE_ALIAS, __VA_ARGS__) + +// +// Switch case macros +// +// These macros provide an easy way to generate switch statements that apply a +// common lambda function to subsets of ScalarTypes supported by ExecuTorch. +// The lambda function can type specialize to the ctype associated with the +// ScalarType being handled through an alias passed as the CTYPE_ALIAS argument. +// +// Arguments: +// - ADDITIONAL: Additional ScalarType case to add +// - TYPE: The ScalarType to handle through the switch statement +// - CONTEXT: The KernelRuntimeContext instance used for error handling, etc. +// - NAME: A name for this operation which will be used in error messages +// - CTYPE_ALIAS: A typedef for the ctype associated with the ScalarType. +// - [&](){...}: A lambda function to be applied to each ScalarType case +// +// An example usage is: +// +// ET_SWITCH_REAL_TYPES(input.scalar_type(), "example", CTYPE, [&]() { +// output.mutable_data_ptr[0] = input.const_data_ptr[0]; +// }); +// +// Note that these can be nested as well: +// +// ET_SWITCH_REAL_TYPES(input.scalar_type(), "example", CTYPE_IN, [&]() { +// ET_SWITCH_REAL_TYPES(output.scalar_type(), "example", CTYPE_OUT, [&]() { +// output.mutable_data_ptr[0] = +// input.const_data_ptr[0]; +// }); +// }); +// +// These macros are adapted from Dispatch.h in the ATen library. The primary +// difference is that the CTYPE_ALIAS argument is exposed to users, which is +// used to alias the ctype associated with the ScalarType that is being handled. +// + +#define ET_SWITCH_ALL_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_ALL_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_REAL_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_REAL_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_REAL_TYPES_AND( \ + ADDITIONAL, TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_REAL_TYPES_AND( \ + ADDITIONAL, CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_REAL_TYPES_AND2( \ + ADDITIONAL1, ADDITIONAL2, TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_REAL_TYPES_AND2( \ + ADDITIONAL1, ADDITIONAL2, CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_REAL_TYPES_AND3( \ + ADDITIONAL1, \ + ADDITIONAL2, \ + ADDITIONAL3, \ + TYPE, \ + CONTEXT, \ + NAME, \ + CTYPE_ALIAS, \ + ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_REAL_TYPES_AND3( \ + ADDITIONAL1, ADDITIONAL2, ADDITIONAL3, CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_REALH_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_SWITCH_REAL_TYPES_AND(Half, TYPE, CONTEXT, NAME, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_SWITCH_REALHBF16_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_SWITCH_REAL_TYPES_AND2( \ + Half, BFloat16, TYPE, CONTEXT, NAME, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_SWITCH_REALB_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_SWITCH_REAL_TYPES_AND(Bool, TYPE, CONTEXT, NAME, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_SWITCH_REALHB_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_SWITCH_REAL_TYPES_AND2( \ + Half, Bool, TYPE, CONTEXT, NAME, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_SWITCH_REALHBBF16_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_SWITCH_REAL_TYPES_AND3( \ + Half, Bool, BFloat16, TYPE, CONTEXT, NAME, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_SWITCH_REALHBBF16_AND_UINT_TYPES( \ + TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_REAL_TYPES_AND3( \ + Half, Bool, BFloat16, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE_UINT_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_INT_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_INT_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_INT_TYPES_AND( \ + ADDITIONAL, TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_INT_TYPES_AND( \ + ADDITIONAL, CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_FLOAT_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_FLOAT_TYPES_AND( \ + ADDITIONAL, TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES_AND( \ + ADDITIONAL, CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_FLOAT_TYPES_AND2( \ + ADDITIONAL1, ADDITIONAL2, TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES_AND2( \ + ADDITIONAL1, ADDITIONAL2, CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_FLOAT_TYPES_AND3( \ + ADDITIONAL1, \ + ADDITIONAL2, \ + ADDITIONAL3, \ + TYPE, \ + CONTEXT, \ + NAME, \ + CTYPE_ALIAS, \ + ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_FLOAT_TYPES_AND3( \ + ADDITIONAL1, ADDITIONAL2, ADDITIONAL3, CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_FLOATH_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_SWITCH_FLOAT_TYPES_AND(Half, TYPE, CONTEXT, NAME, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_SWITCH_FLOATHBF16_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_SWITCH_FLOAT_TYPES_AND2( \ + Half, BFloat16, TYPE, CONTEXT, NAME, CTYPE_ALIAS, __VA_ARGS__) + +#define ET_SWITCH_FLOATHBF16_TYPES_AND( \ + ADDITIONAL, TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_SWITCH_FLOAT_TYPES_AND3( \ + Half, \ + BFloat16, \ + ADDITIONAL, \ + TYPE, \ + CONTEXT, \ + NAME, \ + CTYPE_ALIAS, \ + __VA_ARGS__) + +#define ET_SWITCH_QINT_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_QINT_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_COMPLEX_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_COMPLEX_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_COMPLEXH_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_COMPLEXH_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_SCALAR_OBJ_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_SCALAR_OBJ_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_SCALAR_OBJ_REAL_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_SCALAR_OBJ_REAL_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_SCALAR_OBJ_INTB_TYPES(TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_SCALAR_OBJ_INTB_TYPES(CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_SCALAR_OBJ_FLOATB_TYPES( \ + TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE_SCALAR_OBJ_FLOATB_TYPES( \ + CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_TWO_TYPES(T1, T2, TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::T1, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::T2, CTYPE_ALIAS, __VA_ARGS__)) + +#define ET_SWITCH_THREE_TYPES( \ + T1, T2, T3, TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::T1, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::T2, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::T3, \ + CTYPE_ALIAS, \ + __VA_ARGS__)) + +#define ET_SWITCH_FOUR_TYPES( \ + T1, T2, T3, T4, TYPE, CONTEXT, NAME, CTYPE_ALIAS, ...) \ + ET_INTERNAL_SWITCH( \ + TYPE, \ + CONTEXT, \ + NAME, \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::T1, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::T2, CTYPE_ALIAS, __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::T3, \ + CTYPE_ALIAS, \ + __VA_ARGS__) \ + ET_INTERNAL_SWITCH_CASE( \ + ::executorch::aten::ScalarType::T4, \ + CTYPE_ALIAS, \ + __VA_ARGS__)) + +} // namespace runtime +} // namespace executorch + +namespace executorch { +namespace aten { +#ifdef USE_ATEN_LIB +using ::at::elementSize; +#else // USE_ATEN_LIB +using ::executorch::runtime::elementSize; +#endif // USE_ATEN_LIB +} // namespace aten +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::can_cast; +using ::executorch::runtime::canCast; +using ::executorch::runtime::convert; +using ::executorch::runtime::CppTypeToScalarType; +using ::executorch::runtime::elementSize; +using ::executorch::runtime::is_barebones_unsigned_type; +using ::executorch::runtime::is_bits_type; +using ::executorch::runtime::is_complex_type; +using ::executorch::runtime::is_float8_type; +using ::executorch::runtime::is_integral_type; +using ::executorch::runtime::is_qint_type; +using ::executorch::runtime::isBitsType; +using ::executorch::runtime::isComplexType; +using ::executorch::runtime::isFloatingType; +using ::executorch::runtime::isIntegralType; +using ::executorch::runtime::isQIntType; +using ::executorch::runtime::isRealHBType; +using ::executorch::runtime::isRealHType; +using ::executorch::runtime::isRealType; +using ::executorch::runtime::isValid; +using ::executorch::runtime::promote_types; +using ::executorch::runtime::promoteTypes; +using ::executorch::runtime::ScalarTypeToCppType; +using ::executorch::runtime::toString; +#if !defined(USE_ATEN_LIB) +using ::executorch::runtime::is_floating_point; +using ::executorch::runtime::is_reduced_floating_point; +#endif +namespace internal { +using ::executorch::runtime::internal::B1; +using ::executorch::runtime::internal::C2; +using ::executorch::runtime::internal::C4; +using ::executorch::runtime::internal::C8; +using ::executorch::runtime::internal::F2; +using ::executorch::runtime::internal::F4; +using ::executorch::runtime::internal::F8; +using ::executorch::runtime::internal::I1; +using ::executorch::runtime::internal::I2; +using ::executorch::runtime::internal::I4; +using ::executorch::runtime::internal::I8; +using ::executorch::runtime::internal::U1; +} // namespace internal +} // namespace executor +} // namespace torch + +C10_DIAGNOSTIC_POP() diff --git a/include/executorch/runtime/core/exec_aten/util/tensor_dimension_limit.h b/include/executorch/runtime/core/exec_aten/util/tensor_dimension_limit.h new file mode 100644 index 0000000..c690d96 --- /dev/null +++ b/include/executorch/runtime/core/exec_aten/util/tensor_dimension_limit.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch::runtime { +/** + * The expected output size may not be the existing size of any inputs and + * outputs if the operator supports both broadcast and dynamic shape. + * Therefore such operators needs extra space to store the calculated expected + * output size. such dynamic allocation is troublesome in executorch so we can + * just hard code a static value of a relatively small value because users + * don't create high dimensional tensors. + */ +constexpr size_t kTensorDimensionLimit = 16; +} // namespace executorch::runtime diff --git a/include/executorch/runtime/core/exec_aten/util/tensor_shape_to_c_string.h b/include/executorch/runtime/core/exec_aten/util/tensor_shape_to_c_string.h new file mode 100644 index 0000000..efc91f8 --- /dev/null +++ b/include/executorch/runtime/core/exec_aten/util/tensor_shape_to_c_string.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace executorch::runtime { + +/** + * Maximum size of a string returned by tensor_shape_to_c_string, for + * stack allocation. + */ +constexpr size_t kTensorShapeStringSizeLimit = 1 + /* opening parenthesis */ + 10 * kTensorDimensionLimit + /* maximum digits we will print; update + * kMaximumPrintableTensorShapeElement + * if changing */ + 2 * kTensorDimensionLimit + /* comma and space after each item, + * overwritten with closing paren and + * NUL terminator for last element */ + 1; /* padding for temporary NUL terminator for simplicity of implementation + */ + +namespace internal { +constexpr size_t kMaximumPrintableTensorShapeElement = + std::numeric_limits::max(); +} // namespace internal + +/** + * Convert a shape to a NUL-terminated C string with limited size. If + * elements of the shape are larger than + * kMaximumPrintableTensorShapeElement, those elements will be + * rendered as ERR instead. + * + * NOTE: There are two overloads of this function to support both ATen + * tensors and ExecuTorch Tensors, which have different SizesType, + * while also avoiding a dependency on exec_aten.h from this header + * because that would cause a circular dependency. + */ +std::array tensor_shape_to_c_string( + executorch::runtime::Span shape); + +/** + * Convert a shape to a NUL-terminated C string with limited size. If + * elements of the shape are larger than + * kMaximumPrintableTensorShapeElement, those elements will be + * rendered as ERR instead. + * + * NOTE: There are two overloads of this function to support both ATen + * tensors and ExecuTorch Tensors, which have different SizesType, + * while also avoiding a dependency on exec_aten.h from this header + * because that would cause a circular dependency. + */ +std::array tensor_shape_to_c_string( + executorch::runtime::Span shape); + +} // namespace executorch::runtime diff --git a/include/executorch/runtime/core/exec_aten/util/tensor_util.h b/include/executorch/runtime/core/exec_aten/util/tensor_util.h new file mode 100644 index 0000000..b9cbab4 --- /dev/null +++ b/include/executorch/runtime/core/exec_aten/util/tensor_util.h @@ -0,0 +1,1428 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include // std::array +#include // PRId64 +#include +#include // size_t + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/// All assertion messages should begin with this prefix. +#define ET_TENSOR_CHECK_PREFIX__ "Tensors do not match" +#define ET_MIN2(a, b) (std::min(a, b)) +#define ET_MIN3(a, b, c) (std::min(a, std::min(b, c))) + +#define ET_NORMALIZE_IX(IX, UPPER_BOUND) IX < 0 ? IX + UPPER_BOUND : IX + +#define ET_CHECK_VALID_IX(IX, UPPER_BOUND) \ + ET_CHECK_MSG( \ + IX >= -static_cast(UPPER_BOUND) && \ + IX < static_cast(UPPER_BOUND), \ + "index %" PRId64 " must be within range [-%zd, %zd)", \ + IX, \ + UPPER_BOUND, \ + UPPER_BOUND) + +#define ET_CHECK_VALID_DIM(DIM, UPPER_BOUND) \ + ET_CHECK_MSG( \ + DIM >= -static_cast(UPPER_BOUND) && \ + DIM < static_cast(UPPER_BOUND), \ + "dim %" PRId64 " must be within range [-%zd, %zd)", \ + DIM, \ + UPPER_BOUND, \ + UPPER_BOUND) + +#define ET_CHECK_NON_ZERO_DIM_SIZE(DIM, T) \ + const size_t udim = ET_NORMALIZE_IX(DIM, T.dim()); \ + ET_CHECK_MSG( \ + T.size(udim) != 0, "Expected dim %zd to have non-zero size.", udim); + +/** + * Asserts that all tensors have the same shape. + * This also handles a edge case where there is only one element in all the + * tensors being compared but the number of dimensions >= 0. In the for loop + * iterating over the dimensions we make sure that we pick the smallest + * dimension of all the tensors as the upper bound for the for loop. + */ +#define ET_CHECK_SAME_SHAPE2(a__, b__) \ + do { \ + const size_t a_numel__ = (a__).numel(); \ + const size_t b_numel__ = (b__).numel(); \ + const size_t a_dim__ = (a__).dim(); \ + const size_t b_dim__ = (b__).dim(); \ + ET_CHECK_MSG( \ + a_numel__ == b_numel__ && \ + ((a_numel__ == 1 && b_numel__ == 1) || (a_dim__ == b_dim__)), \ + ET_TENSOR_CHECK_PREFIX__ ": numel={%zu, %zu}, dim={%zu, %zu}", \ + a_numel__, \ + b_numel__, \ + a_dim__, \ + b_dim__); \ + for (size_t dim__ = 0; dim__ < ET_MIN2(a_dim__, b_dim__); ++dim__) { \ + size_t a_size__ = (a__).size(dim__); \ + size_t b_size__ = (b__).size(dim__); \ + ET_CHECK_MSG( \ + a_size__ == b_size__, \ + ET_TENSOR_CHECK_PREFIX__ " at size(%zu): {%zu, %zu}", \ + dim__, \ + a_size__, \ + b_size__); \ + } \ + } while (0) + +#define ET_CHECK_SAME_SHAPE3(a__, b__, c__) \ + do { \ + const size_t a_numel__ = (a__).numel(); \ + const size_t b_numel__ = (b__).numel(); \ + const size_t c_numel__ = (c__).numel(); \ + const size_t a_dim__ = (a__).dim(); \ + const size_t b_dim__ = (b__).dim(); \ + const size_t c_dim__ = (c__).dim(); \ + ET_CHECK_MSG( \ + a_numel__ == b_numel__ && b_numel__ == c_numel__ && \ + ((a_numel__ == 1 && b_numel__ == 1 && c_numel__ == 1) || \ + a_dim__ == b_dim__ && b_dim__ == c_dim__), \ + ET_TENSOR_CHECK_PREFIX__ \ + ": numel={%zu, %zu, %zu}, dim={%zu, %zu, %zu}", \ + a_numel__, \ + b_numel__, \ + c_numel__, \ + a_dim__, \ + b_dim__, \ + c_dim__); \ + for (size_t dim__ = 0; dim__ < ET_MIN3(a_dim__, b_dim__, c_dim__); \ + ++dim__) { \ + size_t a_size__ = (a__).size(dim__); \ + size_t b_size__ = (b__).size(dim__); \ + size_t c_size__ = (c__).size(dim__); \ + ET_CHECK_MSG( \ + a_size__ == b_size__ && b_size__ == c_size__, \ + ET_TENSOR_CHECK_PREFIX__ " at size(%zu): {%zu, %zu, %zu}", \ + dim__, \ + a_size__, \ + b_size__, \ + c_size__); \ + } \ + } while (0) + +/// Asserts that all tensors have the same dtype. +#define ET_CHECK_SAME_DTYPE2(a__, b__) \ + do { \ + const ::executorch::aten::ScalarType a_type__ = (a__).scalar_type(); \ + const ::executorch::aten::ScalarType b_type__ = (b__).scalar_type(); \ + ET_CHECK_MSG( \ + a_type__ == b_type__, \ + ET_TENSOR_CHECK_PREFIX__ ": dtype={%" PRId8 ", %" PRId8 "}", \ + static_cast(a_type__), \ + static_cast(b_type__)); \ + } while (0) + +#define ET_CHECK_SAME_DTYPE3(a__, b__, c__) \ + do { \ + const ::executorch::aten::ScalarType a_type__ = (a__).scalar_type(); \ + const ::executorch::aten::ScalarType b_type__ = (b__).scalar_type(); \ + const ::executorch::aten::ScalarType c_type__ = (c__).scalar_type(); \ + ET_CHECK_MSG( \ + a_type__ == b_type__ && b_type__ == c_type__, \ + ET_TENSOR_CHECK_PREFIX__ ": dtype={%" PRId8 ", %" PRId8 ", %" PRId8 \ + "}", \ + static_cast(a_type__), \ + static_cast(b_type__), \ + static_cast(c_type__)); \ + } while (0) + +/** + * Asserts that all tensors have the same shape and dtype. + * + * This macro should produce less code/data than calling the SHAPE and DTYPE + * macros independently, because it only calls ET_CHECK_MSG once. + */ +#define ET_CHECK_SAME_SHAPE_AND_DTYPE2(a__, b__) \ + do { \ + const size_t a_numel__ = (a__).numel(); \ + const size_t b_numel__ = (b__).numel(); \ + const size_t a_dim__ = (a__).dim(); \ + const size_t b_dim__ = (b__).dim(); \ + const ::executorch::aten::ScalarType a_type__ = (a__).scalar_type(); \ + const ::executorch::aten::ScalarType b_type__ = (b__).scalar_type(); \ + \ + ET_CHECK_MSG( \ + a_numel__ == b_numel__ && \ + ((a_numel__ == 1 && b_numel__ == 1) || a_dim__ == b_dim__) && \ + a_type__ == b_type__, \ + ET_TENSOR_CHECK_PREFIX__ \ + ": numel={%zu, %zu}, dim={%zu, %zu}, dtype={%" PRId8 ", %" PRId8 "}", \ + a_numel__, \ + b_numel__, \ + a_dim__, \ + b_dim__, \ + static_cast(a_type__), \ + static_cast(b_type__)); \ + for (size_t dim__ = 0; dim__ < ET_MIN2(a_dim__, b_dim__); ++dim__) { \ + size_t a_size__ = (a__).size(dim__); \ + size_t b_size__ = (b__).size(dim__); \ + ET_CHECK_MSG( \ + a_size__ == b_size__, \ + ET_TENSOR_CHECK_PREFIX__ " at size(%zu): {%zu, %zu}", \ + dim__, \ + a_size__, \ + b_size__); \ + } \ + } while (0) + +#define ET_CHECK_SAME_SHAPE_AND_DTYPE3(a__, b__, c__) \ + do { \ + const size_t a_numel__ = (a__).numel(); \ + const size_t b_numel__ = (b__).numel(); \ + const size_t c_numel__ = (c__).numel(); \ + const size_t a_dim__ = (a__).dim(); \ + const size_t b_dim__ = (b__).dim(); \ + const size_t c_dim__ = (c__).dim(); \ + const ::executorch::aten::ScalarType a_type__ = (a__).scalar_type(); \ + const ::executorch::aten::ScalarType b_type__ = (b__).scalar_type(); \ + const ::executorch::aten::ScalarType c_type__ = (c__).scalar_type(); \ + \ + ET_CHECK_MSG( \ + a_numel__ == b_numel__ && b_numel__ == c_numel__ && \ + ((a_numel__ == 1 && b_numel__ == 1 && c_numel__ == 1) || \ + (a_dim__ == b_dim__ && b_dim__ == c_dim__)) && \ + a_type__ == b_type__ && b_type__ == c_type__, \ + ET_TENSOR_CHECK_PREFIX__ \ + ": numel={%zu, %zu, %zu}, dim={%zu, %zu, %zu}, " \ + "dtype={%" PRId8 ", %" PRId8 ", %" PRId8 "}", \ + a_numel__, \ + b_numel__, \ + c_numel__, \ + a_dim__, \ + b_dim__, \ + c_dim__, \ + static_cast(a_type__), \ + static_cast(b_type__), \ + static_cast(c_type__)); \ + for (size_t dim__ = 0; dim__ < ET_MIN3(a_dim__, b_dim__, c_dim__); \ + ++dim__) { \ + size_t a_size__ = (a__).size(dim__); \ + size_t b_size__ = (b__).size(dim__); \ + size_t c_size__ = (c__).size(dim__); \ + ET_CHECK_MSG( \ + a_size__ == b_size__ && b_size__ == c_size__, \ + ET_TENSOR_CHECK_PREFIX__ " at size(%zu): {%zu, %zu, %zu}", \ + dim__, \ + a_size__, \ + b_size__, \ + c_size__); \ + } \ + } while (0) + +/** + * Assert that the input tensor is contiguous tensor. + */ +#define ET_CHECK_CONTIGUOUS(a__) \ + do { \ + const ::executorch::aten::ArrayRef \ + strides = a__.strides(); \ + const ::executorch::aten::ArrayRef sizes = \ + a__.sizes(); \ + ET_CHECK_MSG( \ + strides[strides.size() - 1] == 1, \ + "The stride of the last dimension shall be 1 for contiguous tensor, " \ + "not %d", \ + strides[strides.size() - 1]); \ + for (size_t i = strides.size() - 1; i > 0; i--) { \ + ET_CHECK_MSG( \ + strides[i - 1] == strides[i] * sizes[i], \ + "The stride of the %zu-th dimension shall equal to " \ + "strides[%zu] * sizes[%zu], now is %d and %d", \ + i - 1, \ + i, \ + i, \ + strides[i - 1], \ + strides[i] * sizes[i]); \ + } \ + } while (0) + +/** + * Assert the input two tensors share same strides. + * Noted that this function does not make any check or promise on the contiguity + * of any input tensors. + */ +#define ET_CHECK_SAME_STRIDES2(a__, b__) \ + do { \ + ET_CHECK_MSG( \ + a__.dim() == b__.dim(), \ + "Two tensors shall have same number of strides, but not %zu and %zu.", \ + a__.dim(), \ + b__.dim()); \ + const ::executorch::aten::ArrayRef \ + a_strides = a__.strides(); \ + const ::executorch::aten::ArrayRef \ + b_strides = b__.strides(); \ + for (const auto i : c10::irange(a__.dim())) { \ + ET_CHECK_MSG( \ + a_strides[i] == b_strides[i], \ + "a.strides()[%zu] shall equal to b.strides()[%zu], " \ + "but now is %d and %d.", \ + i, \ + i, \ + (int32_t)a_strides[i], \ + (int32_t)b_strides[i]); \ + } \ + } while (0) + +/** + * Assert the input three tensors share same strides. + * Noted that this function does not make any check or promise on the contiguity + * of any input tensors. + */ +#define ET_CHECK_SAME_STRIDES3(a__, b__, c__) \ + do { \ + ET_CHECK_MSG( \ + a__.dim() == b__.dim() && b__.dim() == c__.dim(), \ + "Three tensors shall have same number of strides, " \ + "but not %zu, %zu and %zu.", \ + a__.dim(), \ + b__.dim(), \ + c__.dim()); \ + const ::executorch::aten::ArrayRef \ + a_strides = a__.strides(); \ + const ::executorch::aten::ArrayRef \ + b_strides = b__.strides(); \ + const ::executorch::aten::ArrayRef \ + c_strides = c__.strides(); \ + for (const auto i : c10::irange(a__.dim())) { \ + ET_CHECK_MSG( \ + a_strides[i] == b_strides[i] && b_strides[i] == c_strides[i], \ + "a_strides[%zu], b_strides[%zu] and c_strides[%zu] " \ + "shall share same value, but now is %d, %d and %d", \ + i, \ + i, \ + i, \ + (int32_t)a_strides[i], \ + (int32_t)b_strides[i], \ + (int32_t)c_strides[i]); \ + } \ + } while (0) + +#define ET_CHECK_DEFAULT_OR_CHANNELSLAST_DIMORDER(t__) \ + do { \ + ET_CHECK_MSG( \ + is_contiguous_dim_order( \ + t__.dim_order().data(), t__.dim_order().size()) || \ + is_channels_last_dim_order( \ + t__.dim_order().data(), t__.dim_order().size()), \ + "Tensor must have default or channels last dim order"); \ + } while (0) + +/** + * DEPRECATED: Please use ET_CHECK_OR_RETURN_FALSE instead and provide + * an informative message. (For example, the values of any variables used in + * `cond` would not be reported automatically by this macro.) + * + * A convenience macro to be used in utility functions that check whether input + * tensor(s) are valid, which are expected to return a boolean. Checks whether + * `cond` is true; if not, log the failed check and return false. + * + * @param[in] cond the condition to check + */ +#define ET_LOG_AND_RETURN_IF_FALSE(cond) ET_CHECK_OR_RETURN_FALSE(cond, "") + +/** + * DEPRECATED: Please use ET_CHECK_OR_RETURN_FALSE instead. + */ +#define ET_LOG_MSG_AND_RETURN_IF_FALSE ET_CHECK_OR_RETURN_FALSE + +/** + * If `cond` is false, log `cond` and return from the kernel with a failure + * state set. + * + * @param[in] context the runtime context + * @param[in] cond the condition to check + * @param[in] error torch::executor::Error enum value (e.g `InvalidArgument`) + * @param[in] retval return value of the kernel to allow for early exit + */ +#define ET_KERNEL_CHECK(context, cond, error, retval) \ + do { \ + if (!(cond)) { \ + ET_LOG(Error, "Check failed (%s): ", #cond); \ + context.fail(torch::executor::Error::error); \ + return retval; \ + } \ + } while (false) + +/** + * If `cond` is false, log `message` and return from the kernel with a failure + * state set. + * + * @param[in] context the runtime context + * @param[in] cond the condition to check + * @param[in] error torch::executor::Error enum value (e.g `InvalidArgument`) + * @param[in] retval return value of the kernel to allow for early exit + */ +#define ET_KERNEL_CHECK_MSG(context, cond, error, retval, message, ...) \ + do { \ + if (!(cond)) { \ + ET_LOG(Error, "Check failed (%s): " message, #cond, ##__VA_ARGS__); \ + context.fail(torch::executor::Error::error); \ + return retval; \ + } \ + } while (false) + +/** + * Convenience macro to extract a scalar tensor into a value + */ +#define ET_EXTRACT_SCALAR_TENSOR(scalar_tensor, out_val) \ + ET_CHECK_MSG( \ + extract_scalar_tensor(scalar_tensor, &out_val), \ + #scalar_tensor " could not be extracted: wrong type or out of range"); + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +// +// Utility functions for checking tensor attributes +// +// + +/* + * Returns true if the given dimension value is between -upper_bound and + * upper_bound - 1, inclusive. + */ +inline bool dim_is_valid(int64_t dim, int64_t upper_bound) { + ET_CHECK_OR_RETURN_FALSE( + dim >= -upper_bound && dim < upper_bound, + "Dimension %" PRId64 + " is out of range. Dimension should be between %" PRId64 " and %" PRId64 + ", inclusive.", + dim, + -upper_bound, + upper_bound - 1); + + return true; +} + +/* + * Returns the tensor's number of dimensions, except when the tensor is zero + * dimensional. In this case, it returns 1. This is used to properly handle + * the zero dimensional tensors in some kernels, that treat them as 1D tensors + * with a single element. + */ +inline ssize_t nonzero_dim(const executorch::aten::Tensor& tensor) { + return tensor.dim() == 0 ? 1 : tensor.dim(); +} + +/* + * Returns the size along a dimension dim, except when the tensor is zero + * dimensional. In this case, it returns 1. This is used to properly handle + * the zero dimensional tensors in some kernels, that treat them as 1D tensors + * with a single element. + */ +inline ssize_t nonempty_size( + const executorch::aten::Tensor& tensor, + ssize_t dim) { + return tensor.dim() == 0 ? 1 : tensor.size(dim); +} + +inline bool tensor_can_cast_to( + executorch::aten::Tensor a, + executorch::aten::ScalarType dtype) { + ET_CHECK_OR_RETURN_FALSE( + ::torch::executor::canCast(a.scalar_type(), dtype), + "Tensor of dtype %s cannot cast to dtype %s", + ::torch::executor::toString(a.scalar_type()), + ::torch::executor::toString(dtype)); + + return true; +} + +inline bool tensor_is_bool_type(executorch::aten::Tensor t) { + ET_CHECK_OR_RETURN_FALSE( + t.scalar_type() == executorch::aten::ScalarType::Bool, + "Expected to find bool type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_type( + executorch::aten::Tensor t, + executorch::aten::ScalarType dtype) { + ET_CHECK_OR_RETURN_FALSE( + t.scalar_type() == dtype, + "Expected to find %s type, but tensor has type %s", + ::torch::executor::toString(dtype), + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_type( + executorch::aten::Tensor t, + executorch::aten::ScalarType dtype, + executorch::aten::ScalarType dtype2) { + ET_LOG_MSG_AND_RETURN_IF_FALSE( + t.scalar_type() == dtype || t.scalar_type() == dtype2, + "Expected to find %s or %s type, but tensor has type %s", + ::torch::executor::toString(dtype), + ::torch::executor::toString(dtype2), + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_type( + executorch::aten::Tensor t, + executorch::aten::ScalarType dtype, + executorch::aten::ScalarType dtype2, + executorch::aten::ScalarType dtype3) { + ET_LOG_MSG_AND_RETURN_IF_FALSE( + t.scalar_type() == dtype || t.scalar_type() == dtype2 || + t.scalar_type() == dtype3, + "Expected to find %s, %s, or %s type, but tensor has type %s", + ::torch::executor::toString(dtype), + ::torch::executor::toString(dtype2), + ::torch::executor::toString(dtype3), + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_integral_type( + executorch::aten::Tensor t, + bool includeBool = false) { + ET_CHECK_OR_RETURN_FALSE( + ::torch::executor::isIntegralType(t.scalar_type(), includeBool), + "Expected to find a integral type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_floating_type(executorch::aten::Tensor t) { + ET_CHECK_OR_RETURN_FALSE( + ::torch::executor::isFloatingType(t.scalar_type()), + "Expected to find a floating type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_real_type(executorch::aten::Tensor t) { + ET_CHECK_OR_RETURN_FALSE( + ::torch::executor::isRealType(t.scalar_type()), + "Expected to find a real type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_realh_type(executorch::aten::Tensor t) { + ET_CHECK_OR_RETURN_FALSE( + ::torch::executor::isRealHType(t.scalar_type()), + "Expected to find a real type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_realhbf16_type(executorch::aten::Tensor t) { + ET_CHECK_OR_RETURN_FALSE( + executorch::runtime::isRealHBF16Type(t.scalar_type()), + "Expected to find a real type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_realhb_type(executorch::aten::Tensor t) { + ET_CHECK_OR_RETURN_FALSE( + ::torch::executor::isRealHBType(t.scalar_type()), + "Expected to find a real type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_realhbbf16_type(executorch::aten::Tensor t) { + ET_CHECK_OR_RETURN_FALSE( + executorch::runtime::isRealHBBF16Type(t.scalar_type()), + "Expected to find a real type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_complex_type(executorch::aten::Tensor t) { + ET_CHECK_OR_RETURN_FALSE( + ::torch::executor::isComplexType(t.scalar_type()), + "Expected to find a complex type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensor_is_bits_type(executorch::aten::Tensor t) { + ET_CHECK_OR_RETURN_FALSE( + ::torch::executor::isBitsType(t.scalar_type()), + "Expected to find a bits type, but tensor has type %s", + ::torch::executor::toString(t.scalar_type())); + + return true; +} + +inline bool tensors_have_same_dtype( + executorch::aten::Tensor a, + executorch::aten::Tensor b) { + ET_CHECK_OR_RETURN_FALSE( + a.scalar_type() == b.scalar_type(), + ET_TENSOR_CHECK_PREFIX__ ": dtype={%s, %s}", + ::torch::executor::toString(a.scalar_type()), + ::torch::executor::toString(b.scalar_type())); + return true; +} + +inline bool tensors_have_same_dtype( + executorch::aten::Tensor a, + executorch::aten::Tensor b, + executorch::aten::Tensor c) { + ET_CHECK_OR_RETURN_FALSE( + a.scalar_type() == b.scalar_type() && b.scalar_type() == c.scalar_type(), + ET_TENSOR_CHECK_PREFIX__ ": dtype={%s, %s, %s}", + ::torch::executor::toString(a.scalar_type()), + ::torch::executor::toString(b.scalar_type()), + ::torch::executor::toString(c.scalar_type())); + return true; +} + +inline bool tensor_is_rank(executorch::aten::Tensor t, size_t rank) { + ET_CHECK_OR_RETURN_FALSE( + static_cast(t.dim()) == rank, + "Expected tensor.dim() to be %zu, but got %zu", + static_cast(rank), + static_cast(t.dim())); + + return true; +} + +inline bool tensor_has_rank_greater_or_equal_to( + executorch::aten::Tensor t, + size_t rank) { + ET_CHECK_OR_RETURN_FALSE( + static_cast(t.dim()) >= rank, + "Expected tensor.dim() to be >= %zu, but got %zu", + static_cast(rank), + static_cast(t.dim())); + + return true; +} + +inline bool tensor_has_rank_smaller_or_equal_to( + executorch::aten::Tensor t, + size_t rank) { + ET_CHECK_OR_RETURN_FALSE( + static_cast(t.dim()) <= rank, + "Expected tensor.dim() to be <= %zu, but got %zu", + static_cast(rank), + static_cast(t.dim())); + + return true; +} + +inline bool tensor_has_dim(executorch::aten::Tensor t, int64_t d) { + if (t.dim() == 0) { + ET_CHECK_OR_RETURN_FALSE( + d == 0 || d == -1, + "dim must be 0 or -1 for 0-dim tensor, got %" PRId64, + d); + } else { + ET_CHECK_OR_RETURN_FALSE( + d > 0 ? d < t.dim() : t.dim() + d >= 0, + "%zu-dim tensor does not have dim at index %zu", + static_cast(t.dim()), + static_cast(d)); + } + return true; +} + +inline bool tensor_has_non_empty_dim(executorch::aten::Tensor t, int64_t d) { + const size_t udim = ET_NORMALIZE_IX(d, t.dim()); + ET_LOG_AND_RETURN_IF_FALSE(tensor_has_dim(t, d)); + ET_LOG_AND_RETURN_IF_FALSE(t.size(udim) != 0); + return true; +} + +inline bool +tensor_dim_has_index(executorch::aten::Tensor t, int64_t d, int64_t ix) { + // Indexing ops don't support zero-dim tensors + ET_CHECK(t.dim() != 0); + if (d < 0) { + d += t.dim(); + } + // Dimension must have been already checked by tensor_has_dim + ET_CHECK(d >= 0 && d < t.dim()); + + ET_CHECK_OR_RETURN_FALSE( + ix >= -t.size(d) && ix < t.size(d), + "index %" PRId64 " out of range [-%zu,%zu) at dimension %" PRId64 ")", + ix, + static_cast(t.size(d)), + static_cast(t.size(d)), + d); + return true; +} + +inline bool tensors_have_same_size_at_dims( + executorch::aten::Tensor a, + size_t dim_a, + executorch::aten::Tensor b, + size_t dim_b) { + ET_CHECK_OR_RETURN_FALSE( + dim_a < static_cast(a.dim()), + "Cannot retrieve dim %zu from tensor with dim %zu", + static_cast(dim_a), + static_cast(a.dim())); + ET_CHECK_OR_RETURN_FALSE( + dim_b < static_cast(b.dim()), + "Cannot retrieve dim %zu from tensor with dim %zu", + static_cast(dim_b), + static_cast(b.dim())); + ET_CHECK_OR_RETURN_FALSE( + a.size(dim_a) == b.size(dim_b), + ET_TENSOR_CHECK_PREFIX__ + ": a.size(%zu) = %zu does not match b.size(%zu) = %zu", + static_cast(dim_a), + static_cast(a.size(dim_a)), + static_cast(dim_b), + static_cast(b.size(dim_b))); + + return true; +} + +inline bool tensors_have_same_shape( + executorch::aten::Tensor a, + executorch::aten::Tensor b) { + if (a.numel() == 1 && b.numel() == 1) { + // PyTorch operators treat all scalar tensors as the same shape even if + // they have different dims. + return true; + } + if (!(a.sizes() == b.sizes() && a.numel() == b.numel())) { + ET_LOG( + Error, + ET_TENSOR_CHECK_PREFIX__ ": numel=(%zu, %zu), dim=(%zu, %zu)", + static_cast(a.numel()), + static_cast(b.numel()), + static_cast(a.dim()), + static_cast(b.dim())); + // Using [[maybe_unused]] as ET_LOG may not trigger based on verbosity + for ([[maybe_unused]] const auto d : + c10::irange(ET_MIN2(a.dim(), b.dim()))) { + ET_LOG( + Error, + " size(%zu): (%zu, %zu)", + static_cast(d), + static_cast(a.size(d)), + static_cast(b.size(d))); + } + + return false; + } + + return true; +} + +inline bool tensors_have_same_shape( + executorch::aten::Tensor a, + executorch::aten::Tensor b, + executorch::aten::Tensor c) { + if (a.numel() == 1 && b.numel() == 1 && c.numel() == 1) { + // PyTorch operators treat all scalar tensors as the same shape even if + // they have different dims. + return true; + } + bool cond1 = (a.sizes() == b.sizes()) && (a.numel() == b.numel()); + bool cond2 = (b.sizes() == c.sizes()) && (b.numel() == c.numel()); + + if (!(cond1 && cond2)) { + ET_LOG( + Error, + ET_TENSOR_CHECK_PREFIX__ ": numel=(%zu, %zu, %zu), dim=(%zu, %zu, %zu)", + static_cast(a.numel()), + static_cast(b.numel()), + static_cast(c.numel()), + static_cast(a.dim()), + static_cast(b.dim()), + static_cast(c.dim())); + for ([[maybe_unused]] const auto d : + c10::irange(ET_MIN3(a.dim(), b.dim(), c.dim()))) { + ET_LOG( + Error, + " size(%zu): (%zu, %zu, %zu)", + static_cast(d), + static_cast(a.size(d)), + static_cast(b.size(d)), + static_cast(c.size(d))); + } + + return false; + } + + return true; +} + +inline bool tensors_have_same_shape_and_dtype( + executorch::aten::Tensor a, + executorch::aten::Tensor b) { + return tensors_have_same_shape(a, b) && tensors_have_same_dtype(a, b); +} + +inline bool tensors_have_same_shape_and_dtype( + executorch::aten::Tensor a, + executorch::aten::Tensor b, + executorch::aten::Tensor c) { + return tensors_have_same_shape(a, b, c) && tensors_have_same_dtype(a, b, c); +} + +inline bool tensor_has_expected_size( + executorch::aten::Tensor a, + executorch::aten::ArrayRef expected_sizes) { + if (!(a.sizes() == expected_sizes)) { + ET_LOG( + Error, + ET_TENSOR_CHECK_PREFIX__ ": dim=(%zu, %zu)", + static_cast(a.dim()), + static_cast(expected_sizes.size())); + size_t a_dim = static_cast(a.dim()); + size_t expected_dim = static_cast(expected_sizes.size()); + for ([[maybe_unused]] const auto d : + c10::irange(ET_MIN2(a_dim, expected_dim))) { + ET_LOG( + Error, + " size(%zu): (%zu, %zu)", + static_cast(d), + static_cast(a.size(d)), + static_cast(expected_sizes[d])); + } + + return false; + } + return true; +} + +inline bool tensors_have_same_strides( + executorch::aten::Tensor a, + executorch::aten::Tensor b) { + if (a.strides() != b.strides()) { + ET_LOG( + Error, + ET_TENSOR_CHECK_PREFIX__ ": dim=(%zu, %zu)", + static_cast(a.dim()), + static_cast(b.dim())); + for ([[maybe_unused]] const auto d : + c10::irange(ET_MIN2(a.dim(), b.dim()))) { + ET_LOG( + Error, + " stride(%zu): (%zu, %zu)", + static_cast(d), + static_cast(a.strides()[d]), + static_cast(b.strides()[d])); + } + + return false; + } + return true; +} + +inline bool tensors_have_same_strides( + executorch::aten::Tensor a, + executorch::aten::Tensor b, + executorch::aten::Tensor c) { + if (!(a.strides() == b.strides() && b.strides() == c.strides())) { + ET_LOG( + Error, + ET_TENSOR_CHECK_PREFIX__ ": dim=(%zu, %zu, %zu)", + static_cast(a.dim()), + static_cast(b.dim()), + static_cast(c.dim())); + for ([[maybe_unused]] const auto d : + c10::irange(ET_MIN3(a.dim(), b.dim(), c.dim()))) { + ET_LOG( + Error, + " stride(%zu): (%zu, %zu, %zu)", + static_cast(d), + static_cast(a.strides()[d]), + static_cast(b.strides()[d]), + static_cast(c.strides()[d])); + } + + return false; + } + return true; +} + +inline bool tensor_is_contiguous(executorch::aten::Tensor t) { + const auto strides = t.strides(); + const auto sizes = t.sizes(); + // If tensor is 0-dim (i.e. a scalar tensor) it is contiguous + if (strides.size() == 0) { + return true; + } + ET_CHECK_OR_RETURN_FALSE( + strides[strides.size() - 1] == 1, + "Tensor is not contiguous; the stride of the last dimension must be 1, " + "but got %zu", + static_cast(strides[strides.size() - 1])); + for (int i = strides.size() - 1; i > 0; --i) { + ET_CHECK_OR_RETURN_FALSE( + strides[i - 1] == strides[i] * sizes[i], + "Tensor is not contiguous; the stride of dim %zu should be equal to " + "strides[%zu] * sizes[%zu] = %zu, but found %zu", + static_cast(i - 1), + static_cast(i), + static_cast(i), + static_cast(strides[i] * sizes[i]), + static_cast(strides[i - 1])); + } + return true; +} + +inline bool tensors_have_same_rank( + executorch::aten::Tensor a, + executorch::aten::Tensor b) { + ET_CHECK_OR_RETURN_FALSE( + a.dim() == b.dim(), + ET_TENSOR_CHECK_PREFIX__ ": rank={%zd, %zd}", + ssize_t(a.dim()), + ssize_t(b.dim())); + return true; +} + +inline bool tensor_is_scalar(executorch::aten::Tensor t) { + return t.dim() == 0 && t.numel() == 1; +} + +/// Returns the product of dim[0:dim), not including dim. +inline size_t getLeadingDims( + const executorch::aten::Tensor& tensor, + int64_t dim) { + ET_CHECK_MSG( + dim >= 0 && dim <= tensor.dim(), + "Ending dimension %" PRId64 + " should be in the range [0, tensor.dim() %zd].", + dim, + ssize_t(tensor.dim())); + size_t dims = 1; + for (const auto i : c10::irange(dim)) { + size_t next_dims; + ET_CHECK_MSG( + !c10::mul_overflows( + dims, static_cast(tensor.size(i)), &next_dims), + "Overflow computing leading dims at dimension %zd", + (ssize_t)i); + dims = next_dims; + } + return dims; +} + +/// Returns the product of dim[dim+1:]. +inline size_t getTrailingDims( + const executorch::aten::Tensor& tensor, + int64_t dim) { + ET_CHECK_MSG( + dim >= -1 && dim < tensor.dim(), + "Starting dimension %" PRId64 + " should be in the range [-1, tensor.dim() -1 %zd).", + dim, + ssize_t(tensor.dim())); + size_t dims = 1; + for (size_t i = dim + 1; i < static_cast(tensor.dim()); ++i) { + size_t next_dims; + ET_CHECK_MSG( + !c10::mul_overflows( + dims, static_cast(tensor.size(i)), &next_dims), + "Overflow computing trailing dims at dimension %zu", + i); + dims = next_dims; + } + return dims; +} + +/** + * Given a N-dimensional tensor coordinate, return a linear index that can be + * used to access the corresponding element in the tensor's data buffer. + * + * @param[in] tensor The tensor that will be indexed + * @param[in] coordinate A n-dimensional array representing the coordinate to + * index. It is assumed that the array has kTensorDimensionLimit elements. + * @param[out] index The linear index to element at the specified coordinate + * in the tensor. + */ +inline size_t coordinateToIndex( + const executorch::aten::Tensor& tensor, + const size_t* const coordinate) { + size_t index = 0; + for (const auto d : c10::irange(tensor.dim())) { + index += coordinate[d] * getTrailingDims(tensor, d); + } + return index; +} + +/** + * Produce a memoized array for use with repeated calls to + * coordinateToIndexWithTrailingDimsMemo, which will be faster than + * repeated calls to coordinateToIndex. + */ +inline void memoizeTrailingDims( + const executorch::aten::Tensor& tensor, + size_t trailing_dims_memo[kTensorDimensionLimit]) { + const auto tensorDim = tensor.dim(); + size_t dims = 1; + for (int ii = tensorDim - 1; ii >= 0; --ii) { + trailing_dims_memo[ii] = dims; + dims *= static_cast(tensor.size(ii)); + } +} + +/** + * Like coordinateToIndex, but faster for repeated calls with the same + * tensor. trailing_dims_memo must be produced by a call to + * memoizeTrailingDims. + */ +inline size_t coordinateToIndexWithTrailingDimsMemo( + const executorch::aten::Tensor& tensor, + const size_t* const coordinate, + const size_t trailing_dims_memo[kTensorDimensionLimit]) { + size_t index = 0; + for (const auto d : c10::irange(tensor.dim())) { + index += coordinate[d] * trailing_dims_memo[d]; + } + return index; +} + +/** + * Given the linear index return the N-dimensional tensor coordinate. This is + * the inverse operation of coordinateToIndex. + * + * @param[in] tensor The tensor that will be indexed + * @param[in] index The linear index to element at the specified coordinate in + * the tensor. + * @param[out] coordinate A n-dimensional array representing the coordinate to + * index. It is assumed that the array has kTensorDimensionLimit elements. + * @returns void + */ +inline void indexToCoordinate( + const executorch::aten::Tensor& tensor, + size_t index, + size_t* coordinate) { + ET_CHECK(index < static_cast(tensor.numel())); + for (const auto i : c10::irange(tensor.dim())) { + auto dim = tensor.dim() - 1 - i; + size_t dim_size = tensor.size(dim); + coordinate[dim] = index % dim_size; + index /= dim_size; + } +} + +/** + * Extracts an integer value from a scalar Tensor. + * + * @param[in] tensor The source of the value to extract. + * @param[out] out_val The extracted value, on success. + * @returns `true` if a value was extracted, and sets `*out_val` to that + * value. `false` if a value could not be extracted: either it was not an + * integer Scalar Tensor, or the value of that Scalar Tensor could not be + * represented by INT_T. + */ +template < + typename INT_T, + typename std::enable_if< + std::is_integral::value && !std::is_same::value, + bool>::type = true> +bool extract_scalar_tensor(executorch::aten::Tensor tensor, INT_T* out_val) { + if (tensor.numel() != 1) { + return false; + } +#define CASE_INT_DTYPE(TENSOR_CTYPE, TENSOR_DTYPE) \ + case executorch::aten::ScalarType::TENSOR_DTYPE: { \ + const TENSOR_CTYPE val = tensor.const_data_ptr()[0]; \ + if (val < std::numeric_limits::lowest() || \ + val > std::numeric_limits::max()) { \ + return false; \ + } \ + *out_val = static_cast(val); \ + return true; \ + } + + switch (tensor.scalar_type()) { + ET_FORALL_INT_TYPES(CASE_INT_DTYPE); + default: + return false; + } +#undef CASE_INT_DTYPE +} + +/** + * Extracts a floating point value from a scalar Tensor. + * + * @param[in] tensor The source of the value to extract. + * @param[out] out_val The extracted value, on success. + * @returns `true` if a value was extracted, and sets `*out_val` to that + * value. `false` if a value could not be extracted: either it was not a + * floating point Scalar Tensor, or the value of that Scalar Tensor could not + * be represented by FLOAT_T. + */ +template < + typename FLOAT_T, + typename std::enable_if< + std::is_floating_point_v || + std::is_same_v || + std::is_same_v, + bool>::type = true> +bool extract_scalar_tensor(executorch::aten::Tensor tensor, FLOAT_T* out_val) { + if (tensor.numel() != 1) { + return false; + } +#define CASE_REAL_DTYPE(TENSOR_CTYPE, TENSOR_DTYPE) \ + case executorch::aten::ScalarType::TENSOR_DTYPE: { \ + /* ET_FORALL_REAL_TYPES guarantees TENSOR_CTYPE is a real type. */ \ + double val = \ + static_cast(tensor.const_data_ptr()[0]); \ + if (std::isfinite(val) && \ + (val < std::numeric_limits::lowest() || \ + val > std::numeric_limits::max())) { \ + return false; \ + } \ + *out_val = static_cast(val); \ + return true; \ + } + + switch (tensor.scalar_type()) { + ET_FORALL_REALHBF16_TYPES(CASE_REAL_DTYPE); + default: + return false; + } +#undef CASE_REAL_DTYPE +} + +/** + * Extracts a boolean value from a Scalar. + * + * @param[in] scalar The source of the value to extract. + * @param[out] out_val The extracted value, on success. + * @returns `true` if a value was extracted, and sets `*out_val` to that + * value. `false` if a value could not be extracted, i.e. not a boolean + */ +template < + typename BOOL_T, + typename std::enable_if::value, bool>::type = + true> +bool extract_scalar_tensor(executorch::aten::Tensor tensor, BOOL_T* out_val) { + if (tensor.scalar_type() != executorch::aten::ScalarType::Bool) { + return false; + } + if (tensor.numel() != 1) { + return false; + } + + bool val = tensor.const_data_ptr()[0]; + + *out_val = static_cast(val); + + return true; +} + +/// These APIs should not be used outside of Executor.cpp. +namespace internal { +/** + * Share t_src's data_ptr with t_dst. + */ +ET_NODISCARD Error share_tensor_data( + const executorch::aten::Tensor& t_dst, + const executorch::aten::Tensor& t_src); + +/** + * Copy t_src's data_ptr to t_dst. + */ +ET_NODISCARD Error copy_tensor_data( + const executorch::aten::Tensor& t_dst, + const executorch::aten::Tensor& t_src); + +/** + * Set the data_ptr of t to buffer. + */ +ET_NODISCARD Error set_tensor_data( + const executorch::aten::Tensor& t, + void* buffer, + size_t buffer_size); + +/** + * Reset tensor's data_ptr, clear all the storage for at::Tensor. + */ +void reset_data_ptr(const executorch::aten::Tensor& tensor); + +/** + * Resize tensor impl + */ +ET_NODISCARD Error resize_tensor_impl( + executorch::aten::TensorImpl* impl, + executorch::aten::ArrayRef new_sizes); + +} // namespace internal + +/** + * Resize a tensor to new_sizes, rank must stay the same. Currently does not + * expand the tensor if new size exceeds the current capacity. Currently + * fails an ET_CHECK if the tensor cannot be resized. + * + * WARNING: Placeholder API until discussion around runtime context is + * settled, will likely move to be a class method on a TensorResizer object + * passed in through runtimeContext. + */ +ET_NODISCARD inline Error resize_tensor( + executorch::aten::Tensor t, + executorch::aten::ArrayRef new_sizes) { + return internal::resize_tensor_impl(t.unsafeGetTensorImpl(), new_sizes); +} + +/** + * Resize a tensor to new_sizes, rank must stay the same. Currently does not + * expand the tensor if new size exceeds the current capacity. Currently + * fails an ET_CHECK if the tensor cannot be resized. + * + * WARNING: Placeholder API until discussion around runtime context is + * settled, will likely move to be a class method on a TensorResizer object + * passed in through runtimeContext. + */ +template < + typename T, + typename std::enable_if< + !std::is_same::value, + int>::type = 0> +ET_NODISCARD inline Error resize_tensor( + executorch::aten::Tensor t, + executorch::aten::ArrayRef new_sizes) { + // Need to cast the input array to an array of Tensor::SizesType + std::array + new_sizes_casted{}; + size_t new_sizes_ndim = new_sizes.size(); + ET_CHECK_OR_RETURN_ERROR( + new_sizes_ndim <= kTensorDimensionLimit, + InvalidArgument, + "new_sizes_ndim %zu is greater than kTensorDimensionLimit %zu", + new_sizes_ndim, + kTensorDimensionLimit); + for (const auto i : c10::irange(new_sizes_ndim)) { + new_sizes_casted[i] = + static_cast(new_sizes[i]); + } + + return internal::resize_tensor_impl( + t.unsafeGetTensorImpl(), {new_sizes_casted.data(), new_sizes_ndim}); +} + +/// DEPRECATED: Use `resize_tensor()` instead, which can fail non-fatally. +ET_DEPRECATED inline void resize( + executorch::aten::Tensor t, + executorch::aten::ArrayRef new_sizes) { + Error err = resize_tensor(t, new_sizes); + ET_CHECK_MSG( + err == Error::Ok, "Could not resize Tensor; see logs for details"); +} +/** + * Get dim_order of a Tensor and write it to out_dim_order. + * @param tensor The tensor where we want to get dim order from. + * @param out_dim_order Pointing to an array of DimOrderType where we write + * dim order into it. + * @param out_dim_order_size Size of the DimOrderType array. + */ +ET_NODISCARD Error get_dim_order( + const executorch::aten::Tensor& tensor, + executorch::aten::DimOrderType* out_dim_order, + size_t out_dim_order_size); + +/** + * Checks whether a tensor has a valid dim order. If the dim order could not + * be determined, then this function returns false by default. + */ +bool tensor_has_valid_dim_order(executorch::aten::Tensor t); + +/** + * Checks whether a tensor has either the default of channels last dim order. + * If the dim order could not be determined, then this function returns false + * by default. + */ +bool tensor_is_default_or_channels_last_dim_order(executorch::aten::Tensor t); + +/** + * Checks whether a tensor has the default dimension order. + * Logs an error message if the tensor does not meet the expected criteria. + * + * @param t The tensor to check the dimension order of. + * @return True if the tensor has the default dimension order, false otherwise. + */ +bool tensor_is_default_dim_order(executorch::aten::Tensor t); + +/** + * Checks whether a tensor has the channels last dimension order. + * Logs an error message if the tensor does not meet the expected criteria. + * + * @param t The tensor to check the dimension order of. + * @return True if the tensor has the channels last dimension order, false + * otherwise. + */ +bool tensor_is_channels_last_dim_order(executorch::aten::Tensor t); + +/** + * Asserts that four tensors have the same dim_order + * + * Note that this macro only tests dim order, but not others like actual data, + * sizes, etc. + * + */ +bool tensors_have_same_dim_order( + const executorch::aten::ArrayRef tensor_list); + +/** + * Asserts that two tensors have the same dim_order + * + * Note that this macro only tests dim order, but not others like actual data, + * sizes, etc. + */ + +inline bool tensors_have_same_dim_order( + const executorch::aten::Tensor& a, + const executorch::aten::Tensor& b) { + executorch::aten::Tensor tensor_list[2] = {a, b}; + return tensors_have_same_dim_order(tensor_list); +} + +/** + * Asserts that three tensors have the same dim_order + * + * Note that this macro only tests dim order, but not others like actual data, + * sizes, etc. + * + */ + +inline bool tensors_have_same_dim_order( + const executorch::aten::Tensor& a, + const executorch::aten::Tensor& b, + const executorch::aten::Tensor& c) { + executorch::aten::Tensor tensor_list[3] = {a, b, c}; + return tensors_have_same_dim_order(tensor_list); +} + +/** + * Asserts that four tensors have the same dim_order + * + * Note that this macro only tests dim order, but not others like actual data, + * sizes, etc. + * + */ + +inline bool tensors_have_same_dim_order( + const executorch::aten::Tensor& a, + const executorch::aten::Tensor& b, + const executorch::aten::Tensor& c, + const executorch::aten::Tensor& d) { + executorch::aten::Tensor tensor_list[4] = {a, b, c, d}; + return tensors_have_same_dim_order(tensor_list); +} + +/** + * Given an n-dimensional coordinate array and an array of tensor strides, + * calculates the linear index that can be used to retrieve the value at the + * given coordinates. + * @param coordinate Pointer to the array of coordinates. + * @param strides Pointer to the array of strides. + * @param ndim Number of dimensions in the tensor. + */ +inline size_t calculate_linear_index( + const executorch::aten::SizesType* coordinate, + const executorch::aten::StridesType* strides, + const size_t ndim) { + size_t index = 0; + for (const auto i : c10::irange(ndim)) { + index += coordinate[i] * strides[i]; + } + return index; +} + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::calculate_linear_index; +using ::executorch::ET_RUNTIME_NAMESPACE::coordinateToIndex; +using ::executorch::ET_RUNTIME_NAMESPACE::dim_is_valid; +using ::executorch::ET_RUNTIME_NAMESPACE::extract_scalar_tensor; +using ::executorch::ET_RUNTIME_NAMESPACE::get_dim_order; +using ::executorch::ET_RUNTIME_NAMESPACE::getLeadingDims; +using ::executorch::ET_RUNTIME_NAMESPACE::getTrailingDims; +using ::executorch::ET_RUNTIME_NAMESPACE::indexToCoordinate; +using ::executorch::ET_RUNTIME_NAMESPACE::nonempty_size; +using ::executorch::ET_RUNTIME_NAMESPACE::nonzero_dim; +using ::executorch::ET_RUNTIME_NAMESPACE::resize; +using ::executorch::ET_RUNTIME_NAMESPACE::resize_tensor; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_can_cast_to; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_dim_has_index; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_has_dim; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_has_expected_size; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_has_non_empty_dim; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_has_rank_greater_or_equal_to; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_has_rank_smaller_or_equal_to; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_has_valid_dim_order; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_bits_type; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_bool_type; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_complex_type; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_contiguous; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_default_dim_order; +using ::executorch::ET_RUNTIME_NAMESPACE:: + tensor_is_default_or_channels_last_dim_order; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_floating_type; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_integral_type; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_rank; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_real_type; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_realh_type; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_realhb_type; +using ::executorch::ET_RUNTIME_NAMESPACE::tensor_is_scalar; +using ::executorch::ET_RUNTIME_NAMESPACE::tensors_have_same_dim_order; +using ::executorch::ET_RUNTIME_NAMESPACE::tensors_have_same_dtype; +using ::executorch::ET_RUNTIME_NAMESPACE::tensors_have_same_rank; +using ::executorch::ET_RUNTIME_NAMESPACE::tensors_have_same_shape; +using ::executorch::ET_RUNTIME_NAMESPACE::tensors_have_same_shape_and_dtype; +using ::executorch::ET_RUNTIME_NAMESPACE::tensors_have_same_size_at_dims; +using ::executorch::ET_RUNTIME_NAMESPACE::tensors_have_same_strides; +using ::executorch::runtime::kTensorDimensionLimit; +namespace internal { +using ::executorch::ET_RUNTIME_NAMESPACE::internal::copy_tensor_data; +using ::executorch::ET_RUNTIME_NAMESPACE::internal::reset_data_ptr; +using ::executorch::ET_RUNTIME_NAMESPACE::internal::resize_tensor_impl; +using ::executorch::ET_RUNTIME_NAMESPACE::internal::set_tensor_data; +using ::executorch::ET_RUNTIME_NAMESPACE::internal::share_tensor_data; +} // namespace internal +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/freeable_buffer.h b/include/executorch/runtime/core/freeable_buffer.h new file mode 100644 index 0000000..87ed6f1 --- /dev/null +++ b/include/executorch/runtime/core/freeable_buffer.h @@ -0,0 +1,281 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace executorch { +namespace runtime { + +/** + * A read-only buffer than can be freed. + */ +class FreeableBuffer final { + public: + // Callback signature for the function that does the freeing. + using FreeFn = void (*)(void* context, void* data, size_t size); + using FreeUInt64SizeFn = + void (*)(void* context, uint64_t data_uint64, uint64_t size); + /// DEPRECATED: Use FreeUInt64SizeFn instead. + using FreeUInt64Fn ET_DEPRECATED = + void (*)(void* context, uint64_t data_uint64, size_t size); + + private: + using LegacyFreeUInt64Fn = + void (*)(void* context, uint64_t data_uint64, size_t size); + + // Forward declare types. + struct PointerData { + const void* data_; + FreeFn free_fn_; + }; + + struct UInt64Data { + // A pointer value cast to uint64_t. + uint64_t data_; + FreeUInt64SizeFn free_fn_; + }; + + struct LegacyUInt64Data { + uint64_t data_; + LegacyFreeUInt64Fn free_fn_; + }; + + public: + /** + * Creates an empty FreeableBuffer with size zero and a null data pointer. + */ + FreeableBuffer() + : data_(PointerData{nullptr, nullptr}), + free_fn_context_(nullptr), + size_(0) {} + + /** + * Creates a FreeableBuffer with an optional free function. + * + * @param[in] data The data of the segment, as a void*. + * @param[in] size The size of the segment data, in bytes. + * @param[in] free_fn Optional function to free the data. Guaranteed to be + * called exactly once before the FreeableBuffer is destroyed. May be + * nullptr. NOTE: This function must be thread-safe. If it modifies common + * state, the function must do its own locking. + * @param[in] free_fn_context Opaque pointer to pass as the `context` + * parameter of `free_fn`. May be nullptr. + */ + FreeableBuffer( + const void* data, + size_t size, + FreeFn free_fn, + void* free_fn_context = nullptr) + : data_(PointerData{data, free_fn}), + free_fn_context_(free_fn_context), + size_(size) {} + + /** + * Creates a FreeableBuffer with an optional free function. + * + * NOTE: most users should use the other ctor with FreeFn. + * This variant exists for situations where the FreeableBuffer points to + * memory on a different core whose pointer value is larger than the local + * core's void*. + * + * @param[in] data Pointer to the data of the segment, cast to a uint64_t + * value. + * @param[in] size The size of the segment data, in bytes. + * @param[in] free_fn Optional function to free the data. Guaranteed to be + * called exactly once before the FreeableBuffer is destroyed. May be + * nullptr. NOTE: This function must be thread-safe. If it modifies common + * state, the function must do its own locking. + * @param[in] free_fn_context Opaque pointer to pass as the `context` + * parameter of `free_fn`. May be nullptr. + */ + explicit FreeableBuffer( + const uint64_t data_uint64, + uint64_t size, + FreeUInt64SizeFn free_fn, + void* free_fn_context = nullptr) + : data_(UInt64Data{data_uint64, free_fn}), + free_fn_context_(free_fn_context), + size_(size) {} + + /// DEPRECATED: Use the FreeUInt64SizeFn ctor instead. + // Callbacks convertible to the new signature, including nullptr, use the + // non-deprecated ctor. Embedded consumers still require C++17. + // NOLINTBEGIN(facebook-modernize-sfinae-enable-if-to-concepts) + template < + typename Callback, + std::enable_if_t< + std::is_convertible_v && + !std::is_convertible_v, + int> = 0> + ET_DEPRECATED explicit FreeableBuffer( + const uint64_t data_uint64, + size_t size, + Callback&& free_fn, + void* free_fn_context = nullptr) + : data_(LegacyUInt64Data{data_uint64, std::forward(free_fn)}), + free_fn_context_(free_fn_context), + size_(size) {} + // NOLINTEND(facebook-modernize-sfinae-enable-if-to-concepts) + + /** + * Move ctor. Takes the ownership of the data previously owned by `rhs`, + * leaving `rhs` pointing to nullptr. + */ + FreeableBuffer(FreeableBuffer&& rhs) noexcept + : data_(rhs.data_), + free_fn_context_(rhs.free_fn_context_), + size_(rhs.size_) { + if (std::holds_alternative(rhs.data_)) { + rhs.data_ = PointerData{nullptr, nullptr}; + } else if (std::holds_alternative(rhs.data_)) { + rhs.data_ = UInt64Data{0, nullptr}; + } else { + rhs.data_ = LegacyUInt64Data{0, nullptr}; + } + rhs.free_fn_context_ = nullptr; + rhs.size_ = 0; + } + + ~FreeableBuffer() { + Free(); + } + + /** + * Frees the data if not already free. Safe to call multiple times. + */ + void Free() { + if (std::holds_alternative(data_)) { + PointerData& ptr_data = std::get(data_); + if (ptr_data.data_ != nullptr && ptr_data.free_fn_ != nullptr) { + // Do not need to check for truncation here, as free_fn_ is only set + // using the void* ctor. + ptr_data.free_fn_( + free_fn_context_, + const_cast(ptr_data.data_), + static_cast(size_)); + } + ptr_data.data_ = nullptr; + size_ = 0; + } else if (std::holds_alternative(data_)) { + UInt64Data& int64_data = std::get(data_); + if (int64_data.data_ != 0 && int64_data.free_fn_ != nullptr) { + int64_data.free_fn_(free_fn_context_, int64_data.data_, size_); + } + int64_data.data_ = static_cast(0); + size_ = 0; + } else { + LegacyUInt64Data& int64_data = std::get(data_); + if (int64_data.data_ != 0 && int64_data.free_fn_ != nullptr) { + // No truncation: the legacy ctor only accepts a size_t size. + int64_data.free_fn_( + free_fn_context_, int64_data.data_, static_cast(size_)); + } + int64_data.data_ = static_cast(0); + size_ = 0; + } + } + + /** + * Size of the data in bytes. Returns 0 if the data has been freed. + */ + size_t size() const { +#if SIZE_MAX < UINT64_MAX + ET_CHECK_MSG( + size_ <= SIZE_MAX, + "FreeableBuffer size exceeds size_t, please use the size_uint64() API."); +#endif + return static_cast(size_); + } + + /** + * Size of the data in bytes as a uint64_t. Returns 0 if the data has been + * freed. Only needed for uint64_t-backed buffers larger than size_t. + */ + uint64_t size_uint64() const { + return size_; + } + + /** + * Pointer to the data. Returns nullptr if the data has been freed. + */ + const void* data() const { + ET_CHECK_MSG( + std::holds_alternative(data_), + "FreeableBuffer is backed by an uint64_t, please use the data_uint64_type() API."); + return std::get(data_).data_; + } + + /** + * Pointer to the data. Returns nullptr if the data has been freed. + * Safe version of data() API that returns an ERror if the data is + * backed by int64_t instead of void*. + */ + Result data_safe() const { + ET_CHECK_OR_RETURN_ERROR( + std::holds_alternative(data_), + InvalidType, + "FreeableBuffer is backed by an uint64_t, please use the data_uint64_type() API."); + return std::get(data_).data_; + } + + /** + * Data address as a uint64_t. Returns zero if the data has been freed. + * Most users should use data(). data_uint64_type() is only helpful in + * situations where the FreeableBuffer points to memory on a different core + * whose pointer value is larger than the local core's void *. + */ + Result data_uint64_type() const { + ET_CHECK_OR_RETURN_ERROR( + std::holds_alternative(data_) || + std::holds_alternative(data_), + InvalidType, + "FreeableBuffer is backed by a void*, please use the data() API."); + if (std::holds_alternative(data_)) { + return std::get(data_).data_; + } + return std::get(data_).data_; + } + + private: + // Delete other rule-of-five methods. + FreeableBuffer(const FreeableBuffer& rhs) = delete; + FreeableBuffer& operator=(FreeableBuffer&& rhs) noexcept = delete; + FreeableBuffer& operator=(const FreeableBuffer& rhs) = delete; + + // This stores a PointerData, UInt64Data, or LegacyUInt64Data structure. Most + // users should use the PointerData variant and the void* ctor. This creates a + // FreeableBuffer backed by void*, accessed using the void* getter data(). + // The UInt64Data variant is only helpful in situations where the + // FreeableBuffer points to memory on a different core whose pointer value + // is larger than the local core's void*. + std::variant data_; + + void* free_fn_context_; + uint64_t size_; +}; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::FreeableBuffer; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/function_ref.h b/include/executorch/runtime/core/function_ref.h new file mode 100644 index 0000000..07d3d58 --- /dev/null +++ b/include/executorch/runtime/core/function_ref.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +//===- llvm/ADT/STLFunctionalExtras.h - Extras for -*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains some extension to . +// +// No library is required when using these functions. +// +//===----------------------------------------------------------------------===// +// Extra additions to +//===----------------------------------------------------------------------===// + +/// An efficient, type-erasing, non-owning reference to a callable. This is +/// intended for use as the type of a function parameter that is not used +/// after the function in question returns. +/// +/// This class does not own the callable, so it is not in general safe to store +/// a FunctionRef. + +// torch::executor: modified from llvm::function_ref +// - renamed to FunctionRef +// - removed LLVM_GSL_POINTER and LLVM_LIFETIME_BOUND macro uses +// - use namespaced internal::remove_cvref_t + +#pragma once + +#include +#include +#include + +namespace executorch::runtime { + +//===----------------------------------------------------------------------===// +// Features from C++20 +//===----------------------------------------------------------------------===// + +namespace internal { + +template +struct remove_cvref { + using type = + typename std::remove_cv::type>::type; +}; + +template +using remove_cvref_t = typename remove_cvref::type; + +} // namespace internal + +template +class FunctionRef; + +template +class FunctionRef { + Ret (*callback)(intptr_t callable, Params... params) = nullptr; + intptr_t callable; + + template + static Ret callback_fn(intptr_t callable, Params... params) { + return (*reinterpret_cast(callable))( + std::forward(params)...); + } + + public: + FunctionRef() = default; + FunctionRef(std::nullptr_t) {} + + template + FunctionRef( + Callable&& callable, + // This is not the copy-constructor. + std::enable_if_t, + FunctionRef>::value>* = nullptr, + // Functor must be callable and return a suitable type. + std::enable_if_t< + std::is_void::value || + std::is_convertible< + decltype(std::declval()(std::declval()...)), + Ret>::value>* = nullptr) + : callback(callback_fn>), + callable(reinterpret_cast(&callable)) {} + + Ret operator()(Params... params) const { + return callback(callable, std::forward(params)...); + } + + explicit operator bool() const { + return callback; + } + + bool operator==(const FunctionRef& Other) const { + return callable == Other.callable; + } +}; +} // namespace executorch::runtime diff --git a/include/executorch/runtime/core/hierarchical_allocator.h b/include/executorch/runtime/core/hierarchical_allocator.h new file mode 100644 index 0000000..00eb5b3 --- /dev/null +++ b/include/executorch/runtime/core/hierarchical_allocator.h @@ -0,0 +1,167 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace executorch { +namespace runtime { + +/** + * A group of buffers that can be used to represent a device's memory hierarchy. + */ +class HierarchicalAllocator final { + public: + /** + * Constructs a new hierarchical allocator with the given array of buffers. + * + * - Memory IDs are based on the index into `buffers`: `buffers[N]` will have + * a memory ID of `N`. + * - `buffers.size()` must be >= `MethodMeta::num_non_const_buffers()`. + * - `buffers[N].size()` must be >= `MethodMeta::non_const_buffer_size(N)`. + */ + explicit HierarchicalAllocator(Span> buffers) + : buffers_(buffers) {} + + /** + * Constructs a new hierarchical allocator with per-buffer device metadata. + * + * @param[in] buffers Same as above. May contain a mix of CPU and device + * pointers — HierarchicalAllocator only does pointer arithmetic, so + * device pointers are valid. + * @param[in] planned_buffer_devices One entry per buffer (same count as + * `buffers`), indicating the `Device` (type + index) for each buffer. + * Different buffers can target the same device type but different + * indices (e.g., `cuda:0` vs `cuda:1`). For CPU-only programs, use the + * single-arg constructor instead. + */ + HierarchicalAllocator( + Span> buffers, + Span planned_buffer_devices) + : buffers_(buffers), planned_buffer_devices_(planned_buffer_devices) { + ET_CHECK_MSG( + planned_buffer_devices.size() == buffers.size(), + "planned_buffer_devices size (%" ET_PRIsize_t + ") must match buffers size (%" ET_PRIsize_t ")", + planned_buffer_devices.size(), + buffers.size()); + } + + /** + * DEPRECATED: Use spans instead. + */ + ET_DEPRECATED HierarchicalAllocator( + uint32_t n_allocators, + MemoryAllocator* allocators) + : buffers_(to_spans(n_allocators, allocators)) {} + + /** + * Returns the address at the byte offset `offset_bytes` from the given + * buffer's base address, which points to at least `size_bytes` of memory. + * + * @param[in] memory_id The ID of the buffer in the hierarchy. + * @param[in] offset_bytes The offset in bytes into the specified buffer. + * @param[in] size_bytes The amount of memory that should be available at + * the offset. + * + * @returns On success, the address of the requested byte offset into the + * specified buffer. On failure, a non-Ok Error. + */ + ET_NODISCARD Result get_offset_address( + uint32_t memory_id, + size_t offset_bytes, + size_t size_bytes) { + // Check for integer overflow in offset_bytes + size_bytes. + size_t end_bytes = 0; + ET_CHECK_OR_RETURN_ERROR( + !c10::add_overflows(offset_bytes, size_bytes, &end_bytes), + InvalidArgument, + "Integer overflow in offset_bytes (%" ET_PRIsize_t + ") + size_bytes (%" ET_PRIsize_t ")", + offset_bytes, + size_bytes); + ET_CHECK_OR_RETURN_ERROR( + memory_id < buffers_.size(), + InvalidArgument, + "id %" PRIu32 " >= %" ET_PRIsize_t, + memory_id, + buffers_.size()); + Span buffer = buffers_[memory_id]; + ET_CHECK_OR_RETURN_ERROR( + end_bytes <= buffer.size(), + MemoryAllocationFailed, + "offset_bytes (%" ET_PRIsize_t ") + size_bytes (%" ET_PRIsize_t + ") >= allocator size (%" ET_PRIsize_t + ") " + "for memory_id %" PRIu32, + offset_bytes, + size_bytes, + buffer.size(), + memory_id); + return buffer.data() + offset_bytes; + } + + /** + * Returns per-buffer device metadata. One entry per buffer, same count as + * the `buffers` passed to the constructor. Each entry is a `Device` + * carrying both type and index, so callers can distinguish e.g. `cuda:0` + * from `cuda:1`. Empty if no device metadata was provided (CPU-only + * program). + */ + Span planned_buffer_devices() const { + return planned_buffer_devices_; + } + + private: + // TODO(T162089316): Remove the span array and to_spans once all users move to + // spans. This array is necessary to hold the pointers and sizes that were + // originally provided as MemoryAllocator instances. + static constexpr size_t kSpanArraySize = 16; + // NOTE: span_array_ must be declared before buffers_ so that it isn't + // re-initialized to zeros after initializing buffers_. + Span span_array_[kSpanArraySize]; + Span> to_spans( + uint32_t n_allocators, + MemoryAllocator* allocators) { + ET_CHECK_MSG( + n_allocators <= kSpanArraySize, + "n_allocators %" PRIu32 " > %zu", + n_allocators, + kSpanArraySize); + for (const auto i : c10::irange(n_allocators)) { + span_array_[i] = + Span(allocators[i].base_address(), allocators[i].size()); + } + return {span_array_, n_allocators}; + } + + /// The underlying buffers. + Span> buffers_; + + /// Per-buffer device metadata. Empty when no device info was provided + /// (CPU-only program). + Span planned_buffer_devices_; +}; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::HierarchicalAllocator; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/memory_allocator.h b/include/executorch/runtime/core/memory_allocator.h new file mode 100644 index 0000000..4d8f8da --- /dev/null +++ b/include/executorch/runtime/core/memory_allocator.h @@ -0,0 +1,249 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include + +#include +#include +#include + +namespace executorch { +namespace runtime { + +/** + * A class that does simple allocation based on a size and returns the pointer + * to the memory address. It bookmarks a buffer with certain size. The + * allocation is simply checking space and growing the cur_ pointer with each + * allocation request. + * + * Simple example: + * + * // User allocates a 100 byte long memory in the heap. + * uint8_t* memory_pool = malloc(100 * sizeof(uint8_t)); + * MemoryAllocator allocator(100, memory_pool) + * // Pass allocator object in the Executor + * + * Underneath the hood, ExecuTorch will call + * allocator.allocate() to keep iterating cur_ pointer + */ +class MemoryAllocator { + public: + /** + * Default alignment of memory returned by this class. Ensures that pointer + * fields of structs will be aligned. Larger types like `long double` may not + * be, however, depending on the toolchain and architecture. + */ + static constexpr size_t kDefaultAlignment = alignof(void*); + + /** + * Constructs a new memory allocator of a given `size`, starting at the + * provided `base_address`. + * + * @param[in] size The size in bytes of the buffer at `base_address`. + * @param[in] base_address The buffer to allocate from. Does not take + * ownership of this buffer, so it must be valid for the lifetime of of + * the MemoryAllocator. + */ + MemoryAllocator(uint32_t size, uint8_t* base_address) + : begin_(base_address), + end_( + base_address + ? (UINTPTR_MAX - reinterpret_cast(base_address) >= + size + ? base_address + size + : nullptr) + : nullptr), + cur_(base_address), + size_(size) { + ET_CHECK_MSG( + base_address || size == 0, + "Base address is null but size=%" PRIu32, + size); + ET_CHECK_MSG( + !base_address || size == 0 || + (UINTPTR_MAX - reinterpret_cast(base_address) >= size), + "Address space overflow in allocator"); + } + + virtual ~MemoryAllocator() = default; + + /** + * Allocates `size` bytes of memory. + * + * @param[in] size Number of bytes to allocate. + * @param[in] alignment Minimum alignment for the returned pointer. Must be a + * power of 2. + * + * @returns Aligned pointer to the allocated memory on success. + * @retval nullptr Not enough memory, or `alignment` was not a power of 2. + */ + virtual void* allocate(size_t size, size_t alignment = kDefaultAlignment) { + if ET_UNLIKELY (!begin_ || !end_) { + ET_LOG(Error, "allocate() on zero-capacity allocator"); + return nullptr; + } + if (!isPowerOf2(alignment)) { + ET_LOG(Error, "Alignment %zu is not a power of 2", alignment); + return nullptr; + } + + // The allocation will occupy [start, end), where the start is the next + // position that's a multiple of alignment. + uint8_t* start = alignPointer(cur_, alignment); + size_t padding = static_cast(start - cur_); + size_t available = static_cast(end_ - cur_); + if ET_UNLIKELY (padding > available || size > available - padding) { + ET_LOG( + Error, + "Memory allocation failed: %zuB requested (adjusted for alignment), %zuB available", + padding + size, + available); + return nullptr; + } + uint8_t* end = start + size; + + // Otherwise, record how many bytes were used, advance cur_ to the new end, + // and then return start. Note that the number of bytes used is (end - cur_) + // instead of (end - start) because start > cur_ if there is a misalignment + EXECUTORCH_TRACK_ALLOCATION(prof_id_, end - cur_); + cur_ = end; + return static_cast(start); + } + + /** + * Allocates a buffer large enough for an instance of type T. Note that the + * memory will not be initialized. + * + * Example: + * @code + * auto p = memory_allocator->allocateInstance(); + * @endcode + * + * @param[in] alignment Minimum alignment for the returned pointer. Must be a + * power of 2. Defaults to the natural alignment of T. + * + * @returns Aligned pointer to the allocated memory on success. + * @retval nullptr Not enough memory, or `alignment` was not a power of 2. + */ + template + T* allocateInstance(size_t alignment = alignof(T)) { + return static_cast(this->allocate(sizeof(T), alignment)); + } + + /** + * Allocates `size` number of chunks of type T, where each chunk is of size + * equal to sizeof(T) bytes. + * + * @param[in] size Number of memory chunks to allocate. + * @param[in] alignment Minimum alignment for the returned pointer. Must be a + * power of 2. Defaults to the natural alignment of T. + * + * @returns Aligned pointer to the allocated memory on success. + * @retval nullptr Not enough memory, or `alignment` was not a power of 2. + */ + template + T* allocateList(size_t size, size_t alignment = alignof(T)) { + // Some users of this method allocate lists of pointers, causing the next + // line to expand to `sizeof(type *)`, which triggers a clang-tidy warning. + // NOLINTNEXTLINE(bugprone-sizeof-expression) + size_t bytes_size = 0; + bool overflow = c10::mul_overflows(size, sizeof(T), &bytes_size); + if (overflow) { + ET_LOG( + Error, + "Failed to allocate list: size(%zu) * sizeof(T)(%zu) overflowed", + size, + sizeof(T)); + return nullptr; + } + return static_cast(this->allocate(bytes_size, alignment)); + } + + // Returns the allocator memory's base address. + virtual uint8_t* base_address() const { + return begin_; + } + + // Returns the total size of the allocator's memory buffer. + virtual uint32_t size() const { + return size_; + } + + // Returns the number of bytes currently allocated from this allocator. The + // default implementation reports the bump cursor's offset from the base + // (cur_ - begin_); subclasses backed by a different allocator should override + // this to match their own accounting. + virtual size_t used_size() const { + return static_cast(cur_ - begin_); + } + + // Returns the number of bytes still available for allocation, not accounting + // for any alignment padding a future allocation may require. The default + // implementation reports end_ - cur_; subclasses should override to stay + // consistent with used_size(). + virtual size_t free_size() const { + return static_cast(end_ - cur_); + } + + // Resets the current pointer to the base address. It does nothing to + // the contents. + virtual void reset() { + cur_ = begin_; + } + + void enable_profiling(ET_UNUSED const char* name) { + prof_id_ = EXECUTORCH_TRACK_ALLOCATOR(name); + } + + protected: + /** + * Returns the profiler ID for this allocator. + */ + int32_t prof_id() const { + return prof_id_; + } + + /** + * Returns true if the value is an integer power of 2. + */ + static constexpr bool isPowerOf2(size_t value) { + return value && !(value & (value - 1)); + } + + /** + * Returns the next alignment for a given pointer. + */ + static inline uint8_t* alignPointer(void* ptr, size_t alignment) { + uintptr_t address = reinterpret_cast(ptr); + uintptr_t mask = static_cast(alignment - 1); + address = (address + mask) & ~mask; + return reinterpret_cast(address); + } + + private: + uint8_t* const begin_; + uint8_t* const end_; + uint8_t* cur_; + uint32_t const size_; + int32_t prof_id_ = -1; +}; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::MemoryAllocator; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/named_data_map.h b/include/executorch/runtime/core/named_data_map.h new file mode 100644 index 0000000..e6a53b7 --- /dev/null +++ b/include/executorch/runtime/core/named_data_map.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +/** + * Interface to access and retrieve data via name. + * See executorch/extension/flat_tensor/ for an example. + */ +class NamedDataMap { + public: + virtual ~NamedDataMap() = default; + /** + * Get tensor_layout by key. + * + * @param key The name of the tensor. + * @return Result containing TensorLayout. + */ + ET_NODISCARD virtual Result get_tensor_layout( + std::string_view key) const = 0; + /** + * Get data by key. + * + * @param key Name of the data. + * @return Result containing a FreeableBuffer. + */ + ET_NODISCARD virtual Result get_data( + std::string_view key) const = 0; + + /** + * Loads data corresponding to the key into the provided buffer. + * + * @param key The name of the data. + * @param size The number of bytes to load. Use `get_tensor_layout` to + * retrieve the size of the data for a given key. + * @param buffer The buffer to load the data into. Must point to at least + * `size` bytes of memory. + * @returns an Error indicating if the load was successful. + */ + ET_NODISCARD virtual Error + load_data_into(std::string_view key, void* buffer, size_t size) const = 0; + + /** + * Get the number of keys in the NamedDataMap. + * + * @return Result containing the number of keys. + */ + ET_NODISCARD virtual Result get_num_keys() const = 0; + + /** + * Get the key at the given index. + * + * @param index The index of the key to retrieve. + * @return Result containing the key at the given index. The returned pointer + * is owned by the DataMap, remains stable across calls, and is only valid for + * the lifetime of the DataMap. + */ + ET_NODISCARD virtual Result get_key(uint32_t index) const = 0; +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch diff --git a/include/executorch/runtime/core/portable_type/bfloat16.h b/include/executorch/runtime/core/portable_type/bfloat16.h new file mode 100644 index 0000000..233d571 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/bfloat16.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch::runtime::etensor { +using c10::BFloat16; +namespace internal { +using c10::detail::f32_from_bits; +using c10::detail::round_to_nearest_even; +} // namespace internal +} // namespace executorch::runtime::etensor + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::BFloat16; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/bfloat16_math.h b/include/executorch/runtime/core/portable_type/bfloat16_math.h new file mode 100644 index 0000000..3f6bf14 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/bfloat16_math.h @@ -0,0 +1,14 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include + +#include diff --git a/include/executorch/runtime/core/portable_type/bits_types.h b/include/executorch/runtime/core/portable_type/bits_types.h new file mode 100644 index 0000000..cddffc4 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/bits_types.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once +#include + +namespace executorch { +namespace runtime { +namespace etensor { + +/** + * bits1x8 is an uninterpreted dtype of a tensor with 1 bit (packed to byte + * boundary), without any semantics defined. + */ +struct alignas(1) bits1x8 { + using underlying = uint8_t; + uint8_t val_; + bits1x8() = default; + explicit bits1x8(uint8_t val) : val_(val) {} +}; + +/** + * bits2x4 is an uninterpreted dtype of a tensor with 2 bits (packed to byte + * boundary), without any semantics defined. + */ +struct alignas(1) bits2x4 { + using underlying = uint8_t; + uint8_t val_; + bits2x4() = default; + explicit bits2x4(uint8_t val) : val_(val) {} +}; + +/** + * bits4x2 is an uninterpreted dtype of a tensor with 4 bits (packed to byte + * boundary), without any semantics defined. + */ +struct alignas(1) bits4x2 { + using underlying = uint8_t; + uint8_t val_; + bits4x2() = default; + explicit bits4x2(uint8_t val) : val_(val) {} +}; + +/** + * bits8 is an uninterpreted dtype of a tensor with 8 bits, without any + * semantics defined. + */ +struct alignas(1) bits8 { + uint8_t val_; + bits8() = default; + explicit bits8(uint8_t val) : val_(val) {} +}; + +/** + * bits16 is an uninterpreted dtype of a tensor with 16 bits, without any + * semantics defined. + */ +struct alignas(2) bits16 { + uint16_t val_; + bits16() = default; + explicit bits16(uint16_t val) : val_(val) {} +}; + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::bits16; +using ::executorch::runtime::etensor::bits1x8; +using ::executorch::runtime::etensor::bits2x4; +using ::executorch::runtime::etensor::bits4x2; +using ::executorch::runtime::etensor::bits8; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/c10/c10/macros/Export.h b/include/executorch/runtime/core/portable_type/c10/c10/macros/Export.h new file mode 100644 index 0000000..1b8a681 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/macros/Export.h @@ -0,0 +1 @@ +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/macros/Macros.h b/include/executorch/runtime/core/portable_type/c10/c10/macros/Macros.h new file mode 100644 index 0000000..87ebc4f --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/macros/Macros.h @@ -0,0 +1 @@ +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/BFloat16-inl.h b/include/executorch/runtime/core/portable_type/c10/c10/util/BFloat16-inl.h new file mode 100644 index 0000000..6d3510c --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/BFloat16-inl.h @@ -0,0 +1 @@ +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/BFloat16-math.h b/include/executorch/runtime/core/portable_type/c10/c10/util/BFloat16-math.h new file mode 100644 index 0000000..4410002 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/BFloat16-math.h @@ -0,0 +1,3 @@ +#pragma once + +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/BFloat16.h b/include/executorch/runtime/core/portable_type/c10/c10/util/BFloat16.h new file mode 100644 index 0000000..6d3510c --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/BFloat16.h @@ -0,0 +1 @@ +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/Half-inl.h b/include/executorch/runtime/core/portable_type/c10/c10/util/Half-inl.h new file mode 100644 index 0000000..fe66779 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/Half-inl.h @@ -0,0 +1 @@ +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/Half.h b/include/executorch/runtime/core/portable_type/c10/c10/util/Half.h new file mode 100644 index 0000000..98480b2 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/Half.h @@ -0,0 +1,8 @@ +#include + +// need to keep the following for BC because the APIs in here were exposed +// before migrating Half to torch/headeronly +#if (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) +#include +#endif diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/TypeSafeSignMath.h b/include/executorch/runtime/core/portable_type/c10/c10/util/TypeSafeSignMath.h new file mode 100644 index 0000000..2852022 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/TypeSafeSignMath.h @@ -0,0 +1 @@ +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/bit_cast.h b/include/executorch/runtime/core/portable_type/c10/c10/util/bit_cast.h new file mode 100644 index 0000000..49d0822 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/bit_cast.h @@ -0,0 +1 @@ +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/complex.h b/include/executorch/runtime/core/portable_type/c10/c10/util/complex.h new file mode 100644 index 0000000..f9849a9 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/complex.h @@ -0,0 +1,73 @@ +#pragma once + +#include + +#include +#include +#include + +// std functions +// +// The implementation of these functions also follow the design of C++20 + +namespace std { + +template +constexpr T real(const c10::complex& z) { + return z.real(); +} + +template +constexpr T imag(const c10::complex& z) { + return z.imag(); +} + +template +C10_HOST_DEVICE T abs(const c10::complex& z) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return thrust::abs(static_cast>(z)); +#else + return std::abs(static_cast>(z)); +#endif +} + +template +C10_HOST_DEVICE T arg(const c10::complex& z) { + return std::atan2(std::imag(z), std::real(z)); +} + +template +constexpr T norm(const c10::complex& z) { + return z.real() * z.real() + z.imag() * z.imag(); +} + +// For std::conj, there are other versions of it: +// constexpr std::complex conj( float z ); +// template< class DoubleOrInteger > +// constexpr std::complex conj( DoubleOrInteger z ); +// constexpr std::complex conj( long double z ); +// These are not implemented +// TODO(@zasdfgbnm): implement them as c10::conj +template +constexpr c10::complex conj(const c10::complex& z) { + return c10::complex(z.real(), -z.imag()); +} + +// Thrust does not have complex --> complex version of thrust::proj, +// so this function is not implemented at c10 right now. +// TODO(@zasdfgbnm): implement it by ourselves + +// There is no c10 version of std::polar, because std::polar always +// returns std::complex. Use c10::polar instead; + +} // namespace std + +#define C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H +// math functions are included in a separate file +#include // IWYU pragma: keep +#undef C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H + +namespace c10 { +using torch::headeronly::is_complex; +using torch::headeronly::scalar_value_type; +} // namespace c10 diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/complex_math.h b/include/executorch/runtime/core/portable_type/c10/c10/util/complex_math.h new file mode 100644 index 0000000..2b9bbea --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/complex_math.h @@ -0,0 +1,441 @@ +#if !defined(C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H) +#error \ + "c10/util/complex_math.h is not meant to be individually included. Include c10/util/complex.h instead." +#endif + +namespace c10_complex_math { + +// Exponential functions + +template +C10_HOST_DEVICE inline c10::complex exp(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::exp(static_cast>(x))); +#else + return static_cast>( + std::exp(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex log(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::log(static_cast>(x))); +#else + return static_cast>( + std::log(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex log10(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::log10(static_cast>(x))); +#else + return static_cast>( + std::log10(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex log2(const c10::complex& x) { + const c10::complex log2 = c10::complex(::log(2.0), 0.0); + return c10_complex_math::log(x) / log2; +} + +// Power functions +// +#if defined(_LIBCPP_VERSION) || \ + (defined(__GLIBCXX__) && !defined(_GLIBCXX11_USE_C99_COMPLEX)) +namespace _detail { +C10_API c10::complex sqrt(const c10::complex& in); +C10_API c10::complex sqrt(const c10::complex& in); +C10_API c10::complex acos(const c10::complex& in); +C10_API c10::complex acos(const c10::complex& in); +} // namespace _detail +#endif + +template +C10_HOST_DEVICE inline c10::complex sqrt(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::sqrt(static_cast>(x))); +#elif !( \ + defined(_LIBCPP_VERSION) || \ + (defined(__GLIBCXX__) && !defined(_GLIBCXX11_USE_C99_COMPLEX))) + return static_cast>( + std::sqrt(static_cast>(x))); +#else + return _detail::sqrt(x); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const c10::complex& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>(thrust::pow( + static_cast>(x), static_cast>(y))); +#else + return static_cast>(std::pow( + static_cast>(x), static_cast>(y))); +#endif +} + +// Regression in ROCm 7.2. See https://github.com/ROCm/rocm-libraries/pull/3836. +// Specialized version for complex on AMD GPUs to use FMA-based +// multiplication +#if defined(__HIPCC__) +namespace detail { +// FMA-aware complex multiplication for float precision on AMD GPUs. +// This prevents SLP vectorizer from breaking FMA formation, which causes +// numerical precision loss in complex arithmetic. +// The issue occurs when vectorizer packs scalar multiplies before backend +// can form FMA instructions, resulting in double rounding instead of single. +C10_HOST_DEVICE inline thrust::complex complex_mul_fma( + thrust::complex a, + thrust::complex b) { + // Complex multiplication: (a.r + a.i*i) * (b.r + b.i*i) + // = (a.r*b.r - a.i*b.i) + (a.r*b.i + a.i*b.r)*i + // Using __builtin_fmaf ensures FMA at source level: + // real: a.r*b.r + (-(a.i*b.i)) = FMA(a.r, b.r, -(a.i*b.i)) + // imag: a.i*b.r + a.r*b.i = FMA(a.r, b.i, a.i*b.r) + float real_part = __builtin_fmaf(a.real(), b.real(), -(a.imag() * b.imag())); + float imag_part = __builtin_fmaf(a.real(), b.imag(), a.imag() * b.real()); + return thrust::complex(real_part, imag_part); +} +} // namespace detail + +template <> +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const c10::complex& y) { + auto log_x = thrust::log(static_cast>(x)); + auto y_log_x = + detail::complex_mul_fma(static_cast>(y), log_x); + return static_cast>(thrust::exp(y_log_x)); +} +#endif + +template +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const T& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::pow(static_cast>(x), y)); +#else + return static_cast>( + std::pow(static_cast>(x), y)); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const T& x, + const c10::complex& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::pow(x, static_cast>(y))); +#else + return static_cast>( + std::pow(x, static_cast>(y))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const c10::complex& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>(thrust::pow( + static_cast>(x), static_cast>(y))); +#else + return static_cast>(std::pow( + static_cast>(x), static_cast>(y))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const c10::complex& x, + const U& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::pow(static_cast>(x), y)); +#else + return static_cast>( + std::pow(static_cast>(x), y)); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex pow( + const T& x, + const c10::complex& y) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::pow(x, static_cast>(y))); +#else + return static_cast>( + std::pow(x, static_cast>(y))); +#endif +} + +// Trigonometric functions + +template +C10_HOST_DEVICE inline c10::complex sin(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::sin(static_cast>(x))); +#else + return static_cast>( + std::sin(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex cos(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::cos(static_cast>(x))); +#else + return static_cast>( + std::cos(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex tan(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::tan(static_cast>(x))); +#else + return static_cast>( + std::tan(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex asin(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::asin(static_cast>(x))); +#else + return static_cast>( + std::asin(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex acos(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::acos(static_cast>(x))); +#elif !defined(_LIBCPP_VERSION) + return static_cast>( + std::acos(static_cast>(x))); +#else + return _detail::acos(x); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex atan(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::atan(static_cast>(x))); +#else + return static_cast>( + std::atan(static_cast>(x))); +#endif +} + +// Hyperbolic functions + +template +C10_HOST_DEVICE inline c10::complex sinh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::sinh(static_cast>(x))); +#else + return static_cast>( + std::sinh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex cosh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::cosh(static_cast>(x))); +#else + return static_cast>( + std::cosh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex tanh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::tanh(static_cast>(x))); +#else + return static_cast>( + std::tanh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex asinh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::asinh(static_cast>(x))); +#else + return static_cast>( + std::asinh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex acosh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::acosh(static_cast>(x))); +#else + return static_cast>( + std::acosh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex atanh(const c10::complex& x) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>( + thrust::atanh(static_cast>(x))); +#else + return static_cast>( + std::atanh(static_cast>(x))); +#endif +} + +template +C10_HOST_DEVICE inline c10::complex log1p(const c10::complex& z) { +#if defined(__APPLE__) || defined(__MACOSX) || defined(__CUDACC__) || \ + defined(__HIPCC__) || defined(__SYCL_DEVICE_ONLY__) + // For Mac, the new implementation yielded a high relative error. Falling back + // to the old version for now. + // See https://github.com/numpy/numpy/pull/22611#issuecomment-1667945354 + // For CUDA we also use this one, as thrust::log(thrust::complex) takes + // *forever* to compile + + // log1p(z) = log(1 + z) + // Let's define 1 + z = r * e ^ (i * a), then we have + // log(r * e ^ (i * a)) = log(r) + i * a + // With z = x + iy, the term r can be written as + // r = ((1 + x) ^ 2 + y ^ 2) ^ 0.5 + // = (1 + x ^ 2 + 2 * x + y ^ 2) ^ 0.5 + // So, log(r) is + // log(r) = 0.5 * log(1 + x ^ 2 + 2 * x + y ^ 2) + // = 0.5 * log1p(x * (x + 2) + y ^ 2) + // we need to use the expression only on certain condition to avoid overflow + // and underflow from `(x * (x + 2) + y ^ 2)` + T x = z.real(); + T y = z.imag(); + T zabs = std::abs(z); + T theta = std::atan2(y, x + T(1)); + if (zabs < 0.5) { + T r = x * (T(2) + x) + y * y; + if (r == 0) { // handle underflow + return {x, theta}; + } + return {T(0.5) * std::log1p(r), theta}; + } else { + T z0 = std::hypot(x + 1, y); + return {std::log(z0), theta}; + } +#else + // CPU path + // Based on https://github.com/numpy/numpy/pull/22611#issuecomment-1667945354 + c10::complex u = z + T(1); + if (u == T(1)) { + return z; + } else { + auto log_u = log(u); + if (u - T(1) == z) { + return log_u; + } + return log_u * (z / (u - T(1))); + } +#endif +} + +template +C10_HOST_DEVICE inline c10::complex expm1(const c10::complex& z) { + // expm1(z) = exp(z) - 1 + // Define z = x + i * y + // f = e ^ (x + i * y) - 1 + // = e ^ x * e ^ (i * y) - 1 + // = (e ^ x * cos(y) - 1) + i * (e ^ x * sin(y)) + // = (e ^ x - 1) * cos(y) - (1 - cos(y)) + i * e ^ x * sin(y) + // = expm1(x) * cos(y) - 2 * sin(y / 2) ^ 2 + i * e ^ x * sin(y) + T x = z.real(); + T y = z.imag(); + T a = std::sin(y / 2); + T er = std::expm1(x) * std::cos(y) - T(2) * a * a; + T ei = std::exp(x) * std::sin(y); + return {er, ei}; +} + +} // namespace c10_complex_math + +using c10_complex_math::acos; +using c10_complex_math::acosh; +using c10_complex_math::asin; +using c10_complex_math::asinh; +using c10_complex_math::atan; +using c10_complex_math::atanh; +using c10_complex_math::cos; +using c10_complex_math::cosh; +using c10_complex_math::exp; +using c10_complex_math::expm1; +using c10_complex_math::log; +using c10_complex_math::log10; +using c10_complex_math::log1p; +using c10_complex_math::log2; +using c10_complex_math::pow; +using c10_complex_math::sin; +using c10_complex_math::sinh; +using c10_complex_math::sqrt; +using c10_complex_math::tan; +using c10_complex_math::tanh; + +namespace std { + +using c10_complex_math::acos; +using c10_complex_math::acosh; +using c10_complex_math::asin; +using c10_complex_math::asinh; +using c10_complex_math::atan; +using c10_complex_math::atanh; +using c10_complex_math::cos; +using c10_complex_math::cosh; +using c10_complex_math::exp; +using c10_complex_math::expm1; +using c10_complex_math::log; +using c10_complex_math::log10; +using c10_complex_math::log1p; +using c10_complex_math::log2; +using c10_complex_math::pow; +using c10_complex_math::sin; +using c10_complex_math::sinh; +using c10_complex_math::sqrt; +using c10_complex_math::tan; +using c10_complex_math::tanh; + +} // namespace std diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/floating_point_utils.h b/include/executorch/runtime/core/portable_type/c10/c10/util/floating_point_utils.h new file mode 100644 index 0000000..10aa67c --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/floating_point_utils.h @@ -0,0 +1 @@ +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/irange.h b/include/executorch/runtime/core/portable_type/c10/c10/util/irange.h new file mode 100644 index 0000000..c9dd7e5 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/irange.h @@ -0,0 +1,3 @@ +#pragma once + +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/llvmMathExtras.h b/include/executorch/runtime/core/portable_type/c10/c10/util/llvmMathExtras.h new file mode 100644 index 0000000..8ae5cde --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/llvmMathExtras.h @@ -0,0 +1,906 @@ +//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains some functions that are useful for math stuff. +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __ANDROID_NDK__ +#include +#endif + +#ifndef __has_builtin +#define __has_builtin(x) 0 +#endif + +#ifndef LLVM_GNUC_PREREQ +#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) +#define LLVM_GNUC_PREREQ(maj, min, patch) \ + ((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) + __GNUC_PATCHLEVEL__ >= \ + ((maj) << 20) + ((min) << 10) + (patch)) +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) +#define LLVM_GNUC_PREREQ(maj, min, patch) \ + ((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) >= ((maj) << 20) + ((min) << 10)) +#else +#define LLVM_GNUC_PREREQ(maj, min, patch) 0 +#endif +#endif + +#ifdef _MSC_VER +// Declare these intrinsics manually rather including intrin.h. It's very +// expensive, and MathExtras.h is popular. +// #include +extern "C" { +unsigned char _BitScanForward(unsigned long* _Index, unsigned long _Mask); +unsigned char _BitScanForward64(unsigned long* _Index, unsigned __int64 _Mask); +unsigned char _BitScanReverse(unsigned long* _Index, unsigned long _Mask); +unsigned char _BitScanReverse64(unsigned long* _Index, unsigned __int64 _Mask); +} +#endif + +namespace c10::llvm { +/// The behavior an operation has on an input of 0. +enum ZeroBehavior { + /// The returned value is undefined. + ZB_Undefined, + /// The returned value is numeric_limits::max() + ZB_Max, + /// The returned value is numeric_limits::digits + ZB_Width +}; + +namespace detail { +template +struct TrailingZerosCounter { + static std::size_t count(T Val, ZeroBehavior /*unused*/) { + if (!Val) + return std::numeric_limits::digits; + if (Val & 0x1) + return 0; + + // Bisection method. + std::size_t ZeroBits = 0; + T Shift = std::numeric_limits::digits >> 1; + T Mask = std::numeric_limits::max() >> Shift; + while (Shift) { + if ((Val & Mask) == 0) { + Val >>= Shift; + ZeroBits |= Shift; + } + Shift >>= 1; + Mask >>= Shift; + } + return ZeroBits; + } +}; + +#if (defined(__GNUC__) && __GNUC__ >= 4) || defined(_MSC_VER) +template +struct TrailingZerosCounter { + static std::size_t count(T Val, ZeroBehavior ZB) { + if (ZB != ZB_Undefined && Val == 0) + return 32; + +#if __has_builtin(__builtin_ctz) || LLVM_GNUC_PREREQ(4, 0, 0) + return __builtin_ctz(Val); +#elif defined(_MSC_VER) + unsigned long Index; + _BitScanForward(&Index, Val); + return Index; +#endif + } +}; + +#if !defined(_MSC_VER) || defined(_M_X64) +template +struct TrailingZerosCounter { + static std::size_t count(T Val, ZeroBehavior ZB) { + if (ZB != ZB_Undefined && Val == 0) + return 64; + +#if __has_builtin(__builtin_ctzll) || LLVM_GNUC_PREREQ(4, 0, 0) + return __builtin_ctzll(Val); +#elif defined(_MSC_VER) + unsigned long Index; + _BitScanForward64(&Index, Val); + return Index; +#endif + } +}; +#endif +#endif +} // namespace detail + +/// Count number of 0's from the least significant bit to the most +/// stopping at the first 1. +/// +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are +/// valid arguments. +template +std::size_t countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return llvm::detail::TrailingZerosCounter::count(Val, ZB); +} + +namespace detail { +template +struct LeadingZerosCounter { + static std::size_t count(T Val, ZeroBehavior /*unused*/) { + if (!Val) + return std::numeric_limits::digits; + + // Bisection method. + std::size_t ZeroBits = 0; + for (T Shift = std::numeric_limits::digits >> 1; Shift; Shift >>= 1) { + T Tmp = Val >> Shift; + if (Tmp) + Val = Tmp; + else + ZeroBits |= Shift; + } + return ZeroBits; + } +}; + +#if (defined(__GNUC__) && __GNUC__ >= 4) || defined(_MSC_VER) +template +struct LeadingZerosCounter { + static std::size_t count(T Val, ZeroBehavior ZB) { + if (ZB != ZB_Undefined && Val == 0) + return 32; + +#if __has_builtin(__builtin_clz) || LLVM_GNUC_PREREQ(4, 0, 0) + return __builtin_clz(Val); +#elif defined(_MSC_VER) + unsigned long Index; + _BitScanReverse(&Index, Val); + return Index ^ 31; +#endif + } +}; + +#if !defined(_MSC_VER) || defined(_M_X64) +template +struct LeadingZerosCounter { + static std::size_t count(T Val, ZeroBehavior ZB) { + if (ZB != ZB_Undefined && Val == 0) + return 64; + +#if __has_builtin(__builtin_clzll) || LLVM_GNUC_PREREQ(4, 0, 0) + return __builtin_clzll(Val); +#elif defined(_MSC_VER) + unsigned long Index; + _BitScanReverse64(&Index, Val); + return Index ^ 63; +#endif + } +}; +#endif +#endif +} // namespace detail + +/// Count number of 0's from the most significant bit to the least +/// stopping at the first 1. +/// +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are +/// valid arguments. +template +std::size_t countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return llvm::detail::LeadingZerosCounter::count(Val, ZB); +} + +/// Get the index of the first set bit starting from the least +/// significant bit. +/// +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are +/// valid arguments. +template +T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) { + if (ZB == ZB_Max && Val == 0) + return std::numeric_limits::max(); + + return countTrailingZeros(Val, ZB_Undefined); +} + +/// Create a bitmask with the N right-most bits set to 1, and all other +/// bits set to 0. Only unsigned types are allowed. +template +T maskTrailingOnes(unsigned N) { + static_assert(std::is_unsigned_v, "Invalid type!"); + const unsigned Bits = CHAR_BIT * sizeof(T); + assert(N <= Bits && "Invalid bit index"); + return N == 0 ? 0 : (T(-1) >> (Bits - N)); +} + +/// Create a bitmask with the N left-most bits set to 1, and all other +/// bits set to 0. Only unsigned types are allowed. +template +T maskLeadingOnes(unsigned N) { + return ~maskTrailingOnes(CHAR_BIT * sizeof(T) - N); +} + +/// Create a bitmask with the N right-most bits set to 0, and all other +/// bits set to 1. Only unsigned types are allowed. +template +T maskTrailingZeros(unsigned N) { + return maskLeadingOnes(CHAR_BIT * sizeof(T) - N); +} + +/// Create a bitmask with the N left-most bits set to 0, and all other +/// bits set to 1. Only unsigned types are allowed. +template +T maskLeadingZeros(unsigned N) { + return maskTrailingOnes(CHAR_BIT * sizeof(T) - N); +} + +/// Get the index of the last set bit starting from the least +/// significant bit. +/// +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are +/// valid arguments. +template +T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) { + if (ZB == ZB_Max && Val == 0) + return std::numeric_limits::max(); + + // Use ^ instead of - because both gcc and llvm can remove the associated ^ + // in the __builtin_clz intrinsic on x86. + return countLeadingZeros(Val, ZB_Undefined) ^ + (std::numeric_limits::digits - 1); +} + +/// Macro compressed bit reversal table for 256 bits. +/// +/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable +/// NOLINTNEXTLINE(*c-arrays*) +static constexpr unsigned char BitReverseTable256[256] = { +#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64 +#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16) +#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4) + R6(0), + R6(2), + R6(1), + R6(3) +#undef R2 +#undef R4 +#undef R6 +}; + +/// Reverse the bits in \p Val. +template +T reverseBits(T Val) { + // NOLINTNEXTLINE(*c-arrays*) + unsigned char in[sizeof(Val)]; + // NOLINTNEXTLINE(*c-arrays*) + unsigned char out[sizeof(Val)]; + std::memcpy(in, &Val, sizeof(Val)); + for (unsigned i = 0; i < sizeof(Val); ++i) + out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]]; + std::memcpy(&Val, out, sizeof(Val)); + return Val; +} + +// NOTE: The following support functions use the _32/_64 extensions instead of +// type overloading so that signed and unsigned integers can be used without +// ambiguity. + +/// Return the high 32 bits of a 64 bit value. +constexpr inline uint32_t Hi_32(uint64_t Value) { + return static_cast(Value >> 32); +} + +/// Return the low 32 bits of a 64 bit value. +constexpr inline uint32_t Lo_32(uint64_t Value) { + return static_cast(Value); +} + +/// Make a 64-bit integer from a high / low pair of 32-bit integers. +constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) { + return ((uint64_t)High << 32) | (uint64_t)Low; +} + +/// Checks if an integer fits into the given bit width. +template +constexpr inline bool isInt(int64_t x) { + return N >= 64 || + (-(INT64_C(1) << (N - 1)) <= x && x < (INT64_C(1) << (N - 1))); +} +// Template specializations to get better code for common cases. +template <> +constexpr inline bool isInt<8>(int64_t x) { + return static_cast(x) == x; +} +template <> +constexpr inline bool isInt<16>(int64_t x) { + return static_cast(x) == x; +} +template <> +constexpr inline bool isInt<32>(int64_t x) { + return static_cast(x) == x; +} + +/// Checks if a signed integer is an N bit number shifted left by S. +template +constexpr inline bool isShiftedInt(int64_t x) { + static_assert( + N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number."); + static_assert(N + S <= 64, "isShiftedInt with N + S > 64 is too wide."); + return isInt(x) && (x % (UINT64_C(1) << S) == 0); +} + +/// Checks if an unsigned integer fits into the given bit width. +/// +/// This is written as two functions rather than as simply +/// +/// return N >= 64 || X < (UINT64_C(1) << N); +/// +/// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting +/// left too many places. +template +constexpr inline std::enable_if_t<(N < 64), bool> isUInt(uint64_t X) { + static_assert(N > 0, "isUInt<0> doesn't make sense"); + return X < (UINT64_C(1) << N); +} +template +constexpr inline std::enable_if_t= 64, bool> isUInt(uint64_t /*X*/) { + return true; +} + +// Template specializations to get better code for common cases. +template <> +constexpr inline bool isUInt<8>(uint64_t x) { + return static_cast(x) == x; +} +template <> +constexpr inline bool isUInt<16>(uint64_t x) { + return static_cast(x) == x; +} +template <> +constexpr inline bool isUInt<32>(uint64_t x) { + return static_cast(x) == x; +} + +/// Checks if a unsigned integer is an N bit number shifted left by S. +template +constexpr inline bool isShiftedUInt(uint64_t x) { + static_assert( + N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)"); + static_assert( + N + S <= 64, "isShiftedUInt with N + S > 64 is too wide."); + // Per the two static_asserts above, S must be strictly less than 64. So + // 1 << S is not undefined behavior. + // NOLINTNEXTLINE(bugprone-chained-comparison) + return isUInt(x) && (x % (UINT64_C(1) << S) == 0); +} + +/// Gets the maximum value for a N-bit unsigned integer. +inline uint64_t maxUIntN(uint64_t N) { + assert(N > 0 && N <= 64 && "integer width out of range"); + + // uint64_t(1) << 64 is undefined behavior, so we can't do + // (uint64_t(1) << N) - 1 + // without checking first that N != 64. But this works and doesn't have a + // branch. + return UINT64_MAX >> (64 - N); +} + +// Ignore the false warning "Arithmetic overflow" for MSVC +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4146) +#endif + +/// Gets the minimum value for a N-bit signed integer. +inline int64_t minIntN(int64_t N) { + assert(N > 0 && N <= 64 && "integer width out of range"); + // NOLINTNEXTLINE(*-narrowing-conversions) + return -(UINT64_C(1) << (N - 1)); +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +/// Gets the maximum value for a N-bit signed integer. +inline int64_t maxIntN(int64_t N) { + assert(N > 0 && N <= 64 && "integer width out of range"); + + // This relies on two's complement wraparound when N == 64, so we convert to + // int64_t only at the very end to avoid UB. + // NOLINTNEXTLINE(*-narrowing-conversions) + return (UINT64_C(1) << (N - 1)) - 1; +} + +/// Checks if an unsigned integer fits into the given (dynamic) bit width. +inline bool isUIntN(unsigned N, uint64_t x) { + return N >= 64 || x <= maxUIntN(N); +} + +/// Checks if an signed integer fits into the given (dynamic) bit width. +inline bool isIntN(unsigned N, int64_t x) { + return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N)); +} + +/// Return true if the argument is a non-empty sequence of ones starting at the +/// least significant bit with the remainder zero (32 bit version). +/// Ex. isMask_32(0x0000FFFFU) == true. +constexpr inline bool isMask_32(uint32_t Value) { + return Value && ((Value + 1) & Value) == 0; +} + +/// Return true if the argument is a non-empty sequence of ones starting at the +/// least significant bit with the remainder zero (64 bit version). +constexpr inline bool isMask_64(uint64_t Value) { + return Value && ((Value + 1) & Value) == 0; +} + +/// Return true if the argument contains a non-empty sequence of ones with the +/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true. +constexpr inline bool isShiftedMask_32(uint32_t Value) { + return Value && isMask_32((Value - 1) | Value); +} + +/// Return true if the argument contains a non-empty sequence of ones with the +/// remainder zero (64 bit version.) +constexpr inline bool isShiftedMask_64(uint64_t Value) { + return Value && isMask_64((Value - 1) | Value); +} + +/// Return true if the argument is a power of two > 0. +/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.) +constexpr inline bool isPowerOf2_32(uint32_t Value) { + return Value && !(Value & (Value - 1)); +} + +/// Return true if the argument is a power of two > 0 (64 bit edition.) +constexpr inline bool isPowerOf2_64(uint64_t Value) { + return Value && !(Value & (Value - 1)); +} + +/// Count the number of ones from the most significant bit to the first +/// zero bit. +/// +/// Ex. countLeadingOnes(0xFF0FFF00) == 8. +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of all ones. Only ZB_Width and +/// ZB_Undefined are valid arguments. +template +std::size_t countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return countLeadingZeros(~Value, ZB); +} + +/// Count the number of ones from the least significant bit to the first +/// zero bit. +/// +/// Ex. countTrailingOnes(0x00FF00FF) == 8. +/// Only unsigned integral types are allowed. +/// +/// \param ZB the behavior on an input of all ones. Only ZB_Width and +/// ZB_Undefined are valid arguments. +template +std::size_t countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return countTrailingZeros(~Value, ZB); +} + +namespace detail { +template +struct PopulationCounter { + static unsigned count(T Value) { + // Generic version, forward to 32 bits. + static_assert(SizeOfT <= 4, "Not implemented!"); +#if defined(__GNUC__) && __GNUC__ >= 4 + return __builtin_popcount(Value); +#else + uint32_t v = Value; + v = v - ((v >> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >> 2) & 0x33333333); + return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; +#endif + } +}; + +template +struct PopulationCounter { + static unsigned count(T Value) { +#if defined(__GNUC__) && __GNUC__ >= 4 + return __builtin_popcountll(Value); +#else + uint64_t v = Value; + v = v - ((v >> 1) & 0x5555555555555555ULL); + v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL); + v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL; + return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56); +#endif + } +}; +} // namespace detail + +/// Count the number of set bits in a value. +/// Ex. countPopulation(0xF000F000) = 8 +/// Returns 0 if the word is zero. +template +inline unsigned countPopulation(T Value) { + static_assert( + std::numeric_limits::is_integer && !std::numeric_limits::is_signed, + "Only unsigned integral types are allowed."); + return detail::PopulationCounter::count(Value); +} + +/// Return the log base 2 of the specified value. +inline double Log2(double Value) { +#if defined(__ANDROID_API__) && __ANDROID_API__ < 18 + return __builtin_log(Value) / __builtin_log(2.0); +#else + return log2(Value); +#endif +} + +/// Return the floor log base 2 of the specified value, -1 if the value is zero. +/// (32 bit edition.) +/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2 +inline unsigned Log2_32(uint32_t Value) { + return static_cast(31 - countLeadingZeros(Value)); +} + +/// Return the floor log base 2 of the specified value, -1 if the value is zero. +/// (64 bit edition.) +inline unsigned Log2_64(uint64_t Value) { + return static_cast(63 - countLeadingZeros(Value)); +} + +/// Return the ceil log base 2 of the specified value, 32 if the value is zero. +/// (32 bit edition). +/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3 +inline unsigned Log2_32_Ceil(uint32_t Value) { + return static_cast(32 - countLeadingZeros(Value - 1)); +} + +/// Return the ceil log base 2 of the specified value, 64 if the value is zero. +/// (64 bit edition.) +inline unsigned Log2_64_Ceil(uint64_t Value) { + return static_cast(64 - countLeadingZeros(Value - 1)); +} + +/// Return the greatest common divisor of the values using Euclid's algorithm. +inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) { + while (B) { + uint64_t T = B; + B = A % B; + A = T; + } + return A; +} + +/// This function takes a 64-bit integer and returns the bit equivalent double. +inline double BitsToDouble(uint64_t Bits) { + double D = 0; + static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes"); + memcpy(&D, &Bits, sizeof(Bits)); + return D; +} + +/// This function takes a 32-bit integer and returns the bit equivalent float. +inline float BitsToFloat(uint32_t Bits) { + // TODO: Use std::bit_cast once C++20 becomes available. + return c10::bit_cast(Bits); +} + +/// This function takes a double and returns the bit equivalent 64-bit integer. +/// Note that copying doubles around changes the bits of NaNs on some hosts, +/// notably x86, so this routine cannot be used if these bits are needed. +inline uint64_t DoubleToBits(double Double) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + uint64_t Bits; + static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes"); + memcpy(&Bits, &Double, sizeof(Double)); + return Bits; +} + +/// This function takes a float and returns the bit equivalent 32-bit integer. +/// Note that copying floats around changes the bits of NaNs on some hosts, +/// notably x86, so this routine cannot be used if these bits are needed. +inline uint32_t FloatToBits(float Float) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + uint32_t Bits; + static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes"); + memcpy(&Bits, &Float, sizeof(Float)); + return Bits; +} + +/// A and B are either alignments or offsets. Return the minimum alignment that +/// may be assumed after adding the two together. +constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) { + // The largest power of 2 that divides both A and B. + // + // Replace "-Value" by "1+~Value" in the following commented code to avoid + // MSVC warning C4146 + // return (A | B) & -(A | B); + return (A | B) & (1 + ~(A | B)); +} + +/// Aligns \c Addr to \c Alignment bytes, rounding up. +/// +/// Alignment should be a power of two. This method rounds up, so +/// alignAddr(7, 4) == 8 and alignAddr(8, 4) == 8. +inline uintptr_t alignAddr(const void* Addr, size_t Alignment) { + assert( + Alignment && isPowerOf2_64((uint64_t)Alignment) && + "Alignment is not a power of two!"); + + assert((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr); + + return (((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1)); +} + +/// Returns the necessary adjustment for aligning \c Ptr to \c Alignment +/// bytes, rounding up. +inline size_t alignmentAdjustment(const void* Ptr, size_t Alignment) { + return alignAddr(Ptr, Alignment) - (uintptr_t)Ptr; +} + +/// Returns the next power of two (in 64-bits) that is strictly greater than A. +/// Returns zero on overflow. +inline uint64_t NextPowerOf2(uint64_t A) { + A |= (A >> 1); + A |= (A >> 2); + A |= (A >> 4); + A |= (A >> 8); + A |= (A >> 16); + A |= (A >> 32); + return A + 1; +} + +/// Returns the power of two which is less than or equal to the given value. +/// Essentially, it is a floor operation across the domain of powers of two. +inline uint64_t PowerOf2Floor(uint64_t A) { + if (!A) + return 0; + return 1ull << (63 - countLeadingZeros(A, ZB_Undefined)); +} + +/// Returns the power of two which is greater than or equal to the given value. +/// Essentially, it is a ceil operation across the domain of powers of two. +inline uint64_t PowerOf2Ceil(uint64_t A) { + if (!A) + return 0; + return NextPowerOf2(A - 1); +} + +/// Returns the next integer (mod 2**64) that is greater than or equal to +/// \p Value and is a multiple of \p Align. \p Align must be non-zero. +/// +/// If non-zero \p Skew is specified, the return value will be a minimal +/// integer that is greater than or equal to \p Value and equal to +/// \p Align * N + \p Skew for some integer N. If \p Skew is larger than +/// \p Align, its value is adjusted to '\p Skew mod \p Align'. +/// +/// Examples: +/// \code +/// alignTo(5, 8) = 8 +/// alignTo(17, 8) = 24 +/// alignTo(~0LL, 8) = 0 +/// alignTo(321, 255) = 510 +/// +/// alignTo(5, 8, 7) = 7 +/// alignTo(17, 8, 1) = 17 +/// alignTo(~0LL, 8, 3) = 3 +/// alignTo(321, 255, 42) = 552 +/// \endcode +inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) { + assert(Align != 0u && "Align can't be 0."); + Skew %= Align; + return (Value + Align - 1 - Skew) / Align * Align + Skew; +} + +/// Returns the next integer (mod 2**64) that is greater than or equal to +/// \p Value and is a multiple of \c Align. \c Align must be non-zero. +template +constexpr inline uint64_t alignTo(uint64_t Value) { + static_assert(Align != 0u, "Align must be non-zero"); + return (Value + Align - 1) / Align * Align; +} + +/// Returns the integer ceil(Numerator / Denominator). +inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) { + return alignTo(Numerator, Denominator) / Denominator; +} + +/// \c alignTo for contexts where a constant expression is required. +/// \sa alignTo +/// +/// \todo FIXME: remove when \c constexpr becomes really \c constexpr +template +struct AlignTo { + static_assert(Align != 0u, "Align must be non-zero"); + template + struct from_value { + static const uint64_t value = (Value + Align - 1) / Align * Align; + }; +}; + +/// Returns the largest uint64_t less than or equal to \p Value and is +/// \p Skew mod \p Align. \p Align must be non-zero +inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) { + assert(Align != 0u && "Align can't be 0."); + Skew %= Align; + return (Value - Skew) / Align * Align + Skew; +} + +/// Returns the offset to the next integer (mod 2**64) that is greater than +/// or equal to \p Value and is a multiple of \p Align. \p Align must be +/// non-zero. +inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) { + return alignTo(Value, Align) - Value; +} + +/// Sign-extend the number in the bottom B bits of X to a 32-bit integer. +/// Requires 0 < B <= 32. +template +constexpr inline int32_t SignExtend32(uint32_t X) { + static_assert(B > 0, "Bit width can't be 0."); + static_assert(B <= 32, "Bit width out of range."); + return int32_t(X << (32 - B)) >> (32 - B); +} + +/// Sign-extend the number in the bottom B bits of X to a 32-bit integer. +/// Requires 0 < B < 32. +inline int32_t SignExtend32(uint32_t X, unsigned B) { + assert(B > 0 && "Bit width can't be 0."); + assert(B <= 32 && "Bit width out of range."); + return int32_t(X << (32 - B)) >> (32 - B); +} + +/// Sign-extend the number in the bottom B bits of X to a 64-bit integer. +/// Requires 0 < B < 64. +template +constexpr inline int64_t SignExtend64(uint64_t x) { + static_assert(B > 0, "Bit width can't be 0."); + static_assert(B <= 64, "Bit width out of range."); + return int64_t(x << (64 - B)) >> (64 - B); +} + +/// Sign-extend the number in the bottom B bits of X to a 64-bit integer. +/// Requires 0 < B < 64. +inline int64_t SignExtend64(uint64_t X, unsigned B) { + assert(B > 0 && "Bit width can't be 0."); + assert(B <= 64 && "Bit width out of range."); + return int64_t(X << (64 - B)) >> (64 - B); +} + +/// Subtract two unsigned integers, X and Y, of type T and return the absolute +/// value of the result. +template +std::enable_if_t, T> AbsoluteDifference(T X, T Y) { + return std::max(X, Y) - std::min(X, Y); +} + +/// Add two unsigned integers, X and Y, of type T. Clamp the result to the +/// maximum representable value of T on overflow. ResultOverflowed indicates if +/// the result is larger than the maximum representable value of type T. +template +std::enable_if_t, T> SaturatingAdd( + T X, + T Y, + bool* ResultOverflowed = nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + bool Dummy; + bool& Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy; + // Hacker's Delight, p. 29 + T Z = X + Y; + Overflowed = (Z < X || Z < Y); + if (Overflowed) + return std::numeric_limits::max(); + else + return Z; +} + +/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the +/// maximum representable value of T on overflow. ResultOverflowed indicates if +/// the result is larger than the maximum representable value of type T. +template +std::enable_if_t, T> SaturatingMultiply( + T X, + T Y, + bool* ResultOverflowed = nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + bool Dummy; + bool& Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy; + + // Hacker's Delight, p. 30 has a different algorithm, but we don't use that + // because it fails for uint16_t (where multiplication can have undefined + // behavior due to promotion to int), and requires a division in addition + // to the multiplication. + + Overflowed = false; + + // Log2(Z) would be either Log2Z or Log2Z + 1. + // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z + // will necessarily be less than Log2Max as desired. + int Log2Z = Log2_64(X) + Log2_64(Y); + const T Max = std::numeric_limits::max(); + int Log2Max = Log2_64(Max); + if (Log2Z < Log2Max) { + return X * Y; + } + if (Log2Z > Log2Max) { + Overflowed = true; + return Max; + } + + // We're going to use the top bit, and maybe overflow one + // bit past it. Multiply all but the bottom bit then add + // that on at the end. + T Z = (X >> 1) * Y; + if (Z & ~(Max >> 1)) { + Overflowed = true; + return Max; + } + Z <<= 1; + if (X & 1) + return SaturatingAdd(Z, Y, ResultOverflowed); + + return Z; +} + +/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to +/// the product. Clamp the result to the maximum representable value of T on +/// overflow. ResultOverflowed indicates if the result is larger than the +/// maximum representable value of type T. +template +std::enable_if_t, T> SaturatingMultiplyAdd( + T X, + T Y, + T A, + bool* ResultOverflowed = nullptr) { + // NOLINTNEXTLINE(cppcoreguidelines-init-variables) + bool Dummy; + bool& Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy; + + T Product = SaturatingMultiply(X, Y, &Overflowed); + if (Overflowed) + return Product; + + return SaturatingAdd(A, Product, &Overflowed); +} + +/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC. +extern const float huge_valf; +} // namespace c10::llvm diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/overflows.h b/include/executorch/runtime/core/portable_type/c10/c10/util/overflows.h new file mode 100644 index 0000000..1494e2c --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/overflows.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include diff --git a/include/executorch/runtime/core/portable_type/c10/c10/util/safe_numerics.h b/include/executorch/runtime/core/portable_type/c10/c10/util/safe_numerics.h new file mode 100644 index 0000000..f695fa2 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/c10/util/safe_numerics.h @@ -0,0 +1,112 @@ +#pragma once +#include + +#include +#include +#include + +// GCC has __builtin_mul_overflow from before it supported __has_builtin +#ifdef _MSC_VER +#define C10_HAS_BUILTIN_OVERFLOW() (0) +#include +#include +#else +#define C10_HAS_BUILTIN_OVERFLOW() (1) +#endif + +namespace c10 { + +template , int> = 0> +C10_ALWAYS_INLINE bool add_overflows(T a, T b, T* out) { +#if C10_HAS_BUILTIN_OVERFLOW() + return __builtin_add_overflow(a, b, out); +#else + if constexpr (std::is_signed_v) { + // For signed types, detect overflow by checking sign changes + volatile T tmp = a + b; + *out = tmp; + + // If both operands have the same sign, check if result changed sign + // unexpectedly. + if ((a > 0) == (b > 0)) { + if ((a > 0) && (tmp <= 0)) { + return true; // Positive overflow + } + if ((a < 0) && (tmp >= 0)) { + return true; // Negative overflow + } + } + return false; + } else { + // For unsigned types, overflow causes wrap-around + volatile T tmp = a + b; + *out = tmp; + return (tmp < a || tmp < b); + } +#endif +} + +C10_ALWAYS_INLINE bool add_overflows(uint64_t a, uint64_t b, uint64_t* out) { + return add_overflows(a, b, out); +} + +template , int> = 0> +C10_ALWAYS_INLINE bool mul_overflows(T a, T b, T* out) { +#if C10_HAS_BUILTIN_OVERFLOW() + return __builtin_mul_overflow(a, b, out); +#else + if constexpr (std::is_signed_v) { + // For signed types, use the division-based check + volatile T tmp = a * b; + *out = tmp; + if (a == 0 || b == 0) { + return false; + } + return !(a == tmp / b); + } else { + // For unsigned types, use leading zeros approach + // This test isn't exact, but avoids doing integer division + *out = a * b; + constexpr int bits = sizeof(T) * 8; + return (std::countl_zero(a) + std::countl_zero(b)) < bits; + } +#endif +} + +C10_ALWAYS_INLINE bool mul_overflows(uint64_t a, uint64_t b, uint64_t* out) { + return mul_overflows(a, b, out); +} + +template +bool safe_multiplies_u64(It first, It last, uint64_t* out) { +#if C10_HAS_BUILTIN_OVERFLOW() + uint64_t prod = 1; + bool overflow = false; + for (; first != last; ++first) { + overflow |= c10::mul_overflows(prod, *first, &prod); + } + *out = prod; + return overflow; +#else + uint64_t prod = 1; + uint64_t prod_log2 = 0; + bool is_zero = false; + for (; first != last; ++first) { + auto x = static_cast(*first); + prod *= x; + // log2(0) isn't valid, so need to track it specially + is_zero |= (x == 0); + prod_log2 += std::bit_width(x - 1); + } + *out = prod; + // This test isn't exact, but avoids doing integer division + return !is_zero && (prod_log2 >= 64); +#endif +} + +template +bool safe_multiplies_u64(const Container& c, uint64_t* out) { + return safe_multiplies_u64(c.begin(), c.end(), out); +} + +} // namespace c10 diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/macros/Export.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/macros/Export.h new file mode 100644 index 0000000..14b26c1 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/macros/Export.h @@ -0,0 +1,145 @@ +#pragma once + +#ifndef C10_MACROS_EXPORT_H_ +#define C10_MACROS_EXPORT_H_ + +#ifndef C10_USING_CUSTOM_GENERATED_MACROS +#include +#endif // C10_USING_CUSTOM_GENERATED_MACROS + +/* Header file to define the common scaffolding for exported symbols. + * + * Export is by itself a quite tricky situation to deal with, and if you are + * hitting this file, make sure you start with the background here: + * - Linux: https://gcc.gnu.org/wiki/Visibility + * - Windows: + * https://docs.microsoft.com/en-us/cpp/cpp/dllexport-dllimport?view=vs-2017 + * + * Do NOT include this file directly. Instead, use c10/macros/Macros.h + */ + +// You do not need to edit this part of file unless you are changing the core +// pytorch export abstractions. +// +// This part defines the C10 core export and import macros. This is controlled +// by whether we are building shared libraries or not, which is determined +// during build time and codified in c10/core/cmake_macros.h. +// When the library is built as a shared lib, EXPORT and IMPORT will contain +// visibility attributes. If it is being built as a static lib, then EXPORT +// and IMPORT basically have no effect. + +// As a rule of thumb, you should almost NEVER mix static and shared builds for +// libraries that depend on c10. AKA, if c10 is built as a static library, we +// recommend everything dependent on c10 to be built statically. If c10 is built +// as a shared library, everything dependent on it should be built as shared. In +// the PyTorch project, all native libraries shall use the macro +// C10_BUILD_SHARED_LIB to check whether pytorch is building shared or static +// libraries. + +// For build systems that do not directly depend on CMake and directly build +// from the source directory (such as Buck), one may not have a cmake_macros.h +// file at all. In this case, the build system is responsible for providing +// correct macro definitions corresponding to the cmake_macros.h.in file. +// +// In such scenarios, one should define the macro +// C10_USING_CUSTOM_GENERATED_MACROS +// to inform this header that it does not need to include the cmake_macros.h +// file. + +#ifdef _WIN32 +#define C10_HIDDEN +#if defined(C10_BUILD_SHARED_LIBS) +#define C10_EXPORT __declspec(dllexport) +#define C10_IMPORT __declspec(dllimport) +#else +#define C10_EXPORT +#define C10_IMPORT +#endif +#else // _WIN32 +#if defined(__GNUC__) +#define C10_EXPORT __attribute__((__visibility__("default"))) +#define C10_HIDDEN __attribute__((__visibility__("hidden"))) +#else // defined(__GNUC__) +#define C10_EXPORT +#define C10_HIDDEN +#endif // defined(__GNUC__) +#define C10_IMPORT C10_EXPORT +#endif // _WIN32 + +#ifdef NO_EXPORT +#undef C10_EXPORT +#define C10_EXPORT +#endif + +// Definition of an adaptive XX_API macro, that depends on whether you are +// building the library itself or not, routes to XX_EXPORT and XX_IMPORT. +// Basically, you will need to do this for each shared library that you are +// building, and the instruction is as follows: assuming that you are building +// a library called libawesome.so. You should: +// (1) for your cmake target (usually done by "add_library(awesome, ...)"), +// define a macro called AWESOME_BUILD_MAIN_LIB using +// target_compile_options. +// (2) define the AWESOME_API macro similar to the one below. +// And in the source file of your awesome library, use AWESOME_API to +// annotate public symbols. + +// Here, for the C10 library, we will define the macro C10_API for both import +// and export. + +// This one is being used by libc10.so +#ifdef C10_BUILD_MAIN_LIB +#define C10_API C10_EXPORT +#else +#define C10_API C10_IMPORT +#endif + +// This one is being used by libtorch.so +#ifdef CAFFE2_BUILD_MAIN_LIB +#define TORCH_API C10_EXPORT +#else +#define TORCH_API C10_IMPORT +#endif + +// You may be wondering why we have TORCH_CUDA_CPP_API and TORCH_CUDA_CU_API +// belonging to the same library instead of just one TORCH_CUDA_API. Well, it +// can indeed just be one TORCH_CUDA_API (and used to be)! TORCH_CUDA_CPP_API +// and TORCH_CUDA_CU_API are artifacts of when we needed a split build to +// avoid relocation marker linking errors. The context is as follows: +// +// Once upon a time, there _was_ only TORCH_CUDA_API. All was happy until we +// tried to compile PyTorch for CUDA 11.1, which ran into relocation marker +// issues when linking big binaries. +// (https://github.com/pytorch/pytorch/issues/39968) We had two choices: +// (1) Stop supporting so many GPU architectures +// (2) Do something else +// We chose #2 and decided to split the behemoth that was torch_cuda into two +// smaller libraries, one with most of the core kernel functions (torch_cuda_cu) +// and the other that had..well..everything else (torch_cuda_cpp). The idea was +// this: instead of linking our static libraries (like the hefty +// libcudnn_static.a) with another huge library, torch_cuda, and run into pesky +// relocation marker issues, we could link our static libraries to a smaller +// part of torch_cuda (torch_cuda_cpp) and avoid the issues. + +// libtorch_cuda.so (where torch_cuda_cu and torch_cuda_cpp are a part of the +// same api) +#ifdef TORCH_CUDA_BUILD_MAIN_LIB +#define TORCH_CUDA_CPP_API C10_EXPORT +#define TORCH_CUDA_CU_API C10_EXPORT +#else +#define TORCH_CUDA_CPP_API C10_IMPORT +#define TORCH_CUDA_CU_API C10_IMPORT +#endif + +#if defined(TORCH_XPU_BUILD_MAIN_LIB) +#define TORCH_XPU_API C10_EXPORT +#else +#define TORCH_XPU_API C10_IMPORT +#endif + +// Enums only need to be exported on windows for non-CUDA files +#if defined(_WIN32) && defined(__CUDACC__) +#define C10_API_ENUM C10_API +#else +#define C10_API_ENUM +#endif +#endif // C10_MACROS_EXPORT_H_ diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/macros/Macros.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/macros/Macros.h new file mode 100644 index 0000000..718bd35 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/macros/Macros.h @@ -0,0 +1,830 @@ +#ifndef C10_MACROS_MACROS_H_ +#define C10_MACROS_MACROS_H_ + +#ifdef __cplusplus +#include +#else +#include +#endif + +/* Main entry for torch/headeronly/macros (used to be c10/macros). + * + * In your code, include torch/headeronly/macros/Macros.h directly, instead of + * individual files in this folder. + */ + +// For build systems that do not directly depend on CMake and directly build +// from the source directory (such as Buck), one may not have a cmake_macros.h +// file at all. In this case, the build system is responsible for providing +// correct macro definitions corresponding to the cmake_macros.h.in file. +// +// In such scenarios, one should define the macro +// C10_USING_CUSTOM_GENERATED_MACROS +// to inform this header that it does not need to include the cmake_macros.h +// file. + +#ifndef C10_USING_CUSTOM_GENERATED_MACROS +#include +#endif // C10_USING_CUSTOM_GENERATED_MACROS + +#include + +#if defined(__clang__) +#define __ubsan_ignore_float_divide_by_zero__ \ + __attribute__((no_sanitize("float-divide-by-zero"))) +#define __ubsan_ignore_undefined__ __attribute__((no_sanitize("undefined"))) +#define __ubsan_ignore_signed_int_overflow__ \ + __attribute__((no_sanitize("signed-integer-overflow"))) +#define __ubsan_ignore_pointer_overflow__ \ + __attribute__((no_sanitize("pointer-overflow"))) +#define __ubsan_ignore_function__ __attribute__((no_sanitize("function"))) +#define __ubsan_ignore_float_cast_overflow__ \ + __attribute__((no_sanitize("float-cast-overflow"))) +#else +#define __ubsan_ignore_float_divide_by_zero__ +#define __ubsan_ignore_undefined__ +#define __ubsan_ignore_signed_int_overflow__ +#define __ubsan_ignore_pointer_overflow__ +#define __ubsan_ignore_function__ +#define __ubsan_ignore_float_cast_overflow__ +#endif + +// Detect address sanitizer as some stuff doesn't work with it +#undef C10_ASAN_ENABLED + +// for clang +#if defined(__has_feature) +#if ((__has_feature(address_sanitizer))) +#define C10_ASAN_ENABLED 1 +#endif +#endif + +// for gcc +#if defined(__SANITIZE_ADDRESS__) +#if __SANITIZE_ADDRESS__ +#if !defined(C10_ASAN_ENABLED) +#define C10_ASAN_ENABLED 1 +#endif +#endif +#endif + +#if !defined(C10_ASAN_ENABLED) +#define C10_ASAN_ENABLED 0 +#endif + +// Detect undefined-behavior sanitizer (UBSAN) +#undef C10_UBSAN_ENABLED + +// for clang or gcc >= 14 +// NB: gcc 14 adds support for Clang's __has_feature +// https://gcc.gnu.org/gcc-14/changes.html +// gcc < 14 doesn't have a macro for UBSAN +// (e.g. __SANITIZE_UNDEFINED__ does not exist in gcc) +// https://github.com/google/sanitizers/issues/765 +#if defined(__has_feature) +#if ((__has_feature(undefined_behavior_sanitizer))) +#define C10_UBSAN_ENABLED 1 +#endif +#endif + +#if !defined(C10_UBSAN_ENABLED) +#define C10_UBSAN_ENABLED 0 +#endif + +// Disable the copy and assignment operator for a class. Note that this will +// disable the usage of the class in std containers. +#define C10_DISABLE_COPY_AND_ASSIGN(classname) \ + classname(const classname&) = delete; \ + classname& operator=(const classname&) = delete + +#define C10_CONCATENATE_IMPL(s1, s2) s1##s2 +#define C10_CONCATENATE(s1, s2) C10_CONCATENATE_IMPL(s1, s2) + +#define C10_MACRO_EXPAND(args) args + +#define C10_STRINGIZE_IMPL(x) #x +#define C10_STRINGIZE(x) C10_STRINGIZE_IMPL(x) + +/** + * C10_ANONYMOUS_VARIABLE(str) introduces a new identifier which starts with + * str and ends with a unique number. + */ +#ifdef __COUNTER__ +#define C10_UID __COUNTER__ +#define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __COUNTER__) +#else +#define C10_UID __LINE__ +#define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __LINE__) +#endif + +#ifdef __has_cpp_attribute +#define C10_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +#define C10_HAS_CPP_ATTRIBUTE(x) (0) +#endif + +/// Bind a returned reference/pointer's lifetime to a parameter (or *this) so +/// Clang can warn when it would dangle. Expands to nothing on compilers that +/// lack the attribute (e.g. non-clang, older nvcc). +#if C10_HAS_CPP_ATTRIBUTE(clang::lifetimebound) +#define C10_LIFETIMEBOUND [[clang::lifetimebound]] +#else +#define C10_LIFETIMEBOUND +#endif + +#ifndef FBCODE_CAFFE2 +/// DEPRECATED: Warn if a type or return value is discarded. +#define C10_NODISCARD [[nodiscard]] + +/// DEPRECATED: Suppress an unused variable. +#define C10_UNUSED [[maybe_unused]] +#endif + +#if !defined(__has_attribute) +#define __has_attribute(x) 0 +#endif + +// Direct port of LLVM_ATTRIBUTE_USED. +#if __has_attribute(used) +#define C10_USED __attribute__((__used__)) +#else +#define C10_USED +#endif + +#define C10_RESTRICT __restrict + +#ifdef __cplusplus + +// Simply define the namespace, in case a dependent library want to refer to +// the c10 namespace but not any nontrivial files. +namespace c10 {} +namespace c10::cuda {} +namespace c10::hip {} +namespace c10::xpu {} + +// Since C10 is the core library for caffe2 (and aten), we will simply reroute +// all abstractions defined in c10 to be available in caffe2 as well. +// This is only for backwards compatibility. Please use the symbols from the +// c10 namespace where possible. +namespace caffe2 { +using namespace c10; +} +namespace at { +using namespace c10; +} +namespace at::cuda { +using namespace c10::cuda; +} // namespace at::cuda + +// WARNING!!! THIS IS A GIANT HACK!!! +// This line means you cannot simultaneously include c10/hip +// and c10/cuda and then use them from the at::cuda namespace. +// This is true in practice, because HIPIFY works inplace on +// files in ATen/cuda, so it assumes that c10::hip is available +// from at::cuda. This namespace makes that happen. When +// HIPIFY is no longer out-of-place, we can switch the cuda +// here to hip and everyone is happy. +namespace at::cuda { +using namespace c10::hip; +} // namespace at::cuda + +namespace at::xpu { +using namespace c10::xpu; +} // namespace at::xpu + +#endif // __cplusplus + +// C10_LIKELY/C10_UNLIKELY +// +// These macros provide parentheses, so you can use these macros as: +// +// if C10_LIKELY(some_expr) { +// ... +// } +// +// NB: static_cast to boolean is mandatory in C++, because __builtin_expect +// takes a long argument, which means you may trigger the wrong conversion +// without it. +// +#if defined(__GNUC__) || defined(__ICL) || defined(__clang__) +#define C10_LIKELY(expr) (__builtin_expect(static_cast(expr), 1)) +#define C10_UNLIKELY(expr) (__builtin_expect(static_cast(expr), 0)) +#else +#define C10_LIKELY(expr) (expr) +#define C10_UNLIKELY(expr) (expr) +#endif + +/// C10_NOINLINE - Functions whose declaration is annotated with this will not +/// be inlined. +#ifdef __GNUC__ +#define C10_NOINLINE __attribute__((noinline)) +#elif _MSC_VER +#define C10_NOINLINE __declspec(noinline) +#else +#define C10_NOINLINE +#endif + +#if defined(_MSC_VER) +#define C10_ALWAYS_INLINE __forceinline +#elif __has_attribute(always_inline) || defined(__GNUC__) +#define C10_ALWAYS_INLINE __attribute__((__always_inline__)) inline +#else +#define C10_ALWAYS_INLINE inline +#endif + +// Unlike C10_ALWAYS_INLINE, C10_ALWAYS_INLINE_ATTRIBUTE can be used +// on a lambda. +#if defined(_MSC_VER) +// MSVC 14.39 is reasonably recent and doesn't like +// [[msvc::forceinline]] on a lambda, so don't try to use it. +#define C10_ALWAYS_INLINE_ATTRIBUTE +#elif __has_attribute(always_inline) || defined(__GNUC__) +#define C10_ALWAYS_INLINE_ATTRIBUTE __attribute__((__always_inline__)) +#else +#define C10_ALWAYS_INLINE_ATTRIBUTE +#endif + +#if defined(_MSC_VER) +#define C10_ATTR_VISIBILITY_HIDDEN +#elif defined(__GNUC__) +#define C10_ATTR_VISIBILITY_HIDDEN __attribute__((__visibility__("hidden"))) +#else +#define C10_ATTR_VISIBILITY_HIDDEN +#endif + +#define C10_ERASE C10_ALWAYS_INLINE C10_ATTR_VISIBILITY_HIDDEN + +#ifdef __cplusplus +#include +#else +#include +#endif + +#ifdef __HIPCC__ +// Unlike CUDA, HIP requires a HIP header to be included for __host__ to work. +// We do this #include here so that C10_HOST_DEVICE and friends will Just Work. +// See https://github.com/ROCm/hip/issues/441 +#include +#endif + +#if defined(__CUDACC__) || defined(__HIPCC__) +// Designates functions callable from the host (CPU) and the device (GPU) +#define C10_HOST_DEVICE __host__ __device__ +#define C10_DEVICE __device__ +#define C10_HOST __host__ +// constants from +// (https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications) +// The maximum number of threads per multiprocessor is 1024 for Turing +// architecture (7.5), 1536 for Geforce Ampere (8.6)/Jetson Orin (8.7), and +// 2048 for all other architectures. You'll get warnings if you exceed these +// constants. Hence, the following macros adjust the input values from the user +// to resolve potential warnings. +#if __CUDA_ARCH__ == 750 +constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1024; +#elif __CUDA_ARCH__ == 860 || __CUDA_ARCH__ == 870 || __CUDA_ARCH__ == 890 || \ + __CUDA_ARCH__ == 1200 +constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1536; +#else +constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 2048; +#endif +// CUDA_MAX_THREADS_PER_BLOCK is same for all architectures currently +constexpr uint32_t CUDA_MAX_THREADS_PER_BLOCK = 1024; +// CUDA_THREADS_PER_BLOCK_FALLBACK is the "canonical fallback" choice of block +// size. 256 is a good number for this fallback and should give good occupancy +// and versatility across all architectures. +constexpr uint32_t CUDA_THREADS_PER_BLOCK_FALLBACK = 256; +// NOTE: if you are thinking of constexpr-ify the inputs to launch bounds, it +// turns out that although __launch_bounds__ can take constexpr, it +// can't take a constexpr that has anything to do with templates. +// Currently we use launch_bounds that depend on template arguments in +// Loops.cuh, Reduce.cuh and LossCTC.cuh. Hence, C10_MAX_THREADS_PER_BLOCK +// and C10_MIN_BLOCKS_PER_SM are kept as macros. +// Suppose you were planning to write __launch_bounds__(a, b), based on your +// performance tuning on a modern GPU. Instead, you should write +// __launch_bounds__(C10_MAX_THREADS_PER_BLOCK(a), C10_MIN_BLOCKS_PER_SM(a, b)), +// which will also properly respect limits on old architectures. +#define C10_MAX_THREADS_PER_BLOCK(val) \ + (((val) <= CUDA_MAX_THREADS_PER_BLOCK) ? (val) \ + : CUDA_THREADS_PER_BLOCK_FALLBACK) +#define C10_MIN_BLOCKS_PER_SM(threads_per_block, blocks_per_sm) \ + ((((threads_per_block) * (blocks_per_sm) <= CUDA_MAX_THREADS_PER_SM) \ + ? (blocks_per_sm) \ + : ((CUDA_MAX_THREADS_PER_SM + (threads_per_block) - 1) / \ + (threads_per_block)))) +// C10_LAUNCH_BOUNDS is analogous to __launch_bounds__ +#define C10_LAUNCH_BOUNDS_0 \ + __launch_bounds__( \ + 256, 4) // default launch bounds that should give good occupancy and + // versatility across all architectures. +#define C10_LAUNCH_BOUNDS_1(max_threads_per_block) \ + __launch_bounds__((C10_MAX_THREADS_PER_BLOCK((max_threads_per_block)))) +#define C10_LAUNCH_BOUNDS_2(max_threads_per_block, min_blocks_per_sm) \ + __launch_bounds__( \ + (C10_MAX_THREADS_PER_BLOCK((max_threads_per_block))), \ + (C10_MIN_BLOCKS_PER_SM((max_threads_per_block), (min_blocks_per_sm)))) +#else +#define C10_HOST_DEVICE +#define C10_HOST +#define C10_DEVICE +#endif + +#if defined(USE_ROCM) +#define C10_HIP_HOST_DEVICE __host__ __device__ +#else +#define C10_HIP_HOST_DEVICE +#endif + +// C10_WARP_SIZE is only allowed for device code. +// Host code dynamically-sized launch configs _must_ use at::cuda::warp_size(). +// Host or device statically-sized arrays _must_ use either +// C10_WARP_SIZE_UPPER_BOUND or C10_WARP_SIZE_LOWER_BOUND, as needed. +// +// HIP header used to define warpSize as a constexpr that was either 32 or 64 +// depending on the target device, and then always set it to 64 for host code. +// For a time, that allowed C10_WARP_SIZE to be defined like so: +// +// #ifdef USE_ROCM +// #define C10_WARP_SIZE warpSize +// #else +// #define C10_WARP_SIZE 32 +// #endif +// +// In ROCm 7, warpSize is no longer constexpr, matching CUDA behavior. +// We can now only use warpSize for C10_WARP_SIZE in device code and this is +// enforced by using __device__ in its definition. In host code where +// C10_WARP_SIZE was previously used as a compile-time constant, this will now +// cause a compile-time error. +// +// If an array was previously expected to be sized at compile-time using +// C10_WARP_SIZE, users must now use either C10_WARP_SIZE_UPPER_BOUND or +// C10_WARP_SIZE_LOWER_BOUND depending on the situation. +// +// If C10_WARP_SIZE was previously used to determine kernel launch sizes, users +// must now use at::cuda::warp_size() for the dynamic runtime query. +// +// Unfortunately, C10_WARP_SIZE has been public and available for both host and +// device since approximately 2019, so forcing it to be device-only would break +// existing code in the wild. +#if defined(USE_ROCM) +namespace at::cuda { +TORCH_CUDA_CPP_API int warp_size(); +} +#if defined(__HIPCC__) +static __host__ inline int C10_WARP_SIZE_INTERNAL() { + return at::cuda::warp_size(); +} +// NOTE: __device__ C10_WARP_SIZE_INTERNAL +// For __SPIRV__, we must use dynamic warpSize. When not targeting __SPIRV__, +// we can use constexpr. This matches prior behavior. We preserve this for +// backward compatibility instead of forcing old code to use dynamic warpSize +// and losing constexpr. However, compiling for --offload-arch=amdgcnspirv +// could expose where C10_WARP_SIZE was used incorrectly where the dynamic +// warpSize is not allowed. +#if defined(__SPIRV__) +static __device__ inline int C10_WARP_SIZE_INTERNAL() { + return warpSize; +} +#else // __SPIRV__ +static __device__ inline constexpr int C10_WARP_SIZE_INTERNAL() { +#if defined(__GFX9__) + return 64; +#else // __GFX9__ + return 32; +#endif // __GFX9__ +} +#endif // __SPIRV__ +#if defined(__SPIRV__) +#define C10_WARP_SIZE_LOWER_BOUND 32 +#define C10_WARP_SIZE_UPPER_BOUND 64 +#elif defined(__GFX9__) +#define C10_WARP_SIZE_LOWER_BOUND 64 +#define C10_WARP_SIZE_UPPER_BOUND 64 +#else +#define C10_WARP_SIZE_LOWER_BOUND 32 +#define C10_WARP_SIZE_UPPER_BOUND 32 +#endif +#else // !__HIPCC__ +static inline int C10_WARP_SIZE_INTERNAL() { + return at::cuda::warp_size(); +} +#define C10_WARP_SIZE_LOWER_BOUND 32 +#define C10_WARP_SIZE_UPPER_BOUND 64 +#endif // __HIPCC__ +#define C10_WARP_SIZE (C10_WARP_SIZE_INTERNAL()) +#else // !USE_ROCM +#define C10_WARP_SIZE 32 +#define C10_WARP_SIZE_LOWER_BOUND 32 +#define C10_WARP_SIZE_UPPER_BOUND 32 +#endif // USE_ROCM + +#if defined(_MSC_VER) && _MSC_VER <= 1900 +#define __func__ __FUNCTION__ +#endif + +// CUDA_KERNEL_ASSERT checks the assertion +// even when NDEBUG is defined. This is useful for important assertions in CUDA +// code that would otherwise be suppressed when building Release. +#if defined(__ANDROID__) || defined(__APPLE__) || defined(__FreeBSD__) +// Those platforms do not support assert() +#define CUDA_KERNEL_ASSERT(cond) +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) +#define SYCL_KERNEL_ASSERT(cond) +#elif defined(_MSC_VER) +#if defined(NDEBUG) +extern "C" { +C10_IMPORT +#if defined(__SYCL_DEVICE_ONLY__) +extern SYCL_EXTERNAL void _wassert( + const wchar_t* wexpr, + const wchar_t* wfile, + unsigned line); +#else +#if defined(__CUDA_ARCH__) +__host__ __device__ +#endif // __CUDA_ARCH__ + void + _wassert(wchar_t const* _Message, wchar_t const* _File, unsigned _Line); +#endif // __SYCL_DEVICE_ONLY__ +} +#endif // NDEBUG +#define CUDA_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +// TODO: This doesn't assert the message because I (chilli) couldn't figure out +// a nice way to convert a char* to a wchar_t* +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(printf( \ + "[CUDA_KERNEL_ASSERT] " __FILE__ ":" C10_STRINGIZE( \ + __LINE__) ": %s: block: [%d,%d,%d], thread: [%d,%d,%d]: " \ + "Assertion failed: `%s`: " msg "\n", \ + __func__, \ + blockIdx.x, \ + blockIdx.y, \ + blockIdx.z, \ + threadIdx.x, \ + threadIdx.y, \ + threadIdx.z, \ + #cond, \ + ##__VA_ARGS__)); \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +#define SYCL_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +#else // __APPLE__, _MSC_VER +#if defined(NDEBUG) +extern "C" { +#if defined(__SYCL_DEVICE_ONLY__) +extern SYCL_EXTERNAL void __assert_fail( + const char* expr, + const char* file, + unsigned int line, + const char* func); +#elif (defined(__EMSCRIPTEN__)) +// As defined in assert.h in the Emscripten stdlib +_Noreturn void __assert_fail( + const char* expr, + const char* file, + int line, + const char* func); +#else // __SYCL_DEVICE_ONLY__ +#if (defined(__CUDA_ARCH__) && !(defined(__clang__) && defined(__CUDA__))) +// CUDA supports __assert_fail function which are common for both device +// and host side code. +__host__ __device__ +#endif + + // This forward declaration matching the declaration of __assert_fail + // exactly how it is in glibc in case parts of the program are compiled with + // different NDEBUG settings. Otherwise we might get 'ambiguous declaration' + // error. Note: On ROCm - this declaration serves for host side compilation. + void + __assert_fail( + const char* assertion, + const char* file, + unsigned int line, + const char* function) noexcept __attribute__((__noreturn__)); + +#endif // __SYCL_DEVICE_ONLY__ +} +#endif // NDEBUG +// ROCm disables kernel assert by default for performance considerations. +// Though ROCm supports __assert_fail, it uses kernel printf which has +// a non-negligible performance impact even if the assert condition is +// never triggered. We choose to use abort() instead which will still +// terminate the application but without a more useful error message. +#if !defined(C10_USE_ROCM_KERNEL_ASSERT) && defined(USE_ROCM) +#define CUDA_KERNEL_ASSERT(cond) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#define SYCL_KERNEL_ASSERT(cond) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#else +#if defined(USE_ROCM) && defined(__HIP_DEVICE_COMPILE__) +namespace torch::headeronly::detail { +// Compile-time string fragment for CUDA_KERNEL_ASSERT message pieces. +template +struct RoCmAssertLit { + char data[N]{}; + constexpr RoCmAssertLit(const char (&s)[N]) { + for (unsigned i = 0; i < N; ++i) { + data[i] = s[i]; + } + } + static constexpr unsigned size() { + return N; + } + constexpr unsigned percent() const { + unsigned count = 0; + for (unsigned i = 0; i < N - 1; ++i) { + if (data[i] == '%') { + ++count; + } + } + return count; + } +}; + +// OCKL is_last=1 treats the append as printf format; escape '%'. Size the +// buffer as Out + NumPercent. +template +constexpr auto rocm_assert_concat() { + constexpr unsigned out = A.size() + B.size() + C.size() - 2; + constexpr unsigned pct = A.percent() + B.percent() + C.percent(); + struct { + char data[out + pct]; + unsigned length; + } msg{}; + unsigned j = 0; + auto append = [&](const char* s, unsigned n) { + for (unsigned k = 0; k < n; ++k) { + if (s[k] == '%') { + msg.data[j++] = '%'; + } + msg.data[j++] = s[k]; + } + }; + append(A.data, A.size() - 1); + append(B.data, B.size() - 1); + append(C.data, C.size()); + msg.length = j; + return msg; +} + +// __host__ __device__: hipcc's device pass still type-checks host-only call +// sites (e.g. MemoryAccess.cuh LoadWithCast ctors). Host runtime uses #else +// __assert_fail; this body is not emitted for host codegen. +template +__host__ __device__ inline __attribute__((always_inline, flatten)) void +rocm_assert_one_shot(const char (&msg)[N], unsigned length) { + auto d = __ockl_fprintf_stderr_begin(); + __ockl_fprintf_append_string_n(d, msg, length, 1); + __builtin_trap(); +} +} // namespace torch::headeronly::detail + +#define ROCM_ASSERT_LIT(s) ::torch::headeronly::detail::RoCmAssertLit(s) + +#define CUDA_KERNEL_ASSERT(cond) \ + if C10_UNLIKELY (!(cond)) { \ + static constexpr auto _rocm_assert_msg = \ + ::torch::headeronly::detail::rocm_assert_concat< \ + ROCM_ASSERT_LIT(__FILE__ ":" C10_STRINGIZE(__LINE__) ": "), \ + ROCM_ASSERT_LIT(__func__), \ + ROCM_ASSERT_LIT(": Device-side assertion `" #cond \ + "' failed.\n")>(); \ + ::torch::headeronly::detail::rocm_assert_one_shot( \ + _rocm_assert_msg.data, _rocm_assert_msg.length); \ + } +#else +#define CUDA_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + __assert_fail( \ + #cond, __FILE__, static_cast(__LINE__), __func__); \ + } +#endif // defined(USE_ROCM) && defined(__HIP_DEVICE_COMPILE__) +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) \ + if (C10_UNLIKELY(!(cond))) { \ + __assert_fail( \ + msg, __FILE__, static_cast(__LINE__), __func__); \ + } +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) \ + if (C10_UNLIKELY(!(cond))) { \ + printf( \ + "[CUDA_KERNEL_ASSERT] " __FILE__ ":" C10_STRINGIZE( \ + __LINE__) ": %s: block: [%d,%d,%d], thread: [%d,%d,%d]: " \ + "Assertion failed: `%s`: " msg "\n", \ + __func__, \ + blockIdx.x, \ + blockIdx.y, \ + blockIdx.z, \ + threadIdx.x, \ + threadIdx.y, \ + threadIdx.z, \ + #cond, \ + ##__VA_ARGS__); \ + __assert_fail( \ + #cond, __FILE__, static_cast(__LINE__), __func__); \ + } +#define SYCL_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + __assert_fail( \ + #cond, __FILE__, static_cast(__LINE__), __func__); \ + } +#endif // C10_USE_ROCM_KERNEL_ASSERT && USE_ROCM +#endif // __APPLE__ + +// Compile-time switch to control how assertions are logged inside CUDA kernels. +// If C10_CUDA_VERBOSE_ASSERT is defined, CUDA_KERNEL_ASSERT_VERBOSE will +// take addition information passed to the macro and forward them to +// CUDA_KERNEL_ASSERT_PRINTF If C10_CUDA_VERBOSE_ASSERT is not defined, +// CUDA_KERNEL_ASSERT_VERBOSE will behave the same as CUDA_KERNEL_ASSERT. +#ifdef C10_ENABLE_VERBOSE_ASSERT +#define CUDA_KERNEL_ASSERT_VERBOSE(cond, ...) \ + CUDA_KERNEL_ASSERT_PRINTF(cond, __VA_ARGS__) +#else +#define CUDA_KERNEL_ASSERT_VERBOSE(cond, ...) CUDA_KERNEL_ASSERT(cond) +#endif + +#ifdef __APPLE__ +#include +#endif + +#if defined(__ANDROID__) +#define C10_ANDROID 1 +#define C10_MOBILE 1 +#elif ( \ + defined(__APPLE__) && \ + (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE)) +#define C10_IOS 1 +#define C10_MOBILE 1 +#endif // ANDROID / IOS + +#if defined(C10_MOBILE) && C10_MOBILE +#define C10_ALWAYS_INLINE_UNLESS_MOBILE inline +#else +#define C10_ALWAYS_INLINE_UNLESS_MOBILE C10_ALWAYS_INLINE +#endif + +#if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) +#define CONSTEXPR_EXCEPT_WIN_CUDA constexpr +#define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA constexpr + +#define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \ + static constexpr const char field[] = val; +#define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val) +#endif // !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) + +#ifndef HAS_DEMANGLE +#if defined(__ANDROID__) || defined(_WIN32) || defined(__EMSCRIPTEN__) +#define HAS_DEMANGLE 0 +#elif defined(__APPLE__) && \ + (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE) +#define HAS_DEMANGLE 0 +#else +#define HAS_DEMANGLE 1 +#endif +#endif // HAS_DEMANGLE + +#define _C10_PRAGMA__(string) _Pragma(#string) +#define _C10_PRAGMA_(string) _C10_PRAGMA__(string) + +#ifdef __clang__ +#define C10_CLANG_DIAGNOSTIC_PUSH() _Pragma("clang diagnostic push") +#define C10_CLANG_DIAGNOSTIC_POP() _Pragma("clang diagnostic pop") +#define C10_CLANG_DIAGNOSTIC_IGNORE(flag) \ + _C10_PRAGMA_(clang diagnostic ignored flag) +#define C10_CLANG_HAS_WARNING(flag) __has_warning(flag) +#else +#define C10_CLANG_DIAGNOSTIC_PUSH() +#define C10_CLANG_DIAGNOSTIC_POP() +#define C10_CLANG_DIAGNOSTIC_IGNORE(flag) +#define C10_CLANG_HAS_WARNING(flag) 0 +#endif + +#ifdef __clang__ + +#define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \ + _C10_PRAGMA_(clang diagnostic push) \ + _C10_PRAGMA_(clang diagnostic ignored "-Wunknown-warning-option") \ + _C10_PRAGMA_(clang diagnostic ignored warning) + +#define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(clang diagnostic pop) + +#elif __GNUC__ + +#define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \ + _C10_PRAGMA_(GCC diagnostic push) \ + _C10_PRAGMA_(GCC diagnostic ignored "-Wpragmas") \ + _C10_PRAGMA_(GCC diagnostic ignored warning) + +#define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(GCC diagnostic pop) + +#else + +#define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) +#define C10_DIAGNOSTIC_POP() + +#endif + +// This macro is used to find older C++ compilers +// that don't support move optimization for return values. + +#if (defined(__GNUC__) && __GNUC__ < 13 && __cplusplus < 202002L) || \ + (defined(__clang_major__) && __clang_major__ < 13) +#define C10_RETURN_MOVE_IF_OLD_COMPILER 1 +#else +#define C10_RETURN_MOVE_IF_OLD_COMPILER 0 +#endif + +// The HIDDEN_NAMESPACE_BEGIN and HIDDEN_NAMESPACE_END below +// are needed for maintaining robustness in our header APIs in +// torch/headeronly and torch/csrc/stable under the namespaces +// torch::headeronly and torch::stable respectively. We enforce +// hidden visibility for these APIs because we want to enable +// loading custom extensions compiled against different libtorch +// versions where these APIs may have changed. + +// Helper macros to handle 1-3 hidden namespace levels when not windows +#define _HIDDEN_NS_GET_MACRO(_1, _2, _3, NAME, ...) NAME +#define _HIDDEN_NS_1(n1) namespace n1 __attribute__((visibility("hidden"))) { +#define _HIDDEN_NS_2(n1, n2) \ + namespace n1 { \ + namespace n2 __attribute__((visibility("hidden"))) { +#define _HIDDEN_NS_3(n1, n2, n3) \ + namespace n1::n2 { \ + namespace n3 __attribute__((visibility("hidden"))) { + +// Helper macros to close namespaces when not windows +#define _HIDDEN_NS_END_1(n1) } +#define _HIDDEN_NS_END_N(n1, ...) \ + } \ + } + +// Helper macros to join strs with :: (for win, where symbols are hidden by +// default) +#define _EXPAND(...) __VA_ARGS__ +#define _JOIN_GET_MACRO(_1, _2, _3, NAME, ...) NAME +#define _JOIN_NS1(a) a +#define _JOIN_NS2(a, b) a::b +#define _JOIN_NS3(a, b, c) a::b::c + +#if !defined(HIDDEN_NAMESPACE_BEGIN) +#if defined(__GNUG__) && !defined(_WIN32) +#define HIDDEN_NAMESPACE_BEGIN(...) \ + _HIDDEN_NS_GET_MACRO( \ + __VA_ARGS__, _HIDDEN_NS_3, _HIDDEN_NS_2, _HIDDEN_NS_1)(__VA_ARGS__) +#else +#define HIDDEN_NAMESPACE_BEGIN(...) \ + namespace _EXPAND(_JOIN_GET_MACRO( \ + __VA_ARGS__, _JOIN_NS3, _JOIN_NS2, _JOIN_NS1)(__VA_ARGS__)) { +#endif +#endif + +#if !defined(HIDDEN_NAMESPACE_END) +#if defined(__GNUG__) && !defined(_WIN32) +#define HIDDEN_NAMESPACE_END(...) \ + _HIDDEN_NS_GET_MACRO( \ + __VA_ARGS__, _HIDDEN_NS_END_N, _HIDDEN_NS_END_N, _HIDDEN_NS_END_1)( \ + __VA_ARGS__) +#else +#define HIDDEN_NAMESPACE_END(...) } +#endif +#endif + +#endif // C10_MACROS_MACROS_H_ diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/BFloat16-math.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/BFloat16-math.h new file mode 100644 index 0000000..257ef24 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/BFloat16-math.h @@ -0,0 +1,337 @@ +#pragma once + +#include +#include +#include + +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion") +#endif + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +template +struct is_reduced_floating_point + : std::integral_constant< + bool, + std::is_same_v || std::is_same_v> {}; + +template +constexpr bool is_reduced_floating_point_v = + is_reduced_floating_point::value; +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace c10 { +using torch::headeronly::is_reduced_floating_point; +using torch::headeronly::is_reduced_floating_point_v; +} // namespace c10 + +namespace std { + +#if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) +using torch::headeronly::is_reduced_floating_point; +using torch::headeronly::is_reduced_floating_point_v; +#endif // !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) + +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T acos(T a) { + return std::acos(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T asin(T a) { + return std::asin(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T atan(T a) { + return std::atan(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T atanh(T a) { + return std::atanh(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T erf(T a) { + return std::erf(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T erfc(T a) { + return std::erfc(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T exp(T a) { + return std::exp(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T expm1(T a) { + return std::expm1(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline bool isfinite(T a) { + return std::isfinite(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T log(T a) { + return std::log(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T log10(T a) { + return std::log10(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T log1p(T a) { + return std::log1p(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T log2(T a) { + return std::log2(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T ceil(T a) { + return std::ceil(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T cos(T a) { + return std::cos(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T floor(T a) { + return std::floor(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T nearbyint(T a) { + return std::nearbyint(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T sin(T a) { + return std::sin(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T tan(T a) { + return std::tan(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T sinh(T a) { + return std::sinh(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T cosh(T a) { + return std::cosh(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T tanh(T a) { + return std::tanh(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T trunc(T a) { + return std::trunc(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T lgamma(T a) { + return std::lgamma(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T sqrt(T a) { + return std::sqrt(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T rsqrt(T a) { + return 1.0f / std::sqrt(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T abs(T a) { + return std::abs(float(a)); +} +#if defined(_MSC_VER) && defined(__CUDACC__) +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T pow(T a, double b) { + return std::pow(float(a), float(b)); +} +#else +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T pow(T a, double b) { + return std::pow(float(a), b); +} +#endif +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T pow(T a, T b) { + return std::pow(float(a), float(b)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T fmod(T a, T b) { + return std::fmod(float(a), float(b)); +} + +/* + The following function is inspired from the implementation in `musl` + Link to License: https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT + ---------------------------------------------------------------------- + Copyright © 2005-2020 Rich Felker, et al. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + ---------------------------------------------------------------------- + */ +template < + typename T, + typename std:: + enable_if_t, int> = 0> +C10_HOST_DEVICE inline T nextafter(T from, T to) { + // Reference: + // https://git.musl-libc.org/cgit/musl/tree/src/math/nextafter.c + using int_repr_t = uint16_t; + constexpr uint8_t bits = 16; + union { + T f; + int_repr_t i; + } ufrom = {from}, uto = {to}; + + // get a mask to get the sign bit i.e. MSB + int_repr_t sign_mask = int_repr_t{1} << (bits - 1); + + // short-circuit: if either is NaN, return NaN + if (from != from || to != to) { + return from + to; + } + + // short-circuit: if they are exactly the same. + if (ufrom.i == uto.i) { + return from; + } + + // mask the sign-bit to zero i.e. positive + // equivalent to abs(x) + int_repr_t abs_from = ufrom.i & ~sign_mask; + int_repr_t abs_to = uto.i & ~sign_mask; + if (abs_from == 0) { + // if both are zero but with different sign, + // preserve the sign of `to`. + if (abs_to == 0) { + return to; + } + // smallest subnormal with sign of `to`. + ufrom.i = (uto.i & sign_mask) | int_repr_t{1}; + return ufrom.f; + } + + // if abs(from) > abs(to) or sign(from) != sign(to) + if (abs_from > abs_to || ((ufrom.i ^ uto.i) & sign_mask)) { + ufrom.i--; + } else { + ufrom.i++; + } + + return ufrom.f; +} + +} // namespace std + +C10_CLANG_DIAGNOSTIC_POP() diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/BFloat16.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/BFloat16.h new file mode 100644 index 0000000..2c6ce79 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/BFloat16.h @@ -0,0 +1,481 @@ +#pragma once + +// Defines the bloat16 type (brain floating-point). This representation uses +// 1 bit for the sign, 8 bits for the exponent and 7 bits for the mantissa. + +#include +#include + +#include +#include +#include +#include +#include + +#if defined(__CUDACC__) && (!defined(USE_ROCM) || (TORCH_HIP_VERSION >= 702)) +#include +#endif + +#if defined(CL_SYCL_LANGUAGE_VERSION) +#include // for SYCL 1.2.1 +#elif defined(SYCL_LANGUAGE_VERSION) +#include // for SYCL 2020 +#endif + +namespace c10 { + +struct alignas(2) BFloat16 { + uint16_t x; + + // HIP wants __host__ __device__ tag, CUDA does not +#if defined(USE_ROCM) && defined(__HIPCC__) + C10_HOST_DEVICE BFloat16() = default; +#else + BFloat16() = default; +#endif + + struct from_bits_t {}; + static constexpr C10_HOST_DEVICE from_bits_t from_bits() { + return from_bits_t(); + } + + constexpr C10_HOST_DEVICE BFloat16( + unsigned short bits, + from_bits_t /*unused*/) + : x(bits) {} + /* implicit */ inline C10_HOST_DEVICE BFloat16(float value); + inline C10_HOST_DEVICE operator float() const; + +#if defined(__CUDACC__) && (!defined(USE_ROCM) || (TORCH_HIP_VERSION >= 702)) + inline C10_HOST_DEVICE BFloat16(const __nv_bfloat16& value); + explicit inline C10_HOST_DEVICE operator __nv_bfloat16() const; +#endif + +#if defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) + inline C10_HOST_DEVICE BFloat16(const sycl::ext::oneapi::bfloat16& value); + explicit inline C10_HOST_DEVICE operator sycl::ext::oneapi::bfloat16() const; +#endif +}; + +inline std::ostream& operator<<(std::ostream& out, const BFloat16& value) { + out << (float)value; + return out; +} + +namespace detail { +inline C10_HOST_DEVICE float f32_from_bits(uint16_t src) { + float res = 0; + uint32_t tmp = src; + tmp <<= 16; + +#if defined(USE_ROCM) && defined(__HIPCC__) + float* tempRes; + + // We should be using memcpy in order to respect the strict aliasing rule + // but it fails in the HIP environment. + tempRes = reinterpret_cast(&tmp); + res = *tempRes; +#else + std::memcpy(&res, &tmp, sizeof(tmp)); +#endif + + return res; +} + +inline C10_HOST_DEVICE uint16_t bits_from_f32(float src) { + uint32_t res = 0; + +#if defined(USE_ROCM) && defined(__HIPCC__) + // We should be using memcpy in order to respect the strict aliasing rule + // but it fails in the HIP environment. + uint32_t* tempRes = reinterpret_cast(&src); + res = *tempRes; +#else + std::memcpy(&res, &src, sizeof(res)); +#endif + + return res >> 16; +} + +inline C10_HOST_DEVICE uint16_t round_to_nearest_even(float src) { +#if defined(USE_ROCM) && defined(__HIPCC__) + if (src != src) { +#elif defined(_MSC_VER) + if (isnan(src)) { +#else + if (std::isnan(src)) { +#endif + return UINT16_C(0x7FC0); + } else { + const uint32_t U32 = c10::bit_cast(src); + uint32_t rounding_bias = ((U32 >> 16) & 1) + UINT32_C(0x7FFF); + return static_cast((U32 + rounding_bias) >> 16); + } +} + +} // namespace detail + +//-------- the following is copied from c10/util/BFloat16-inl.h ---------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +/// Constructors +inline C10_HOST_DEVICE BFloat16::BFloat16(float value) + : +#if defined(__CUDACC__) && \ + (!defined(USE_ROCM) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 || \ + defined(USE_ROCM) && (TORCH_HIP_VERSION >= 702)) + x(__bfloat16_as_ushort(__float2bfloat16(value))) +#elif defined(__SYCL_DEVICE_ONLY__) && \ + defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) + x(c10::bit_cast(sycl::ext::oneapi::bfloat16(value))) +#else + // RNE by default + x(detail::round_to_nearest_even(value)) +#endif +{ +} + +/// Implicit conversions +inline C10_HOST_DEVICE BFloat16::operator float() const { +#if defined(__CUDACC__) && (!defined(USE_ROCM) || (TORCH_HIP_VERSION >= 702)) + return __bfloat162float(*reinterpret_cast(&x)); +#elif defined(__SYCL_DEVICE_ONLY__) && \ + defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) + return float(*reinterpret_cast(&x)); +#else + return detail::f32_from_bits(x); +#endif +} + +#if defined(__CUDACC__) && (!defined(USE_ROCM) || (TORCH_HIP_VERSION >= 702)) +inline C10_HOST_DEVICE BFloat16::BFloat16(const __nv_bfloat16& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE BFloat16::operator __nv_bfloat16() const { + return *reinterpret_cast(&x); +} +#endif + +#if defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) +inline C10_HOST_DEVICE BFloat16::BFloat16( + const sycl::ext::oneapi::bfloat16& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE BFloat16::operator sycl::ext::oneapi::bfloat16() const { + return *reinterpret_cast(&x); +} +#endif + +// CUDA intrinsics + +#if defined(__CUDACC__) || defined(__HIPCC__) +inline C10_DEVICE BFloat16 __ldg(const BFloat16* ptr) { +#if !defined(USE_ROCM) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + return __ldg(reinterpret_cast(ptr)); +#else + return *ptr; +#endif +} +#endif + +/// Arithmetic + +inline C10_HOST_DEVICE BFloat16 +operator+(const BFloat16& a, const BFloat16& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 +operator-(const BFloat16& a, const BFloat16& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 +operator*(const BFloat16& a, const BFloat16& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator/(const BFloat16& a, const BFloat16& b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator-(const BFloat16& a) { + return -static_cast(a); +} + +inline C10_HOST_DEVICE BFloat16& operator+=(BFloat16& a, const BFloat16& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator-=(BFloat16& a, const BFloat16& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator*=(BFloat16& a, const BFloat16& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator/=(BFloat16& a, const BFloat16& b) { + a = a / b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator|(BFloat16& a, const BFloat16& b) { + a.x = a.x | b.x; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator^(BFloat16& a, const BFloat16& b) { + a.x = a.x ^ b.x; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator&(BFloat16& a, const BFloat16& b) { + a.x = a.x & b.x; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(BFloat16 a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(BFloat16 a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(BFloat16 a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(BFloat16 a, float b) { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, BFloat16 b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, BFloat16 b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, BFloat16 b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, BFloat16 b) { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const BFloat16& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const BFloat16& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const BFloat16& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const BFloat16& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(BFloat16 a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(BFloat16 a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(BFloat16 a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(BFloat16 a, double b) { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, BFloat16 b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, BFloat16 b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, BFloat16 b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, BFloat16 b) { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE BFloat16 operator+(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator-(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator*(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator/(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator+(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE BFloat16 operator-(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE BFloat16 operator*(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE BFloat16 operator/(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE BFloat16 operator+(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator-(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator*(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator/(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator+(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE BFloat16 operator-(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE BFloat16 operator*(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE BFloat16 operator/(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +// Overloading < and > operators, because std::max and std::min use them. + +inline C10_HOST_DEVICE bool operator>(BFloat16& lhs, BFloat16& rhs) { + return float(lhs) > float(rhs); +} + +inline C10_HOST_DEVICE bool operator<(BFloat16& lhs, BFloat16& rhs) { + return float(lhs) < float(rhs); +} + +C10_CLANG_DIAGNOSTIC_POP() +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +namespace detail { +using c10::detail::bits_from_f32; +using c10::detail::f32_from_bits; +using c10::detail::round_to_nearest_even; +} // namespace detail + +using c10::BFloat16; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +using c10::operator<; +using c10::operator>; +using c10::operator<<; +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_signed = true; + static constexpr bool is_specialized = true; + static constexpr bool is_integer = false; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = true; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = true; + static constexpr auto has_denorm = numeric_limits::has_denorm; + static constexpr auto has_denorm_loss = + numeric_limits::has_denorm_loss; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = false; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 8; + static constexpr int digits10 = 2; + static constexpr int max_digits10 = 4; + static constexpr int radix = 2; + static constexpr int min_exponent = -125; + static constexpr int min_exponent10 = -37; + static constexpr int max_exponent = 128; + static constexpr int max_exponent10 = 38; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = + numeric_limits::tinyness_before; + + static constexpr c10::BFloat16 min() { + return c10::BFloat16(0x0080, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 lowest() { + return c10::BFloat16(0xFF7F, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 max() { + return c10::BFloat16(0x7F7F, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 epsilon() { + return c10::BFloat16(0x3C00, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 round_error() { + return c10::BFloat16(0x3F00, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 infinity() { + return c10::BFloat16(0x7F80, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 quiet_NaN() { + return c10::BFloat16(0x7FC0, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 signaling_NaN() { + return c10::BFloat16(0x7FA0, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 denorm_min() { + return c10::BFloat16(0x0001, c10::BFloat16::from_bits()); + } +}; + +} // namespace std diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/Half.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/Half.h new file mode 100644 index 0000000..4014723 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/Half.h @@ -0,0 +1,788 @@ +#pragma once + +/// Defines the Half type (half-precision floating-point) including conversions +/// to standard C types and basic arithmetic operations. Note that arithmetic +/// operations are implemented by converting to floating point and +/// performing the operation in float32, instead of using CUDA half intrinsics. +/// Most uses of this type within ATen are memory bound, including the +/// element-wise kernels, and the half intrinsics aren't efficient on all GPUs. +/// If you are writing a compute bound kernel, you can use the CUDA half +/// intrinsics directly on the Half type from device code. + +#include +#include +#include + +#if defined(__cplusplus) +#include +#elif !defined(__OPENCL_VERSION__) +#include +#endif + +#ifdef _MSC_VER +#include +#endif + +#include +#include +#include + +#ifdef __CUDACC__ +#include +#endif + +#ifdef __HIPCC__ +#include +#endif + +#if defined(CL_SYCL_LANGUAGE_VERSION) +#include // for SYCL 1.2.1 +#elif defined(SYCL_LANGUAGE_VERSION) +#include // for SYCL 2020 +#endif + +#if (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) +#include +#endif + +#if defined(__aarch64__) && !defined(__CUDACC__) +#include +#endif + +#if defined(__GNUC__) || defined(__clang__) +#if defined(__x86_64__) || defined(_M_X64) || defined(__i386) || \ + defined(_M_IX86) +#if defined(__F16C__) && \ + !(defined(__CUDA_ARCH__) || defined(__CUDACC__) || \ + defined(__HIP_DEVICE_COMPILE__)) +#define C10_X86_F16 1 +#include // import conversion ops from f16cintrin.h +#endif // defined(__F16C__) && !(defined(__CUDA_ARCH__) || defined(__CUDACC__) + // || defined(__HIP_DEVICE_COMPILE__)) +#endif // __x86_64__ || _M_X64 || __i386 || _M_IX86 +#endif // __GNUC__ || __clang__ + +namespace c10 { + +struct alignas(2) Half { + unsigned short x; + + struct from_bits_t {}; + C10_HOST_DEVICE static constexpr from_bits_t from_bits() { + return from_bits_t(); + } + + // HIP wants __host__ __device__ tag, CUDA does not +#if defined(USE_ROCM) + C10_HOST_DEVICE Half() = default; +#else + Half() = default; +#endif + + constexpr C10_HOST_DEVICE Half(unsigned short bits, from_bits_t /*unused*/) + : x(bits) {} +#if defined(__aarch64__) && !defined(__CUDACC__) + inline Half(float16_t value); + inline operator float16_t() const; +#else + inline C10_HOST_DEVICE Half(float value); + inline C10_HOST_DEVICE operator float() const; +#endif + +#if defined(__CUDACC__) || defined(__HIPCC__) + inline C10_HOST_DEVICE Half(const __half& value); + inline C10_HOST_DEVICE operator __half() const; +#endif +#ifdef SYCL_LANGUAGE_VERSION + inline C10_HOST_DEVICE Half(const sycl::half& value); + inline C10_HOST_DEVICE operator sycl::half() const; +#endif +}; + +inline std::ostream& operator<<(std::ostream& out, const Half& value) { + out << (float)value; + return out; +} + +namespace detail { +/* + * Convert a 16-bit floating-point number in IEEE half-precision format, in bit + * representation, to a 32-bit floating-point number in IEEE single-precision + * format. + * + * @note The implementation relies on IEEE-like (no assumption about rounding + * mode and no operations on denormals) floating-point operations and bitcasts + * between integer and floating-point variables. + */ +C10_HOST_DEVICE inline float fp16_ieee_to_fp32_value(uint16_t h) { +#ifdef C10_X86_F16 + return _cvtsh_ss(h); +#else + /* + * Extend the half-precision floating-point number to 32 bits and shift to the + * upper part of the 32-bit word: + * +---+-----+------------+-------------------+ + * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000| + * +---+-----+------------+-------------------+ + * Bits 31 26-30 16-25 0-15 + * + * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0 + * - zero bits. + */ + const uint32_t w = (uint32_t)h << 16; + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = w & UINT32_C(0x80000000); + /* + * Extract mantissa and biased exponent of the input number into the high bits + * of the 32-bit word: + * + * +-----+------------+---------------------+ + * |EEEEE|MM MMMM MMMM|0 0000 0000 0000 0000| + * +-----+------------+---------------------+ + * Bits 27-31 17-26 0-16 + */ + const uint32_t two_w = w + w; + + /* + * Shift mantissa and exponent into bits 23-28 and bits 13-22 so they become + * mantissa and exponent of a single-precision floating-point number: + * + * S|Exponent | Mantissa + * +-+---+-----+------------+----------------+ + * |0|000|EEEEE|MM MMMM MMMM|0 0000 0000 0000| + * +-+---+-----+------------+----------------+ + * Bits | 23-31 | 0-22 + * + * Next, there are some adjustments to the exponent: + * - The exponent needs to be corrected by the difference in exponent bias + * between single-precision and half-precision formats (0x7F - 0xF = 0x70) + * - Inf and NaN values in the inputs should become Inf and NaN values after + * conversion to the single-precision number. Therefore, if the biased + * exponent of the half-precision input was 0x1F (max possible value), the + * biased exponent of the single-precision output must be 0xFF (max possible + * value). We do this correction in two steps: + * - First, we adjust the exponent by (0xFF - 0x1F) = 0xE0 (see exp_offset + * below) rather than by 0x70 suggested by the difference in the exponent bias + * (see above). + * - Then we multiply the single-precision result of exponent adjustment by + * 2**(-112) to reverse the effect of exponent adjustment by 0xE0 less the + * necessary exponent adjustment by 0x70 due to difference in exponent bias. + * The floating-point multiplication hardware would ensure than Inf and + * NaN would retain their value on at least partially IEEE754-compliant + * implementations. + * + * Note that the above operations do not handle denormal inputs (where biased + * exponent == 0). However, they also do not operate on denormal inputs, and + * do not produce denormal results. + */ + constexpr uint32_t exp_offset = UINT32_C(0xE0) << 23; + // const float exp_scale = 0x1.0p-112f; + constexpr uint32_t scale_bits = (uint32_t)15 << 23; + float exp_scale_val = 0; +#if defined(_MSC_VER) && defined(__clang__) + __builtin_memcpy(&exp_scale_val, &scale_bits, sizeof(exp_scale_val)); +#else + std::memcpy(&exp_scale_val, &scale_bits, sizeof(exp_scale_val)); +#endif + + const float exp_scale = exp_scale_val; + const float normalized_value = + fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale; + + /* + * Convert denormalized half-precision inputs into single-precision results + * (always normalized). Zero inputs are also handled here. + * + * In a denormalized number the biased exponent is zero, and mantissa has + * on-zero bits. First, we shift mantissa into bits 0-9 of the 32-bit word. + * + * zeros | mantissa + * +---------------------------+------------+ + * |0000 0000 0000 0000 0000 00|MM MMMM MMMM| + * +---------------------------+------------+ + * Bits 10-31 0-9 + * + * Now, remember that denormalized half-precision numbers are represented as: + * FP16 = mantissa * 2**(-24). + * The trick is to construct a normalized single-precision number with the + * same mantissa and the half-precision input and with an exponent which would + * scale the corresponding mantissa bits to 2**(-24). A normalized + * single-precision floating-point number is represented as: FP32 = (1 + + * mantissa * 2**(-23)) * 2**(exponent - 127) Therefore, when the biased + * exponent is 126, a unit change in the mantissa of the input denormalized + * half-precision number causes a change of the constructed single-precision + * number by 2**(-24), i.e. the same amount. + * + * The last step is to adjust the bias of the constructed single-precision + * number. When the input half-precision number is zero, the constructed + * single-precision number has the value of FP32 = 1 * 2**(126 - 127) = + * 2**(-1) = 0.5 Therefore, we need to subtract 0.5 from the constructed + * single-precision number to get the numerical equivalent of the input + * half-precision number. + */ + constexpr uint32_t magic_mask = UINT32_C(126) << 23; + constexpr float magic_bias = 0.5f; + const float denormalized_value = + fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias; + + /* + * - Choose either results of conversion of input as a normalized number, or + * as a denormalized number, depending on the input exponent. The variable + * two_w contains input exponent in bits 27-31, therefore if it's smaller than + * 2**27, the input is either a denormal number, or zero. + * - Combine the result of conversion of exponent and mantissa with the sign + * of the input number. + */ + constexpr uint32_t denormalized_cutoff = UINT32_C(1) << 27; + const uint32_t result = sign | + (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) + : fp32_to_bits(normalized_value)); + return fp32_from_bits(result); +#endif // C10_X86_F16 +} + +/* + * Convert a 32-bit floating-point number in IEEE single-precision format to a + * 16-bit floating-point number in IEEE half-precision format, in bit + * representation. + * + * @note The implementation relies on IEEE-like (no assumption about rounding + * mode and no operations on denormals) floating-point operations and bitcasts + * between integer and floating-point variables. + */ +inline uint16_t fp16_ieee_from_fp32_value(float f) { +#ifdef C10_X86_F16 + return _cvtss_sh(f, _MM_FROUND_TO_NEAREST_INT); +#else + // const float scale_to_inf = 0x1.0p+112f; + // const float scale_to_zero = 0x1.0p-110f; + constexpr uint32_t scale_to_inf_bits = (uint32_t)239 << 23; + constexpr uint32_t scale_to_zero_bits = (uint32_t)17 << 23; + float scale_to_inf_val = 0, scale_to_zero_val = 0; + std::memcpy(&scale_to_inf_val, &scale_to_inf_bits, sizeof(scale_to_inf_val)); + std::memcpy( + &scale_to_zero_val, &scale_to_zero_bits, sizeof(scale_to_zero_val)); + const float scale_to_inf = scale_to_inf_val; + const float scale_to_zero = scale_to_zero_val; + +#if defined(_MSC_VER) && _MSC_VER == 1916 + float base = ((signbit(f) != 0 ? -f : f) * scale_to_inf) * scale_to_zero; +#else + float base = (fabsf(f) * scale_to_inf) * scale_to_zero; +#endif + + const uint32_t w = fp32_to_bits(f); + const uint32_t shl1_w = w + w; + const uint32_t sign = w & UINT32_C(0x80000000); + uint32_t bias = shl1_w & UINT32_C(0xFF000000); + if (bias < UINT32_C(0x71000000)) { + bias = UINT32_C(0x71000000); + } + + base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base; + const uint32_t bits = fp32_to_bits(base); + const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00); + const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF); + const uint32_t nonsign = exp_bits + mantissa_bits; + return static_cast( + (sign >> 16) | + (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign)); +#endif // C10_X86_F16 +} + +/* + * Convert a 16-bit floating-point number in IEEE half-precision format, in bit + * representation, to a 32-bit floating-point number in IEEE single-precision + * format, in bit representation. + * + * @note The implementation doesn't use any floating-point operations. + */ +inline uint32_t fp16_ieee_to_fp32_bits(uint16_t h) { + /* + * Extend the half-precision floating-point number to 32 bits and shift to the + * upper part of the 32-bit word: + * +---+-----+------------+-------------------+ + * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000| + * +---+-----+------------+-------------------+ + * Bits 31 26-30 16-25 0-15 + * + * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0 + * - zero bits. + */ + const uint32_t w = (uint32_t)h << 16; + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = w & UINT32_C(0x80000000); + /* + * Extract mantissa and biased exponent of the input number into the bits 0-30 + * of the 32-bit word: + * + * +---+-----+------------+-------------------+ + * | 0 |EEEEE|MM MMMM MMMM|0000 0000 0000 0000| + * +---+-----+------------+-------------------+ + * Bits 30 27-31 17-26 0-16 + */ + const uint32_t nonsign = w & UINT32_C(0x7FFFFFFF); + /* + * Renorm shift is the number of bits to shift mantissa left to make the + * half-precision number normalized. If the initial number is normalized, some + * of its high 6 bits (sign == 0 and 5-bit exponent) equals one. In this case + * renorm_shift == 0. If the number is denormalize, renorm_shift > 0. Note + * that if we shift denormalized nonsign by renorm_shift, the unit bit of + * mantissa will shift into exponent, turning the biased exponent into 1, and + * making mantissa normalized (i.e. without leading 1). + */ +#ifdef _MSC_VER + unsigned long nonsign_bsr; + _BitScanReverse(&nonsign_bsr, (unsigned long)nonsign); + uint32_t renorm_shift = (uint32_t)nonsign_bsr ^ 31; +#else + uint32_t renorm_shift = __builtin_clz(nonsign); +#endif + renorm_shift = renorm_shift > 5 ? renorm_shift - 5 : 0; + /* + * Iff half-precision number has exponent of 15, the addition overflows + * it into bit 31, and the subsequent shift turns the high 9 bits + * into 1. Thus inf_nan_mask == 0x7F800000 if the half-precision number + * had exponent of 15 (i.e. was NaN or infinity) 0x00000000 otherwise + */ + const int32_t inf_nan_mask = + ((int32_t)(nonsign + 0x04000000) >> 8) & INT32_C(0x7F800000); + /* + * Iff nonsign is 0, it overflows into 0xFFFFFFFF, turning bit 31 + * into 1. Otherwise, bit 31 remains 0. The signed shift right by 31 + * broadcasts bit 31 into all bits of the zero_mask. Thus zero_mask == + * 0xFFFFFFFF if the half-precision number was zero (+0.0h or -0.0h) + * 0x00000000 otherwise + */ + const int32_t zero_mask = (int32_t)(nonsign - 1) >> 31; + /* + * 1. Shift nonsign left by renorm_shift to normalize it (if the input + * was denormal) + * 2. Shift nonsign right by 3 so the exponent (5 bits originally) + * becomes an 8-bit field and 10-bit mantissa shifts into the 10 high + * bits of the 23-bit mantissa of IEEE single-precision number. + * 3. Add 0x70 to the exponent (starting at bit 23) to compensate the + * different in exponent bias (0x7F for single-precision number less 0xF + * for half-precision number). + * 4. Subtract renorm_shift from the exponent (starting at bit 23) to + * account for renormalization. As renorm_shift is less than 0x70, this + * can be combined with step 3. + * 5. Binary OR with inf_nan_mask to turn the exponent into 0xFF if the + * input was NaN or infinity. + * 6. Binary ANDNOT with zero_mask to turn the mantissa and exponent + * into zero if the input was zero. + * 7. Combine with the sign of the input number. + */ + return sign | + ((((nonsign << renorm_shift >> 3) + ((0x70 - renorm_shift) << 23)) | + inf_nan_mask) & + ~zero_mask); +} + +#ifdef C10_X86_F16 +#undef C10_X86_F16 +#endif // C10_X86_F16 + +#if defined(__aarch64__) && !defined(__CUDACC__) +inline float16_t fp16_from_bits(uint16_t h) { + return c10::bit_cast(h); +} + +inline uint16_t fp16_to_bits(float16_t f) { + return c10::bit_cast(f); +} + +// According to https://godbolt.org/z/frExdbsWG it would translate to single +// fcvt s0, h0 +inline float native_fp16_to_fp32_value(uint16_t h) { + return static_cast(fp16_from_bits(h)); +} + +inline uint16_t native_fp16_from_fp32_value(float f) { + return fp16_to_bits(static_cast(f)); +} +#endif + +} // namespace detail + +//---------- below is copied from c10/util/Half-inl.h ----------------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +#if defined(__aarch64__) && !defined(__CUDACC__) +/// Constructors +inline Half::Half(float16_t value) : x(detail::fp16_to_bits(value)) {} +inline Half::operator float16_t() const { + return detail::fp16_from_bits(x); +} +#else + +inline C10_HOST_DEVICE Half::Half(float value) + : +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + x(__half_as_short(__float2half(value))) +#elif defined(__SYCL_DEVICE_ONLY__) + x(c10::bit_cast(sycl::half(value))) +#elif (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) + x(at::vec::float2half_scalar(value)) +#else + x(detail::fp16_ieee_from_fp32_value(value)) +#endif +{ +} + +/// Implicit conversions + +inline C10_HOST_DEVICE Half::operator float() const { +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + return __half2float(*reinterpret_cast(&x)); +#elif defined(__SYCL_DEVICE_ONLY__) + return float(c10::bit_cast(x)); +#elif (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) + return at::vec::half2float_scalar(x); +#elif defined(__aarch64__) && !defined(__CUDACC__) + return detail::native_fp16_to_fp32_value(x); +#else + return detail::fp16_ieee_to_fp32_value(x); +#endif +} + +#endif /* !defined(__aarch64__) || defined(__CUDACC__) \ + */ + +#if defined(__CUDACC__) || defined(__HIPCC__) +inline C10_HOST_DEVICE Half::Half(const __half& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE Half::operator __half() const { + return *reinterpret_cast(&x); +} +#endif + +#ifdef SYCL_LANGUAGE_VERSION +inline C10_HOST_DEVICE Half::Half(const sycl::half& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE Half::operator sycl::half() const { + return *reinterpret_cast(&x); +} +#endif + +// CUDA intrinsics + +#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 350)) || \ + (defined(__clang__) && defined(__CUDA__)) +inline __device__ Half __ldg(const Half* ptr) { + return __ldg(reinterpret_cast(ptr)); +} +#endif + +/// Arithmetic + +inline C10_HOST_DEVICE Half operator+(const Half& a, const Half& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE Half operator-(const Half& a, const Half& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE Half operator*(const Half& a, const Half& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE Half operator/(const Half& a, const Half& b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE Half operator-(const Half& a) { +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530) || \ + defined(__HIP_DEVICE_COMPILE__) + return __hneg(a); +#elif defined(__SYCL_DEVICE_ONLY__) + return -c10::bit_cast(a); +#else + return -static_cast(a); +#endif +} + +inline C10_HOST_DEVICE Half& operator+=(Half& a, const Half& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE Half& operator-=(Half& a, const Half& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE Half& operator*=(Half& a, const Half& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE Half& operator/=(Half& a, const Half& b) { + a = a / b; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(Half a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(Half a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(Half a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(Half a, float b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, Half b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, Half b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, Half b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, Half b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const Half& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const Half& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const Half& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const Half& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(Half a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(Half a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(Half a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(Half a, double b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, Half b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, Half b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, Half b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, Half b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE Half operator+(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Half operator-(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Half operator*(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Half operator/(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Half operator+(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Half operator-(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Half operator*(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Half operator/(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE Half operator+(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Half operator-(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Half operator*(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Half operator/(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Half operator+(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Half operator-(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Half operator*(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Half operator/(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) / b; +} + +/// NOTE: we do not define comparisons directly and instead rely on the implicit +/// conversion from c10::Half to float. + +C10_CLANG_DIAGNOSTIC_POP() + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +using c10::Half; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +using c10::operator<<; + +namespace detail { +#if defined(__aarch64__) && !defined(__CUDACC__) +using c10::detail::fp16_from_bits; +using c10::detail::fp16_to_bits; +using c10::detail::native_fp16_from_fp32_value; +using c10::detail::native_fp16_to_fp32_value; +#endif + +using c10::detail::fp16_ieee_from_fp32_value; +using c10::detail::fp16_ieee_to_fp32_bits; +using c10::detail::fp16_ieee_to_fp32_value; +} // namespace detail + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_specialized = true; + static constexpr bool is_signed = true; + static constexpr bool is_integer = false; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = true; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = true; + static constexpr auto has_denorm = numeric_limits::has_denorm; + static constexpr auto has_denorm_loss = + numeric_limits::has_denorm_loss; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = true; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 11; + static constexpr int digits10 = 3; + static constexpr int max_digits10 = 5; + static constexpr int radix = 2; + static constexpr int min_exponent = -13; + static constexpr int min_exponent10 = -4; + static constexpr int max_exponent = 16; + static constexpr int max_exponent10 = 4; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = + numeric_limits::tinyness_before; + static constexpr c10::Half min() { + return c10::Half(0x0400, c10::Half::from_bits()); + } + static constexpr c10::Half lowest() { + return c10::Half(0xFBFF, c10::Half::from_bits()); + } + static constexpr c10::Half max() { + return c10::Half(0x7BFF, c10::Half::from_bits()); + } + static constexpr c10::Half epsilon() { + return c10::Half(0x1400, c10::Half::from_bits()); + } + static constexpr c10::Half round_error() { + return c10::Half(0x3800, c10::Half::from_bits()); + } + static constexpr c10::Half infinity() { + return c10::Half(0x7C00, c10::Half::from_bits()); + } + static constexpr c10::Half quiet_NaN() { + return c10::Half(0x7E00, c10::Half::from_bits()); + } + static constexpr c10::Half signaling_NaN() { + return c10::Half(0x7D00, c10::Half::from_bits()); + } + static constexpr c10::Half denorm_min() { + return c10::Half(0x0001, c10::Half::from_bits()); + } +}; + +} // namespace std diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/TypeSafeSignMath.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/TypeSafeSignMath.h new file mode 100644 index 0000000..8e89795 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/TypeSafeSignMath.h @@ -0,0 +1,100 @@ +#pragma once + +#include +#include +#include + +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wstring-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wstring-conversion") +#endif +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +namespace c10 { + +/// Returns true if x < 0 +/// NOTE: Will fail on an unsigned custom type +/// For the most part it's possible to fix this if +/// the custom type has a constexpr constructor. +/// However, notably, c10::Half does not :-( +template +inline constexpr bool is_negative(const T& x) { + if constexpr (std::is_unsigned_v) { + // An unsigned value can never be less than zero. + return false; + } else { + return x < T(0); + } +} + +/// Returns the sign of x as -1, 0, 1 +/// NOTE: Will fail on an unsigned custom type +/// For the most part it's possible to fix this if +/// the custom type has a constexpr constructor. +/// However, notably, c10::Half does not :-( +template +inline constexpr int signum(const T& x) { + if constexpr (std::is_unsigned_v) { + return T(0) < x; + } else { + return (T(0) < x) - (x < T(0)); + } +} + +/// Returns true if a and b are not both negative +template +inline constexpr bool signs_differ(const T& a, const U& b) { + return is_negative(a) != is_negative(b); +} + +// Suppress sign compare warning when compiling with GCC +// as later does not account for short-circuit rule before +// raising the warning, see https://godbolt.org/z/Tr3Msnz99 +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wsign-compare" +#endif + +/// Returns true if x is greater than the greatest value of the type Limit +template +inline constexpr bool greater_than_max(const T& x) { + constexpr bool can_overflow = + std::numeric_limits::digits > std::numeric_limits::digits; + return can_overflow && x > std::numeric_limits::max(); +} + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +/// Returns true if x is less than the lowest value of type Limit +/// NOTE: Will fail on an unsigned custom type +/// For the most part it's possible to fix this if +/// the custom type has a constexpr constructor. +/// However, notably, c10::Half does not : +template +inline constexpr bool less_than_lowest(const T& x) { + if constexpr (std::is_unsigned_v) { + // x is unsigned, so it can never be below the lowest value of any type. + return false; + } else if constexpr (std::is_unsigned_v) { + // Limit is unsigned, so its lowest value is zero. + return x < T(0); + } else { + return x < std::numeric_limits::lowest(); + } +} + +} // namespace c10 + +C10_CLANG_DIAGNOSTIC_POP() + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::greater_than_max; +using c10::is_negative; +using c10::less_than_lowest; +using c10::signs_differ; +using c10::signum; +HIDDEN_NAMESPACE_END(torch, headeronly) diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/bit_cast.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/bit_cast.h new file mode 100644 index 0000000..3f357f8 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/bit_cast.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include + +#include + +#if __has_include() && (defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L) +#include +#define C10_HAVE_STD_BIT_CAST 1 +#else +#define C10_HAVE_STD_BIT_CAST 0 +#endif // __has_include() && (__cplusplus >= 202002L || + // (defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L)) + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +#if C10_HAVE_STD_BIT_CAST +using std::bit_cast; +#else +// Implementations of std::bit_cast() from C++ 20. +// +// This is a less sketchy version of reinterpret_cast. +// +// See https://en.cppreference.com/w/cpp/numeric/bit_cast for more +// information as well as the source of our implementations. +template +C10_HOST_DEVICE std::enable_if_t< + sizeof(To) == sizeof(From) && std::is_trivially_copyable_v && + std::is_trivially_copyable_v, + To> +// constexpr support needs compiler magic +bit_cast(const From& src) noexcept { + static_assert( + std::is_trivially_constructible_v, + "This implementation additionally requires " + "destination type to be trivially constructible"); + + To dst; + std::memcpy(&dst, &src, sizeof(To)); + return dst; +} +#endif // C10_HAVE_STD_BIT_CAST +#undef C10_HAVE_STD_BIT_CAST + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace c10 { +using torch::headeronly::bit_cast; +} // namespace c10 diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/complex.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/complex.h new file mode 100644 index 0000000..265b250 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/complex.h @@ -0,0 +1,676 @@ +#pragma once + +#include + +#include +#include +#include + +#if defined(__CUDACC__) || defined(__HIPCC__) +#include +#endif + +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion") +#endif +#if C10_CLANG_HAS_WARNING("-Wfloat-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wfloat-conversion") +#endif + +namespace c10 { + +// c10::complex is an implementation of complex numbers that aims +// to work on all devices supported by PyTorch +// +// Most of the APIs duplicates std::complex +// Reference: https://en.cppreference.com/w/cpp/numeric/complex +// +// [NOTE: Complex Operator Unification] +// Operators currently use a mix of std::complex, thrust::complex, and +// c10::complex internally. The end state is that all operators will use +// c10::complex internally. Until then, there may be some hacks to support all +// variants. +// +// +// [Note on Constructors] +// +// The APIs of constructors are mostly copied from C++ standard: +// https://en.cppreference.com/w/cpp/numeric/complex/complex +// +// Since C++14, all constructors are constexpr in std::complex +// +// There are three types of constructors: +// - initializing from real and imag: +// `constexpr complex( const T& re = T(), const T& im = T() );` +// - implicitly-declared copy constructor +// - converting constructors +// +// Converting constructors: +// - std::complex defines converting constructor between float/double/long +// double, +// while we define converting constructor between float/double. +// - For these converting constructors, upcasting is implicit, downcasting is +// explicit. +// - We also define explicit casting from std::complex/thrust::complex +// - Note that the conversion from thrust is not constexpr, because +// thrust does not define them as constexpr ???? +// +// +// [Operator =] +// +// The APIs of operator = are mostly copied from C++ standard: +// https://en.cppreference.com/w/cpp/numeric/complex/operator%3D +// +// Since C++20, all operator= are constexpr. Although we are not building with +// C++20, we also obey this behavior. +// +// There are three types of assign operator: +// - Assign a real value from the same scalar type +// - In std, this is templated as complex& operator=(const T& x) +// with specialization `complex& operator=(T x)` for float/double/long +// double Since we only support float and double, on will use `complex& +// operator=(T x)` +// - Copy assignment operator and converting assignment operator +// - There is no specialization of converting assignment operators, which type +// is +// convertible is solely dependent on whether the scalar type is convertible +// +// In addition to the standard assignment, we also provide assignment operators +// with std and thrust +// +// +// [Casting operators] +// +// std::complex does not have casting operators. We define casting operators +// casting to std::complex and thrust::complex +// +// +// [Operator ""] +// +// std::complex has custom literals `i`, `if` and `il` defined in namespace +// `std::literals::complex_literals`. We define our own custom literals in the +// namespace `c10::complex_literals`. Our custom literals does not follow the +// same behavior as in std::complex, instead, we define _if, _id to construct +// float/double complex literals. +// +// +// [real() and imag()] +// +// In C++20, there are two overload of these functions, one it to return the +// real/imag, another is to set real/imag, they are both constexpr. We follow +// this design. +// +// +// [Operator +=,-=,*=,/=] +// +// Since C++20, these operators become constexpr. In our implementation, they +// are also constexpr. +// +// There are two types of such operators: operating with a real number, or +// operating with another complex number. For the operating with a real number, +// the generic template form has argument type `const T &`, while the overload +// for float/double/long double has `T`. We will follow the same type as +// float/double/long double in std. +// +// [Unary operator +-] +// +// Since C++20, they are constexpr. We also make them expr +// +// [Binary operators +-*/] +// +// Each operator has three versions (taking + as example): +// - complex + complex +// - complex + real +// - real + complex +// +// [Operator ==, !=] +// +// Each operator has three versions (taking == as example): +// - complex == complex +// - complex == real +// - real == complex +// +// Some of them are removed on C++20, but we decide to keep them +// +// [Operator <<, >>] +// +// These are implemented by casting to std::complex +// +// +// +// TODO(@zasdfgbnm): c10::complex is not currently supported, +// because: +// - lots of members and functions of c10::Half are not constexpr +// - thrust::complex only support float and double + +template +struct alignas(sizeof(T) * 2) complex { + using value_type = T; + + T real_ = T(0); + T imag_ = T(0); + + constexpr complex() = default; + C10_HOST_DEVICE constexpr complex(const T& re, const T& im = T()) + : real_(re), imag_(im) {} + template + explicit constexpr complex(const std::complex& other) + : complex(other.real(), other.imag()) {} +#if defined(__CUDACC__) || defined(__HIPCC__) + template + explicit C10_HOST_DEVICE complex(const thrust::complex& other) + : real_(other.real()), imag_(other.imag()) {} +// NOTE can not be implemented as follows due to ROCm bug: +// explicit C10_HOST_DEVICE complex(const thrust::complex &other): +// complex(other.real(), other.imag()) {} +#endif + + // Use SFINAE to specialize casting constructor for c10::complex and + // c10::complex + template + C10_HOST_DEVICE explicit constexpr complex( + const std::enable_if_t, complex>& other) + : real_(other.real_), imag_(other.imag_) {} + template + C10_HOST_DEVICE constexpr complex( + const std::enable_if_t, complex>& other) + : real_(other.real_), imag_(other.imag_) {} + + constexpr complex& operator=(T re) { + real_ = re; + imag_ = 0; + return *this; + } + + constexpr complex& operator+=(T re) { + real_ += re; + return *this; + } + + constexpr complex& operator-=(T re) { + real_ -= re; + return *this; + } + + constexpr complex& operator*=(T re) { + real_ *= re; + imag_ *= re; + return *this; + } + + constexpr complex& operator/=(T re) { + real_ /= re; + imag_ /= re; + return *this; + } + + template + constexpr complex& operator=(const complex& rhs) { + real_ = rhs.real(); + imag_ = rhs.imag(); + return *this; + } + + template + constexpr complex& operator+=(const complex& rhs) { + real_ += rhs.real(); + imag_ += rhs.imag(); + return *this; + } + + template + constexpr complex& operator-=(const complex& rhs) { + real_ -= rhs.real(); + imag_ -= rhs.imag(); + return *this; + } + + template + constexpr complex& operator*=(const complex& rhs) { + // (a + bi) * (c + di) = (a*c - b*d) + (a * d + b * c) i + T a = real_; + T b = imag_; + U c = rhs.real(); + U d = rhs.imag(); + real_ = a * c - b * d; + imag_ = a * d + b * c; + return *this; + } + +#ifdef __APPLE__ +#define FORCE_INLINE_APPLE __attribute__((always_inline)) +#else +#define FORCE_INLINE_APPLE +#endif + template + constexpr FORCE_INLINE_APPLE complex& operator/=(const complex& rhs) + __ubsan_ignore_float_divide_by_zero__ { + // (a + bi) / (c + di) = (ac + bd)/(c^2 + d^2) + (bc - ad)/(c^2 + d^2) i + // the calculation below follows numpy's complex division + T a = real_; + T b = imag_; + U c = rhs.real(); + U d = rhs.imag(); + +#if defined(__GNUC__) && !defined(__clang__) + // std::abs is already constexpr by gcc + auto abs_c = std::abs(c); + auto abs_d = std::abs(d); +#else + auto abs_c = c < 0 ? -c : c; + auto abs_d = d < 0 ? -d : d; +#endif + + if (abs_c >= abs_d) { + if (abs_c == U(0) && abs_d == U(0)) { + /* divide by zeros should yield a complex inf or nan */ + real_ = a / abs_c; + imag_ = b / abs_d; + } else { + auto rat = d / c; + auto scl = U(1.0) / (c + d * rat); + real_ = (a + b * rat) * scl; + imag_ = (b - a * rat) * scl; + } + } else { + auto rat = c / d; + auto scl = U(1.0) / (d + c * rat); + real_ = (a * rat + b) * scl; + imag_ = (b * rat - a) * scl; + } + return *this; + } +#undef FORCE_INLINE_APPLE + + template + constexpr complex& operator=(const std::complex& rhs) { + real_ = rhs.real(); + imag_ = rhs.imag(); + return *this; + } + +#if defined(__CUDACC__) || defined(__HIPCC__) + template + C10_HOST_DEVICE complex& operator=(const thrust::complex& rhs) { + real_ = rhs.real(); + imag_ = rhs.imag(); + return *this; + } +#endif + + template + explicit constexpr operator std::complex() const { + return std::complex(std::complex(real(), imag())); + } + +#if defined(__CUDACC__) || defined(__HIPCC__) + template + C10_HOST_DEVICE explicit operator thrust::complex() const { + return static_cast>(thrust::complex(real(), imag())); + } +#endif + + // consistent with NumPy behavior + explicit constexpr operator bool() const { + return real() || imag(); + } + + C10_HOST_DEVICE constexpr T real() const { + return real_; + } + constexpr void real(T value) { + real_ = value; + } + C10_HOST_DEVICE constexpr T imag() const { + return imag_; + } + constexpr void imag(T value) { + imag_ = value; + } +}; + +namespace complex_literals { + +constexpr complex operator""_if(long double imag) { + return complex(0.0f, static_cast(imag)); +} + +constexpr complex operator""_id(long double imag) { + return complex(0.0, static_cast(imag)); +} + +constexpr complex operator""_if(unsigned long long imag) { + return complex(0.0f, static_cast(imag)); +} + +constexpr complex operator""_id(unsigned long long imag) { + return complex(0.0, static_cast(imag)); +} + +} // namespace complex_literals + +template +constexpr complex operator+(const complex& val) { + return val; +} + +template +constexpr complex operator-(const complex& val) { + return complex(-val.real(), -val.imag()); +} + +template +constexpr complex operator+(const complex& lhs, const complex& rhs) { + complex result = lhs; + return result += rhs; +} + +template +constexpr complex operator+(const complex& lhs, const T& rhs) { + complex result = lhs; + return result += rhs; +} + +template +constexpr complex operator+(const T& lhs, const complex& rhs) { + return complex(lhs + rhs.real(), rhs.imag()); +} + +template +constexpr complex operator-(const complex& lhs, const complex& rhs) { + complex result = lhs; + return result -= rhs; +} + +template +constexpr complex operator-(const complex& lhs, const T& rhs) { + complex result = lhs; + return result -= rhs; +} + +template +constexpr complex operator-(const T& lhs, const complex& rhs) { + complex result = -rhs; + return result += lhs; +} + +template +constexpr complex operator*(const complex& lhs, const complex& rhs) { + complex result = lhs; + return result *= rhs; +} + +template +constexpr complex operator*(const complex& lhs, const T& rhs) { + complex result = lhs; + return result *= rhs; +} + +template +constexpr complex operator*(const T& lhs, const complex& rhs) { + complex result = rhs; + return result *= lhs; +} + +template +constexpr complex operator/(const complex& lhs, const complex& rhs) { + complex result = lhs; + return result /= rhs; +} + +template +constexpr complex operator/(const complex& lhs, const T& rhs) { + complex result = lhs; + return result /= rhs; +} + +template +constexpr complex operator/(const T& lhs, const complex& rhs) { + complex result(lhs, T()); + return result /= rhs; +} + +// Define operators between integral scalars and c10::complex. std::complex does +// not support this when T is a floating-point number. This is useful because it +// saves a lot of "static_cast" when operate a complex and an integer. This +// makes the code both less verbose and potentially more efficient. +#define COMPLEX_INTEGER_OP_TEMPLATE_CONDITION \ + typename std::enable_if_t< \ + std::is_floating_point_v && std::is_integral_v, \ + int> = 0 + +template +constexpr c10::complex operator+(const c10::complex& a, const iT& b) { + return a + static_cast(b); +} + +template +constexpr c10::complex operator+(const iT& a, const c10::complex& b) { + return static_cast(a) + b; +} + +template +constexpr c10::complex operator-(const c10::complex& a, const iT& b) { + return a - static_cast(b); +} + +template +constexpr c10::complex operator-(const iT& a, const c10::complex& b) { + return static_cast(a) - b; +} + +template +constexpr c10::complex operator*(const c10::complex& a, const iT& b) { + return a * static_cast(b); +} + +template +constexpr c10::complex operator*(const iT& a, const c10::complex& b) { + return static_cast(a) * b; +} + +template +constexpr c10::complex operator/(const c10::complex& a, const iT& b) { + return a / static_cast(b); +} + +template +constexpr c10::complex operator/(const iT& a, const c10::complex& b) { + return static_cast(a) / b; +} + +#undef COMPLEX_INTEGER_OP_TEMPLATE_CONDITION + +template +constexpr bool operator==(const complex& lhs, const complex& rhs) { + return (lhs.real() == rhs.real()) && (lhs.imag() == rhs.imag()); +} + +template +constexpr bool operator==(const complex& lhs, const T& rhs) { + return (lhs.real() == rhs) && (lhs.imag() == T()); +} + +template +constexpr bool operator==(const T& lhs, const complex& rhs) { + return (lhs == rhs.real()) && (T() == rhs.imag()); +} + +template +constexpr bool operator!=(const complex& lhs, const complex& rhs) { + return !(lhs == rhs); +} + +template +constexpr bool operator!=(const complex& lhs, const T& rhs) { + return !(lhs == rhs); +} + +template +constexpr bool operator!=(const T& lhs, const complex& rhs) { + return !(lhs == rhs); +} + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const complex& x) { + return (os << static_cast>(x)); +} + +template +std::basic_istream& operator>>( + std::basic_istream& is, + complex& x) { + std::complex tmp; + is >> tmp; + x = tmp; + return is; +} + +template +C10_HOST_DEVICE complex polar(const T& r, const T& theta = T()) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>(thrust::polar(r, theta)); +#else + // std::polar() requires r >= 0, so spell out the explicit implementation to + // avoid a branch. + return complex(r * std::cos(theta), r * std::sin(theta)); +#endif +} + +template <> +struct alignas(4) complex { + Half real_; + Half imag_; + + // Constructors + complex() = default; + // Half constructor is not constexpr so the following constructor can't + // be constexpr + C10_HOST_DEVICE explicit inline complex(const Half& real, const Half& imag) + : real_(real), imag_(imag) {} + C10_HOST_DEVICE inline complex(const c10::complex& value) + : real_(value.real()), imag_(value.imag()) {} + + // Conversion operator + inline C10_HOST_DEVICE operator c10::complex() const { + return {real_, imag_}; + } + + constexpr C10_HOST_DEVICE Half real() const { + return real_; + } + constexpr C10_HOST_DEVICE Half imag() const { + return imag_; + } + + C10_HOST_DEVICE complex& operator+=(const complex& other) { + real_ = static_cast(real_) + static_cast(other.real_); + imag_ = static_cast(imag_) + static_cast(other.imag_); + return *this; + } + + C10_HOST_DEVICE complex& operator-=(const complex& other) { + real_ = static_cast(real_) - static_cast(other.real_); + imag_ = static_cast(imag_) - static_cast(other.imag_); + return *this; + } + + C10_HOST_DEVICE complex& operator*=(const complex& other) { + auto a = static_cast(real_); + auto b = static_cast(imag_); + auto c = static_cast(other.real()); + auto d = static_cast(other.imag()); + real_ = a * c - b * d; + imag_ = a * d + b * c; + return *this; + } +}; + +template <> +struct alignas(4) complex { + BFloat16 real_; + BFloat16 imag_; + + // Constructors + complex() = default; + // BFloat16 constructor is not constexpr so the following constructor can't + // be constexpr + C10_HOST_DEVICE explicit inline complex( + const BFloat16& real, + const BFloat16& imag) + : real_(real), imag_(imag) {} + C10_HOST_DEVICE inline complex(const c10::complex& value) + : real_(value.real()), imag_(value.imag()) {} + + // Conversion operator + inline C10_HOST_DEVICE operator c10::complex() const { + return {real_, imag_}; + } + + constexpr C10_HOST_DEVICE BFloat16 real() const { + return real_; + } + constexpr C10_HOST_DEVICE BFloat16 imag() const { + return imag_; + } + + C10_HOST_DEVICE complex& operator+=( + const complex& other) { + real_ = static_cast(real_) + static_cast(other.real_); + imag_ = static_cast(imag_) + static_cast(other.imag_); + return *this; + } + + C10_HOST_DEVICE complex& operator-=( + const complex& other) { + real_ = static_cast(real_) - static_cast(other.real_); + imag_ = static_cast(imag_) - static_cast(other.imag_); + return *this; + } + + C10_HOST_DEVICE complex& operator*=( + const complex& other) { + auto a = static_cast(real_); + auto b = static_cast(imag_); + auto c = static_cast(other.real()); + auto d = static_cast(other.imag()); + real_ = a * c - b * d; + imag_ = a * d + b * c; + return *this; + } +}; + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::complex; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +using c10::operator==; +using c10::operator!=; +using c10::operator<<; +using c10::operator>>; +using c10::polar; + +namespace complex_literals { +using c10::complex_literals::operator""_if; +using c10::complex_literals::operator""_id; +} // namespace complex_literals + +HIDDEN_NAMESPACE_END(torch, headeronly) + +C10_CLANG_DIAGNOSTIC_POP() + +#define C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H +// utilities for complex types +#include // IWYU pragma: keep +#undef C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/complex_utils.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/complex_utils.h new file mode 100644 index 0000000..ddc66ff --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/complex_utils.h @@ -0,0 +1,48 @@ +#pragma once + +#if !defined(C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H) +#error \ + "torch/headeronly/util/complex_utils.h is not meant to be individually included. Include torch/headeronly/util/complex.h instead." +#endif + +#include + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +template +struct is_complex : public std::false_type {}; + +template +struct is_complex> : public std::true_type {}; + +template +struct is_complex> : public std::true_type {}; + +// Extract double from std::complex; is identity otherwise +// TODO: Write in more idiomatic C++17 +template +struct scalar_value_type { + using type = T; +}; +template +struct scalar_value_type> { + using type = T; +}; +template +struct scalar_value_type> { + using type = T; +}; + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template +class numeric_limits> : public numeric_limits {}; + +template +bool isnan(const c10::complex& v) { + return std::isnan(v.real()) || std::isnan(v.imag()); +} + +} // namespace std diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/floating_point_utils.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/floating_point_utils.h new file mode 100644 index 0000000..1e60bd8 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/floating_point_utils.h @@ -0,0 +1,38 @@ +#pragma once + +#include +#include +#include + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly, detail) + +C10_HOST_DEVICE inline float fp32_from_bits(uint32_t w) { +#if defined(__OPENCL_VERSION__) + return as_float(w); +#elif defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + return __uint_as_float((unsigned int)w); +#elif defined(__INTEL_COMPILER) + return _castu32_f32(w); +#else + return torch::headeronly::bit_cast(w); +#endif +} + +C10_HOST_DEVICE inline uint32_t fp32_to_bits(float f) { +#if defined(__OPENCL_VERSION__) + return as_uint(f); +#elif defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + return (uint32_t)__float_as_uint(f); +#elif defined(__INTEL_COMPILER) + return _castf32_u32(f); +#else + return torch::headeronly::bit_cast(f); +#endif +} + +HIDDEN_NAMESPACE_END(torch, headeronly, detail) + +namespace c10::detail { +using torch::headeronly::detail::fp32_from_bits; +using torch::headeronly::detail::fp32_to_bits; +} // namespace c10::detail diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/irange.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/irange.h new file mode 100644 index 0000000..0d1bf44 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/irange.h @@ -0,0 +1,137 @@ +// Copyright 2004-present Facebook. All Rights Reserved. + +#pragma once + +#include +#include + +#include +#include +#include +#include + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +namespace detail { + +template < + typename I, + bool one_sided = false, + std::enable_if_t, int> = 0> +struct integer_iterator { + using iterator_category = std::input_iterator_tag; + using value_type = I; + using difference_type = std::ptrdiff_t; + using pointer = I*; + using reference = I&; + + C10_ALWAYS_INLINE explicit constexpr integer_iterator(I val) : value(val) {} + + C10_ALWAYS_INLINE constexpr I operator*() const { + return value; + } + + C10_ALWAYS_INLINE constexpr I const* operator->() const { + return &value; + } + + C10_ALWAYS_INLINE constexpr integer_iterator& operator++() { + ++value; + return *this; + } + + C10_ALWAYS_INLINE constexpr integer_iterator operator++(int) { + const auto copy = *this; + ++*this; + return copy; + } + + C10_ALWAYS_INLINE constexpr bool operator==( + const integer_iterator& other) const { + if constexpr (one_sided) { + // Range-for loops' end test is `begin != end`, not `begin < + // end`. To handle `irange(n)` where n < 0 (which should be + // empty), we just make `begin != end` fail whenever `end` is + // negative. + return is_negative(other.value) || value == other.value; + } else { + return value == other.value; + } + // Suppress "warning: missing return statement at end of non-void function" + // which Nvidia's Robert Crovella confirms is an NVCC compiler error + // here https://stackoverflow.com/a/64561686/752843 on 2020-10-27 + // `__builtin_unreachable();` would be best here, but it's not + // available with all compilers. So we instead return an arbitrary + // value trusting that this line will, in fact, never be reached. + return false; // Horrible hack + } + + C10_ALWAYS_INLINE constexpr bool operator!=( + const integer_iterator& other) const { + return !(*this == other); + } + + protected: + I value; +}; + +} // namespace detail + +template < + typename I, + bool one_sided = false, + std::enable_if_t, bool> = true> +struct integer_range { + public: + C10_ALWAYS_INLINE constexpr integer_range(I begin, I end) + : begin_(begin), end_(end) {} + using iterator = detail::integer_iterator; + C10_ALWAYS_INLINE constexpr iterator begin() const { + return begin_; + } + C10_ALWAYS_INLINE constexpr iterator end() const { + return end_; + } + + private: + iterator begin_; + iterator end_; +}; + +/// Creates an integer range for the half-open interval [begin, end) +/// If end<=begin, then the range is empty. +/// The range has the type of the `end` integer; `begin` integer is +/// cast to this type. +template < + typename Integer1, + typename Integer2, + std::enable_if_t, bool> = true, + std::enable_if_t, bool> = true> +C10_ALWAYS_INLINE constexpr integer_range irange( + Integer1 begin, + Integer2 end) { + // If end<=begin then the range is empty; we can achieve this effect by + // choosing the larger of {begin, end} as the loop terminator + return { + static_cast(begin), + std::max(static_cast(begin), end)}; +} + +/// Creates an integer range for the half-open interval [0, end) +/// If end<=begin, then the range is empty +template < + typename Integer, + std::enable_if_t, bool> = true> +C10_ALWAYS_INLINE constexpr integer_range irange(Integer end) { + return {Integer(), end}; +} + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace c10 { +using torch::headeronly::integer_range; +using torch::headeronly::irange; +namespace detail { +using torch::headeronly::detail::integer_iterator; +} // namespace detail +} // namespace c10 diff --git a/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/overflows.h b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/overflows.h new file mode 100644 index 0000000..6e68311 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/c10/torch/headeronly/util/overflows.h @@ -0,0 +1,120 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace c10 { +// In some versions of MSVC, there will be a compiler error when building. +// C4146: unary minus operator applied to unsigned type, result still unsigned +// C4804: unsafe use of type 'bool' in operation +// It can be addressed by disabling the following warning. +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4146) +#pragma warning(disable : 4804) +#pragma warning(disable : 4018) +#endif + +// The overflow checks may involve float to int conversion which may +// trigger precision loss warning. Re-enable the warning once the code +// is fixed. See T58053069. +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion") +#endif + +// bool can be converted to any type. +// Without specializing on bool, in pytorch_linux_trusty_py2_7_9_build: +// `error: comparison of constant '255' with boolean expression is always false` +// for `f > limit::max()` below +template +std::enable_if_t, bool> overflows( + From /*f*/, + bool strict_unsigned [[maybe_unused]] = false) { + return false; +} + +// skip isnan and isinf check for integral types +template +std::enable_if_t && !std::is_same_v, bool> +overflows(From f, bool strict_unsigned = false) { + using limit = std::numeric_limits< + typename torch::headeronly::scalar_value_type::type>; + if constexpr (!limit::is_signed && std::numeric_limits::is_signed) { + // allow for negative numbers to wrap using two's complement arithmetic. + // For example, with uint8, this allows for `a - b` to be treated as + // `a + 255 * b`. + if (!strict_unsigned) { + return c10::greater_than_max(f) || + (c10::is_negative(f) && + -static_cast(f) > static_cast(limit::max())); + } + } + return c10::less_than_lowest(f) || c10::greater_than_max(f); +} + +template +std::enable_if_t, bool> overflows( + From f, + bool strict_unsigned [[maybe_unused]] = false) { + using ToScalar = typename torch::headeronly::scalar_value_type::type; + using limit = std::numeric_limits; + if (limit::has_infinity && std::isinf(static_cast(f))) { + return false; + } + if (!limit::has_quiet_NaN && (f != f)) { + return true; + } + if constexpr (std::is_integral_v) { + // limit::max() for wide integer types is NOT exactly representable in + // floating point (e.g. int64 max = 2^63-1 rounds up to 2^63), so `f > + // limit::max()` lets a just-out-of-range value like 2^63 slip through and + // then become INT64_MIN via static_cast. Compare against the + // exactly-representable upper bound max()+1 == 2^digits instead. lowest() + // is 0 or a negated power of two, so it stays exact. (digits-1 keeps the + // shift < 64 for the uint64 case; the *2 recovers 2^digits without a 1<<64 + // overflow.) + constexpr int digits = limit::digits; + constexpr From upper = + static_cast(uint64_t{1} << (digits - 1)) * From{2}; + return f < static_cast(limit::lowest()) || f >= upper; + } + return f < limit::lowest() || f > limit::max(); +} + +C10_CLANG_DIAGNOSTIC_POP() + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +template +std::enable_if_t::value, bool> overflows( + From f, + bool strict_unsigned = false) { + // casts from complex to real are considered to overflow if the + // imaginary component is non-zero + if (!torch::headeronly::is_complex::value && f.imag() != 0) { + return true; + } + // Check for overflow componentwise + // (Technically, the imag overflow check is guaranteed to be false + // when !is_complex, but any optimizer worth its salt will be + // able to figure it out.) + return c10::overflows< + typename torch::headeronly::scalar_value_type::type, + typename From::value_type>(f.real(), strict_unsigned) || + c10::overflows< + typename torch::headeronly::scalar_value_type::type, + typename From::value_type>(f.imag(), strict_unsigned); +} +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::overflows; +HIDDEN_NAMESPACE_END(torch, headeronly) diff --git a/include/executorch/runtime/core/portable_type/complex.h b/include/executorch/runtime/core/portable_type/complex.h new file mode 100644 index 0000000..faf13a0 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/complex.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch::runtime::etensor { +using c10::complex; +} // namespace executorch::runtime::etensor + +namespace torch::executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::complex; +} // namespace torch::executor diff --git a/include/executorch/runtime/core/portable_type/device.h b/include/executorch/runtime/core/portable_type/device.h new file mode 100644 index 0000000..41a8c6b --- /dev/null +++ b/include/executorch/runtime/core/portable_type/device.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include + +namespace executorch { +namespace runtime { +namespace etensor { + +/// Represents the type of compute device. +/// Note: ExecuTorch Device is distinct from PyTorch Device. +enum class DeviceType : int8_t { + CPU = 0, + CUDA = 1, +}; + +/// Total number of device types, used for fixed-size registry arrays. +constexpr size_t kNumDeviceTypes = 2; + +/// An index representing a specific device; e.g. GPU 0 vs GPU 1. +using DeviceIndex = int8_t; + +/** + * An abstraction for the compute device on which a tensor is located. + * + * Tensors carry a Device to express where their underlying data resides + * (e.g. CPU host memory vs CUDA device memory). The runtime uses this to + * dispatch memory allocation to the appropriate device allocator. + */ +struct Device final { + using Type = DeviceType; + + /// Constructs a new `Device` from a `DeviceType` and an optional device + /// index. + /* implicit */ Device(DeviceType type, DeviceIndex index = 0) + : type_(type), index_(index) {} + + /// Returns the type of device the tensor data resides on. + DeviceType type() const noexcept { + return type_; + } + + /// Returns true if the device is of CPU type. + bool is_cpu() const noexcept { + return type_ == DeviceType::CPU; + } + + /// Returns the device index. + DeviceIndex index() const noexcept { + return index_; + } + + bool operator==(const Device& other) const noexcept { + return type_ == other.type_ && index_ == other.index_; + } + + bool operator!=(const Device& other) const noexcept { + return !(*this == other); + } + + private: + DeviceType type_; + DeviceIndex index_ = 0; +}; + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::Device; +using ::executorch::runtime::etensor::DeviceType; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/half.h b/include/executorch/runtime/core/portable_type/half.h new file mode 100644 index 0000000..bf4c676 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/half.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch::runtime::etensor { +using c10::Half; +namespace internal { +using c10::detail::fp16_ieee_from_fp32_value; +using c10::detail::fp16_ieee_to_fp32_bits; +using c10::detail::fp16_ieee_to_fp32_value; +using c10::detail::fp32_from_bits; +using c10::detail::fp32_to_bits; +} // namespace internal +} // namespace executorch::runtime::etensor +namespace torch::executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::Half; +} // namespace torch::executor diff --git a/include/executorch/runtime/core/portable_type/optional.h b/include/executorch/runtime/core/portable_type/optional.h new file mode 100644 index 0000000..deff1f1 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/optional.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include + +namespace executorch { +namespace runtime { +namespace etensor { + +template +using optional ET_DEPRECATED = std::optional; +using nullopt_t ET_DEPRECATED = std::nullopt_t; +ET_DEPRECATED inline constexpr std::nullopt_t nullopt{std::nullopt}; + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +template +using optional ET_DEPRECATED = std::optional; +using nullopt_t ET_DEPRECATED = std::nullopt_t; +ET_DEPRECATED inline constexpr std::nullopt_t nullopt{std::nullopt}; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/qint_types.h b/include/executorch/runtime/core/portable_type/qint_types.h new file mode 100644 index 0000000..183675e --- /dev/null +++ b/include/executorch/runtime/core/portable_type/qint_types.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch { +namespace runtime { +namespace etensor { + +/** + * qint8 is for signed 8 bit quantized Tensors + */ +struct alignas(1) qint8 { + using underlying = int8_t; + int8_t val_; + qint8() = default; + explicit qint8(int8_t val) : val_(val) {} +}; + +/** + * quint8 is for unsigned 8 bit quantized Tensors + */ +struct alignas(1) quint8 { + using underlying = uint8_t; + uint8_t val_; + quint8() = default; + explicit quint8(uint8_t val) : val_(val) {} +}; + +/** + * qint32 is for signed 32 bit quantized Tensors + */ +struct alignas(4) qint32 { + using underlying = int32_t; + int32_t val_; + qint32() = default; + explicit qint32(int32_t val) : val_(val) {} +}; + +/** + * quint4x2 is for un-signed 4 bit quantized Tensors that are packed to byte + * boundary. + */ +struct alignas(1) quint4x2 { + using underlying = uint8_t; + uint8_t val_; + quint4x2() = default; + explicit quint4x2(uint8_t val) : val_(val) {} +}; + +/** + * quint2x4 is for un-signed 2 bit quantized Tensors that are packed to byte + * boundary. + */ +struct alignas(1) quint2x4 { + using underlying = uint8_t; + uint8_t val_; + quint2x4() = default; + explicit quint2x4(uint8_t val) : val_(val) {} +}; + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::qint32; +using ::executorch::runtime::etensor::qint8; +using ::executorch::runtime::etensor::quint2x4; +using ::executorch::runtime::etensor::quint4x2; +using ::executorch::runtime::etensor::quint8; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/scalar.h b/include/executorch/runtime/core/portable_type/scalar.h new file mode 100644 index 0000000..0922cec --- /dev/null +++ b/include/executorch/runtime/core/portable_type/scalar.h @@ -0,0 +1,123 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace executorch { +namespace runtime { +namespace etensor { + +/** + * Represents a scalar value. + * + * The API is a source-compatible subset of c10::Scalar, and the + * semantics/behavior should also match the c10 version. + */ +class Scalar { + public: + Scalar() : Scalar(int64_t(0)) {} + + template < + typename T, + typename std::enable_if::value, bool>::type = true> + /*implicit*/ Scalar(T val) : tag(Tag::Int) { + v.as_int = static_cast(val); + } + /*implicit*/ Scalar(bool val) : tag(Tag::Bool) { + v.as_bool = val; + } + /*implicit*/ Scalar(double val) : tag(Tag::Double) { + v.as_double = val; + } + /*implicit*/ Scalar(BFloat16 val) : Scalar((double)(float)val) {} + /*implicit*/ Scalar(Half val) : Scalar((double)(float)val) {} + + /// Returns the concrete scalar value stored within. + template + T to() const; + + /// Returns true if the scalar is integral, false otherwise. + bool isIntegral(bool includeBool) const { + return Tag::Int == tag || (includeBool && isBoolean()); + } + + /// Returns true if the scalar is a floating point, false otherwise. + bool isFloatingPoint() const { + return tag == Tag::Double; + } + + /// Returns true if the scalar is a boolean, false otherwise. + bool isBoolean() const { + return tag == Tag::Bool; + } + + private: + int64_t toInt() const { + if (isIntegral(/*includeBool=*/false)) { + return v.as_int; + } else if (isBoolean()) { + return static_cast(v.as_bool); + } else { + ET_CHECK_MSG(false, "Scalar is not an int nor a Boolean."); + } + } + + double toFloatingPoint() const { + ET_CHECK_MSG(isFloatingPoint(), "Scalar is not a Double."); + return v.as_double; + } + + double toDouble() const { + ET_CHECK_MSG(isFloatingPoint(), "Scalar is not a Double."); + return v.as_double; + } + + bool toBool() const { + ET_CHECK_MSG(isBoolean(), "Scalar is not a Boolean."); + return v.as_bool; + } + + Tag tag; + union v_t { + double as_double; + int64_t as_int; + bool as_bool; + v_t() {} // default constructor + } v; +}; + +#define ET_DEFINE_SCALAR_TO_METHOD(T, name) \ + template <> \ + inline T Scalar::to() const { \ + return to##name(); \ + } + +ET_DEFINE_SCALAR_TO_METHOD(double, Double) +ET_DEFINE_SCALAR_TO_METHOD(int64_t, Int) +ET_DEFINE_SCALAR_TO_METHOD(bool, Bool) +#undef ET_DEFINE_SCALAR_TO_METHOD + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::Scalar; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/scalar_type.h b/include/executorch/runtime/core/portable_type/scalar_type.h new file mode 100644 index 0000000..dc81428 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/scalar_type.h @@ -0,0 +1,154 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * + * Forked from + * https://github.com/pytorch/pytorch/blob/master/c10/core/ScalarType.h + * + * Everything but the ScalarType definition is in util/ScalarTypeUtil.h + * + * Note that these files do not need to be strictly identical to the pytorch + * core file, as far as names go. The only critical piece is that the types and + * indices of the main ScalarType enum line up, so that serialization is + * compatible between the two. + * + * Modifications for ExecuTorch: + * - Namespace torch::executor instead of c10 + * - Macro prefix ET_ instead of AT_ + * - Use ET_CHECK_MSG() instead of TORCH_CHECK() + * - Don't define standalone constants like `kByte`, `kInt` to keep the + * namespace clean + * - Remove operator<< to avoid a dependency on ostream and stdlib + * - Make `static inline` functions `inline` to avoid creating multiple + * copies of them. See + * https://gist.github.com/htfy96/50308afc11678d2e3766a36aa60d5f75#conclusion. + * - Remove deprecated definitions + * - Minor cleanup for internal consistency + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace executorch { +namespace runtime { +namespace etensor { + +// Placing a bunch of unused dtypes here as our macros don't make it easy +// to skip scalar types defined in aten that we dont have. +namespace unused_dtype { +struct alignas(1) Float8_e5m2 { + uint8_t x; + using underlying = uint8_t; + Float8_e5m2() = default; + explicit Float8_e5m2(uint8_t val) : x(val) {} +}; +struct alignas(1) Float8_e4m3fn { + uint8_t x; + using underlying = uint8_t; + Float8_e4m3fn() = default; + explicit Float8_e4m3fn(uint8_t val) : x(val) {} +}; +struct alignas(1) Float8_e5m2fnuz { + uint8_t x; + using underlying = uint8_t; + Float8_e5m2fnuz() = default; + explicit Float8_e5m2fnuz(uint8_t val) : x(val) {} +}; +struct alignas(1) Float8_e4m3fnuz { + uint8_t x; + using underlying = uint8_t; + Float8_e4m3fnuz() = default; + explicit Float8_e4m3fnuz(uint8_t val) : x(val) {} +}; + +} // namespace unused_dtype + +/** + * Calls the provided macro on every ScalarType, providing the C type and the + * ScalarType name to each call. + * + * The indices and C types must be consistent with + * AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS in the core pytorch file + * c10/core/ScalarType.h. This ensures that ExecuTorch serialization is + * compatible with ATen serialization. + * + * @param _ A macro that takes two parameters: the name of a C type, and the + * name of the corresponding ScalarType enumerator. + */ +#define ET_FORALL_SCALAR_TYPES(_) \ + _(uint8_t, Byte) /* 0 */ \ + _(int8_t, Char) /* 1 */ \ + _(int16_t, Short) /* 2 */ \ + _(int32_t, Int) /* 3 */ \ + _(int64_t, Long) /* 4 */ \ + _(::executorch::runtime::etensor::Half, Half) /* 5 */ \ + _(float, Float) /* 6 */ \ + _(double, Double) /* 7 */ \ + _(::executorch::runtime::etensor::complex<::torch::executor::Half>, \ + ComplexHalf) /* 8 */ \ + _(::executorch::runtime::etensor::complex, ComplexFloat) /* 9 */ \ + _(::executorch::runtime::etensor::complex, ComplexDouble) /* 10 */ \ + _(bool, Bool) /* 11 */ \ + _(::executorch::runtime::etensor::qint8, QInt8) /* 12 */ \ + _(::executorch::runtime::etensor::quint8, QUInt8) /* 13 */ \ + _(::executorch::runtime::etensor::qint32, QInt32) /* 14 */ \ + _(::executorch::runtime::etensor::BFloat16, BFloat16) /* 15 */ \ + _(::executorch::runtime::etensor::quint4x2, QUInt4x2) /* 16 */ \ + _(::executorch::runtime::etensor::quint2x4, QUInt2x4) /* 17 */ \ + _(::executorch::runtime::etensor::bits1x8, Bits1x8) /* 18 */ \ + _(::executorch::runtime::etensor::bits2x4, Bits2x4) /* 19 */ \ + _(::executorch::runtime::etensor::bits4x2, Bits4x2) /* 20 */ \ + _(::executorch::runtime::etensor::bits8, Bits8) /* 21 */ \ + _(::executorch::runtime::etensor::bits16, Bits16) /* 22 */ \ + _(::executorch::runtime::etensor::unused_dtype::Float8_e5m2, \ + Float8_e5m2) /* 23 */ \ + _(::executorch::runtime::etensor::unused_dtype::Float8_e4m3fn, \ + Float8_e4m3fn) /* 24 */ \ + _(::executorch::runtime::etensor::unused_dtype::Float8_e5m2fnuz, \ + Float8_e5m2fnuz) /* 25 */ \ + _(::executorch::runtime::etensor::unused_dtype::Float8_e4m3fnuz, \ + Float8_e4m3fnuz) /* 26 */ \ + _(uint16_t, UInt16) /* 27 */ \ + _(uint32_t, UInt32) /* 28 */ \ + _(uint64_t, UInt64) /* 29 */ + +/** + * Data types (dtypes) that can be used as element types in ETensors. + */ +enum class ScalarType : int8_t { +/// Define an enumerator for each ScalarType. +#define DEFINE_ENUM(unused, name) name, + ET_FORALL_SCALAR_TYPES(DEFINE_ENUM) +#undef DEFINE_ENUM + + /// An explicitly undefined ScalarType. Does not map to any C type. + Undefined, + /// The number of ScalarType enumerators. + NumOptions, +}; + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::ScalarType; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/string_view.h b/include/executorch/runtime/core/portable_type/string_view.h new file mode 100644 index 0000000..f1f25f0 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/string_view.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include + +namespace executorch { +namespace runtime { +namespace etensor { + +using string_view ET_DEPRECATED = std::string_view; + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using string_view ET_DEPRECATED = std::string_view; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/tensor.h b/include/executorch/runtime/core/portable_type/tensor.h new file mode 100644 index 0000000..f4ee2ae --- /dev/null +++ b/include/executorch/runtime/core/portable_type/tensor.h @@ -0,0 +1,190 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include + +namespace executorch { +namespace runtime { +namespace etensor { + +/** + * A minimal Tensor type whose API is a source compatible subset of at::Tensor. + * + * NOTE: Instances of this class do not own the TensorImpl given to it, + * which means that the caller must guarantee that the TensorImpl lives longer + * than any Tensor instances that point to it. + * + * See the documention on TensorImpl for details about the return/parameter + * types used here and how they relate to at::Tensor. + */ +class Tensor { + public: + /// The type used for elements of `sizes()`. + using SizesType = TensorImpl::SizesType; + /// The type used for elements of `dim_order()`. + using DimOrderType = TensorImpl::DimOrderType; + /// The type used for elements of `strides()`. + using StridesType = TensorImpl::StridesType; + + Tensor() = delete; + explicit constexpr Tensor(TensorImpl* impl) : impl_(impl) {} + + /** + * Returns a pointer to the underlying TensorImpl. + * + * NOTE: Clients should be wary of operating on the TensorImpl + * directly instead of the Tensor. It is easy to break things. + */ + TensorImpl* unsafeGetTensorImpl() const { + // TODO(T154114015): See if we can make this api private with friends. + return impl_; + } + + /** + * Returns the size of the tensor in bytes. + * + * NOTE: Only the alive space is returned not the total capacity of the + * underlying data blob. + */ + size_t nbytes() const { + return impl_->nbytes(); + } + + /** + * Returns the size of the tensor at the given dimension. + * + * NOTE: that size() intentionally does not return SizeType even though it + * returns an element of an array of SizeType. This is to help make calls of + * this method more compatible with at::Tensor, and more consistent with the + * rest of the methods on this class and in ETensor. + */ + ssize_t size(ssize_t dim) const { + return impl_->size(dim); + } + + /// Returns the tensor's number of dimensions. + ssize_t dim() const { + return impl_->dim(); + } + + /// Returns the number of elements in the tensor. + ssize_t numel() const { + return impl_->numel(); + } + + /// Returns the type of the elements in the tensor (int32, float, bool, etc). + ScalarType scalar_type() const { + return impl_->scalar_type(); + } + + inline ScalarType dtype() const { + return scalar_type(); + } + + /// Returns the size in bytes of one element of the tensor. + ssize_t element_size() const { + return impl_->element_size(); + } + + /// Returns the sizes of the tensor at each dimension. + const ArrayRef sizes() const { + return impl_->sizes(); + } + + /// Returns the order the dimensions are laid out in memory. + const ArrayRef dim_order() const { + return impl_->dim_order(); + } + + /// Returns the strides of the tensor at each dimension. + const ArrayRef strides() const { + return impl_->strides(); + } + + /// Returns the mutability of the shape of the tensor. + TensorShapeDynamism shape_dynamism() const { + return impl_->shape_dynamism(); + } + + /// Returns the device where tensor data resides. + Device device() const { + return impl_->device(); + } + + /// Returns the type of device where tensor data resides. + DeviceType device_type() const { + return impl_->device_type(); + } + + /// Returns the device index, or 0 if default/unspecified. + DeviceIndex device_index() const { + return impl_->device_index(); + } + + /// Returns a pointer of type T to the constant underlying data blob. + template + inline const T* const_data_ptr() const { + return impl_->data(); + } + + /// Returns a pointer to the constant underlying data blob. + inline const void* const_data_ptr() const { + return impl_->data(); + } + + /// Returns a pointer of type T to the mutable underlying data blob. + template + inline T* mutable_data_ptr() const { + return impl_->mutable_data(); + } + + /// Returns a pointer to the mutable underlying data blob. + inline void* mutable_data_ptr() const { + return impl_->mutable_data(); + } + + /// DEPRECATED: Use const_data_ptr or mutable_data_ptr instead. + template + ET_DEPRECATED inline T* data_ptr() const { + return impl_->mutable_data(); + } + + /// DEPRECATED: Use const_data_ptr or mutable_data_ptr instead. + ET_DEPRECATED inline void* data_ptr() const { + return impl_->mutable_data(); + } + + /** + * DEPRECATED: Changes the data_ptr the tensor aliases. Does not free the + * previously pointed to data, does not assume ownership semantics of the new + * ptr. This api does not exist in at::Tensor so kernel developers should + * avoid it. + */ + ET_DEPRECATED void set_data(void* ptr) const { + impl_->set_data(ptr); + } + + private: + TensorImpl* impl_ = nullptr; +}; + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::Tensor; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/tensor_impl.h b/include/executorch/runtime/core/portable_type/tensor_impl.h new file mode 100644 index 0000000..fcfe4d9 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/tensor_impl.h @@ -0,0 +1,345 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// Forward declaration of a helper that provides access to internal resizing +// methods of TensorImpl. Real definition is in +// executorch/runtime/core/exec_aten/tensor_util.h. +namespace executorch { +namespace runtime { +namespace internal { +class TensorResizerFriend; +} // namespace internal +} // namespace runtime +} // namespace executorch + +namespace executorch { +namespace runtime { +namespace etensor { + +/** + * Manages the storage behind an ETensor (torch::executor::Tensor). + * + * Note that instances of this class do not own the arrays given to it + * (sizes/strides/data), which means that the caller must guarantee that they + * live longer than a given instance of this class. + * + * Note on types: + * + * Code that uses ETensor should also be able to build against at::Tensor. So, + * although the overlapping APIs don't need to be exactly the same, their types + * should be semantically similar. + * + * Many of the methods in at::Tensor use int64_t for parameter and return types. + * This can be a waste when building for 32-bit environments. So, TensorImpl and + * ETensor use ssize_t instead: like int64_t it is signed, but it will match the + * native word size of the target architecture. This will avoid unnecessarily + * expensive uses of 64-bit integers on 32-bit machines. + * + * But, since the types are not identical, code that uses ETensor needs to be + * generic about the local types it uses when working with these methods. In + * most cases, `auto` will do the trick. In the worst case, code can be guarded + * with `#ifdef USE_ATEN_LIB`. + */ +class TensorImpl { + public: + /** + * The type used for elements of `sizes()`. + * + * This must match the size/signedness of the type used for `Tensor.sizes` in + * //executorch/schema/program.fbs. + * + * Note that at::TensorImpl uses `int64_t` for this type. ExecuTorch uses + * `int32_t` to save memory, since no single size value will ever be larger + * than 2 billion. + */ + using SizesType = int32_t; + + /** + * The type used for elements of `dim_order()`. + * + * This must match the size/signedness of the type used for `Tensor.dim_order` + * in //executorch/schema/program.fbs. + */ + using DimOrderType = uint8_t; + + /** + * The type used for elements of `strides()`. + * + * This must match the size/signedness of the type used for `Tensor.strides` + * in //executorch/schema/program.fbs. + * + * Note that at::TensorImpl uses `int64_t` for this type. ExecuTorch uses + * `int32_t` to save memory, since no single stride value will ever be larger + * than 2 billion. + */ + using StridesType = int32_t; + + TensorImpl() = delete; + + /** + * @param type The type of the data (int, float, bool). + * @param dim Number of dimensions, and the length of the `sizes` array. + * @param sizes Sizes of the tensor at each dimension. Must contain `dim` + * entries. + * @param data Pointer to the data, whose size is determined by `type`, + * `dim`, and `sizes`. The tensor will not own this memory. + * @param dim_order Order in which dimensions are laid out in memory. + * @param strides Strides of the tensor at each dimension. Must contain `dim` + * entries. + * @param dynamism The mutability of the shape of the tensor. + * @param device_type The type of device where tensor data resides. + * @param device_index The device index for multi-device scenarios. + */ + TensorImpl( + ScalarType type, + ssize_t dim, + SizesType* sizes, + void* data = nullptr, + DimOrderType* dim_order = nullptr, + StridesType* strides = nullptr, + TensorShapeDynamism dynamism = TensorShapeDynamism::STATIC, + DeviceType device_type = DeviceType::CPU, + DeviceIndex device_index = 0); + + /** + * Returns the size of the tensor in bytes. + * + * NOTE: This returns the size of the data used by the tensor's current shape, + * not the capacity of the underlying buffer. + */ + size_t nbytes() const; + + /** + * Returns the size of the tensor at the given dimension. + * + * NOTE: size() intentionally does not return SizeType even though it + * returns an element of an array of SizeType. This is to help make calls of + * this method more compatible with at::Tensor, and more consistent with the + * rest of the methods on this class and in ETensor. + */ + ssize_t size(ssize_t dim) const { + ET_CHECK_MSG( + dim < dim_ && dim >= 0, + "Dimension out of range (expected to be in range of [0, %zd], but got %zd", + dim_ - 1, + dim); + return sizes_[dim]; + } + + /// Returns the tensor's number of dimensions. + ssize_t dim() const { + return dim_; + } + + /// Returns true if non-scalar layout metadata has backing storage. + bool has_layout_metadata() const { + return dim_ == 0 || (dim_order_ != nullptr && strides_ != nullptr); + } + + /// Returns the number of elements in the tensor. + ssize_t numel() const { + return numel_; + } + + /// Returns the type of the elements in the tensor (int32, float, bool, etc). + ScalarType scalar_type() const { + return type_; + } + + inline ScalarType dtype() const { + return scalar_type(); + } + + /// Returns the size in bytes of one element of the tensor. + ssize_t element_size() const; + + /// Returns the sizes of the tensor at each dimension. + const ArrayRef sizes() const { + return ArrayRef{sizes_, static_cast(dim_)}; + } + + /// Returns the order the dimensions are laid out in memory. + const ArrayRef dim_order() const { + return ArrayRef{dim_order_, static_cast(dim_)}; + } + + /// Returns the strides of the tensor at each dimension. + const ArrayRef strides() const { + return ArrayRef{strides_, static_cast(dim_)}; + } + + /// Returns the mutability of the shape of the tensor. + TensorShapeDynamism shape_dynamism() const { + return shape_dynamism_; + } + + /// Returns the device where tensor data resides. + Device device() const { + return device_; + } + + /// Returns the type of device where tensor data resides. + DeviceType device_type() const { + return device_.type(); + } + + /// Returns the device index, or 0 if default/unspecified. + DeviceIndex device_index() const { + return device_.index(); + } + + /// Returns a pointer of type T to the constant underlying data blob. + template + inline const T* data() const { + return static_cast(data()); + } + + /// Returns a pointer to the constant underlying data blob. + const void* data() const { + return data_; + } + + /// Returns a pointer of type T to the mutable underlying data blob. + template + inline T* mutable_data() const { + return static_cast(mutable_data()); + } + + /// Returns a pointer to the mutable underlying data blob. + void* mutable_data() const { + return data_; + } + + /// Sets the underlying data blob to the passed in pointer. + void set_data(void* ptr) { + data_ = ptr; + } + + /* + * DEPRECATED: Use torch::executor::resize_tensor() or + * torch::executor::resize_tensor_impl(). + */ + ET_DEPRECATED + void set_sizes_contiguous(ArrayRef new_sizes) { + Error err = internal_resize_contiguous(new_sizes); + ET_CHECK_MSG( + err == Error::Ok, "Could not resize Tensor; see logs for details"); + } + + private: + // For access to internal_resize_contiguous(). + friend class ::executorch::runtime::internal::TensorResizerFriend; + + /** + * Set the sizes and strides of a tensor assuming contiguous strides. + * Requires that `new_sizes.size() == this.dim()`. + * + * Callers must use torch::executor::resize_tensor() or + * torch::executor::resize_tensor_impl() instead, defined in TensorUtil.h. + * + * Same semantics as at::TensorImpl::set_sizes_contiguous(), but returns an + * error instead of panicking on failure. This is not part of the at::Tensor + * API, and can only be used in lean mode. + */ + ET_NODISCARD Error internal_resize_contiguous(ArrayRef new_sizes); + + private: + // Keep fields arranged to avoid unnecessary alignment holes. + + /// List of sizes of each dimension in the tensor. + SizesType* sizes_; + + /// List of the order that dimensions are laid out in memory. + DimOrderType* dim_order_; + + // TODO(T148356881): Get rid of strides from ETensor + StridesType* strides_; + + /// Pointer to underlying data blob. NOTE: Can be null. + void* data_; + + /// Tensor's number of dimensions. + const ssize_t dim_; + + /// Number of elements in the tensor. + ssize_t numel_; + + /// Maximum number of elements in the bounded tensor. Used when resizing up + /// and down. + size_t numel_bound_; + + /// Scalar type (int, float, bool, etc) of the tensor data. + const ScalarType type_; + + /// Specifies the mutability of the shape of the tensor. + const TensorShapeDynamism shape_dynamism_; + + /// Device where tensor data resides (CPU, CUDA, etc.) + Device device_; +}; + +/** + * Compute the number of elements based on the sizes of a tensor. + */ +ssize_t compute_numel( + const ::executorch::runtime::etensor::TensorImpl::SizesType* sizes, + ssize_t dim); + +/** + * Compute the number of elements based on the sizes of a tensor. + * Returns Error::InvalidArgument if any intermediate multiplication would + * overflow ssize_t, or if a size is negative. Prefer this over compute_numel() + * for paths that can propagate an Error upward. + */ +::executorch::runtime::Result safe_numel( + const ::executorch::runtime::etensor::TensorImpl::SizesType* sizes, + ssize_t dim); + +/// Appropriate format specifier for the result of calling +/// size(). Must be used instead of using zd directly to support ATen +/// mode. +#define ET_PRI_TENSOR_SIZE "zd" + +/// Appropriate format specifier for the result of calling +/// dim(). Must be used instead of using zd directly to support ATen +/// mode. +#define ET_PRI_TENSOR_DIM "zd" + +/// Appropriate format specifier for the result of calling +/// numel(). Must be used instead of using zd directly to support ATen +/// mode. +#define ET_PRI_TENSOR_NUMEL "zd" + +// Appropriate format specifier for elements of sizes() and +// strides(). Must be used instead of using d directly to support ATen +// mode. +#define ET_PRI_SIZES_AND_STRIDES "d" + +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::compute_numel; +using ::executorch::runtime::etensor::safe_numel; +using ::executorch::runtime::etensor::TensorImpl; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/portable_type/tensor_options.h b/include/executorch/runtime/core/portable_type/tensor_options.h new file mode 100644 index 0000000..8b8f984 --- /dev/null +++ b/include/executorch/runtime/core/portable_type/tensor_options.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch { +namespace runtime { +namespace etensor { + +/** + * Tensor data memory formats supported by ExecuTorch. This concept only exists + * for compatibility with ATen; use dim_order to describe non-contiguous + * layouts. + */ +enum class MemoryFormat : int8_t { + /** + * Row-major contiguous data. + */ + Contiguous = 0, + /** + * Output tensor format should remain the same as the input tensor format. + * E.g. if the input tensor is in channels_last format, operator output + * should be in channels_last format. + */ + Preserve = 1, +}; + +/** + * Tensor data memory layout. This concept only exists for compatibility + * with ATen. + */ +enum class Layout : int8_t { + /** + * The tensor occupies memory densely and indexing is managed through strides. + * Contrasted with a sparse tensor layout where the memory structure of the + * data blob will be more complicated and indexing requires larger structures. + * + * This is the only layout supported by ExecuTorch. + */ + Strided = 0, +}; +} // namespace etensor +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::etensor::Layout; +using ::executorch::runtime::etensor::MemoryFormat; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/result.h b/include/executorch/runtime/core/result.h new file mode 100644 index 0000000..6f8bab8 --- /dev/null +++ b/include/executorch/runtime/core/result.h @@ -0,0 +1,333 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * Result type to be used in conjunction with ExecuTorch Error type. + */ + +#pragma once + +#include +#include + +#include "executorch/runtime/core/error.h" +#include "executorch/runtime/platform/assert.h" + +namespace executorch { +namespace runtime { + +/** + * Result type wrapping either a value of type T or an error. + * + * Example use case: + * @code + * Result getOp(int opcode) { + * if (isValidOpCode(opcode)) { + * return opFns[opcode]; + * } + * return Error::NotFound; + * } + * + * Error useOp(int opcode) { + * Result op = getOp(opcode); + * if (!op.ok()) { + * return op.error(); + * } + * print(op->toString()); + * execute(*op); + * return Error::Ok; + * } + * @endcode + */ +template +class Result final { + public: + /// `value_type` member for generic programming. + typedef T value_type; + + /** + * Creates a Result object from an Error. + * + * To preserve the invariant that `(result.error() == Error::Ok) == + * result.ok()`, an `error` parameter value of `Error:Ok` will be converted to + * a non-Ok value. + */ + /* implicit */ Result(Error error) + : error_(error == Error::Ok ? Error::Internal : error), hasValue_(false) { + if ET_UNLIKELY (error == Error::Ok) { + ET_LOG( + Debug, + "Attempted to create Result from Error::Ok, this has been converted to Error::Internal."); + } + } + + /// Value copy constructor. + /* implicit */ Result(const T& val) : value_(val), hasValue_(true) {} + + /// Value move constructor. + /* implicit */ Result(T&& val) : value_(std::move(val)), hasValue_(true) {} + + /// Result move constructor. + /* implicit */ Result(Result&& rhs) noexcept : hasValue_(rhs.hasValue_) { + if (hasValue_) { + // Use the value type's move constructor. + new (&value_) T(std::move(rhs.value_)); + } else { + error_ = rhs.error_; + } + } + + ~Result() { + if (hasValue_) { + // Manual value destruction. + // Result "owns" the memory, so `delete` would segfault. + value_.~T(); + } + } + + /** + * Returns true if this Result has a value. + * + * If true, it is guaranteed that `error()` will return `Error::Ok`. + * If false, it is guaranteed that `error()` will not return `Error::Ok`. + */ + ET_NODISCARD bool ok() const { + return hasValue_; + } + + /** + * Returns the error code of this Result. + * + * If this returns `Error::Ok`, it is guaranteed that `ok()` will return true. + * If this does not return `Error:Ok`, it is guaranteed that `ok()` will + * return false. + */ + ET_NODISCARD Error error() const { + if (hasValue_) { + return Error::Ok; + } else { + return error_; + } + } + + /** + * Returns a reference to the Result's value; longhand for operator*(). + * + * Only legal to call if `ok()` returns true. + */ + T& get() { + CheckOk(); + return value_; + } + + /** + * Returns a reference to the Result's value; longhand for operator*(). + * + * Only legal to call if `ok()` returns true. + */ + const T& get() const { + CheckOk(); + return value_; + } + + /* + * Returns a reference to the Result's value; shorthand for get(). + * + * Only legal to call if `ok()` returns true. + */ + const T& operator*() const&; + T& operator*() &; + + /* + * Returns a pointer to the Result's value. + * + * Only legal to call if `ok()` returns true. + */ + const T* operator->() const; + T* operator->(); + + private: + /** + * Delete default constructor since all Results should contain a value or + * error. + */ + Result() = delete; + /// Delete copy constructor since T may not be copyable. + Result(const Result&) = delete; + /// Delete copy assignment since T may not be copyable. + Result& operator=(const Result&) = delete; + /// Delete move assignment since it's not a supported pattern to reuse Result. + Result& operator=(Result&& rhs) = delete; + + // Panics if ok() would return false; + void CheckOk() const { + ET_CHECK(hasValue_); + } + + union { + T value_; // Used if hasValue_ is true. + Error error_; // Used if hasValue_ is false. + }; + + /// True if the Result contains a value. + const bool hasValue_; +}; + +template +const T& Result::operator*() const& { + CheckOk(); + return value_; +} + +template +T& Result::operator*() & { + CheckOk(); + return value_; +} + +template +const T* Result::operator->() const { + CheckOk(); + return &value_; +} + +template +T* Result::operator->() { + CheckOk(); + return &value_; +} + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::Result; +} // namespace executor +} // namespace torch + +/** + * Unwrap a Result to obtain its value. If the Result contains an error, + * propagate the error via trivial function return. + * + * Note: A function using ET_UNWRAP should itself return a Result or Error. + * + * This macro expands to a GNU statement expression and is therefore used as an + * expression (e.g. `auto value = ET_UNWRAP(expr);`). It is NOT portable to + * MSVC, which does not support statement expressions. Code that must compile + * under MSVC should use ET_ASSIGN_OR_RETURN below instead. + * + * @param[in] result__ Expression yielding the result to unwrap. + * @param[in] ... Optional format string for the log error message and its + * arguments. + */ +#define ET_UNWRAP(result__, ...) ET_INTERNAL_UNWRAP(result__, ##__VA_ARGS__) + +// Internal only: Use ET_UNWRAP() instead. +#define ET_INTERNAL_UNWRAP(...) \ + ET_INTERNAL_UNWRAP_SELECT(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1) \ + (__VA_ARGS__) + +// Internal only: Use ET_UNWRAP() instead. +#define ET_INTERNAL_UNWRAP_SELECT( \ + _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) \ + ET_INTERNAL_UNWRAP_##N + +// Internal only: Use ET_UNWRAP() instead. +#define ET_INTERNAL_UNWRAP_1(result__) \ + ({ \ + auto et_result__ = (result__); \ + if (!et_result__.ok()) { \ + return et_result__.error(); \ + } \ + std::move(*et_result__); \ + }) + +// Internal only: Use ET_UNWRAP() instead. +#define ET_INTERNAL_UNWRAP_2(result__, message__, ...) \ + ({ \ + auto et_result__ = (result__); \ + if (!et_result__.ok()) { \ + ET_LOG(Error, message__, ##__VA_ARGS__); \ + return et_result__.error(); \ + } \ + std::move(*et_result__); \ + }) + +// Internal only: Use ET_UNWRAP() instead. +#define ET_INTERNAL_UNWRAP_3 ET_INTERNAL_UNWRAP_2 +#define ET_INTERNAL_UNWRAP_4 ET_INTERNAL_UNWRAP_2 +#define ET_INTERNAL_UNWRAP_5 ET_INTERNAL_UNWRAP_2 +#define ET_INTERNAL_UNWRAP_6 ET_INTERNAL_UNWRAP_2 +#define ET_INTERNAL_UNWRAP_7 ET_INTERNAL_UNWRAP_2 +#define ET_INTERNAL_UNWRAP_8 ET_INTERNAL_UNWRAP_2 +#define ET_INTERNAL_UNWRAP_9 ET_INTERNAL_UNWRAP_2 +#define ET_INTERNAL_UNWRAP_10 ET_INTERNAL_UNWRAP_2 + +/** + * Assign the unwrapped value of a Result to a newly declared variable, or + * return the error via trivial function return. + * + * Unlike ET_UNWRAP (which expands to a GNU statement expression), this macro + * expands to plain statements and is therefore portable to MSVC. Prefer it in + * code that must build with MSVC. + * + * Note: A function using ET_ASSIGN_OR_RETURN should itself return a Result or + * Error. + * + * Usage: + * ET_ASSIGN_OR_RETURN(value, expr); + * ET_ASSIGN_OR_RETURN(value, expr, "log message %d", arg); + * + * @param[in] var__ Name of the variable to declare and assign the unwrapped + * value to. + * @param[in] result__ Expression yielding the result to unwrap. + * @param[in] ... Optional format string for the log error message and its + * arguments. + */ +#define ET_ASSIGN_OR_RETURN(...) \ + ET_INTERNAL_ASSIGN_OR_RETURN_EXPAND(ET_INTERNAL_ASSIGN_OR_RETURN_SELECT( \ + __VA_ARGS__, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)(__VA_ARGS__)) + +// Internal only: Use ET_ASSIGN_OR_RETURN() instead. +#define ET_INTERNAL_ASSIGN_OR_RETURN_EXPAND(x) x + +// Internal only: Use ET_ASSIGN_OR_RETURN() instead. +#define ET_INTERNAL_ASSIGN_OR_RETURN_SELECT( \ + _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, N, ...) \ + ET_INTERNAL_ASSIGN_OR_RETURN_##N + +// Internal only: Use ET_ASSIGN_OR_RETURN() instead. +#define ET_INTERNAL_ASSIGN_OR_RETURN_2(var__, result__) \ + auto et_assign_result_##var__ = (result__); \ + if (!et_assign_result_##var__.ok()) { \ + return et_assign_result_##var__.error(); \ + } \ + auto var__ = std::move(*et_assign_result_##var__) + +// Internal only: Use ET_ASSIGN_OR_RETURN() instead. +#define ET_INTERNAL_ASSIGN_OR_RETURN_3(var__, result__, message__, ...) \ + auto et_assign_result_##var__ = (result__); \ + if (!et_assign_result_##var__.ok()) { \ + ET_LOG(Error, message__, ##__VA_ARGS__); \ + return et_assign_result_##var__.error(); \ + } \ + auto var__ = std::move(*et_assign_result_##var__) + +// Internal only: Use ET_ASSIGN_OR_RETURN() instead. +#define ET_INTERNAL_ASSIGN_OR_RETURN_4 ET_INTERNAL_ASSIGN_OR_RETURN_3 +#define ET_INTERNAL_ASSIGN_OR_RETURN_5 ET_INTERNAL_ASSIGN_OR_RETURN_3 +#define ET_INTERNAL_ASSIGN_OR_RETURN_6 ET_INTERNAL_ASSIGN_OR_RETURN_3 +#define ET_INTERNAL_ASSIGN_OR_RETURN_7 ET_INTERNAL_ASSIGN_OR_RETURN_3 +#define ET_INTERNAL_ASSIGN_OR_RETURN_8 ET_INTERNAL_ASSIGN_OR_RETURN_3 +#define ET_INTERNAL_ASSIGN_OR_RETURN_9 ET_INTERNAL_ASSIGN_OR_RETURN_3 +#define ET_INTERNAL_ASSIGN_OR_RETURN_10 ET_INTERNAL_ASSIGN_OR_RETURN_3 +#define ET_INTERNAL_ASSIGN_OR_RETURN_11 ET_INTERNAL_ASSIGN_OR_RETURN_3 diff --git a/include/executorch/runtime/core/span.h b/include/executorch/runtime/core/span.h new file mode 100644 index 0000000..2202204 --- /dev/null +++ b/include/executorch/runtime/core/span.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include + +namespace executorch { +namespace runtime { + +/** + * Represent a reference to an array (0 or more elements + * consecutively in memory), i.e. a start pointer and a length. It allows + * various APIs to take consecutive elements easily and conveniently. + * + * This class does not own the underlying data, it is expected to be used in + * situations where the data resides in some other buffer, whose lifetime + * extends past that of the Span. + * + * Span and ArrayRef are extrememly similar with the difference being ArrayRef + * views a list of constant elements and Span views a list of mutable elements. + * Clients should decide between the two based on if the list elements for their + * use case should be mutable. + * + * This is intended to be trivially copyable, so it should be passed by + * value. + */ +template +class Span final { + public: + using value_type = T; + using iterator = T*; + using size_type = size_t; + + public: + /// Construct an empty Span. + /* implicit */ constexpr Span() noexcept : data_(nullptr), length_(0) {} + + /// Construct a Span from a pointer and length. + Span(T* data, size_t length) : data_(data), length_(length) { + ET_DCHECK(data_ != nullptr || length_ == 0); + } + + /// Construct a Span from a range. + Span(T* begin, T* end) : data_(begin), length_(end - begin) {} + + /// Construct a Span from a C array. + template + /* implicit */ constexpr Span(T (&Arr)[N]) : data_(Arr), length_(N) {} + + /// Construct a Span from a single element reference. + /* implicit */ constexpr Span(T& single_element) + : data_(&single_element), length_(1) {} + + /// @returns a pointer to the start of the underlying element buffer. + iterator begin() const noexcept { + return data_; + } + + /// @returns a pointer to the end of the underlying element buffer. + iterator end() const noexcept { + return data_ + length_; + } + + /// @retval a boolean indicating if the Span is empty. + constexpr bool empty() const noexcept { + return length_ == 0; + } + + /// @returns a pointer to the start of the underlying element buffer. + constexpr T* data() const noexcept { + return data_; + } + + /// @returns the number of elements in the Span. + constexpr size_t size() const noexcept { + return length_; + } + + /// Unchecked index into the array according to the argument index. + /// @returns a reference to the element at the specified index. + T& operator[](size_t index) const { + return data_[index]; + } + + private: + /// The start of the array, in an external buffer. + T* data_; + + /// The number of elements. + size_type length_; +}; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::Span; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/tag.h b/include/executorch/runtime/core/tag.h new file mode 100644 index 0000000..a737756 --- /dev/null +++ b/include/executorch/runtime/core/tag.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include + +// X11 headers via volk define None, so we need to undef it +#if defined(__linux__) +#undef None +#endif + +namespace executorch { +namespace runtime { + +#define EXECUTORCH_FORALL_TAGS(_) \ + _(None) \ + _(Tensor) \ + _(String) \ + _(Double) \ + _(Int) \ + _(Bool) \ + _(ListBool) \ + _(ListDouble) \ + _(ListInt) \ + _(ListTensor) \ + _(ListScalar) \ + _(ListOptionalTensor) + +/** + * The dynamic type of an EValue. + */ +enum class Tag : uint32_t { +#define DEFINE_TAG(x) x, + EXECUTORCH_FORALL_TAGS(DEFINE_TAG) +#undef DEFINE_TAG +}; + +#if ET_ENABLE_ENUM_STRINGS +inline const char* tag_to_string(Tag tag) { + switch (tag) { +#define CASE_TAG(x) \ + case Tag::x: \ + return #x; + EXECUTORCH_FORALL_TAGS(CASE_TAG) +#undef CASE_TAG + default: + return "Unknown"; + } +} +#endif // ET_ENABLE_ENUM_STRINGS + +/** + * Convert a tag value to a string representation. If ET_ENABLE_ENUM_STRINGS is + * set (it is on by default), this will return a string name (for example, + * "Tensor"). Otherwise, it will return a string representation of the index + * value ("1"). + * + * If the user buffer is not large enough to hold the string representation, the + * string will be truncated. + * + * The return value is the number of characters written, or in the case of + * truncation, the number of characters that would be written if the buffer was + * large enough. + */ +size_t tag_to_string(Tag tag, char* buffer, size_t buffer_size); + +/* The size of the buffer needed to hold the longest tag string, including the + * null terminator. This value is expected to be updated manually, but it + * checked in test_tag.cpp. + */ +constexpr size_t kTagNameBufferSize = 19; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::Tag; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/tensor_layout.h b/include/executorch/runtime/core/tensor_layout.h new file mode 100644 index 0000000..ce445df --- /dev/null +++ b/include/executorch/runtime/core/tensor_layout.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { + +/** + * Describes the layout of a tensor. + */ +class TensorLayout final { + public: + TensorLayout() = delete; + + /** + * Creates a TensorLayout from the given parameters. + * + * @param[in] sizes The sizes of the tensor. Note: the span passed here must + * outlive the TensorLayout and all copies of it. + * @param[in] dim_order The dim order of the tensor. Note: the span passed + * here must outlive the TensorLayout and all copies of it. + * @param[in] scalar_type The scalar type of the tensor. + * @return A Result containing the TensorLayout on success, or an error. + */ + static executorch::runtime::Result create( + Span sizes, + Span dim_order, + executorch::aten::ScalarType scalar_type); + + /** + * Returns the sizes of the tensor. + * + * NOTE: The TensorLayout must outlive the spans returned here. + */ + Span sizes() const { + return sizes_; + } + + /** + * Returns the dim order of the tensor. + * + * NOTE: The TensorLayout must outlive the spans returned here. + */ + Span dim_order() const { + return dim_order_; + } + + /// Returns the scalar type of the tensor. + executorch::aten::ScalarType scalar_type() const { + return scalar_type_; + } + + /// Returns the size of the tensor in bytes. + size_t nbytes() const { + return nbytes_; + } + + private: + TensorLayout( + Span sizes, + Span dim_order, + executorch::aten::ScalarType scalar_type, + size_t nbytes) + : sizes_(sizes), + dim_order_(dim_order), + scalar_type_(scalar_type), + nbytes_(nbytes) {} + /// The sizes of the tensor. + const Span sizes_; + + /// The dim order of the tensor. + const Span dim_order_; + + /// The scalar type of the tensor. + const executorch::aten::ScalarType scalar_type_; + + /// The size in bytes of the tensor. + const size_t nbytes_; +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch diff --git a/include/executorch/runtime/core/tensor_shape_dynamism.h b/include/executorch/runtime/core/tensor_shape_dynamism.h new file mode 100644 index 0000000..ee95628 --- /dev/null +++ b/include/executorch/runtime/core/tensor_shape_dynamism.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch { +namespace runtime { + +/** + * The resizing capabilities of a Tensor. + * + * The rank of an ExecuTorch Tensors can never change, but shape sometimes can. + */ +enum class TensorShapeDynamism : uint8_t { + /// Cannot change shape. + STATIC = 0, + /// Shape cannot exceed initial capacity. + DYNAMIC_BOUND = 1, + /// No restriction on shape and capacity. + DYNAMIC_UNBOUND = 2, +}; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::TensorShapeDynamism; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/core/testing_util/error_matchers.h b/include/executorch/runtime/core/testing_util/error_matchers.h new file mode 100644 index 0000000..9522030 --- /dev/null +++ b/include/executorch/runtime/core/testing_util/error_matchers.h @@ -0,0 +1,303 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * Testing utilities for working with `executorch::runtime::Result` and + * `executorch::runtime::Error`. Provides matchers similar to `absl::StatusOr` + * and `absl::Status`. + * + * Defines the following utilities: + * + * =============== + * `IsOkAndHolds(m)` + * =============== + * + * This gMock matcher matches a Result value whose error is Ok + * and whose inner value matches matcher m. Example: + * + * ``` + * using ::testing::MatchesRegex; + * using ::executorch::runtime::testing::IsOkAndHolds; + * ... + * executorch::runtime::Result maybe_name = ...; + * EXPECT_THAT(maybe_name, IsOkAndHolds(MatchesRegex("John .*"))); + * ``` + * + * =============== + * `ErrorIs(Error::error_code)` + * =============== + * + * This gMock matcher matches a Result value whose error matches + * the given error matcher. Example: + * + * ``` + * using ::executorch::runtime::testing::ErrorIs; + * ... + * executorch::runtime::Result maybe_name = ...; + * EXPECT_THAT(maybe_name, ErrorIs(Error::InvalidArgument)); + * ``` + * + * =============== + * `IsOk()` + * =============== + * + * Matches an `executorch::runtime::Result` value whose error value + * is `executorch::runtime::Error::Ok`. + * + * Example: + * ``` + * using ::executorch::runtime::testing::IsOk; + * ... + * executorch::runtime::Result maybe_name = ...; + * EXPECT_THAT(maybe_name, IsOk()); + * ``` + */ + +#pragma once + +#include +#include + +#include +#include + +#include +#include + +/** + * Unwrap a Result to obtain its value. If the Result contains an error, + * fail the test with ASSERT_TRUE. + * + * This macro is useful for test code where you want to extract the value + * from a Result and fail the test if the Result contains an error. + * + * Example usage: + * ``` + * Result maybe_value = GetSomeValue(); + * int value = ASSERT_OK_AND_UNWRAP(maybe_value); + * // Use value... + * ``` + * + * @param[in] result__ Expression yielding the Result to unwrap. + */ +#define ASSERT_OK_AND_UNWRAP(result__) \ + ({ \ + auto&& et_result__ = (result__); \ + ASSERT_TRUE(et_result__.ok()); \ + std::move(*et_result__); \ + }) + +namespace executorch { +namespace runtime { +namespace testing { +namespace internal { + +// Helper function to get the error from a Result +template +inline Error GetError(const Result& result) { + return result.error(); +} + +// Helper function to get the error from a raw Error (identity function) +inline Error GetError(const Error& error) { + return error; +} + +//////////////////////////////////////////////////////////// +// Implementation of IsOkAndHolds(). + +// Monomorphic implementation of matcher IsOkAndHolds(m). ResultType is a +// reference to Result. +template +class IsOkAndHoldsMatcherImpl : public ::testing::MatcherInterface { + public: + typedef + typename std::remove_reference::type::value_type value_type; + + template + explicit IsOkAndHoldsMatcherImpl(InnerMatcher&& inner_matcher) + : inner_matcher_(::testing::SafeMatcherCast( + std::forward(inner_matcher))) {} + + void DescribeTo(std::ostream* os) const override { + *os << "is OK and has a value that "; + inner_matcher_.DescribeTo(os); + } + + void DescribeNegationTo(std::ostream* os) const override { + *os << "isn't OK or has a value that "; + inner_matcher_.DescribeNegationTo(os); + } + + bool MatchAndExplain( + ResultType actual_value, + ::testing::MatchResultListener* result_listener) const override { + if (!actual_value.ok()) { + *result_listener << "which has error " + << ::executorch::runtime::to_string( + GetError(actual_value)); + return false; + } + + // Call through to the inner matcher. + return inner_matcher_.MatchAndExplain(*actual_value, result_listener); + } + + private: + const ::testing::Matcher inner_matcher_; +}; + +// Implements IsOkAndHolds(m) as a polymorphic matcher. +template +class IsOkAndHoldsMatcher { + public: + explicit IsOkAndHoldsMatcher(InnerMatcher inner_matcher) + : inner_matcher_(std::forward(inner_matcher)) {} + + // Converts this polymorphic matcher to a monomorphic matcher of the + // given type. ResultType can be either Result or a + // reference to Result. + template + operator ::testing::Matcher() const { // NOLINT + return ::testing::Matcher( + new IsOkAndHoldsMatcherImpl(inner_matcher_)); + } + + private: + const InnerMatcher inner_matcher_; +}; + +//////////////////////////////////////////////////////////// +// Implementation of IsOk(). + +// Monomorphic implementation of matcher IsOk() for a given type T. +// T can be Result, Error, or references to either. +template +class MonoIsOkMatcherImpl : public ::testing::MatcherInterface { + public: + void DescribeTo(std::ostream* os) const override { + *os << "is OK"; + } + void DescribeNegationTo(std::ostream* os) const override { + *os << "is not OK"; + } + bool MatchAndExplain( + T actual_value, + ::testing::MatchResultListener* result_listener) const override { + const Error error = GetError(actual_value); + if (error != Error::Ok) { + *result_listener << "which has error " + << ::executorch::runtime::to_string(error); + return false; + } + return true; + } +}; + +// Implements IsOk() as a polymorphic matcher. +class IsOkMatcher { + public: + template + operator ::testing::Matcher() const { // NOLINT + return ::testing::Matcher(new MonoIsOkMatcherImpl()); + } +}; + +//////////////////////////////////////////////////////////// +// Implementation of ErrorIs(). + +// Monomorphic implementation of matcher ErrorIs() for a given type T. +// T can be Result or a reference to Result. +template +class MonoErrorIsMatcherImpl : public ::testing::MatcherInterface { + public: + explicit MonoErrorIsMatcherImpl(::testing::Matcher error_matcher) + : error_matcher_(std::move(error_matcher)) {} + + void DescribeTo(std::ostream* os) const override { + *os << "has an error that "; + error_matcher_.DescribeTo(os); + } + + void DescribeNegationTo(std::ostream* os) const override { + *os << "does not have an error that "; + error_matcher_.DescribeNegationTo(os); + } + + bool MatchAndExplain( + T actual_value, + ::testing::MatchResultListener* result_listener) const override { + Error actual_error = GetError(actual_value); + *result_listener << "which has error " + << ::executorch::runtime::to_string(actual_error); + return error_matcher_.MatchAndExplain(actual_error, result_listener); + } + + private: + const ::testing::Matcher error_matcher_; +}; + +// Implements ErrorIs() as a polymorphic matcher. +template +class ErrorIsMatcher { + public: + explicit ErrorIsMatcher(ErrorMatcher error_matcher) + : error_matcher_(std::forward(error_matcher)) {} + + // Converts this polymorphic matcher to a monomorphic matcher of the + // given type. T can be Result or a reference to Result. + template + operator ::testing::Matcher() const { // NOLINT + return ::testing::Matcher(new MonoErrorIsMatcherImpl( + ::testing::MatcherCast(error_matcher_))); + } + + private: + const ErrorMatcher error_matcher_; +}; + +} // namespace internal + +// Returns a gMock matcher that matches a Result<> whose error is +// OK and whose value matches the inner matcher. +template +internal::IsOkAndHoldsMatcher::type> +IsOkAndHolds(InnerMatcherT&& inner_matcher) { + return internal::IsOkAndHoldsMatcher< + typename std::decay::type>( + std::forward(inner_matcher)); +} + +// Returns a gMock matcher that matches a Result<> whose error matches +// the given error matcher. +template +internal::ErrorIsMatcher::type> ErrorIs( + ErrorMatcherT&& error_matcher) { + return internal::ErrorIsMatcher::type>( + std::forward(error_matcher)); +} + +// Returns a gMock matcher that matches a Result<> which is OK. +inline internal::IsOkMatcher IsOk() { + return internal::IsOkMatcher(); +} + +} // namespace testing +} // namespace runtime +} // namespace executorch + +namespace executorch { +namespace runtime { + +// This needs to be defined in the SAME namespace that defines Error. +// C++'s look-up rules rely on that. +void PrintTo(const Error& error, std::ostream* os); + +} // namespace runtime +} // namespace executorch diff --git a/include/executorch/runtime/core/version.h b/include/executorch/runtime/core/version.h new file mode 100644 index 0000000..3be43d2 --- /dev/null +++ b/include/executorch/runtime/core/version.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * ExecuTorch version information. + * + * This file is auto-generated by CMake from version.h.in. + * Do not edit directly. + */ + +#pragma once + +/// ExecuTorch major version number. +#define ET_VERSION_MAJOR 1 + +/// ExecuTorch minor version number. +#define ET_VERSION_MINOR 6 + +/// ExecuTorch patch version number. +#define ET_VERSION_PATCH 0 + +/// ExecuTorch version string (e.g., "1.2.0"). +#define ET_VERSION "1.6.0" + +/** + * ExecuTorch version as an integer. + * Format: (MAJOR << 16) | (MINOR << 8) | PATCH + */ +#define ET_VERSION_CODE \ + ((ET_VERSION_MAJOR << 16) | (ET_VERSION_MINOR << 8) | ET_VERSION_PATCH) + +/** + * Helper macro for version comparisons. + * Usage: #if ET_VERSION_CODE >= ET_VERSION_CHECK(1, 2, 0) + */ +#define ET_VERSION_CHECK(major, minor, patch) \ + (((major) << 16) | ((minor) << 8) | (patch)) diff --git a/include/executorch/runtime/executor/memory_manager.h b/include/executorch/runtime/executor/memory_manager.h new file mode 100644 index 0000000..bc89adc --- /dev/null +++ b/include/executorch/runtime/executor/memory_manager.h @@ -0,0 +1,149 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include + +namespace executorch { +namespace runtime { + +/** + * A container class for allocators used during Method load and execution. + * + * This class consolidates all dynamic memory needs for Method load and + * execution. This can allow for heap-based as well as heap-less execution + * (relevant to some embedded scenarios), and overall provides more control over + * memory use. + * + * This class, however, cannot ensure all allocation is accounted for since + * kernel and backend implementations are free to use a separate way to allocate + * memory (e.g., for things like scratch space). But we do suggest that backends + * and kernels use these provided allocators whenever possible. + */ +class MemoryManager final { + public: + /** + * Constructs a new MemoryManager. + * + * @param[in] method_allocator The allocator to use when loading a Method and + * allocating its internal structures. Must outlive the Method that uses + * it. + * @param[in] planned_memory The memory-planned buffers to use for mutable + * tensor data when executing a Method. Must outlive the Method that uses + * it. May be `nullptr` if the Method does not use any memory-planned + * tensor data. The sizes of the buffers in this HierarchicalAllocator + * must agree with the corresponding + * `MethodMeta::num_memory_planned_buffers()` and + * `MethodMeta::memory_planned_buffer_size(N)` values, which are embedded + * in the Program. For device-aware programs, the per-buffer device + * metadata is owned by the HierarchicalAllocator as well. + * @param[in] temp_allocator The allocator to use when allocating temporary + * data during kernel or delegate execution. Must outlive the Method that + * uses it. May be `nullptr` if the Method does not use kernels or + * delegates that allocate temporary data. This allocator will be reset + * after every kernel or delegate call during execution. + */ + explicit MemoryManager( + MemoryAllocator* method_allocator, + HierarchicalAllocator* planned_memory = nullptr, + MemoryAllocator* temp_allocator = nullptr) + : method_allocator_(method_allocator), + planned_memory_(planned_memory), + temp_allocator_(temp_allocator) { + ET_CHECK_MSG( + method_allocator != temp_allocator, + "method allocator cannot be the same as temp allocator"); + } + + /** + * DEPRECATED: Use the constructor without `constant_allocator` instead. + * + * TODO(T162089316): Remove this once all users migrate to the new ctor. + */ + ET_DEPRECATED MemoryManager( + MemoryAllocator* constant_allocator, + HierarchicalAllocator* non_constant_allocator, + MemoryAllocator* runtime_allocator, + MemoryAllocator* temporary_allocator) + : MemoryManager( + /*method_allocator=*/runtime_allocator, + /*planned_memory=*/non_constant_allocator, + /*temp_allocator=*/temporary_allocator) { + (void)constant_allocator; // Suppress unused variable warning + } + + /** + * Returns the allocator that the runtime will use to allocate internal + * structures while loading a Method. Must not be used after its associated + * Method has been loaded. + */ + MemoryAllocator* method_allocator() const { + return method_allocator_; + } + + /** + * Returns the memory-planned buffers to use for mutable tensor data. + */ + HierarchicalAllocator* planned_memory() const { + return planned_memory_; + } + + /** + * Returns the allocator to use for allocating temporary data during kernel or + * delegate execution. + * + * This allocator will be reset after every kernel or delegate call during + * execution. + */ + MemoryAllocator* temp_allocator() const { + return temp_allocator_; + } + + /** + * Returns per-buffer device metadata. One entry per planned memory buffer, + * same count as planned_memory buffers. Empty if no device metadata was + * provided (CPU-only program) or if `planned_memory` is null. + * + * This is a thin wrapper around + * `HierarchicalAllocator::planned_buffer_devices()`. + */ + Span planned_buffer_devices() const { + if (planned_memory_ == nullptr) { + return {}; + } + return planned_memory_->planned_buffer_devices(); + } + + /** + * Returns true if any planned buffer has device metadata attached. + * When false, the memory setup is CPU-only. + */ + bool has_device_memory() const { + return planned_buffer_devices().size() > 0; + } + + private: + MemoryAllocator* method_allocator_; + HierarchicalAllocator* planned_memory_; + MemoryAllocator* temp_allocator_; +}; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::MemoryManager; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/executor/merged_data_map.h b/include/executorch/runtime/executor/merged_data_map.h new file mode 100644 index 0000000..aae92d9 --- /dev/null +++ b/include/executorch/runtime/executor/merged_data_map.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +namespace internal { + +/** + * A NamedDataMap implementation that wraps other NamedDataMaps. + */ +class MergedDataMap final : public NamedDataMap { + public: + /** + * Creates a new NamedDataMap that wraps two other data maps. + * + * @param[in] first The first NamedDataMap to merge. + * @param[in] second The second NamedDataMap to merge. + * Note: the data maps must outlive the MergedDataMap instance. + */ + static Result load( + const NamedDataMap* first, + const NamedDataMap* second) { + ET_CHECK_OR_RETURN_ERROR( + first != nullptr && second != nullptr, + InvalidArgument, + "Input data map is null."); + + // Check for duplicate keys. + for (uint32_t k = 0; k < first->get_num_keys().get(); k++) { + const auto key = first->get_key(k).get(); + const auto error = second->get_tensor_layout(key).error(); + // TODO(lfq): add API to check if key exists. + ET_CHECK_OR_RETURN_ERROR( + error == Error::NotFound || error == Error::NotImplemented, + InvalidArgument, + "Duplicate key %s.", + key); + } + return MergedDataMap(first, second); + } + + /** + * Retrieve the tensor_layout for the specified key. + * + * @param[in] key The name of the tensor to get metadata on. + * + * @return Error::NotFound if the key is not present. + */ + ET_NODISCARD + Result get_tensor_layout( + std::string_view key) const override { + auto layout = first_->get_tensor_layout(key); + if (layout.ok()) { + return layout.get(); + } + if (layout.error() != Error::NotFound) { + return layout.error(); + } + return second_->get_tensor_layout(key); + } + + /** + * Retrieve read-only data for the specified key. + * + * @param[in] key The name of the tensor to get data on. + * + * @return error if the key is not present or data cannot be loaded. + */ + ET_NODISCARD + Result get_data(std::string_view key) const override { + auto data = first_->get_data(key); + if (data.error() != Error::NotFound) { + return data; + } + return second_->get_data(key); + } + + /** + * Loads the data of the specified tensor into the provided buffer. + * Not used in the MergedDataMap. + * + * @param[in] key The name of the tensor to get the data of. + * @param[in] buffer The buffer to load data into. Must point to at least + * `size` bytes of memory. + * @param[in] size The number of bytes to load. + * + * @returns an Error indicating if the load was successful. + */ + ET_NODISCARD Error load_data_into( + ET_UNUSED std::string_view key, + ET_UNUSED void* buffer, + ET_UNUSED size_t size) const override { + return Error::NotImplemented; + } + + /** + * @returns The number of keys in the map. + */ + ET_NODISCARD Result get_num_keys() const override { + return first_->get_num_keys().get() + second_->get_num_keys().get(); + } + + /** + * @returns The key at the specified index, error if index out of bounds. + */ + ET_NODISCARD Result get_key(uint32_t index) const override { + uint32_t total_num_keys = get_num_keys().get(); + ET_CHECK_OR_RETURN_ERROR( + index < total_num_keys, + InvalidArgument, + "Index %" PRIu32 " out of range of size %" PRIu32, + index, + total_num_keys); + + if (index < first_->get_num_keys().get()) { + return first_->get_key(index); + } else { + return second_->get_key(index - first_->get_num_keys().get()); + } + } + + MergedDataMap(MergedDataMap&&) noexcept = default; + + ~MergedDataMap() override = default; + + private: + MergedDataMap(const NamedDataMap* first, const NamedDataMap* second) + : first_{first}, second_{second} {} + + // Not copyable or assignable. + MergedDataMap(const MergedDataMap& rhs) = delete; + MergedDataMap& operator=(MergedDataMap&& rhs) noexcept = delete; + MergedDataMap& operator=(const MergedDataMap& rhs) = delete; + + const NamedDataMap* first_; + const NamedDataMap* second_; +}; + +} // namespace internal +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch diff --git a/include/executorch/runtime/executor/method.h b/include/executorch/runtime/executor/method.h new file mode 100644 index 0000000..9432e2c --- /dev/null +++ b/include/executorch/runtime/executor/method.h @@ -0,0 +1,466 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#ifdef __GNUC__ +// Disable -Wdeprecated-declarations, as some builds use 'Werror'. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Forward declare flatbuffer types. This is a public header and must not +// include the generated flatbuffer header. +namespace executorch_flatbuffer { +struct Chain; +struct ExecutionPlan; +struct EValue; +} // namespace executorch_flatbuffer + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { + +// Forward declare NamedData. This is a public header and must not include +// internal data types. +namespace deserialization { +struct NamedData; +} // namespace deserialization + +// Forward declare Program to avoid a circular reference. +class Program; + +// Forward declare internal types. +class BackendDelegate; +struct Chain; +class KernelRuntimeContext; +using OpFunction = void (*)(KernelRuntimeContext&, Span); +/// A list of pointers into the master values table that together compose the +/// argument list for a single instruction +using InstructionArgs = Span; +using deserialization::NamedData; + +/** + * An executable method of an executorch program. Maps to a python method like + * `forward()` on the original nn.Module. + */ +class Method final { + public: + /** + * Move ctor. Takes ownership of resources previously owned by `rhs`, + * and leaves `rhs` in an uninitialized state. + */ + Method(Method&& rhs) noexcept + : step_state_(rhs.step_state_), + program_(rhs.program_), + memory_manager_(rhs.memory_manager_), + temp_allocator_(rhs.temp_allocator_), + serialization_plan_(rhs.serialization_plan_), + event_tracer_(rhs.event_tracer_), + n_value_(rhs.n_value_), + values_(rhs.values_), + input_set_(rhs.input_set_), + n_delegate_(rhs.n_delegate_), + delegates_(rhs.delegates_), + n_chains_(rhs.n_chains_), + chains_(rhs.chains_), + merged_data_map_(std::move(rhs.merged_data_map_)), + external_constants_(rhs.external_constants_), + n_external_constants_(rhs.n_external_constants_), + kernel_registry_(rhs.kernel_registry_), + init_state_(rhs.init_state_) { + // Required: clear out fields that the dtor looks at, so that we don't free + // anything twice. + rhs.n_value_ = 0; + rhs.values_ = nullptr; + rhs.input_set_ = nullptr; + rhs.n_delegate_ = 0; + rhs.delegates_ = nullptr; + + rhs.merged_data_map_ = nullptr; + rhs.n_external_constants_ = 0; + rhs.external_constants_ = nullptr; + + // Helpful: Try to ensure that any other interactions with the old object + // result in failures. + rhs.init_state_ = InitializationState::Uninitialized; + rhs.step_state_ = {}; + rhs.program_ = nullptr; + rhs.memory_manager_ = nullptr; + rhs.serialization_plan_ = nullptr; + rhs.event_tracer_ = nullptr; + rhs.n_chains_ = 0; + rhs.chains_ = nullptr; + } + + /** + * Sets the internal input value to be equivalent to the to the provided + * value. + * + * @param[in] input_evalue The evalue to copy into the method input. If the + * evalue is a tensor, the data is copied in most cases, so the tensor + * passed in here does not always need to outlive this call. But there is + * a case where the Method will keep a pointer to the tensor's data. + * Based on the memory plan of the method, the inputs may not have + * buffer space pre-allocated for them. In this case the executor will + * alias the memory of the tensors provided as inputs here rather then + * deepcopy the input into the memory planned arena. + * + * @param[in] input_idx Zero-based index of the input to set. Must be less + * than the value returned by inputs_size(). + * + * @returns Error::Ok on success, non-Ok on failure. + */ + ET_NODISCARD Error set_input(const EValue& input_evalue, size_t input_idx); + + /** + * Sets the values of all method inputs. + * + * See set_input() for a more detailed description of the behavior. + * + * @param[in] input_evalues The new values for all of the method inputs. The + * type of each element must match the type of corresponding input. If the + * value of an element is a tensor, attempts to allow dynamic shape, but + * the dtype must always agree. + * + * @returns Error::Ok on success, non-Ok on failure. + */ + ET_NODISCARD Error + set_inputs(const executorch::aten::ArrayRef& input_evalues); + + /** + * Sets the data buffer of the specified method output to the provided value. + * + * NOTE: Based on the memory plan of the method, the output tensors may not + * have buffer space pre-allocated for them, in this case the executor will + * point those tensors to the buffer provided here, so the user should take + * care that the life span of this memory outlasts the executor forward. + * + * @param[in] buffer The block of memory to point the specified tensor at. + * + * @param[in] size the length of buffer in bytes, must be >= the largest + * nbytes the output can have, + * `MethodMeta::output_tensor_meta(output_idx)->nbytes()`. + * + * @param[in] output_idx The index of the output to set the data_ptr for. Must + * correspond to a tensor, and that tensor must not have had a buffer + * allocated by the memory plan. + * + * @returns Error::Ok on success, non-Ok on failure. + */ + ET_NODISCARD Error + set_output_data_ptr(void* buffer, size_t size, size_t output_idx); + + /** + * Copies the method's outputs into the provided array. + * + * WARNING: The output contains shallow copies of internal tensor outputs. + * Please do not mutate returned Tensor elements. + * + * TODO(T139259264): Add checks to detect output mutation, or deep-copy + * outputs. + * + * @param[in] output_evalues The array to copy the outputs into. The first + * `outputs_size()` elements will be set to the corresponding output + * values. The rest of the array will be set to the EValue value None. + * @param[in] length The size of the `output_evalues` array in elements. Must + * be greater than or equal to `outputs_size()`. + * + * @returns Error::Ok on success, non-Ok on failure. + */ + ET_NODISCARD Error get_outputs(EValue* output_evalues, size_t length); + + /** + * DEPRECATED: Use MethodMeta instead to access metadata, and set_input to + * update Method inputs. + * + * Copies the method's inputs into the provided array. + * + * WARNING: The input contains shallow copies of internal tensor inputs. + * Please do not mutate returned Tensor elements. + * + * @param[in] input_evalues The array to copy the inputs into. The first + * `inputs_size()` elements will be set to the corresponding input + * values. The rest of the array will be set to the EValue value None. + * @param[in] length The size of the `input_evalues` array in elements. Must + * be greater than or equal to `inputs_size()`. + * + * @returns Error::Ok on success, non-Ok on failure. + */ + ET_DEPRECATED ET_NODISCARD Error + get_inputs(EValue* input_evalues, size_t length); + + /** + * + * Retrieves the attribute tensor associated with the given name. + * + * @param[in] name The name of the attribute tensor to retrieve. + * + * @returns Result containing the attribute tensor on success, non-Ok on + * failure. + */ + ET_NODISCARD Result get_attribute( + std::string_view name); + + /** + * Execute the method. + * + * NOTE: Will fail with Error::InvalidState if the method has been partially + * executed using the `step()` api. Call reset_execution() after step() + * reaches EndOfMethod before calling execute(). + * + * If execute() encounters an error mid-execution, the state is automatically + * reset to allow retry attempts. + * + * @returns Error::Ok on success, non-Ok on failure. + */ + ET_NODISCARD Error execute(); + + /** + * EXPERIMENTAL: Advances/executes a single instruction in the method. + * + * @retval Error::Ok step succeeded + * @retval non-Ok step failed + * @retval Error::EndOfMethod method finished executing successfully + */ + ET_EXPERIMENTAL ET_NODISCARD Error step(); + + /// DEPRECATED: Use `step()` instead. + ET_DEPRECATED ET_NODISCARD Error experimental_step(); + + /** + * EXPERIMENTAL: Returns true if method execution is in progress. + * + * Execution is considered "in progress" when step() has been called and + * execution is mid-way through the instruction sequence. + * + * @retval true if execution is in progress (not at initial state, not at end) + * @retval false if at initial state, after completion, or after any error + * + * @note execute() automatically resets state on error, so in_progress() + * returns false immediately after execute() fails. + */ + ET_EXPERIMENTAL ET_NODISCARD bool in_progress() const; + + /** + * EXPERIMENTAL: Resets execution state to the start of the Method. For use + * with the `step()` API. + * + * @retval Error::Ok on success + * @retval Error::InvalidState if called before step-based execution reached + * the end of the Method. When using step(), you must step through to + * EndOfMethod before resetting. Note: execute() handles its own error + * recovery and does not require manual reset. + */ + ET_EXPERIMENTAL ET_NODISCARD Error reset_execution(); + + /// DEPRECATED: Use `reset_execution()` instead. + ET_DEPRECATED ET_NODISCARD Error experimental_reset_execution(); + + /** + * Returns the MethodMeta that corresponds to the calling Method. + */ + MethodMeta method_meta() const; + + /** + * Returns the number of inputs the Method expects. + */ + size_t inputs_size() const; + + /** + * Returns the number of outputs the Method returns. + */ + size_t outputs_size() const; + + /** + * Retrieves the output at the specified index. + */ + const EValue& get_output(size_t i) const; + + EventTracer* get_event_tracer(); + + /// DEPRECATED: Use MethodMeta instead to access metadata, and set_input to + /// update Method inputs. + ET_DEPRECATED const EValue& get_input(size_t i) const; + /// DEPRECATED: Use MethodMeta instead to access metadata, and set_input to + /// update Method inputs. + ET_DEPRECATED EValue& mutable_input(size_t i); + /// DEPRECATED: Use MethodMeta instead to access metadata, and get_output to + /// retrieve Method outputs. + ET_DEPRECATED EValue& mutable_output(size_t i); + + ~Method(); + + private: + // Delete other rule-of-five methods. + Method(const Method&) = delete; + Method& operator=(const Method&) noexcept = delete; + Method& operator=(Method&&) = delete; + + // Let Program call load(). + friend class Program; + // Let Executor call the ctor and init(). + friend class Executor; + + enum class InitializationState : uint8_t { + Uninitialized, + Initialized, + InitializationFailed, + }; + + /// Tracks what step in program execution we are on + struct StepState { + size_t chain_idx; + size_t instr_idx; + }; + + Method( + const Program* program, + MemoryManager* memory_manager, + EventTracer* event_tracer, + MemoryAllocator* temp_allocator, + Span kernel_registry = {}) + : step_state_(), + program_(program), + memory_manager_(memory_manager), + temp_allocator_(temp_allocator), + serialization_plan_(nullptr), + event_tracer_(event_tracer), + n_value_(0), + values_(nullptr), + input_set_(nullptr), + n_delegate_(0), + delegates_(nullptr), + n_chains_(0), + chains_(nullptr), + merged_data_map_(nullptr), + external_constants_(nullptr), + n_external_constants_(0), + kernel_registry_(kernel_registry), + init_state_(InitializationState::Uninitialized) {} + + /// Static factory used by Program. + ET_NODISCARD static Result load( + executorch_flatbuffer::ExecutionPlan* s_plan, + const Program* program, + MemoryManager* memory_manager, + EventTracer* event_tracer, + const NamedDataMap* named_data_map, + const LoadBackendOptionsMap* backend_options = nullptr, + Span kernel_registry = {}); + + /** + * Initialize the method from its serialized representation. + * + * @returns Error::Ok on success, non-Ok on failure. + */ + ET_NODISCARD Error init( + executorch_flatbuffer::ExecutionPlan* s_plan, + const NamedDataMap* named_data_map, + const LoadBackendOptionsMap* backend_options); + + /// Returns true if the Method was successfully initialized. + inline bool initialized() const { + return init_state_ == InitializationState::Initialized; + } + + const EValue& get_value(size_t i) const; + EValue& mutable_value(size_t i); + size_t get_input_index(size_t i) const; + size_t get_output_index(size_t i) const; + + // Executes a single instruction using the state in step_state_ + ET_NODISCARD Error execute_instruction(); + + StepState step_state_; + const Program* program_; + MemoryManager* memory_manager_; + MemoryAllocator* temp_allocator_; + executorch_flatbuffer::ExecutionPlan* serialization_plan_; + EventTracer* event_tracer_; + + size_t n_value_; + EValue* values_; + bool* input_set_; + + size_t n_delegate_; + BackendDelegate* delegates_; + + size_t n_chains_; + Chain* chains_; + + internal::MergedDataMap* merged_data_map_; + NamedData* external_constants_; + size_t n_external_constants_ = 0; + + Span kernel_registry_; + + InitializationState init_state_; + + /** + * Counts the number of tensors marked as EXTERNAL in the flatbuffer + * for this method. + */ + ET_NODISCARD Result get_num_external_constants(); + + /** + * Parses the flatbuffer for constant tensors tagged as EXTERNAL. + * Retrieves the external constants using the named_data_map and places them + * into `external_constants_`. Updates `n_external_constants_` to count the + * number of successfully-initialized external constants. + * FreeableBuffers returned by the named_data_map are owned by the + * method and are freed on method destruction. + * + * @param[in] named_data_map, to retrieve external constants from. + * @returns Error::Ok on success, non-Ok on failure. + */ + ET_NODISCARD Error + parse_external_constants(const NamedDataMap* named_data_map); + + /** + * Parses the elements of the values_ array. On error, n_value_ will be set to + * the number of successfully-initialized entries so that ~Method doesn't try + * to clean up uninitialized entries. + */ + ET_NODISCARD Error parse_values(const NamedDataMap* named_data_map); + + ET_NODISCARD Error resolve_operator( + int32_t op_index, + OpFunction* kernels, + size_t kernel_index, + InstructionArgs args, + size_t n_args); + + void log_outputs(); +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::Method; +} // namespace executor +} // namespace torch + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif diff --git a/include/executorch/runtime/executor/method_meta.h b/include/executorch/runtime/executor/method_meta.h new file mode 100644 index 0000000..e61e219 --- /dev/null +++ b/include/executorch/runtime/executor/method_meta.h @@ -0,0 +1,338 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include + +// Forward declare flatbuffer types. This is a public header and must not +// include the generated flatbuffer header. +namespace executorch_flatbuffer { +struct ExecutionPlan; +} // namespace executorch_flatbuffer + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +namespace testing { +// Provides test access to private Program methods. +class TensorInfoTestFriend; +} // namespace testing + +/** + * Metadata about a specific tensor of an ExecuTorch Program. + * + * The program used to create the MethodMeta object that created this + * TensorInfo must outlive this TensorInfo. + */ +class TensorInfo final { + public: + TensorInfo() = delete; + TensorInfo(const TensorInfo&) = default; + TensorInfo(TensorInfo&&) = default; + TensorInfo& operator=(const TensorInfo&) = default; + TensorInfo& operator=(TensorInfo&& other) = default; + ~TensorInfo() = default; + + /** + * Returns the sizes of the tensor. + */ + Span sizes() const; + + /** + * Returns the dim order of the tensor. + */ + Span dim_order() const; + + /** + * Returns the scalar type of the input/output. + */ + executorch::aten::ScalarType scalar_type() const; + + /** + * Returns whether the tensor's memory was planned during export. + */ + bool is_memory_planned() const; + + /** + * Returns the size of the tensor in bytes. + */ + size_t nbytes() const; + + /** + * Returns the fully qualified name of the Tensor might be empty if the tensor + * is nameless. + */ + std::string_view name() const; + + /** + * Returns the device the program places the tensor on. Tensors without a + * device annotation are on the CPU. + */ + etensor::Device device() const; + + private: + // Let MethodMeta create TensorInfo. + friend class MethodMeta; + friend class testing::TensorInfoTestFriend; + + /** + * Create a TensorInfo instance. + * + * @param[in] sizes The sizes of the tensor. + * @param[in] dim_order The dim order of the tensor. + * @param[in] scalar_type The scalar type of the tensor. + * @param[in] is_memory_planned Whether the tensor's memory was planned. + * @param[in] name The fully qualified name of the tensor. + * @param[in] device The device the program places the tensor on. + * @returns A Result containing the TensorInfo on success, or an error on + * failure. + */ + static Result create( + Span sizes, + Span dim_order, + executorch::aten::ScalarType scalar_type, + const bool is_memory_planned, + std::string_view name, + etensor::Device device); + + TensorInfo( + Span sizes, + Span dim_order, + executorch::aten::ScalarType scalar_type, + const bool is_memory_planned, + std::string_view name, + size_t nbytes, + etensor::Device device); + + /** + * The sizes of the tensor. + * + * NOTE: References data from the Program, so the Program must outlive the + * TensorInfo. + */ + Span sizes_; + + /** + * The dim order of the tensor. + * + * NOTE: References data from the Program, so the Program must outlive the + * TensorInfo. + */ + Span dim_order_; + + /// The fully qualified name of the Tensor. + std::string_view name_; + + /// The scalar type of the tensor. + executorch::aten::ScalarType scalar_type_; + + /// Whether the tensor's memory was planned during export. + bool is_memory_planned_; + + /// The size in bytes of the tensor. + size_t nbytes_; + + /// The device the program places the tensor on. + etensor::Device device_; +}; + +/** + * Describes a a method in an ExecuTorch program. + * + * The program used to create a MethodMeta object must outlive the MethodMeta. + * It is separate from Method so that this information can be accessed without + * paying the initialization cost of loading the full Method. + */ +class MethodMeta final { + public: + MethodMeta() = delete; + MethodMeta(const MethodMeta&) = default; + MethodMeta(MethodMeta&&) = default; + MethodMeta& operator=(const MethodMeta&) = default; + MethodMeta& operator=(MethodMeta&& other) = default; + ~MethodMeta() = default; + + /** + * Creates metadata over a serialized execution plan after validating it. + * + * `data` and its backing storage must outlive the returned view. This is + * intended for format adapters that synthesize an ExecuTorch metadata view. + */ + static Result from_serialized_execution_plan( + const void* data, + size_t size); + + /** + * Get the name of this method. + * + * @returns The method name. + */ + const char* name() const; + + /** + * Get the number of inputs to this method. + * + * @returns The number of inputs. + */ + size_t num_inputs() const; + + /** + * Get the tag of the specified input. + * + * @param[in] index The index of the input to look up. + * @returns The tag of input, can only be [Tensor, Int, Bool, Double, String]. + */ + Result input_tag(size_t index) const; + + /** + * Get metadata about the specified input. + * + * @param[in] index The index of the input to look up. + * @returns The metadata on success, or an error on failure. Only valid for + * tag::Tensor + */ + Result input_tensor_meta(size_t index) const; + + /** + * Get the number of outputs to this method. + * + * @returns The number of outputs. + */ + size_t num_outputs() const; + + /** + * Get the tag of the specified output. + * + * @param[in] index The index of the output to look up. + * @returns The tag of output, can only be [Tensor, Int, Bool, Double, + * String]. + */ + Result output_tag(size_t index) const; + + /** + * Get metadata about the specified output. + * + * @param[in] index The index of the output to look up. + * @returns The metadata on success, or an error on failure. Only valid for + * tag::Tensor + */ + Result output_tensor_meta(size_t index) const; + + /** + * Get the number of attribute tensors in this method. + * + * @returns The number of attribute tensors. + */ + size_t num_attributes() const; + + /** + * Get metadata about the specified attribute tensor. + * + * @param[in] index The index of the attribute tensor to look up. + * @returns The metadata on success, or an error on failure. + */ + Result attribute_tensor_meta(size_t index) const; + + /** + * Get the number of memory-planned buffers this method requires. + * + * @returns The number of memory-planned buffers. + */ + size_t num_memory_planned_buffers() const; + + /** + * Get the size in bytes of the specified memory-planned buffer. + * + * @param[in] index The index of the buffer to look up. + * @returns The size in bytes on success, or an error on failure. + */ + Result memory_planned_buffer_size(size_t index) const; + + /** + * Get the device placement for the specified memory-planned buffer. + * + * For CPU-only programs (no non_const_buffer_device in the PTE), all buffers + * default to Device{CPU, 0}. For programs with device annotations, returns + * the device type and index that the buffer should be allocated on. + * + * @param[in] index The index of the buffer to look up (0-based, same + * indexing as memory_planned_buffer_size()). + * @returns The Device on success, or an error on failure. + */ + Result memory_planned_buffer_device(size_t index) const; + + /** + * Check to see if a backend is used in this method. + * + * @param[in] backend_name The name of the backend to search for. + * @returns true if a backend is used in this method, otherwise false. + */ + bool uses_backend(const char* backend_name) const; + + /** + * Get the number of backends used in this method. + * + * @returns The total number of backend names. + */ + size_t num_backends() const; + + /** + * Get the backend name at the given index. + * + * @param[in] index The index of the backend name. + * @returns A Result wrapping the backend name as a C-style string + * on success, or an error if the index is invalid. + */ + Result get_backend_name(size_t index) const; + + /** + * Get the number of instructions in this method. + * + * @returns The number of instructions. + */ + ET_EXPERIMENTAL size_t num_instructions() const; + + /** + * DEPRECATED: Use num_memory_planned_buffers() instead. + */ + ET_DEPRECATED size_t num_non_const_buffers() const { + return num_memory_planned_buffers(); + } + + /** + * DEPRECATED: Use memory_planned_buffer_size() instead. + */ + Result non_const_buffer_size(size_t index) const { + return memory_planned_buffer_size(index); + } + + private: + // Let Program create MethodMeta. + friend class Program; + + explicit MethodMeta(const executorch_flatbuffer::ExecutionPlan* s_plan); + + /// Source of truth for method information + const executorch_flatbuffer::ExecutionPlan* s_plan_; +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::MethodMeta; +using ::executorch::ET_RUNTIME_NAMESPACE::TensorInfo; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/executor/platform_memory_allocator.h b/include/executorch/runtime/executor/platform_memory_allocator.h new file mode 100644 index 0000000..a103da1 --- /dev/null +++ b/include/executorch/runtime/executor/platform_memory_allocator.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +namespace internal { + +/** + * PlatformMemoryAllocator is a memory allocator that uses a linked list to + * manage allocated nodes. It overrides the allocate method of MemoryAllocator + * using the PAL fallback allocator method `et_pal_allocate`. + */ +class PlatformMemoryAllocator final : public MemoryAllocator { + private: + // We allocate a little more than requested and use that memory as a node in + // a linked list, pushing the allocated buffers onto a list that's iterated + // and freed when the KernelRuntimeContext is destroyed. + struct AllocationNode { + void* data; + AllocationNode* next; + }; + + AllocationNode* head_ = nullptr; + + public: + PlatformMemoryAllocator() : MemoryAllocator(0, nullptr) {} + + void* allocate(size_t size, size_t alignment = kDefaultAlignment) override { + if (!isPowerOf2(alignment)) { + ET_LOG(Error, "Alignment %zu is not a power of 2", alignment); + return nullptr; + } + + // Check for overflow before computing total allocation size. + // Allocate enough for the node, data, and alignment bump (at most + // alignment - 1 extra bytes to align the data pointer). + size_t alloc_size = 0; + if (c10::add_overflows(sizeof(AllocationNode), size, &alloc_size) || + c10::add_overflows(alloc_size, alignment - 1, &alloc_size)) { + ET_LOG( + Error, + "Allocation size overflow: size %zu, alignment %zu", + size, + alignment); + return nullptr; + } + + void* node_memory = runtime::pal_allocate(alloc_size); + + // If allocation failed, log message and return nullptr. + if (node_memory == nullptr) { + ET_LOG(Error, "Failed to allocate %zu bytes", alloc_size); + return nullptr; + } + + // Compute data pointer. + uint8_t* data_ptr = + reinterpret_cast(node_memory) + sizeof(AllocationNode); + + // Align the data pointer. + void* aligned_data_ptr = alignPointer(data_ptr, alignment); + + // Assert that the alignment didn't overflow the allocated memory. + ET_DCHECK_MSG( + reinterpret_cast(aligned_data_ptr) + size <= + reinterpret_cast(node_memory) + alloc_size, + "aligned_data_ptr %p + size %zu > node_memory %p + alloc_size %zu", + aligned_data_ptr, + size, + node_memory, + alloc_size); + + // Construct the node. + AllocationNode* new_node = reinterpret_cast(node_memory); + new_node->data = aligned_data_ptr; + new_node->next = head_; + head_ = new_node; + + // Return the aligned data pointer. + return head_->data; + } + + void reset() override { + AllocationNode* current = head_; + while (current != nullptr) { + AllocationNode* next = current->next; + runtime::pal_free(current); + current = next; + } + head_ = nullptr; + } + + ~PlatformMemoryAllocator() override { + reset(); + } + + private: + // Disable copy and move. + PlatformMemoryAllocator(const PlatformMemoryAllocator&) = delete; + PlatformMemoryAllocator& operator=(const PlatformMemoryAllocator&) = delete; + PlatformMemoryAllocator(PlatformMemoryAllocator&&) noexcept = delete; + PlatformMemoryAllocator& operator=(PlatformMemoryAllocator&&) noexcept = + delete; +}; + +} // namespace internal +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch diff --git a/include/executorch/runtime/executor/program.h b/include/executorch/runtime/executor/program.h new file mode 100644 index 0000000..02d08f6 --- /dev/null +++ b/include/executorch/runtime/executor/program.h @@ -0,0 +1,365 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Forward declare flatbuffer types. This is a public header and must not +// include the generated flatbuffer header. +namespace executorch_flatbuffer { +struct Program; +} // namespace executorch_flatbuffer + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +namespace testing { +// Provides test access to private Program methods. +class ProgramTestFriend; +} // namespace testing + +namespace deserialization { +// Provides Tensor deserializaiton access to private Program methods. +class TensorParser; +} // namespace deserialization + +/** + * A deserialized ExecuTorch program binary. + */ +class Program final { + public: + /** + * Types of validation that the Program can do before parsing the data. + */ + enum class Verification : uint8_t { + /** + * Do minimal verification of the data, ensuring that the header appears + * correct. + * + * Has minimal runtime overhead. + */ + Minimal, + /** + * When ET_ENABLE_PROGRAM_VERIFICATION is enabled, + * Do full verification of the data, ensuring that internal pointers are + * self-consistent and that the data has not been truncated or obviously + * corrupted. May not catch all types of corruption, but should guard + * against illegal memory operations during parsing. + * Also performs additional semantic validation such as: + * - Tensor numel overflow checks (ensuring size calculations don't + * overflow) + * - List element type validation + * + * Will have higher runtime overhead, scaling with the complexity of the + * proram data. + */ + InternalConsistency, + }; + + /** + * The highest program schema version that this runtime can read. + * + * Keep in sync with EXECUTORCH_SCHEMA_VERSION in + * //executorch/exir/version.py, which is the version that the exporter stamps + * into every PTE file. + */ + static constexpr uint32_t kMaxSupportedSchemaVersion = 0; + + /** + * Loads a Program from the provided loader. The Program will hold a pointer + * to the loader, which must outlive the returned Program instance. + * + * @param[in] loader The source to load program data from. The Program will + * hold a pointer to this loader, which must outlive the returned Program + * instance. + * @param[in] verification The type of verification to do before returning + * success. + */ + ET_NODISCARD static Result load( + DataLoader* loader, + Verification verification = Verification::Minimal); + + /// DEPRECATED: Use the lowercase `load()` instead. + ET_DEPRECATED ET_NODISCARD static Result Load( + DataLoader* loader, + Verification verification = Verification::Minimal) { + return load(loader, verification); + } + + // Movable, to be compatible with Result. + Program(Program&&) noexcept = default; + ~Program() = default; + + /** + * Get the constant buffer inside Program with index buffer_idx. + * @param[in] buffer_idx the index of the buffer in the constant_buffer. + * @param[in] nbytes the number of bytes to read from the buffer. + * @return The buffer with corresponding index. + */ + Result get_constant_buffer_data(size_t buffer_idx, size_t nbytes) + const; + + /** + * Get the named data map from the program. + * @return The named data map. + */ + Result get_named_data_map() const; + + /** + * Returns the number of methods in the program. + */ + size_t num_methods() const; + + /** + * Returns the name of the method at particular index. + * + * @param[in] method_index The index of the method name to retrieve. Must be + * less than the value returned by `num_methods()`. + * + * @returns The name of the requested method. The pointer is owned by the + * Program, and has the same lifetime as the Program. + */ + Result get_method_name(size_t method_index) const; + + /** + * Loads the named method and prepares it for execution. + * + * @param[in] method_name The name of the method to load. + * @param[in] memory_manager The allocators to use during initialization and + * execution of the loaded method. If `memory_manager.temp_allocator()` is + * null, the runtime will allocate temp memory using `et_pal_allocate()`. + * @param[in] event_tracer The event tracer to use for this method run. + * @param[in] named_data_map An optional map of {name, blob} used to resolve + * data that is external to the PTE, if any. + * @param[in] backend_options An optional map of per-backend load-time options + * (RuntimeSpecs). Each backend will receive its corresponding options + * during initialization. + * + * @returns The loaded method on success, or an error on failure. + */ + Result load_method( + const char* method_name, + MemoryManager* memory_manager, + EventTracer* event_tracer = nullptr, + const NamedDataMap* named_data_map = nullptr, + const LoadBackendOptionsMap* backend_options = nullptr, + Span kernel_registry = {}) const; + + /** + * Gathers metadata for the named method. + * + * @param[in] method_name The name of the method to get metadata for. + */ + Result method_meta(const char* method_name) const; + + /** + * DEPRECATED: Get the pytree encoding string for the output. Deprecated as + * this functionality will eventually move out of the core program into a + * higher level structure, but that does not exist at this time. + * @param[in] method_name The name of the method to get the encoding for. + * + * @return The pytree encoding string for the output + */ + ET_DEPRECATED Result get_output_flattening_encoding( + const char* method_name = "forward") const; + + /** + * Describes the presence of an ExecuTorch program header. + */ + enum HeaderStatus { + /** + * An ExecuTorch program header is present, and its version is compatible + * with this version of the runtime. + */ + CompatibleVersion, + + /** + * An ExecuTorch program header is present, but its version is not + * compatible with this version of the runtime. + */ + IncompatibleVersion, + + /** + * An ExecuTorch program header is not present. + */ + NotPresent, + + /** + * The data provided was too short to find the program header. + */ + ShortData, + }; + + /** + * The minimum number of bytes necessary for calls to `check_header`. + */ + static constexpr size_t kMinHeadBytes = 64; + + /** + * Looks for an ExecuTorch program header in the provided data. + * + * @param[in] data The data from the beginning of a file that might contain + * an ExecuTorch program. + * @param[in] size The size of `data` in bytes. Must be >= `kMinHeadBytes`. + * + * @returns A value describing the presence of a header in the data. + */ + static HeaderStatus check_header(const void* data, size_t size); + + private: + // Let some classes call these private methods. + friend class BackendDelegate; + friend class Executor; + friend class Method; + friend class deserialization::TensorParser; + friend class testing::ProgramTestFriend; + + const executorch_flatbuffer::Program* get_internal_program() const { + return internal_program_; + } + + // Used by Method to look up entries in the delegate data table. + Error get_backend_delegate_data( + size_t index, + const void** out_data, + size_t* out_size) const; + + /** + * Loads a segment by index. + * + * @param[in] segment_info Struct containing an index to load from the + * Program.segments list. The other fields of the struct, such as + * `segment_type` and `descriptor`, need to also be correct. + * + * @returns The data as a FreeableBuffer, if the index is valid. + * @retval Error::NotFound The program does not contain any segments or the + * index is out of range. + * @returns Other errors depending on the implementation of + * DataLoader: The Program.segment table is inconsistent, or the + * data cannot be accessed. + */ + ET_NODISCARD Result LoadSegment( + const DataLoader::SegmentInfo& segment_info) const; + + /** + * Loads a portion of a mutable segment into the provided buffer. + * + * @param[in] mutable_data_segments_index The index into the + * mutable_data_segments_array. + * @param[in] offset_index The index into the segment's offsets array. + * @param[in] size The number of bytes to load. + * @param[in] buffer The buffer to load data into. Must point to at least + * `size` bytes of memory. + * + * @returns An error code on if the load was successful. + * @retval Error::Ok The load was successful. + * @retval Error::NotFound The program does not contain any segments or the + * indices are out of range. + * @returns Other errors depending on the implementation of + * DataLoader: The Program.segment table is inconsistent, or the + * data cannot be accessed. + */ + ET_NODISCARD Error load_mutable_subsegment_into( + size_t mutable_data_segments_index, + size_t offset_index, + size_t size, + void* buffer) const; + + /** + * Loads a portion of a mutable segment into a new buffer, for a destination + * such as device memory that the data loader cannot write. + * + * Takes the same arguments as load_mutable_subsegment_into(), except the + * buffer, and fails in the same cases. + * + * @returns The data as a FreeableBuffer of `size` bytes. + */ + ET_NODISCARD Result load_mutable_subsegment( + size_t mutable_data_segments_index, + size_t offset_index, + size_t size) const; + + /// Where a mutable subsegment starts in the data loader's data, and the + /// segment info to load it with. + struct MutableSubsegment { + size_t offset; + DataLoader::SegmentInfo info; + }; + + /// Checks the indices and size of a mutable subsegment and locates it. + ET_NODISCARD Result locate_mutable_subsegment( + size_t mutable_data_segments_index, + size_t offset_index, + size_t size) const; + + private: + Program( + DataLoader* loader, + size_t segment_base_offset, + FreeableBuffer&& program_data, + const executorch_flatbuffer::Program* internal_program, + FreeableBuffer&& constant_segment_data, + std::optional&& pte_data_map) + : program_data_(std::move(program_data)), + // Don't need the loader if there are no segments. + loader_(segment_base_offset > 0 ? loader : nullptr), + internal_program_(internal_program), + segment_base_offset_(segment_base_offset), + constant_segment_data_(std::move(constant_segment_data)), + pte_data_map_(std::move(pte_data_map)) {} + + // Not copyable or assignable. + Program(const Program& rhs) = delete; + Program& operator=(Program&& rhs) noexcept = delete; + Program& operator=(const Program& rhs) = delete; + + /// The serialized program data. Tensors will point directly into this buffer. + FreeableBuffer program_data_; + + /// Used to load segment data. Null if there are no segments. + DataLoader* loader_; + + /// The flatbuffer representation of the program. Must not be exposed to + /// users. + const executorch_flatbuffer::Program* internal_program_; + + /// The offset to the first segment, in bytes. If zero, no segments should + /// be present in internal_program_. + size_t segment_base_offset_; + + /// Constant segment data. + FreeableBuffer constant_segment_data_; + + /// NamedDataMap holding named data from the program. + std::optional pte_data_map_; +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::Program; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/executor/program_validation.h b/include/executorch/runtime/executor/program_validation.h new file mode 100644 index 0000000..68e4ff7 --- /dev/null +++ b/include/executorch/runtime/executor/program_validation.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +// Forward declare flatbuffer types. +namespace executorch_flatbuffer { +struct ExecutionPlan; +struct Program; +struct Tensor; +struct TensorList; +} // namespace executorch_flatbuffer + +namespace executorch { +namespace runtime { + +/** + * Validates that a tensor's metadata is semantically valid: sizes are + * non-negative, scalar type is valid, and computing numel/nbytes will not + * overflow. + * + * @param[in] tensor The flatbuffer Tensor to validate. + * @return Error::Ok if validation passes, Error::InvalidProgram otherwise. + */ +ET_NODISCARD Error validate_tensor(const executorch_flatbuffer::Tensor* tensor); + +/** + * Performs validation of all tensors and lists in the program, checking that + * their metadata is semantically valid and will not cause issues during + * execution. + * + * Currently validates: + * - Tensor numel overflow (all tensors) + * - TensorList element types (all TensorLists) + * + * @param[in] program The flatbuffer Program to validate. + * @return Error::Ok if validation passes, Error::InvalidProgram if any + * validation check fails. + */ +ET_NODISCARD Error +validate_program(const executorch_flatbuffer::Program* program); + +} // namespace runtime +} // namespace executorch diff --git a/include/executorch/runtime/executor/pte_data_map.h b/include/executorch/runtime/executor/pte_data_map.h new file mode 100644 index 0000000..36d33ae --- /dev/null +++ b/include/executorch/runtime/executor/pte_data_map.h @@ -0,0 +1,151 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include + +// Forward declare flatbuffer types. This is a public header and must not +// include the generated flatbuffer header. +namespace executorch_flatbuffer { +struct NamedData; +struct DataSegment; +} // namespace executorch_flatbuffer + +namespace flatbuffers { +template +struct Offset; +} // namespace flatbuffers + +// @lint-ignore CLANGTIDY facebook-modularize-issue-check +#if EXECUTORCH_INTERNAL_FLATBUFFERS == 1 +// TODO(T216992074): update internal flatbuffers (v1.12) to match OSS (v24.3.5). +namespace flatbuffers { +template +class Vector; +using FlatbufferNamedData = + flatbuffers::Vector>; +using FlatbufferDataSegment = flatbuffers::Vector< + flatbuffers::Offset>; +} // namespace flatbuffers +#else +namespace flatbuffers { +template +class Vector; +using FlatbufferNamedData = flatbuffers:: + Vector, uint32_t>; +using FlatbufferDataSegment = flatbuffers:: + Vector, uint32_t>; +} // namespace flatbuffers +#endif + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +namespace internal { + +/** + * A NamedDataMap implementation for Flatbuffer-serialized named data + * originating from a PTE file. + */ +class PteDataMap final : public NamedDataMap { + public: + /** + * Creates a new DataMap that wraps named_data from the PTE file. + * + * @param[in] loader The DataLoader that accesses the PTE file. + * Note: the loader must outlive the PteDataMap instance. + * @param[in] segment_base_offset The offset to the first segment in the PTE + * file, in bytes. + * @param[in] named_data The named_data from the PTE file. Note: the pointer + * passed here must outlive the PteDataMap instance. + * @param[in] segments The segments from the PTE file. Note: the pointer + * passed here must outlive the PteDataMap instance. + */ + static Result create( + DataLoader* loader, + size_t segment_base_offset, + const flatbuffers::FlatbufferNamedData* named_data, + const flatbuffers::FlatbufferDataSegment* segments); + + /** + * The PteDataMap currently only handles opaque data that does not contain + * tensor-specific metadata. + */ + ET_NODISCARD + Result get_tensor_layout( + ET_UNUSED std::string_view key) const override { + return Error::NotImplemented; + } + + /** + * Retrieve read-only data for the specified key. + * + * @param[in] key The name of the blob to get data on. + * + * @return error if the key is not present or data cannot be loaded. + */ + ET_NODISCARD + Result get_data(std::string_view key) const override; + + /** + * The PteDataMap currently does not implement load_into. + */ + ET_NODISCARD Error load_data_into( + ET_UNUSED std::string_view key, + ET_UNUSED void* buffer, + ET_UNUSED size_t size) const override { + return Error::NotImplemented; + } + + /** + * @returns The number of keys in the map. + */ + ET_NODISCARD Result get_num_keys() const override; + + /** + * @returns The key at the specified index, error if index out of bounds. + */ + ET_NODISCARD Result get_key(uint32_t index) const override; + + // Moveable, to be compatible with Result. + PteDataMap(PteDataMap&&) noexcept = default; + ~PteDataMap() override = default; + + private: + PteDataMap( + DataLoader* loader, + size_t segment_base_offset, + const flatbuffers::FlatbufferNamedData* named_data, + const flatbuffers::FlatbufferDataSegment* segments) + : loader_(loader), + segment_base_offset_(segment_base_offset), + named_data_(named_data), + segments_(segments) {} + + // Not copyable or assignable. + PteDataMap(const PteDataMap& rhs) = delete; + PteDataMap& operator=(PteDataMap&& rhs) noexcept = delete; + PteDataMap& operator=(const PteDataMap& rhs) = delete; + + // Data loader, used to load segment data. + DataLoader* loader_; + + // The offset to the first segment in the PTE file, in bytes. + size_t segment_base_offset_; + + // Named data, containing name and segment index. + const flatbuffers::FlatbufferNamedData* named_data_; + + // Segments, to retrieve offset and size for the loader. + const flatbuffers::FlatbufferDataSegment* segments_; +}; + +} // namespace internal +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch diff --git a/include/executorch/runtime/executor/tensor_parser.h b/include/executorch/runtime/executor/tensor_parser.h new file mode 100644 index 0000000..55ea23e --- /dev/null +++ b/include/executorch/runtime/executor/tensor_parser.h @@ -0,0 +1,175 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#ifdef __GNUC__ +// Disable -Wdeprecated-declarations, as some builds use 'Werror'. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +#include // @donotremove + +#include +#include +#include +#include +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { +namespace deserialization { + +/// Data structure to hold key and data buffer for external data used +/// in a method. +struct NamedData { + const char* key; + FreeableBuffer buffer; +}; + +NamedData* get_data_by_key(const char* key, Span entries); + +ET_NODISCARD Result parseTensor( + const Program* program, + MemoryManager* memory_manager, + const executorch_flatbuffer::Tensor* s_tensor, + const NamedDataMap* named_data_map = nullptr, + Span external_constants = {}); + +ET_NODISCARD Result> parseTensorList( + const flatbuffers::Vector* tensor_indices, + EValue* values, + size_t values_len, + MemoryManager* memory_manager); + +// Checks that the sizes, dim_order and scalar_type match between tensors +// stored in the PTE and externally. +ET_NODISCARD Error validateTensorLayout( + const executorch_flatbuffer::Tensor* s_tensor, + const TensorLayout& expected_layout); + +// Deserializes a List of optional type. The code here is the same between all +// list of optionals: list of optional Tensor, list of optional float etc, so we +// just use a template to avoid boilerplate. +template +ET_NODISCARD Result>> parseListOptionalType( + const flatbuffers::Vector* value_indices, + EValue* values, + size_t values_len, + MemoryManager* memory_manager) { + auto* evalp_list = memory_manager->method_allocator()->allocateList( + value_indices->size()); + if (evalp_list == nullptr) { + return Error::MemoryAllocationFailed; + } + + auto* optional_tensor_list = + memory_manager->method_allocator()->allocateList>( + value_indices->size()); + if (optional_tensor_list == nullptr) { + return Error::MemoryAllocationFailed; + } + + size_t output_idx = 0; + // For each index look up the corresponding EValue (which has been + // already allocated) and stick it in the list. + for (int32_t index : *value_indices) { + // Lists of objects are stored in fbb as list[int] where the ints are + // indices into values. Currently serialization is deciding if they want to + // put -1 for serialized None type indices, or give us a valid index to a + // serialized None. We support either for now. + // Placement new as the list elements are not initialized, so calling + // copy assignment is not defined if its non trivial. + if (index == -1) { + new (&optional_tensor_list[output_idx]) + std::optional(executorch::aten::nullopt); + // no value to point to. BoxedEvalueList for optional tensor will convert + // this to nullopt. + // TODO(T161156879): do something less hacky here. + evalp_list[output_idx] = nullptr; + } else { + ET_CHECK_OR_RETURN_ERROR( + index >= 0 && static_cast(index) < values_len, + InvalidProgram, + "Invalid value index %" PRId32 " for ListOptional", + index); + auto optional_result = values[index].tryToOptional(); + if (!optional_result.ok()) { + return optional_result.error(); + } + new (&optional_tensor_list[output_idx]) + std::optional(std::move(optional_result.get())); + evalp_list[output_idx] = &values[static_cast(index)]; + } + output_idx++; + } + return BoxedEvalueList>( + evalp_list, optional_tensor_list, value_indices->size()); +} + +// Retrieve the buffer specified by the allocation_info +ET_NODISCARD Result getMemPlannedPtr( + const executorch_flatbuffer::AllocationDetails* allocation_info, + size_t nbytes, + HierarchicalAllocator* allocator); + +/** + * Returns the appropriate data pointer for `s_tensor`. + * + * Overall, a Tensor is either constant or non-constant, except we differentiate + * 2 special variants of non-constant Tensor ("input" and control-flow + * "placeholder") as a special optimization to avoid holding unnecessary + * AllocationDetails. Thus, s_tensor can be configured as 1 of 3 options: + * - constant_buffer > 0, allocation_info = Null: Constant Tensor. + * - constant_buffer = 0, allocation_info = Non Null: Non-constant Tensor. + * - constant_buffer = 0, allocation_info = Null: Input/placeholder Tensor. + * + * @param[in] s_tensor The tensor to find the data pointer for. + * @param[in] program The Program to use for constant buffer data. + * @param[in] nbytes The amount of memory to get from the allocator. + * @param[in] allocator The source of memory for non-constant tensors. + * @param[in] named_data_map An optional map of {name, blob} used to resolve + * data that is mutable and external to the PTE, if any. + * @param[in] external_constants An optional span containing tensor fqn to + * corresponding tensor data. Used to resolve data that is constant and + * external to the PTE, if any. Referencing data from external_constants is + * safe, as it has the same lifetime as the method. + * + * @returns On success, the data pointer to use for the tensor. On failure, a + * non-Ok Error. + */ +ET_NODISCARD Result getTensorDataPtr( + const executorch_flatbuffer::Tensor* s_tensor, + const Program* program, + size_t nbytes, + HierarchicalAllocator* allocator, + const NamedDataMap* named_data_map = nullptr, + Span external_constants = {}); + +} // namespace deserialization +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +namespace deserialization { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::deserialization::getTensorDataPtr; +using ::executorch::ET_RUNTIME_NAMESPACE::deserialization:: + parseListOptionalType; +using ::executorch::ET_RUNTIME_NAMESPACE::deserialization::parseTensor; +using ::executorch::ET_RUNTIME_NAMESPACE::deserialization::parseTensorList; +} // namespace deserialization +} // namespace executor +} // namespace torch + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif diff --git a/include/executorch/runtime/kernel/kernel_includes.h b/include/executorch/runtime/kernel/kernel_includes.h new file mode 100644 index 0000000..7561e2c --- /dev/null +++ b/include/executorch/runtime/kernel/kernel_includes.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * + * Common includes used by all kernel implementations. + */ + +#pragma once + +#include + +// This list should be very conservative since most kernel .cpp files will +// include these and depend on their transitive deps. Only add a header if 99% +// of kernels would have included it anyway. +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export + +#if defined(_MSC_VER) && defined(_MSVC_LANG) && _MSVC_LANG >= 202002L +#define ET_USE_STRUCTURAL_OPERATOR_NAME 1 +namespace executorch { +namespace runtime { + +// MSVC rejects pointers to function-local arrays as template arguments. Copy +// the operator name into a C++20 structural type instead. +template +struct OperatorName { + char value[N]; + + constexpr OperatorName(const char (&name)[N]) : value{} { + for (std::size_t i = 0; i < N; ++i) { + value[i] = name[i]; + } + } + + constexpr operator const char*() const { + return value; + } +}; + +} // namespace runtime +} // namespace executorch + +#define ET_OPERATOR_NAME_TYPE ::executorch::runtime::OperatorName +#define ET_DEFINE_OPERATOR_NAME(variable, name) \ + static constexpr auto variable = ::executorch::runtime::OperatorName { \ + name \ + } +#else +#define ET_USE_STRUCTURAL_OPERATOR_NAME 0 +#define ET_OPERATOR_NAME_TYPE const char* +#define ET_DEFINE_OPERATOR_NAME(variable, name) \ + static constexpr const char variable[] = name +#endif diff --git a/include/executorch/runtime/kernel/kernel_runtime_context.h b/include/executorch/runtime/kernel/kernel_runtime_context.h new file mode 100644 index 0000000..6facecc --- /dev/null +++ b/include/executorch/runtime/kernel/kernel_runtime_context.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { + +/** + * Runtime state and functionality for kernel implementations. + * + * NOTE: Will not be passed to operators if running in ATen mode as those + * operators do not expect to receive a KernelRuntimeContext argument. + */ +class KernelRuntimeContext { + public: + /** + * Construct a new kernel runtime context. + * + * KernelRuntimeContext does not take ownership + * of these pointers, so they must outlive the context instance. + * + * @param[in] event_tracer The optional EventTracer to use for + * profiling/debugging + * @param[in] temp_allocator The optional MemoryAllocator used to allocate + * temporary memory for the kernel. If not provided, an error will be + * returned when calling allocate_temp. + */ + KernelRuntimeContext( + EventTracer* event_tracer = nullptr, + MemoryAllocator* temp_allocator = nullptr) + : event_tracer_(event_tracer), temp_allocator_(temp_allocator) {} + /** + * Tells the runtime that the kernel call has failed. Prefer this over + * ET_CHECK_*(), which fatally panics the process/system. + * + * If this is not called, the runtime will treat the kernel call as + * successful. + * + * This unusual error-propagation path is required because kernel signatures + * do not have a natural way to return errors directly. They are generally + * compatible with core PyTorch ATen kernel signatures, which use exceptions + * to report errors. But, ExecuTorch does not use exceptions. + */ + void fail(Error error) { + failure_state_ = error; + } + + /// Returns the current failure state. + ET_NODISCARD Error failure_state() const { + return failure_state_; + } + + /** + * INTERNAL ONLY + * + * Returns a pointer to an instance of EventTracer to do profiling/debugging + * logging inside the codegen layer. This is only for internal usage inside + * the codegen layer and users should not be accessing this. + */ + EventTracer* internal_event_tracer() { + return event_tracer_; + } + + /** + * Allocates temporary memory that will be freed when the kernel returns. This + * returns a pointer to the allocated memory or an error if the allocation + * fails. + * + * @param[in] size Number of bytes to allocate. + * @param[in] alignment Minimum alignment for the returned pointer. Must be a + * power of 2. + * + * @returns A result object containing either a pointer to the allocated + * memory or an error to indicate failure + */ + Result allocate_temp( + size_t size, + size_t alignment = MemoryAllocator::kDefaultAlignment) { + ET_CHECK_OR_RETURN_ERROR( + temp_allocator_ != nullptr, NotFound, "No temp allocator provided"); + void* temp_memory = temp_allocator_->allocate(size, alignment); + ET_CHECK_OR_RETURN_ERROR( + temp_memory != nullptr, + MemoryAllocationFailed, + "Failed to allocate temp memory. Bytes requested: %zu", + size); + return temp_memory; + } + + // TODO(T147221312): Add a way to resize a tensor. + + private: + EventTracer* event_tracer_ = nullptr; + MemoryAllocator* temp_allocator_ = nullptr; + Error failure_state_ = Error::Ok; +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +namespace torch { +namespace executor { +/// DEPRECATED: Use ::executorch::runtime::KernelRuntimeContext instead. +using ::executorch::ET_RUNTIME_NAMESPACE::KernelRuntimeContext; +/// DEPRECATED: Use ::executorch::runtime::KernelRuntimeContext instead. +using RuntimeContext = ::executorch::ET_RUNTIME_NAMESPACE::KernelRuntimeContext; +} // namespace executor +} // namespace torch +namespace executorch { +namespace aten { +/// DEPRECATED: Use ::executorch::runtime::KernelRuntimeContext instead. +using RuntimeContext = ::executorch::ET_RUNTIME_NAMESPACE::KernelRuntimeContext; +} // namespace aten +} // namespace executorch +// DEPRECATED: The executorch::aten:: namespace is deprecated. Use +// executorch::aten:: instead. +namespace exec_aten = ::executorch::aten; diff --git a/include/executorch/runtime/kernel/operator_registry.h b/include/executorch/runtime/kernel/operator_registry.h new file mode 100644 index 0000000..4f69bb7 --- /dev/null +++ b/include/executorch/runtime/kernel/operator_registry.h @@ -0,0 +1,308 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +// Debug switch for operator registry +#if defined(ET_OP_REGISTRY_DEBUG) +#include +#endif + +#define ET_LOG_KERNEL_KEY(k) \ + ET_LOG( \ + Info, \ + "key: %s, is_fallback: %s", \ + k.data(), \ + k.is_fallback() ? "true" : "false"); +#define ET_LOG_TENSOR_META(meta_list) \ + for (const auto& meta : meta_list) { \ + ET_LOG(Info, "dtype: %d | dim order: [", int(meta.dtype_)); \ + for (size_t i = 0; i < meta.dim_order_.size(); i++) { \ + ET_LOG(Info, "%d,", static_cast(meta.dim_order_[i])); \ + } \ + ET_LOG(Info, "]"); \ + } + +namespace executorch { +namespace ET_RUNTIME_NAMESPACE { + +class KernelRuntimeContext; // Forward declaration +using OpFunction = void (*)(KernelRuntimeContext&, Span); + +/** + * Dtype and dim order metadata for a Tensor argument to an operator. + * Used by the Executor to hold the tensor metadata info and retrieve kernel. + */ +struct TensorMeta { + executorch::aten::ScalarType dtype_; + Span dim_order_; + + TensorMeta() = default; + TensorMeta( + executorch::aten::ScalarType dtype, + Span order) + : dtype_(dtype), dim_order_(order) {} + + bool operator==(const TensorMeta& other) const { + return this->equals(other); + } + + bool operator!=(const TensorMeta& other) const { + return !this->equals(other); + } + + bool equals(const TensorMeta& other) const { + if (dtype_ != other.dtype_) { + return false; + } + if (dim_order_.size() != other.dim_order_.size()) { + return false; + } + for (size_t i = 0; i < dim_order_.size(); i++) { + if (dim_order_[i] != other.dim_order_[i]) { + return false; + } + } + return true; + } + +#if defined(ET_OP_REGISTRY_DEBUG) + friend std::ostream& operator<<(std::ostream& os, const TensorMeta& meta) { + os << "dtype: " << int(meta.dtype_) << " | dim order: ["; + for (int i = 0; i < meta.dim_order_.size(); i++) { + os << static_cast(meta.dim_order_[i]) << ", "; + } + os << "]"; + return os; + } +#endif +}; + +/** + * Describes which dtype & dim order specialized kernel to be bound to an + * operator. + * + * Kernel key data is a string with the format: + * + * "v/|..." + * + * The version is v1 for now. If the kernel key format changes, update the + * version to avoid breaking pre-existing kernel keys. + * + * Each tensor_meta has the following format: ";" + * + * Example kernel key data: "v1/7;0,1,2,3|1;0,1,2,3,4,5,6,7" + * + * This has two tensors: the first with dtype=7 and dim order 0,1,2,3, and the + * second with dtype=1 and dim order 0,1,2,3,4,5,6,7. + * + * IMPORTANT: + * Users should not construct a kernel key manually. Instead, it should be + * generated from kernel yaml. + */ +struct KernelKey { + public: + /** + * Creates a fallback (non-specialized) kernel key: this kernel can be used + * for all input tensor dtypes and dim orders if the specialized kernel is not + * registered. + */ + constexpr KernelKey() = default; + + /** + * Creates a specialized (non-fallback) kernel key that matches a specific + * set of input tensor dtypes and dim orders. See the class comment for the + * expected format of `kernel_key_data`. + */ + /* implicit */ constexpr KernelKey(const char* kernel_key_data) + : kernel_key_data_(kernel_key_data) {} + + bool operator==(const KernelKey& other) const { + return this->equals(other); + } + + bool operator!=(const KernelKey& other) const { + return !this->equals(other); + } + + bool equals(const KernelKey& other) const { + if (is_fallback() != other.is_fallback()) { + return false; + } + if (is_fallback()) { + return true; + } + return strcmp(kernel_key_data_, other.kernel_key_data_) == 0; + } + + bool is_fallback() const { + return kernel_key_data_ == nullptr; + } + + const char* data() const { + return kernel_key_data_; + } + +#if defined(ET_OP_REGISTRY_DEBUG) + friend std::ostream& operator<<(std::ostream& os, const KernelKey& key) { + os << key.kernel_key_data_ << std::endl; + return os; + } +#endif + + private: + const char* kernel_key_data_ = nullptr; +}; + +/** + * Struct that bundles a kernel key, a function and an op name together. An + * `Operator` may have more than one `Kernel` (maximum kMaxNumOfKernelPerOp) and + * they should have the same op name and different kernel key. A "fallback" + * kernel may or may not live in an `Operator`. + */ +struct Kernel { + const char* name_; + // String representation of kernel key, with the same format as + // KernelKey.to_string_representation() + // Data is not owned by the Kernel struct. + KernelKey kernel_key_; + OpFunction op_; + /** + * We are doing a copy of the string pointer instead of duplicating the string + * itself, we require the lifetime of the operator name to be at least as long + * as the operator registry. + */ + constexpr explicit Kernel(const char* name, OpFunction func) + : name_(name), op_(func) {} + + constexpr explicit Kernel(const char* name, KernelKey key, OpFunction func) + : name_(name), kernel_key_(key), op_(func) {} + + constexpr Kernel() : name_(nullptr), op_(nullptr) {} +}; + +namespace internal { + +/** + * A make_kernel_key_string buffer size that is large enough to hold a kernel + * key string with 16 tensors of 16 dimensions, plus the trailing NUL byte. + */ +constexpr size_t kKernelKeyBufSize = 659; + +/** + * Given the list of input tensor dtypes + dim orders, writes the kernel key + * string into the buffer. Returns an error if the buffer is too small or if the + * tensors cannot be represented as a valid key string. + */ +Error make_kernel_key_string( + Span key, + char* buf, + size_t buf_size); + +} // namespace internal + +/** + * Checks whether an operator exists with a given name and TensorMeta list. When + * TensorMeta is empty, it means this op does not have specialized kernels, so + * it checks whether it has any fallback kernels. + */ +bool registry_has_op_function( + const char* name, + Span meta_list = {}); + +/** + * Returns the operator with a given name and TensorMeta list, if present. + */ +::executorch::runtime::Result get_op_function_from_registry( + const char* name, + Span meta_list = {}); + +/** + * Returns the operator with a given name and TensorMeta list from the provided + * kernel list instead of the global registry. + */ +::executorch::runtime::Result get_op_function_from_registry( + const char* name, + Span meta_list, + Span kernel_list); + +/** + * Returns all registered kernels. + */ +Span get_registered_kernels(); + +/** + * Registers the provided kernels. + * + * @param[in] kernels Kernel objects to register. + * @retval Error::Ok always. Panics on error. This function needs to return a + * non-void type to run at static initialization time. + */ +ET_NODISCARD Error register_kernels(const Span); + +/** + * Registers a single kernel. + * + * @param[in] kernel Kernel object to register. + * @retval Error::Ok always. Panics on error. This function needs to return a + * non-void type to run at static initialization time. + */ +ET_NODISCARD inline Error register_kernel(const Kernel& kernel) { + return register_kernels({&kernel, 1}); +}; + +} // namespace ET_RUNTIME_NAMESPACE +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::ET_RUNTIME_NAMESPACE::Kernel; +using ::executorch::ET_RUNTIME_NAMESPACE::KernelKey; +using ::executorch::ET_RUNTIME_NAMESPACE::KernelRuntimeContext; +using ::executorch::ET_RUNTIME_NAMESPACE::OpFunction; +using ::executorch::ET_RUNTIME_NAMESPACE::TensorMeta; +using KernelRuntimeContext = + ::executorch::ET_RUNTIME_NAMESPACE::KernelRuntimeContext; + +inline ::executorch::runtime::Error register_kernels(ArrayRef kernels) { + return ::executorch::ET_RUNTIME_NAMESPACE::register_kernels( + {kernels.data(), kernels.size()}); +} +inline OpFunction getOpsFn( + const char* name, + ArrayRef meta_list = {}) { + auto result = + ::executorch::ET_RUNTIME_NAMESPACE::get_op_function_from_registry( + name, {meta_list.data(), meta_list.size()}); + ET_CHECK(result.ok()); // get_op_function_from_registry() logs details. + return *result; +} +inline bool hasOpsFn(const char* name, ArrayRef meta_list = {}) { + return ::executorch::ET_RUNTIME_NAMESPACE::registry_has_op_function( + name, {meta_list.data(), meta_list.size()}); +} +inline ArrayRef get_kernels() { + Span kernels = + ::executorch::ET_RUNTIME_NAMESPACE::get_registered_kernels(); + return ArrayRef(kernels.data(), kernels.size()); +} +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/kernel/thread_parallel_interface.h b/include/executorch/runtime/kernel/thread_parallel_interface.h new file mode 100644 index 0000000..61cbdbb --- /dev/null +++ b/include/executorch/runtime/kernel/thread_parallel_interface.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace executorch { +namespace extension { +namespace internal { +template +inline bool parallel_for_no_threadpool( + const int64_t begin, + const int64_t end, + const int64_t grain_size, + const Func& f) { + ET_CHECK_OR_RETURN_FALSE( + begin >= 0 && end >= 0 && end >= begin, + "begin = %" PRId64 ", end = %" PRId64, + begin, + end); + ET_CHECK_OR_RETURN_FALSE(grain_size > 0, "grain_size = %" PRId64, grain_size); + // An empty range runs no work items, so the callback is not invoked. Checked + // here rather than only in the release branch below: the debug branch skips + // it as a side effect of iterating an empty range, and relying on that made + // the two branches disagree. + if (begin == end) { + return true; + } +#ifndef NDEBUG + // Go backwards through the range elementwise to catch code that + // assumes parallel_for is in order like a regular for loop. + for (const auto i : c10::irange(begin, end)) { + const auto offset = i - begin; + const auto idx = end - offset - 1; + f(idx, idx + 1); + } +#else // NDEBUG + f(begin, end); +#endif + return true; +} + +// Match GRAIN_SIZE from PyTorch core. +// https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/TensorIterator.h#L78 +constexpr int64_t GRAIN_SIZE = 32768; +} // namespace internal + +#ifdef ET_USE_THREADPOOL +/** + * A helper to run a function in parallel. + * + * begin, end: describe the extent of the workitems via first and last workitem + * to be processed + * grain_size: number of workitems processed by user callback which is + * described below + * f: user function applied in parallel to the chunks, signature: + * void f(int64_t begin, int64_t end) + * Returns true if all work items are processed successfully, false otherwise + * + * Warning: parallel_for does NOT copy thread local states from the current + * thread to the worker threads. Users need to protect the access to captured + * data if they mutate them in f. + */ +bool parallel_for( + const int64_t begin, + const int64_t end, + const int64_t grain_size, + runtime::FunctionRef f); + +/** Returns the number of threads available to parallel_for. */ +int64_t get_thread_count(); + +int64_t get_thread_num(); + +void set_thread_num(int64_t thread_num); +#else // ET_USE_THREADPOOL +template +bool parallel_for( + const int64_t begin, + const int64_t end, + const int64_t grain_size, + const Func& func) { + return internal::parallel_for_no_threadpool(begin, end, grain_size, func); +} + +inline int64_t get_thread_num() { + return 0; +} + +inline int64_t get_thread_count() { + return 1; +} + +inline void set_thread_num(int64_t thread_num) { + ET_DCHECK_MSG(false, "cannot set_thread_num without threading support!"); +} +#endif // ET_USE_THREADPOOL +} // namespace extension +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::extension::get_thread_num; +using ::executorch::extension::parallel_for; +using ::executorch::extension::set_thread_num; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/platform/abort.h b/include/executorch/runtime/platform/abort.h new file mode 100644 index 0000000..ae1a761 --- /dev/null +++ b/include/executorch/runtime/platform/abort.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * ExecuTorch global abort wrapper function. + */ + +#pragma once + +#include + +namespace executorch { +namespace runtime { + +/** + * Trigger the ExecuTorch global runtime to immediately exit without cleaning + * up, and set an abnormal exit status (platform-defined). + */ +ET_NORETURN void runtime_abort(); + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::runtime_abort; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/platform/assert.h b/include/executorch/runtime/platform/assert.h new file mode 100644 index 0000000..c8c189d --- /dev/null +++ b/include/executorch/runtime/platform/assert.h @@ -0,0 +1,124 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include + +/** + * Assertion failure message emit method. + * + * @param[in] _format Printf-style message format string. + * @param[in] ... Format string arguments. + */ +#define ET_ASSERT_MESSAGE_EMIT(_format, ...) \ + ET_LOG( \ + Fatal, \ + "In function %s(), assert failed" _format, \ + ET_FUNCTION, \ + ##__VA_ARGS__) + +/** + * Abort the runtime if the condition is not true. + * This check will be performed even in release builds. + * + * @param[in] _cond Condition asserted as true. + * @param[in] _format Printf-style message format string. + * @param[in] ... Format string arguments. + */ +#define ET_CHECK_MSG(_cond, _format, ...) \ + do { \ + if ET_UNLIKELY (!(_cond)) { \ + ET_ASSERT_MESSAGE_EMIT(" (%s): " _format, #_cond, ##__VA_ARGS__); \ + ::executorch::runtime::runtime_abort(); \ + } \ + } while (0) + +/** + * Abort the runtime if the condition is not true. + * This check will be performed even in release builds. + * + * @param[in] _cond Condition asserted as true. + */ +#define ET_CHECK(_cond) \ + do { \ + if ET_UNLIKELY (!(_cond)) { \ + ET_ASSERT_MESSAGE_EMIT(": %s", #_cond); \ + ::executorch::runtime::runtime_abort(); \ + } \ + } while (0) + +#ifdef NDEBUG + +/** + * Abort the runtime if the condition is not true. + * This check will be performed in debug builds, but not release builds. + * + * @param[in] _cond Condition asserted as true. + * @param[in] _format Printf-style message format string. + * @param[in] ... Format string arguments. + */ +#define ET_DCHECK_MSG(_cond, _format, ...) ((void)0) + +/** + * Abort the runtime if the condition is not true. + * This check will be performed in debug builds, but not release builds. + * + * @param[in] _cond Condition asserted as true. + */ +#define ET_DCHECK(_cond) ((void)0) +#define ET_DEBUG_ONLY [[maybe_unused]] + +#else // NDEBUG + +/** + * Abort the runtime if the condition is not true. + * This check will be performed in debug builds, but not release builds. + * + * @param[in] _cond Condition asserted as true. + * @param[in] _format Printf-style message format string. + * @param[in] ... Format string arguments. + */ +#define ET_DCHECK_MSG(_cond, _format, ...) \ + ET_CHECK_MSG(_cond, _format, ##__VA_ARGS__) + +/** + * Abort the runtime if the condition is not true. + * This check will be performed in debug builds, but not release builds. + * + * @param[in] _cond Condition asserted as true. + */ +#define ET_DCHECK(_cond) ET_CHECK(_cond) +#define ET_DEBUG_ONLY + +#endif // NDEBUG + +/** + * Assert that this code location is unreachable during execution. + */ +#define ET_ASSERT_UNREACHABLE() \ + do { \ + ET_CHECK_MSG(false, "Execution should not reach this point"); \ + ET_UNREACHABLE(); \ + } while (0) + +/** + * Assert that this code location is unreachable during execution. + * + * @param[in] _message Message on how to avoid this assertion error. + */ +#define ET_ASSERT_UNREACHABLE_MSG(_format, ...) \ + do { \ + ET_CHECK_MSG( \ + false, \ + "Execution should not reach this point. " _format, \ + ##__VA_ARGS__); \ + ET_UNREACHABLE(); \ + } while (0) diff --git a/include/executorch/runtime/platform/clock.h b/include/executorch/runtime/platform/clock.h new file mode 100644 index 0000000..36c25d9 --- /dev/null +++ b/include/executorch/runtime/platform/clock.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * Clock and timing related methods. + */ + +#pragma once + +#include + +namespace executorch { +namespace runtime { + +/** + * Convert an interval from units of system ticks to nanoseconds. + * The conversion ratio is platform-dependent, and thus depends on + * the platform implementation of et_pal_ticks_to_ns_multiplier(). + * + * @param[in] ticks The interval length in system ticks. + * @retval The interval length in nanoseconds. + */ +inline uint64_t ticks_to_ns(et_timestamp_t ticks) { + et_tick_ratio_t ratio = et_pal_ticks_to_ns_multiplier(); + return static_cast(ticks) * ratio.numerator / ratio.denominator; +} + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::ticks_to_ns; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/platform/compat_unistd.h b/include/executorch/runtime/platform/compat_unistd.h new file mode 100644 index 0000000..c8bc486 --- /dev/null +++ b/include/executorch/runtime/platform/compat_unistd.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * unistd.h related macros for POSIX/Windows compatibility. + */ +#pragma once + +#if defined(_WIN32) && !defined(_WIN64) +#error \ + "You're trying to build ExecuTorch with a too old version of Windows. We need Windows 64-bit." +#endif + +#if !defined(_WIN64) +#include +#else +#include +#define O_RDONLY _O_RDONLY +#define open _open +#define close _close +#define read _read +#define write _write +#define stat _stat64 +#define fstat _fstat64 +#define off_t _off_t +#define lseek _lseeki64 + +#include // For ssize_t. +#include +// To avoid conflicts with std::numeric_limits::max() in +// file_data_loader.cpp. +#undef max + +inline ssize_t pread(int fd, void* buf, size_t nbytes, size_t offset) { + OVERLAPPED overlapped; /* The offset for ReadFile. */ + memset(&overlapped, 0, sizeof(overlapped)); + overlapped.Offset = offset; + overlapped.OffsetHigh = offset >> 32; + + BOOL result; /* The result of ReadFile. */ + DWORD bytes_read; /* The number of bytes read. */ + HANDLE file = (HANDLE)_get_osfhandle(fd); + + result = ReadFile(file, buf, nbytes, &bytes_read, &overlapped); + DWORD error = GetLastError(); + if (!result) { + if (error == ERROR_IO_PENDING) { + result = GetOverlappedResult(file, &overlapped, &bytes_read, TRUE); + if (!result) { + error = GetLastError(); + } + } + } + if (!result) { + // Translate error into errno. + switch (error) { + case ERROR_HANDLE_EOF: + errno = 0; + break; + default: + errno = EIO; + break; + } + return -1; + } + return bytes_read; +} + +#endif // !defined(_WIN64) \ No newline at end of file diff --git a/include/executorch/runtime/platform/compiler.h b/include/executorch/runtime/platform/compiler.h new file mode 100644 index 0000000..5109671 --- /dev/null +++ b/include/executorch/runtime/platform/compiler.h @@ -0,0 +1,254 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * Compiler utility macros. + */ + +#pragma once + +/* + * Compiler support checks. Follows the logic used by pytorch/c10/util/C++17.h + * but may support older versions. + */ + +// https://gcc.gnu.org/projects/cxx-status.html#cxx17 +#if !defined(__clang__) && !defined(_MSC_VER) && defined(__GNUC__) && \ + __GNUC__ < 7 +#error \ + "You're trying to build ExecuTorch with a too old version of GCC. We need GCC 7 or later." +#endif + +// https://clang.llvm.org/cxx_status.html#cxx17 +#if defined(__clang__) && __clang_major__ < 5 +#error \ + "You're trying to build ExecuTorch with a too old version of Clang. We need Clang 5 or later." +#endif + +#if (defined(_MSC_VER) && (!defined(_MSVC_LANG) || _MSVC_LANG < 201703L)) || \ + (!defined(_MSC_VER) && __cplusplus < 201703L) +#error "You need C++17 to compile ExecuTorch" +#endif + +#if defined(_MSC_VER) && (defined(min) || defined(max)) +#error \ + "Macro clash with min and max -- define NOMINMAX when compiling your program on Windows" +#endif + +// The prebuilt Windows package defines ET_PREBUILT_RELEASE_CRT or +// ET_PREBUILT_DEBUG_CRT, after the C++ library its DLLs were built with. A +// program built with the other one (/MDd and /MTd define _DEBUG, /MD and /MT do +// not) sees differently laid out types: the two mixed in one process corrupt +// memory instead of failing to link. +#if defined(ET_PREBUILT_RELEASE_CRT) && defined(_DEBUG) +#error \ + "The prebuilt ExecuTorch DLLs use the release C++ library; build this program as Release (configure with -DCMAKE_BUILD_TYPE=Release, or build with --config Release under a multi-config generator such as Visual Studio)" +#endif +#if defined(ET_PREBUILT_DEBUG_CRT) && !defined(_DEBUG) +#error \ + "The prebuilt ExecuTorch DLLs use the debug C++ library; build this program as Debug (configure with -DCMAKE_BUILD_TYPE=Debug, or build with --config Debug under a multi-config generator such as Visual Studio)" +#endif +// The same configuration can still change the layout: an explicit +// _ITERATOR_DEBUG_LEVEL adds checking members to the standard containers. The +// DLLs use the default for their library, 0 for release and 2 for debug, and +// only a value set by the program (with /D, before any standard header) can +// differ, since the library's own default is not defined yet at this point. +#if defined(ET_PREBUILT_RELEASE_CRT) && defined(_ITERATOR_DEBUG_LEVEL) && \ + _ITERATOR_DEBUG_LEVEL != 0 +#error \ + "The prebuilt ExecuTorch DLLs use _ITERATOR_DEBUG_LEVEL=0; do not set it for this program" +#endif +#if defined(ET_PREBUILT_DEBUG_CRT) && defined(_ITERATOR_DEBUG_LEVEL) && \ + _ITERATOR_DEBUG_LEVEL != 2 +#error \ + "The prebuilt ExecuTorch DLLs use _ITERATOR_DEBUG_LEVEL=2; do not set it for this program" +#endif + +/* + * Define annotations aliasing C++ declaration attributes. + * See all C++ declaration attributes here: + * https://en.cppreference.com/w/cpp/language/attributes + * + * Note that ExecuTorch supports a lower C++ standard version than all standard + * attributes. Therefore, some annotations are defined using their Clang/GNU + * counterparts. + * + * GNU attribute definitions: + * https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html + */ + +#define ET_NORETURN [[noreturn]] + +// Inline/NoInline +#if defined(_MSC_VER) +#define ET_NOINLINE __declspec(noinline) +#define ET_INLINE __forceinline +#else +#define ET_NOINLINE __attribute__((noinline)) +#define ET_INLINE __attribute__((always_inline)) inline +#endif + +// Restrict +#if defined(_MSC_VER) +#define ET_RESTRICT __restrict +#else +#define ET_RESTRICT __restrict__ +#endif + +#if defined(__GNUC__) + +#define ET_UNREACHABLE() __builtin_unreachable() + +#elif defined(_MSC_VER) + +#define ET_UNREACHABLE() __assume(0) + +#else // defined(__GNUC__) + +#define ET_UNREACHABLE() \ + while (1) \ + ; + +#endif // defined(__GNUC__) + +#define ET_DEPRECATED [[deprecated]] +#define ET_EXPERIMENTAL \ + [[deprecated("This API is experimental and may change without notice.")]] +#define ET_FALLTHROUGH [[fallthrough]] +#define ET_NODISCARD [[nodiscard]] +#define ET_UNUSED [[maybe_unused]] + +// UNLIKELY Macro +// example +// if ET_UNLIKELY(a > 10 && b < 5) { +// do something +// } +#if (__cplusplus) >= 202002L + +#define ET_LIKELY(expr) (expr) [[likely]] +#define ET_UNLIKELY(expr) (expr) [[unlikely]] + +#else + +#define ET_LIKELY(expr) (expr) +#define ET_UNLIKELY(expr) (expr) + +#endif // (__cplusplus) >= 202002L + +/// Define a C symbol with weak linkage. +#ifdef _MSC_VER +// There currently doesn't seem to be a great way to do this in Windows and +// given that weak linkage is not really critical on Windows, we'll just leave +// it as a stub. +#define ET_WEAK +#else +#define ET_WEAK __attribute__((weak)) +#endif + +/** + * Annotation marking a function as printf-like, providing compiler support + * for format string argument checking. + */ +#ifdef _MSC_VER +#include +#define ET_PRINTFLIKE(_string_index, _va_index) _Printf_format_string_ +#else +#define ET_PRINTFLIKE(_string_index, _va_index) \ + __attribute__((format(printf, _string_index, _va_index))) +#endif + +#ifndef __has_builtin +#define __has_builtin(x) (0) +#endif + +#if defined(__FILE_NAME__) +/// __FILE_NAME__ provides just the filename at +/// compile time, avoiding embedding full paths in the binary +#define ET_SHORT_FILENAME __FILE_NAME__ +#elif __has_builtin(__builtin_strrchr) +/// Name of the source file without a directory string. +/// Note: This approach embeds the full path in .rodata even though only the +/// basename is used at runtime. __FILE_NAME__ is preferred when available. +#define ET_SHORT_FILENAME (__builtin_strrchr("/" __FILE__, '/') + 1) +#else +#define ET_SHORT_FILENAME __FILE__ +#endif + +#if __has_builtin(__builtin_LINE) +/// Current line as an integer. +#define ET_LINE __builtin_LINE() +#else +#define ET_LINE __LINE__ +#endif // __has_builtin(__builtin_LINE) + +#if defined(ET_USE_BUILTIN_FUNCTION_NAME) && ET_USE_BUILTIN_FUNCTION_NAME == 0 +/// __FUNCTION__ provides a short undecorated name, saving .rodata space +/// compared to __builtin_FUNCTION() which includes the full signature +/// (namespace, parameters, return type). +#define ET_FUNCTION __FUNCTION__ +#elif __has_builtin(__builtin_FUNCTION) +/// Name of the current function as a const char[]. +#define ET_FUNCTION __builtin_FUNCTION() +#else +#define ET_FUNCTION __FUNCTION__ +#endif + +// As of G3 RJ-2024.3 toolchain, zu format specifier is not supported for Xtensa +#if defined(__XTENSA__) +#define ET_PRIsize_t "u" +#define ET_PRIssize_t "d" +#else +#define ET_PRIsize_t "zu" +#define ET_PRIssize_t "zd" +#endif + +// Whether the compiler supports GNU statement expressions. +// https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html +#ifndef ET_HAVE_GNU_STATEMENT_EXPRESSIONS +#if (defined(__GNUC__) && __GNUC__ >= 3) || defined(__clang__) +#define ET_HAVE_GNU_STATEMENT_EXPRESSIONS 1 +#else +#define ET_HAVE_GNU_STATEMENT_EXPRESSIONS 0 +#endif +#endif // ifndef + +// Define size_t and ssize_t. +#ifndef _MSC_VER +#include +#else +#include +using ssize_t = ptrdiff_t; +#endif + +#ifdef __EXCEPTIONS +#define ET_HAS_EXCEPTIONS 1 +#elif defined(_MSC_VER) && defined(_HAS_EXCEPTIONS) && _HAS_EXCEPTIONS +#define ET_HAS_EXCEPTIONS 1 +#else +#define ET_HAS_EXCEPTIONS 0 +#endif + +// DEPRECATED: Use the non-underscore-prefixed versions instead. +// TODO(T199005537): Remove these once all users have stopped using them. +#define __ET_DEPRECATED ET_DEPRECATED +#define __ET_FALLTHROUGH ET_FALLTHROUGH +#define __ET_FUNCTION ET_FUNCTION +#define __ET_HAVE_GNU_STATEMENT_EXPRESSIONS ET_HAVE_GNU_STATEMENT_EXPRESSIONS +#define __ET_INLINE ET_INLINE +#define __ET_LIKELY ET_LIKELY +#define __ET_LINE ET_LINE +#define __ET_NODISCARD ET_NODISCARD +#define __ET_NOINLINE ET_NOINLINE +#define __ET_NORETURN ET_NORETURN +#define __ET_PRINTFLIKE ET_PRINTFLIKE +#define __ET_SHORT_FILENAME ET_SHORT_FILENAME +#define __ET_UNLIKELY ET_UNLIKELY +#define __ET_UNREACHABLE ET_UNREACHABLE +#define __ET_UNUSED ET_UNUSED +#define __ET_WEAK ET_WEAK diff --git a/include/executorch/runtime/platform/log.h b/include/executorch/runtime/platform/log.h new file mode 100644 index 0000000..7293fa2 --- /dev/null +++ b/include/executorch/runtime/platform/log.h @@ -0,0 +1,216 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * ExecuTorch logging API. + */ + +#pragma once + +#include +#include +#include + +#include +#include + +// Set minimum log severity if compiler option is not provided. +#ifndef ET_MIN_LOG_LEVEL +#define ET_MIN_LOG_LEVEL Info +#endif // !defined(ET_MIN_LOG_LEVEL) + +/* + * Enable logging by default if compiler option is not provided. + * This should facilitate less confusion for those developing ExecuTorch. + */ +#ifndef ET_LOG_ENABLED +#define ET_LOG_ENABLED 1 +#endif // !defined(ET_LOG_ENABLED) + +// Even though it is supposed to be "portable" some toolchains +// do not define, so providing a definition here +#ifndef PRIu64 +#define PRIu64 "llu" +#endif +#ifndef PRId64 +#define PRId64 "lld" +#endif + +namespace executorch { +namespace runtime { + +/** + * Severity level of a log message. Must be ordered from lowest to highest + * severity. + */ +enum class LogLevel : uint8_t { + /** + * Log messages provided for highly granular debuggability. + * + * Log messages using this severity are unlikely to be compiled by default + * into most debug builds. + */ + Debug, + + /** + * Log messages providing information about the state of the system + * for debuggability. + */ + Info, + + /** + * Log messages about errors within ExecuTorch during runtime. + */ + Error, + + /** + * Log messages that precede a fatal error. However, logging at this level + * does not perform the actual abort, something else needs to. + */ + Fatal, + + /** + * Number of supported log levels, with values in [0, NumLevels). + */ + NumLevels, +}; + +namespace internal { + +/** + * Get the current timestamp to construct a log event. + * + * @retval Monotonically non-decreasing timestamp in system ticks. + */ +et_timestamp_t get_log_timestamp(); + +/** + * Log a string message. + * + * Note: This is an internal function. Use the `ET_LOG` macro instead. + * + * @param[in] level Log severity level. + * @param[in] timestamp Timestamp (in system ticks) of the log event. + * @param[in] filename Name of the source file creating the log event. + * @param[in] function Name of the function creating the log event. + * @param[in] line Source file line of the caller. + * @param[in] format Format string. + * @param[in] args Variable argument list. + */ +ET_PRINTFLIKE(6, 0) +void vlogf( + LogLevel level, + et_timestamp_t timestamp, + const char* filename, + const char* function, + size_t line, + const char* format, + va_list args); + +/** + * Log a string message. + * + * Note: This is an internal function. Use the `ET_LOG` macro instead. + * + * @param[in] level Log severity level. + * @param[in] timestamp Timestamp (in system ticks) of the log event. + * @param[in] filename Name of the source file creating the log event. + * @param[in] function Name of the function creating the log event. + * @param[in] line Source file line of the caller. + * @param[in] format Format string. + */ +ET_PRINTFLIKE(6, 7) +inline void logf( + LogLevel level, + et_timestamp_t timestamp, + const char* filename, + const char* function, + size_t line, + const char* format, + ...) { +#if ET_LOG_ENABLED + va_list args; + va_start(args, format); + internal::vlogf(level, timestamp, filename, function, line, format, args); + va_end(args); +#endif // ET_LOG_ENABLED +} + +} // namespace internal + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::LogLevel; +} // namespace executor +} // namespace torch + +#if ET_LOG_ENABLED + +/** + * Log a message at the given log severity level. + * + * @param[in] _level Log severity level. + * @param[in] _format Log message format string. + */ +#define ET_LOG(_level, _format, ...) \ + do { \ + const auto _log_level = ::executorch::runtime::LogLevel::_level; \ + if (static_cast(_log_level) >= \ + static_cast( \ + ::executorch::runtime::LogLevel::ET_MIN_LOG_LEVEL)) { \ + const auto _timestamp = \ + ::executorch::runtime::internal::get_log_timestamp(); \ + ::executorch::runtime::internal::logf( \ + _log_level, \ + _timestamp, \ + ET_SHORT_FILENAME, \ + ET_FUNCTION, \ + ET_LINE, \ + _format, \ + ##__VA_ARGS__); \ + } \ + } while (0) + +/** + * Check a condition and log an error message if the condition is false. + * + * @param[in] _condition The condition to check. + * @param[in] _format Log message format string. + */ +#define ET_CHECK_OR_LOG_ERROR(_condition, _format, ...) \ + do { \ + if (!(_condition)) { \ + ET_LOG(Error, _format, ##__VA_ARGS__); \ + } \ + } while (0) + +#else // ET_LOG_ENABLED + +/** + * Log a message at the given log severity level. + * + * @param[in] _level Log severity level. + * @param[in] _format Log message format string. + */ +#define ET_LOG(_level, _format, ...) ((void)0) + +/** + * Check a condition and log an error message if the condition is false. + * + * @param[in] _condition The condition to check. + * @param[in] _format Log message format string. + */ +#define ET_CHECK_OR_LOG_ERROR(_condition, _format, ...) ((void)0) + +#endif // ET_LOG_ENABLED diff --git a/include/executorch/runtime/platform/platform.h b/include/executorch/runtime/platform/platform.h new file mode 100644 index 0000000..7235305 --- /dev/null +++ b/include/executorch/runtime/platform/platform.h @@ -0,0 +1,276 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * Platform abstraction layer to allow individual platform libraries to override + * symbols in ExecuTorch. PAL functions are defined as C functions so a platform + * library implementer can use C in lieu of C++. + * + * The et_pal_ methods should not be called directly. Use the corresponding + * methods in the executorch::runtime namespace instead to appropriately + * dispatch through the PAL function table. + */ + +#pragma once + +// Use C-style includes so that C code can include this header. +#include +#include + +#include +#include + +/** + * Clients should neither define nor use this macro. Used to optionally declare + * the et_pal_*() functions as weak symbols. + * + * This provides a way to both: + * - Include the header and define weak symbols (used by the internal default + * implementations) + * - Include the header and define strong symbols (used by client overrides) + */ +#ifndef ET_INTERNAL_PLATFORM_WEAKNESS +#define ET_INTERNAL_PLATFORM_WEAKNESS +#endif + +extern "C" { + +/** + * Represents the conversion ratio from system ticks to nanoseconds. + * To convert, use nanoseconds = ticks * numerator / denominator. + */ +typedef struct { + uint64_t numerator; + uint64_t denominator; +} et_tick_ratio_t; + +/** + * Initialize the platform abstraction layer. + * + * This function should be called before any other function provided by the PAL + * to initialize any global state. Typically overridden by PAL implementer. + */ +void et_pal_init(void) ET_INTERNAL_PLATFORM_WEAKNESS; +using pal_init_method = void (*)(); + +/** + * Immediately abort execution, setting the device into an error state, if + * available. + */ +ET_NORETURN void et_pal_abort(void) ET_INTERNAL_PLATFORM_WEAKNESS; +using pal_abort_method = void (*)(); + +/** + * Return a monotonically non-decreasing timestamp in system ticks. + * + * @retval Timestamp value in system ticks. + */ +et_timestamp_t et_pal_current_ticks(void) ET_INTERNAL_PLATFORM_WEAKNESS; +typedef et_timestamp_t (*et_pal_current_ticks_t)(void); +using pal_current_ticks_method = et_timestamp_t (*)(); + +/** + * Return the conversion rate from system ticks to nanoseconds as a fraction. + * To convert a system ticks to nanoseconds, multiply the tick count by the + * numerator and then divide by the denominator: + * nanoseconds = ticks * numerator / denominator + * + * The utility method executorch::runtime::ticks_to_ns(et_timestamp_t) can also + * be used to perform the conversion for a given tick count. It is defined in + * torch/executor/runtime/platform/clock.h. + * + * @retval The ratio of nanoseconds to system ticks. + */ +et_tick_ratio_t et_pal_ticks_to_ns_multiplier(void) + ET_INTERNAL_PLATFORM_WEAKNESS; +using pal_ticks_to_ns_multiplier_method = et_tick_ratio_t (*)(); + +/** + * Severity level of a log message. Values must map to printable 7-bit ASCII + * uppercase letters. + */ +typedef enum { + kDebug = 'D', + kInfo = 'I', + kError = 'E', + kFatal = 'F', + kUnknown = '?', // Exception to the "uppercase letter" rule. +} et_pal_log_level_t; + +/** + * Emit a log message via platform output (serial port, console, etc). + * + * @param[in] timestamp Timestamp of the log event in system ticks since boot. + * @param[in] level Severity level of the message. Must be a printable 7-bit + * ASCII uppercase letter. + * @param[in] filename Name of the file that created the log event. + * @param[in] function Name of the function that created the log event. + * @param[in] line Line in the source file where the log event was created. + * @param[in] message Message string to log. + * @param[in] length Message string length. + */ +void et_pal_emit_log_message( + et_timestamp_t timestamp, + et_pal_log_level_t level, + const char* filename, + const char* function, + size_t line, + const char* message, + size_t length) ET_INTERNAL_PLATFORM_WEAKNESS; +using pal_emit_log_message_method = void (*)( + et_timestamp_t timestamp, + et_pal_log_level_t level, + const char* filename, + const char* function, + size_t line, + const char* message, + size_t length); + +/** + * NOTE: Core runtime code must not call this directly. It may only be called by + * a MemoryAllocator wrapper. + * + * Allocates size bytes of memory. + * + * @param[in] size Number of bytes to allocate. + * @returns the allocated memory, or nullptr on failure. Must be freed using + * et_pal_free(). + */ +void* et_pal_allocate(size_t size) ET_INTERNAL_PLATFORM_WEAKNESS; +using pal_allocate_method = void* (*)(size_t size); + +/** + * Frees memory allocated by et_pal_allocate(). + * + * @param[in] ptr Pointer to memory to free. May be nullptr. + */ +void et_pal_free(void* ptr) ET_INTERNAL_PLATFORM_WEAKNESS; +using pal_free_method = void (*)(void* ptr); + +} // extern "C" + +namespace executorch::runtime { + +/** + * Table of pointers to platform abstraction layer functions. + */ +struct PalImpl { + // Note that this struct cannot contain constructors in order to ensure that + // the singleton instance can be initialized without relying on a global + // constructor. If it does require a global constructor, there can be a race + // between the init of the default PAL and the user static registration code. + static PalImpl create( + pal_emit_log_message_method emit_log_message, + const char* source_filename); + + static PalImpl create( + pal_init_method init, + pal_abort_method abort, + pal_current_ticks_method current_ticks, + pal_ticks_to_ns_multiplier_method ticks_to_ns_multiplier, + pal_emit_log_message_method emit_log_message, + pal_allocate_method allocate, + pal_free_method free, + const char* source_filename); + + pal_init_method init = nullptr; + pal_abort_method abort = nullptr; + pal_current_ticks_method current_ticks = nullptr; + pal_ticks_to_ns_multiplier_method ticks_to_ns_multiplier = nullptr; + pal_emit_log_message_method emit_log_message = nullptr; + pal_allocate_method allocate = nullptr; + pal_free_method free = nullptr; + + // An optional metadata field, indicating the name of the source + // file that registered the PAL implementation. + const char* source_filename; +}; + +/** + * Override the PAL functions with user implementations. Any null entries in the + * table are unchanged and will keep the default implementation. + * + * Returns true if the registration was successful, false otherwise. + */ +bool register_pal(PalImpl impl); + +/** + * Returns the PAL function table, which contains function pointers to the + * active implementation of each PAL function. + */ +const PalImpl* get_pal_impl(); + +/** + * Initialize the platform abstraction layer. + * + * This function should be called before any other function provided by the PAL + * to initialize any global state. Typically overridden by PAL implementer. + */ +void pal_init(); + +/** + * Immediately abort execution, setting the device into an error state, if + * available. + */ +ET_NORETURN void pal_abort(); + +/** + * Return a monotonically non-decreasing timestamp in system ticks. + * + * @retval Timestamp value in system ticks. + */ +et_timestamp_t pal_current_ticks(); + +/** + * Return the conversion rate from system ticks to nanoseconds as a fraction. + * To convert a system ticks to nanoseconds, multiply the tick count by the + * numerator and then divide by the denominator: + * nanoseconds = ticks * numerator / denominator + * + * The utility method executorch::runtime::ticks_to_ns(et_timestamp_t) can also + * be used to perform the conversion for a given tick count. It is defined in + * torch/executor/runtime/platform/clock.h. + * + * @retval The ratio of nanoseconds to system ticks. + */ +et_tick_ratio_t pal_ticks_to_ns_multiplier(); + +/** + * Severity level of a log message. Values must map to printable 7-bit ASCII + * uppercase letters. + */ +void pal_emit_log_message( + et_timestamp_t timestamp, + et_pal_log_level_t level, + const char* filename, + const char* function, + size_t line, + const char* message, + size_t length); + +/** + * NOTE: Core runtime code must not call this directly. It may only be called by + * a MemoryAllocator wrapper. + * + * Allocates size bytes of memory. + * + * @param[in] size Number of bytes to allocate. + * @returns the allocated memory, or nullptr on failure. Must be freed using + * et_pal_free(). + */ +void* pal_allocate(size_t size); + +/** + * Frees memory allocated by et_pal_allocate(). + * + * @param[in] ptr Pointer to memory to free. May be nullptr. + */ +void pal_free(void* ptr); + +} // namespace executorch::runtime diff --git a/include/executorch/runtime/platform/profiler.h b/include/executorch/runtime/platform/profiler.h new file mode 100644 index 0000000..cb011bd --- /dev/null +++ b/include/executorch/runtime/platform/profiler.h @@ -0,0 +1,293 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include + +namespace executorch { +namespace runtime { + +// Version string used to check for compatibility with post-processing +// tool +#define ET_PROF_VER 0x00000001 + +// By default we support profiling upto 1024 perf events. Build +// targets can override this to increase the profiling buffer size +// during compilation. +#ifndef MAX_PROFILE_EVENTS +#define MAX_PROFILE_EVENTS 1024 +#endif +// By default we support profiling upto 1024 memory allocation events. +// Build targets can choose to override this, which will consequently have +// the effect of increasing/decreasing the profiling buffer size. +#ifndef MAX_MEM_PROFILE_EVENTS +#define MAX_MEM_PROFILE_EVENTS 1024 +#endif +// By default we support profiling only upto 16 allocators. If users +// have more allocators than these then they can override this during +// compilation time. There will be an increase/decrease in the profiling +// buffer size based on the way this value is changed. +#ifndef MEM_PROFILE_MAX_ALLOCATORS +#define MEM_PROFILE_MAX_ALLOCATORS 32 +#endif +// By default we support only one profiling block. If users want to profile +// something that will be iterated on multiple times then they will have to +// increment this to support their use case. In post-processing the stats for +// all these iterations will be consolidated. +#ifndef MAX_PROFILE_BLOCKS +#define MAX_PROFILE_BLOCKS 2 +#endif + +#define PROF_NAME_MAX_LEN 32 + +typedef struct alignas(8) { + union { + const char* name_str; + char name[PROF_NAME_MAX_LEN]; + }; + // chain_idx == -1 is a null value, when profile event happens out of chain + // execution + int32_t chain_idx; + uint32_t instruction_idx; + uint64_t start_time; + uint64_t end_time; +} prof_event_t; + +typedef struct alignas(8) { + uint32_t allocator_id; + uint32_t allocation_size; +} mem_prof_event_t; + +typedef struct alignas(8) { + char name[PROF_NAME_MAX_LEN]; + uint64_t allocator_id; +} prof_allocator_t; + +typedef struct alignas(8) { + uint8_t* prof_data; + uint32_t num_bytes; + uint32_t num_blocks; +} prof_result_t; + +typedef struct alignas(8) { + char name[32]; + uint32_t prof_ver; + uint32_t max_prof_entries; + uint32_t prof_entries; + uint32_t max_allocator_entries; + uint32_t allocator_entries; + uint32_t max_mem_prof_entries; + uint32_t mem_prof_entries; +} prof_header_t; + +/* +This is what the layout of the profiling buffer looks like. +--------------------------------------- +| Profiling header | +--------------------------------------- +| Profile events (Perf events) | +--------------------------------------- +| Memory allocators info | +--------------------------------------- +| Profile events (Memory allocations) | +--------------------------------------- +*/ + +// offsets of the various sections in the profiling buffer +// Total size required for profiling buffer +constexpr uint32_t prof_buf_size = sizeof(prof_header_t) + + sizeof(prof_event_t) * MAX_PROFILE_EVENTS + + sizeof(mem_prof_event_t) * MAX_MEM_PROFILE_EVENTS + + sizeof(prof_allocator_t) * MEM_PROFILE_MAX_ALLOCATORS; + +constexpr size_t prof_header_offset = 0; +constexpr size_t prof_events_offset = sizeof(prof_header_t); +constexpr size_t prof_mem_alloc_info_offset = + prof_events_offset + sizeof(prof_event_t) * MAX_PROFILE_EVENTS; +constexpr size_t prof_mem_alloc_events_offset = prof_mem_alloc_info_offset + + sizeof(prof_allocator_t) * MEM_PROFILE_MAX_ALLOCATORS; + +// Set the initial state for the profiler assuming we're using the +// statically allocated buffer declared in the profiler module. +void profiler_init(void); + +// This starts the profiling of this event and returns a token +// by which this event can be referred to in the future. +uint32_t begin_profiling(const char* name); + +// End profiling event represented by token_id +void end_profiling(uint32_t token_id); + +// Dump profiler results, return pointer to prof event array and number of +// events in it. +void dump_profile_stats(prof_result_t* prof_result); + +void reset_profile_stats(); + +void track_allocation(int32_t id, uint32_t size); + +uint32_t track_allocator(const char* name); + +void profiling_create_block(const char* name); + +// This class enables scope based profiling where needed. Profiling +// will be started when the object is created and will end when the +// object goes out of scope. +class ExecutorchProfiler { + public: + explicit ExecutorchProfiler(const char* name); + + ~ExecutorchProfiler(); + + private: + uint32_t prof_tok; +}; + +typedef struct { + int32_t chain_idx; + uint32_t instruction_idx; +} prof_state_t; + +const prof_state_t& get_profile_tls_state(); + +void set_profile_tls_state(const prof_state_t& state); + +class ExecutorchProfilerInstructionScope { + public: + explicit ExecutorchProfilerInstructionScope(const prof_state_t& state); + ~ExecutorchProfilerInstructionScope(); + + // ScopeGuard: non-copyable, non-movable + ExecutorchProfilerInstructionScope( + const ExecutorchProfilerInstructionScope&) = delete; + ExecutorchProfilerInstructionScope& operator=( + const ExecutorchProfilerInstructionScope&) = delete; + + ExecutorchProfilerInstructionScope(ExecutorchProfilerInstructionScope&&) = + delete; + ExecutorchProfilerInstructionScope& operator=( + ExecutorchProfilerInstructionScope&&) = delete; + + private: + prof_state_t old_state_; +}; + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::begin_profiling; +using ::executorch::runtime::dump_profile_stats; +using ::executorch::runtime::end_profiling; +using ::executorch::runtime::ExecutorchProfiler; +using ::executorch::runtime::ExecutorchProfilerInstructionScope; +using ::executorch::runtime::get_profile_tls_state; +using ::executorch::runtime::mem_prof_event_t; +using ::executorch::runtime::prof_allocator_t; +using ::executorch::runtime::prof_buf_size; +using ::executorch::runtime::prof_event_t; +using ::executorch::runtime::prof_events_offset; +using ::executorch::runtime::prof_header_offset; +using ::executorch::runtime::prof_header_t; +using ::executorch::runtime::prof_mem_alloc_events_offset; +using ::executorch::runtime::prof_mem_alloc_info_offset; +using ::executorch::runtime::prof_result_t; +using ::executorch::runtime::prof_state_t; +using ::executorch::runtime::profiler_init; +using ::executorch::runtime::profiling_create_block; +using ::executorch::runtime::reset_profile_stats; +using ::executorch::runtime::set_profile_tls_state; +using ::executorch::runtime::track_allocation; +using ::executorch::runtime::track_allocator; +} // namespace executor +} // namespace torch + +#ifdef PROFILING_ENABLED + +#define EXECUTORCH_PROFILE_CREATE_BLOCK(name) \ + ::executorch::runtime::profiling_create_block(name); + +// Convenience macros to begin and end profiling. These can be inserted +// anywhere as it'll be ensured that for the prod builds these will +// essentially be noops. +#define EXECUTORCH_BEGIN_PROF(name) \ + ::executorch::runtime::begin_profiling(name); + +#define EXECUTORCH_END_PROF(token_id) \ + ::executorch::runtime::end_profiling(token_id); + +#define EXECUTORCH_SCOPE_PROF_CONCAT_IMPL(a, b) a##b +#define EXECUTORCH_SCOPE_PROF_CONCAT(a, b) \ + EXECUTORCH_SCOPE_PROF_CONCAT_IMPL(a, b) +#define EXECUTORCH_SCOPE_PROF(name) \ + ::executorch::runtime::ExecutorchProfiler EXECUTORCH_SCOPE_PROF_CONCAT( \ + et_profiler_, __LINE__)(name); + +#define EXECUTORCH_PROFILE_INSTRUCTION_SCOPE(chain_idx, instruction_idx) \ + ::executorch::runtime::ExecutorchProfilerInstructionScope \ + __profiler_instruction_scope({chain_idx, instruction_idx}); + +#define EXECUTORCH_DUMP_PROFILE_RESULTS(prof_result) \ + ::executorch::runtime::dump_profile_stats(prof_result); + +#define EXECUTORCH_RESET_PROFILE_RESULTS() \ + ::executorch::runtime::reset_profile_stats(); + +#define EXECUTORCH_TRACK_ALLOCATOR(name) \ + ::executorch::runtime::track_allocator(name); + +#define EXECUTORCH_TRACK_ALLOCATION(id, size) \ + ::executorch::runtime::track_allocation(id, size); + +#else + +#define EXECUTORCH_PROFILE_CREATE_BLOCK(name) \ + do { \ + (void)(name); \ + } while (0) + +#define EXECUTORCH_BEGIN_PROF(name) \ + {} + +#define EXECUTORCH_END_PROF(token_id) \ + do { \ + (void)(token_id); \ + } while (0) + +#define EXECUTORCH_SCOPE_PROF(name) \ + do { \ + (void)(name); \ + } while (0) + +#define EXECUTORCH_PROFILE_INSTRUCTION_SCOPE(chain_idx, instruction_idx) \ + do { \ + (void)(chain_idx); \ + (void)(instruction_idx); \ + } while (0) + +#define EXECUTORCH_DUMP_PROFILE_RESULTS(prof_result_test) \ + memset(prof_result_test, 0, sizeof(::executorch::runtime::prof_result_t)); + +#define EXECUTORCH_RESET_PROFILE_RESULTS() \ + {} + +#define EXECUTORCH_TRACK_ALLOCATOR(name) ((void)(name), -1) + +#define EXECUTORCH_TRACK_ALLOCATION(id, size) \ + do { \ + (void)(id); \ + (void)(size); \ + } while (0) + +#endif diff --git a/include/executorch/runtime/platform/runtime.h b/include/executorch/runtime/platform/runtime.h new file mode 100644 index 0000000..375ae79 --- /dev/null +++ b/include/executorch/runtime/platform/runtime.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * ExecuTorch global runtime wrapper functions. + */ + +#pragma once + +#include + +namespace executorch { +namespace runtime { + +/** + * Initialize the ExecuTorch global runtime. + */ +void runtime_init(); + +} // namespace runtime +} // namespace executorch + +namespace torch { +namespace executor { +// TODO(T197294990): Remove these deprecated aliases once all users have moved +// to the new `::executorch` namespaces. +using ::executorch::runtime::runtime_init; +} // namespace executor +} // namespace torch diff --git a/include/executorch/runtime/platform/system.h b/include/executorch/runtime/platform/system.h new file mode 100644 index 0000000..18c6ee3 --- /dev/null +++ b/include/executorch/runtime/platform/system.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * Platform abstraction layer to allow individual host OS to override + * symbols in ExecuTorch. PAL functions are defined as C functions so an + * implementer can use C in lieu of C++. + */ +#pragma once + +/** + * To enable dynamic linking debugging capability on UNIX-like OS. If enabled + * and see an error like: `undefined symbol: dladdr`, install `libdl` to fix. + */ +#if defined(ET_USE_LIBDL) +#include +#endif + +static constexpr const char* DYNAMIC_LIBRARY_NOT_SUPPORTED = "NOT_SUPPORTED"; +static constexpr const char* DYNAMIC_LIBRARY_NOT_FOUND = "NOT_FOUND"; + +extern "C" { + +/** + * Return shared library . + * + * @param[in] addr Address to the symbol we are looking for in shared libraries. + * @retval The path to the shared library containing the symbol. + */ +inline const char* et_pal_get_shared_library_name(const void* addr) { +#if defined(ET_USE_LIBDL) + Dl_info info; + if (dladdr(addr, &info) && info.dli_fname) { + return info.dli_fname; + } else { + return DYNAMIC_LIBRARY_NOT_FOUND; + } +#endif + (void)addr; + return DYNAMIC_LIBRARY_NOT_SUPPORTED; +} + +} // extern "C" diff --git a/include/executorch/runtime/platform/types.h b/include/executorch/runtime/platform/types.h new file mode 100644 index 0000000..a91f357 --- /dev/null +++ b/include/executorch/runtime/platform/types.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * @file + * Public types used by the ExecuTorch Platform Abstraction Layer. + */ + +#pragma once + +// Use C-style includes so that C code can include this header. +#include + +extern "C" { + +/// Platform timestamp in system ticks. +typedef uint64_t et_timestamp_t; + +} // extern "C" diff --git a/include/torch/headeronly/macros/Export.h b/include/torch/headeronly/macros/Export.h new file mode 100644 index 0000000..14b26c1 --- /dev/null +++ b/include/torch/headeronly/macros/Export.h @@ -0,0 +1,145 @@ +#pragma once + +#ifndef C10_MACROS_EXPORT_H_ +#define C10_MACROS_EXPORT_H_ + +#ifndef C10_USING_CUSTOM_GENERATED_MACROS +#include +#endif // C10_USING_CUSTOM_GENERATED_MACROS + +/* Header file to define the common scaffolding for exported symbols. + * + * Export is by itself a quite tricky situation to deal with, and if you are + * hitting this file, make sure you start with the background here: + * - Linux: https://gcc.gnu.org/wiki/Visibility + * - Windows: + * https://docs.microsoft.com/en-us/cpp/cpp/dllexport-dllimport?view=vs-2017 + * + * Do NOT include this file directly. Instead, use c10/macros/Macros.h + */ + +// You do not need to edit this part of file unless you are changing the core +// pytorch export abstractions. +// +// This part defines the C10 core export and import macros. This is controlled +// by whether we are building shared libraries or not, which is determined +// during build time and codified in c10/core/cmake_macros.h. +// When the library is built as a shared lib, EXPORT and IMPORT will contain +// visibility attributes. If it is being built as a static lib, then EXPORT +// and IMPORT basically have no effect. + +// As a rule of thumb, you should almost NEVER mix static and shared builds for +// libraries that depend on c10. AKA, if c10 is built as a static library, we +// recommend everything dependent on c10 to be built statically. If c10 is built +// as a shared library, everything dependent on it should be built as shared. In +// the PyTorch project, all native libraries shall use the macro +// C10_BUILD_SHARED_LIB to check whether pytorch is building shared or static +// libraries. + +// For build systems that do not directly depend on CMake and directly build +// from the source directory (such as Buck), one may not have a cmake_macros.h +// file at all. In this case, the build system is responsible for providing +// correct macro definitions corresponding to the cmake_macros.h.in file. +// +// In such scenarios, one should define the macro +// C10_USING_CUSTOM_GENERATED_MACROS +// to inform this header that it does not need to include the cmake_macros.h +// file. + +#ifdef _WIN32 +#define C10_HIDDEN +#if defined(C10_BUILD_SHARED_LIBS) +#define C10_EXPORT __declspec(dllexport) +#define C10_IMPORT __declspec(dllimport) +#else +#define C10_EXPORT +#define C10_IMPORT +#endif +#else // _WIN32 +#if defined(__GNUC__) +#define C10_EXPORT __attribute__((__visibility__("default"))) +#define C10_HIDDEN __attribute__((__visibility__("hidden"))) +#else // defined(__GNUC__) +#define C10_EXPORT +#define C10_HIDDEN +#endif // defined(__GNUC__) +#define C10_IMPORT C10_EXPORT +#endif // _WIN32 + +#ifdef NO_EXPORT +#undef C10_EXPORT +#define C10_EXPORT +#endif + +// Definition of an adaptive XX_API macro, that depends on whether you are +// building the library itself or not, routes to XX_EXPORT and XX_IMPORT. +// Basically, you will need to do this for each shared library that you are +// building, and the instruction is as follows: assuming that you are building +// a library called libawesome.so. You should: +// (1) for your cmake target (usually done by "add_library(awesome, ...)"), +// define a macro called AWESOME_BUILD_MAIN_LIB using +// target_compile_options. +// (2) define the AWESOME_API macro similar to the one below. +// And in the source file of your awesome library, use AWESOME_API to +// annotate public symbols. + +// Here, for the C10 library, we will define the macro C10_API for both import +// and export. + +// This one is being used by libc10.so +#ifdef C10_BUILD_MAIN_LIB +#define C10_API C10_EXPORT +#else +#define C10_API C10_IMPORT +#endif + +// This one is being used by libtorch.so +#ifdef CAFFE2_BUILD_MAIN_LIB +#define TORCH_API C10_EXPORT +#else +#define TORCH_API C10_IMPORT +#endif + +// You may be wondering why we have TORCH_CUDA_CPP_API and TORCH_CUDA_CU_API +// belonging to the same library instead of just one TORCH_CUDA_API. Well, it +// can indeed just be one TORCH_CUDA_API (and used to be)! TORCH_CUDA_CPP_API +// and TORCH_CUDA_CU_API are artifacts of when we needed a split build to +// avoid relocation marker linking errors. The context is as follows: +// +// Once upon a time, there _was_ only TORCH_CUDA_API. All was happy until we +// tried to compile PyTorch for CUDA 11.1, which ran into relocation marker +// issues when linking big binaries. +// (https://github.com/pytorch/pytorch/issues/39968) We had two choices: +// (1) Stop supporting so many GPU architectures +// (2) Do something else +// We chose #2 and decided to split the behemoth that was torch_cuda into two +// smaller libraries, one with most of the core kernel functions (torch_cuda_cu) +// and the other that had..well..everything else (torch_cuda_cpp). The idea was +// this: instead of linking our static libraries (like the hefty +// libcudnn_static.a) with another huge library, torch_cuda, and run into pesky +// relocation marker issues, we could link our static libraries to a smaller +// part of torch_cuda (torch_cuda_cpp) and avoid the issues. + +// libtorch_cuda.so (where torch_cuda_cu and torch_cuda_cpp are a part of the +// same api) +#ifdef TORCH_CUDA_BUILD_MAIN_LIB +#define TORCH_CUDA_CPP_API C10_EXPORT +#define TORCH_CUDA_CU_API C10_EXPORT +#else +#define TORCH_CUDA_CPP_API C10_IMPORT +#define TORCH_CUDA_CU_API C10_IMPORT +#endif + +#if defined(TORCH_XPU_BUILD_MAIN_LIB) +#define TORCH_XPU_API C10_EXPORT +#else +#define TORCH_XPU_API C10_IMPORT +#endif + +// Enums only need to be exported on windows for non-CUDA files +#if defined(_WIN32) && defined(__CUDACC__) +#define C10_API_ENUM C10_API +#else +#define C10_API_ENUM +#endif +#endif // C10_MACROS_EXPORT_H_ diff --git a/include/torch/headeronly/macros/Macros.h b/include/torch/headeronly/macros/Macros.h new file mode 100644 index 0000000..718bd35 --- /dev/null +++ b/include/torch/headeronly/macros/Macros.h @@ -0,0 +1,830 @@ +#ifndef C10_MACROS_MACROS_H_ +#define C10_MACROS_MACROS_H_ + +#ifdef __cplusplus +#include +#else +#include +#endif + +/* Main entry for torch/headeronly/macros (used to be c10/macros). + * + * In your code, include torch/headeronly/macros/Macros.h directly, instead of + * individual files in this folder. + */ + +// For build systems that do not directly depend on CMake and directly build +// from the source directory (such as Buck), one may not have a cmake_macros.h +// file at all. In this case, the build system is responsible for providing +// correct macro definitions corresponding to the cmake_macros.h.in file. +// +// In such scenarios, one should define the macro +// C10_USING_CUSTOM_GENERATED_MACROS +// to inform this header that it does not need to include the cmake_macros.h +// file. + +#ifndef C10_USING_CUSTOM_GENERATED_MACROS +#include +#endif // C10_USING_CUSTOM_GENERATED_MACROS + +#include + +#if defined(__clang__) +#define __ubsan_ignore_float_divide_by_zero__ \ + __attribute__((no_sanitize("float-divide-by-zero"))) +#define __ubsan_ignore_undefined__ __attribute__((no_sanitize("undefined"))) +#define __ubsan_ignore_signed_int_overflow__ \ + __attribute__((no_sanitize("signed-integer-overflow"))) +#define __ubsan_ignore_pointer_overflow__ \ + __attribute__((no_sanitize("pointer-overflow"))) +#define __ubsan_ignore_function__ __attribute__((no_sanitize("function"))) +#define __ubsan_ignore_float_cast_overflow__ \ + __attribute__((no_sanitize("float-cast-overflow"))) +#else +#define __ubsan_ignore_float_divide_by_zero__ +#define __ubsan_ignore_undefined__ +#define __ubsan_ignore_signed_int_overflow__ +#define __ubsan_ignore_pointer_overflow__ +#define __ubsan_ignore_function__ +#define __ubsan_ignore_float_cast_overflow__ +#endif + +// Detect address sanitizer as some stuff doesn't work with it +#undef C10_ASAN_ENABLED + +// for clang +#if defined(__has_feature) +#if ((__has_feature(address_sanitizer))) +#define C10_ASAN_ENABLED 1 +#endif +#endif + +// for gcc +#if defined(__SANITIZE_ADDRESS__) +#if __SANITIZE_ADDRESS__ +#if !defined(C10_ASAN_ENABLED) +#define C10_ASAN_ENABLED 1 +#endif +#endif +#endif + +#if !defined(C10_ASAN_ENABLED) +#define C10_ASAN_ENABLED 0 +#endif + +// Detect undefined-behavior sanitizer (UBSAN) +#undef C10_UBSAN_ENABLED + +// for clang or gcc >= 14 +// NB: gcc 14 adds support for Clang's __has_feature +// https://gcc.gnu.org/gcc-14/changes.html +// gcc < 14 doesn't have a macro for UBSAN +// (e.g. __SANITIZE_UNDEFINED__ does not exist in gcc) +// https://github.com/google/sanitizers/issues/765 +#if defined(__has_feature) +#if ((__has_feature(undefined_behavior_sanitizer))) +#define C10_UBSAN_ENABLED 1 +#endif +#endif + +#if !defined(C10_UBSAN_ENABLED) +#define C10_UBSAN_ENABLED 0 +#endif + +// Disable the copy and assignment operator for a class. Note that this will +// disable the usage of the class in std containers. +#define C10_DISABLE_COPY_AND_ASSIGN(classname) \ + classname(const classname&) = delete; \ + classname& operator=(const classname&) = delete + +#define C10_CONCATENATE_IMPL(s1, s2) s1##s2 +#define C10_CONCATENATE(s1, s2) C10_CONCATENATE_IMPL(s1, s2) + +#define C10_MACRO_EXPAND(args) args + +#define C10_STRINGIZE_IMPL(x) #x +#define C10_STRINGIZE(x) C10_STRINGIZE_IMPL(x) + +/** + * C10_ANONYMOUS_VARIABLE(str) introduces a new identifier which starts with + * str and ends with a unique number. + */ +#ifdef __COUNTER__ +#define C10_UID __COUNTER__ +#define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __COUNTER__) +#else +#define C10_UID __LINE__ +#define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __LINE__) +#endif + +#ifdef __has_cpp_attribute +#define C10_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +#define C10_HAS_CPP_ATTRIBUTE(x) (0) +#endif + +/// Bind a returned reference/pointer's lifetime to a parameter (or *this) so +/// Clang can warn when it would dangle. Expands to nothing on compilers that +/// lack the attribute (e.g. non-clang, older nvcc). +#if C10_HAS_CPP_ATTRIBUTE(clang::lifetimebound) +#define C10_LIFETIMEBOUND [[clang::lifetimebound]] +#else +#define C10_LIFETIMEBOUND +#endif + +#ifndef FBCODE_CAFFE2 +/// DEPRECATED: Warn if a type or return value is discarded. +#define C10_NODISCARD [[nodiscard]] + +/// DEPRECATED: Suppress an unused variable. +#define C10_UNUSED [[maybe_unused]] +#endif + +#if !defined(__has_attribute) +#define __has_attribute(x) 0 +#endif + +// Direct port of LLVM_ATTRIBUTE_USED. +#if __has_attribute(used) +#define C10_USED __attribute__((__used__)) +#else +#define C10_USED +#endif + +#define C10_RESTRICT __restrict + +#ifdef __cplusplus + +// Simply define the namespace, in case a dependent library want to refer to +// the c10 namespace but not any nontrivial files. +namespace c10 {} +namespace c10::cuda {} +namespace c10::hip {} +namespace c10::xpu {} + +// Since C10 is the core library for caffe2 (and aten), we will simply reroute +// all abstractions defined in c10 to be available in caffe2 as well. +// This is only for backwards compatibility. Please use the symbols from the +// c10 namespace where possible. +namespace caffe2 { +using namespace c10; +} +namespace at { +using namespace c10; +} +namespace at::cuda { +using namespace c10::cuda; +} // namespace at::cuda + +// WARNING!!! THIS IS A GIANT HACK!!! +// This line means you cannot simultaneously include c10/hip +// and c10/cuda and then use them from the at::cuda namespace. +// This is true in practice, because HIPIFY works inplace on +// files in ATen/cuda, so it assumes that c10::hip is available +// from at::cuda. This namespace makes that happen. When +// HIPIFY is no longer out-of-place, we can switch the cuda +// here to hip and everyone is happy. +namespace at::cuda { +using namespace c10::hip; +} // namespace at::cuda + +namespace at::xpu { +using namespace c10::xpu; +} // namespace at::xpu + +#endif // __cplusplus + +// C10_LIKELY/C10_UNLIKELY +// +// These macros provide parentheses, so you can use these macros as: +// +// if C10_LIKELY(some_expr) { +// ... +// } +// +// NB: static_cast to boolean is mandatory in C++, because __builtin_expect +// takes a long argument, which means you may trigger the wrong conversion +// without it. +// +#if defined(__GNUC__) || defined(__ICL) || defined(__clang__) +#define C10_LIKELY(expr) (__builtin_expect(static_cast(expr), 1)) +#define C10_UNLIKELY(expr) (__builtin_expect(static_cast(expr), 0)) +#else +#define C10_LIKELY(expr) (expr) +#define C10_UNLIKELY(expr) (expr) +#endif + +/// C10_NOINLINE - Functions whose declaration is annotated with this will not +/// be inlined. +#ifdef __GNUC__ +#define C10_NOINLINE __attribute__((noinline)) +#elif _MSC_VER +#define C10_NOINLINE __declspec(noinline) +#else +#define C10_NOINLINE +#endif + +#if defined(_MSC_VER) +#define C10_ALWAYS_INLINE __forceinline +#elif __has_attribute(always_inline) || defined(__GNUC__) +#define C10_ALWAYS_INLINE __attribute__((__always_inline__)) inline +#else +#define C10_ALWAYS_INLINE inline +#endif + +// Unlike C10_ALWAYS_INLINE, C10_ALWAYS_INLINE_ATTRIBUTE can be used +// on a lambda. +#if defined(_MSC_VER) +// MSVC 14.39 is reasonably recent and doesn't like +// [[msvc::forceinline]] on a lambda, so don't try to use it. +#define C10_ALWAYS_INLINE_ATTRIBUTE +#elif __has_attribute(always_inline) || defined(__GNUC__) +#define C10_ALWAYS_INLINE_ATTRIBUTE __attribute__((__always_inline__)) +#else +#define C10_ALWAYS_INLINE_ATTRIBUTE +#endif + +#if defined(_MSC_VER) +#define C10_ATTR_VISIBILITY_HIDDEN +#elif defined(__GNUC__) +#define C10_ATTR_VISIBILITY_HIDDEN __attribute__((__visibility__("hidden"))) +#else +#define C10_ATTR_VISIBILITY_HIDDEN +#endif + +#define C10_ERASE C10_ALWAYS_INLINE C10_ATTR_VISIBILITY_HIDDEN + +#ifdef __cplusplus +#include +#else +#include +#endif + +#ifdef __HIPCC__ +// Unlike CUDA, HIP requires a HIP header to be included for __host__ to work. +// We do this #include here so that C10_HOST_DEVICE and friends will Just Work. +// See https://github.com/ROCm/hip/issues/441 +#include +#endif + +#if defined(__CUDACC__) || defined(__HIPCC__) +// Designates functions callable from the host (CPU) and the device (GPU) +#define C10_HOST_DEVICE __host__ __device__ +#define C10_DEVICE __device__ +#define C10_HOST __host__ +// constants from +// (https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications) +// The maximum number of threads per multiprocessor is 1024 for Turing +// architecture (7.5), 1536 for Geforce Ampere (8.6)/Jetson Orin (8.7), and +// 2048 for all other architectures. You'll get warnings if you exceed these +// constants. Hence, the following macros adjust the input values from the user +// to resolve potential warnings. +#if __CUDA_ARCH__ == 750 +constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1024; +#elif __CUDA_ARCH__ == 860 || __CUDA_ARCH__ == 870 || __CUDA_ARCH__ == 890 || \ + __CUDA_ARCH__ == 1200 +constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1536; +#else +constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 2048; +#endif +// CUDA_MAX_THREADS_PER_BLOCK is same for all architectures currently +constexpr uint32_t CUDA_MAX_THREADS_PER_BLOCK = 1024; +// CUDA_THREADS_PER_BLOCK_FALLBACK is the "canonical fallback" choice of block +// size. 256 is a good number for this fallback and should give good occupancy +// and versatility across all architectures. +constexpr uint32_t CUDA_THREADS_PER_BLOCK_FALLBACK = 256; +// NOTE: if you are thinking of constexpr-ify the inputs to launch bounds, it +// turns out that although __launch_bounds__ can take constexpr, it +// can't take a constexpr that has anything to do with templates. +// Currently we use launch_bounds that depend on template arguments in +// Loops.cuh, Reduce.cuh and LossCTC.cuh. Hence, C10_MAX_THREADS_PER_BLOCK +// and C10_MIN_BLOCKS_PER_SM are kept as macros. +// Suppose you were planning to write __launch_bounds__(a, b), based on your +// performance tuning on a modern GPU. Instead, you should write +// __launch_bounds__(C10_MAX_THREADS_PER_BLOCK(a), C10_MIN_BLOCKS_PER_SM(a, b)), +// which will also properly respect limits on old architectures. +#define C10_MAX_THREADS_PER_BLOCK(val) \ + (((val) <= CUDA_MAX_THREADS_PER_BLOCK) ? (val) \ + : CUDA_THREADS_PER_BLOCK_FALLBACK) +#define C10_MIN_BLOCKS_PER_SM(threads_per_block, blocks_per_sm) \ + ((((threads_per_block) * (blocks_per_sm) <= CUDA_MAX_THREADS_PER_SM) \ + ? (blocks_per_sm) \ + : ((CUDA_MAX_THREADS_PER_SM + (threads_per_block) - 1) / \ + (threads_per_block)))) +// C10_LAUNCH_BOUNDS is analogous to __launch_bounds__ +#define C10_LAUNCH_BOUNDS_0 \ + __launch_bounds__( \ + 256, 4) // default launch bounds that should give good occupancy and + // versatility across all architectures. +#define C10_LAUNCH_BOUNDS_1(max_threads_per_block) \ + __launch_bounds__((C10_MAX_THREADS_PER_BLOCK((max_threads_per_block)))) +#define C10_LAUNCH_BOUNDS_2(max_threads_per_block, min_blocks_per_sm) \ + __launch_bounds__( \ + (C10_MAX_THREADS_PER_BLOCK((max_threads_per_block))), \ + (C10_MIN_BLOCKS_PER_SM((max_threads_per_block), (min_blocks_per_sm)))) +#else +#define C10_HOST_DEVICE +#define C10_HOST +#define C10_DEVICE +#endif + +#if defined(USE_ROCM) +#define C10_HIP_HOST_DEVICE __host__ __device__ +#else +#define C10_HIP_HOST_DEVICE +#endif + +// C10_WARP_SIZE is only allowed for device code. +// Host code dynamically-sized launch configs _must_ use at::cuda::warp_size(). +// Host or device statically-sized arrays _must_ use either +// C10_WARP_SIZE_UPPER_BOUND or C10_WARP_SIZE_LOWER_BOUND, as needed. +// +// HIP header used to define warpSize as a constexpr that was either 32 or 64 +// depending on the target device, and then always set it to 64 for host code. +// For a time, that allowed C10_WARP_SIZE to be defined like so: +// +// #ifdef USE_ROCM +// #define C10_WARP_SIZE warpSize +// #else +// #define C10_WARP_SIZE 32 +// #endif +// +// In ROCm 7, warpSize is no longer constexpr, matching CUDA behavior. +// We can now only use warpSize for C10_WARP_SIZE in device code and this is +// enforced by using __device__ in its definition. In host code where +// C10_WARP_SIZE was previously used as a compile-time constant, this will now +// cause a compile-time error. +// +// If an array was previously expected to be sized at compile-time using +// C10_WARP_SIZE, users must now use either C10_WARP_SIZE_UPPER_BOUND or +// C10_WARP_SIZE_LOWER_BOUND depending on the situation. +// +// If C10_WARP_SIZE was previously used to determine kernel launch sizes, users +// must now use at::cuda::warp_size() for the dynamic runtime query. +// +// Unfortunately, C10_WARP_SIZE has been public and available for both host and +// device since approximately 2019, so forcing it to be device-only would break +// existing code in the wild. +#if defined(USE_ROCM) +namespace at::cuda { +TORCH_CUDA_CPP_API int warp_size(); +} +#if defined(__HIPCC__) +static __host__ inline int C10_WARP_SIZE_INTERNAL() { + return at::cuda::warp_size(); +} +// NOTE: __device__ C10_WARP_SIZE_INTERNAL +// For __SPIRV__, we must use dynamic warpSize. When not targeting __SPIRV__, +// we can use constexpr. This matches prior behavior. We preserve this for +// backward compatibility instead of forcing old code to use dynamic warpSize +// and losing constexpr. However, compiling for --offload-arch=amdgcnspirv +// could expose where C10_WARP_SIZE was used incorrectly where the dynamic +// warpSize is not allowed. +#if defined(__SPIRV__) +static __device__ inline int C10_WARP_SIZE_INTERNAL() { + return warpSize; +} +#else // __SPIRV__ +static __device__ inline constexpr int C10_WARP_SIZE_INTERNAL() { +#if defined(__GFX9__) + return 64; +#else // __GFX9__ + return 32; +#endif // __GFX9__ +} +#endif // __SPIRV__ +#if defined(__SPIRV__) +#define C10_WARP_SIZE_LOWER_BOUND 32 +#define C10_WARP_SIZE_UPPER_BOUND 64 +#elif defined(__GFX9__) +#define C10_WARP_SIZE_LOWER_BOUND 64 +#define C10_WARP_SIZE_UPPER_BOUND 64 +#else +#define C10_WARP_SIZE_LOWER_BOUND 32 +#define C10_WARP_SIZE_UPPER_BOUND 32 +#endif +#else // !__HIPCC__ +static inline int C10_WARP_SIZE_INTERNAL() { + return at::cuda::warp_size(); +} +#define C10_WARP_SIZE_LOWER_BOUND 32 +#define C10_WARP_SIZE_UPPER_BOUND 64 +#endif // __HIPCC__ +#define C10_WARP_SIZE (C10_WARP_SIZE_INTERNAL()) +#else // !USE_ROCM +#define C10_WARP_SIZE 32 +#define C10_WARP_SIZE_LOWER_BOUND 32 +#define C10_WARP_SIZE_UPPER_BOUND 32 +#endif // USE_ROCM + +#if defined(_MSC_VER) && _MSC_VER <= 1900 +#define __func__ __FUNCTION__ +#endif + +// CUDA_KERNEL_ASSERT checks the assertion +// even when NDEBUG is defined. This is useful for important assertions in CUDA +// code that would otherwise be suppressed when building Release. +#if defined(__ANDROID__) || defined(__APPLE__) || defined(__FreeBSD__) +// Those platforms do not support assert() +#define CUDA_KERNEL_ASSERT(cond) +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) +#define SYCL_KERNEL_ASSERT(cond) +#elif defined(_MSC_VER) +#if defined(NDEBUG) +extern "C" { +C10_IMPORT +#if defined(__SYCL_DEVICE_ONLY__) +extern SYCL_EXTERNAL void _wassert( + const wchar_t* wexpr, + const wchar_t* wfile, + unsigned line); +#else +#if defined(__CUDA_ARCH__) +__host__ __device__ +#endif // __CUDA_ARCH__ + void + _wassert(wchar_t const* _Message, wchar_t const* _File, unsigned _Line); +#endif // __SYCL_DEVICE_ONLY__ +} +#endif // NDEBUG +#define CUDA_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +// TODO: This doesn't assert the message because I (chilli) couldn't figure out +// a nice way to convert a char* to a wchar_t* +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(printf( \ + "[CUDA_KERNEL_ASSERT] " __FILE__ ":" C10_STRINGIZE( \ + __LINE__) ": %s: block: [%d,%d,%d], thread: [%d,%d,%d]: " \ + "Assertion failed: `%s`: " msg "\n", \ + __func__, \ + blockIdx.x, \ + blockIdx.y, \ + blockIdx.z, \ + threadIdx.x, \ + threadIdx.y, \ + threadIdx.z, \ + #cond, \ + ##__VA_ARGS__)); \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +#define SYCL_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + (void)(_wassert( \ + _CRT_WIDE(#cond), \ + _CRT_WIDE(__FILE__), \ + static_cast(__LINE__)), \ + 0); \ + } +#else // __APPLE__, _MSC_VER +#if defined(NDEBUG) +extern "C" { +#if defined(__SYCL_DEVICE_ONLY__) +extern SYCL_EXTERNAL void __assert_fail( + const char* expr, + const char* file, + unsigned int line, + const char* func); +#elif (defined(__EMSCRIPTEN__)) +// As defined in assert.h in the Emscripten stdlib +_Noreturn void __assert_fail( + const char* expr, + const char* file, + int line, + const char* func); +#else // __SYCL_DEVICE_ONLY__ +#if (defined(__CUDA_ARCH__) && !(defined(__clang__) && defined(__CUDA__))) +// CUDA supports __assert_fail function which are common for both device +// and host side code. +__host__ __device__ +#endif + + // This forward declaration matching the declaration of __assert_fail + // exactly how it is in glibc in case parts of the program are compiled with + // different NDEBUG settings. Otherwise we might get 'ambiguous declaration' + // error. Note: On ROCm - this declaration serves for host side compilation. + void + __assert_fail( + const char* assertion, + const char* file, + unsigned int line, + const char* function) noexcept __attribute__((__noreturn__)); + +#endif // __SYCL_DEVICE_ONLY__ +} +#endif // NDEBUG +// ROCm disables kernel assert by default for performance considerations. +// Though ROCm supports __assert_fail, it uses kernel printf which has +// a non-negligible performance impact even if the assert condition is +// never triggered. We choose to use abort() instead which will still +// terminate the application but without a more useful error message. +#if !defined(C10_USE_ROCM_KERNEL_ASSERT) && defined(USE_ROCM) +#define CUDA_KERNEL_ASSERT(cond) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#define SYCL_KERNEL_ASSERT(cond) \ + if C10_UNLIKELY (!(cond)) { \ + abort(); \ + } +#else +#if defined(USE_ROCM) && defined(__HIP_DEVICE_COMPILE__) +namespace torch::headeronly::detail { +// Compile-time string fragment for CUDA_KERNEL_ASSERT message pieces. +template +struct RoCmAssertLit { + char data[N]{}; + constexpr RoCmAssertLit(const char (&s)[N]) { + for (unsigned i = 0; i < N; ++i) { + data[i] = s[i]; + } + } + static constexpr unsigned size() { + return N; + } + constexpr unsigned percent() const { + unsigned count = 0; + for (unsigned i = 0; i < N - 1; ++i) { + if (data[i] == '%') { + ++count; + } + } + return count; + } +}; + +// OCKL is_last=1 treats the append as printf format; escape '%'. Size the +// buffer as Out + NumPercent. +template +constexpr auto rocm_assert_concat() { + constexpr unsigned out = A.size() + B.size() + C.size() - 2; + constexpr unsigned pct = A.percent() + B.percent() + C.percent(); + struct { + char data[out + pct]; + unsigned length; + } msg{}; + unsigned j = 0; + auto append = [&](const char* s, unsigned n) { + for (unsigned k = 0; k < n; ++k) { + if (s[k] == '%') { + msg.data[j++] = '%'; + } + msg.data[j++] = s[k]; + } + }; + append(A.data, A.size() - 1); + append(B.data, B.size() - 1); + append(C.data, C.size()); + msg.length = j; + return msg; +} + +// __host__ __device__: hipcc's device pass still type-checks host-only call +// sites (e.g. MemoryAccess.cuh LoadWithCast ctors). Host runtime uses #else +// __assert_fail; this body is not emitted for host codegen. +template +__host__ __device__ inline __attribute__((always_inline, flatten)) void +rocm_assert_one_shot(const char (&msg)[N], unsigned length) { + auto d = __ockl_fprintf_stderr_begin(); + __ockl_fprintf_append_string_n(d, msg, length, 1); + __builtin_trap(); +} +} // namespace torch::headeronly::detail + +#define ROCM_ASSERT_LIT(s) ::torch::headeronly::detail::RoCmAssertLit(s) + +#define CUDA_KERNEL_ASSERT(cond) \ + if C10_UNLIKELY (!(cond)) { \ + static constexpr auto _rocm_assert_msg = \ + ::torch::headeronly::detail::rocm_assert_concat< \ + ROCM_ASSERT_LIT(__FILE__ ":" C10_STRINGIZE(__LINE__) ": "), \ + ROCM_ASSERT_LIT(__func__), \ + ROCM_ASSERT_LIT(": Device-side assertion `" #cond \ + "' failed.\n")>(); \ + ::torch::headeronly::detail::rocm_assert_one_shot( \ + _rocm_assert_msg.data, _rocm_assert_msg.length); \ + } +#else +#define CUDA_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + __assert_fail( \ + #cond, __FILE__, static_cast(__LINE__), __func__); \ + } +#endif // defined(USE_ROCM) && defined(__HIP_DEVICE_COMPILE__) +#define CUDA_KERNEL_ASSERT_MSG(cond, msg) \ + if (C10_UNLIKELY(!(cond))) { \ + __assert_fail( \ + msg, __FILE__, static_cast(__LINE__), __func__); \ + } +#define CUDA_KERNEL_ASSERT_PRINTF(cond, msg, ...) \ + if (C10_UNLIKELY(!(cond))) { \ + printf( \ + "[CUDA_KERNEL_ASSERT] " __FILE__ ":" C10_STRINGIZE( \ + __LINE__) ": %s: block: [%d,%d,%d], thread: [%d,%d,%d]: " \ + "Assertion failed: `%s`: " msg "\n", \ + __func__, \ + blockIdx.x, \ + blockIdx.y, \ + blockIdx.z, \ + threadIdx.x, \ + threadIdx.y, \ + threadIdx.z, \ + #cond, \ + ##__VA_ARGS__); \ + __assert_fail( \ + #cond, __FILE__, static_cast(__LINE__), __func__); \ + } +#define SYCL_KERNEL_ASSERT(cond) \ + if (C10_UNLIKELY(!(cond))) { \ + __assert_fail( \ + #cond, __FILE__, static_cast(__LINE__), __func__); \ + } +#endif // C10_USE_ROCM_KERNEL_ASSERT && USE_ROCM +#endif // __APPLE__ + +// Compile-time switch to control how assertions are logged inside CUDA kernels. +// If C10_CUDA_VERBOSE_ASSERT is defined, CUDA_KERNEL_ASSERT_VERBOSE will +// take addition information passed to the macro and forward them to +// CUDA_KERNEL_ASSERT_PRINTF If C10_CUDA_VERBOSE_ASSERT is not defined, +// CUDA_KERNEL_ASSERT_VERBOSE will behave the same as CUDA_KERNEL_ASSERT. +#ifdef C10_ENABLE_VERBOSE_ASSERT +#define CUDA_KERNEL_ASSERT_VERBOSE(cond, ...) \ + CUDA_KERNEL_ASSERT_PRINTF(cond, __VA_ARGS__) +#else +#define CUDA_KERNEL_ASSERT_VERBOSE(cond, ...) CUDA_KERNEL_ASSERT(cond) +#endif + +#ifdef __APPLE__ +#include +#endif + +#if defined(__ANDROID__) +#define C10_ANDROID 1 +#define C10_MOBILE 1 +#elif ( \ + defined(__APPLE__) && \ + (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE)) +#define C10_IOS 1 +#define C10_MOBILE 1 +#endif // ANDROID / IOS + +#if defined(C10_MOBILE) && C10_MOBILE +#define C10_ALWAYS_INLINE_UNLESS_MOBILE inline +#else +#define C10_ALWAYS_INLINE_UNLESS_MOBILE C10_ALWAYS_INLINE +#endif + +#if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) +#define CONSTEXPR_EXCEPT_WIN_CUDA constexpr +#define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA constexpr + +#define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \ + static constexpr const char field[] = val; +#define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val) +#endif // !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) + +#ifndef HAS_DEMANGLE +#if defined(__ANDROID__) || defined(_WIN32) || defined(__EMSCRIPTEN__) +#define HAS_DEMANGLE 0 +#elif defined(__APPLE__) && \ + (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE) +#define HAS_DEMANGLE 0 +#else +#define HAS_DEMANGLE 1 +#endif +#endif // HAS_DEMANGLE + +#define _C10_PRAGMA__(string) _Pragma(#string) +#define _C10_PRAGMA_(string) _C10_PRAGMA__(string) + +#ifdef __clang__ +#define C10_CLANG_DIAGNOSTIC_PUSH() _Pragma("clang diagnostic push") +#define C10_CLANG_DIAGNOSTIC_POP() _Pragma("clang diagnostic pop") +#define C10_CLANG_DIAGNOSTIC_IGNORE(flag) \ + _C10_PRAGMA_(clang diagnostic ignored flag) +#define C10_CLANG_HAS_WARNING(flag) __has_warning(flag) +#else +#define C10_CLANG_DIAGNOSTIC_PUSH() +#define C10_CLANG_DIAGNOSTIC_POP() +#define C10_CLANG_DIAGNOSTIC_IGNORE(flag) +#define C10_CLANG_HAS_WARNING(flag) 0 +#endif + +#ifdef __clang__ + +#define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \ + _C10_PRAGMA_(clang diagnostic push) \ + _C10_PRAGMA_(clang diagnostic ignored "-Wunknown-warning-option") \ + _C10_PRAGMA_(clang diagnostic ignored warning) + +#define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(clang diagnostic pop) + +#elif __GNUC__ + +#define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \ + _C10_PRAGMA_(GCC diagnostic push) \ + _C10_PRAGMA_(GCC diagnostic ignored "-Wpragmas") \ + _C10_PRAGMA_(GCC diagnostic ignored warning) + +#define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(GCC diagnostic pop) + +#else + +#define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) +#define C10_DIAGNOSTIC_POP() + +#endif + +// This macro is used to find older C++ compilers +// that don't support move optimization for return values. + +#if (defined(__GNUC__) && __GNUC__ < 13 && __cplusplus < 202002L) || \ + (defined(__clang_major__) && __clang_major__ < 13) +#define C10_RETURN_MOVE_IF_OLD_COMPILER 1 +#else +#define C10_RETURN_MOVE_IF_OLD_COMPILER 0 +#endif + +// The HIDDEN_NAMESPACE_BEGIN and HIDDEN_NAMESPACE_END below +// are needed for maintaining robustness in our header APIs in +// torch/headeronly and torch/csrc/stable under the namespaces +// torch::headeronly and torch::stable respectively. We enforce +// hidden visibility for these APIs because we want to enable +// loading custom extensions compiled against different libtorch +// versions where these APIs may have changed. + +// Helper macros to handle 1-3 hidden namespace levels when not windows +#define _HIDDEN_NS_GET_MACRO(_1, _2, _3, NAME, ...) NAME +#define _HIDDEN_NS_1(n1) namespace n1 __attribute__((visibility("hidden"))) { +#define _HIDDEN_NS_2(n1, n2) \ + namespace n1 { \ + namespace n2 __attribute__((visibility("hidden"))) { +#define _HIDDEN_NS_3(n1, n2, n3) \ + namespace n1::n2 { \ + namespace n3 __attribute__((visibility("hidden"))) { + +// Helper macros to close namespaces when not windows +#define _HIDDEN_NS_END_1(n1) } +#define _HIDDEN_NS_END_N(n1, ...) \ + } \ + } + +// Helper macros to join strs with :: (for win, where symbols are hidden by +// default) +#define _EXPAND(...) __VA_ARGS__ +#define _JOIN_GET_MACRO(_1, _2, _3, NAME, ...) NAME +#define _JOIN_NS1(a) a +#define _JOIN_NS2(a, b) a::b +#define _JOIN_NS3(a, b, c) a::b::c + +#if !defined(HIDDEN_NAMESPACE_BEGIN) +#if defined(__GNUG__) && !defined(_WIN32) +#define HIDDEN_NAMESPACE_BEGIN(...) \ + _HIDDEN_NS_GET_MACRO( \ + __VA_ARGS__, _HIDDEN_NS_3, _HIDDEN_NS_2, _HIDDEN_NS_1)(__VA_ARGS__) +#else +#define HIDDEN_NAMESPACE_BEGIN(...) \ + namespace _EXPAND(_JOIN_GET_MACRO( \ + __VA_ARGS__, _JOIN_NS3, _JOIN_NS2, _JOIN_NS1)(__VA_ARGS__)) { +#endif +#endif + +#if !defined(HIDDEN_NAMESPACE_END) +#if defined(__GNUG__) && !defined(_WIN32) +#define HIDDEN_NAMESPACE_END(...) \ + _HIDDEN_NS_GET_MACRO( \ + __VA_ARGS__, _HIDDEN_NS_END_N, _HIDDEN_NS_END_N, _HIDDEN_NS_END_1)( \ + __VA_ARGS__) +#else +#define HIDDEN_NAMESPACE_END(...) } +#endif +#endif + +#endif // C10_MACROS_MACROS_H_ diff --git a/include/torch/headeronly/util/BFloat16-math.h b/include/torch/headeronly/util/BFloat16-math.h new file mode 100644 index 0000000..257ef24 --- /dev/null +++ b/include/torch/headeronly/util/BFloat16-math.h @@ -0,0 +1,337 @@ +#pragma once + +#include +#include +#include + +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion") +#endif + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +template +struct is_reduced_floating_point + : std::integral_constant< + bool, + std::is_same_v || std::is_same_v> {}; + +template +constexpr bool is_reduced_floating_point_v = + is_reduced_floating_point::value; +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace c10 { +using torch::headeronly::is_reduced_floating_point; +using torch::headeronly::is_reduced_floating_point_v; +} // namespace c10 + +namespace std { + +#if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) +using torch::headeronly::is_reduced_floating_point; +using torch::headeronly::is_reduced_floating_point_v; +#endif // !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) + +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T acos(T a) { + return std::acos(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T asin(T a) { + return std::asin(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T atan(T a) { + return std::atan(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T atanh(T a) { + return std::atanh(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T erf(T a) { + return std::erf(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T erfc(T a) { + return std::erfc(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T exp(T a) { + return std::exp(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T expm1(T a) { + return std::expm1(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline bool isfinite(T a) { + return std::isfinite(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T log(T a) { + return std::log(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T log10(T a) { + return std::log10(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T log1p(T a) { + return std::log1p(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T log2(T a) { + return std::log2(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T ceil(T a) { + return std::ceil(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T cos(T a) { + return std::cos(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T floor(T a) { + return std::floor(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T nearbyint(T a) { + return std::nearbyint(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T sin(T a) { + return std::sin(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T tan(T a) { + return std::tan(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T sinh(T a) { + return std::sinh(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T cosh(T a) { + return std::cosh(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T tanh(T a) { + return std::tanh(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T trunc(T a) { + return std::trunc(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T lgamma(T a) { + return std::lgamma(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T sqrt(T a) { + return std::sqrt(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T rsqrt(T a) { + return 1.0f / std::sqrt(float(a)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T abs(T a) { + return std::abs(float(a)); +} +#if defined(_MSC_VER) && defined(__CUDACC__) +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T pow(T a, double b) { + return std::pow(float(a), float(b)); +} +#else +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T pow(T a, double b) { + return std::pow(float(a), b); +} +#endif +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T pow(T a, T b) { + return std::pow(float(a), float(b)); +} +template < + typename T, + typename std:: + enable_if_t, int> = 0> +inline T fmod(T a, T b) { + return std::fmod(float(a), float(b)); +} + +/* + The following function is inspired from the implementation in `musl` + Link to License: https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT + ---------------------------------------------------------------------- + Copyright © 2005-2020 Rich Felker, et al. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + ---------------------------------------------------------------------- + */ +template < + typename T, + typename std:: + enable_if_t, int> = 0> +C10_HOST_DEVICE inline T nextafter(T from, T to) { + // Reference: + // https://git.musl-libc.org/cgit/musl/tree/src/math/nextafter.c + using int_repr_t = uint16_t; + constexpr uint8_t bits = 16; + union { + T f; + int_repr_t i; + } ufrom = {from}, uto = {to}; + + // get a mask to get the sign bit i.e. MSB + int_repr_t sign_mask = int_repr_t{1} << (bits - 1); + + // short-circuit: if either is NaN, return NaN + if (from != from || to != to) { + return from + to; + } + + // short-circuit: if they are exactly the same. + if (ufrom.i == uto.i) { + return from; + } + + // mask the sign-bit to zero i.e. positive + // equivalent to abs(x) + int_repr_t abs_from = ufrom.i & ~sign_mask; + int_repr_t abs_to = uto.i & ~sign_mask; + if (abs_from == 0) { + // if both are zero but with different sign, + // preserve the sign of `to`. + if (abs_to == 0) { + return to; + } + // smallest subnormal with sign of `to`. + ufrom.i = (uto.i & sign_mask) | int_repr_t{1}; + return ufrom.f; + } + + // if abs(from) > abs(to) or sign(from) != sign(to) + if (abs_from > abs_to || ((ufrom.i ^ uto.i) & sign_mask)) { + ufrom.i--; + } else { + ufrom.i++; + } + + return ufrom.f; +} + +} // namespace std + +C10_CLANG_DIAGNOSTIC_POP() diff --git a/include/torch/headeronly/util/BFloat16.h b/include/torch/headeronly/util/BFloat16.h new file mode 100644 index 0000000..2c6ce79 --- /dev/null +++ b/include/torch/headeronly/util/BFloat16.h @@ -0,0 +1,481 @@ +#pragma once + +// Defines the bloat16 type (brain floating-point). This representation uses +// 1 bit for the sign, 8 bits for the exponent and 7 bits for the mantissa. + +#include +#include + +#include +#include +#include +#include +#include + +#if defined(__CUDACC__) && (!defined(USE_ROCM) || (TORCH_HIP_VERSION >= 702)) +#include +#endif + +#if defined(CL_SYCL_LANGUAGE_VERSION) +#include // for SYCL 1.2.1 +#elif defined(SYCL_LANGUAGE_VERSION) +#include // for SYCL 2020 +#endif + +namespace c10 { + +struct alignas(2) BFloat16 { + uint16_t x; + + // HIP wants __host__ __device__ tag, CUDA does not +#if defined(USE_ROCM) && defined(__HIPCC__) + C10_HOST_DEVICE BFloat16() = default; +#else + BFloat16() = default; +#endif + + struct from_bits_t {}; + static constexpr C10_HOST_DEVICE from_bits_t from_bits() { + return from_bits_t(); + } + + constexpr C10_HOST_DEVICE BFloat16( + unsigned short bits, + from_bits_t /*unused*/) + : x(bits) {} + /* implicit */ inline C10_HOST_DEVICE BFloat16(float value); + inline C10_HOST_DEVICE operator float() const; + +#if defined(__CUDACC__) && (!defined(USE_ROCM) || (TORCH_HIP_VERSION >= 702)) + inline C10_HOST_DEVICE BFloat16(const __nv_bfloat16& value); + explicit inline C10_HOST_DEVICE operator __nv_bfloat16() const; +#endif + +#if defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) + inline C10_HOST_DEVICE BFloat16(const sycl::ext::oneapi::bfloat16& value); + explicit inline C10_HOST_DEVICE operator sycl::ext::oneapi::bfloat16() const; +#endif +}; + +inline std::ostream& operator<<(std::ostream& out, const BFloat16& value) { + out << (float)value; + return out; +} + +namespace detail { +inline C10_HOST_DEVICE float f32_from_bits(uint16_t src) { + float res = 0; + uint32_t tmp = src; + tmp <<= 16; + +#if defined(USE_ROCM) && defined(__HIPCC__) + float* tempRes; + + // We should be using memcpy in order to respect the strict aliasing rule + // but it fails in the HIP environment. + tempRes = reinterpret_cast(&tmp); + res = *tempRes; +#else + std::memcpy(&res, &tmp, sizeof(tmp)); +#endif + + return res; +} + +inline C10_HOST_DEVICE uint16_t bits_from_f32(float src) { + uint32_t res = 0; + +#if defined(USE_ROCM) && defined(__HIPCC__) + // We should be using memcpy in order to respect the strict aliasing rule + // but it fails in the HIP environment. + uint32_t* tempRes = reinterpret_cast(&src); + res = *tempRes; +#else + std::memcpy(&res, &src, sizeof(res)); +#endif + + return res >> 16; +} + +inline C10_HOST_DEVICE uint16_t round_to_nearest_even(float src) { +#if defined(USE_ROCM) && defined(__HIPCC__) + if (src != src) { +#elif defined(_MSC_VER) + if (isnan(src)) { +#else + if (std::isnan(src)) { +#endif + return UINT16_C(0x7FC0); + } else { + const uint32_t U32 = c10::bit_cast(src); + uint32_t rounding_bias = ((U32 >> 16) & 1) + UINT32_C(0x7FFF); + return static_cast((U32 + rounding_bias) >> 16); + } +} + +} // namespace detail + +//-------- the following is copied from c10/util/BFloat16-inl.h ---------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +/// Constructors +inline C10_HOST_DEVICE BFloat16::BFloat16(float value) + : +#if defined(__CUDACC__) && \ + (!defined(USE_ROCM) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 || \ + defined(USE_ROCM) && (TORCH_HIP_VERSION >= 702)) + x(__bfloat16_as_ushort(__float2bfloat16(value))) +#elif defined(__SYCL_DEVICE_ONLY__) && \ + defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) + x(c10::bit_cast(sycl::ext::oneapi::bfloat16(value))) +#else + // RNE by default + x(detail::round_to_nearest_even(value)) +#endif +{ +} + +/// Implicit conversions +inline C10_HOST_DEVICE BFloat16::operator float() const { +#if defined(__CUDACC__) && (!defined(USE_ROCM) || (TORCH_HIP_VERSION >= 702)) + return __bfloat162float(*reinterpret_cast(&x)); +#elif defined(__SYCL_DEVICE_ONLY__) && \ + defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) + return float(*reinterpret_cast(&x)); +#else + return detail::f32_from_bits(x); +#endif +} + +#if defined(__CUDACC__) && (!defined(USE_ROCM) || (TORCH_HIP_VERSION >= 702)) +inline C10_HOST_DEVICE BFloat16::BFloat16(const __nv_bfloat16& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE BFloat16::operator __nv_bfloat16() const { + return *reinterpret_cast(&x); +} +#endif + +#if defined(SYCL_EXT_ONEAPI_BFLOAT16_MATH_FUNCTIONS) +inline C10_HOST_DEVICE BFloat16::BFloat16( + const sycl::ext::oneapi::bfloat16& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE BFloat16::operator sycl::ext::oneapi::bfloat16() const { + return *reinterpret_cast(&x); +} +#endif + +// CUDA intrinsics + +#if defined(__CUDACC__) || defined(__HIPCC__) +inline C10_DEVICE BFloat16 __ldg(const BFloat16* ptr) { +#if !defined(USE_ROCM) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + return __ldg(reinterpret_cast(ptr)); +#else + return *ptr; +#endif +} +#endif + +/// Arithmetic + +inline C10_HOST_DEVICE BFloat16 +operator+(const BFloat16& a, const BFloat16& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 +operator-(const BFloat16& a, const BFloat16& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 +operator*(const BFloat16& a, const BFloat16& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator/(const BFloat16& a, const BFloat16& b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator-(const BFloat16& a) { + return -static_cast(a); +} + +inline C10_HOST_DEVICE BFloat16& operator+=(BFloat16& a, const BFloat16& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator-=(BFloat16& a, const BFloat16& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator*=(BFloat16& a, const BFloat16& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator/=(BFloat16& a, const BFloat16& b) { + a = a / b; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator|(BFloat16& a, const BFloat16& b) { + a.x = a.x | b.x; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator^(BFloat16& a, const BFloat16& b) { + a.x = a.x ^ b.x; + return a; +} + +inline C10_HOST_DEVICE BFloat16& operator&(BFloat16& a, const BFloat16& b) { + a.x = a.x & b.x; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(BFloat16 a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(BFloat16 a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(BFloat16 a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(BFloat16 a, float b) { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, BFloat16 b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, BFloat16 b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, BFloat16 b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, BFloat16 b) { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const BFloat16& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const BFloat16& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const BFloat16& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const BFloat16& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(BFloat16 a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(BFloat16 a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(BFloat16 a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(BFloat16 a, double b) { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, BFloat16 b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, BFloat16 b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, BFloat16 b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, BFloat16 b) { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE BFloat16 operator+(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator-(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator*(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator/(BFloat16 a, int b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator+(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE BFloat16 operator-(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE BFloat16 operator*(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE BFloat16 operator/(int a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE BFloat16 operator+(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator-(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator*(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE BFloat16 operator/(BFloat16 a, int64_t b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE BFloat16 operator+(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE BFloat16 operator-(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE BFloat16 operator*(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE BFloat16 operator/(int64_t a, BFloat16 b) { + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + return static_cast(a) / b; +} + +// Overloading < and > operators, because std::max and std::min use them. + +inline C10_HOST_DEVICE bool operator>(BFloat16& lhs, BFloat16& rhs) { + return float(lhs) > float(rhs); +} + +inline C10_HOST_DEVICE bool operator<(BFloat16& lhs, BFloat16& rhs) { + return float(lhs) < float(rhs); +} + +C10_CLANG_DIAGNOSTIC_POP() +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +namespace detail { +using c10::detail::bits_from_f32; +using c10::detail::f32_from_bits; +using c10::detail::round_to_nearest_even; +} // namespace detail + +using c10::BFloat16; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +using c10::operator<; +using c10::operator>; +using c10::operator<<; +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_signed = true; + static constexpr bool is_specialized = true; + static constexpr bool is_integer = false; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = true; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = true; + static constexpr auto has_denorm = numeric_limits::has_denorm; + static constexpr auto has_denorm_loss = + numeric_limits::has_denorm_loss; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = false; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 8; + static constexpr int digits10 = 2; + static constexpr int max_digits10 = 4; + static constexpr int radix = 2; + static constexpr int min_exponent = -125; + static constexpr int min_exponent10 = -37; + static constexpr int max_exponent = 128; + static constexpr int max_exponent10 = 38; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = + numeric_limits::tinyness_before; + + static constexpr c10::BFloat16 min() { + return c10::BFloat16(0x0080, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 lowest() { + return c10::BFloat16(0xFF7F, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 max() { + return c10::BFloat16(0x7F7F, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 epsilon() { + return c10::BFloat16(0x3C00, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 round_error() { + return c10::BFloat16(0x3F00, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 infinity() { + return c10::BFloat16(0x7F80, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 quiet_NaN() { + return c10::BFloat16(0x7FC0, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 signaling_NaN() { + return c10::BFloat16(0x7FA0, c10::BFloat16::from_bits()); + } + static constexpr c10::BFloat16 denorm_min() { + return c10::BFloat16(0x0001, c10::BFloat16::from_bits()); + } +}; + +} // namespace std diff --git a/include/torch/headeronly/util/Half.h b/include/torch/headeronly/util/Half.h new file mode 100644 index 0000000..4014723 --- /dev/null +++ b/include/torch/headeronly/util/Half.h @@ -0,0 +1,788 @@ +#pragma once + +/// Defines the Half type (half-precision floating-point) including conversions +/// to standard C types and basic arithmetic operations. Note that arithmetic +/// operations are implemented by converting to floating point and +/// performing the operation in float32, instead of using CUDA half intrinsics. +/// Most uses of this type within ATen are memory bound, including the +/// element-wise kernels, and the half intrinsics aren't efficient on all GPUs. +/// If you are writing a compute bound kernel, you can use the CUDA half +/// intrinsics directly on the Half type from device code. + +#include +#include +#include + +#if defined(__cplusplus) +#include +#elif !defined(__OPENCL_VERSION__) +#include +#endif + +#ifdef _MSC_VER +#include +#endif + +#include +#include +#include + +#ifdef __CUDACC__ +#include +#endif + +#ifdef __HIPCC__ +#include +#endif + +#if defined(CL_SYCL_LANGUAGE_VERSION) +#include // for SYCL 1.2.1 +#elif defined(SYCL_LANGUAGE_VERSION) +#include // for SYCL 2020 +#endif + +#if (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) +#include +#endif + +#if defined(__aarch64__) && !defined(__CUDACC__) +#include +#endif + +#if defined(__GNUC__) || defined(__clang__) +#if defined(__x86_64__) || defined(_M_X64) || defined(__i386) || \ + defined(_M_IX86) +#if defined(__F16C__) && \ + !(defined(__CUDA_ARCH__) || defined(__CUDACC__) || \ + defined(__HIP_DEVICE_COMPILE__)) +#define C10_X86_F16 1 +#include // import conversion ops from f16cintrin.h +#endif // defined(__F16C__) && !(defined(__CUDA_ARCH__) || defined(__CUDACC__) + // || defined(__HIP_DEVICE_COMPILE__)) +#endif // __x86_64__ || _M_X64 || __i386 || _M_IX86 +#endif // __GNUC__ || __clang__ + +namespace c10 { + +struct alignas(2) Half { + unsigned short x; + + struct from_bits_t {}; + C10_HOST_DEVICE static constexpr from_bits_t from_bits() { + return from_bits_t(); + } + + // HIP wants __host__ __device__ tag, CUDA does not +#if defined(USE_ROCM) + C10_HOST_DEVICE Half() = default; +#else + Half() = default; +#endif + + constexpr C10_HOST_DEVICE Half(unsigned short bits, from_bits_t /*unused*/) + : x(bits) {} +#if defined(__aarch64__) && !defined(__CUDACC__) + inline Half(float16_t value); + inline operator float16_t() const; +#else + inline C10_HOST_DEVICE Half(float value); + inline C10_HOST_DEVICE operator float() const; +#endif + +#if defined(__CUDACC__) || defined(__HIPCC__) + inline C10_HOST_DEVICE Half(const __half& value); + inline C10_HOST_DEVICE operator __half() const; +#endif +#ifdef SYCL_LANGUAGE_VERSION + inline C10_HOST_DEVICE Half(const sycl::half& value); + inline C10_HOST_DEVICE operator sycl::half() const; +#endif +}; + +inline std::ostream& operator<<(std::ostream& out, const Half& value) { + out << (float)value; + return out; +} + +namespace detail { +/* + * Convert a 16-bit floating-point number in IEEE half-precision format, in bit + * representation, to a 32-bit floating-point number in IEEE single-precision + * format. + * + * @note The implementation relies on IEEE-like (no assumption about rounding + * mode and no operations on denormals) floating-point operations and bitcasts + * between integer and floating-point variables. + */ +C10_HOST_DEVICE inline float fp16_ieee_to_fp32_value(uint16_t h) { +#ifdef C10_X86_F16 + return _cvtsh_ss(h); +#else + /* + * Extend the half-precision floating-point number to 32 bits and shift to the + * upper part of the 32-bit word: + * +---+-----+------------+-------------------+ + * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000| + * +---+-----+------------+-------------------+ + * Bits 31 26-30 16-25 0-15 + * + * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0 + * - zero bits. + */ + const uint32_t w = (uint32_t)h << 16; + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = w & UINT32_C(0x80000000); + /* + * Extract mantissa and biased exponent of the input number into the high bits + * of the 32-bit word: + * + * +-----+------------+---------------------+ + * |EEEEE|MM MMMM MMMM|0 0000 0000 0000 0000| + * +-----+------------+---------------------+ + * Bits 27-31 17-26 0-16 + */ + const uint32_t two_w = w + w; + + /* + * Shift mantissa and exponent into bits 23-28 and bits 13-22 so they become + * mantissa and exponent of a single-precision floating-point number: + * + * S|Exponent | Mantissa + * +-+---+-----+------------+----------------+ + * |0|000|EEEEE|MM MMMM MMMM|0 0000 0000 0000| + * +-+---+-----+------------+----------------+ + * Bits | 23-31 | 0-22 + * + * Next, there are some adjustments to the exponent: + * - The exponent needs to be corrected by the difference in exponent bias + * between single-precision and half-precision formats (0x7F - 0xF = 0x70) + * - Inf and NaN values in the inputs should become Inf and NaN values after + * conversion to the single-precision number. Therefore, if the biased + * exponent of the half-precision input was 0x1F (max possible value), the + * biased exponent of the single-precision output must be 0xFF (max possible + * value). We do this correction in two steps: + * - First, we adjust the exponent by (0xFF - 0x1F) = 0xE0 (see exp_offset + * below) rather than by 0x70 suggested by the difference in the exponent bias + * (see above). + * - Then we multiply the single-precision result of exponent adjustment by + * 2**(-112) to reverse the effect of exponent adjustment by 0xE0 less the + * necessary exponent adjustment by 0x70 due to difference in exponent bias. + * The floating-point multiplication hardware would ensure than Inf and + * NaN would retain their value on at least partially IEEE754-compliant + * implementations. + * + * Note that the above operations do not handle denormal inputs (where biased + * exponent == 0). However, they also do not operate on denormal inputs, and + * do not produce denormal results. + */ + constexpr uint32_t exp_offset = UINT32_C(0xE0) << 23; + // const float exp_scale = 0x1.0p-112f; + constexpr uint32_t scale_bits = (uint32_t)15 << 23; + float exp_scale_val = 0; +#if defined(_MSC_VER) && defined(__clang__) + __builtin_memcpy(&exp_scale_val, &scale_bits, sizeof(exp_scale_val)); +#else + std::memcpy(&exp_scale_val, &scale_bits, sizeof(exp_scale_val)); +#endif + + const float exp_scale = exp_scale_val; + const float normalized_value = + fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale; + + /* + * Convert denormalized half-precision inputs into single-precision results + * (always normalized). Zero inputs are also handled here. + * + * In a denormalized number the biased exponent is zero, and mantissa has + * on-zero bits. First, we shift mantissa into bits 0-9 of the 32-bit word. + * + * zeros | mantissa + * +---------------------------+------------+ + * |0000 0000 0000 0000 0000 00|MM MMMM MMMM| + * +---------------------------+------------+ + * Bits 10-31 0-9 + * + * Now, remember that denormalized half-precision numbers are represented as: + * FP16 = mantissa * 2**(-24). + * The trick is to construct a normalized single-precision number with the + * same mantissa and the half-precision input and with an exponent which would + * scale the corresponding mantissa bits to 2**(-24). A normalized + * single-precision floating-point number is represented as: FP32 = (1 + + * mantissa * 2**(-23)) * 2**(exponent - 127) Therefore, when the biased + * exponent is 126, a unit change in the mantissa of the input denormalized + * half-precision number causes a change of the constructed single-precision + * number by 2**(-24), i.e. the same amount. + * + * The last step is to adjust the bias of the constructed single-precision + * number. When the input half-precision number is zero, the constructed + * single-precision number has the value of FP32 = 1 * 2**(126 - 127) = + * 2**(-1) = 0.5 Therefore, we need to subtract 0.5 from the constructed + * single-precision number to get the numerical equivalent of the input + * half-precision number. + */ + constexpr uint32_t magic_mask = UINT32_C(126) << 23; + constexpr float magic_bias = 0.5f; + const float denormalized_value = + fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias; + + /* + * - Choose either results of conversion of input as a normalized number, or + * as a denormalized number, depending on the input exponent. The variable + * two_w contains input exponent in bits 27-31, therefore if it's smaller than + * 2**27, the input is either a denormal number, or zero. + * - Combine the result of conversion of exponent and mantissa with the sign + * of the input number. + */ + constexpr uint32_t denormalized_cutoff = UINT32_C(1) << 27; + const uint32_t result = sign | + (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) + : fp32_to_bits(normalized_value)); + return fp32_from_bits(result); +#endif // C10_X86_F16 +} + +/* + * Convert a 32-bit floating-point number in IEEE single-precision format to a + * 16-bit floating-point number in IEEE half-precision format, in bit + * representation. + * + * @note The implementation relies on IEEE-like (no assumption about rounding + * mode and no operations on denormals) floating-point operations and bitcasts + * between integer and floating-point variables. + */ +inline uint16_t fp16_ieee_from_fp32_value(float f) { +#ifdef C10_X86_F16 + return _cvtss_sh(f, _MM_FROUND_TO_NEAREST_INT); +#else + // const float scale_to_inf = 0x1.0p+112f; + // const float scale_to_zero = 0x1.0p-110f; + constexpr uint32_t scale_to_inf_bits = (uint32_t)239 << 23; + constexpr uint32_t scale_to_zero_bits = (uint32_t)17 << 23; + float scale_to_inf_val = 0, scale_to_zero_val = 0; + std::memcpy(&scale_to_inf_val, &scale_to_inf_bits, sizeof(scale_to_inf_val)); + std::memcpy( + &scale_to_zero_val, &scale_to_zero_bits, sizeof(scale_to_zero_val)); + const float scale_to_inf = scale_to_inf_val; + const float scale_to_zero = scale_to_zero_val; + +#if defined(_MSC_VER) && _MSC_VER == 1916 + float base = ((signbit(f) != 0 ? -f : f) * scale_to_inf) * scale_to_zero; +#else + float base = (fabsf(f) * scale_to_inf) * scale_to_zero; +#endif + + const uint32_t w = fp32_to_bits(f); + const uint32_t shl1_w = w + w; + const uint32_t sign = w & UINT32_C(0x80000000); + uint32_t bias = shl1_w & UINT32_C(0xFF000000); + if (bias < UINT32_C(0x71000000)) { + bias = UINT32_C(0x71000000); + } + + base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base; + const uint32_t bits = fp32_to_bits(base); + const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00); + const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF); + const uint32_t nonsign = exp_bits + mantissa_bits; + return static_cast( + (sign >> 16) | + (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign)); +#endif // C10_X86_F16 +} + +/* + * Convert a 16-bit floating-point number in IEEE half-precision format, in bit + * representation, to a 32-bit floating-point number in IEEE single-precision + * format, in bit representation. + * + * @note The implementation doesn't use any floating-point operations. + */ +inline uint32_t fp16_ieee_to_fp32_bits(uint16_t h) { + /* + * Extend the half-precision floating-point number to 32 bits and shift to the + * upper part of the 32-bit word: + * +---+-----+------------+-------------------+ + * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000| + * +---+-----+------------+-------------------+ + * Bits 31 26-30 16-25 0-15 + * + * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0 + * - zero bits. + */ + const uint32_t w = (uint32_t)h << 16; + /* + * Extract the sign of the input number into the high bit of the 32-bit word: + * + * +---+----------------------------------+ + * | S |0000000 00000000 00000000 00000000| + * +---+----------------------------------+ + * Bits 31 0-31 + */ + const uint32_t sign = w & UINT32_C(0x80000000); + /* + * Extract mantissa and biased exponent of the input number into the bits 0-30 + * of the 32-bit word: + * + * +---+-----+------------+-------------------+ + * | 0 |EEEEE|MM MMMM MMMM|0000 0000 0000 0000| + * +---+-----+------------+-------------------+ + * Bits 30 27-31 17-26 0-16 + */ + const uint32_t nonsign = w & UINT32_C(0x7FFFFFFF); + /* + * Renorm shift is the number of bits to shift mantissa left to make the + * half-precision number normalized. If the initial number is normalized, some + * of its high 6 bits (sign == 0 and 5-bit exponent) equals one. In this case + * renorm_shift == 0. If the number is denormalize, renorm_shift > 0. Note + * that if we shift denormalized nonsign by renorm_shift, the unit bit of + * mantissa will shift into exponent, turning the biased exponent into 1, and + * making mantissa normalized (i.e. without leading 1). + */ +#ifdef _MSC_VER + unsigned long nonsign_bsr; + _BitScanReverse(&nonsign_bsr, (unsigned long)nonsign); + uint32_t renorm_shift = (uint32_t)nonsign_bsr ^ 31; +#else + uint32_t renorm_shift = __builtin_clz(nonsign); +#endif + renorm_shift = renorm_shift > 5 ? renorm_shift - 5 : 0; + /* + * Iff half-precision number has exponent of 15, the addition overflows + * it into bit 31, and the subsequent shift turns the high 9 bits + * into 1. Thus inf_nan_mask == 0x7F800000 if the half-precision number + * had exponent of 15 (i.e. was NaN or infinity) 0x00000000 otherwise + */ + const int32_t inf_nan_mask = + ((int32_t)(nonsign + 0x04000000) >> 8) & INT32_C(0x7F800000); + /* + * Iff nonsign is 0, it overflows into 0xFFFFFFFF, turning bit 31 + * into 1. Otherwise, bit 31 remains 0. The signed shift right by 31 + * broadcasts bit 31 into all bits of the zero_mask. Thus zero_mask == + * 0xFFFFFFFF if the half-precision number was zero (+0.0h or -0.0h) + * 0x00000000 otherwise + */ + const int32_t zero_mask = (int32_t)(nonsign - 1) >> 31; + /* + * 1. Shift nonsign left by renorm_shift to normalize it (if the input + * was denormal) + * 2. Shift nonsign right by 3 so the exponent (5 bits originally) + * becomes an 8-bit field and 10-bit mantissa shifts into the 10 high + * bits of the 23-bit mantissa of IEEE single-precision number. + * 3. Add 0x70 to the exponent (starting at bit 23) to compensate the + * different in exponent bias (0x7F for single-precision number less 0xF + * for half-precision number). + * 4. Subtract renorm_shift from the exponent (starting at bit 23) to + * account for renormalization. As renorm_shift is less than 0x70, this + * can be combined with step 3. + * 5. Binary OR with inf_nan_mask to turn the exponent into 0xFF if the + * input was NaN or infinity. + * 6. Binary ANDNOT with zero_mask to turn the mantissa and exponent + * into zero if the input was zero. + * 7. Combine with the sign of the input number. + */ + return sign | + ((((nonsign << renorm_shift >> 3) + ((0x70 - renorm_shift) << 23)) | + inf_nan_mask) & + ~zero_mask); +} + +#ifdef C10_X86_F16 +#undef C10_X86_F16 +#endif // C10_X86_F16 + +#if defined(__aarch64__) && !defined(__CUDACC__) +inline float16_t fp16_from_bits(uint16_t h) { + return c10::bit_cast(h); +} + +inline uint16_t fp16_to_bits(float16_t f) { + return c10::bit_cast(f); +} + +// According to https://godbolt.org/z/frExdbsWG it would translate to single +// fcvt s0, h0 +inline float native_fp16_to_fp32_value(uint16_t h) { + return static_cast(fp16_from_bits(h)); +} + +inline uint16_t native_fp16_from_fp32_value(float f) { + return fp16_to_bits(static_cast(f)); +} +#endif + +} // namespace detail + +//---------- below is copied from c10/util/Half-inl.h ----------------// +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +#if defined(__aarch64__) && !defined(__CUDACC__) +/// Constructors +inline Half::Half(float16_t value) : x(detail::fp16_to_bits(value)) {} +inline Half::operator float16_t() const { + return detail::fp16_from_bits(x); +} +#else + +inline C10_HOST_DEVICE Half::Half(float value) + : +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + x(__half_as_short(__float2half(value))) +#elif defined(__SYCL_DEVICE_ONLY__) + x(c10::bit_cast(sycl::half(value))) +#elif (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) + x(at::vec::float2half_scalar(value)) +#else + x(detail::fp16_ieee_from_fp32_value(value)) +#endif +{ +} + +/// Implicit conversions + +inline C10_HOST_DEVICE Half::operator float() const { +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + return __half2float(*reinterpret_cast(&x)); +#elif defined(__SYCL_DEVICE_ONLY__) + return float(c10::bit_cast(x)); +#elif (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) + return at::vec::half2float_scalar(x); +#elif defined(__aarch64__) && !defined(__CUDACC__) + return detail::native_fp16_to_fp32_value(x); +#else + return detail::fp16_ieee_to_fp32_value(x); +#endif +} + +#endif /* !defined(__aarch64__) || defined(__CUDACC__) \ + */ + +#if defined(__CUDACC__) || defined(__HIPCC__) +inline C10_HOST_DEVICE Half::Half(const __half& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE Half::operator __half() const { + return *reinterpret_cast(&x); +} +#endif + +#ifdef SYCL_LANGUAGE_VERSION +inline C10_HOST_DEVICE Half::Half(const sycl::half& value) { + x = *reinterpret_cast(&value); +} +inline C10_HOST_DEVICE Half::operator sycl::half() const { + return *reinterpret_cast(&x); +} +#endif + +// CUDA intrinsics + +#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 350)) || \ + (defined(__clang__) && defined(__CUDA__)) +inline __device__ Half __ldg(const Half* ptr) { + return __ldg(reinterpret_cast(ptr)); +} +#endif + +/// Arithmetic + +inline C10_HOST_DEVICE Half operator+(const Half& a, const Half& b) { + return static_cast(a) + static_cast(b); +} + +inline C10_HOST_DEVICE Half operator-(const Half& a, const Half& b) { + return static_cast(a) - static_cast(b); +} + +inline C10_HOST_DEVICE Half operator*(const Half& a, const Half& b) { + return static_cast(a) * static_cast(b); +} + +inline C10_HOST_DEVICE Half operator/(const Half& a, const Half& b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / static_cast(b); +} + +inline C10_HOST_DEVICE Half operator-(const Half& a) { +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530) || \ + defined(__HIP_DEVICE_COMPILE__) + return __hneg(a); +#elif defined(__SYCL_DEVICE_ONLY__) + return -c10::bit_cast(a); +#else + return -static_cast(a); +#endif +} + +inline C10_HOST_DEVICE Half& operator+=(Half& a, const Half& b) { + a = a + b; + return a; +} + +inline C10_HOST_DEVICE Half& operator-=(Half& a, const Half& b) { + a = a - b; + return a; +} + +inline C10_HOST_DEVICE Half& operator*=(Half& a, const Half& b) { + a = a * b; + return a; +} + +inline C10_HOST_DEVICE Half& operator/=(Half& a, const Half& b) { + a = a / b; + return a; +} + +/// Arithmetic with floats + +inline C10_HOST_DEVICE float operator+(Half a, float b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE float operator-(Half a, float b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE float operator*(Half a, float b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE float operator/(Half a, float b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE float operator+(float a, Half b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE float operator-(float a, Half b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE float operator*(float a, Half b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE float operator/(float a, Half b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +inline C10_HOST_DEVICE float& operator+=(float& a, const Half& b) { + return a += static_cast(b); +} +inline C10_HOST_DEVICE float& operator-=(float& a, const Half& b) { + return a -= static_cast(b); +} +inline C10_HOST_DEVICE float& operator*=(float& a, const Half& b) { + return a *= static_cast(b); +} +inline C10_HOST_DEVICE float& operator/=(float& a, const Half& b) { + return a /= static_cast(b); +} + +/// Arithmetic with doubles + +inline C10_HOST_DEVICE double operator+(Half a, double b) { + return static_cast(a) + b; +} +inline C10_HOST_DEVICE double operator-(Half a, double b) { + return static_cast(a) - b; +} +inline C10_HOST_DEVICE double operator*(Half a, double b) { + return static_cast(a) * b; +} +inline C10_HOST_DEVICE double operator/(Half a, double b) + __ubsan_ignore_float_divide_by_zero__ { + return static_cast(a) / b; +} + +inline C10_HOST_DEVICE double operator+(double a, Half b) { + return a + static_cast(b); +} +inline C10_HOST_DEVICE double operator-(double a, Half b) { + return a - static_cast(b); +} +inline C10_HOST_DEVICE double operator*(double a, Half b) { + return a * static_cast(b); +} +inline C10_HOST_DEVICE double operator/(double a, Half b) + __ubsan_ignore_float_divide_by_zero__ { + return a / static_cast(b); +} + +/// Arithmetic with ints + +inline C10_HOST_DEVICE Half operator+(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Half operator-(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Half operator*(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Half operator/(Half a, int b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Half operator+(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Half operator-(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Half operator*(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Half operator/(int a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) / b; +} + +//// Arithmetic with int64_t + +inline C10_HOST_DEVICE Half operator+(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a + static_cast(b); +} +inline C10_HOST_DEVICE Half operator-(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a - static_cast(b); +} +inline C10_HOST_DEVICE Half operator*(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a * static_cast(b); +} +inline C10_HOST_DEVICE Half operator/(Half a, int64_t b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return a / static_cast(b); +} + +inline C10_HOST_DEVICE Half operator+(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) + b; +} +inline C10_HOST_DEVICE Half operator-(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) - b; +} +inline C10_HOST_DEVICE Half operator*(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) * b; +} +inline C10_HOST_DEVICE Half operator/(int64_t a, Half b) { + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + return static_cast(a) / b; +} + +/// NOTE: we do not define comparisons directly and instead rely on the implicit +/// conversion from c10::Half to float. + +C10_CLANG_DIAGNOSTIC_POP() + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +using c10::Half; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +using c10::operator<<; + +namespace detail { +#if defined(__aarch64__) && !defined(__CUDACC__) +using c10::detail::fp16_from_bits; +using c10::detail::fp16_to_bits; +using c10::detail::native_fp16_from_fp32_value; +using c10::detail::native_fp16_to_fp32_value; +#endif + +using c10::detail::fp16_ieee_from_fp32_value; +using c10::detail::fp16_ieee_to_fp32_bits; +using c10::detail::fp16_ieee_to_fp32_value; +} // namespace detail + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template <> +class numeric_limits { + public: + static constexpr bool is_specialized = true; + static constexpr bool is_signed = true; + static constexpr bool is_integer = false; + static constexpr bool is_exact = false; + static constexpr bool has_infinity = true; + static constexpr bool has_quiet_NaN = true; + static constexpr bool has_signaling_NaN = true; + static constexpr auto has_denorm = numeric_limits::has_denorm; + static constexpr auto has_denorm_loss = + numeric_limits::has_denorm_loss; + static constexpr auto round_style = numeric_limits::round_style; + static constexpr bool is_iec559 = true; + static constexpr bool is_bounded = true; + static constexpr bool is_modulo = false; + static constexpr int digits = 11; + static constexpr int digits10 = 3; + static constexpr int max_digits10 = 5; + static constexpr int radix = 2; + static constexpr int min_exponent = -13; + static constexpr int min_exponent10 = -4; + static constexpr int max_exponent = 16; + static constexpr int max_exponent10 = 4; + static constexpr auto traps = numeric_limits::traps; + static constexpr auto tinyness_before = + numeric_limits::tinyness_before; + static constexpr c10::Half min() { + return c10::Half(0x0400, c10::Half::from_bits()); + } + static constexpr c10::Half lowest() { + return c10::Half(0xFBFF, c10::Half::from_bits()); + } + static constexpr c10::Half max() { + return c10::Half(0x7BFF, c10::Half::from_bits()); + } + static constexpr c10::Half epsilon() { + return c10::Half(0x1400, c10::Half::from_bits()); + } + static constexpr c10::Half round_error() { + return c10::Half(0x3800, c10::Half::from_bits()); + } + static constexpr c10::Half infinity() { + return c10::Half(0x7C00, c10::Half::from_bits()); + } + static constexpr c10::Half quiet_NaN() { + return c10::Half(0x7E00, c10::Half::from_bits()); + } + static constexpr c10::Half signaling_NaN() { + return c10::Half(0x7D00, c10::Half::from_bits()); + } + static constexpr c10::Half denorm_min() { + return c10::Half(0x0001, c10::Half::from_bits()); + } +}; + +} // namespace std diff --git a/include/torch/headeronly/util/TypeSafeSignMath.h b/include/torch/headeronly/util/TypeSafeSignMath.h new file mode 100644 index 0000000..8e89795 --- /dev/null +++ b/include/torch/headeronly/util/TypeSafeSignMath.h @@ -0,0 +1,100 @@ +#pragma once + +#include +#include +#include + +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wstring-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wstring-conversion") +#endif +#if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion") +#endif + +namespace c10 { + +/// Returns true if x < 0 +/// NOTE: Will fail on an unsigned custom type +/// For the most part it's possible to fix this if +/// the custom type has a constexpr constructor. +/// However, notably, c10::Half does not :-( +template +inline constexpr bool is_negative(const T& x) { + if constexpr (std::is_unsigned_v) { + // An unsigned value can never be less than zero. + return false; + } else { + return x < T(0); + } +} + +/// Returns the sign of x as -1, 0, 1 +/// NOTE: Will fail on an unsigned custom type +/// For the most part it's possible to fix this if +/// the custom type has a constexpr constructor. +/// However, notably, c10::Half does not :-( +template +inline constexpr int signum(const T& x) { + if constexpr (std::is_unsigned_v) { + return T(0) < x; + } else { + return (T(0) < x) - (x < T(0)); + } +} + +/// Returns true if a and b are not both negative +template +inline constexpr bool signs_differ(const T& a, const U& b) { + return is_negative(a) != is_negative(b); +} + +// Suppress sign compare warning when compiling with GCC +// as later does not account for short-circuit rule before +// raising the warning, see https://godbolt.org/z/Tr3Msnz99 +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wsign-compare" +#endif + +/// Returns true if x is greater than the greatest value of the type Limit +template +inline constexpr bool greater_than_max(const T& x) { + constexpr bool can_overflow = + std::numeric_limits::digits > std::numeric_limits::digits; + return can_overflow && x > std::numeric_limits::max(); +} + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +/// Returns true if x is less than the lowest value of type Limit +/// NOTE: Will fail on an unsigned custom type +/// For the most part it's possible to fix this if +/// the custom type has a constexpr constructor. +/// However, notably, c10::Half does not : +template +inline constexpr bool less_than_lowest(const T& x) { + if constexpr (std::is_unsigned_v) { + // x is unsigned, so it can never be below the lowest value of any type. + return false; + } else if constexpr (std::is_unsigned_v) { + // Limit is unsigned, so its lowest value is zero. + return x < T(0); + } else { + return x < std::numeric_limits::lowest(); + } +} + +} // namespace c10 + +C10_CLANG_DIAGNOSTIC_POP() + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::greater_than_max; +using c10::is_negative; +using c10::less_than_lowest; +using c10::signs_differ; +using c10::signum; +HIDDEN_NAMESPACE_END(torch, headeronly) diff --git a/include/torch/headeronly/util/bit_cast.h b/include/torch/headeronly/util/bit_cast.h new file mode 100644 index 0000000..3f357f8 --- /dev/null +++ b/include/torch/headeronly/util/bit_cast.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include + +#include + +#if __has_include() && (defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L) +#include +#define C10_HAVE_STD_BIT_CAST 1 +#else +#define C10_HAVE_STD_BIT_CAST 0 +#endif // __has_include() && (__cplusplus >= 202002L || + // (defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L)) + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +#if C10_HAVE_STD_BIT_CAST +using std::bit_cast; +#else +// Implementations of std::bit_cast() from C++ 20. +// +// This is a less sketchy version of reinterpret_cast. +// +// See https://en.cppreference.com/w/cpp/numeric/bit_cast for more +// information as well as the source of our implementations. +template +C10_HOST_DEVICE std::enable_if_t< + sizeof(To) == sizeof(From) && std::is_trivially_copyable_v && + std::is_trivially_copyable_v, + To> +// constexpr support needs compiler magic +bit_cast(const From& src) noexcept { + static_assert( + std::is_trivially_constructible_v, + "This implementation additionally requires " + "destination type to be trivially constructible"); + + To dst; + std::memcpy(&dst, &src, sizeof(To)); + return dst; +} +#endif // C10_HAVE_STD_BIT_CAST +#undef C10_HAVE_STD_BIT_CAST + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace c10 { +using torch::headeronly::bit_cast; +} // namespace c10 diff --git a/include/torch/headeronly/util/complex.h b/include/torch/headeronly/util/complex.h new file mode 100644 index 0000000..265b250 --- /dev/null +++ b/include/torch/headeronly/util/complex.h @@ -0,0 +1,676 @@ +#pragma once + +#include + +#include +#include +#include + +#if defined(__CUDACC__) || defined(__HIPCC__) +#include +#endif + +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion") +#endif +#if C10_CLANG_HAS_WARNING("-Wfloat-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wfloat-conversion") +#endif + +namespace c10 { + +// c10::complex is an implementation of complex numbers that aims +// to work on all devices supported by PyTorch +// +// Most of the APIs duplicates std::complex +// Reference: https://en.cppreference.com/w/cpp/numeric/complex +// +// [NOTE: Complex Operator Unification] +// Operators currently use a mix of std::complex, thrust::complex, and +// c10::complex internally. The end state is that all operators will use +// c10::complex internally. Until then, there may be some hacks to support all +// variants. +// +// +// [Note on Constructors] +// +// The APIs of constructors are mostly copied from C++ standard: +// https://en.cppreference.com/w/cpp/numeric/complex/complex +// +// Since C++14, all constructors are constexpr in std::complex +// +// There are three types of constructors: +// - initializing from real and imag: +// `constexpr complex( const T& re = T(), const T& im = T() );` +// - implicitly-declared copy constructor +// - converting constructors +// +// Converting constructors: +// - std::complex defines converting constructor between float/double/long +// double, +// while we define converting constructor between float/double. +// - For these converting constructors, upcasting is implicit, downcasting is +// explicit. +// - We also define explicit casting from std::complex/thrust::complex +// - Note that the conversion from thrust is not constexpr, because +// thrust does not define them as constexpr ???? +// +// +// [Operator =] +// +// The APIs of operator = are mostly copied from C++ standard: +// https://en.cppreference.com/w/cpp/numeric/complex/operator%3D +// +// Since C++20, all operator= are constexpr. Although we are not building with +// C++20, we also obey this behavior. +// +// There are three types of assign operator: +// - Assign a real value from the same scalar type +// - In std, this is templated as complex& operator=(const T& x) +// with specialization `complex& operator=(T x)` for float/double/long +// double Since we only support float and double, on will use `complex& +// operator=(T x)` +// - Copy assignment operator and converting assignment operator +// - There is no specialization of converting assignment operators, which type +// is +// convertible is solely dependent on whether the scalar type is convertible +// +// In addition to the standard assignment, we also provide assignment operators +// with std and thrust +// +// +// [Casting operators] +// +// std::complex does not have casting operators. We define casting operators +// casting to std::complex and thrust::complex +// +// +// [Operator ""] +// +// std::complex has custom literals `i`, `if` and `il` defined in namespace +// `std::literals::complex_literals`. We define our own custom literals in the +// namespace `c10::complex_literals`. Our custom literals does not follow the +// same behavior as in std::complex, instead, we define _if, _id to construct +// float/double complex literals. +// +// +// [real() and imag()] +// +// In C++20, there are two overload of these functions, one it to return the +// real/imag, another is to set real/imag, they are both constexpr. We follow +// this design. +// +// +// [Operator +=,-=,*=,/=] +// +// Since C++20, these operators become constexpr. In our implementation, they +// are also constexpr. +// +// There are two types of such operators: operating with a real number, or +// operating with another complex number. For the operating with a real number, +// the generic template form has argument type `const T &`, while the overload +// for float/double/long double has `T`. We will follow the same type as +// float/double/long double in std. +// +// [Unary operator +-] +// +// Since C++20, they are constexpr. We also make them expr +// +// [Binary operators +-*/] +// +// Each operator has three versions (taking + as example): +// - complex + complex +// - complex + real +// - real + complex +// +// [Operator ==, !=] +// +// Each operator has three versions (taking == as example): +// - complex == complex +// - complex == real +// - real == complex +// +// Some of them are removed on C++20, but we decide to keep them +// +// [Operator <<, >>] +// +// These are implemented by casting to std::complex +// +// +// +// TODO(@zasdfgbnm): c10::complex is not currently supported, +// because: +// - lots of members and functions of c10::Half are not constexpr +// - thrust::complex only support float and double + +template +struct alignas(sizeof(T) * 2) complex { + using value_type = T; + + T real_ = T(0); + T imag_ = T(0); + + constexpr complex() = default; + C10_HOST_DEVICE constexpr complex(const T& re, const T& im = T()) + : real_(re), imag_(im) {} + template + explicit constexpr complex(const std::complex& other) + : complex(other.real(), other.imag()) {} +#if defined(__CUDACC__) || defined(__HIPCC__) + template + explicit C10_HOST_DEVICE complex(const thrust::complex& other) + : real_(other.real()), imag_(other.imag()) {} +// NOTE can not be implemented as follows due to ROCm bug: +// explicit C10_HOST_DEVICE complex(const thrust::complex &other): +// complex(other.real(), other.imag()) {} +#endif + + // Use SFINAE to specialize casting constructor for c10::complex and + // c10::complex + template + C10_HOST_DEVICE explicit constexpr complex( + const std::enable_if_t, complex>& other) + : real_(other.real_), imag_(other.imag_) {} + template + C10_HOST_DEVICE constexpr complex( + const std::enable_if_t, complex>& other) + : real_(other.real_), imag_(other.imag_) {} + + constexpr complex& operator=(T re) { + real_ = re; + imag_ = 0; + return *this; + } + + constexpr complex& operator+=(T re) { + real_ += re; + return *this; + } + + constexpr complex& operator-=(T re) { + real_ -= re; + return *this; + } + + constexpr complex& operator*=(T re) { + real_ *= re; + imag_ *= re; + return *this; + } + + constexpr complex& operator/=(T re) { + real_ /= re; + imag_ /= re; + return *this; + } + + template + constexpr complex& operator=(const complex& rhs) { + real_ = rhs.real(); + imag_ = rhs.imag(); + return *this; + } + + template + constexpr complex& operator+=(const complex& rhs) { + real_ += rhs.real(); + imag_ += rhs.imag(); + return *this; + } + + template + constexpr complex& operator-=(const complex& rhs) { + real_ -= rhs.real(); + imag_ -= rhs.imag(); + return *this; + } + + template + constexpr complex& operator*=(const complex& rhs) { + // (a + bi) * (c + di) = (a*c - b*d) + (a * d + b * c) i + T a = real_; + T b = imag_; + U c = rhs.real(); + U d = rhs.imag(); + real_ = a * c - b * d; + imag_ = a * d + b * c; + return *this; + } + +#ifdef __APPLE__ +#define FORCE_INLINE_APPLE __attribute__((always_inline)) +#else +#define FORCE_INLINE_APPLE +#endif + template + constexpr FORCE_INLINE_APPLE complex& operator/=(const complex& rhs) + __ubsan_ignore_float_divide_by_zero__ { + // (a + bi) / (c + di) = (ac + bd)/(c^2 + d^2) + (bc - ad)/(c^2 + d^2) i + // the calculation below follows numpy's complex division + T a = real_; + T b = imag_; + U c = rhs.real(); + U d = rhs.imag(); + +#if defined(__GNUC__) && !defined(__clang__) + // std::abs is already constexpr by gcc + auto abs_c = std::abs(c); + auto abs_d = std::abs(d); +#else + auto abs_c = c < 0 ? -c : c; + auto abs_d = d < 0 ? -d : d; +#endif + + if (abs_c >= abs_d) { + if (abs_c == U(0) && abs_d == U(0)) { + /* divide by zeros should yield a complex inf or nan */ + real_ = a / abs_c; + imag_ = b / abs_d; + } else { + auto rat = d / c; + auto scl = U(1.0) / (c + d * rat); + real_ = (a + b * rat) * scl; + imag_ = (b - a * rat) * scl; + } + } else { + auto rat = c / d; + auto scl = U(1.0) / (d + c * rat); + real_ = (a * rat + b) * scl; + imag_ = (b * rat - a) * scl; + } + return *this; + } +#undef FORCE_INLINE_APPLE + + template + constexpr complex& operator=(const std::complex& rhs) { + real_ = rhs.real(); + imag_ = rhs.imag(); + return *this; + } + +#if defined(__CUDACC__) || defined(__HIPCC__) + template + C10_HOST_DEVICE complex& operator=(const thrust::complex& rhs) { + real_ = rhs.real(); + imag_ = rhs.imag(); + return *this; + } +#endif + + template + explicit constexpr operator std::complex() const { + return std::complex(std::complex(real(), imag())); + } + +#if defined(__CUDACC__) || defined(__HIPCC__) + template + C10_HOST_DEVICE explicit operator thrust::complex() const { + return static_cast>(thrust::complex(real(), imag())); + } +#endif + + // consistent with NumPy behavior + explicit constexpr operator bool() const { + return real() || imag(); + } + + C10_HOST_DEVICE constexpr T real() const { + return real_; + } + constexpr void real(T value) { + real_ = value; + } + C10_HOST_DEVICE constexpr T imag() const { + return imag_; + } + constexpr void imag(T value) { + imag_ = value; + } +}; + +namespace complex_literals { + +constexpr complex operator""_if(long double imag) { + return complex(0.0f, static_cast(imag)); +} + +constexpr complex operator""_id(long double imag) { + return complex(0.0, static_cast(imag)); +} + +constexpr complex operator""_if(unsigned long long imag) { + return complex(0.0f, static_cast(imag)); +} + +constexpr complex operator""_id(unsigned long long imag) { + return complex(0.0, static_cast(imag)); +} + +} // namespace complex_literals + +template +constexpr complex operator+(const complex& val) { + return val; +} + +template +constexpr complex operator-(const complex& val) { + return complex(-val.real(), -val.imag()); +} + +template +constexpr complex operator+(const complex& lhs, const complex& rhs) { + complex result = lhs; + return result += rhs; +} + +template +constexpr complex operator+(const complex& lhs, const T& rhs) { + complex result = lhs; + return result += rhs; +} + +template +constexpr complex operator+(const T& lhs, const complex& rhs) { + return complex(lhs + rhs.real(), rhs.imag()); +} + +template +constexpr complex operator-(const complex& lhs, const complex& rhs) { + complex result = lhs; + return result -= rhs; +} + +template +constexpr complex operator-(const complex& lhs, const T& rhs) { + complex result = lhs; + return result -= rhs; +} + +template +constexpr complex operator-(const T& lhs, const complex& rhs) { + complex result = -rhs; + return result += lhs; +} + +template +constexpr complex operator*(const complex& lhs, const complex& rhs) { + complex result = lhs; + return result *= rhs; +} + +template +constexpr complex operator*(const complex& lhs, const T& rhs) { + complex result = lhs; + return result *= rhs; +} + +template +constexpr complex operator*(const T& lhs, const complex& rhs) { + complex result = rhs; + return result *= lhs; +} + +template +constexpr complex operator/(const complex& lhs, const complex& rhs) { + complex result = lhs; + return result /= rhs; +} + +template +constexpr complex operator/(const complex& lhs, const T& rhs) { + complex result = lhs; + return result /= rhs; +} + +template +constexpr complex operator/(const T& lhs, const complex& rhs) { + complex result(lhs, T()); + return result /= rhs; +} + +// Define operators between integral scalars and c10::complex. std::complex does +// not support this when T is a floating-point number. This is useful because it +// saves a lot of "static_cast" when operate a complex and an integer. This +// makes the code both less verbose and potentially more efficient. +#define COMPLEX_INTEGER_OP_TEMPLATE_CONDITION \ + typename std::enable_if_t< \ + std::is_floating_point_v && std::is_integral_v, \ + int> = 0 + +template +constexpr c10::complex operator+(const c10::complex& a, const iT& b) { + return a + static_cast(b); +} + +template +constexpr c10::complex operator+(const iT& a, const c10::complex& b) { + return static_cast(a) + b; +} + +template +constexpr c10::complex operator-(const c10::complex& a, const iT& b) { + return a - static_cast(b); +} + +template +constexpr c10::complex operator-(const iT& a, const c10::complex& b) { + return static_cast(a) - b; +} + +template +constexpr c10::complex operator*(const c10::complex& a, const iT& b) { + return a * static_cast(b); +} + +template +constexpr c10::complex operator*(const iT& a, const c10::complex& b) { + return static_cast(a) * b; +} + +template +constexpr c10::complex operator/(const c10::complex& a, const iT& b) { + return a / static_cast(b); +} + +template +constexpr c10::complex operator/(const iT& a, const c10::complex& b) { + return static_cast(a) / b; +} + +#undef COMPLEX_INTEGER_OP_TEMPLATE_CONDITION + +template +constexpr bool operator==(const complex& lhs, const complex& rhs) { + return (lhs.real() == rhs.real()) && (lhs.imag() == rhs.imag()); +} + +template +constexpr bool operator==(const complex& lhs, const T& rhs) { + return (lhs.real() == rhs) && (lhs.imag() == T()); +} + +template +constexpr bool operator==(const T& lhs, const complex& rhs) { + return (lhs == rhs.real()) && (T() == rhs.imag()); +} + +template +constexpr bool operator!=(const complex& lhs, const complex& rhs) { + return !(lhs == rhs); +} + +template +constexpr bool operator!=(const complex& lhs, const T& rhs) { + return !(lhs == rhs); +} + +template +constexpr bool operator!=(const T& lhs, const complex& rhs) { + return !(lhs == rhs); +} + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const complex& x) { + return (os << static_cast>(x)); +} + +template +std::basic_istream& operator>>( + std::basic_istream& is, + complex& x) { + std::complex tmp; + is >> tmp; + x = tmp; + return is; +} + +template +C10_HOST_DEVICE complex polar(const T& r, const T& theta = T()) { +#if defined(__CUDACC__) || defined(__HIPCC__) + return static_cast>(thrust::polar(r, theta)); +#else + // std::polar() requires r >= 0, so spell out the explicit implementation to + // avoid a branch. + return complex(r * std::cos(theta), r * std::sin(theta)); +#endif +} + +template <> +struct alignas(4) complex { + Half real_; + Half imag_; + + // Constructors + complex() = default; + // Half constructor is not constexpr so the following constructor can't + // be constexpr + C10_HOST_DEVICE explicit inline complex(const Half& real, const Half& imag) + : real_(real), imag_(imag) {} + C10_HOST_DEVICE inline complex(const c10::complex& value) + : real_(value.real()), imag_(value.imag()) {} + + // Conversion operator + inline C10_HOST_DEVICE operator c10::complex() const { + return {real_, imag_}; + } + + constexpr C10_HOST_DEVICE Half real() const { + return real_; + } + constexpr C10_HOST_DEVICE Half imag() const { + return imag_; + } + + C10_HOST_DEVICE complex& operator+=(const complex& other) { + real_ = static_cast(real_) + static_cast(other.real_); + imag_ = static_cast(imag_) + static_cast(other.imag_); + return *this; + } + + C10_HOST_DEVICE complex& operator-=(const complex& other) { + real_ = static_cast(real_) - static_cast(other.real_); + imag_ = static_cast(imag_) - static_cast(other.imag_); + return *this; + } + + C10_HOST_DEVICE complex& operator*=(const complex& other) { + auto a = static_cast(real_); + auto b = static_cast(imag_); + auto c = static_cast(other.real()); + auto d = static_cast(other.imag()); + real_ = a * c - b * d; + imag_ = a * d + b * c; + return *this; + } +}; + +template <> +struct alignas(4) complex { + BFloat16 real_; + BFloat16 imag_; + + // Constructors + complex() = default; + // BFloat16 constructor is not constexpr so the following constructor can't + // be constexpr + C10_HOST_DEVICE explicit inline complex( + const BFloat16& real, + const BFloat16& imag) + : real_(real), imag_(imag) {} + C10_HOST_DEVICE inline complex(const c10::complex& value) + : real_(value.real()), imag_(value.imag()) {} + + // Conversion operator + inline C10_HOST_DEVICE operator c10::complex() const { + return {real_, imag_}; + } + + constexpr C10_HOST_DEVICE BFloat16 real() const { + return real_; + } + constexpr C10_HOST_DEVICE BFloat16 imag() const { + return imag_; + } + + C10_HOST_DEVICE complex& operator+=( + const complex& other) { + real_ = static_cast(real_) + static_cast(other.real_); + imag_ = static_cast(imag_) + static_cast(other.imag_); + return *this; + } + + C10_HOST_DEVICE complex& operator-=( + const complex& other) { + real_ = static_cast(real_) - static_cast(other.real_); + imag_ = static_cast(imag_) - static_cast(other.imag_); + return *this; + } + + C10_HOST_DEVICE complex& operator*=( + const complex& other) { + auto a = static_cast(real_); + auto b = static_cast(imag_); + auto c = static_cast(other.real()); + auto d = static_cast(other.imag()); + real_ = a * c - b * d; + imag_ = a * d + b * c; + return *this; + } +}; + +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::complex; +using c10::operator+; +using c10::operator-; +using c10::operator*; +using c10::operator/; +using c10::operator+=; +using c10::operator-=; +using c10::operator*=; +using c10::operator/=; +using c10::operator==; +using c10::operator!=; +using c10::operator<<; +using c10::operator>>; +using c10::polar; + +namespace complex_literals { +using c10::complex_literals::operator""_if; +using c10::complex_literals::operator""_id; +} // namespace complex_literals + +HIDDEN_NAMESPACE_END(torch, headeronly) + +C10_CLANG_DIAGNOSTIC_POP() + +#define C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H +// utilities for complex types +#include // IWYU pragma: keep +#undef C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H diff --git a/include/torch/headeronly/util/complex_utils.h b/include/torch/headeronly/util/complex_utils.h new file mode 100644 index 0000000..ddc66ff --- /dev/null +++ b/include/torch/headeronly/util/complex_utils.h @@ -0,0 +1,48 @@ +#pragma once + +#if !defined(C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H) +#error \ + "torch/headeronly/util/complex_utils.h is not meant to be individually included. Include torch/headeronly/util/complex.h instead." +#endif + +#include + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +template +struct is_complex : public std::false_type {}; + +template +struct is_complex> : public std::true_type {}; + +template +struct is_complex> : public std::true_type {}; + +// Extract double from std::complex; is identity otherwise +// TODO: Write in more idiomatic C++17 +template +struct scalar_value_type { + using type = T; +}; +template +struct scalar_value_type> { + using type = T; +}; +template +struct scalar_value_type> { + using type = T; +}; + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace std { + +template +class numeric_limits> : public numeric_limits {}; + +template +bool isnan(const c10::complex& v) { + return std::isnan(v.real()) || std::isnan(v.imag()); +} + +} // namespace std diff --git a/include/torch/headeronly/util/floating_point_utils.h b/include/torch/headeronly/util/floating_point_utils.h new file mode 100644 index 0000000..1e60bd8 --- /dev/null +++ b/include/torch/headeronly/util/floating_point_utils.h @@ -0,0 +1,38 @@ +#pragma once + +#include +#include +#include + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly, detail) + +C10_HOST_DEVICE inline float fp32_from_bits(uint32_t w) { +#if defined(__OPENCL_VERSION__) + return as_float(w); +#elif defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + return __uint_as_float((unsigned int)w); +#elif defined(__INTEL_COMPILER) + return _castu32_f32(w); +#else + return torch::headeronly::bit_cast(w); +#endif +} + +C10_HOST_DEVICE inline uint32_t fp32_to_bits(float f) { +#if defined(__OPENCL_VERSION__) + return as_uint(f); +#elif defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + return (uint32_t)__float_as_uint(f); +#elif defined(__INTEL_COMPILER) + return _castf32_u32(f); +#else + return torch::headeronly::bit_cast(f); +#endif +} + +HIDDEN_NAMESPACE_END(torch, headeronly, detail) + +namespace c10::detail { +using torch::headeronly::detail::fp32_from_bits; +using torch::headeronly::detail::fp32_to_bits; +} // namespace c10::detail diff --git a/include/torch/headeronly/util/irange.h b/include/torch/headeronly/util/irange.h new file mode 100644 index 0000000..0d1bf44 --- /dev/null +++ b/include/torch/headeronly/util/irange.h @@ -0,0 +1,137 @@ +// Copyright 2004-present Facebook. All Rights Reserved. + +#pragma once + +#include +#include + +#include +#include +#include +#include + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +namespace detail { + +template < + typename I, + bool one_sided = false, + std::enable_if_t, int> = 0> +struct integer_iterator { + using iterator_category = std::input_iterator_tag; + using value_type = I; + using difference_type = std::ptrdiff_t; + using pointer = I*; + using reference = I&; + + C10_ALWAYS_INLINE explicit constexpr integer_iterator(I val) : value(val) {} + + C10_ALWAYS_INLINE constexpr I operator*() const { + return value; + } + + C10_ALWAYS_INLINE constexpr I const* operator->() const { + return &value; + } + + C10_ALWAYS_INLINE constexpr integer_iterator& operator++() { + ++value; + return *this; + } + + C10_ALWAYS_INLINE constexpr integer_iterator operator++(int) { + const auto copy = *this; + ++*this; + return copy; + } + + C10_ALWAYS_INLINE constexpr bool operator==( + const integer_iterator& other) const { + if constexpr (one_sided) { + // Range-for loops' end test is `begin != end`, not `begin < + // end`. To handle `irange(n)` where n < 0 (which should be + // empty), we just make `begin != end` fail whenever `end` is + // negative. + return is_negative(other.value) || value == other.value; + } else { + return value == other.value; + } + // Suppress "warning: missing return statement at end of non-void function" + // which Nvidia's Robert Crovella confirms is an NVCC compiler error + // here https://stackoverflow.com/a/64561686/752843 on 2020-10-27 + // `__builtin_unreachable();` would be best here, but it's not + // available with all compilers. So we instead return an arbitrary + // value trusting that this line will, in fact, never be reached. + return false; // Horrible hack + } + + C10_ALWAYS_INLINE constexpr bool operator!=( + const integer_iterator& other) const { + return !(*this == other); + } + + protected: + I value; +}; + +} // namespace detail + +template < + typename I, + bool one_sided = false, + std::enable_if_t, bool> = true> +struct integer_range { + public: + C10_ALWAYS_INLINE constexpr integer_range(I begin, I end) + : begin_(begin), end_(end) {} + using iterator = detail::integer_iterator; + C10_ALWAYS_INLINE constexpr iterator begin() const { + return begin_; + } + C10_ALWAYS_INLINE constexpr iterator end() const { + return end_; + } + + private: + iterator begin_; + iterator end_; +}; + +/// Creates an integer range for the half-open interval [begin, end) +/// If end<=begin, then the range is empty. +/// The range has the type of the `end` integer; `begin` integer is +/// cast to this type. +template < + typename Integer1, + typename Integer2, + std::enable_if_t, bool> = true, + std::enable_if_t, bool> = true> +C10_ALWAYS_INLINE constexpr integer_range irange( + Integer1 begin, + Integer2 end) { + // If end<=begin then the range is empty; we can achieve this effect by + // choosing the larger of {begin, end} as the loop terminator + return { + static_cast(begin), + std::max(static_cast(begin), end)}; +} + +/// Creates an integer range for the half-open interval [0, end) +/// If end<=begin, then the range is empty +template < + typename Integer, + std::enable_if_t, bool> = true> +C10_ALWAYS_INLINE constexpr integer_range irange(Integer end) { + return {Integer(), end}; +} + +HIDDEN_NAMESPACE_END(torch, headeronly) + +namespace c10 { +using torch::headeronly::integer_range; +using torch::headeronly::irange; +namespace detail { +using torch::headeronly::detail::integer_iterator; +} // namespace detail +} // namespace c10 diff --git a/include/torch/headeronly/util/overflows.h b/include/torch/headeronly/util/overflows.h new file mode 100644 index 0000000..6e68311 --- /dev/null +++ b/include/torch/headeronly/util/overflows.h @@ -0,0 +1,120 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace c10 { +// In some versions of MSVC, there will be a compiler error when building. +// C4146: unary minus operator applied to unsigned type, result still unsigned +// C4804: unsafe use of type 'bool' in operation +// It can be addressed by disabling the following warning. +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4146) +#pragma warning(disable : 4804) +#pragma warning(disable : 4018) +#endif + +// The overflow checks may involve float to int conversion which may +// trigger precision loss warning. Re-enable the warning once the code +// is fixed. See T58053069. +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion") +#endif + +// bool can be converted to any type. +// Without specializing on bool, in pytorch_linux_trusty_py2_7_9_build: +// `error: comparison of constant '255' with boolean expression is always false` +// for `f > limit::max()` below +template +std::enable_if_t, bool> overflows( + From /*f*/, + bool strict_unsigned [[maybe_unused]] = false) { + return false; +} + +// skip isnan and isinf check for integral types +template +std::enable_if_t && !std::is_same_v, bool> +overflows(From f, bool strict_unsigned = false) { + using limit = std::numeric_limits< + typename torch::headeronly::scalar_value_type::type>; + if constexpr (!limit::is_signed && std::numeric_limits::is_signed) { + // allow for negative numbers to wrap using two's complement arithmetic. + // For example, with uint8, this allows for `a - b` to be treated as + // `a + 255 * b`. + if (!strict_unsigned) { + return c10::greater_than_max(f) || + (c10::is_negative(f) && + -static_cast(f) > static_cast(limit::max())); + } + } + return c10::less_than_lowest(f) || c10::greater_than_max(f); +} + +template +std::enable_if_t, bool> overflows( + From f, + bool strict_unsigned [[maybe_unused]] = false) { + using ToScalar = typename torch::headeronly::scalar_value_type::type; + using limit = std::numeric_limits; + if (limit::has_infinity && std::isinf(static_cast(f))) { + return false; + } + if (!limit::has_quiet_NaN && (f != f)) { + return true; + } + if constexpr (std::is_integral_v) { + // limit::max() for wide integer types is NOT exactly representable in + // floating point (e.g. int64 max = 2^63-1 rounds up to 2^63), so `f > + // limit::max()` lets a just-out-of-range value like 2^63 slip through and + // then become INT64_MIN via static_cast. Compare against the + // exactly-representable upper bound max()+1 == 2^digits instead. lowest() + // is 0 or a negated power of two, so it stays exact. (digits-1 keeps the + // shift < 64 for the uint64 case; the *2 recovers 2^digits without a 1<<64 + // overflow.) + constexpr int digits = limit::digits; + constexpr From upper = + static_cast(uint64_t{1} << (digits - 1)) * From{2}; + return f < static_cast(limit::lowest()) || f >= upper; + } + return f < limit::lowest() || f > limit::max(); +} + +C10_CLANG_DIAGNOSTIC_POP() + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +template +std::enable_if_t::value, bool> overflows( + From f, + bool strict_unsigned = false) { + // casts from complex to real are considered to overflow if the + // imaginary component is non-zero + if (!torch::headeronly::is_complex::value && f.imag() != 0) { + return true; + } + // Check for overflow componentwise + // (Technically, the imag overflow check is guaranteed to be false + // when !is_complex, but any optimizer worth its salt will be + // able to figure it out.) + return c10::overflows< + typename torch::headeronly::scalar_value_type::type, + typename From::value_type>(f.real(), strict_unsigned) || + c10::overflows< + typename torch::headeronly::scalar_value_type::type, + typename From::value_type>(f.imag(), strict_unsigned); +} +} // namespace c10 + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) +using c10::overflows; +HIDDEN_NAMESPACE_END(torch, headeronly) diff --git a/lib/libtorch-cmsis-nn-cortex-m55.a b/lib/libtorch-cmsis-nn-cortex-m55.a new file mode 100644 index 0000000..d583e65 Binary files /dev/null and b/lib/libtorch-cmsis-nn-cortex-m55.a differ diff --git a/lib/libtorch-cmsis-nn-cortex-m7.a b/lib/libtorch-cmsis-nn-cortex-m7.a new file mode 100644 index 0000000..b388c9a Binary files /dev/null and b/lib/libtorch-cmsis-nn-cortex-m7.a differ diff --git a/lib/libtorch-cortex-m55.a b/lib/libtorch-cortex-m55.a new file mode 100644 index 0000000..4cebc72 Binary files /dev/null and b/lib/libtorch-cortex-m55.a differ diff --git a/lib/libtorch-cortex-m7.a b/lib/libtorch-cortex-m7.a new file mode 100644 index 0000000..7248ec7 Binary files /dev/null and b/lib/libtorch-cortex-m7.a differ