-
Notifications
You must be signed in to change notification settings - Fork 13
/
bfloat16.cc
2090 lines (1973 loc) · 56.2 KB
/
bfloat16.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
/* Modified by [email protected] - Modifications to allow a standalone build
and remove requirements for pybind11 and other tensorflow dependencies
Add support for scalar operations and python numeric types
*/
#include <iostream>
#include <array>
#include <locale>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// #define DEBUG_CALLS
#include <Python.h>
#include <cinttypes>
#include <patchlevel.h>
#include <vector>
#ifdef DEBUG_CALLS
#include <iostream>
#endif
#include "eigen/Eigen/Core"
#include <fenv.h>
#include "numpy/arrayobject.h"
#include "numpy/ufuncobject.h"
#include <memory>
namespace greenwaves
{
namespace
{
using bfloat16 = Eigen::bfloat16;
using uint8 = std::uint8_t;
using int8 = std::int8_t;
using uint16 = std::uint16_t;
using int16 = std::int16_t;
using uint64 = std::uint64_t;
struct PyDecrefDeleter
{
void operator()(PyObject *p) const { Py_DECREF(p); }
};
// Safe container for an owned PyObject. On destruction, the reference count of
// the contained object will be decremented.
using Safe_PyObjectPtr = std::unique_ptr<PyObject, PyDecrefDeleter>;
Safe_PyObjectPtr make_safe(PyObject *object)
{
return Safe_PyObjectPtr(object);
}
bool PyLong_CheckNoOverflow(PyObject *object)
{
if (!PyLong_Check(object))
{
return false;
}
int overflow = 0;
PyLong_AsLongAndOverflow(object, &overflow);
return (overflow == 0);
}
// Registered numpy type ID. Global variable populated by the registration code.
// Protected by the GIL.
int npy_bfloat16 = NPY_NOTYPE;
// Forward declaration.
extern PyTypeObject bfloat16_type;
extern PyArray_Descr NPyBfloat16_Descr;
// Pointer to the bfloat16 type object we are using. This is either a pointer
// to bfloat16_type, if we choose to register it, or to the bfloat16 type
// registered by another system into NumPy.
PyTypeObject *bfloat16_type_ptr = nullptr;
// Representation of a Python bfloat16 object.
struct PyBfloat16
{
PyObject_HEAD; // Python object header
bfloat16 value;
};
// Returns true if 'object' is a PyBfloat16.
bool PyBfloat16_Check(PyObject *object)
{
return PyObject_IsInstance(object, reinterpret_cast<PyObject *>(&bfloat16_type));
}
// Extracts the value of a PyBfloat16 object.
bfloat16 PyBfloat16_Bfloat16(PyObject *object)
{
return reinterpret_cast<PyBfloat16 *>(object)->value;
}
// Constructs a PyBfloat16 object from a bfloat16.
PyObject *PyBfloat16_FromBfloat16(bfloat16 x)
{
return PyArray_Scalar(&x, &NPyBfloat16_Descr, NULL);
}
// Converts a Python object to a bfloat16 value. Returns true on success,
// returns false and reports a Python error on failure.
bool CastToBfloat16(PyObject *arg, bfloat16 *output)
{
if (PyBfloat16_Check(arg))
{
*output = PyBfloat16_Bfloat16(arg);
return true;
}
if (PyFloat_Check(arg))
{
double d = PyFloat_AsDouble(arg);
if (PyErr_Occurred())
{
return false;
}
// TODO(phawkins): check for overflow
*output = bfloat16(d);
return true;
}
if (PyLong_CheckNoOverflow(arg))
{
long l = PyLong_AsLong(arg); // NOLINT
if (PyErr_Occurred())
{
return false;
}
// TODO(phawkins): check for overflow
*output = bfloat16(static_cast<float>(l));
return true;
}
if (PyArray_IsScalar(arg, Half))
{
Eigen::half f;
PyArray_ScalarAsCtype(arg, &f);
*output = bfloat16(f);
return true;
}
if (PyArray_IsScalar(arg, Float))
{
float f;
PyArray_ScalarAsCtype(arg, &f);
*output = bfloat16(f);
return true;
}
if (PyArray_IsScalar(arg, Double))
{
double f;
PyArray_ScalarAsCtype(arg, &f);
*output = bfloat16(f);
return true;
}
if (PyArray_IsZeroDim(arg))
{
Safe_PyObjectPtr ref;
PyArrayObject *arr = reinterpret_cast<PyArrayObject *>(arg);
if (PyArray_TYPE(arr) != npy_bfloat16)
{
ref = make_safe(PyArray_Cast(arr, npy_bfloat16));
if (PyErr_Occurred())
{
return false;
}
arg = ref.get();
arr = reinterpret_cast<PyArrayObject *>(arg);
}
*output = *reinterpret_cast<bfloat16 *>(PyArray_DATA(arr));
return true;
}
return false;
}
// Constructs a new PyBfloat16.
PyObject *PyBfloat16_New(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
if (kwds && PyDict_Size(kwds))
{
PyErr_SetString(PyExc_TypeError, "constructor takes no keyword arguments");
return nullptr;
}
Py_ssize_t size = PyTuple_Size(args);
if (size != 1)
{
PyErr_SetString(PyExc_TypeError,
"expected number as argument to bfloat16 constructor");
return nullptr;
}
PyObject *arg = PyTuple_GetItem(args, 0);
bfloat16 value;
if (PyBfloat16_Check(arg))
{
Py_INCREF(arg);
return arg;
}
else if (CastToBfloat16(arg, &value))
{
return PyBfloat16_FromBfloat16(value);
}
else if (PyArray_Check(arg))
{
PyArrayObject *arr = reinterpret_cast<PyArrayObject *>(arg);
if (PyArray_TYPE(arr) != npy_bfloat16)
{
return PyArray_Cast(arr, npy_bfloat16);
}
else
{
Py_INCREF(arg);
return arg;
}
}
PyErr_Format(PyExc_TypeError, "expected number, got %s",
arg->ob_type->tp_name);
return nullptr;
}
// Comparisons on PyBfloat16s.
PyObject *PyBfloat16_RichCompare(PyObject *self, PyObject *other, int cmp_op)
{
PyObject *arr, *ret;
arr = PyArray_FromScalar(self, NULL);
if (arr == NULL)
{
return NULL;
}
if (PyBfloat16_Check(other))
{
PyObject *arr_other;
arr_other = PyArray_FromScalar(other, NULL);
ret = Py_TYPE(arr)->tp_richcompare(arr, arr_other, cmp_op);
Py_DECREF(arr_other);
} else {
ret = Py_TYPE(arr)->tp_richcompare(arr, other, cmp_op);
}
Py_DECREF(arr);
return ret;
}
// Implementation of repr() for PyBfloat16.
PyObject *PyBfloat16_Repr(PyObject *self)
{
bfloat16 x = reinterpret_cast<PyBfloat16 *>(self)->value;
std::string v = std::to_string(static_cast<float>(x));
return PyUnicode_FromString(v.c_str());
}
// Implementation of str() for PyBfloat16.
PyObject *PyBfloat16_Str(PyObject *self)
{
bfloat16 x = reinterpret_cast<PyBfloat16 *>(self)->value;
std::string v = std::to_string(static_cast<float>(x));
return PyUnicode_FromString(v.c_str());
}
// Hash function for PyBfloat16. We use the identity function, which is a weak
// hash function.
Py_hash_t PyBfloat16_Hash(PyObject *self)
{
bfloat16 x = reinterpret_cast<PyBfloat16 *>(self)->value;
return x.value;
}
// Converts a PyBfloat16 into a PyFloat.
PyObject* PyBfloat16_Float(PyObject* self) {
bfloat16 x = PyBfloat16_Bfloat16(self);
return PyFloat_FromDouble(static_cast<double>(x));
}
// Converts a PyBfloat16 into a PyInt.
PyObject* PyBfloat16_Int(PyObject* self) {
bfloat16 x = PyBfloat16_Bfloat16(self);
long y = static_cast<long>(x); // NOLINT
return PyLong_FromLong(y);
}
PyNumberMethods PyBfloat16_AsNumber = {
nullptr, // nb_add
nullptr, // nb_subtract
nullptr, // nb_multiply
nullptr, // nb_remainder
nullptr, // nb_divmod
nullptr, // nb_power
nullptr, // nb_negative
nullptr, // nb_positive
nullptr, // nb_absolute
nullptr, // nb_nonzero
nullptr, // nb_invert
nullptr, // nb_lshift
nullptr, // nb_rshift
nullptr, // nb_and
nullptr, // nb_xor
nullptr, // nb_or
PyBfloat16_Int, // nb_int
nullptr, // reserved
PyBfloat16_Float, // nb_float
nullptr, // nb_inplace_add
nullptr, // nb_inplace_subtract
nullptr, // nb_inplace_multiply
nullptr, // nb_inplace_remainder
nullptr, // nb_inplace_power
nullptr, // nb_inplace_lshift
nullptr, // nb_inplace_rshift
nullptr, // nb_inplace_and
nullptr, // nb_inplace_xor
nullptr, // nb_inplace_or
nullptr, // nb_floor_divide
nullptr, // nb_true_divide
nullptr, // nb_inplace_floor_divide
nullptr, // nb_inplace_true_divide
nullptr, // nb_index
};
// format bfloat16. Convert to a float and call format on that
PyObject *PyBfloat16_Format(PyObject *self, PyObject *format)
{
bfloat16 x = reinterpret_cast<PyBfloat16 *>(self)->value;
PyObject * f_obj = PyFloat_FromDouble(static_cast<double>(x));
PyObject * __format__str = PyUnicode_FromString("__format__");
PyObject * f_str = PyObject_CallMethodObjArgs(f_obj, __format__str, format, NULL);
Py_DECREF(__format__str);
Py_XDECREF(f_obj);
return f_str;
}
static PyMethodDef PyBfloat16_methods[] = {
{
"__format__",
(PyCFunction) PyBfloat16_Format,
METH_O,
"__format__ method for bfloat16"
},
{NULL} /* Sentinel */
};
#ifdef IMPLEMENT_BUFFER
int PyBfloat16_getbuffer(PyObject *exporter, Py_buffer *view, int flags) {
view->obj = exporter;
Py_INCREF(exporter);
view->buf = &(reinterpret_cast<PyBfloat16 *>(exporter)->value);
view->len = 1;
view->itemsize = sizeof(bfloat16);
view->readonly = 0;
view->format = NULL;
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
view->format = (char *)"BB";
view->ndim = 1;
view->shape = NULL;
if ((flags & PyBUF_ND) == PyBUF_ND)
view->shape = &(view->len);
view->strides = NULL;
if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
view->strides = &(view->itemsize);
view->suboffsets = NULL;
view->internal = NULL;
return 0;
}
static PyBufferProcs PyBfloat16_buffer_procs = {
&PyBfloat16_getbuffer,
NULL
};
#endif
// Python type for PyBfloat16 objects.
PyTypeObject bfloat16_type = {
PyVarObject_HEAD_INIT(nullptr, 0) "bfloat16", // tp_name
sizeof(PyBfloat16), // tp_basicsize
0, // tp_itemsize
nullptr, // tp_dealloc
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare / tp_reserved
PyBfloat16_Repr, // tp_repr
&PyBfloat16_AsNumber, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
PyBfloat16_Hash, // tp_hash
nullptr, // tp_call
PyBfloat16_Str, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
#ifdef IMPLEMENT_BUFFER
&PyBfloat16_buffer_procs, // tp_as_buffer
#else
nullptr,
#endif
// tp_flags
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
"bfloat16 floating-point values", // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
PyBfloat16_RichCompare, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
PyBfloat16_methods, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
nullptr, // tp_init
nullptr, // tp_alloc
PyBfloat16_New, // tp_new
nullptr, // tp_free
nullptr, // tp_is_gc
nullptr, // tp_bases
nullptr, // tp_mro
nullptr, // tp_cache
nullptr, // tp_subclasses
nullptr, // tp_weaklist
nullptr, // tp_del
0, // tp_version_tag
};
// Numpy support
PyArray_ArrFuncs NPyBfloat16_ArrFuncs;
PyArray_Descr NPyBfloat16_Descr = {
PyObject_HEAD_INIT(nullptr) //
/*typeobj=*/
(&bfloat16_type),
// We must register bfloat16 with a kind other than "f", because numpy
// considers two types with the same kind and size to be equal, but
// float16 != bfloat16.
// The downside of this is that NumPy scalar promotion does not work with
// bfloat16 values.
/*kind=*/'g',
// TODO(phawkins): there doesn't seem to be a way of guaranteeing a type
// character is unique.
/*type=*/'E',
/*byteorder=*/'=',
/*flags=*/NPY_NEEDS_PYAPI, // | NPY_USE_GETITEM | NPY_USE_SETITEM,
/*type_num=*/0,
/*elsize=*/sizeof(bfloat16),
/*alignment=*/alignof(bfloat16),
/*subarray=*/nullptr,
/*fields=*/nullptr,
/*names=*/nullptr,
/*f=*/&NPyBfloat16_ArrFuncs,
/*metadata=*/nullptr,
/*c_metadata=*/nullptr,
/*hash=*/-1, // -1 means "not computed yet".
};
// Implementations of NumPy array methods.
PyObject *NPyBfloat16_GetItem(void *data, void *arr)
{
bfloat16 x;
NPyBfloat16_Descr.f->copyswap(&x, data, !PyArray_ISNOTSWAPPED(reinterpret_cast<PyArrayObject *>(arr)), NULL);
return PyBfloat16_FromBfloat16(x);
}
int NPyBfloat16_SetItem(PyObject *item, void *data, void *arr)
{
bfloat16 x;
if (!CastToBfloat16(item, &x))
{
PyErr_Format(PyExc_TypeError, "expected number, got %s",
item->ob_type->tp_name);
return -1;
}
memcpy(data, &x, sizeof(bfloat16));
return 0;
}
void ByteSwap16(void *value)
{
char *p = reinterpret_cast<char *>(value);
std::swap(p[0], p[1]);
}
void NPyBfloat16_CopySwapN(void *dstv, npy_intp dstride, void *srcv,
npy_intp sstride, npy_intp n, int swap, void *arr)
{
char *dst = reinterpret_cast<char *>(dstv);
char *src = reinterpret_cast<char *>(srcv);
if (!src)
{
return;
}
if (swap)
{
for (npy_intp i = 0; i < n; i++)
{
char *r = dst + dstride * i;
memcpy(r, src + sstride * i, sizeof(uint16_t));
ByteSwap16(r);
}
}
else if (dstride == sizeof(uint16_t) && sstride == sizeof(uint16_t))
{
memcpy(dst, src, n * sizeof(uint16_t));
}
else
{
for (npy_intp i = 0; i < n; i++)
{
memcpy(dst + dstride * i, src + sstride * i, sizeof(uint16_t));
}
}
}
void NPyBfloat16_CopySwap(void *dst, void *src, int swap, void *arr)
{
if (!src)
{
return;
}
memcpy(dst, src, sizeof(uint16_t));
if (swap)
{
ByteSwap16(dst);
}
}
npy_bool NPyBfloat16_NonZero(void *data, void *arr)
{
bfloat16 x;
memcpy(&x, data, sizeof(x));
return x != static_cast<bfloat16>(0);
}
int NPyBfloat16_Fill(void *buffer_raw, npy_intp length, void *ignored)
{
bfloat16 *const buffer = reinterpret_cast<bfloat16 *>(buffer_raw);
const float start(buffer[0]);
const float delta = static_cast<float>(buffer[1]) - start;
for (npy_intp i = 2; i < length; ++i)
{
buffer[i] = static_cast<bfloat16>(start + i * delta);
}
return 0;
}
void NPyBfloat16_DotFunc(void *ip1, npy_intp is1, void *ip2, npy_intp is2,
void *op, npy_intp n, void *arr)
{
char *c1 = reinterpret_cast<char *>(ip1);
char *c2 = reinterpret_cast<char *>(ip2);
float acc = 0.0f;
for (npy_intp i = 0; i < n; ++i)
{
bfloat16 *const b1 = reinterpret_cast<bfloat16 *>(c1);
bfloat16 *const b2 = reinterpret_cast<bfloat16 *>(c2);
acc += static_cast<float>(*b1) * static_cast<float>(*b2);
c1 += is1;
c2 += is2;
}
bfloat16 *out = reinterpret_cast<bfloat16 *>(op);
*out = static_cast<bfloat16>(acc);
}
int NPyBfloat16_CompareFunc(const void *v1, const void *v2, void *arr)
{
#ifdef DEBUG_CALLS
std::cout << "NPyBfloat16_CompareFunc\n";
#endif
bfloat16 b1 = *reinterpret_cast<const bfloat16 *>(v1);
bfloat16 b2 = *reinterpret_cast<const bfloat16 *>(v2);
if (b1 < b2)
{
return -1;
}
if (b1 > b2)
{
return 1;
}
if (!Eigen::numext::isnan(b1) && Eigen::numext::isnan(b2))
{
return 1;
}
if (Eigen::numext::isnan(b2) && !Eigen::numext::isnan(b1))
{
return -1;
}
return 0;
}
int NPyBfloat16_ArgMaxFunc(void *data, npy_intp n, npy_intp *max_ind,
void *arr)
{
const bfloat16 *bdata = reinterpret_cast<const bfloat16 *>(data);
float max_val = -std::numeric_limits<float>::infinity();
for (npy_intp i = 0; i < n; ++i)
{
if (static_cast<float>(bdata[i]) > max_val)
{
max_val = static_cast<float>(bdata[i]);
*max_ind = i;
}
}
return 0;
}
int NPyBfloat16_ArgMinFunc(void *data, npy_intp n, npy_intp *min_ind,
void *arr)
{
const bfloat16 *bdata = reinterpret_cast<const bfloat16 *>(data);
float min_val = std::numeric_limits<float>::infinity();
for (npy_intp i = 0; i < n; ++i)
{
if (static_cast<float>(bdata[i]) < min_val)
{
min_val = static_cast<float>(bdata[i]);
*min_ind = i;
}
}
return 0;
}
// NumPy casts
template <typename T, typename Enable = void>
struct TypeDescriptor
{
// typedef ... T; // Representation type in memory for NumPy values of type
// static int Dtype() { return NPY_...; } // Numpy type number for T.
};
template <>
struct TypeDescriptor<bfloat16>
{
typedef bfloat16 T;
static int Dtype() { return npy_bfloat16; }
};
template <>
struct TypeDescriptor<uint8>
{
typedef uint8 T;
static int Dtype() { return NPY_UINT8; }
};
template <>
struct TypeDescriptor<uint16>
{
typedef uint16 T;
static int Dtype() { return NPY_UINT16; }
};
// We register "int", "long", and "long long" types for portability across
// Linux, where "int" and "long" are the same type, and Windows, where "long"
// and "longlong" are the same type.
template <>
struct TypeDescriptor<unsigned int>
{
typedef unsigned int T;
static int Dtype() { return NPY_UINT; }
};
template <>
struct TypeDescriptor<unsigned long>
{ // NOLINT
typedef unsigned long T; // NOLINT
static int Dtype() { return NPY_ULONG; }
};
template <>
struct TypeDescriptor<unsigned long long>
{ // NOLINT
typedef unsigned long long T; // NOLINT
static int Dtype() { return NPY_ULONGLONG; }
};
template <>
struct TypeDescriptor<int8>
{
typedef int8 T;
static int Dtype() { return NPY_INT8; }
};
template <>
struct TypeDescriptor<int16>
{
typedef int16 T;
static int Dtype() { return NPY_INT16; }
};
template <>
struct TypeDescriptor<int>
{
typedef int T;
static int Dtype() { return NPY_INT; }
};
template <>
struct TypeDescriptor<long>
{ // NOLINT
typedef long T; // NOLINT
static int Dtype() { return NPY_LONG; }
};
template <>
struct TypeDescriptor<long long>
{ // NOLINT
typedef long long T; // NOLINT
static int Dtype() { return NPY_LONGLONG; }
};
template <>
struct TypeDescriptor<bool>
{
typedef int8 T;
static int Dtype() { return NPY_BOOL; }
};
template <>
struct TypeDescriptor<Eigen::half>
{
typedef Eigen::half T;
static int Dtype() { return NPY_HALF; }
};
template <>
struct TypeDescriptor<float>
{
typedef float T;
static int Dtype() { return NPY_FLOAT; }
};
template <>
struct TypeDescriptor<double>
{
typedef double T;
static int Dtype() { return NPY_DOUBLE; }
};
template <>
struct TypeDescriptor<std::complex<float>>
{
typedef std::complex<float> T;
static int Dtype() { return NPY_COMPLEX64; }
};
template <>
struct TypeDescriptor<std::complex<double>>
{
typedef std::complex<double> T;
static int Dtype() { return NPY_COMPLEX128; }
};
template <>
struct TypeDescriptor<PyObject *>
{
typedef void * T;
static int Dtype() { return NPY_OBJECT; }
};
// Performs a NumPy array cast from type 'From' to 'To'.
template <typename From, typename To>
void NPyCast(void *from_void, void *to_void, npy_intp n, void *fromarr,
void *toarr)
{
const auto *from =
reinterpret_cast<typename TypeDescriptor<From>::T *>(from_void);
auto *to = reinterpret_cast<typename TypeDescriptor<To>::T *>(to_void);
for (npy_intp i = 0; i < n; ++i)
{
to[i] =
static_cast<typename TypeDescriptor<To>::T>(static_cast<To>(from[i]));
}
}
// Registers a cast between bfloat16 and type 'T'. 'numpy_type' is the NumPy
// type corresponding to 'T'. If 'cast_is_safe', registers that bfloat16 can be
// safely coerced to T.
template <typename T>
bool RegisterBfloat16Cast(int numpy_type, bool cast_is_safe)
{
if (PyArray_RegisterCastFunc(PyArray_DescrFromType(numpy_type), npy_bfloat16, NPyCast<T, bfloat16>) < 0)
{
return false;
}
if (PyArray_RegisterCastFunc(&NPyBfloat16_Descr, numpy_type, NPyCast<bfloat16, T>) < 0)
{
return false;
}
if (cast_is_safe && PyArray_RegisterCanCast(&NPyBfloat16_Descr, numpy_type, NPY_NOSCALAR) < 0)
{
return false;
}
return true;
}
template <typename InType, typename OutType, typename Functor>
struct UnaryUFunc
{
static std::vector<int> Types()
{
return {TypeDescriptor<InType>::Dtype(), TypeDescriptor<OutType>::Dtype()};
}
static void Call(char **args, const npy_intp *dimensions,
const npy_intp *steps, void *data)
{
const char *i0 = args[0];
char *o = args[1];
for (npy_intp k = 0; k < *dimensions; k++)
{
auto x = *reinterpret_cast<const typename TypeDescriptor<InType>::T *>(i0);
*reinterpret_cast<typename TypeDescriptor<OutType>::T *>(o) = Functor()(x);
i0 += steps[0];
o += steps[1];
}
}
};
template <typename InType, typename OutType, typename OutType2,
typename Functor>
struct UnaryUFunc2
{
static std::vector<int> Types()
{
return {TypeDescriptor<InType>::Dtype(), TypeDescriptor<OutType>::Dtype(),
TypeDescriptor<OutType2>::Dtype()};
}
static void Call(char **args, const npy_intp *dimensions,
const npy_intp *steps, void *data)
{
const char *i0 = args[0];
char *o0 = args[1];
char *o1 = args[2];
for (npy_intp k = 0; k < *dimensions; k++)
{
auto x = *reinterpret_cast<const typename TypeDescriptor<InType>::T *>(i0);
std::tie(*reinterpret_cast<typename TypeDescriptor<OutType>::T *>(o0),
*reinterpret_cast<typename TypeDescriptor<OutType2>::T *>(o1)) =
Functor()(x);
i0 += steps[0];
o0 += steps[1];
o1 += steps[2];
}
}
};
template <typename InType, typename OutType, typename Functor>
struct BinaryUFunc
{
static std::vector<int> Types()
{
return {TypeDescriptor<InType>::Dtype(), TypeDescriptor<InType>::Dtype(),
TypeDescriptor<OutType>::Dtype()};
}
static void Call(char **args, const npy_intp *dimensions,
const npy_intp *steps, void *data)
{
#ifdef DEBUG_CALLS
std::cout << "BinaryUFunc->Call\n";
#endif
const char *i0 = args[0];
const char *i1 = args[1];
char *o = args[2];
fenv_t fenv;
feholdexcept(&fenv);
for (npy_intp k = 0; k < *dimensions; k++)
{
auto x = *reinterpret_cast<const typename TypeDescriptor<InType>::T *>(i0);
auto y = *reinterpret_cast<const typename TypeDescriptor<InType>::T *>(i1);
*reinterpret_cast<typename TypeDescriptor<OutType>::T *>(o) =
Functor()(x, y);
i0 += steps[0];
i1 += steps[1];
o += steps[2];
}
if (fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW)) {
if (fetestexcept(FE_INVALID)) {
PyErr_SetString(PyExc_ArithmeticError, "bfloat16 invalid");
} else if (fetestexcept(FE_DIVBYZERO)) {
PyErr_SetString(PyExc_ArithmeticError, "bfloat16 divide by zero");
} else if (fetestexcept(FE_OVERFLOW)) {
PyErr_SetString(PyExc_ArithmeticError, "bfloat16 overflow");
} else if (fetestexcept(FE_UNDERFLOW)) {
PyErr_SetString(PyExc_ArithmeticError, "bfloat16 underflow");
}
}
fesetenv(&fenv);
}
};
template <typename InType, typename InType2, typename OutType, typename Functor>
struct BinaryUFunc2
{
static std::vector<int> Types()
{
return {TypeDescriptor<InType>::Dtype(), TypeDescriptor<InType2>::Dtype(),
TypeDescriptor<OutType>::Dtype()};
}
static void Call(char **args, const npy_intp *dimensions,
const npy_intp *steps, void *data)
{
#ifdef DEBUG_CALLS
std::cout << "BinaryUFunc2->Call\n";
#endif
const char *i0 = args[0];
const char *i1 = args[1];
char *o = args[2];
fenv_t fenv;
feholdexcept(&fenv);
for (npy_intp k = 0; k < *dimensions; k++)
{
auto x = *reinterpret_cast<const typename TypeDescriptor<InType>::T *>(i0);
auto y =
*reinterpret_cast<const typename TypeDescriptor<InType2>::T *>(i1);
*reinterpret_cast<typename TypeDescriptor<OutType>::T *>(o) =
Functor()(x, y);
i0 += steps[0];
i1 += steps[1];
o += steps[2];
}
if (fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW)) {
if (fetestexcept(FE_INVALID)) {
PyErr_SetString(PyExc_ArithmeticError, "bfloat16 invalid");
} else if (fetestexcept(FE_DIVBYZERO)) {
PyErr_SetString(PyExc_ArithmeticError, "bfloat16 divide by zero");
} else if (fetestexcept(FE_OVERFLOW)) {
PyErr_SetString(PyExc_ArithmeticError, "bfloat16 overflow");
} else if (fetestexcept(FE_UNDERFLOW)) {
PyErr_SetString(PyExc_ArithmeticError, "bfloat16 underflow");
}
}
fesetenv(&fenv);
}
};
// template <typename InType, typename OutType, typename Functor>
// struct BinaryUFuncObj
// {
// static std::vector<int> Types()
// {
// return {TypeDescriptor<InType>::Dtype(), NPY_OBJECT,
// TypeDescriptor<OutType>::Dtype()};
// }
// static void Call(char **args, const npy_intp *dimensions,
// const npy_intp *steps, void *data)
// {
// const char *i0 = args[0];
// char *i1 = args[1];
// char *o = args[2];
// for (npy_intp k = 0; k < *dimensions; k++)
// {
// auto x = *reinterpret_cast<const typename TypeDescriptor<InType>::T *>(i0);
// bfloat16 y = *reinterpret_cast<bfloat16 *>(i1);
// *reinterpret_cast<typename TypeDescriptor<OutType>::T *>(o) =
// Functor()(x, y);
// i0 += steps[0];
// i1 += steps[1];
// o += steps[2];
// }
// }
// };
template <typename UFunc>
bool RegisterUFunc(PyObject *numpy, const char *name)
{
std::vector<int> types = UFunc::Types();
PyUFuncGenericFunction fn =
reinterpret_cast<PyUFuncGenericFunction>(UFunc::Call);
Safe_PyObjectPtr ufunc_obj = make_safe(PyObject_GetAttrString(numpy, name));
if (!ufunc_obj)
{
return false;
}
PyUFuncObject *ufunc = reinterpret_cast<PyUFuncObject *>(ufunc_obj.get());
if (static_cast<int>(types.size()) != ufunc->nargs)
{
PyErr_Format(PyExc_AssertionError,
"ufunc %s takes %d arguments, loop takes %lu", name,
ufunc->nargs, types.size());
return false;
}
if (PyUFunc_RegisterLoopForType(ufunc, npy_bfloat16, fn,