|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <cstdint> |
| 4 | +#include <type_traits> |
| 5 | + |
| 6 | +#include "glog/logging.h" |
| 7 | + |
| 8 | +#include "infini_train/include/common/cpu/common_cpu.h" |
| 9 | + |
| 10 | +namespace infini_train { |
| 11 | + |
| 12 | +struct Scalar { |
| 13 | + enum class Kind : uint8_t { kBool, kDouble, kInt64, kUInt64 }; |
| 14 | + |
| 15 | + Scalar() : kind(Kind::kInt64), i(0) {} |
| 16 | + Scalar(bool v) : kind(Kind::kBool), u(v ? 1 : 0) {} |
| 17 | + |
| 18 | + template <typename T, typename std::enable_if_t<std::is_floating_point_v<T>, int> = 0> |
| 19 | + Scalar(T v) : kind(Kind::kDouble), d(static_cast<double>(v)) {} |
| 20 | + |
| 21 | + template <typename T, |
| 22 | + typename std::enable_if_t<std::is_integral_v<T> && std::is_signed_v<T> && !std::is_same_v<T, bool>, int> |
| 23 | + = 0> |
| 24 | + Scalar(T v) : kind(Kind::kInt64), i(static_cast<int64_t>(v)) {} |
| 25 | + |
| 26 | + template <typename T, |
| 27 | + typename std::enable_if_t<std::is_integral_v<T> && std::is_unsigned_v<T> && !std::is_same_v<T, bool>, int> |
| 28 | + = 0> |
| 29 | + Scalar(T v) : kind(Kind::kUInt64), u(static_cast<uint64_t>(v)) {} |
| 30 | + |
| 31 | + Scalar(FP16 v) : kind(Kind::kDouble), d(static_cast<float>(v)) {} |
| 32 | + Scalar(BF16 v) : kind(Kind::kDouble), d(static_cast<float>(v)) {} |
| 33 | + |
| 34 | + template <typename T> T to() const { |
| 35 | + switch (kind) { |
| 36 | + case Kind::kBool: |
| 37 | + return common::cpu::Cast<T>(u != 0); |
| 38 | + case Kind::kDouble: |
| 39 | + return common::cpu::Cast<T>(d); |
| 40 | + case Kind::kInt64: |
| 41 | + return common::cpu::Cast<T>(i); |
| 42 | + case Kind::kUInt64: |
| 43 | + return common::cpu::Cast<T>(u); |
| 44 | + default: |
| 45 | + LOG(FATAL) << "Unknown scalar kind"; |
| 46 | + } |
| 47 | + |
| 48 | + std::abort(); |
| 49 | + } |
| 50 | + |
| 51 | + Kind kind; |
| 52 | + union { |
| 53 | + double d; |
| 54 | + int64_t i; |
| 55 | + uint64_t u; |
| 56 | + }; |
| 57 | +}; |
| 58 | + |
| 59 | +} // namespace infini_train |
0 commit comments