Mojo DType
A DType names a number format: how many bits a number gets and what those bits mean. DType.float32 is a 32-bit floating-point number, DType.uint8 is an 8-bit whole number from 0 to 255, and so on. You met DType as the first parameter of SIMD in the last lesson. Here you’ll see which formats exist, what each one can hold, and how to pick one. That choice matters for correctness (can the number fit?) and for speed (how many fit in one SIMD register?).
DType is a name, not a number
Section titled “DType is a name, not a number”A DType value doesn’t hold any data. It’s a label you can print, compare and pass around:
def main(): print(DType.float32) print(DType.uint8) print(DType.float32 == DType.float32, DType.int8 == DType.uint8)Output:
float32uint8True FalseHere are the ones you’ll actually use:
| DType | Short name | What it holds |
|---|---|---|
DType.int8, .int16, .int32, .int64 |
Int8 … Int64 |
Whole numbers, with a sign |
DType.uint8, .uint16, .uint32, .uint64 |
UInt8 … UInt64 |
Whole numbers, 0 and up |
DType.int, DType.uint |
Int, UInt |
Machine-sized whole numbers (64-bit on today’s 64-bit computers) |
DType.float16, .float32, .float64 |
Float16 … Float64 |
Numbers with a fractional part |
DType.bfloat16 |
BFloat16 |
A 16-bit float used in machine learning |
DType.bool |
Bool lanes in a mask |
True or False |
There are more: 128- and 256-bit integers, and several 8-bit and 4-bit float formats for machine learning. The DType reference lists every one. Not every format works on every machine; for example, the docs say bfloat16 isn’t supported on Apple silicon yet.
Every number type is a DType plus a width of 1
Section titled “Every number type is a DType plus a width of 1”You saw that Float32 is a one-lane SIMD. Put the pieces together:
Float32isScalar[DType.float32],- which is
SIMD[DType.float32, 1].
So every number in Mojo carries a DType, and you can ask any SIMD value for it with .dtype:
def main(): var price: Float32 = 9.99 var pixels = SIMD[DType.uint8, 4](255, 128, 0, 64) print(price.dtype) print(pixels.dtype)Output:
float32uint8If you’ve used NumPy, this will feel familiar: np.float32 and arr.dtype work the same way. The difference is that in Mojo the DType is part of the type, so it’s known while compiling, not just at run time.
How many bytes each one takes
Section titled “How many bytes each one takes”size_of from std.sys tells you how much memory one value of a DType uses. This small function takes the DType as a parameter in square brackets and asks a few questions about it:
from std.sys import size_of
def describe[dt: DType](): print(dt, size_of[dt](), "bytes, float:", dt.is_floating_point(), "signed:", dt.is_signed())
def main(): describe[DType.uint8]() describe[DType.int32]() describe[DType.float16]() describe[DType.float64]() describe[DType.bool]()Output:
uint8 1 bytes, float: False signed: Falseint32 4 bytes, float: False signed: Truefloat16 2 bytes, float: True signed: Truefloat64 8 bytes, float: True signed: Truebool 1 bytes, float: False signed: Falseis_floating_point(), is_signed(), is_unsigned() and is_integral() answer the obvious questions. A bool uses a full byte in memory, even though it only needs one bit.
The limits of each format
Section titled “The limits of each format”Every integer type has MIN and MAX:
def main(): print(UInt8.MIN, UInt8.MAX) print(Int8.MIN, Int8.MAX) print(Int16.MAX, UInt32.MAX) var level: Int8 = 100 print(level * 2)Output:
0 255-128 12732767 4294967295-56The last line is the trap. 100 * 2 is 200, which doesn’t fit in an Int8, so it wraps around to -56. No error, no warning. The Mojo Integer Overflow lesson covers this for Int; with small types it just happens much sooner.
For floats, MAX is not what you’d guess:
def main(): print(Float32.MAX) print(Float32.MAX_FINITE) print(Float64.MAX_FINITE)Output:
inf3.4028235e+381.7976931348623157e+308Float32.MAX is infinity, because infinity really is the largest value a float can hold. Use MAX_FINITE when you want the largest ordinary number.
Floats are approximations
Section titled “Floats are approximations”Fewer bits means fewer digits of precision. 0.1 can’t be stored exactly in binary, and a Float32 gets it “less exactly” than a Float64:
def main(): var a: Float32 = 0.1 var b: Float64 = 0.1 print(a, b) print(Float64(a)) var h: Float16 = 2049 print(h)Output:
0.1 0.10.100000001490116122048.0Both print as 0.1, because print shows the shortest text that reads back as the same value. Widen the Float32 to a Float64 and you see what it really stored. Float16 is rougher still: it can’t even hold the whole number 2049, so you get 2048.
Mixing types is an error
Section titled “Mixing types is an error”Mojo won’t quietly mix two different DTypes:
def main(): var a: Int32 = 5 var b: Int64 = 7 print(a + b)hello.mojo:4:15: error: invalid call to '__add__': value passed to 'rhs' cannot be converted from 'Int64' to 'Int32' print(a + b) ~~~~^mojo: error: failed to parse the provided Mojo source moduleIn Python this would just work, because Python has one integer type. In Mojo you pick the format yourself, and convert on purpose with .cast[...]():
def main(): var a: Int32 = 5 var b: Int64 = 7 print(a.cast[DType.int64]() + b) var big: Int32 = 300 print(big.cast[DType.uint8]()) print(Float64(3.99).cast[DType.int32]())Output:
12443Casting does exactly what you ask, even when the value doesn’t fit. 300 doesn’t fit in a uint8, so only its low 8 bits survive (300 - 256 = 44). Casting a float to an integer drops the fraction. Writing Int64(a) or Float64(x) works too, as the Mojo Type Conversion lesson showed.
Writing code for any DType
Section titled “Writing code for any DType”Because a DType is known at compile time, you can take it as a parameter and write one function for all number formats:
def double[dt: DType](x: Scalar[dt]) -> Scalar[dt]: return x * 2
def kind[dt: DType](): comptime if dt.is_floating_point(): print(dt, "has a fractional part") else: print(dt, "holds whole numbers")
def main(): print(double(Int8(21)), double(Float32(1.25)), double(UInt16(7))) kind[DType.float16]() kind[DType.uint8]()Output:
42 2.5 14float16 has a fractional partuint8 holds whole numbersdouble[dt: DType](x: Scalar[dt]): Mojo works outdtfrom the argument, so you calldouble(Int8(21))without naming it.comptime ifchecks theDTypewhile compiling, so each version ofkindonly contains the branch it needs. The Mojo Parameters and Mojo Generics lessons go deeper into this style.
Choosing a DType
Section titled “Choosing a DType”Smaller formats fit more lanes into one SIMD register, so math on them can go through more numbers per step. You saw it with simd_width_of:
from std.sys import simd_width_of
def main(): print("float64:", simd_width_of[DType.float64]()) print("float32:", simd_width_of[DType.float32]()) print("int16: ", simd_width_of[DType.int16]())You’ll see something like this (on our test machine, a 4-core VM with 512-bit registers; results vary by CPU):
float64: 8float32: 16int16: 32But a smaller type that overflows or loses precision gives you wrong answers fast, which is worse than right answers slowly. A sensible order of questions:
| Question | Then use |
|---|---|
| Counting, indexing, sizes? | Int (what len() and range() use) |
| Data with a fixed format, like pixels or bytes from a file? | That exact format, such as UInt8 |
| Fractional numbers where 7 digits are enough? | Float32 |
| Money, science, long running sums? | Float64 |
| Not sure? | Int or Float64, and change it only after measuring |
Practice
Section titled “Practice”1. Size table
Section titled “1. Size table”Use size_of to print how many bytes an Int16, a UInt64 and a Float32 use, one per line, like int16: 2.
Hint: size_of[DType.int16]() takes the DType in square brackets.
Show solution
from std.sys import size_of
def main(): print("int16:", size_of[DType.int16]()) print("uint64:", size_of[DType.uint64]()) print("float32:", size_of[DType.float32]())Output:
int16: 2uint64: 8float32: 4The number in the name is the number of bits; divide by 8 for bytes.
2. Brighten a pixel safely
Section titled “2. Brighten a pixel safely”A pixel is SIMD[DType.uint8, 4](200, 100, 50, 255). Add 80 to every lane, but don’t let any value wrap around: anything over 255 should stay at 255.
Hint: cast to a wider type first, add, use min with 255, then cast back to uint8.
Show solution
def main(): var pixel = SIMD[DType.uint8, 4](200, 100, 50, 255) print(pixel + 80) var wide = pixel.cast[DType.int32]() + 80 var safe = min(wide, 255).cast[DType.uint8]() print(safe)Output:
[24, 180, 130, 79][255, 180, 130, 255]The first line shows the bug: 200 + 80 and 255 + 80 wrap around. In int32 the sums fit, min caps them at 255, and then they fit back into uint8.
- A
DTypenames a number format (DType.int32,DType.float64,DType.uint8,DType.bool…). It holds no data. - Every number type is a
DTypeplus a width of 1:Float32isSIMD[DType.float32, 1]. Ask any value for its.dtype. size_of[dt]()gives the size in bytes;MIN/MAXgive the limits, and floats haveMAX_FINITE.- Small integers wrap around silently and small floats lose precision: pick a format the data really fits.
- Mojo doesn’t mix
DTypes automatically. Convert with.cast[...](), which keeps low bits and drops fractions. - A
DTypecan be a parameter, so one function works for every format.
Next up: vectorize, the standard library helper that runs your SIMD code over a whole list, chunk by chunk.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- DType (standard library): every
DTypemember and its methods, likeis_floating_point(). - Mojo numeric types reference: tables of integer and float formats,
Scalar,Int,UIntandByte. - Types and literals cheat sheet: number types and conversions on one page.
- size_of: how many bytes a type or
DTypeuses.