-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
bfloat.rs
1861 lines (1691 loc) · 57.6 KB
/
bfloat.rs
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
#[cfg(all(feature = "serde", feature = "alloc"))]
#[allow(unused_imports)]
use alloc::string::ToString;
#[cfg(feature = "bytemuck")]
use bytemuck::{Pod, Zeroable};
use core::{
cmp::Ordering,
iter::{Product, Sum},
num::FpCategory,
ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign},
};
#[cfg(not(target_arch = "spirv"))]
use core::{
fmt::{
Binary, Debug, Display, Error, Formatter, LowerExp, LowerHex, Octal, UpperExp, UpperHex,
},
num::ParseFloatError,
str::FromStr,
};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "zerocopy")]
use zerocopy::{AsBytes, FromBytes};
pub(crate) mod convert;
/// A 16-bit floating point type implementing the [`bfloat16`] format.
///
/// The [`bfloat16`] floating point format is a truncated 16-bit version of the IEEE 754 standard
/// `binary32`, a.k.a [`f32`]. [`bf16`] has approximately the same dynamic range as [`f32`] by
/// having a lower precision than [`f16`][crate::f16]. While [`f16`][crate::f16] has a precision of
/// 11 bits, [`bf16`] has a precision of only 8 bits.
///
/// [`bfloat16`]: https://en.wikipedia.org/wiki/Bfloat16_floating-point_format
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Default)]
#[repr(transparent)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "bytemuck", derive(Zeroable, Pod))]
#[cfg_attr(feature = "zerocopy", derive(AsBytes, FromBytes))]
#[cfg_attr(kani, derive(kani::Arbitrary))]
pub struct bf16(u16);
impl bf16 {
/// Constructs a [`bf16`] value from the raw bits.
#[inline]
#[must_use]
pub const fn from_bits(bits: u16) -> bf16 {
bf16(bits)
}
/// Constructs a [`bf16`] value from a 32-bit floating point value.
///
/// This operation is lossy. If the 32-bit value is too large to fit, ±∞ will result. NaN values
/// are preserved. Subnormal values that are too tiny to be represented will result in ±0. All
/// other values are truncated and rounded to the nearest representable value.
#[inline]
#[must_use]
pub fn from_f32(value: f32) -> bf16 {
Self::from_f32_const(value)
}
/// Constructs a [`bf16`] value from a 32-bit floating point value.
///
/// This function is identical to [`from_f32`][Self::from_f32] except it never uses hardware
/// intrinsics, which allows it to be `const`. [`from_f32`][Self::from_f32] should be preferred
/// in any non-`const` context.
///
/// This operation is lossy. If the 32-bit value is too large to fit, ±∞ will result. NaN values
/// are preserved. Subnormal values that are too tiny to be represented will result in ±0. All
/// other values are truncated and rounded to the nearest representable value.
#[inline]
#[must_use]
pub const fn from_f32_const(value: f32) -> bf16 {
bf16(convert::f32_to_bf16(value))
}
/// Constructs a [`bf16`] value from a 64-bit floating point value.
///
/// This operation is lossy. If the 64-bit value is to large to fit, ±∞ will result. NaN values
/// are preserved. 64-bit subnormal values are too tiny to be represented and result in ±0.
/// Exponents that underflow the minimum exponent will result in subnormals or ±0. All other
/// values are truncated and rounded to the nearest representable value.
#[inline]
#[must_use]
pub fn from_f64(value: f64) -> bf16 {
Self::from_f64_const(value)
}
/// Constructs a [`bf16`] value from a 64-bit floating point value.
///
/// This function is identical to [`from_f64`][Self::from_f64] except it never uses hardware
/// intrinsics, which allows it to be `const`. [`from_f64`][Self::from_f64] should be preferred
/// in any non-`const` context.
///
/// This operation is lossy. If the 64-bit value is to large to fit, ±∞ will result. NaN values
/// are preserved. 64-bit subnormal values are too tiny to be represented and result in ±0.
/// Exponents that underflow the minimum exponent will result in subnormals or ±0. All other
/// values are truncated and rounded to the nearest representable value.
#[inline]
#[must_use]
pub const fn from_f64_const(value: f64) -> bf16 {
bf16(convert::f64_to_bf16(value))
}
/// Converts a [`bf16`] into the underlying bit representation.
#[inline]
#[must_use]
pub const fn to_bits(self) -> u16 {
self.0
}
/// Returns the memory representation of the underlying bit representation as a byte array in
/// little-endian byte order.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
/// let bytes = bf16::from_f32(12.5).to_le_bytes();
/// assert_eq!(bytes, [0x48, 0x41]);
/// ```
#[inline]
#[must_use]
pub const fn to_le_bytes(self) -> [u8; 2] {
self.0.to_le_bytes()
}
/// Returns the memory representation of the underlying bit representation as a byte array in
/// big-endian (network) byte order.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
/// let bytes = bf16::from_f32(12.5).to_be_bytes();
/// assert_eq!(bytes, [0x41, 0x48]);
/// ```
#[inline]
#[must_use]
pub const fn to_be_bytes(self) -> [u8; 2] {
self.0.to_be_bytes()
}
/// Returns the memory representation of the underlying bit representation as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code should use
/// [`to_be_bytes`][bf16::to_be_bytes] or [`to_le_bytes`][bf16::to_le_bytes], as appropriate,
/// instead.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
/// let bytes = bf16::from_f32(12.5).to_ne_bytes();
/// assert_eq!(bytes, if cfg!(target_endian = "big") {
/// [0x41, 0x48]
/// } else {
/// [0x48, 0x41]
/// });
/// ```
#[inline]
#[must_use]
pub const fn to_ne_bytes(self) -> [u8; 2] {
self.0.to_ne_bytes()
}
/// Creates a floating point value from its representation as a byte array in little endian.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
/// let value = bf16::from_le_bytes([0x48, 0x41]);
/// assert_eq!(value, bf16::from_f32(12.5));
/// ```
#[inline]
#[must_use]
pub const fn from_le_bytes(bytes: [u8; 2]) -> bf16 {
bf16::from_bits(u16::from_le_bytes(bytes))
}
/// Creates a floating point value from its representation as a byte array in big endian.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
/// let value = bf16::from_be_bytes([0x41, 0x48]);
/// assert_eq!(value, bf16::from_f32(12.5));
/// ```
#[inline]
#[must_use]
pub const fn from_be_bytes(bytes: [u8; 2]) -> bf16 {
bf16::from_bits(u16::from_be_bytes(bytes))
}
/// Creates a floating point value from its representation as a byte array in native endian.
///
/// As the target platform's native endianness is used, portable code likely wants to use
/// [`from_be_bytes`][bf16::from_be_bytes] or [`from_le_bytes`][bf16::from_le_bytes], as
/// appropriate instead.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
/// let value = bf16::from_ne_bytes(if cfg!(target_endian = "big") {
/// [0x41, 0x48]
/// } else {
/// [0x48, 0x41]
/// });
/// assert_eq!(value, bf16::from_f32(12.5));
/// ```
#[inline]
#[must_use]
pub const fn from_ne_bytes(bytes: [u8; 2]) -> bf16 {
bf16::from_bits(u16::from_ne_bytes(bytes))
}
/// Converts a [`bf16`] value into an [`f32`] value.
///
/// This conversion is lossless as all values can be represented exactly in [`f32`].
#[inline]
#[must_use]
pub fn to_f32(self) -> f32 {
self.to_f32_const()
}
/// Converts a [`bf16`] value into an [`f32`] value.
///
/// This function is identical to [`to_f32`][Self::to_f32] except it never uses hardware
/// intrinsics, which allows it to be `const`. [`to_f32`][Self::to_f32] should be preferred
/// in any non-`const` context.
///
/// This conversion is lossless as all values can be represented exactly in [`f32`].
#[inline]
#[must_use]
pub const fn to_f32_const(self) -> f32 {
convert::bf16_to_f32(self.0)
}
/// Converts a [`bf16`] value into an [`f64`] value.
///
/// This conversion is lossless as all values can be represented exactly in [`f64`].
#[inline]
#[must_use]
pub fn to_f64(self) -> f64 {
self.to_f64_const()
}
/// Converts a [`bf16`] value into an [`f64`] value.
///
/// This function is identical to [`to_f64`][Self::to_f64] except it never uses hardware
/// intrinsics, which allows it to be `const`. [`to_f64`][Self::to_f64] should be preferred
/// in any non-`const` context.
///
/// This conversion is lossless as all values can be represented exactly in [`f64`].
#[inline]
#[must_use]
pub const fn to_f64_const(self) -> f64 {
convert::bf16_to_f64(self.0)
}
/// Returns `true` if this value is NaN and `false` otherwise.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
///
/// let nan = bf16::NAN;
/// let f = bf16::from_f32(7.0_f32);
///
/// assert!(nan.is_nan());
/// assert!(!f.is_nan());
/// ```
#[inline]
#[must_use]
pub const fn is_nan(self) -> bool {
self.0 & 0x7FFFu16 > 0x7F80u16
}
/// Returns `true` if this value is ±∞ and `false` otherwise.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
///
/// let f = bf16::from_f32(7.0f32);
/// let inf = bf16::INFINITY;
/// let neg_inf = bf16::NEG_INFINITY;
/// let nan = bf16::NAN;
///
/// assert!(!f.is_infinite());
/// assert!(!nan.is_infinite());
///
/// assert!(inf.is_infinite());
/// assert!(neg_inf.is_infinite());
/// ```
#[inline]
#[must_use]
pub const fn is_infinite(self) -> bool {
self.0 & 0x7FFFu16 == 0x7F80u16
}
/// Returns `true` if this number is neither infinite nor NaN.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
///
/// let f = bf16::from_f32(7.0f32);
/// let inf = bf16::INFINITY;
/// let neg_inf = bf16::NEG_INFINITY;
/// let nan = bf16::NAN;
///
/// assert!(f.is_finite());
///
/// assert!(!nan.is_finite());
/// assert!(!inf.is_finite());
/// assert!(!neg_inf.is_finite());
/// ```
#[inline]
#[must_use]
pub const fn is_finite(self) -> bool {
self.0 & 0x7F80u16 != 0x7F80u16
}
/// Returns `true` if the number is neither zero, infinite, subnormal, or NaN.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
///
/// let min = bf16::MIN_POSITIVE;
/// let max = bf16::MAX;
/// let lower_than_min = bf16::from_f32(1.0e-39_f32);
/// let zero = bf16::from_f32(0.0_f32);
///
/// assert!(min.is_normal());
/// assert!(max.is_normal());
///
/// assert!(!zero.is_normal());
/// assert!(!bf16::NAN.is_normal());
/// assert!(!bf16::INFINITY.is_normal());
/// // Values between 0 and `min` are subnormal.
/// assert!(!lower_than_min.is_normal());
/// ```
#[inline]
#[must_use]
pub const fn is_normal(self) -> bool {
let exp = self.0 & 0x7F80u16;
exp != 0x7F80u16 && exp != 0
}
/// Returns the floating point category of the number.
///
/// If only one property is going to be tested, it is generally faster to use the specific
/// predicate instead.
///
/// # Examples
///
/// ```rust
/// use std::num::FpCategory;
/// # use half::prelude::*;
///
/// let num = bf16::from_f32(12.4_f32);
/// let inf = bf16::INFINITY;
///
/// assert_eq!(num.classify(), FpCategory::Normal);
/// assert_eq!(inf.classify(), FpCategory::Infinite);
/// ```
#[must_use]
pub const fn classify(self) -> FpCategory {
let exp = self.0 & 0x7F80u16;
let man = self.0 & 0x007Fu16;
match (exp, man) {
(0, 0) => FpCategory::Zero,
(0, _) => FpCategory::Subnormal,
(0x7F80u16, 0) => FpCategory::Infinite,
(0x7F80u16, _) => FpCategory::Nan,
_ => FpCategory::Normal,
}
}
/// Returns a number that represents the sign of `self`.
///
/// * 1.0 if the number is positive, +0.0 or [`INFINITY`][bf16::INFINITY]
/// * −1.0 if the number is negative, −0.0` or [`NEG_INFINITY`][bf16::NEG_INFINITY]
/// * [`NAN`][bf16::NAN] if the number is NaN
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
///
/// let f = bf16::from_f32(3.5_f32);
///
/// assert_eq!(f.signum(), bf16::from_f32(1.0));
/// assert_eq!(bf16::NEG_INFINITY.signum(), bf16::from_f32(-1.0));
///
/// assert!(bf16::NAN.signum().is_nan());
/// ```
#[must_use]
pub const fn signum(self) -> bf16 {
if self.is_nan() {
self
} else if self.0 & 0x8000u16 != 0 {
Self::NEG_ONE
} else {
Self::ONE
}
}
/// Returns `true` if and only if `self` has a positive sign, including +0.0, NaNs with a
/// positive sign bit and +∞.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
///
/// let nan = bf16::NAN;
/// let f = bf16::from_f32(7.0_f32);
/// let g = bf16::from_f32(-7.0_f32);
///
/// assert!(f.is_sign_positive());
/// assert!(!g.is_sign_positive());
/// // NaN can be either positive or negative
/// assert!(nan.is_sign_positive() != nan.is_sign_negative());
/// ```
#[inline]
#[must_use]
pub const fn is_sign_positive(self) -> bool {
self.0 & 0x8000u16 == 0
}
/// Returns `true` if and only if `self` has a negative sign, including −0.0, NaNs with a
/// negative sign bit and −∞.
///
/// # Examples
///
/// ```rust
/// # use half::prelude::*;
///
/// let nan = bf16::NAN;
/// let f = bf16::from_f32(7.0f32);
/// let g = bf16::from_f32(-7.0f32);
///
/// assert!(!f.is_sign_negative());
/// assert!(g.is_sign_negative());
/// // NaN can be either positive or negative
/// assert!(nan.is_sign_positive() != nan.is_sign_negative());
/// ```
#[inline]
#[must_use]
pub const fn is_sign_negative(self) -> bool {
self.0 & 0x8000u16 != 0
}
/// Returns a number composed of the magnitude of `self` and the sign of `sign`.
///
/// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
/// If `self` is NaN, then NaN with the sign of `sign` is returned.
///
/// # Examples
///
/// ```
/// # use half::prelude::*;
/// let f = bf16::from_f32(3.5);
///
/// assert_eq!(f.copysign(bf16::from_f32(0.42)), bf16::from_f32(3.5));
/// assert_eq!(f.copysign(bf16::from_f32(-0.42)), bf16::from_f32(-3.5));
/// assert_eq!((-f).copysign(bf16::from_f32(0.42)), bf16::from_f32(3.5));
/// assert_eq!((-f).copysign(bf16::from_f32(-0.42)), bf16::from_f32(-3.5));
///
/// assert!(bf16::NAN.copysign(bf16::from_f32(1.0)).is_nan());
/// ```
#[inline]
#[must_use]
pub const fn copysign(self, sign: bf16) -> bf16 {
bf16((sign.0 & 0x8000u16) | (self.0 & 0x7FFFu16))
}
/// Returns the maximum of the two numbers.
///
/// If one of the arguments is NaN, then the other argument is returned.
///
/// # Examples
///
/// ```
/// # use half::prelude::*;
/// let x = bf16::from_f32(1.0);
/// let y = bf16::from_f32(2.0);
///
/// assert_eq!(x.max(y), y);
/// ```
#[inline]
#[must_use]
pub fn max(self, other: bf16) -> bf16 {
if other > self && !other.is_nan() {
other
} else {
self
}
}
/// Returns the minimum of the two numbers.
///
/// If one of the arguments is NaN, then the other argument is returned.
///
/// # Examples
///
/// ```
/// # use half::prelude::*;
/// let x = bf16::from_f32(1.0);
/// let y = bf16::from_f32(2.0);
///
/// assert_eq!(x.min(y), x);
/// ```
#[inline]
#[must_use]
pub fn min(self, other: bf16) -> bf16 {
if other < self && !other.is_nan() {
other
} else {
self
}
}
/// Restrict a value to a certain interval unless it is NaN.
///
/// Returns `max` if `self` is greater than `max`, and `min` if `self` is less than `min`.
/// Otherwise this returns `self`.
///
/// Note that this function returns NaN if the initial value was NaN as well.
///
/// # Panics
/// Panics if `min > max`, `min` is NaN, or `max` is NaN.
///
/// # Examples
///
/// ```
/// # use half::prelude::*;
/// assert!(bf16::from_f32(-3.0).clamp(bf16::from_f32(-2.0), bf16::from_f32(1.0)) == bf16::from_f32(-2.0));
/// assert!(bf16::from_f32(0.0).clamp(bf16::from_f32(-2.0), bf16::from_f32(1.0)) == bf16::from_f32(0.0));
/// assert!(bf16::from_f32(2.0).clamp(bf16::from_f32(-2.0), bf16::from_f32(1.0)) == bf16::from_f32(1.0));
/// assert!(bf16::NAN.clamp(bf16::from_f32(-2.0), bf16::from_f32(1.0)).is_nan());
/// ```
#[inline]
#[must_use]
pub fn clamp(self, min: bf16, max: bf16) -> bf16 {
assert!(min <= max);
let mut x = self;
if x < min {
x = min;
}
if x > max {
x = max;
}
x
}
/// Returns the ordering between `self` and `other`.
///
/// Unlike the standard partial comparison between floating point numbers,
/// this comparison always produces an ordering in accordance to
/// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
/// floating point standard. The values are ordered in the following sequence:
///
/// - negative quiet NaN
/// - negative signaling NaN
/// - negative infinity
/// - negative numbers
/// - negative subnormal numbers
/// - negative zero
/// - positive zero
/// - positive subnormal numbers
/// - positive numbers
/// - positive infinity
/// - positive signaling NaN
/// - positive quiet NaN.
///
/// The ordering established by this function does not always agree with the
/// [`PartialOrd`] and [`PartialEq`] implementations of `bf16`. For example,
/// they consider negative and positive zero equal, while `total_cmp`
/// doesn't.
///
/// The interpretation of the signaling NaN bit follows the definition in
/// the IEEE 754 standard, which may not match the interpretation by some of
/// the older, non-conformant (e.g. MIPS) hardware implementations.
///
/// # Examples
/// ```
/// # use half::bf16;
/// let mut v: Vec<bf16> = vec![];
/// v.push(bf16::ONE);
/// v.push(bf16::INFINITY);
/// v.push(bf16::NEG_INFINITY);
/// v.push(bf16::NAN);
/// v.push(bf16::MAX_SUBNORMAL);
/// v.push(-bf16::MAX_SUBNORMAL);
/// v.push(bf16::ZERO);
/// v.push(bf16::NEG_ZERO);
/// v.push(bf16::NEG_ONE);
/// v.push(bf16::MIN_POSITIVE);
///
/// v.sort_by(|a, b| a.total_cmp(&b));
///
/// assert!(v
/// .into_iter()
/// .zip(
/// [
/// bf16::NEG_INFINITY,
/// bf16::NEG_ONE,
/// -bf16::MAX_SUBNORMAL,
/// bf16::NEG_ZERO,
/// bf16::ZERO,
/// bf16::MAX_SUBNORMAL,
/// bf16::MIN_POSITIVE,
/// bf16::ONE,
/// bf16::INFINITY,
/// bf16::NAN
/// ]
/// .iter()
/// )
/// .all(|(a, b)| a.to_bits() == b.to_bits()));
/// ```
// Implementation based on: https://doc.rust-lang.org/std/primitive.f32.html#method.total_cmp
#[inline]
#[must_use]
pub fn total_cmp(&self, other: &Self) -> Ordering {
let mut left = self.to_bits() as i16;
let mut right = other.to_bits() as i16;
left ^= (((left >> 15) as u16) >> 1) as i16;
right ^= (((right >> 15) as u16) >> 1) as i16;
left.cmp(&right)
}
/// Alternate serialize adapter for serializing as a float.
///
/// By default, [`bf16`] serializes as a newtype of [`u16`]. This is an alternate serialize
/// implementation that serializes as an [`f32`] value. It is designed for use with
/// `serialize_with` serde attributes. Deserialization from `f32` values is already supported by
/// the default deserialize implementation.
///
/// # Examples
///
/// A demonstration on how to use this adapater:
///
/// ```
/// use serde::{Serialize, Deserialize};
/// use half::bf16;
///
/// #[derive(Serialize, Deserialize)]
/// struct MyStruct {
/// #[serde(serialize_with = "bf16::serialize_as_f32")]
/// value: bf16 // Will be serialized as f32 instead of u16
/// }
/// ```
#[cfg(feature = "serde")]
pub fn serialize_as_f32<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_f32(self.to_f32())
}
/// Alternate serialize adapter for serializing as a string.
///
/// By default, [`bf16`] serializes as a newtype of [`u16`]. This is an alternate serialize
/// implementation that serializes as a string value. It is designed for use with
/// `serialize_with` serde attributes. Deserialization from string values is already supported
/// by the default deserialize implementation.
///
/// # Examples
///
/// A demonstration on how to use this adapater:
///
/// ```
/// use serde::{Serialize, Deserialize};
/// use half::bf16;
///
/// #[derive(Serialize, Deserialize)]
/// struct MyStruct {
/// #[serde(serialize_with = "bf16::serialize_as_string")]
/// value: bf16 // Will be serialized as a string instead of u16
/// }
/// ```
#[cfg(all(feature = "serde", feature = "alloc"))]
pub fn serialize_as_string<S: serde::Serializer>(
&self,
serializer: S,
) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
/// Approximate number of [`bf16`] significant digits in base 10
pub const DIGITS: u32 = 2;
/// [`bf16`]
/// [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value
///
/// This is the difference between 1.0 and the next largest representable number.
pub const EPSILON: bf16 = bf16(0x3C00u16);
/// [`bf16`] positive Infinity (+∞)
pub const INFINITY: bf16 = bf16(0x7F80u16);
/// Number of [`bf16`] significant digits in base 2
pub const MANTISSA_DIGITS: u32 = 8;
/// Largest finite [`bf16`] value
pub const MAX: bf16 = bf16(0x7F7F);
/// Maximum possible [`bf16`] power of 10 exponent
pub const MAX_10_EXP: i32 = 38;
/// Maximum possible [`bf16`] power of 2 exponent
pub const MAX_EXP: i32 = 128;
/// Smallest finite [`bf16`] value
pub const MIN: bf16 = bf16(0xFF7F);
/// Minimum possible normal [`bf16`] power of 10 exponent
pub const MIN_10_EXP: i32 = -37;
/// One greater than the minimum possible normal [`bf16`] power of 2 exponent
pub const MIN_EXP: i32 = -125;
/// Smallest positive normal [`bf16`] value
pub const MIN_POSITIVE: bf16 = bf16(0x0080u16);
/// [`bf16`] Not a Number (NaN)
pub const NAN: bf16 = bf16(0x7FC0u16);
/// [`bf16`] negative infinity (-∞).
pub const NEG_INFINITY: bf16 = bf16(0xFF80u16);
/// The radix or base of the internal representation of [`bf16`]
pub const RADIX: u32 = 2;
/// Minimum positive subnormal [`bf16`] value
pub const MIN_POSITIVE_SUBNORMAL: bf16 = bf16(0x0001u16);
/// Maximum subnormal [`bf16`] value
pub const MAX_SUBNORMAL: bf16 = bf16(0x007Fu16);
/// [`bf16`] 1
pub const ONE: bf16 = bf16(0x3F80u16);
/// [`bf16`] 0
pub const ZERO: bf16 = bf16(0x0000u16);
/// [`bf16`] -0
pub const NEG_ZERO: bf16 = bf16(0x8000u16);
/// [`bf16`] -1
pub const NEG_ONE: bf16 = bf16(0xBF80u16);
/// [`bf16`] Euler's number (ℯ)
pub const E: bf16 = bf16(0x402Eu16);
/// [`bf16`] Archimedes' constant (π)
pub const PI: bf16 = bf16(0x4049u16);
/// [`bf16`] 1/π
pub const FRAC_1_PI: bf16 = bf16(0x3EA3u16);
/// [`bf16`] 1/√2
pub const FRAC_1_SQRT_2: bf16 = bf16(0x3F35u16);
/// [`bf16`] 2/π
pub const FRAC_2_PI: bf16 = bf16(0x3F23u16);
/// [`bf16`] 2/√π
pub const FRAC_2_SQRT_PI: bf16 = bf16(0x3F90u16);
/// [`bf16`] π/2
pub const FRAC_PI_2: bf16 = bf16(0x3FC9u16);
/// [`bf16`] π/3
pub const FRAC_PI_3: bf16 = bf16(0x3F86u16);
/// [`bf16`] π/4
pub const FRAC_PI_4: bf16 = bf16(0x3F49u16);
/// [`bf16`] π/6
pub const FRAC_PI_6: bf16 = bf16(0x3F06u16);
/// [`bf16`] π/8
pub const FRAC_PI_8: bf16 = bf16(0x3EC9u16);
/// [`bf16`] 𝗅𝗇 10
pub const LN_10: bf16 = bf16(0x4013u16);
/// [`bf16`] 𝗅𝗇 2
pub const LN_2: bf16 = bf16(0x3F31u16);
/// [`bf16`] 𝗅𝗈𝗀₁₀ℯ
pub const LOG10_E: bf16 = bf16(0x3EDEu16);
/// [`bf16`] 𝗅𝗈𝗀₁₀2
pub const LOG10_2: bf16 = bf16(0x3E9Au16);
/// [`bf16`] 𝗅𝗈𝗀₂ℯ
pub const LOG2_E: bf16 = bf16(0x3FB9u16);
/// [`bf16`] 𝗅𝗈𝗀₂10
pub const LOG2_10: bf16 = bf16(0x4055u16);
/// [`bf16`] √2
pub const SQRT_2: bf16 = bf16(0x3FB5u16);
}
impl From<bf16> for f32 {
#[inline]
fn from(x: bf16) -> f32 {
x.to_f32()
}
}
impl From<bf16> for f64 {
#[inline]
fn from(x: bf16) -> f64 {
x.to_f64()
}
}
impl From<i8> for bf16 {
#[inline]
fn from(x: i8) -> bf16 {
// Convert to f32, then to bf16
bf16::from_f32(f32::from(x))
}
}
impl From<u8> for bf16 {
#[inline]
fn from(x: u8) -> bf16 {
// Convert to f32, then to f16
bf16::from_f32(f32::from(x))
}
}
impl PartialEq for bf16 {
fn eq(&self, other: &bf16) -> bool {
if self.is_nan() || other.is_nan() {
false
} else {
(self.0 == other.0) || ((self.0 | other.0) & 0x7FFFu16 == 0)
}
}
}
impl PartialOrd for bf16 {
fn partial_cmp(&self, other: &bf16) -> Option<Ordering> {
if self.is_nan() || other.is_nan() {
None
} else {
let neg = self.0 & 0x8000u16 != 0;
let other_neg = other.0 & 0x8000u16 != 0;
match (neg, other_neg) {
(false, false) => Some(self.0.cmp(&other.0)),
(false, true) => {
if (self.0 | other.0) & 0x7FFFu16 == 0 {
Some(Ordering::Equal)
} else {
Some(Ordering::Greater)
}
}
(true, false) => {
if (self.0 | other.0) & 0x7FFFu16 == 0 {
Some(Ordering::Equal)
} else {
Some(Ordering::Less)
}
}
(true, true) => Some(other.0.cmp(&self.0)),
}
}
}
fn lt(&self, other: &bf16) -> bool {
if self.is_nan() || other.is_nan() {
false
} else {
let neg = self.0 & 0x8000u16 != 0;
let other_neg = other.0 & 0x8000u16 != 0;
match (neg, other_neg) {
(false, false) => self.0 < other.0,
(false, true) => false,
(true, false) => (self.0 | other.0) & 0x7FFFu16 != 0,
(true, true) => self.0 > other.0,
}
}
}
fn le(&self, other: &bf16) -> bool {
if self.is_nan() || other.is_nan() {
false
} else {
let neg = self.0 & 0x8000u16 != 0;
let other_neg = other.0 & 0x8000u16 != 0;
match (neg, other_neg) {
(false, false) => self.0 <= other.0,
(false, true) => (self.0 | other.0) & 0x7FFFu16 == 0,
(true, false) => true,
(true, true) => self.0 >= other.0,
}
}
}
fn gt(&self, other: &bf16) -> bool {
if self.is_nan() || other.is_nan() {
false
} else {
let neg = self.0 & 0x8000u16 != 0;
let other_neg = other.0 & 0x8000u16 != 0;
match (neg, other_neg) {
(false, false) => self.0 > other.0,
(false, true) => (self.0 | other.0) & 0x7FFFu16 != 0,
(true, false) => false,
(true, true) => self.0 < other.0,
}
}
}
fn ge(&self, other: &bf16) -> bool {
if self.is_nan() || other.is_nan() {
false
} else {
let neg = self.0 & 0x8000u16 != 0;
let other_neg = other.0 & 0x8000u16 != 0;
match (neg, other_neg) {
(false, false) => self.0 >= other.0,
(false, true) => true,
(true, false) => (self.0 | other.0) & 0x7FFFu16 == 0,
(true, true) => self.0 <= other.0,
}
}
}
}
#[cfg(not(target_arch = "spirv"))]
impl FromStr for bf16 {
type Err = ParseFloatError;
fn from_str(src: &str) -> Result<bf16, ParseFloatError> {
f32::from_str(src).map(bf16::from_f32)
}
}
#[cfg(not(target_arch = "spirv"))]
impl Debug for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
Debug::fmt(&self.to_f32(), f)
}
}
#[cfg(not(target_arch = "spirv"))]
impl Display for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
Display::fmt(&self.to_f32(), f)
}
}
#[cfg(not(target_arch = "spirv"))]
impl LowerExp for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{:e}", self.to_f32())
}
}
#[cfg(not(target_arch = "spirv"))]
impl UpperExp for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{:E}", self.to_f32())
}
}
#[cfg(not(target_arch = "spirv"))]
impl Binary for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{:b}", self.0)
}
}
#[cfg(not(target_arch = "spirv"))]
impl Octal for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{:o}", self.0)
}
}
#[cfg(not(target_arch = "spirv"))]
impl LowerHex for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{:x}", self.0)
}
}
#[cfg(not(target_arch = "spirv"))]
impl UpperHex for bf16 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "{:X}", self.0)
}
}
impl Neg for bf16 {
type Output = Self;
fn neg(self) -> Self::Output {
Self(self.0 ^ 0x8000)
}
}
impl Neg for &bf16 {
type Output = <bf16 as Neg>::Output;
#[inline]
fn neg(self) -> Self::Output {
Neg::neg(*self)
}
}
impl Add for bf16 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self::from_f32(Self::to_f32(self) + Self::to_f32(rhs))
}
}