-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
dtype.mojo
740 lines (621 loc) · 23.2 KB
/
dtype.mojo
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
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2024, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# 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.
# ===----------------------------------------------------------------------=== #
"""Implements the DType class.
These are Mojo built-ins, so you don't need to import them.
"""
from collections import KeyElement
from sys import sizeof, bitwidthof, os_is_windows
alias _mIsSigned = UInt8(1)
alias _mIsInteger = UInt8(1 << 7)
alias _mIsNotInteger = UInt8(~(1 << 7))
alias _mIsFloat = UInt8(1 << 6)
@value
@register_passable("trivial")
struct DType(
Stringable, Formattable, Representable, KeyElement, CollectionElementNew
):
"""Represents DType and provides methods for working with it."""
alias type = __mlir_type.`!kgen.dtype`
var value: Self.type
"""The underlying storage for the DType value."""
alias invalid = DType(
__mlir_attr.`#kgen.dtype.constant<invalid> : !kgen.dtype`
)
"""Represents an invalid or unknown data type."""
alias bool = DType(__mlir_attr.`#kgen.dtype.constant<bool> : !kgen.dtype`)
"""Represents a boolean data type."""
alias int8 = DType(__mlir_attr.`#kgen.dtype.constant<si8> : !kgen.dtype`)
"""Represents a signed integer type whose bitwidth is 8."""
alias uint8 = DType(__mlir_attr.`#kgen.dtype.constant<ui8> : !kgen.dtype`)
"""Represents an unsigned integer type whose bitwidth is 8."""
alias int16 = DType(__mlir_attr.`#kgen.dtype.constant<si16> : !kgen.dtype`)
"""Represents a signed integer type whose bitwidth is 16."""
alias uint16 = DType(__mlir_attr.`#kgen.dtype.constant<ui16> : !kgen.dtype`)
"""Represents an unsigned integer type whose bitwidth is 16."""
alias int32 = DType(__mlir_attr.`#kgen.dtype.constant<si32> : !kgen.dtype`)
"""Represents a signed integer type whose bitwidth is 32."""
alias uint32 = DType(__mlir_attr.`#kgen.dtype.constant<ui32> : !kgen.dtype`)
"""Represents an unsigned integer type whose bitwidth is 32."""
alias int64 = DType(__mlir_attr.`#kgen.dtype.constant<si64> : !kgen.dtype`)
"""Represents a signed integer type whose bitwidth is 64."""
alias uint64 = DType(__mlir_attr.`#kgen.dtype.constant<ui64> : !kgen.dtype`)
"""Represents an unsigned integer type whose bitwidth is 64."""
alias bfloat16 = DType(
__mlir_attr.`#kgen.dtype.constant<bf16> : !kgen.dtype`
)
"""Represents a brain floating point value whose bitwidth is 16."""
alias float16 = DType(__mlir_attr.`#kgen.dtype.constant<f16> : !kgen.dtype`)
"""Represents an IEEE754-2008 `binary16` floating point value."""
alias float32 = DType(__mlir_attr.`#kgen.dtype.constant<f32> : !kgen.dtype`)
"""Represents an IEEE754-2008 `binary32` floating point value."""
alias tensor_float32 = DType(
__mlir_attr.`#kgen.dtype.constant<tf32> : !kgen.dtype`
)
"""Represents a special floating point format supported by NVIDIA Tensor
Cores, with the same range as float32 and reduced precision (>=10 bits).
Note that this type is only available on NVIDIA GPUs.
"""
alias float64 = DType(__mlir_attr.`#kgen.dtype.constant<f64> : !kgen.dtype`)
"""Represents an IEEE754-2008 `binary64` floating point value."""
alias index = DType(__mlir_attr.`#kgen.dtype.constant<index> : !kgen.dtype`)
"""Represents an integral type whose bitwidth is the maximum integral value
on the system."""
@always_inline
fn __init__(inout self, *, other: Self):
"""Copy this DType.
Args:
other: The DType to copy.
"""
self = other
@staticmethod
fn _from_str(str: String) -> DType:
"""Construct a DType from a string.
Args:
str: The name of the DType.
"""
if str.startswith(String("DType.")):
return Self._from_str(str.removeprefix("DType."))
elif str == String("bool"):
return DType.bool
elif str == String("int8"):
return DType.int8
elif str == String("uint8"):
return DType.uint8
elif str == String("int16"):
return DType.int16
elif str == String("uint16"):
return DType.uint16
elif str == String("int32"):
return DType.int32
elif str == String("uint32"):
return DType.uint32
elif str == String("int64"):
return DType.int64
elif str == String("uint64"):
return DType.uint64
elif str == String("index"):
return DType.index
elif str == String("bfloat16"):
return DType.bfloat16
elif str == String("float16"):
return DType.float16
elif str == String("float32"):
return DType.float32
elif str == String("float64"):
return DType.float64
elif str == String("tensor_float32"):
return DType.tensor_float32
elif str == String("invalid"):
return DType.invalid
else:
return DType.invalid
@no_inline
fn __str__(self) -> String:
"""Gets the name of the DType.
Returns:
The name of the dtype.
"""
return String.format_sequence(self)
@no_inline
fn format_to(self, inout writer: Formatter):
"""
Formats this dtype to the provided formatter.
Args:
writer: The formatter to write to.
"""
if self == DType.bool:
return writer.write_str("bool")
if self == DType.int8:
return writer.write_str("int8")
if self == DType.uint8:
return writer.write_str("uint8")
if self == DType.int16:
return writer.write_str("int16")
if self == DType.uint16:
return writer.write_str("uint16")
if self == DType.int32:
return writer.write_str("int32")
if self == DType.uint32:
return writer.write_str("uint32")
if self == DType.int64:
return writer.write_str("int64")
if self == DType.uint64:
return writer.write_str("uint64")
if self == DType.index:
return writer.write_str("index")
if self == DType.bfloat16:
return writer.write_str("bfloat16")
if self == DType.float16:
return writer.write_str("float16")
if self == DType.float32:
return writer.write_str("float32")
if self == DType.tensor_float32:
return writer.write_str("tensor_float32")
if self == DType.float64:
return writer.write_str("float64")
if self == DType.invalid:
return writer.write_str("invalid")
return writer.write_str("<<unknown>>")
@always_inline("nodebug")
fn __repr__(self) -> String:
"""Gets the representation of the DType e.g. `"DType.float32"`.
Returns:
The representation of the dtype.
"""
return "DType." + str(self)
@always_inline("nodebug")
fn get_value(self) -> __mlir_type.`!kgen.dtype`:
"""Gets the associated internal kgen.dtype value.
Returns:
The kgen.dtype value.
"""
return self.value
@staticmethod
fn _from_ui8(ui8: __mlir_type.ui8) -> DType:
return __mlir_op.`pop.dtype.from_ui8`(ui8)
@staticmethod
fn _from_ui8(ui8: __mlir_type.`!pop.scalar<ui8>`) -> DType:
return DType._from_ui8(
__mlir_op.`pop.cast_to_builtin`[_type = __mlir_type.ui8](ui8)
)
@always_inline("nodebug")
fn _as_i8(
self,
) -> __mlir_type.`!pop.scalar<ui8>`:
var val = __mlir_op.`pop.dtype.to_ui8`(self.value)
return __mlir_op.`pop.cast_from_builtin`[
_type = __mlir_type.`!pop.scalar<ui8>`
](val)
@always_inline("nodebug")
fn __is__(self, rhs: DType) -> Bool:
"""Compares one DType to another for equality.
Args:
rhs: The DType to compare against.
Returns:
True if the DTypes are the same and False otherwise.
"""
return self == rhs
@always_inline("nodebug")
fn __isnot__(self, rhs: DType) -> Bool:
"""Compares one DType to another for inequality.
Args:
rhs: The DType to compare against.
Returns:
True if the DTypes are the same and False otherwise.
"""
return self != rhs
@always_inline("nodebug")
fn __eq__(self, rhs: DType) -> Bool:
"""Compares one DType to another for equality.
Args:
rhs: The DType to compare against.
Returns:
True if the DTypes are the same and False otherwise.
"""
return __mlir_op.`pop.cmp`[pred = __mlir_attr.`#pop<cmp_pred eq>`](
self._as_i8(), rhs._as_i8()
)
@always_inline("nodebug")
fn __ne__(self, rhs: DType) -> Bool:
"""Compares one DType to another for inequality.
Args:
rhs: The DType to compare against.
Returns:
False if the DTypes are the same and True otherwise.
"""
return __mlir_op.`pop.cmp`[pred = __mlir_attr.`#pop<cmp_pred ne>`](
self._as_i8(), rhs._as_i8()
)
fn __hash__(self) -> UInt:
"""Return a 64-bit hash for this `DType` value.
Returns:
A 64-bit integer hash of this `DType` value.
"""
return hash(UInt8(self._as_i8()))
@always_inline("nodebug")
fn is_unsigned(self) -> Bool:
"""Returns True if the type parameter is unsigned and False otherwise.
Returns:
Returns True if the input type parameter is unsigned.
"""
if not self.is_integral():
return False
return Bool(
__mlir_op.`pop.cmp`[pred = __mlir_attr.`#pop<cmp_pred eq>`](
__mlir_op.`pop.and`(self._as_i8(), _mIsSigned.value),
UInt8(0).value,
)
)
@always_inline("nodebug")
fn is_signed(self) -> Bool:
"""Returns True if the type parameter is signed and False otherwise.
Returns:
Returns True if the input type parameter is signed.
"""
if self is DType.index or self.is_floating_point():
return True
if not self.is_integral():
return False
return Bool(
__mlir_op.`pop.cmp`[pred = __mlir_attr.`#pop<cmp_pred ne>`](
__mlir_op.`pop.and`(self._as_i8(), _mIsSigned.value),
UInt8(0).value,
)
)
@always_inline("nodebug")
fn _is_non_index_integral(self) -> Bool:
"""Returns True if the type parameter is a non-index integer value and False otherwise.
Returns:
Returns True if the input type parameter is a non-index integer.
"""
return Bool(
__mlir_op.`pop.cmp`[pred = __mlir_attr.`#pop<cmp_pred ne>`](
__mlir_op.`pop.and`(self._as_i8(), _mIsInteger.value),
UInt8(0).value,
)
)
@always_inline("nodebug")
fn is_integral(self) -> Bool:
"""Returns True if the type parameter is an integer and False otherwise.
Returns:
Returns True if the input type parameter is an integer.
"""
if self is DType.index:
return True
return self._is_non_index_integral()
@always_inline("nodebug")
fn is_floating_point(self) -> Bool:
"""Returns True if the type parameter is a floating-point and False
otherwise.
Returns:
Returns True if the input type parameter is a floating-point.
"""
if self.is_integral():
return False
return Bool(
__mlir_op.`pop.cmp`[pred = __mlir_attr.`#pop<cmp_pred ne>`](
__mlir_op.`pop.and`(self._as_i8(), _mIsFloat.value),
UInt8(0).value,
)
)
@always_inline("nodebug")
fn is_half_float(self) -> Bool:
"""Returns True if the type is a half-precision floating point type,
e.g. either fp16 or bf16.
Returns:
True if the type is a half-precision float, false otherwise..
"""
return self in (DType.bfloat16, DType.float16)
@always_inline("nodebug")
fn is_numeric(self) -> Bool:
"""Returns True if the type parameter is numeric (i.e. you can perform
arithmetic operations on).
Returns:
Returns True if the input type parameter is either integral or
floating-point.
"""
return self.is_integral() or self.is_floating_point()
@always_inline
fn sizeof(self) -> Int:
"""Returns the size in bytes of the current DType.
Returns:
Returns the size in bytes of the current DType.
"""
if self._is_non_index_integral():
return int(
UInt8(
__mlir_op.`pop.shl`(
UInt8(1).value,
__mlir_op.`pop.sub`(
__mlir_op.`pop.shr`(
__mlir_op.`pop.and`(
self._as_i8(), _mIsNotInteger.value
),
UInt8(1).value,
),
UInt8(3).value,
),
)
)
)
if self == DType.bool:
return sizeof[DType.bool]()
if self == DType.index:
return sizeof[DType.index]()
if self == DType.bfloat16:
return sizeof[DType.bfloat16]()
if self == DType.float16:
return sizeof[DType.float16]()
if self == DType.float32:
return sizeof[DType.float32]()
if self == DType.tensor_float32:
return sizeof[DType.tensor_float32]()
if self == DType.float64:
return sizeof[DType.float64]()
return sizeof[DType.invalid]()
@always_inline
fn bitwidth(self) -> Int:
"""Returns the size in bits of the current DType.
Returns:
Returns the size in bits of the current DType.
"""
return 8 * self.sizeof()
# ===----------------------------------------------------------------------===#
# dispatch_integral
# ===----------------------------------------------------------------------===#
@always_inline
fn dispatch_integral[
func: fn[type: DType] () capturing -> None
](self) raises:
"""Dispatches an integral function corresponding to the current DType.
Constraints:
DType must be integral.
Parameters:
func: A parametrized on dtype function to dispatch.
"""
if self is DType.uint8:
func[DType.uint8]()
elif self is DType.int8:
func[DType.int8]()
elif self is DType.uint16:
func[DType.uint16]()
elif self is DType.int16:
func[DType.int16]()
elif self is DType.uint32:
func[DType.uint32]()
elif self is DType.int32:
func[DType.int32]()
elif self is DType.uint64:
func[DType.uint64]()
elif self is DType.int64:
func[DType.int64]()
elif self is DType.index:
func[DType.index]()
else:
raise Error("only integral types are supported")
# ===----------------------------------------------------------------------===#
# dispatch_floating
# ===----------------------------------------------------------------------===#
@always_inline
fn dispatch_floating[
func: fn[type: DType] () capturing -> None
](self) raises:
"""Dispatches a floating-point function corresponding to the current DType.
Constraints:
DType must be floating-point or integral.
Parameters:
func: A parametrized on dtype function to dispatch.
"""
if self is DType.float16:
func[DType.float16]()
# TODO(#15473): Enable after extending LLVM support
# elif self is DType.bfloat16:
# func[DType.bfloat16]()
elif self is DType.float32:
func[DType.float32]()
elif self is DType.float64:
func[DType.float64]()
else:
raise Error("only floating point types are supported")
@always_inline
fn _dispatch_bitwidth[
func: fn[type: DType] () capturing -> None,
](self) raises:
"""Dispatches a function corresponding to the current DType's bitwidth.
This should only be used if func only depends on the bitwidth of the dtype,
and not other properties of the dtype.
Parameters:
func: A parametrized on dtype function to dispatch.
"""
var bitwidth = self.bitwidth()
if bitwidth == 8:
func[DType.uint8]()
elif bitwidth == 16:
func[DType.uint16]()
elif bitwidth == 32:
func[DType.uint32]()
elif bitwidth == 64:
func[DType.uint64]()
else:
raise Error(
"bitwidth_dispatch only supports types with bitwidth [8, 16,"
" 32, 64]"
)
return
@always_inline
fn _dispatch_custom[
func: fn[type: DType] () capturing -> None, *dtypes: DType
](self) raises:
"""Dispatches a function corresponding to current DType if it matches
any type in the dtypes parameter.
Parameters:
func: A parametrized on dtype function to dispatch.
dtypes: A list of DTypes on which to do dispatch.
"""
alias dtype_var = VariadicList[DType](dtypes)
@parameter
for idx in range(len(dtype_var)):
alias dtype = dtype_var[idx]
if self == dtype:
return func[dtype]()
raise Error(
"dispatch_custom: dynamic_type does not match any dtype parameters"
)
# ===----------------------------------------------------------------------===#
# dispatch_arithmetic
# ===----------------------------------------------------------------------===#
@always_inline
fn dispatch_arithmetic[
func: fn[type: DType] () capturing -> None
](self) raises:
"""Dispatches a function corresponding to the current DType.
Parameters:
func: A parametrized on dtype function to dispatch.
"""
if self.is_floating_point():
self.dispatch_floating[func]()
elif self.is_integral():
self.dispatch_integral[func]()
else:
raise Error("only arithmetic types are supported")
# ===-------------------------------------------------------------------===#
# integral_type_of
# ===-------------------------------------------------------------------===#
@always_inline("nodebug")
fn _integral_type_of[type: DType]() -> DType:
"""Gets the integral type which has the same bitwidth as the input type."""
@parameter
if type.is_integral():
return type
@parameter
if type is DType.bfloat16 or type is DType.float16:
return DType.int16
@parameter
if type is DType.float32 or type is DType.tensor_float32:
return DType.int32
@parameter
if type is DType.float64:
return DType.int64
return type.invalid
# ===-------------------------------------------------------------------===#
# _unsigned_integral_type_of
# ===-------------------------------------------------------------------===#
@always_inline("nodebug")
fn _unsigned_integral_type_of[type: DType]() -> DType:
"""Gets the unsigned integral type which has the same bitwidth as
the input type."""
@parameter
if type.is_integral():
return _uint_type_of_width[bitwidthof[type]()]()
@parameter
if type is DType.bfloat16 or type is DType.float16:
return DType.uint16
@parameter
if type is DType.float32 or type is DType.tensor_float32:
return DType.uint32
@parameter
if type is DType.float64:
return DType.uint64
return type.invalid
# ===-------------------------------------------------------------------===#
# _scientific_notation_digits
# ===-------------------------------------------------------------------===#
fn _scientific_notation_digits[type: DType]() -> StringLiteral:
"""Get the number of digits as a StringLiteral for the scientific notation
representation of a float.
"""
constrained[type.is_floating_point(), "expected floating point type"]()
@parameter
if type is DType.bfloat16 or type is DType.float16:
return "4"
elif type is DType.float32 or type is DType.tensor_float32:
return "8"
else:
constrained[type is DType.float64, "unknown floating point type"]()
return "16"
# ===-------------------------------------------------------------------===#
# _int_type_of_width
# ===-------------------------------------------------------------------===#
fn _int_type_of_width[width: Int]() -> DType:
@parameter
if width == 8:
return DType.int8
elif width == 16:
return DType.int16
elif width == 32:
return DType.int32
else:
constrained[width == 64]()
return DType.int64
# ===-------------------------------------------------------------------===#
# _uint_type_of_width
# ===-------------------------------------------------------------------===#
fn _uint_type_of_width[width: Int]() -> DType:
@parameter
if width == 8:
return DType.uint8
elif width == 16:
return DType.uint16
elif width == 32:
return DType.uint32
else:
constrained[width == 64]()
return DType.uint64
# ===-------------------------------------------------------------------===#
# printf format
# ===-------------------------------------------------------------------===#
@always_inline
fn _index_printf_format() -> StringLiteral:
@parameter
if bitwidthof[Int]() == 32:
return "%d"
elif os_is_windows():
return "%lld"
else:
return "%ld"
@always_inline
fn _get_dtype_printf_format[type: DType]() -> StringLiteral:
@parameter
if type is DType.bool:
return _index_printf_format()
elif type is DType.uint8:
return "%hhu"
elif type is DType.int8:
return "%hhi"
elif type is DType.uint16:
return "%hu"
elif type is DType.int16:
return "%hi"
elif type is DType.uint32:
return "%u"
elif type is DType.int32:
return "%i"
elif type is DType.int64:
@parameter
if os_is_windows():
return "%lld"
else:
return "%ld"
elif type is DType.uint64:
@parameter
if os_is_windows():
return "%llu"
else:
return "%lu"
elif type is DType.index:
return _index_printf_format()
elif type.is_floating_point():
return "%.17g"
else:
constrained[False, "invalid dtype"]()
return ""