Data Types

May 27, 2026 · View on GitHub


Magnetron Logo

magnetron cheatsheet

Reference for data types, operators, and tensor semantics in Magnetron.

Data Types

Magnetron currently supports the following data types, with additional formats planned (e.g. MXFP8).

DTypeTypeSize (bits)Min valueMax value
float16Floating point166.5e4\approx -6.5e46.5e4\approx 6.5e4
bfloat16Floating point163.4e38\approx -3.4e383.4e38\approx 3.4e38
float32Floating point323.4e38\approx -3.4e383.4e38\approx 3.4e38
booleanBoolean8$0$$1$
int8Integer (signed)827-2^{7}$2^{7}-1$
uint8Integer (unsigned)8$0$$2^{8}-1$
int16Integer (signed)16215-2^{15}$2^{15}-1$
uint16Integer (unsigned)16$0$$2^{16}-1$
int32Integer (signed)32231-2^{31}$2^{31}-1$
uint32Integer (unsigned)32$0$$2^{32}-1$
int64Integer (signed)64263-2^{63}$2^{63}-1$

Examples

Create a float16 tensor filled with zeros:

Tensor.zeros(10, dtype=dtype.float16)
``$

\text{Create} \text{a} 2 \times 3 $float32` tensor filled with ones:
```python
Tensor.ones(2, 3, dtype=dtype.float32)

Create a range tensor of integers from 0 to 9:

Tensor.arange(0, 10, dtype=dtype.int64)

Operators

All operations in Magnetron are exposed as methods on Tensor. If you are familiar with PyTorch, think x.sin() instead of torch.sin(x).


Tensor Creation & Initialization

MethodDescriptionMathExample
Tensor.empty(shape)Create an uninitialized tensor (contents undefined)N/Ax = Tensor.empty(2, 3)
Tensor.empty_like(x)Create an uninitialized tensor with same shape and dtype as inputN/Ax = Tensor.empty_like(x)
Tensor.full(shape, v)Create tensor filled with constant valuexi=vx_i = vx = Tensor.full(2, 3, fill_value=3.0)
Tensor.full_like(x, v)Create constant-filled tensor with the same shape as inputxi=vx_i = vx = Tensor.full_like(x, fill_value=3.0)
Tensor.zeros(shape)Create tensor filled with zerosxi=0x_i = 0x = Tensor.zeros(2, 3)
Tensor.zeros_like(x)Create tensor filled with zeros and same shape as inputxi=0x_i = 0x = Tensor.zeros_like(x)
Tensor.ones(shape)Create tensor filled with onesxi=1x_i = 1x = Tensor.ones(2, 3)
Tensor.ones_like(x)Create tensor filled with ones and same shape as inputxi=1x_i = 1x = Tensor.ones_like(x)
Tensor.uniform(a,b)Fill with uniform random valuesxU(a,b)x\sim U(a,b)x = Tensor.uniform(2, 3, low=-1.0, high=1.0)
Tensor.uniform_like(x, a, b)Create tensor filled with uniform random values and same shape as inputxU(a,b)x\sim U(a,b)x = Tensor.uniform_like(x, low=-1.0, high=1.0)
Tensor.normal(μ, σ)Fill with normal distributionxN(μ,σ)x\sim\mathcal N(\mu,\sigma)x = Tensor.normal(2, 3, mean=0.0, std=1.0)
Tensor.normal_like(x, μ, σ)Create tensor filled with normal random values and same shape as inputxN(μ,σ)x\sim\mathcal N(\mu,\sigma)x = Tensor.normal_like(x, mean=0.0, std=1.0)
Tensor.bernoulli(p)Fill with Bernoulli samplesxBern(p)x\sim\text{Bern}(p)x = Tensor.bernoulli(2, 3, p=0.5)
Tensor.bernoulli_like(x, p)Create tensor filled with bernoulli random values and same shape as inputxBern(p)x\sim\text{Bern}(p)x = Tensor.bernoulli_like(x, p=0.5)
Tensor.arange(a,b,s)Create evenly spaced values from start to stopa,a+s,<ba, a+s, \dots < bx = Tensor.arange(0, 10, 2)
Tensor.rand_perm(n)Random permutation of integerspermutation of {0..n1}\{0..n-1\}x = Tensor.rand_perm(10)
Tensor.one_hot(c)Convert indices to one-hot vectorsyi,j=[xi=j]y_{i,j}=[x_i=j]x = idx.one_hot(10)
Tensor.load_image(p)Load image file into tensorN/Aimg = Tensor.load_image("img.png")

Type & Device Conversion

MethodDescriptionExample
cast(dtype)Return tensor with new dtypex.cast(dtype.float16)
transfer(device)Move tensor to devicex.transfer('cuda')

Filling & Mutation

MethodDescriptionMathExample
fill_(v)Fill tensor in-place with constant valuexi=vx_i=vx.fill_(0)
zeros_()In-place fill with zerosxi=0x_i=0x.zeros_()
ones_()In-place fill with onesxi=1x_i=1x.ones_()
copy_(y)Copy data from another tensorx=yx=yx.copy_(y)
masked_fill(mask,v)Replace values where mask is truexi=vx_i=v if mim_iy = x.masked_fill(m,0)
masked_fill_(mask,v)In-place masked fillN/Ax.masked_fill_(m,0)
uniform_(a,b)Fill with uniform random valuesxU(a,b)x\sim U(a,b)x.uniform_(0,1)
normal_(μ,σ)Fill with normal distributionxN(μ,σ)x\sim\mathcal N(\mu,\sigma)x.normal_(0,1)
bernoulli_(p)Fill with Bernoulli samplesxBern(p)x\sim\text{Bern}(p)x.bernoulli_(0.5)
Tensor.where(cond,x,y)Conditional elementwise selectionzi=xi if ci else yiz_i = x_i \text{ if } c_i \text{ else } y_iz = Tensor.where(x > 0, x, 0)
clamp(min,max)Clamp values into an intervalyi=min(max(xi,mini),maxi)y_i=\min(\max(x_i,\mathrm{min}_i),\mathrm{max}_i)y = x.clamp(-1, 1)

Shape, Views & Indexing

MethodDescriptionMathExample
clone()Create a deep copy of the tensorN/Ay = x.clone()
copy_(src)Copy data from src into this tensor in-placeselfsrcself \leftarrow srcx.copy_(y)
view(shape)Create a view with new shapeN/Ax.view(2, -1)
view_slice(d,s,l)Slice tensor without copyingx[s:s+l]x[s:s+l]x.view_slice(0,0,4)
reshape(shape)Reshape tensor (may copy)N/Ax.reshape(4,3)
transpose(a,b)Swap two dimensionsxTx^Tx.transpose(0,1)
permute(dims)Reorder dimensions arbitrarilyN/Ax.permute(1,0,2)
contiguous()Ensure tensor is contiguous in memoryN/Ax = x.contiguous()
squeeze()Remove dimensions of size 1N/Ax.squeeze()
unsqueeze(d)Insert new dimensionN/Ax.unsqueeze(0)
flatten(a,b)Flatten a range of dimensionsN/Ax.flatten(1)
unflatten(s)Expand flattened dimensionN/Ax.unflatten((2,3))
narrow(d,s,l)Take slice along dimensionN/Ax.narrow(1,0,4)
movedim(a,b)Move dimension to new positionN/Ax.movedim(0,-1)
select(d,i)Select single index along dimx[...,i]x[...,i]x.select(1,2)
split(n,d)Split tensor into chunksN/Ax.split(4,1)
cat(xs,d)Concatenate tensorsN/ATensor.cat([a,b],1)
gather(d,idx)Gather elements by index tensoryi=xidxiy_i=x_{idx_i}x.gather(1,idx)

Reductions

MethodDescriptionMathExample
mean(dim=-1)Compute mean over elements1Nx\frac1N\sum xx.mean()
sum(dim=-1)Sum elementsx\sum xx.sum()
prod(dim=-1)Product of elementsx\prod xx.prod()
min(dim=None, keepdim=False)Reduction minimum, or elementwise min if argument is tensor/scalarmin(x)\min(x) / min(x,y)\min(x,y)x.min() / x.min(y)
max(dim=None, keepdim=False)Reduction maximum, or elementwise max if argument is tensor/scalarmax(x)\max(x) / max(x,y)\max(x,y)x.max() / x.max(y)
argmin(dim=-1)Index of minimumargmin(x)\arg\min(x)x.argmin()
argmax(dim=-1)Index of maximumargmax(x)\arg\max(x)x.argmax()
any(dim=-1)True if any element is non-zeroxi0\exists x_i\neq0x.any()
all(dim=-1)True if all elements are non-zeroxi0\forall x_i\neq0x.all()
topk(k, dim=-1, largest=True, sorted=True)Select k largest valuestopk(x,k)={(xij,ij)}j=1k,  xi1xik\mathrm{topk}(x,k)=\{(x_{i_j},i_j)\}_{j=1}^k,\;x_{i_1}\ge\dots\ge x_{i_k}values, indices = x.topk(k)

Unary Math Operations

MethodDescriptionMath (per element)Example
abs()Absolute valuey=xy = \vert x \verty = x.abs()
sgn()Sign of each elementy=sign(x)y = \mathrm{sign}(x)y = x.sgn()
neg()Negationy=xy = -xy = x.neg()
sqr()Squarey=x2y = x^2y = x.sqr()
rcp()Reciprocaly=1xy = \frac{1}{x}y = x.rcp()
sqrt()Square rooty=xy = \sqrt{x}y = x.sqrt()
rsqrt()Inverse square rooty=1xy = \frac{1}{\sqrt{x}}y = x.rsqrt()
log()Natural logarithmy=ln(x)y = \ln(x)y = x.log()
log2()Base-2 logarithmy=log2(x)y = \log_2(x)y = x.log2()
log10()Base-10 logarithmy=log10(x)y = \log_{10}(x)y = x.log10()
log1p()Log of (1 + x)y=ln(1+x)y = \ln(1 + x)y = x.log1p()
exp()Exponentialy=exy = e^xy = x.exp()
exp2()Power of 2y=2xy = 2^xy = x.exp2()
expm1()Exponential minus 1y=ex1y = e^x - 1y = x.expm1()
floor()Round downy=xy = \lfloor x \rfloory = x.floor()
ceil()Round upy=xy = \lceil x \rceily = x.ceil()
round()Round to nearest integery=round(x)y = \mathrm{round}(x)y = x.round()
trunc()Truncate fractional party=trunc(x)y = \mathrm{trunc}(x)y = x.trunc()
sin()Siney=sin(x)y = \sin(x)y = x.sin()
cos()Cosiney=cos(x)y = \cos(x)y = x.cos()
tan()Tangenty=tan(x)y = \tan(x)y = x.tan()
asin()Inverse siney=arcsin(x)y = \arcsin(x)y = x.asin()
acos()Inverse cosiney=arccos(x)y = \arccos(x)y = x.acos()
atan()Inverse tangenty=arctan(x)y = \arctan(x)y = x.atan()
sinh()Hyperbolic siney=sinh(x)y = \sinh(x)y = x.sinh()
cosh()Hyperbolic cosiney=cosh(x)y = \cosh(x)y = x.cosh()
tanh()Hyperbolic tangenty=tanh(x)y = \tanh(x)y = x.tanh()
asinh()Inverse hyperbolic siney=asinh(x)y = \mathrm{asinh}(x)y = x.asinh()
acosh()Inverse hyperbolic cosiney=acosh(x)y = \mathrm{acosh}(x)y = x.acosh()
atanh()Inverse hyperbolic tangenty=atanh(x)y = \mathrm{atanh}(x)y = x.atanh()
step()Heaviside step (0/1)y=1[x>0]y = \mathbb{1}[x > 0]y = x.step()
erf()Error functiony=erf(x)y = \mathrm{erf}(x)y = x.erf()
erfc()Complementary error functiony=erfc(x)y = \mathrm{erfc}(x)y = x.erfc()
softmax()Softmax over last dimyi=exijexjy_i = \frac{e^{x_i}}{\sum_j e^{x_j}}y = x.softmax()
sigmoid()Logistic sigmoidy=11+exy = \frac{1}{1 + e^{-x}}y = x.sigmoid()
hard_sigmoid()Piecewise linear sigmoidy=min(1,max(0,x+36))y = \min(1, \max(0, \frac{x + 3}{6}))y = x.hard_sigmoid()
silu()SiLU / Swishy=xσ(x)y = x \cdot \sigma(x)y = x.silu()
relu()Rectified Linear Unity=max(0,x)y = \max(0,x)y = x.relu()
gelu()Exact GELUy=xΦ(x)y = x \cdot \Phi(x)y = x.gelu()
gelu_approx()Fast approximate GELUy0.5x(1+tanh())y \approx 0.5x(1+\tanh(\cdots))y = x.gelu_approx()

Binary Arithmetic

MethodOperatorDescriptionMathExample
add()+Elementwise additionx+yx+yx + y
sub()-Elementwise subtractionxyx-yx - y
mul()*Elementwise multiplicationxyx\cdot yx * y
div()/Elementwise divisionxy\frac{x}{y}x / y
floordiv()//Elementwise floor divisionxy\lfloor\frac{x}{y}\rfloorx // y
mod()%Elementwise modulusxmodyx\bmod yx % y
pow()**Elementwise exponentiationxyx^yx ** y
matmul()@Matrix multiplicationXYXYx @ y
scaled_matmul(w, scale)N/AMatrix multiplication with output/input scaleXYsXY\cdot s or implementation-defined scaled GEMMx.scaled_matmul(w, scale)
min(y)N/AElementwise minimummin(x,y)\min(x,y)x.min(y)
max(y)N/AElementwise maximummax(x,y)\max(x,y)x.max(y)

Comparison

MethodOperatorDescriptionExample
eq()==Elementwise equalityx == y
ne()!=Elementwise inequalityx != y
lt()<Elementwise less-thanx < y
le()<=Elementwise less-or-equalx <= y
gt()>Elementwise greater-thanx > y
ge()>=Elementwise greater-or-equalx >= y

Logical & Bitwise

MethodOperatorDescriptionMathExample
logical_and()&Elementwise ANDxyx\land yx & y
logical_or()|Elementwise ORxyx\lor yx | y
logical_xor()^Elementwise XORxyx\oplus yx ^ y
logical_not()~Elementwise NOT¬x\lnot x~x
bitwise_and()&Elementwise ANDxyx\land yx & y
bitwise_or()|Bitwise ORxyx\lor yx | y
bitwise_xor()^Bitwise XORxyx\oplus yx ^ y
bitwise_not()~Bitwise NOT¬x\lnot x~x
bitwise_shl()<<Bitwise shift leftxkx\ll kx << 1
bitwise_shr()>>Bitwise shift rightxkx\gg kx >> 1

Sampling

MethodDescriptionMathExample
multinomial(k, replacement)Sample indices from a categorical distributionPr(i=m)=xmjxj\Pr(i=m)=\frac{x_m}{\sum_j x_j}idx = probs.multinomial(k)

Matrix Utilities

MethodDescriptionMathExample
tril()Lower-triangular matrixiji\ge jx.tril()
triu()Upper-triangular matrixiji\le jx.triu()