Complex Ops
Reduce¤
sum
¤
sum(
axis: int | Sequence[int] | None = None,
keepdim=False,
dtype: DTypeLike | None = None,
) -> Self
Returns the sum of the elements of the tensor along the specified axis or axes.
You can pass in axis and keepdim keyword arguments to control the axis along
which the maximum is computed and whether the reduced dimensions are retained.
You can pass in dtype keyword argument to control the data type of the accumulation.
If not specified, the accumulation data type is chosen based on the input tensor's data type.
t = Tensor.arange(6).reshape(2, 3)
print(t.numpy())
[[0 1 2]
[3 4 5]]
print(t.sum().numpy())
15
print(t.sum(axis=0).numpy())
[3 5 7]
print(t.sum(axis=1).numpy())
[ 3 12]
Source code in tinygrad/mixin/reduce.py
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 | |
prod
¤
prod(
axis: int | Sequence[int] | None = None,
keepdim=False,
dtype: DTypeLike | None = None,
) -> Self
Returns the product of the elements of the tensor along the specified axis or axes.
You can pass in axis and keepdim keyword arguments to control the axis along
which the maximum is computed and whether the reduced dimensions are retained.
You can pass in dtype keyword argument to control the data type of the accumulation.
If not specified, the accumulation data type is chosen based on the input tensor's data type.
t = Tensor([-1, -2, -3, 1, 2, 3]).reshape(2, 3)
print(t.numpy())
[[-1 -2 -3]
[ 1 2 3]]
print(t.prod().numpy())
-36
print(t.prod(axis=0).numpy())
[-1 -4 -9]
print(t.prod(axis=1).numpy())
[-6 6]
Source code in tinygrad/mixin/reduce.py
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 | |
max
¤
Returns the maximum value of the tensor along the specified axis or axes.
You can pass in axis and keepdim keyword arguments to control the axis along
which the maximum is computed and whether the reduced dimensions are retained.
t = Tensor([[1, 0, 2], [5, 4, 3]])
print(t.numpy())
[[1 0 2]
[5 4 3]]
print(t.max().numpy())
5
print(t.max(axis=0).numpy())
[5 4 3]
print(t.max(axis=1, keepdim=True).numpy())
[[2]
[5]]
Source code in tinygrad/mixin/reduce.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
min
¤
Returns the minimum value of the tensor along the specified axis or axes.
You can pass in axis and keepdim keyword arguments to control the axis along
which the minimum is computed and whether the reduced dimensions are retained.
t = Tensor([[1, 0, 2], [5, 4, 3]])
print(t.numpy())
[[1 0 2]
[5 4 3]]
print(t.min().numpy())
0
print(t.min(axis=0).numpy())
[1 0 2]
print(t.min(axis=1, keepdim=True).numpy())
[[0]
[3]]
Source code in tinygrad/tensor.py
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 | |
any
¤
Tests if any element evaluates to True along the specified axis or axes.
You can pass in axis and keepdim keyword arguments to control the reduce axis and whether the reduced dimensions are retained.
t = Tensor([[True, True], [True, False], [False, False]])
print(t.numpy())
[[ True True]
[ True False]
[False False]]
print(t.any().numpy())
True
print(t.any(axis=0).numpy())
[ True True]
print(t.any(axis=1, keepdim=True).numpy())
[[ True]
[ True]
[False]]
Source code in tinygrad/tensor.py
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 | |
all
¤
Tests if all element evaluates to True along the specified axis or axes.
You can pass in axis and keepdim keyword arguments to control the reduce axis and whether the reduced dimensions are retained.
t = Tensor([[True, True], [True, False], [False, False]])
print(t.numpy())
[[ True True]
[ True False]
[False False]]
print(t.all().numpy())
False
print(t.all(axis=0).numpy())
[False False]
print(t.all(axis=1, keepdim=True).numpy())
[[ True]
[False]
[False]]
Source code in tinygrad/tensor.py
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 | |
isclose
¤
Returns a new tensor with element-wise comparison of closeness to other within a tolerance.
The rtol and atol keyword arguments control the relative and absolute tolerance of the comparison.
By default, two NaN values are not close to each other. If equal_nan is True, two NaN values are considered close.
print(Tensor([1e-7, 1e-8, 1e-9, float('nan')]).isclose(Tensor([0.0, 0.0, 0.0, float('nan')])).numpy())
[False True True False]
print(Tensor([float('nan')]).isclose(Tensor([float('nan')]), equal_nan=True).numpy())
[ True]
Source code in tinygrad/tensor.py
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 | |
allclose
¤
Check if all self and other are close. Return True or False.
Source code in tinygrad/tensor.py
1708 1709 1710 1711 1712 | |
mean
¤
Returns the mean value of the tensor along the specified axis or axes.
You can pass in axis and keepdim keyword arguments to control the axis along
which the mean is computed and whether the reduced dimensions are retained.
Tensor.manual_seed(42)
t = Tensor.normal(2, 3, mean=2.5, std=0.5)
print(t.numpy())
[[3.4788 2.407 3.3202]
[2.1177 2.0653 2.2811]]
print(t.mean().numpy())
2.6116748
print(t.mean(axis=0).numpy())
[2.7982 2.2361 2.8006]
print(t.mean(axis=1).numpy())
[3.0687 2.1547]
Source code in tinygrad/tensor.py
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 | |
var
¤
Returns the variance of the tensor along the specified axis or axes.
You can pass in axis, keepdim, and correction keyword arguments to control the axis along
which the variance is computed, whether the reduced dimensions are retained, and the Bessel's correction applied.
Tensor.manual_seed(42)
t = Tensor.normal(2, 3, mean=2.5, std=0.5)
print(t.numpy())
[[3.4788 2.407 3.3202]
[2.1177 2.0653 2.2811]]
print(t.var().numpy())
0.38955206
print(t.var(axis=0).numpy())
[0.9264 0.0584 0.5399]
print(t.var(axis=1).numpy())
[0.3346 0.0127]
Source code in tinygrad/tensor.py
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 | |
var_mean
¤
var_mean(
axis: int | Sequence[int] | None = None,
keepdim=False,
correction=1,
) -> tuple[Tensor, Tensor]
Calculates the variance and mean over the dimensions specified by dim.
Syntactic sugar around Tensor.var and Tensor.mean to match torch.var_mean.
Tensor.manual_seed(42)
t = Tensor.normal(2, 3, mean=2.5, std=0.5)
print(t.numpy())
[[3.4788 2.407 3.3202]
[2.1177 2.0653 2.2811]]
var, mean = t.var_mean()
print(var.numpy(), mean.numpy())
0.38955206 2.6116748
Source code in tinygrad/tensor.py
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 | |
std
¤
Returns the standard deviation of the tensor along the specified axis or axes.
You can pass in axis, keepdim, and correction keyword arguments to control the axis along
which the standard deviation is computed, whether the reduced dimensions are retained, and the Bessel's correction applied.
Tensor.manual_seed(42)
t = Tensor.normal(2, 3, mean=2.5, std=0.5)
print(t.numpy())
[[3.4788 2.407 3.3202]
[2.1177 2.0653 2.2811]]
print(t.std().numpy())
0.62414104
print(t.std(axis=0).numpy())
[0.9625 0.2417 0.7348]
print(t.std(axis=1).numpy())
[0.5785 0.1126]
Source code in tinygrad/tensor.py
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 | |
std_mean
¤
std_mean(
axis: int | Sequence[int] | None = None,
keepdim=False,
correction=1,
) -> tuple[Tensor, Tensor]
Calculates the standard deviation and mean over the dimensions specified by dim.
Syntactic sugar around Tensor.std and Tensor.mean to match torch.std_mean.
Tensor.manual_seed(42)
t = Tensor.normal(2, 3, mean=2.5, std=0.5)
print(t.numpy())
[[3.4788 2.407 3.3202]
[2.1177 2.0653 2.2811]]
std, mean = t.std_mean()
print(std.numpy(), mean.numpy())
0.62414104 2.6116748
Source code in tinygrad/tensor.py
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 | |
softmax
¤
softmax(axis=-1, dtype: DTypeLike | None = None) -> Tensor
Applies the softmax function to the tensor along the specified axis.
Rescales the elements of the tensor such that they lie in the range [0, 1] and sum to 1.
You can pass in the axis keyword argument to control the axis along which the softmax is computed.
Tensor.manual_seed(42)
t = Tensor.randn(2, 3)
print(t.numpy())
[[ 1.9576 -0.1859 1.6404]
[-0.7647 -0.8695 -0.4379]]
print(t.softmax().numpy())
[[0.5419 0.0635 0.3946]
[0.3042 0.274 0.4218]]
print(t.softmax(axis=0).numpy())
[[0.9383 0.6645 0.8888]
[0.0617 0.3355 0.1112]]
Source code in tinygrad/tensor.py
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 | |
log_softmax
¤
log_softmax(
axis=-1, dtype: DTypeLike | None = None
) -> Tensor
Applies the log-softmax function to the tensor along the specified axis.
The log-softmax function is a numerically stable alternative to the softmax function in log space.
You can pass in the axis keyword argument to control the axis along which the log-softmax is computed.
Tensor.manual_seed(42)
t = Tensor.randn(2, 3)
print(t.numpy())
[[ 1.9576 -0.1859 1.6404]
[-0.7647 -0.8695 -0.4379]]
print(t.log_softmax().numpy())
[[-0.6127 -2.7563 -0.9299]
[-1.19 -1.2948 -0.8632]]
print(t.log_softmax(axis=0).numpy())
[[-0.0637 -0.4087 -0.1179]
[-2.786 -1.0922 -2.1962]]
Source code in tinygrad/tensor.py
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 | |
logsumexp
¤
logsumexp(axis=None, keepdim=False) -> Tensor
Computes the log-sum-exp of the tensor along the specified axis or axes.
The log-sum-exp function is a numerically stable way to compute the logarithm of the sum of exponentials.
You can pass in axis and keepdim keyword arguments to control the axis along
which the log-sum-exp is computed and whether the reduced dimensions are retained.
Tensor.manual_seed(42)
t = Tensor.randn(2, 3)
print(t.numpy())
[[ 1.9576 -0.1859 1.6404]
[-0.7647 -0.8695 -0.4379]]
print(t.logsumexp().numpy())
2.681043
print(t.logsumexp(axis=0).numpy())
[2.0213 0.2227 1.7583]
print(t.logsumexp(axis=1).numpy())
[2.5703 0.4253]
Source code in tinygrad/tensor.py
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 | |
logcumsumexp
¤
logcumsumexp(axis=0) -> Tensor
Computes the log-cumsum-exp of the tensor along the specified axis or axes.
The log-cumsum-exp function is a numerically stable way to compute the logarithm of the cumulative sum of exponentials.
You can pass in the axis keyword argument to control the axis along which
the log-cumsum-exp is computed.
Tensor.manual_seed(42)
t = Tensor.randn(2, 3)
print(t.numpy())
[[ 1.9576 -0.1859 1.6404]
[-0.7647 -0.8695 -0.4379]]
print(t.logcumsumexp().numpy())
[[ 1.9576 -0.1859 1.6404]
[ 2.0213 0.2227 1.7583]]
print(t.logcumsumexp(axis=0).numpy())
[[ 1.9576 -0.1859 1.6404]
[ 2.0213 0.2227 1.7583]]
print(t.logcumsumexp(axis=1).numpy())
[[ 1.9576 2.0685 2.5703]
[-0.7647 -0.1226 0.4253]]
Source code in tinygrad/tensor.py
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 | |
argmax
¤
argmax(axis=None, keepdim=False) -> Tensor
Returns the indices of the maximum value of the tensor along the specified axis.
You can pass in axis and keepdim keyword arguments to control the axis along
which the maximum is computed and whether the reduced dimensions are retained.
t = Tensor([[1, 0, 2], [5, 4, 3]])
print(t.numpy())
[[1 0 2]
[5 4 3]]
print(t.argmax().numpy()) # Returns the index of the maximum value in the flattened tensor.
3
print(t.argmax(axis=0).numpy()) # Returns the indices of the maximum values along axis 0.
[1 1 1]
print(t.argmax(axis=1).numpy()) # Returns the indices of the maximum values along axis 1.
[2 0]
Source code in tinygrad/tensor.py
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 | |
argmin
¤
argmin(axis=None, keepdim=False) -> Tensor
Returns the indices of the minimum value of the tensor along the specified axis.
You can pass in axis and keepdim keyword arguments to control the axis along
which the minimum is computed and whether the reduced dimensions are retained.
t = Tensor([[1, 0, 2], [5, 4, 3]])
print(t.numpy())
[[1 0 2]
[5 4 3]]
print(t.argmin().numpy()) # Returns the index of the minimum value in the flattened tensor.
1
print(t.argmin(axis=0).numpy()) # Returns the indices of the minimum values along axis 0.
[0 0 0]
print(t.argmin(axis=1).numpy()) # Returns the indices of the minimum values along axis 1.
[1 2]
Source code in tinygrad/tensor.py
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 | |
Processing¤
avg_pool2d
¤
avg_pool2d(
kernel_size: tuple[int, ...] = (2, 2),
stride=None,
dilation=1,
padding: int | tuple[int, ...] = 0,
ceil_mode=False,
count_include_pad=True,
) -> Tensor
Applies average pooling over a tensor.
This function supports three different types of padding
-
int(single value): Applies the same padding value uniformly to all spatial dimensions. -
tuple[int, ...](length = number of spatial dimensions): Specifies a distinct padding value for each spatial dimension in the form(padding_height, padding_width, ...). -
tuple[int, ...](length = 2 * number of spatial dimensions): Specifies explicit padding for each side of each spatial dimension in the form(padding_left, padding_right, padding_top, padding_bottom, ...).
When ceil_mode is set to True, output shape will be determined using ceil division.
When count_include_pad is set to False, zero padding will not be included in the averaging calculation.
Note
unlike PyTorch, this implementation is not limited to only 2d pooling and instead works for any number of dimensions.
t = Tensor.arange(25).reshape(1, 1, 5, 5)
print(t.avg_pool2d().numpy())
[[[[ 3. 5.]
[13. 15.]]]]
print(t.avg_pool2d(ceil_mode=True).numpy())
[[[[ 3. 5. 6.5]
[13. 15. 16.5]
[20.5 22.5 24. ]]]]
print(t.avg_pool2d(padding=1).numpy())
[[[[ 0. 0.75 1.75]
[ 3.75 9. 11. ]
[ 8.75 19. 21. ]]]]
print(t.avg_pool2d(padding=1, count_include_pad=False).numpy())
[[[[ 0. 1.5 3.5]
[ 7.5 9. 11. ]
[17.5 19. 21. ]]]]
Source code in tinygrad/tensor.py
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 | |
max_pool2d
¤
max_pool2d(
kernel_size: tuple[int, ...] = (2, 2),
stride=None,
dilation=1,
padding: int | tuple[int, ...] = 0,
ceil_mode=False,
return_indices=False,
) -> Tensor | tuple[Tensor, Tensor]
Applies max pooling over a tensor.
This function supports three different types of padding
-
int(single value): Applies the same padding value uniformly to all spatial dimensions. -
tuple[int, ...](length = number of spatial dimensions): Specifies a distinct padding value for each spatial dimension in the form(padding_height, padding_width, ...). -
tuple[int, ...](length = 2 * number of spatial dimensions): Specifies explicit padding for each side of each spatial dimension in the form(padding_left, padding_right, padding_top, padding_bottom, ...).
When ceil_mode is set to True, output shape will be determined using ceil division.
When return_indices is set to True, the argmax will be returned along with the max values.
Note
unlike PyTorch, this implementation is not limited to only 2d pooling and instead works for any number of dimensions.
t = Tensor.arange(25).reshape(1, 1, 5, 5)
print(t.max_pool2d().numpy())
[[[[ 6 8]
[16 18]]]]
print(t.max_pool2d(ceil_mode=True).numpy())
[[[[ 6 8 9]
[16 18 19]
[21 23 24]]]]
print(t.max_pool2d(padding=1).numpy())
[[[[ 0 2 4]
[10 12 14]
[20 22 24]]]]
Source code in tinygrad/tensor.py
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 | |
max_unpool2d
¤
max_unpool2d(
indices: Tensor,
kernel_size: tuple[int, ...] = (2, 2),
stride=None,
dilation=1,
padding: int | tuple[int, ...] = 0,
output_size=None,
)
Performs a partial inverse of max_pool2d using the indices from the argmax.
When output_size is provided, the output shape disambiguates to the provided shape.
Note
unlike PyTorch, this implementation is not limited to only 2d pooling and instead works for any number of dimensions.
t = Tensor.arange(1, 17).reshape(1, 1, 4, 4)
print(t.numpy())
[[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]]]
output, indices = Tensor.max_pool2d(t, return_indices=True)
print(output.numpy())
print(indices.numpy())
[[[[ 6 8]
[14 16]]]]
[[[[ 5 7]
[13 15]]]]
print(Tensor.max_unpool2d(output, indices).numpy())
[[[[ 0 0 0 0]
[ 0 6 0 8]
[ 0 0 0 0]
[ 0 14 0 16]]]]
Source code in tinygrad/tensor.py
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 | |
conv2d
¤
conv2d(
weight: Tensor,
bias: Tensor | None = None,
groups=1,
stride=1,
dilation=1,
padding: int | tuple[int, ...] = 0,
dtype: DTypeLike | None = None,
) -> Tensor
Applies a convolution over a tensor with a given weight and optional bias.
This function supports three different types of padding
-
int(single value): Applies the same padding value uniformly to all spatial dimensions. -
tuple[int, ...](length = number of spatial dimensions): Specifies a distinct padding value for each spatial dimension in the form(padding_height, padding_width, ...). -
tuple[int, ...](length = 2 * number of spatial dimensions): Specifies explicit padding for each side of each spatial dimension in the form(padding_left, padding_right, padding_top, padding_bottom, ...).
Note
unlike PyTorch, this implementation is not limited to only 2d convolutions and instead works for any number of dimensions.
See: https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html
t = Tensor.arange(9).reshape(1, 1, 3, 3)
w = Tensor.ones(1, 1, 2, 2)
print(t.conv2d(w).numpy())
[[[[ 8. 12.]
[20. 24.]]]]
Source code in tinygrad/tensor.py
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 | |
conv_transpose2d
¤
conv_transpose2d(
weight: Tensor,
bias: Tensor | None = None,
groups=1,
stride=1,
dilation=1,
padding=0,
output_padding=0,
) -> Tensor
Applies a transposed convolution over a tensor with a given weight and optional bias.
This function supports three different types of padding
-
int(single value): Applies the same padding value uniformly to all spatial dimensions. -
tuple[int, ...](length = number of spatial dimensions): Specifies a distinct padding value for each spatial dimension in the form(padding_height, padding_width, ...). -
tuple[int, ...](length = 2 * number of spatial dimensions): Specifies explicit padding for each side of each spatial dimension in the form(padding_left, padding_right, padding_top, padding_bottom, ...).
Note
unlike PyTorch, this implementation is not limited to only 2d transposed convolutions and instead works for any number of dimensions.
See: https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html
t = Tensor.arange(9).reshape(1, 1, 3, 3)
w = Tensor.ones(1, 1, 2, 2)
print(t.conv_transpose2d(w).numpy())
[[[[ 0. 1. 3. 2.]
[ 3. 8. 12. 7.]
[ 9. 20. 24. 13.]
[ 6. 13. 15. 8.]]]]
Source code in tinygrad/tensor.py
2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 | |
dot
¤
Source code in tinygrad/tensor.py
2396 2397 2398 2399 2400 2401 | |
matmul
¤
Performs matrix multiplication between two tensors.
You can pass in the reverse keyword argument to control the order of the matrix multiplication.
You can pass in the optional dtype keyword argument to control the data type of the accumulation.
a = Tensor([[1, 2], [3, 4]])
b = Tensor([[5, 6], [7, 8]])
print(a.matmul(b).numpy())
[[19 22]
[43 50]]
Source code in tinygrad/mixin/__init__.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 | |
einsum
staticmethod
¤
einsum(
formula: str,
*operands: Tensor | Sequence[Tensor],
dtype: DTypeLike | None = None
) -> Tensor
Sums the product of the elements of the input tensors according to a formula based on the Einstein summation convention.
See: https://pytorch.org/docs/stable/generated/torch.einsum.html
x = Tensor([[1, 2], [3, 4]])
y = Tensor([[5, 6], [7, 8]])
print(Tensor.einsum("ij,ij->", x, y).numpy())
70
Source code in tinygrad/tensor.py
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 | |
cumsum
¤
Computes the cumulative sum of the tensor along the specified axis.
t = Tensor.ones(2, 3)
print(t.numpy())
[[1. 1. 1.]
[1. 1. 1.]]
print(t.cumsum(1).numpy())
[[1. 2. 3.]
[1. 2. 3.]]
Source code in tinygrad/tensor.py
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 | |
cumprod
¤
Computes the cumulative product of the elements of the tensor along the specified axis.
t = Tensor.arange(1, 7).reshape(2, 3)
print(t.numpy())
[[1 2 3]
[4 5 6]]
print(t.cumprod(axis=0).numpy())
[[ 1 2 3]
[ 4 10 18]]
Source code in tinygrad/tensor.py
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 | |
cummax
¤
Computes the cumulative max of the tensor along axis, returning (values, indices).
t = Tensor([0, 1, -1, 2, -2, 3, -3])
values, indices = t.cummax(0)
print(values.numpy())
print(indices.numpy())
[0 1 1 2 2 3 3]
[0 1 1 3 3 5 5]
Source code in tinygrad/tensor.py
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 | |
cummin
¤
Computes the cumulative min of the tensor along axis, returning (values, indices).
t = Tensor([0, 1, -1, 2, -2, 3, -3])
values, indices = t.cummin(0)
print(values.numpy())
print(indices.numpy())
[ 0 0 -1 -1 -2 -2 -3]
[0 0 2 2 4 4 6]
Source code in tinygrad/tensor.py
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 | |
triu
¤
triu(diagonal: sint = 0) -> Tensor
Returns the upper triangular part of the tensor, the other elements are set to 0.
The argument diagonal determines which diagonal is on the boundary. diagonal = 0 means the main diagonal.
Positive diagonal means above the main diagonal, and negative diagonal means below the main diagonal.
t = Tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(t.numpy())
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
print(t.triu(diagonal=0).numpy())
[[ 1 2 3 4]
[ 0 6 7 8]
[ 0 0 11 12]]
print(t.triu(diagonal=1).numpy())
[[ 0 2 3 4]
[ 0 0 7 8]
[ 0 0 0 12]]
print(t.triu(diagonal=-1).numpy())
[[ 1 2 3 4]
[ 5 6 7 8]
[ 0 10 11 12]]
Source code in tinygrad/tensor.py
2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 | |
tril
¤
tril(diagonal: sint = 0) -> Tensor
Returns the lower triangular part of the tensor, the other elements are set to 0.
The argument diagonal determines which diagonal is on the boundary. diagonal = 0 means the main diagonal.
Positive diagonal means above the main diagonal, and negative diagonal means below the main diagonal.
t = Tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(t.numpy())
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
print(t.tril(diagonal=0).numpy())
[[ 1 0 0 0]
[ 5 6 0 0]
[ 9 10 11 0]]
print(t.tril(diagonal=1).numpy())
[[ 1 2 0 0]
[ 5 6 7 0]
[ 9 10 11 12]]
print(t.tril(diagonal=-1).numpy())
[[ 0 0 0 0]
[ 5 0 0 0]
[ 9 10 0 0]]
Source code in tinygrad/tensor.py
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 | |
interpolate
¤
Downsamples or Upsamples to the input size, accepts 0 to N batch dimensions.
The interpolation algorithm is selected with mode which currently only supports linear, nearest and nearest-exact.
To run bilinear or trilinear, pass in a 2D or 3D size.
t = Tensor([[1, 2, 3, 4], [21, 22, 23, 24], [41, 42, 43, 44]])
print(t.numpy())
[[ 1 2 3 4]
[21 22 23 24]
[41 42 43 44]]
print(t.interpolate(size=(2,3), mode="linear").numpy())
[[ 6 7 8]
[36 37 38]]
Source code in tinygrad/tensor.py
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 | |
scatter
¤
scatter(
dim: int,
index: Tensor,
src: Tensor | PyConst,
reduce: Literal["multiply", "add"] | None = None,
) -> Tensor
Scatters src values along an axis specified by dim.
Apply add or multiply reduction operation with reduce.
Note
To use the reduce argument with a Tensor src, see Tensor.scatter_reduce.
src = Tensor.arange(1, 11).reshape(2, 5)
print(src.numpy())
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
index = Tensor([[0, 1, 2, 0]])
print(Tensor.zeros(3, 5, dtype=src.dtype).scatter(0, index, src).numpy())
[[1 0 0 4 0]
[0 2 0 0 0]
[0 0 3 0 0]]
index = Tensor([[0, 1, 2], [0, 1, 4]])
print(Tensor.zeros(3, 5, dtype=src.dtype).scatter(1, index, src).numpy())
[[1 2 3 0 0]
[6 7 0 0 8]
[0 0 0 0 0]]
print(Tensor.full((2, 4), 2.0).scatter(1, Tensor([[2], [3]]), 1.23, reduce='multiply').numpy())
[[2. 2. 2.46 2. ]
[2. 2. 2. 2.46]]
print(Tensor.full((2, 4), 2.0).scatter(1, Tensor([[2], [3]]), 1.23, reduce='add').numpy())
[[2. 2. 3.23 2. ]
[2. 2. 2. 3.23]]
Source code in tinygrad/tensor.py
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 | |
scatter_reduce
¤
scatter_reduce(
dim: int,
index: Tensor,
src: Tensor,
reduce: Literal["sum", "prod", "mean", "amax", "amin"],
include_self: bool = True,
) -> Tensor
Scatters src values along an axis specified by dim.
Apply "sum", "prod", "mean", "amax", or "amin" reduction operations with reduce.
Set include_self=False to exclude values in the self Tensor from the reduction.
src = Tensor.arange(1, 11).cast(dtypes.float).reshape(2, 5)
print(src.numpy())
index = Tensor([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
print(index.numpy())
[[ 1. 2. 3. 4. 5.]
[ 6. 7. 8. 9. 10.]]
[[0 0 0 0 0]
[0 0 0 0 0]]
print(Tensor.ones(1, 5, dtype=src.dtype).scatter_reduce(0, index, src, reduce='sum').numpy())
[[ 8. 10. 12. 14. 16.]]
print(Tensor.ones(1, 5, dtype=src.dtype).scatter_reduce(0, index, src, reduce='prod').numpy())
[[ 6. 14. 24. 36. 50.]]
print(Tensor.ones(1, 5, dtype=src.dtype).scatter_reduce(0, index, src, reduce='mean', include_self=False).numpy())
[[3.5 4.5 5.5 6.5 7.5]]
print(Tensor([[-10, 20, 0, 5, 10]], dtype=src.dtype).scatter_reduce(0, index, src, reduce='amax').numpy())
[[ 6. 20. 8. 9. 10.]]
print(Tensor([[-10, 20, 0, 5, 10]], dtype=src.dtype).scatter_reduce(0, index, src, reduce='amin').numpy())
[[-10. 2. 0. 4. 5.]]
Source code in tinygrad/tensor.py
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 | |
masked_select
¤
masked_select(mask)
Selects elements from self based on the boolean mask.
t = Tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
mask = Tensor([[True, False, True], [False, True, False], [False, False, True]])
print(t.numpy())
print(mask.numpy())
[[0 1 2]
[3 4 5]
[6 7 8]]
[[ True False True]
[False True False]
[False False True]]
print(t.masked_select(mask).numpy())
[0 2 4 8]
Source code in tinygrad/tensor.py
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 | |
masked_fill
¤
Replaces self with value wherever the elements of mask are True.
t = Tensor([1, 2, 3, 4, 5])
mask = Tensor([True, False, True, False, False])
print(t.masked_fill(mask, -12).numpy())
[-12 2 -12 4 5]
t = Tensor([1, 2, 3, 4, 5])
mask = Tensor([True, False, True, False, False])
value = Tensor([-1, -2, -3, -4, -5])
print(t.masked_fill(mask, value).numpy())
[-1 2 -3 4 5]
Source code in tinygrad/tensor.py
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 | |
nonzero
¤
nonzero() -> Tensor
Returns the indices of the elements that are non-zero.
Returns a 2D tensor where each row is the index of a non-zero element.
t = Tensor([1, 0, 2, 0, 3])
print(t.numpy())
[1 0 2 0 3]
print(t.nonzero().numpy())
[[0]
[2]
[4]]
t = Tensor([[1, 0], [0, 2]])
print(t.numpy())
[[1 0]
[0 2]]
print(t.nonzero().numpy())
[[0 0]
[1 1]]
Source code in tinygrad/tensor.py
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 | |
sort
¤
Performs a bitonic sort on the tensor along the specified dimension.
Order of indices for equivalent elements is always preserved.
See: https://en.wikipedia.org/wiki/Bitonic_sorter
t = Tensor([[0.1, 0.5, 1.2, 3.4, 2.1], [2.2, 1.9, 0.3, 4.5, 0.8]])
print(t.numpy())
[[0.1 0.5 1.2 3.4 2.1]
[2.2 1.9 0.3 4.5 0.8]]
sorted_values, indices = t.sort(dim=1, descending=True)
print(sorted_values.numpy())
print(indices.numpy())
[[3.4 2.1 1.2 0.5 0.1]
[4.5 2.2 1.9 0.8 0.3]]
[[3 4 2 1 0]
[3 0 1 4 2]]
Source code in tinygrad/tensor.py
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 | |
argsort
¤
Returns the indices that sort input tensor along given dimension in given descending order by value.
t = Tensor([[2, 3, 4, 1], [1, 4, 3, 2]])
print(t.argsort().numpy())
[[3 0 1 2]
[0 3 2 1]]
Source code in tinygrad/tensor.py
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 | |
topk
¤
Computes the top-k elements of the tensor along the specified dim.
Order of indices for equivalent elements is always preserved.
t = Tensor([[0.1, 0.5, 1.2, 3.4, 2.1], [2.2, 1.9, 0.3, 4.5, 0.8]])
print(t.numpy())
[[0.1 0.5 1.2 3.4 2.1]
[2.2 1.9 0.3 4.5 0.8]]
topk_values, topk_indices = t.topk(2, dim=1)
print(topk_values.numpy())
print(topk_indices.numpy())
[[3.4 2.1]
[4.5 2.2]]
[[3 4]
[3 0]]
Source code in tinygrad/tensor.py
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 | |
multinomial
¤
Returns a tensor with num_samples indices sampled from a multinomial distribution weighted by self.
Note
replacement=False for num_samples > 1 is not supported yet.
Tensor.manual_seed(42)
t = Tensor([1, 2, 3, 4])
print(t.multinomial(20, replacement=True).numpy())
[3 2 3 1 2 3 2 3 0 1 2 3 1 2 2 1 2 2 3 3]
Source code in tinygrad/tensor.py
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 | |
Neural Network (functional)¤
linear
¤
Applies a linear transformation to self using weight and bias.
See: https://pytorch.org/docs/stable/generated/torch.nn.Linear.html
t = Tensor([[1, 2], [3, 4]])
weight = Tensor([[1, 2], [3, 4]])
bias = Tensor([1, 2])
print(t.linear(weight, bias).numpy())
[[ 8 12]
[16 24]]
Source code in tinygrad/tensor.py
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 | |
sequential
¤
Applies a sequence of functions to self chaining the output of each function to the input of the next.
t = Tensor([1, 2, 3])
print(t.sequential([lambda x: x * 2, lambda x: x + 1]).numpy())
[3 5 7]
Source code in tinygrad/tensor.py
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 | |
layernorm
¤
Applies Layer Normalization over a mini-batch of inputs.
t = Tensor.randn(8, 10, 16) * 2 + 8
print(t.mean().item(), t.std().item())
7.967566967010498 1.9459360837936401
t = t.layernorm()
print(t.mean().item(), t.std().item())
-3.414653448885474e-09 1.0003889799118042
Source code in tinygrad/tensor.py
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 | |
batchnorm
¤
batchnorm(
weight: Tensor | None,
bias: Tensor | None,
mean: Tensor,
invstd: Tensor,
axis: int | tuple[int, ...] = 1,
) -> Tensor
Applies Batch Normalization over a mini-batch of inputs.
t = Tensor.randn(8, 4, 16, 16) * 2 + 8
print(t.mean().item(), t.std().item())
8.022211074829102 2.003443479537964
t = t.batchnorm(None, None, t.mean(axis=(0,2,3)), t.var(axis=(0,2,3)).add(1e-5).rsqrt())
print(t.mean().item(), t.std().item())
9.536140765931123e-08 0.9998152256011963
Source code in tinygrad/tensor.py
3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 | |
dropout
¤
dropout(p=0.5) -> Tensor
Applies dropout to self.
Note
dropout is only applied when Tensor.training is True.
Tensor.manual_seed(42)
t = Tensor.randn(2, 2)
with Tensor.train():
print(t.dropout().numpy())
[[1.2452 0.3412]
[1.6594 0.6135]]
Source code in tinygrad/tensor.py
3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 | |
one_hot
¤
Converts self to a one-hot tensor.
num_classes defaults to -1, which means num_classes will be inferred as max(self) + 1.
t = Tensor([0, 1, 3, 3, 4])
print(t.one_hot(5).numpy())
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 0 1 0]
[0 0 0 1 0]
[0 0 0 0 1]]
Source code in tinygrad/tensor.py
3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 | |
scaled_dot_product_attention
¤
scaled_dot_product_attention(
key: Tensor,
value: Tensor,
attn_mask: Tensor | None = None,
dropout_p: float = 0.0,
is_causal: bool = False,
enable_gqa: bool = False,
) -> Tensor
Computes scaled dot-product attention.
self is the query tensor, key is the key tensor, and value is the value tensor.
q = Tensor.randn(2, 4, 8)
k = Tensor.randn(2, 4, 8)
v = Tensor.randn(2, 4, 8)
print(q.scaled_dot_product_attention(k, v).numpy())
[[[ 1.0179 -0.1569 0.2824 -0.4453 -0.2782 -1.3624 -0.8654 0.0421]
[ 0.3478 -0.7684 0.9486 1.0626 -0.3239 -0.3466 0.5342 -0.1153]
[ 0.4184 -0.4923 0.5823 0.3521 -0.2315 -0.6822 0.0829 0.2321]
[ 0.9673 -0.1948 0.2563 -0.4294 -0.2532 -1.3211 -0.7997 0.0848]]
[[-0.2036 0.4213 0.8622 -0.9485 0.3362 -0.3886 0.1038 0.3896]
[-0.0297 1.2289 0.512 -0.3317 0.3861 -0.3695 0.1857 0.4452]
[-0.4912 0.4212 0.9596 -1.3411 0.4038 -0.5133 -0.2132 0.4209]
[-0.0036 0.6412 0.8896 -0.6953 0.3864 -0.4349 0.501 0.4907]]]
Source code in tinygrad/tensor.py
3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 | |
binary_crossentropy
¤
Computes the binary cross-entropy loss between self and Y.
See: https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html
t = Tensor([0.1, 0.9, 0.2])
Y = Tensor([0, 1, 0])
print(t.binary_crossentropy(Y).item())
0.14462155103683472
Source code in tinygrad/tensor.py
3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 | |
binary_crossentropy_logits
¤
binary_crossentropy_logits(
Y: Tensor,
reduction: ReductionStr = "mean",
pos_weight: Tensor | None = None,
) -> Tensor
Computes the binary cross-entropy loss between self and Y where self is logits.
See: https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html
t = Tensor([-1, 2, -3])
Y = Tensor([0, 1, 0])
print(t.binary_crossentropy_logits(Y).item())
0.16292566061019897
Source code in tinygrad/tensor.py
3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 | |
sparse_categorical_crossentropy
¤
sparse_categorical_crossentropy(
Y: Tensor,
ignore_index: int = -1,
label_smoothing=0.0,
reduction: ReductionStr = "mean",
) -> Tensor
Computes the sparse categorical cross-entropy loss between self and Y.
Note
self is logits and Y is the target labels.
NOTE: unlike PyTorch, this function expects the class axis to be -1
See: https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html
t = Tensor([[-1, 2, -3], [1, -2, 3]])
Y = Tensor([1, 2])
print(t.sparse_categorical_crossentropy(Y).item())
0.09391524642705917
Source code in tinygrad/tensor.py
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 | |
cross_entropy
¤
cross_entropy(
Y: Tensor,
reduction: ReductionStr = "mean",
label_smoothing: float = 0.0,
) -> Tensor
Computes the cross entropy loss between input logits and target.
Note
self are logits and Y are the target labels or class probabilities.
See: https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html
t = Tensor([[-1, 2, -3], [1, -2, 3]])
Y = Tensor([1, 2])
print(t.cross_entropy(Y).item())
0.09391524642705917
t = Tensor([[-1, 2, -3], [1, -2, 3]])
Y = Tensor([1, 2])
print(t.cross_entropy(Y, reduction='none').numpy())
[0.055 0.1328]
Source code in tinygrad/tensor.py
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 | |
nll_loss
¤
nll_loss(
Y: Tensor,
weight: Tensor | None = None,
ignore_index: int | None = None,
reduction: ReductionStr = "mean",
) -> Tensor
Computes the negative log likelihood loss between log-probabilities and target labels.
Note
self is log-probabilities and Y is the Y labels or class probabilities.
See: https://pytorch.org/docs/stable/generated/torch.nn.functional.nll_loss.html
t = Tensor([[-1, 2, -3], [1, -2, 3]])
Y = Tensor([1, 2])
print(t.log_softmax().nll_loss(Y).item())
0.09391524642705917
t = Tensor([[-1, 2, -3], [1, -2, 3]])
Y = Tensor([1, 2])
print(t.log_softmax().nll_loss(Y, reduction='none').numpy())
[0.055 0.1328]
Source code in tinygrad/tensor.py
3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 | |
Linear Algebra¤
qr
¤
Source code in tinygrad/tensor.py
3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 | |
svd
¤
Source code in tinygrad/tensor.py
3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 | |