← Back to C-Kernel-Engine Docs Doxygen Source Documentation
Loading...
Searching...
No Matches
cast_bf16_checked.c
Go to the documentation of this file.
1#include <math.h>
2#include <stddef.h>
3#include <stdint.h>
4
5#include "bf16_utils.h"
6
7static int checked_cast_spans(const void *input, size_t element_in, const void *output,
8 size_t element_out, size_t count)
9{
10 const uintptr_t from = (uintptr_t)input, to = (uintptr_t)output;
11 if (!from || !to || !count || from % element_in || to % element_out ||
12 count > (UINTPTR_MAX - from) / element_in || count > (UINTPTR_MAX - to) / element_out)
13 return 0;
14 return from + count * element_in <= to || to + count * element_out <= from;
15}
16
17int ck_cast_f32_bf16_checked(const float *input, uint16_t *output, size_t count)
18{
19 if (!checked_cast_spans(input, sizeof(*input), output, sizeof(*output), count))
20 return -2;
21 for (size_t i = 0; i < count; ++i)
22 if (!isfinite(input[i]) || !isfinite(bf16_to_float(float_to_bf16(input[i]))))
23 return -3;
24 for (size_t i = 0; i < count; ++i)
25 output[i] = float_to_bf16(input[i]);
26 return 0;
27}
28
29int ck_cast_bf16_f32_checked(const uint16_t *input, float *output, size_t count)
30{
31 if (!checked_cast_spans(input, sizeof(*input), output, sizeof(*output), count))
32 return -2;
33 for (size_t i = 0; i < count; ++i)
34 if (!isfinite(bf16_to_float(input[i])))
35 return -3;
36 for (size_t i = 0; i < count; ++i)
37 output[i] = bf16_to_float(input[i]);
38 return 0;
39}
static uint16_t float_to_bf16(float f)
Definition bf16_utils.h:90
static float bf16_to_float(uint16_t v)
Definition bf16_utils.h:38
static int checked_cast_spans(const void *input, size_t element_in, const void *output, size_t element_out, size_t count)
int ck_cast_f32_bf16_checked(const float *input, uint16_t *output, size_t count)
int ck_cast_bf16_f32_checked(const uint16_t *input, float *output, size_t count)
const uint8_t size_t count
Definition true_bpe.h:211