tinygrad 0.9.1__py3-none-any.whl → 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. tinygrad/__init__.py +11 -6
  2. tinygrad/codegen/kernel.py +308 -175
  3. tinygrad/codegen/linearize.py +95 -0
  4. tinygrad/codegen/lowerer.py +143 -0
  5. tinygrad/codegen/transcendental.py +257 -0
  6. tinygrad/codegen/uopgraph.py +506 -0
  7. tinygrad/device.py +72 -171
  8. tinygrad/dtype.py +122 -47
  9. tinygrad/engine/jit.py +184 -87
  10. tinygrad/{lazy.py → engine/lazy.py} +74 -66
  11. tinygrad/engine/memory.py +51 -0
  12. tinygrad/engine/realize.py +86 -61
  13. tinygrad/engine/schedule.py +366 -317
  14. tinygrad/engine/search.py +58 -47
  15. tinygrad/function.py +59 -58
  16. tinygrad/helpers.py +120 -102
  17. tinygrad/multi.py +82 -78
  18. tinygrad/nn/__init__.py +116 -67
  19. tinygrad/nn/datasets.py +12 -5
  20. tinygrad/nn/optim.py +1 -1
  21. tinygrad/nn/state.py +91 -6
  22. tinygrad/ops.py +1126 -143
  23. tinygrad/renderer/__init__.py +47 -23
  24. tinygrad/renderer/cstyle.py +338 -265
  25. tinygrad/renderer/llvmir.py +125 -143
  26. tinygrad/renderer/ptx.py +225 -0
  27. tinygrad/runtime/autogen/adreno.py +17904 -0
  28. tinygrad/runtime/autogen/amd_gpu.py +46974 -11993
  29. tinygrad/runtime/autogen/cuda.py +6 -162
  30. tinygrad/runtime/autogen/io_uring.py +97 -63
  31. tinygrad/runtime/autogen/kfd.py +60 -47
  32. tinygrad/runtime/autogen/kgsl.py +1386 -0
  33. tinygrad/runtime/autogen/libc.py +5462 -0
  34. tinygrad/runtime/autogen/nv_gpu.py +1976 -1957
  35. tinygrad/runtime/autogen/nvrtc.py +579 -0
  36. tinygrad/runtime/autogen/opencl.py +11 -11
  37. tinygrad/runtime/autogen/qcom_dsp.py +1739 -0
  38. tinygrad/runtime/graph/clang.py +3 -3
  39. tinygrad/runtime/graph/cuda.py +11 -15
  40. tinygrad/runtime/graph/hcq.py +120 -107
  41. tinygrad/runtime/graph/metal.py +71 -43
  42. tinygrad/runtime/ops_amd.py +244 -323
  43. tinygrad/runtime/ops_clang.py +12 -5
  44. tinygrad/runtime/ops_cloud.py +220 -0
  45. tinygrad/runtime/ops_cuda.py +42 -99
  46. tinygrad/runtime/ops_disk.py +25 -26
  47. tinygrad/runtime/ops_dsp.py +181 -0
  48. tinygrad/runtime/ops_gpu.py +29 -16
  49. tinygrad/runtime/ops_hip.py +68 -0
  50. tinygrad/runtime/ops_llvm.py +15 -10
  51. tinygrad/runtime/ops_metal.py +147 -64
  52. tinygrad/runtime/ops_nv.py +356 -397
  53. tinygrad/runtime/ops_python.py +78 -79
  54. tinygrad/runtime/ops_qcom.py +405 -0
  55. tinygrad/runtime/support/__init__.py +0 -0
  56. tinygrad/runtime/support/compiler_cuda.py +77 -0
  57. tinygrad/runtime/{driver/hip_comgr.py → support/compiler_hip.py} +13 -1
  58. tinygrad/runtime/support/elf.py +38 -0
  59. tinygrad/runtime/support/hcq.py +539 -0
  60. tinygrad/shape/shapetracker.py +40 -50
  61. tinygrad/shape/view.py +102 -63
  62. tinygrad/tensor.py +1109 -365
  63. {tinygrad-0.9.1.dist-info → tinygrad-0.10.0.dist-info}/METADATA +54 -50
  64. tinygrad-0.10.0.dist-info/RECORD +77 -0
  65. {tinygrad-0.9.1.dist-info → tinygrad-0.10.0.dist-info}/WHEEL +1 -1
  66. tinygrad/codegen/linearizer.py +0 -528
  67. tinygrad/codegen/uops.py +0 -451
  68. tinygrad/engine/graph.py +0 -100
  69. tinygrad/renderer/assembly.py +0 -269
  70. tinygrad/shape/symbolic.py +0 -327
  71. tinygrad-0.9.1.dist-info/RECORD +0 -63
  72. /tinygrad/{runtime/driver/__init__.py → py.typed} +0 -0
  73. {tinygrad-0.9.1.dist-info → tinygrad-0.10.0.dist-info}/LICENSE +0 -0
  74. {tinygrad-0.9.1.dist-info → tinygrad-0.10.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,506 @@
1
+ from __future__ import annotations
2
+ from typing import Optional, Tuple, Dict, List, TYPE_CHECKING, Any, DefaultDict, Callable, Set
3
+ import functools, itertools, operator
4
+ from collections import defaultdict
5
+ from tinygrad.dtype import dtypes, ImageDType, PtrDType
6
+ from tinygrad.ops import UOp, Ops, UPat, PatternMatcher, symbolic_flat, symbolic_simple
7
+ from tinygrad.ops import graph_rewrite, split_uop, uop_given_valid, parse_valid, is_increasing, simplify_valid, GroupOp
8
+ from tinygrad.helpers import DEBUG, getenv, flatten, dedup, TRANSCENDENTAL, AMX, prod, partition, all_same
9
+ from tinygrad.codegen.transcendental import xexp2, xlog2, xsin, TRANSCENDENTAL_SUPPORTED_DTYPES
10
+
11
+ if TYPE_CHECKING: from tinygrad.renderer import Renderer
12
+
13
+ # ***** float4/image store handling *****
14
+
15
+ def fold_expanded(ex, buf):
16
+ if buf.dtype.base != dtypes.float and buf.dtype.base != dtypes.half and not isinstance(buf.dtype, ImageDType): return None
17
+ new_srcs = dedup(list(ex.src))
18
+ old_new_srcs = new_srcs[:]
19
+ is_load, is_image = new_srcs[0].op is Ops.LOAD, isinstance(buf.dtype, ImageDType)
20
+
21
+ # first, extract all the relevant offsets
22
+ offsets_rootsrc: DefaultDict[Any, dict] = defaultdict(dict)
23
+ for i,s in enumerate(new_srcs):
24
+ idx = s.src[0].src[1]
25
+ if s.dtype.count != 1 or (is_image and idx.dtype.count == 2): continue
26
+ if idx.op is Ops.ADD and idx.src[1].op is Ops.CONST: root_src, arg = idx.src[0], idx.src[1].arg
27
+ elif idx.op is Ops.CONST: root_src, arg = "CONST", idx.arg
28
+ else: root_src, arg = idx, 0
29
+ # add gates for gated
30
+ if len(s.src[0].src) == 3: root_src = (s.src[0].src[2], root_src)
31
+ assert arg not in offsets_rootsrc[root_src], f"{offsets_rootsrc[root_src][arg]} != {i} with {len(s.src)} sources"
32
+ offsets_rootsrc[root_src][arg] = i
33
+
34
+ # then rewrite everything we can
35
+ lengths = [4] if is_image else ([8,4,2] if buf.dtype.base == dtypes.half and getenv("ALLOW_HALF8") else ([16,8,4,2] if AMX else [4,2]))
36
+ used: Set[Tuple[UOp, UOp]] = set()
37
+ for rootsrc, offsets in offsets_rootsrc.items():
38
+ for o in offsets:
39
+ for fold_length in lengths:
40
+ if all((rootsrc,o+i) not in used and o+i in offsets for i in range(fold_length)):
41
+ load_1 = new_srcs[offsets[o]]
42
+ new_src = list(load_1.src)
43
+ oidx = new_src[0].src[1]
44
+ if oidx.divides(fold_length) is None: continue
45
+ if is_image:
46
+ # for images, we rewrite the index. it must evenly divide 4 from the above check
47
+ new_src[0] = buf.index(
48
+ UOp(Ops.VECTORIZE, dtypes.int.vec(2), ((oidx // 4) % buf.dtype.shape[1], (oidx // (4*buf.dtype.shape[1])))),
49
+ rootsrc[0] if isinstance(rootsrc, tuple) else None)
50
+ else:
51
+ # for non image, we upcast the index pointer
52
+ new_src[0] = new_src[0].cast(new_src[0].dtype.base.vec(fold_length).ptr(new_src[0].dtype.local))
53
+ # generate the folded new_srcs
54
+ if is_load:
55
+ new_load = UOp(Ops.LOAD, load_1.dtype.vec(fold_length), tuple(new_src))
56
+ for i in range(fold_length): new_srcs[offsets[o+i]] = new_load.gep(i)
57
+ else: # vectorize the store
58
+ new_src[1] = UOp(Ops.VECTORIZE, new_src[1].dtype.vec(fold_length), tuple(new_srcs[offsets[o+i]].src[1] for i in range(fold_length)))
59
+ for i in range(fold_length): new_srcs[offsets[o+i]] = UOp(Ops.STORE, dtypes.void, tuple(new_src)) if i == 0 else None
60
+ used.update((rootsrc,o+i) for i in range(fold_length))
61
+
62
+ # dedup expand for LOAD
63
+ if is_load and len(old_new_srcs) != len(ex.src): new_srcs = [new_srcs[old_new_srcs.index(s)] for s in ex.src]
64
+ # remove Nones for STORE
65
+ return UOp(ex.op, ex.dtype, tuple(x for x in new_srcs if x is not None), ex.arg) if len(used) else None
66
+
67
+ def fix_unfoldable_image_load(load:UOp, buf:UOp):
68
+ if not isinstance(buf.dtype, ImageDType) or (oidx:=load.src[0].src[1]).dtype.count == 2: return None
69
+ id4 = oidx % 4
70
+ new_src = list(load.src)
71
+ # TODO: copied logic from above
72
+ new_src[0] = load.src[0].src[0].index(
73
+ UOp(Ops.VECTORIZE, dtypes.int.vec(2), ((oidx // 4) % buf.dtype.shape[1], (oidx // (4*buf.dtype.shape[1])))),
74
+ load.src[0].src[2] if len(load.src[0].src) == 3 else None)
75
+ vec_load = UOp(Ops.LOAD, load.dtype.vec(4), tuple(new_src))
76
+ return functools.reduce(lambda ret, i: id4.ne(i).where(ret, vec_load.gep(i)), range(4), load.const_like(float('nan')))
77
+
78
+ buf_idx_pat = UPat(Ops.INDEX, src=(UPat.var("buf"),), allow_any_len=True)
79
+ float4_folding = PatternMatcher([
80
+ (UPat(Ops.VECTORIZE, src=UPat(Ops.LOAD, src=(buf_idx_pat,), allow_any_len=True), name="ex"), fold_expanded),
81
+ (UPat((Ops.BARRIER, Ops.SINK), src=UPat(Ops.STORE, src=(buf_idx_pat,), allow_any_len=True), name="ex"), fold_expanded),
82
+ ])
83
+
84
+ # ***** image load valid simplification *****
85
+
86
+ def simplify_valid_load(buf:UOp, start_idx:UOp, valid:UOp) -> Optional[UOp]:
87
+ if (idx:=uop_given_valid(valid, start_idx)) is None: return buf.const_like(0)
88
+ if not isinstance(buf.dtype, ImageDType): return None if idx is start_idx else buf.index(idx, valid)
89
+
90
+ # wait for it to be image indexed before running simplification
91
+ if start_idx.dtype.count != 2: return None
92
+
93
+ # can drop valid if idx is out of bound when valid is False
94
+ drop_stmt = []
95
+ for stmt in split_uop(valid, Ops.AND):
96
+ X, is_upper_bound, c = parse_valid(stmt)
97
+
98
+ # for X0 + X1 + ... >= 1, check if it's out of bound when Xi = 0 for all i
99
+ if not is_upper_bound and c == 1 and all(u.op in GroupOp.Irreducible and u.vmin == 0 for u in split_uop(X, Ops.ADD)):
100
+ testidx = functools.reduce(lambda nowidx,u: nowidx.substitute({u:u.const_like(0)}), split_uop(X, Ops.ADD), idx)
101
+ testidx = testidx.simplify()
102
+ if testidx.gep(0).vmax < 0 or testidx.gep(1).vmax < 0:
103
+ drop_stmt.append(stmt)
104
+ continue
105
+
106
+ # if X <= c, check if it's out of bound when X = c+1
107
+ # if X >= c, check if it's out of bound when X = c-1
108
+ test_value = c + 1 if is_upper_bound else c - 1
109
+ for i,b in zip(idx.src, (buf.dtype.shape[1], buf.dtype.shape[0])):
110
+ if is_increasing(i):
111
+ rw = i.substitute({X:X.const_like(test_value)}).simplify()
112
+ if rw.vmin >= b or rw.vmax < 0:
113
+ drop_stmt.append(stmt)
114
+ break
115
+
116
+ if not drop_stmt and idx is start_idx: return None
117
+ new_valid = functools.reduce(operator.and_, ss) if (ss:=[s for s in split_uop(valid, Ops.AND) if s not in drop_stmt]) else None
118
+ return buf.index(idx, new_valid)
119
+
120
+ # ***** optional patterns *****
121
+
122
+ powers_of_two = {2**i:i for i in range(64)}
123
+ @functools.lru_cache(None)
124
+ def get_late_rewrite_patterns(ops, force_transcendental=False):
125
+ pat: List[Tuple[UPat, Callable]] = [(UPat(op, dtype=TRANSCENDENTAL_SUPPORTED_DTYPES, src=(UPat.var("d"),)), f) for op,f in \
126
+ ((Ops.EXP2, xexp2), (Ops.LOG2, xlog2), (Ops.SIN, xsin)) if op not in ops or force_transcendental]
127
+ # rewrite MOD to AND (which should always be supported, but not for generic in tests)
128
+ if Ops.AND in ops:
129
+ pat += [(UPat(Ops.MOD, src=(UPat.var('base'), UPat.cvar("const"))),
130
+ lambda base,const: base & (const.arg-1) if const.arg in powers_of_two else None)]
131
+ # rewrite MUL/IDIV to SHL+SHR
132
+ if Ops.SHL in ops and Ops.SHR in ops:
133
+ pat += [
134
+ (UPat(Ops.MUL, dtype=dtypes.ints, src=[UPat.cvar("const"), UPat.var("mul")]), lambda mul, const:
135
+ mul << powers_of_two[const.arg] if const.arg in powers_of_two else None), # (x * (2**y)) -> shl(x,y)
136
+ (UPat(Ops.IDIV, src=(UPat.var("div"), UPat.cvar("const"))), lambda div, const:
137
+ div >> powers_of_two[const.arg] if const.arg in powers_of_two else None)] # (x // (2**y)) -> shr(x,y)
138
+ if Ops.NEG in ops:
139
+ pat += [(UPat.var('x')*-1, lambda x: x.alu(Ops.NEG))]
140
+ if Ops.SUB in ops: pat += [(UPat.var('x')+UPat.var('y').alu(Ops.NEG), lambda x,y: x.alu(Ops.SUB, y))]
141
+ if Ops.MULACC in ops:
142
+ pat += [(UPat.var('a')*UPat.var('b')+UPat.var('c'), lambda a,b,c: a.alu(Ops.MULACC, b, c))]
143
+ return PatternMatcher(pat)
144
+
145
+ # ***** threefry *****
146
+
147
+ def threefry2x32(x: UOp, key: UOp):
148
+ # split x into two uint32, since x in a uint64
149
+ x0, x1 = (x & 0xffffffff).cast(dtypes.uint32), ((x // 2**32) & 0xffffffff).cast(dtypes.uint32)
150
+
151
+ rotations = [[13, 15, 26, 6], [17, 29, 16, 24]]
152
+ key0, key1 = (key & 0xffffffff).cast(dtypes.uint32), ((key // 2**32) & 0xffffffff).cast(dtypes.uint32)
153
+ ks = [key1, key0 ^ key1 ^ 0x1BD11BDA, key0]
154
+ xr = [x0 + ks[-1], x1 + ks[0]]
155
+ for i in range(5):
156
+ for r in rotations[i % 2]: xr[0], xr[1] = (x0 := xr[0] + xr[1]), x0 ^ ((xr[1] * 2**r) + (xr[1] // 2**(32 - r)))
157
+ xr = [(xr[0] + ks[i % 3]), (xr[1] + ks[(i + 1) % 3] + i + 1)]
158
+
159
+ return xr[1].cast(dtypes.uint64) * 2**32 | xr[0].cast(dtypes.uint64)
160
+
161
+ # ***** main rewriter *****
162
+
163
+ def loop_collapse(compval, multconst, rng:UOp, acc:UOp, idx2=None,idx3=None,extra=None,vec=None,ne=None,
164
+ add=UOp.const(dtypes.int, 0), mul:UOp=UOp.const(dtypes.int, 1)):
165
+ if getenv("DISABLE_LOOP_COLLAPSE") or rng not in acc.src: return None # must be the right REDUCE
166
+ loop_start, loop_end = rng.src
167
+ if loop_start.arg != 0:
168
+ # TODO: support and test this with other mul and loop_starts
169
+ if DEBUG >= 1: print(f"WARNING, NOT FOLDING: mul:{mul.arg} loop_start:{loop_start.arg}")
170
+ return None
171
+ if idx2 is not None: add = add + idx2
172
+ if idx3 is not None: add = add + idx3
173
+ if vec is not None:
174
+ # add, mul, loop_start, loop_end
175
+ def dvec(x:UOp):
176
+ if x.op is Ops.CONST: return UOp.const(x.dtype.vec(vec.dtype.count), x.arg)
177
+ return UOp(Ops.VECTORIZE, x.dtype.vec(vec.dtype.count), src=(x,)*vec.dtype.count)
178
+ add, mul, loop_start, loop_end = dvec(add), dvec(mul), dvec(loop_start), dvec(loop_end)
179
+ if mul.vmin > 0 and ne is not None:
180
+ comprange = UOp.minimum(loop_end, UOp.maximum((add-compval)//mul + (loop_end-loop_start), loop_start))
181
+ elif mul.vmax < 0 and ne is None:
182
+ comprange = UOp.minimum(loop_end, UOp.maximum((add-compval-mul)//mul + (loop_end-loop_start), loop_start))
183
+ else:
184
+ return None
185
+ new_reduce_op = comprange.cast(multconst.dtype) * multconst
186
+ # TODO: what does it mean to have the same numbered DEFINE_ACC with different ranges?
187
+ new_acc = acc.replace(src=acc.src[0:1]+tuple(x for x in acc.src[1:] if x is not rng))
188
+ ret = new_acc.assign(new_acc+new_reduce_op)
189
+ if extra is not None: ret = ret + acc.assign(acc+extra)
190
+ return ret
191
+
192
+ def index_collapse(idx:UOp,rng:UOp,buf:UOp,ld:UOp,acc:UOp,add=UOp.const(dtypes.int, 0),mul=UOp.const(dtypes.int, 1)):
193
+ if rng not in acc.src: return None
194
+ new_load = UOp.load(buf.index(add+mul*idx, idx.ge(rng.src[0]) & idx.lt(rng.src[1])), dtype=ld.dtype)
195
+ new_acc = acc.replace(src=acc.src[0:1]+tuple(x for x in acc.src[1:] if x is not rng))
196
+ return new_acc.assign(new_acc+new_load)
197
+
198
+ # TODO: there's a lot shared with no_vectorized_wmma here
199
+ def gep_through_wmma(gep:UOp, wmma:UOp):
200
+ out_sz = prod(x[1] for x in wmma.arg[6][-1])
201
+ wmma_idxs = gep.arg[::out_sz]
202
+ for i in range(out_sz):
203
+ if tuple(x-i for x in gep.arg[i::out_sz]) != wmma_idxs: return None
204
+ tsrcs = []
205
+ for s,sz in zip(wmma.src, wmma.arg[6]):
206
+ src_args = []
207
+ ssz = prod(x[1] for x in sz)
208
+ for w in wmma_idxs: src_args += list(range((w//out_sz)*ssz, (w//out_sz)*ssz + ssz))
209
+ tsrcs.append(s.gep(tuple(src_args)))
210
+ return UOp(Ops.WMMA, gep.dtype, tuple(tsrcs), wmma.arg)
211
+
212
+ def no_vectorized_wmma(wmma:UOp):
213
+ out_sz = prod(x[1] for x in wmma.arg[6][-1])
214
+ if wmma.dtype.count == out_sz: return None
215
+ tsrcs = []
216
+ for s,sz in zip(wmma.src, wmma.arg[6]):
217
+ ssz = prod(x[1] for x in sz)
218
+ tsrcs.append([s.gep(tuple(range(grp, grp+ssz))) for grp in range(0, s.dtype.count, ssz)])
219
+ wmmas = [UOp(Ops.WMMA, wmma.dtype.scalar().vec(out_sz), tsrc, wmma.arg) for tsrc in zip(*tsrcs)]
220
+ wmma_ex = flatten([[e.gep(i) for i in range(out_sz)] for e in wmmas])
221
+ return UOp(Ops.VECTORIZE, wmma.dtype, tuple(wmma_ex))
222
+
223
+ def reduce_collapse(acc:UOp, ret:UOp, alu:UOp):
224
+ reduce_parented, reduce_unparented = partition(acc.src[1:], lambda x: x in ret.sparents)
225
+ if len(reduce_unparented) == 0: return None
226
+ new_acc = acc.replace(src=acc.src[0:1]+tuple(reduce_parented))
227
+ ret = new_acc.assign(new_acc.alu(alu.op, ret))
228
+ if alu.op is Ops.ADD:
229
+ for r in reduce_unparented: ret = ret * (r.src[1]-r.src[0]).cast(ret.dtype.scalar()).broadcast(ret.dtype.count)
230
+ return ret
231
+
232
+ acc_pat, rng_pat = UPat(Ops.DEFINE_ACC, name="acc"), UPat(Ops.RANGE, name="rng")
233
+ rng_aug = UPat.any(rng_pat, UPat.var("add")+rng_pat, UPat.var("mul")*rng_pat, UPat.var("add")+UPat.var("mul")*rng_pat)
234
+
235
+ index_load = UPat.var("buf").index(rng_aug).load(name="ld")
236
+
237
+ arange_augrng = UPat.any(rng_aug, rng_aug+UPat.var("idx2"), rng_aug+UPat.var("idx2")+UPat.var("idx3"), UPat(Ops.VECTORIZE, name="vec", src=rng_aug))
238
+ arange_m = arange_augrng.lt(UPat.cvar("compval")).ne(UPat(Ops.CONST, name="ne", arg=True)).where(UPat.cvar("multconst"), UPat.const(None, 0))
239
+
240
+ # this is symbolic 2.0
241
+ sym = symbolic_flat+PatternMatcher([
242
+ # self ASSIGN is just self
243
+ (UPat(Ops.ASSIGN, src=(UPat.var('x'), UPat.var('x'))), lambda x: x),
244
+ # ASSIGN to global is just self
245
+ (UPat(Ops.ASSIGN, src=(UPat(Ops.DEFINE_GLOBAL), UPat.var("x"))), lambda x: x),
246
+ # VECTORIZE/CONST, VECTORIZE/GEP
247
+ (UPat(Ops.VECTORIZE, src=UPat(Ops.CONST), name="vec"), lambda vec: UOp.const(vec.dtype, tuple(x.arg for x in vec.src))),
248
+ (UPat(Ops.VECTORIZE, src=UPat(Ops.GEP, src=(UPat(name="x"),)), name="vec"), lambda vec,x: x.gep(tuple(y.arg[0] for y in vec.src))),
249
+ # reorder ALU/VECTORIZE
250
+ (UPat(GroupOp.ALU, src=(UPat(Ops.VECTORIZE, src=UPat(name='x')), UPat(Ops.VECTORIZE, src=UPat(name='y'))), name='alu'),
251
+ lambda x,y,alu: UOp(Ops.VECTORIZE, alu.dtype, (UOp(alu.op, alu.dtype.scalar(), (x,y)),)*alu.dtype.count)),
252
+ # VECTORIZE of a single element is just that element
253
+ (UPat(Ops.VECTORIZE, src=(UPat(name='x'),)), lambda x: x),
254
+ # VECTORIZE void is SINK
255
+ (UPat(Ops.VECTORIZE, dtype=dtypes.void, src=UPat(Ops.BARRIER, name='b')), lambda b: b),
256
+ (UPat(Ops.VECTORIZE, dtype=dtypes.void, name='x'), lambda x: UOp(Ops.SINK, dtypes.void, x.src)),
257
+ # GEP/VECTORIZE, GEP/GEP, GEP/CONST, GEP/VCONST
258
+ (UPat(Ops.GEP, src=(UPat(Ops.GEP, name='g2'),), name='g1'),
259
+ lambda g1, g2: g2.src[0].gep(tuple(g2.arg[g1.arg[i]] for i in range(g1.dtype.count)))),
260
+ (UPat(Ops.GEP, src=(UPat(Ops.VECTORIZE, name="vec"),), name="gep"),
261
+ lambda gep, vec: UOp(Ops.VECTORIZE, gep.dtype, tuple(vec.src[i] for i in gep.arg)) if len(gep.arg) > 1 else vec.src[gep.arg[0]]),
262
+ (UPat(Ops.GEP, src=(UPat.cvar("c", vec=False),), name="gep"), lambda gep, c: gep.const_like(c.arg)),
263
+ (UPat(Ops.GEP, src=(UPat(Ops.VCONST, name="c"),), name="gep"), lambda gep, c: gep.const_like(tuple(c.arg[x] for x in gep.arg))),
264
+ # push all GEPs through ALUs (fix arange stuff)
265
+ (UPat(Ops.GEP, src=(UPat((*GroupOp.ALU, Ops.CAST, Ops.BITCAST), name='alu'),), name='gep'),
266
+ lambda gep,alu: UOp(alu.op, alu.dtype.scalar().vec(gep.dtype.count), tuple(x.gep(gep.arg) for x in alu.src), alu.arg)),
267
+ # push some GEPs through WMMAs
268
+ (UPat(Ops.GEP, src=(UPat(Ops.WMMA, name="wmma"),), name="gep"), gep_through_wmma),
269
+ # tensor core with a 0 input is acc
270
+ (UPat(Ops.WMMA, src=(UPat.const(None, 0.0), UPat.var(), UPat.var("acc"))), lambda acc: acc),
271
+ (UPat(Ops.WMMA, src=(UPat.var(), UPat.const(None, 0.0), UPat.var("acc"))), lambda acc: acc),
272
+ # tensor core cleanups
273
+ (UPat.var("add") + UPat(Ops.WMMA, name="wmma"),
274
+ lambda add, wmma: UOp(wmma.op, wmma.dtype, (wmma.src[0], wmma.src[1], wmma.src[2]+add), wmma.arg)),
275
+ # threefry + remove longs
276
+ (UPat(Ops.THREEFRY, dtype=dtypes.uint64, src=(UPat.var("x"), UPat.var("key"))), threefry2x32),
277
+ (UPat.var('x', dtypes.uint32).cast(dtypes.uint64).cast(dtypes.uint32), lambda x: x), # cast there and back is noop (TODO: genericize)
278
+ ((UPat.var('x', dtypes.uint64)&0xFFFFFFFF).cast(dtypes.uint32), lambda x: x.cast(dtypes.uint32)), # cast does truncation
279
+ (((UPat.var(None, dtypes.uint64)*(1<<32)) | UPat.var('y', dtypes.uint32).cast(dtypes.uint64)).cast(dtypes.uint32), lambda y: y),
280
+ (((UPat.var('x', dtypes.uint64)*(1<<32)) | UPat.var(None, dtypes.uint32).cast(dtypes.uint64))//(1<<32), lambda x: x),
281
+ # hacks for threefry long removal when padded (TODO: genericize)
282
+ (UPat.var('x', dtypes.uint32).cast(dtypes.uint64) * UPat.var('y').where(UPat.const(dtypes.uint64, 1<<32), UPat.const(dtypes.uint64, 0)),
283
+ lambda x,y: y.where(x, UOp.const(dtypes.uint32, 0)).cast(dtypes.uint64) * (1<<32)),
284
+ ((UPat.var('x', dtypes.uint64)&(UPat.var('y').where(UPat.const(dtypes.uint64, 0xFFFFFFFF), UPat.const(dtypes.uint64, 0)))).cast(dtypes.uint32),
285
+ lambda x,y: y.where(x.cast(dtypes.uint32), UOp.const(dtypes.uint32, 0))),
286
+ # arange loop folding
287
+ (acc_pat.assign(UPat.any(arange_m, arange_m+UPat.var("extra"))+acc_pat), loop_collapse),
288
+ # indexing, with cast or where
289
+ (acc_pat.assign(UPat.var("idx").eq(UPat(Ops.RANGE, name="rng")).cast()*index_load+acc_pat), index_collapse),
290
+ (acc_pat.assign(UPat.var("idx").eq(UPat(Ops.RANGE, name="rng")).where(index_load, UPat.const(None, 0.0))+acc_pat), index_collapse),
291
+ # parentless reduce
292
+ (acc_pat.assign(UPat(Ops.ADD, src=[acc_pat, UPat.var("ret")], name="alu")), reduce_collapse),
293
+ (acc_pat.assign(UPat(Ops.MAX, src=[acc_pat, UPat.var("ret")], name="alu")), reduce_collapse),
294
+ # ** self folding **
295
+ (UPat(Ops.DEFINE_ACC, src=(UPat.var("x"),)), lambda x: x), # a DEFINE_ACC without ranges is a CONST
296
+ (UPat(Ops.ASSIGN, src=(UPat.cvar(),UPat.var("x"))), lambda x: x), # an ASSIGN to a const is a NOOP
297
+ # x!=0 -> (bool)x
298
+ (UPat.var("x").ne(0), lambda x: x.cast(dtypes.bool.vec(x.dtype.count))),
299
+ # ** load/store folding **
300
+ (UPat.store(UPat(Ops.INDEX, name="index"), UPat.load(UPat(Ops.INDEX, name="index"))), lambda index: UOp(Ops.NOOP)),
301
+ (UPat.store(UPat(Ops.INDEX, name="index"), UPat.var("gate").where(UPat.var("alt"), UPat.load(UPat(Ops.INDEX, name="index")))),
302
+ lambda index, gate, alt: UOp.store(index.src[0].index(index.src[1], gate), alt)),
303
+ # fold gated LOAD/STORE
304
+ (UPat().index(UPat(), UPat.const(dtypes.bool, True)).named("idx"), lambda idx: idx.replace(src=idx.src[0:2])), # remove True
305
+ (UPat().index(UPat(), UPat.const(dtypes.bool, False)).named("idx"), lambda idx: idx.const_like(0)), # False -> NULL pointer
306
+ (UPat(Ops.LOAD, src=(UPat.const(None, 0),), allow_any_len=True, name="x"), lambda x: x.const_like(0)), # NULL pointer load loads 0
307
+ (UPat(Ops.STORE, src=(UPat.const(None, 0),), allow_any_len=True), lambda: UOp(Ops.NOOP)), # NULL pointer store does nothing
308
+ # remove NOOPs from SINK
309
+ (UPat(Ops.SINK, name="root"),
310
+ lambda root: UOp(Ops.SINK, root.dtype, a, root.arg) if len(a:=tuple(x for x in root.src if x.op is not Ops.NOOP)) != len(root.src) else None),
311
+ # remove EXPANDs from SINK/BARRIER
312
+ (UPat(Ops.BARRIER, src=(UPat((Ops.VECTORIZE, Ops.SINK), name='sink'),)), lambda sink: UOp(Ops.BARRIER, dtypes.void, sink.src)),
313
+ (UPat(Ops.SINK, name="root"),
314
+ lambda root: UOp(Ops.SINK, root.dtype, tuple(flatten(x.src if x.op in {Ops.SINK, Ops.EXPAND} else (x,) for x in root.src)), root.arg)
315
+ if any(x.op in {Ops.SINK, Ops.EXPAND} for x in root.src) else None),
316
+ ])
317
+
318
+ # *** uop expander ***
319
+
320
+ def _expand_arg_to_idx(args:Tuple[Tuple[int, int], ...], rpk:Dict[int, int]) -> int:
321
+ idx, mul = 0, 1
322
+ for axis,m in args[::-1]:
323
+ idx += rpk[axis] * mul
324
+ mul *= m
325
+ return idx
326
+
327
+ def _choices_from_args(args:Tuple[Tuple[int, int], ...]) -> List[Dict[int, int]]:
328
+ return [dict(x) for x in itertools.product(*[zip(itertools.repeat(axis), range(m)) for axis,m in args])]
329
+
330
+ @functools.lru_cache(None)
331
+ def _swizzle_args(cargs:Tuple[Tuple[int, int], ...], eargs:Tuple[Tuple[int, int], ...], exclude_args:Tuple[int, ...]) -> List[int]:
332
+ return [_expand_arg_to_idx(eargs, {**rpk, **{x:0 for x in exclude_args}} if exclude_args else rpk) for rpk in _choices_from_args(cargs)]
333
+
334
+ def do_expand(root:UOp):
335
+ expands = [x for x in root.src if x.op is Ops.EXPAND]
336
+ if len(expands) == 0: return None
337
+ # NOTE: we 0 out the reduce axis for WMMA. in theory they should all be the same, but is this always correct?
338
+ exclude_args = tuple(dedup(root.arg[-1] + tuple(y[0] for y in flatten(root.arg[-2])))) if root.op is Ops.WMMA else ()
339
+ if all_same(expands_args:=[x.arg for x in expands]) and len(exclude_args) == 0:
340
+ # if there's only one expand arg, it's okay to use it (optimization)
341
+ expand_args = expands[0].arg
342
+ else:
343
+ # otherwise, we sort them and GEP
344
+ expand_args = tuple(x for x in sorted(dedup(flatten(expands_args))) if x[0] not in exclude_args)
345
+ expand_sz = prod([x[1] for x in expand_args])
346
+ new_srcs = []
347
+ for i,src in enumerate(root.src):
348
+ if src.op is Ops.EXPAND:
349
+ if root.op is Ops.IF and i == 0:
350
+ # IF means OR on first arg to IF
351
+ new_srcs.append(functools.reduce(operator.__or__, [src.src[0].gep(i) for i in range(expand_sz)]))
352
+ elif expand_args == src.arg:
353
+ # just remove the expand
354
+ new_srcs.append(src.src[0])
355
+ else:
356
+ lst = _swizzle_args(expand_args, src.arg, exclude_args)
357
+ # if the base dtype is > 1, put those at the end
358
+ if src.dtype.count > 1: lst = flatten([[i*src.dtype.count+j for j in range(src.dtype.count)] for i in lst])
359
+ new_srcs.append(src.src[0].gep(tuple(lst)))
360
+ else:
361
+ # non-EXPAND input
362
+ if root.op is Ops.IF:
363
+ # for the first arg of IF, just pass them through ignoring EXPANDS
364
+ new_srcs.append(src)
365
+ elif src.dtype.count > 1:
366
+ # put any input dtype > 1 grouped together
367
+ new_srcs.append(UOp(Ops.VECTORIZE,
368
+ src.dtype.scalar().vec(expand_sz*src.dtype.count), tuple(src.gep(i) for i in range(src.dtype.count))*expand_sz))
369
+ else:
370
+ # repeat the arg
371
+ new_srcs.append(src.broadcast(expand_sz))
372
+
373
+ new_arg = root.arg
374
+ if root.op is Ops.GEP:
375
+ assert root.dtype.count == 1
376
+ # is this right?
377
+ new_arg = tuple(range(root.arg[0], new_srcs[0].dtype.count, new_srcs[0].dtype.count // expand_sz))
378
+ nsrc = UOp(root.op, root.dtype.scalar().vec(root.dtype.count*expand_sz), tuple(new_srcs), new_arg)
379
+ return UOp(Ops.EXPAND, root.dtype, (nsrc,), expand_args)
380
+
381
+ def do_contract(con:UOp):
382
+ ex = con.src[0]
383
+ # CONTRACT without EXPAND repeats the element VECTORIZED
384
+ if ex.op is not Ops.EXPAND: return UOp(Ops.VECTORIZE, con.dtype, con.src*con.dtype.count)
385
+ # CONTRACT may remove several axes from EXPAND
386
+ assert con.dtype.count == prod([x[1] for x in con.arg]), "dtype is wrong"
387
+ idxs = []
388
+ for rpk in _choices_from_args(new_ex_args:=tuple(x for x in ex.arg if x not in con.arg)):
389
+ idxs += [_expand_arg_to_idx(ex.arg, {**rpk, **lrpk}) for lrpk in _choices_from_args(con.arg)]
390
+ return UOp(Ops.EXPAND, con.dtype, (ex.src[0].gep(tuple(idxs)),), new_ex_args)
391
+
392
+ def no_vectorized_alu(alu):
393
+ if alu.dtype.vcount == 1: return None
394
+ alus = tuple(UOp(alu.op, alu.dtype.scalar(), tuple(s.gep(i) for s in alu.src), alu.arg) for i in range(alu.dtype.vcount))
395
+ return UOp(Ops.VECTORIZE, alu.dtype, alus)
396
+
397
+ def create_gate(root:UOp) -> Optional[UOp]:
398
+ @functools.lru_cache(None)
399
+ def _gate_srcs(u:UOp, gate:UOp) -> UOp:
400
+ if u.op is Ops.BARRIER: return u
401
+ if u.op is Ops.LOAD and u.src[-1].op is Ops.BARRIER:
402
+ return UOp(u.op, u.dtype, u.src[:-1]+(UOp(Ops.IF, dtypes.void, (gate, u.src[-1])),), u.arg)
403
+ return u if (replace_source:=tuple(_gate_srcs(x, gate) for x in u.src)) == u.src else UOp(u.op, u.dtype, replace_source, u.arg)
404
+ idx = root.src[0]
405
+ if idx.op is Ops.CAST: idx = idx.src[0]
406
+ return None if idx.op is not Ops.INDEX or len(idx.src) == 2 or (ret:=_gate_srcs(root, idx.src[2])) is root else ret
407
+
408
+ expander = PatternMatcher([
409
+ # double expand
410
+ (UPat(Ops.EXPAND, name="outer", src=(UPat(Ops.EXPAND, name="inner"),)),
411
+ lambda outer, inner: UOp(Ops.EXPAND, outer.dtype, (inner.src[0],), inner.arg+outer.arg)),
412
+ # do expansion
413
+ (UPat((*GroupOp.ALU, Ops.CAST, Ops.BITCAST, Ops.GEP, Ops.WMMA, Ops.LOAD, Ops.STORE, Ops.INDEX, Ops.ASSIGN,
414
+ Ops.VECTORIZE, Ops.IF), name="root", custom_early_reject=set([Ops.EXPAND])), do_expand),
415
+ (UPat(Ops.CONTRACT, name="con"), do_contract),
416
+ # vectorize DEFINE_ACC
417
+ (UPat(Ops.VECTORIZE, src=UPat(Ops.DEFINE_ACC, name="acc"), name="v"), lambda acc,v: acc.replace(dtype=v.dtype)),
418
+ # BARRIERs aren't actually expanded
419
+ (UPat(Ops.BARRIER, src=(UPat(Ops.EXPAND, name="ex"),)),
420
+ lambda ex: UOp(Ops.EXPAND, dtypes.void, (UOp(Ops.BARRIER, dtypes.void, ex.src),)*len(ex.src), ex.arg)),
421
+ # empty EXPAND is NOOP
422
+ (UPat(Ops.EXPAND, src=(UPat.var('x'),), arg=()), lambda x: x),
423
+ # EXPAND GEP (needed for WMMA, generalize this) -> vectorized ALU
424
+ (UPat(Ops.EXPAND, name="ex", src=tuple(UPat.var('x').gep(i)+UPat.var('y').gep(i) for i in range(256 if AMX else 8))),
425
+ lambda ex,x,y: UOp(Ops.EXPAND, ex.dtype, tuple((x+y).gep(i) for i in range(256 if AMX else 8)), ex.arg)),
426
+ ])
427
+
428
+ def no_vectorized_load_store(ls:UOp):
429
+ idx = ls.src[0]
430
+ assert isinstance(idx.dtype, PtrDType)
431
+ if idx.dtype.v == 1: return None
432
+ tv = [UOp(ls.op, ls.dtype.scalar(), tuple(j.gep(i) for j in ls.src)) for i in range(idx.dtype.v)]
433
+ return UOp(Ops.VECTORIZE, ls.dtype, tuple(tv))
434
+
435
+ def no_vectorized_acc(acc:UOp):
436
+ if acc.dtype.count == 1: return None
437
+ alus = tuple(UOp(acc.op, acc.dtype.scalar(),
438
+ tuple(s.gep(i) if j == 0 else s for j,s in enumerate(acc.src)), acc.arg+(i,)) for i in range(acc.dtype.count))
439
+ return UOp(Ops.VECTORIZE, acc.dtype, alus)
440
+
441
+ devectorize = PatternMatcher([
442
+ # no ALU on vectorized dtypes
443
+ (UPat((*GroupOp.ALU, Ops.CAST, Ops.BITCAST, Ops.ASSIGN, Ops.INDEX), name="alu"), no_vectorized_alu),
444
+ (UPat(Ops.WMMA, name="wmma"), no_vectorized_wmma),
445
+ (UPat(Ops.DEFINE_ACC, name="acc"), no_vectorized_acc),
446
+ (UPat((Ops.LOAD, Ops.STORE), name="ls"), no_vectorized_load_store),
447
+ ])
448
+
449
+ def delete_redundant_gates(buf:UOp, idx:UOp, val:UOp, store_gate:UOp, cast:Optional[UOp]=None) -> Optional[UOp]:
450
+ if store_gate not in [gate.src[0] for gate in val.sparents if gate.op is Ops.IF]: return None
451
+ # remove the gate from the index
452
+ return UOp.store(buf.index(idx).cast(cast.dtype) if cast is not None else buf.index(idx), val)
453
+
454
+ load_store_indexing = PatternMatcher([
455
+ # late fixup of unfoldable image loads
456
+ (UPat(Ops.LOAD, src=(UPat.var("buf"), UPat()), allow_any_len=True, name="load"), fix_unfoldable_image_load),
457
+ # simplify valid
458
+ (UPat(Ops.AND, name="valid"), simplify_valid),
459
+ # image load valid idx simplification
460
+ (UPat(Ops.INDEX, src=(UPat.var("buf"), UPat.var("start_idx"), UPat.var("valid"))), simplify_valid_load),
461
+ # delete_redundant_gates (after expand)
462
+ (UPat(Ops.STORE, src=(UPat.any(stidx:=UPat.var("buf").index(UPat.var("idx"), UPat.var("store_gate")), stidx.cast().named("cast")),
463
+ UPat.var("val"))), delete_redundant_gates),
464
+ ])
465
+
466
+ migrate_indexing = PatternMatcher([
467
+ # create gate MUST BE BEFORE expander
468
+ (UPat(Ops.STORE, name="root"), create_gate),
469
+ ])
470
+
471
+ def move_mask(x:UOp, buf:UOp, idx:UOp, mask:UOp, cast:Optional[UOp]=None) -> UOp:
472
+ # this moves the mask from the indexing to the load/store op for rendering
473
+ nidx = buf.index(idx).cast(cast.dtype) if cast is not None else buf.index(idx)
474
+ return UOp.load(nidx, x.const_like(0), mask, *x.src[1:], dtype=x.dtype) if x.op is Ops.LOAD else UOp.store(nidx, x.src[1], mask, *x.src[2:])
475
+
476
+ pm_render = PatternMatcher([
477
+ # for rendering, we use explicit VECTORIZE
478
+ (UPat(Ops.CONST, name='c'),
479
+ lambda c: UOp(Ops.VECTORIZE, c.dtype, (UOp.const(c.dtype.scalar(), c.arg),)*c.dtype.vcount) if c.dtype.vcount > 1 else None),
480
+ (UPat(Ops.VCONST, name='c'), lambda c: UOp(Ops.VECTORIZE, c.dtype, tuple(UOp.const(c.dtype.scalar(), x) for x in c.arg))),
481
+ (UPat(Ops.GEP, name='gep'), lambda gep: UOp(Ops.VECTORIZE, gep.dtype, tuple(gep.src[0].gep(x) for x in gep.arg)) if len(gep.arg) > 1 else None),
482
+ (UPat(Ops.VECTORIZE, src=(UPat(name='x'),)), lambda x: x),
483
+ # move masks of loads/stores
484
+ (UPat((Ops.LOAD, Ops.STORE), src=(UPat.any(masked_index:=UPat(Ops.INDEX, src=(UPat(name="buf"), UPat(name="idx"), UPat(name="mask"))),
485
+ masked_index.cast(None).named("cast")),), allow_any_len=True, name="x"), move_mask),
486
+ ])
487
+
488
+ # *** uop graph ***
489
+
490
+ def full_graph_rewrite(sink:UOp, opts:Optional[Renderer]=None) -> UOp:
491
+ assert sink.op is Ops.SINK, f"sink isn't sink, it's {sink.op}"
492
+ supported_ops = tuple(opts.code_for_op.keys()) if opts is not None else ()
493
+ extra_matcher = opts.extra_matcher if opts is not None and opts.extra_matcher is not None else PatternMatcher([])
494
+
495
+ # initial symbolic + migrate indexing (remove this)
496
+ sink = graph_rewrite(sink, sym+migrate_indexing)
497
+
498
+ # expand
499
+ sink = graph_rewrite(sink, sym+expander)
500
+
501
+ # devectorize + load_store_indexing
502
+ sink = graph_rewrite(sink, sym+(devectorize+float4_folding if opts is not None and opts.supports_float4 else devectorize)+load_store_indexing)
503
+
504
+ # final rules for the renderer (without sym)
505
+ sink = graph_rewrite(sink, symbolic_simple+get_late_rewrite_patterns(supported_ops, TRANSCENDENTAL>=2)+pm_render+extra_matcher)
506
+ return sink