-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.py
2771 lines (2235 loc) · 92.8 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from pathlib import Path
import os
import json
from typing import (
Callable,
NamedTuple,
Dict,
Hashable,
List,
Any,
Iterable,
Sequence,
Iterator,
Type,
Tuple,
Optional,
Union,
Dict,
Set,
DefaultDict,
Final,
)
import weakref
import types
from contextlib import contextmanager, ContextDecorator
import itertools
import weakref
import operator as operator_py
import numpy as np
import math
import inspect
from functools import partial, lru_cache
import mmap
import traceback
import importlib
import time
import cProfile
import pstats
# =================================
# Utils
# =================================
class Timing(ContextDecorator):
def __init__(self, prefix="", on_exit=None, enabled=True):
self.prefix, self.on_exit, self.enabled = prefix, on_exit, enabled
def __enter__(self):
self.st = time.perf_counter_ns()
def __exit__(self, *exc):
self.et = time.perf_counter_ns() - self.st
if self.enabled:
print(f"{self.prefix}{self.et*1e-6:6.2f} ms" + (self.on_exit(self.et) if self.on_exit else ""))
def colored(st, color: Optional[str], background=False):
return (
f"\u001b[{10*background+60*(color.upper() == color)+30+['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'].index(color.lower())}m{st}\u001b[0m"
if color is not None
else st
) # replace the termcolor library with one line # noqa: E501
def _format_fcn(fcn):
return f"{fcn[0]}:{fcn[1]}:{fcn[2]}"
class Profiling(ContextDecorator):
def __init__(self, enabled=True, sort="cumtime", frac=0.2, fn=None, ts=1):
self.enabled, self.sort, self.frac, self.fn, self.time_scale = enabled, sort, frac, fn, 1e3 / ts
def __enter__(self):
self.pr = cProfile.Profile()
if self.enabled:
self.pr.enable()
def __exit__(self, *exc):
if self.enabled:
self.pr.disable()
if self.fn:
self.pr.dump_stats(self.fn)
stats = pstats.Stats(self.pr).strip_dirs().sort_stats(self.sort)
for fcn in stats.fcn_list[0 : int(len(stats.fcn_list) * self.frac)]: # type: ignore[attr-defined]
(_primitive_calls, num_calls, tottime, cumtime, callers) = stats.stats[fcn] # type: ignore[attr-defined]
scallers = sorted(callers.items(), key=lambda x: -x[1][2])
print(
f"n:{num_calls:8d} tm:{tottime*self.time_scale:7.2f}ms tot:{cumtime*self.time_scale:7.2f}ms",
colored(_format_fcn(fcn), "yellow") + " " * (50 - len(_format_fcn(fcn))),
colored(f"<- {(scallers[0][1][2]/tottime)*100:3.0f}% {_format_fcn(scallers[0][0])}", "BLACK") if len(scallers) else "",
)
def dblog(*msg, enable=True):
if enable:
print(*msg)
def unzip2(pairs) -> Tuple[List[Any], List[Any]]:
lst1, lst2 = [], []
for i1, i2 in pairs:
lst1 += [i1]
lst2 += [i2]
return lst1, lst2
def list_map(f: Callable, *xs: Iterable) -> List[Any]:
return list(map(f, *xs))
def list_zip(*args: List[Any]) -> List[Any]:
fst, *rest = args = list_map(list, args)
n = len(fst)
for arg in rest:
assert len(arg) == n
return list(zip(*args))
def split_half(lst: List[Any]) -> Tuple[List[Any], List[Any]]:
assert not len(lst) % 2
return split_list(lst, len(lst) // 2)
def merge_lists(which: List[bool], l1: List[Any], l2: List[Any]) -> List[Any]:
l1, l2 = iter(l1), iter(l2)
out = [next(l2) if b else next(l1) for b in which]
assert next(l1, None) is next(l2, None) is None
return out
def split_list(lst: List[Any], n: int) -> Tuple[List[Any], List[Any]]:
assert 0 <= n <= len(lst)
return lst[:n], lst[n:]
def split_list(lst: List[Any], n: int) -> Tuple[List[Any], List[Any]]:
assert 0 <= n <= len(lst)
return lst[:n], lst[n:]
def partition_list(bs: List[bool], l: List[Any]) -> Tuple[List[Any], List[Any]]:
assert len(bs) == len(l)
lists = lst1, lst2 = [], []
for b, x in zip(bs, l):
lists[b].append(x)
return lst1, lst2
def lru_cache_verbose(
maxsize: int = 100,
typed: bool = False,
tb_start: int = -12,
tb_end: int = -7,
):
def decorator(fn: Callable):
@lru_cache(maxsize=maxsize, typed=typed)
def wrapper(*args, **kwargs) -> Callable:
return fn(*args, **kwargs)
def decorated_function(*args, **kwargs) -> Any:
result = wrapper(*args, **kwargs)
cache_info = wrapper.cache_info()
dblog(
f"{fn.__name__}.{cache_info} {args.__hash__()}",
enable=backend.LOG_LRU,
)
tb = "".join(traceback.format_list(traceback.extract_stack())[tb_start:tb_end]).replace("\n ", ":\t") + "-" * 20 + "\n"
dblog(f"{tb}", enable=backend.LOG_LRU)
return result
decorated_function.cache_info = wrapper.cache_info
decorated_function.fn = fn
return decorated_function
return decorator
def cuda_is_available():
try:
import subprocess
import platform
cmd = f"nvidia-smi{'.exe' if platform.system == 'Windows' else ''}"
result = subprocess.run([cmd], stdout=subprocess.PIPE)
output = result.stdout.decode("utf-8")
return True if "NVIDIA-SMI" in output else False
except FileNotFoundError:
return False
class Hashed:
val: Any
def __init__(self, val):
self.val = val
def __hash__(self) -> int:
return hash((self.val,))
def __eq__(self, other):
if isinstance(other, Hashed):
if isinstance(self.val, Tensor) and isinstance(other.val, Tensor):
# because Tensor.__eq__ already for Tensor.equal
return id(self.val) == id(other.val)
return self.val == other.val
return False
def __repr__(self):
return f"Hashed: {repr(self.val)}"
# =================================
# Tensors
# =================================
class DType(NamedTuple):
priority: int
itemsize: int
name: str
mlir: str
numpy: type
@property
def format_code(self):
return f"slope.{self.name}"
def __repr__(self):
return f"<DType: {self.name}>"
class dtypes:
float32: Final[DType] = DType(4, 4, "float32", "f32", np.float32)
uint8: Final[DType] = DType(0, 1, "uint8", "u8", np.uint8)
int8: Final[DType] = DType(0, 1, "int8", "i8", np.int8)
bool: Final[DType] = DType(0, 1, "bool", "i1", bool)
int32: Final[DType] = DType(1, 4, "int32", "i32", np.int32)
int64: Final[DType] = DType(2, 8, "int64", "i64", np.int64)
uint64: Final[DType] = DType(2, 8, "uint64", "ui64", np.uint64)
float16: Final[DType] = DType(0, 2, "float16", "f16", np.float16)
half = float16
# bfloat16: Final[DType] = DType(0, 2, "bfloat16", "bf16", np.float16)
all_dtypes = (bool, float16, float32, int8, int32, int64, uint8, uint64)
name_dtype_map = {k.name: k for k in all_dtypes}
name_dtype_map_inv = {v: k for k, v in name_dtype_map.items()}
mlir_dtype_map = {k.mlir: k for k in all_dtypes}
mlir_dtype_map_inv = {v: k for k, v in mlir_dtype_map.items()}
@classmethod
def is_int(cls, dtype):
return dtype in (cls.uint8, cls.int8, cls.int32, cls.uint64, cls.int64)
@classmethod
def is_float(cls, dtype):
return dtype in (cls.float16, cls.bfloat16, cls.float32)
class Device(NamedTuple):
name: str
idx: int
@property
def format_code(self):
return f"'{self.name}:{self.idx}'"
def __repr__(self):
return f"<Device: {self.format_code}>"
class devices:
cpu: Final[Device] = Device("cpu", 0)
metal: Final[Device] = Device("metal", 0)
cuda0: Final[Device] = Device("cuda", 0)
# TODO: programmatically define this class attrs to support other setup
cuda = cuda0
all_devices = (cpu, metal, cuda0)
name_idx_device_map = {f"{k.name}:{k.idx}": k for k in all_devices}
name_idx_device_map_inv = {v: k for k, v in name_idx_device_map.items()}
class TensorBuffer:
def __init__(self, val):
self.val = val
class Tensor:
def __init__(self, val: TensorBuffer):
assert isinstance(val, TensorBuffer)
self.buf = val
@property
def symval(self):
return SymbolicTensor.like(self)
@property
def default_dtype(self):
return backend.default_dtype
def is_int(self) -> bool:
return self.dtype in (
dtypes.int8,
dtypes.uint8,
dtypes.uint64,
dtypes.int32,
dtypes.int64,
)
def is_float(self) -> bool:
return self.dtype in (dtypes.float16, dtypes.float32)
def is_unsigned(self) -> bool:
return self.dtype is dtypes.uint8
def to_bool(self):
return self.cast(dtypes.bool)
def short(self):
return self.cast(dtypes.int8)
def int(self):
return self.cast(dtypes.int32)
def long(self):
return self.cast(dtypes.int64)
def half(self):
return self.cast(dtypes.float16)
def float(self):
return self.cast(dtypes.float32)
def __getattr__(self, attr):
if attr in vars(backend.operator_set).keys():
op = getattr(backend.operator_set, attr)
return partial(op, self)
elif attr in vars(backend.procedure_set).keys():
procedure = getattr(backend.procedure_set, attr)
assert not isinstance(procedure, classmethod), f"use {attr} instead of self.{attr}"
return partial(procedure, self)
else:
return self.__getattribute__(attr)
def __getitem__(self, idx):
return self.getitem(idx)
def __setitem__(self, idx, item):
raise NotImplementedError
def str_short(self):
return f"<Tensor: shape={self.shape}, dtype={self.dtype}>"
__neg__ = lambda self: self.neg()
__add__ = lambda self, other: self.add(other)
__radd__ = lambda self, other: self.add(other)
__sub__ = lambda self, other: self.sub(other)
__rsub__ = lambda self, other: self.sub.func(other, self)
__mul__ = lambda self, other: self.mul(other)
__rmul__ = lambda self, other: self.mul(other)
__div__ = lambda self, other: self.div(other)
__rdiv__ = lambda self, other: self.div.func(other, self)
__truediv__ = __div__
__truerdiv__ = __rdiv__
__pow__ = lambda self, other: self.pow(other)
__rpow__ = lambda self, other: self.pow.func(other, self)
__matmul__ = lambda self, other: self.matmul(other)
__rmatmul__ = lambda self, other: self.matmul.func(other, self)
__invert__ = lambda self: self.invert()
__eq__ = lambda self, other: self.equal(other)
__ne__ = lambda self, other: self.not_equal(other)
__ge__ = lambda self, other: self.greater_equal(other)
__le__ = lambda self, other: self.less_equal(other)
__gt__ = lambda self, other: self.greater(other)
__lt__ = lambda self, other: self.less(other)
def __hash__(self):
return id(self.val)
val = property(lambda self: self.buf.val)
def size(self, i):
return self.shape[i]
@property
def dtype(self):
return backend.dtype_of(self)
@property
def device(self):
return backend.device_of(self)
def numpy(self, memmap=False):
return backend.numpy_of(self, memmap)
@property
def shape(self):
return backend.shape_of(self)
@property
def ndim(self):
return len(self.shape)
def numel(self):
return math.prod(self.shape)
def element_size(self):
return self.dtype.itemsize
def nbytes(self):
return self.numel() * self.element_size()
def __repr__(self):
return f"<Tensor: val=\n{self.numpy()}\nshape={self.shape}, dtype={self.dtype.name}, device={self.device.format_code}>"
class SymbolicTensor(Tensor):
def __init__(self, shape, dtype, device):
assert isinstance(dtype, DType)
self._shape = tuple(int(i) for i in shape)
self._dtype = dtype
self._device = device
@property
def symval(self):
return self
@property
def val(self):
raise RuntimeError(f"SymbolicTensor actually has no val, from {trace_stack[-1]=}, ")
@property
def shape(self):
return self._shape
@property
def dtype(self):
return self._dtype
@property
def device(self):
return self._device
def like(self, **overrides):
shape = overrides.get("shape", self.shape)
dtype = overrides.get("dtype", self.dtype)
device = overrides.get("device", self.device)
return SymbolicTensor(shape, dtype, device)
def str_short(self):
return f'{str(self.dtype)}[{",".join(str(d) for d in self.shape)}]'
def __hash__(self):
return hash((self.shape, self.dtype))
def __eq__(self, other):
if type(self) != type(other):
return False
return (self.shape == other.shape) and (self.dtype == other.dtype)
def __repr__(self):
return f"<SymbolicTensor: shape={self.shape}, dtype={self.dtype.name}, device={self.device}>"
# =================================
# Operator
# =================================
class Operator:
def __init__(self, name, variadic_inputs=False, nary_outputs=False):
self.name = name
self.variadic_inputs = variadic_inputs
self.nary_outputs = nary_outputs
if self.variadic_inputs:
self.reorg_args = self.reorg_args_nary
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
if not isinstance(other, Operator):
return False
return self.name == other.name
def args_fixer(self, *args, **params):
return args, params
def __call__(self, *args, **params):
args, params = self.reorg_args(args, params)
args, params = self.args_fixer(*args, **params)
ret = bind(self, *args, **params)
if not self.nary_outputs:
ret = ret[0]
return ret
def __repr__(self) -> str:
return f"<{self.name}>"
def typecheck(self, *args, **params):
raise NotImplementedError
def jvp(self, *args, **params):
raise NotImplementedError
def T(self, *args, **params):
raise NotImplementedError
def vmap(self, *args, **params):
raise NotImplementedError
def reorg_args(self, args, params):
sig = inspect.signature(self.typecheck)
args_strs = [k for k, v in sig.parameters.items() if v.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and k != "self"]
params_strs = [k for k, v in sig.parameters.items() if v.kind == inspect.Parameter.KEYWORD_ONLY and k != "self"]
if args:
if len(args) > len(args_strs):
args, rest = args[: len(args_strs)], args[len(args_strs) :]
if params_strs:
new_params = {k: rest_arg for k, rest_arg in zip(params_strs, rest) if k not in params}
params = {**new_params, **params}
else:
args = tuple([params[k] if k in params else arg for k, arg in zip(args_strs, args)])
assert len(args) == len(args_strs)
return args, params
def reorg_args_nary(self, args, params):
return args, params
def partial_run(self, trace, tracers, **params):
tracers_in = [trace.instantiate_const(t) for t in tracers]
symvals_in = [t.symval for t in tracers_in]
symvals_out = self.typecheck(*symvals_in, **params)
tracers_out = [PartialRunTraceTensor(trace, make_unknown_pval(symval), None) for symval in symvals_out]
instruction = InstructionDraft(
self,
tracers_in,
params,
symvals_out,
list_map(weakref.ref, tracers_out),
)
for t in tracers_out:
t.draft = instruction
return tracers_out
def partial_run_instruction(self, unks_in, instruction):
if any(unks_in):
instruction1 = None
instruction2 = Instruction(
instruction.op,
instruction.inputs,
instruction.params,
instruction.out_binders,
)
unks_out = [True for i in instruction.out_binders]
res = [v for unk, v in zip(unks_in, instruction.inputs) if ((not unk) and type(v) is Var)]
else:
instruction1 = instruction
instruction2 = None
unks_out = [False for i in instruction.out_binders]
res = None
return instruction1, instruction2, unks_out, res
class MetaOperator(Operator):
def meta_impl(self, *args, **kwargs):
raise NotImplementedError
class UnaryOperator(Operator):
def vmap(self, x, *, dim_size, vals_in, dims_in, **params):
(x,), (x_bdim,) = vals_in, dims_in
return [self(x, **params)], [x_bdim]
def typecheck(self, x, **params):
return [SymbolicTensor.like(x)]
def jvp(self, primals, tangents, **params):
(x,), (x_dot,) = primals, tangents
return [self(x, **params)], [self(x_dot, **params)]
class BinaryOperator(Operator):
boolean_output = False
def args_fixer(self, x, w, **params):
if isinstance(x, UndefinedPrimal) or type(w) is UndefinedPrimal:
assert x.shape == w.shape
return (x, w), params
if type(x) in TraceTensor.PYTHON_TYPES:
x = backend.full(shape=(), fill_value=x, dtype=w.dtype)
elif type(w) in TraceTensor.PYTHON_TYPES:
w = backend.full(shape=(), fill_value=w, dtype=x.dtype)
shape_delta = x.ndim - w.ndim
if shape_delta > 0:
w = w.reshape((1,) * shape_delta + w.shape)
elif shape_delta < 0:
x = x.reshape((1,) * -shape_delta + x.shape)
shape_ret = tuple([max(x, w) for x, w in zip(x.shape, w.shape)])
if x.shape != shape_ret:
x = x.expand(shape_ret)
if w.shape != shape_ret:
w = w.expand(shape_ret)
if type(x) is Tensor and isinstance(w, TraceTensor):
x = w._trace.pure(x)
elif type(w) is Tensor and isinstance(x, TraceTensor):
w = x._trace.pure(w)
# TODO: https://jax.readthedocs.io/en/latest/type_promotion.html
if x.dtype != w.dtype:
# {int, bool} -> float
if dtypes.is_float(x.dtype) ^ dtypes.is_float(w.dtype):
if dtypes.is_float(w.dtype):
x = x.cast(w.dtype)
elif dtypes.is_float(x.dtype):
w = w.cast(x.dtype)
# bool -> int
elif dtypes.is_int(x.dtype) ^ dtypes.is_int(w.dtype):
if dtypes.is_int(w.dtype):
x = x.cast(w.dtype)
elif dtypes.is_int(x.dtype):
w = w.cast(x.dtype)
else: # TODO: fine-grained type promotions
raise NotImplementedError("No other type promotion rules")
return (x, w), params
def vmap(self, dim_size, vals_in, dims_in, **params):
(x, w), (x_bdim, w_bdim) = vals_in, dims_in
if x_bdim != w_bdim:
if x_bdim is None:
x = VMapTrace.move_vmap_dim(x, dim_size, x_bdim, w_bdim)
x_bdim = w_bdim
else:
w = VMapTrace.move_vmap_dim(w, dim_size, w_bdim, x_bdim)
return [self(x, w, **params)], [x_bdim]
def typecheck(self, x: SymbolicTensor, y: SymbolicTensor, **params) -> List[SymbolicTensor]:
if not isinstance(x, (Tensor, SymbolicTensor)) or not isinstance(y, (Tensor, SymbolicTensor)):
raise TypeError
symx = SymbolicTensor.like(x, dtype=dtypes.bool if self.boolean_output else x.dtype)
symy = SymbolicTensor.like(y, dtype=dtypes.bool if self.boolean_output else y.dtype)
if x.dtype != y.dtype:
raise TypeError(f"x.dtype ({x.dtype}) != y.dtype ({y.dtype})")
if symx == symy:
return [symx]
shape_delta = len(symx.shape) - len(symy.shape)
if shape_delta > 0:
symy = symy.like(shape=(1,) * shape_delta + symy.shape)
elif shape_delta < 0:
symx = symx.like(shape=(1,) * -shape_delta + symx.shape)
if symx == symy:
return [symx]
else:
shape_ret = tuple([max(x, w) for x, w in zip(symx.shape, symy.shape)])
if symx.shape != shape_ret:
symx = symx.like(shape=shape_ret)
if symy.shape != shape_ret:
symy = symx.like(shape=shape_ret)
if symx != symy:
raise TypeError(f"symx ({symx}) != symy ({symy})")
return [symx]
def jvp(self, primals, tangents, **params):
(x, w), (x_dot, w_dot) = primals, tangents
return [self(x, w, **params)], [self(x_dot, w_dot, **params)]
def T(self, cotangents, x, w):
(gL_y,) = cotangents
if self.boolean_output:
gL_y = gL_y.cast(x.dtype)
if isinstance(x, UndefinedPrimal):
return [gL_y, NullCotangent]
elif isinstance(w, UndefinedPrimal):
return [NullCotangent, gL_y]
else:
raise ValueError
class ReduceOperator(Operator):
def args_fixer(self, x, *, dim=None, keepdim=False):
if dim is None:
dim = tuple(range(x.ndim))
elif isinstance(dim, int):
dim = (dim,)
dim = tuple(a if a >= 0 else a + len(x.shape) for a in dim)
return (x,), dict(dim=dim, keepdim=keepdim)
def vmap(self, dim_size, vals_in, dims_in, *, dim, keepdim):
(x,), (x_bdim,) = vals_in, dims_in
dim = tuple(a + (x_bdim <= a) for a in dim)
out_bdim = x_bdim - sum(a < x_bdim for a in dim)
return [self(x, dim=dim, keepdim=keepdim)], [out_bdim]
def typecheck(self, x: SymbolicTensor, *, dim=None, keepdim=False) -> List[SymbolicTensor]:
dim = list(set([a + len(x.shape) if a < 0 else a for a in dim]))
if keepdim:
new_shape = [d if i not in dim else 1 for i, d in enumerate(x.shape)]
else:
new_shape = [d for i, d in enumerate(x.shape) if i not in dim]
return [SymbolicTensor.like(x, shape=tuple(new_shape))]
class InitOperator(Operator):
def vmap(self, dim_size, vals_in, dims_in, **params):
(x_bdim,) = dims_in
y = self(**params)
y = y.unsqueeze(x_bdim)
return [y], [x_bdim]
def jvp(self, primals, tangents, **params):
y = self(**params)
y_dot = NullCotangent(y.symval)
return [y], [y_dot]
def T(self, cotangents, **params):
return [NullCotangent(cotangents[0])]
class ShapeOperator(Operator):
pass
class GeneralReduceOperator(Operator):
pass
class OperatorSet:
def __init__(self):
self.register("jit_op")(JitOp)
def register(self, name, variadic_inputs=False, nary_outputs=False, aliases=()):
def wrap(op_cls):
assert name not in vars(self)
op = op_cls(name, variadic_inputs, nary_outputs)
setattr(self, name, op)
for a in aliases:
setattr(self, a, op)
return op_cls
return wrap
class ProcedureSet:
def register(self, aliases=()):
def wrap(f):
assert f.__name__ not in vars(self)
setattr(self, f.__name__, f)
for a in aliases:
setattr(self, a, f)
return f
return wrap
class CodegenOutput(NamedTuple):
code_lines: List[str]
fn_defs: Dict[str, List[str]]
in_binders: List["ProgramEnvVar"]
outs: List["ProgramEnvVar"]
class Backend:
LOG_LRU = int(os.environ.get("LOG_LRU", 0))
LOG_JIT = int(os.environ.get("LOG_JIT", 0))
LOG_TREE = int(os.environ.get("LOG_TREE", 0))
LOG_BACKEND = int(os.environ.get("LOG_BACKEND", 0))
LOG_PROGRAM = int(os.environ.get("LOG_PROGRAM", 0))
LOG_INIT = int(os.environ.get("LOG_INIT", 1))
device_var = os.environ.get("DEFAULT_DEVICE", "cpu:0")
if device_var[-2] != ":":
device_var += ":0"
DEFAULT_DEVICE = devices.name_idx_device_map[device_var]
DEFAULT_DTYPE = dtypes.name_dtype_map[os.environ.get("DEFAULT_DTYPE", "float32")]
dtype_for_indices: DType = None # need to override
def __init__(
self,
operator_set: OperatorSet,
procedure_set: ProcedureSet,
):
self.operator_set = operator_set
self.procedure_set = procedure_set
self.node_types = dict()
self.impls = dict()
self.register_node(tuple, lambda t: (None, t), lambda _, xs: tuple(xs), "tuple")
self.register_node(list, lambda l: (None, l), lambda _, xs: list(xs), "list")
self.register_node(
dict,
lambda d: list_map(tuple, unzip2(sorted(d.items()))),
lambda keys, vals: dict(list_zip(keys, vals)),
"dict",
)
self.register_node(
UndefinedPrimal,
lambda u: (u.symval, ()),
lambda symval, _: UndefinedPrimal(symval),
"UndefinedPrimal",
)
def set_impl(self, op: Union[types.LambdaType, types.FunctionType]):
def set_impl_(fn):
self.impls[op] = types.MethodType(fn, self)
return set_impl_
def register_node(self, ty: Type, to_iter: Callable, from_iter: Callable, name=None) -> None:
if name is None:
name = str(ty)
self.node_types[ty] = NodeType(name, to_iter, from_iter)
def __getattr__(self, attr):
try:
dblog(
f"Looking {self}.{attr} in operator_set",
enable=backend.LOG_BACKEND,
)
return getattr(self.operator_set, attr)
except:
pass
try:
dblog(
f"Looking {self}.{attr} in procedure_set",
enable=backend.LOG_BACKEND,
)
return getattr(self.procedure_set, attr)
except:
pass
dblog(
f"Fallback to default {self} getattribute",
enable=backend.LOG_BACKEND,
)
super().__getattribute__(attr)
def tensor(
self,
val: Union[list, tuple, np.ndarray, "TensorBuffer"] = None,
dtype: Optional[Any] = None,
device=None,
):
if isinstance(val, TensorBuffer):
return Tensor(val)
elif isinstance(val, Tensor):
return val
if type(val) is bytes:
val = np.frombuffer(val, dtype=dtype)
return self.from_numpy(val, dtype, device)
def symbolic_tensor(
self,
shape: Union[list, tuple, np.ndarray, "TensorBuffer"] = None,
dtype: Optional[Any] = None,
device=None,
):
dtype = dtype or self.DEFAULT_DTYPE
device = device or self.DEFAULT_DEVICE
return SymbolicTensor(shape, dtype, device)
def seed(self, seed):
raise NotImplementedError
@property
def default_dtype_value(self):
return self.dtype_map[backend.DEFAULT_DTYPE]
def set_method(self, method):
setattr(self, method.__name__, types.MethodType(method, self))
def from_numpy(self, val, device):
raise NotImplementedError
def numpy_of(self, tensor):
raise NotImplementedError
def device_of(self, tensor):
raise NotImplementedError
def shape_of(self, tensor):
raise NotImplementedError
def dtype_of(self, tensor):
raise NotImplementedError
@lru_cache_verbose()
def jit_program(
self,
hashed_program: Hashed,
hashed_consts: Tuple[Hashed, ...],
):
program: Program = hashed_program.val
typecheck_program(program)
consts = [x.val for x in hashed_consts]
in_symvals = [v.symval for v in program.in_binders[len(consts) :]]
codegen_output: CodegenOutput = self.codegen(program, consts + in_symvals, fn_name="main")
fn, code = self.compile(codegen_output)
jit_output = JitOutput(program, codegen_output, fn, code, consts)
return jit_output
def codegen(self, program: "Program", args: Tuple, in_symvals: Tuple, name: str):
"Returns compiler IR from the Program"
raise NotImplementedError
def compile(self, program: "Program", args: Tuple, in_symvals: Tuple, name: str):
"Compiles compiler IR to a Python callable function"
raise NotImplementedError
def export(self, jit_output, *args, **params):
raise NotImplementedError
def load(self, path, single_key="_tensor"):
with open(path, mode="rb") as f:
with mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_READ) as m:
json_len = np.int64(m[0])
start = 8 + json_len
metadata = json.loads(m[8:start])
ret = {}
for k, v in metadata.items():
if k != "__metadata__":
dtype = Tensor.mlir_dtype_map[(v["dtype"])]
data_start = start + v["data_offsets"][0]
data_end = start + v["data_offsets"][1]
t_np = np.frombuffer(m[data_start:data_end], dtype=dtype.numpy())
t = backend.tensor(t_np, dtype=dtype)
t = t.reshape(tuple(v["shape"]))
ret[k] = t
if len(ret) == 1 and single_key in ret.keys():
return ret[single_key]
return ret
def save(self, tensors: Dict[str, Tensor], path: str, single_key="_tensor"):
if isinstance(tensors, Tensor):
tensors = {single_key: tensors}
else:
assert all((isinstance(k, str) and isinstance(v, Tensor)) for k, v in tensors.items())
metadata, offset = {}, 0
for k, v in tensors.items():
metadata[k] = {
"dtype": v.dtype.mlir,
"shape": list(v.shape),
"data_offsets": [offset, offset + v.nbytes()],
}
offset += v.nbytes()
j = json.dumps(metadata, separators=(",", ":"))
Path(path).unlink(missing_ok=True)
jbytes = j.encode("utf-8")
start = 8 + len(jbytes)
with open(path, mode="wb") as f: # make empty file, fill with enough space
f.write(b"\x00" * (start + offset))
with open(path, mode="r+b") as f:
with mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_WRITE) as m:
m[0:8] = np.int64(len(j)).tobytes()
m[8:start] = jbytes
for t, tm in zip(tensors.values(), metadata.values()):
data_start, data_end = tm["data_offsets"]
m[start + data_start : start + data_end] = t.numpy().tobytes()
# =================================
# Program
# =================================
class Var:
def __init__(self, symval):
self.symval = symval
self.val = None
class Lit:
def __init__(self, val):
self.symval = SymbolicTensor.like(get_symval(val))
self.val = val
Atom = Union[Var, Lit]
class Instruction(NamedTuple):
op: Operator
inputs: List[Atom]
params: Dict[str, Any]
out_binders: List[Atom]
class ProgramEnvVar(NamedTuple):
name: str
symval: SymbolicTensor
is_const: bool = False
@property
def shape(self):
return self.symval.shape