/
_backend.py
1472 lines (1299 loc) · 46.5 KB
/
_backend.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
"""
Backends for the frontend API
"""
from __future__ import annotations
from typing import Optional, Any, Union, TypeVar, Generic, Type, Callable, Sequence, Dict, Tuple, List
import contextlib
import numpy
import returnn.frontend as rf
from returnn.tensor import Tensor, Dim
from returnn.util.basic import BehaviorVersion
from .types import RawTensorTypes, ItemKeyType
T = TypeVar("T") # tf.Tensor, torch.Tensor or so
T2 = TypeVar("T2")
S = TypeVar("S") # any nested structure, can be None
class Backend(Generic[T]):
"""
Abstract base class for the backend, operating on tensor type T, i.e. :class:`Tensor[T]`.
This class and instances do not have any state,
and all functions are staticmethod (or classmethod).
"""
# class attribs set by derived classes
name: Optional[str] = None # e.g. "tensorflow" or "torch"
RawTensorType: Type[T]
is_tensorflow: bool = False # whether this framework uses TensorFlow
is_backend_raw_tensor_dim_tag_independent: bool = True # whether raw tensors of backend are independent of Dim
def __init__(self):
raise Exception("do not instantiate this class")
# --- functions to override
@staticmethod
def executing_eagerly() -> bool:
"""
:return: whether we are in eager execution mode
"""
raise NotImplementedError
@staticmethod
def get_tensor_dependencies(x: Tensor) -> Sequence[Tensor]:
"""
:param x: tensor
:return: list of all tensors which are inputs to `x`, ancestor tensors, dependencies.
E.g. :func:`tf.Tensor.op.inputs`.
This mostly makes sense for graph-based frameworks
but eager-based frameworks might have this too with enabled gradient tape,
as they should know the inputs.
"""
raise NotImplementedError
@staticmethod
def get_tensor_consumers(x: Tensor) -> Sequence[Tensor]:
"""
:param x: tensor
:return: list of all tensors depending on `x`, descendant tensors, used by.
E.g. :func:`tf.Tensor.consumers`.
This mostly makes sense for graph-based frameworks
but eager-based frameworks might have this too with enabled gradient tape,
as they should know the consumers.
"""
raise NotImplementedError
@staticmethod
def cond(pred: Tensor, true_fn: Callable, false_fn: Callable):
"""
cond: conditional execution.
Note that this does not need an implementation for eager-based frameworks
(:func:`executing_eagerly` returns True),
as the :func:`returnn.frontend.cond` function already covers that case.
"""
# noinspection PyProtectedMember
assert not pred._raw_backend.executing_eagerly(), "should not get here"
raise NotImplementedError
@staticmethod
def while_loop(
cond: Callable[[S], Union[bool, Tensor]],
body: Callable[[S], S],
initial: S,
) -> S:
"""while loop"""
raise NotImplementedError
@staticmethod
def set_random_seed(seed: int):
"""
:param seed:
"""
raise NotImplementedError
@staticmethod
def get_random_state() -> Dict[str, bytes]:
"""
:return: random state
"""
raise NotImplementedError
@staticmethod
def set_random_state(state: Dict[str, bytes]):
"""
:param state: as returned by :func:`get_random_state`.
This might not always be successful (e.g. different hardware, different backend version),
so the calling code should always have called set_random_seed before to have the random generators
in a reasonable fallback state.
"""
raise NotImplementedError
@staticmethod
def get_dtype_name_raw(raw_tensor: T) -> str:
"""
:return: dtype of raw tensor, as string
"""
raise NotImplementedError
@staticmethod
def as_dtype_raw(dtype_name: str) -> Any:
"""
:param dtype_name: e.g. "float32"
:return: dtype object
"""
raise NotImplementedError
@staticmethod
def get_ndim_raw(raw_tensor: T) -> int:
"""
:return: ndim of raw tensor. assumes it is known
"""
raise NotImplementedError
@staticmethod
def get_shape_raw(raw_tensor: T) -> Union[T, Tuple[Union[int, T]]]:
"""
:return: shape of raw tensor
"""
raise NotImplementedError
@staticmethod
def get_shape_tuple_raw(raw_tensor: T) -> Tuple[Union[int, T]]:
"""
:return: shape of raw tensor. assumes that ndim is known.
In eager frameworks, all dims are int.
"""
raise NotImplementedError
@staticmethod
def get_known_shape_raw(raw_tensor: T) -> Tuple[Optional[int]]:
"""
:return: shape of raw tensor, int for static known, None otherwise. assumes that ndim is known.
This will not create any ops.
In eager frameworks, all dims are known.
"""
raise NotImplementedError
@staticmethod
def set_known_shape_raw(raw_tensor: T, shape: Tuple[Optional[int]]) -> None:
"""
Sets the known shape of the raw tensor.
This is only supported in graph-based frameworks,
and just performs a check in eager frameworks.
"""
# Nothing for eager-based frameworks.
@staticmethod
def get_new_dim_raw(raw_tensor: T, axis: int, *, name: str) -> Dim:
"""
:param raw_tensor:
:param axis:
:param name:
:return: dim tag of axis
"""
raise NotImplementedError
@staticmethod
def get_device(x: Tensor) -> Optional[str]:
"""
:param x:
:return: device, or none if unknown or logic not supported
"""
# default implementation: ignore device
return None
@staticmethod
def copy_to_device(x: Tensor, device: Optional[str]) -> Tensor:
"""
:param x: tensor
:param device: e.g. "cpu" or "gpu"
:return: tensor on device
"""
# default implementation: ignore device
return x
@staticmethod
def fill_raw(shape: Union[Sequence[Union[int, T]], T], value: Union[Any, T]) -> T:
"""
:param shape: shape
:param value: scalar value to fill
:return: raw tensor filled with value everywhere
"""
raise NotImplementedError
@staticmethod
def compare_raw(a: T, kind: str, b: T) -> T:
"""
:param a:
:param kind: "equal", "less", "less_equal", "greater", "greater_equal", "not_equal"
:param b:
:return: a `kind` b
"""
raise NotImplementedError
@staticmethod
def combine_raw(a: T, kind: str, b: T) -> T:
"""
:param a:
:param kind: "add", "sub", "mul", "truediv", "floordiv", "mod", "pow",
"maximum", "minimum", "logical_and", "logical_or", "squared_difference"
:param b:
:return: a `kind` b
"""
raise NotImplementedError
@staticmethod
def reshape_raw(raw_tensor: T, shape: Union[Sequence[Union[int, T]], T]) -> T:
"""
:param raw_tensor: raw tensor
:param shape: new shape
:return: reshaped raw tensor
"""
raise NotImplementedError
@classmethod
def squeeze_raw(cls, raw_tensor: T, axes: Sequence[int]) -> T:
"""
:param raw_tensor: raw tensor
:param axes: axes to squeeze
:return: squeezed raw tensor
"""
# Default implementation using reshape_raw.
known_shape = cls.get_known_shape_raw(raw_tensor)
assert all([known_shape[axis] == 1 for axis in axes])
new_shape = [dim for a, dim in enumerate(cls.get_shape_tuple_raw(raw_tensor)) if a not in axes]
return cls.reshape_raw(raw_tensor, new_shape)
@staticmethod
def transpose_raw(raw_tensor: T, perm: Sequence[int]) -> T:
"""
:param raw_tensor: raw tensor
:param perm: permutation
:return: transposed raw tensor
"""
raise NotImplementedError
@staticmethod
def make_output_tensor(tensor: Tensor, dims: Sequence[Dim], *, name: str) -> Tensor:
"""
:param tensor:
:param dims:
:param name:
:return: tensor with dims order like in dims
"""
assert len(dims) == len(tensor.dims)
tensor = tensor.copy_compatible_to_dims(dims)
tensor = tensor.copy(name=name)
return tensor
@staticmethod
def expand_dims_raw(raw_tensor: T, axis: int) -> T:
"""
:param raw_tensor:
:param axis:
:return: raw tensor with new axis
"""
raise NotImplementedError
@staticmethod
def expand_raw(raw_tensor: T, axis: int, dim: Union[int, T]) -> T:
"""
:param raw_tensor:
:param axis: shape[axis] must be 1
:param dim: the new dim for shape[axis]
:return: shape[axis] expands to dim.
in PyTorch or other frameworks which support custom strides,
this is an efficient view and not a copy.
"""
raise NotImplementedError
@staticmethod
def copy(tensor: Tensor) -> Tensor:
"""copy"""
raise NotImplementedError
@staticmethod
def cast_raw(raw_tensor: T, dtype: str) -> T:
"""
:param raw_tensor:
:param dtype: e.g. "float32"
:return: raw tensor with dtype casted
"""
raise NotImplementedError
@staticmethod
def cast(tensor: Tensor, dtype: str) -> Tensor:
"""
:param tensor:
:param dtype: e.g. "float32"
:return: tensor with dtype casted
"""
# Default implementation using cast_raw.
res = tensor.copy_template()
res.dtype = dtype
if res.sparse_dim:
if dtype.startswith("int") or dtype.startswith("uint"):
pass
elif dtype == "bool" and res.sparse_dim.dimension == 2:
pass
else:
res.sparse_dim = None
# noinspection PyProtectedMember
res.raw_tensor = tensor._raw_backend.cast_raw(tensor.raw_tensor, dtype)
return res
@staticmethod
def set_requires_gradient(tensor: Tensor):
"""
:param tensor:
"""
raise NotImplementedError
@staticmethod
def gradient(y: Tensor, x: Tensor) -> Tensor:
"""
:param y:
:param x:
:return: gradient of y w.r.t. x
"""
raise NotImplementedError
@staticmethod
def stop_gradient(tensor: Tensor) -> Tensor:
"""
:param tensor:
:return: tensor with stopped gradient
"""
raise NotImplementedError
@staticmethod
def scaled_gradient(tensor: Tensor, scale: Union[float, Tensor]) -> Tensor:
"""
:param tensor:
:param scale:
:return: tensor with scaled gradient
"""
raise NotImplementedError
@staticmethod
def scaled_gradient_ext(
x: Tensor,
*,
scale: Union[float, Tensor] = 1.0,
shift: Optional[Union[float, Tensor]] = None,
scale_shift_by_sum_over_axis: Optional[Dim] = None,
):
"""
:param x:
:param scale: will scale gradient by this value
:param shift: will shift gradient by this value
:param scale_shift_by_sum_over_axis: if given, will scale and shift by the sum over the given axis
:return: just x, but gradient in backward pass will be transformed accordingly
"""
raise NotImplementedError
@staticmethod
def merge_dims(
source: Tensor,
*,
dims: Sequence[Dim],
out_dim: Optional[Dim] = None,
) -> Tuple[Tensor, Dim]:
"""
Merges a list of axes into a single one. (Flatten the dims.)
E.g. input is (batch, width, height, dim) and dims=(width,height), then we get (batch, width*height, dim).
Or input is (batch, time, height, dim) and axes=(height,dim), then we get (batch, time, height*dim).
:param source:
:param dims:
:param out_dim:
:return: tensor, out_dim
"""
raise NotImplementedError
@staticmethod
def split_dims(
source: Tensor,
*,
axis: Dim,
dims: Sequence[Dim],
pad_to_multiples: Optional[bool] = None,
pad_value: Union[None, int, float] = None,
) -> Tensor:
"""
:param source:
:param axis:
:param dims:
:param pad_to_multiples:
:param pad_value:
:return: source with axis replaced by dims
"""
raise NotImplementedError
@staticmethod
def reshape(source: Tensor, in_dims: Sequence[Dim], out_dims: Sequence[Dim]) -> Tensor:
"""
:param source: e.g. (..., old_dims, ...)
:param in_dims: the old dims which should be reshaped into new_dims.
This should only cover those dims which should be reshaped,
not all the dims of the source.
:param out_dims: the new dims which should be reshaped from old_dims.
This is excluding any of the other dims in the source.
:return: e.g. (..., new_dims, ...)
"""
raise NotImplementedError
@staticmethod
def split(source: Tensor, *, axis: Dim, out_dims: Sequence[Dim]) -> Tuple[Tensor, ...]:
"""
Split the input on the specified axis (by default feature).
Basically a wrapper around tf.split.
:param source: {..., axis}
:param axis: some static axis
:param out_dims: list of dims where sum(out_dims) == axis
:return: tuple of tensors, same amount as out_dims,
with the same shape as source, but with the specified axis replaced by the out_dims
"""
raise NotImplementedError
@staticmethod
def expand_dim(source: Tensor, dim: Dim) -> Tensor:
"""
:param source:
:param dim:
:return: source with dim added
"""
raise NotImplementedError
@staticmethod
def squeeze(source: Tensor, axis: Dim) -> Tensor:
"""
:param source:
:param axis:
:return: source with axis removed
"""
raise NotImplementedError
@staticmethod
def concat(
*sources: Tuple[Tensor, Dim],
allow_broadcast: bool = False,
out_dim: Dim,
) -> Tensor:
"""concat"""
raise NotImplementedError
@staticmethod
def pad(
source: Tensor,
*,
axes: Sequence[Dim],
padding: Sequence[Tuple[Union[Dim, int], Union[Dim, int]]],
out_dims: Sequence[Dim],
handle_dynamic_dims: bool,
mode: str = "constant",
value: Optional[Union[rf.RawTensorTypes, Tensor]] = None,
) -> Tensor:
"""
:param source:
:param axes:
:param padding:
:param out_dims:
:param handle_dynamic_dims:
:param mode:
:param value:
:return: padded tensor
"""
raise NotImplementedError
@staticmethod
def cum_concat_step(source: Tensor, *, prev_accum: Tensor, axis: Dim, out_spatial_dim: Dim) -> Tensor:
"""
Concatenates all previous frames over a time-axis.
See RETURNN :class:`CumConcatLayer` for details.
:param source: same dims as prev_accum except for the accum axis
:param prev_accum: previous accumulated tensor, shape {..., axis}
:param axis: the axis to accumulate over
:param out_spatial_dim: the spatial dim of the output will be this dim. like axis+1.
:return: accumulated. accumulated shape {..., out_spatial_dim},
same shape as prev_accum with axis replaced by out_spatial_dim.
"""
raise NotImplementedError
# Restrict the possible activation function names,
# to not get unexpected behavior,
# or unwanted incompatibilities.
_AllowedActivationFuncs = {
"exp",
"expm1",
"log",
"log1p",
"sqrt",
"rsqrt",
"square",
"abs",
"tanh",
"sigmoid",
"log_sigmoid",
"sin",
"cos",
"ceil",
"floor",
"round",
"relu",
"elu",
"selu",
"silu",
"gelu",
"logical_not",
"neg",
"reciprocal",
}
@staticmethod
def activation(tensor: Tensor, func: str) -> Tensor:
"""
:param tensor:
:param func: "tanh", "sigmoid", "relu", ...
:return: tensor with elementwise activation applied
"""
out = tensor.copy_template(name=func)
# noinspection PyProtectedMember
out_raw = tensor._raw_backend.activation_raw(tensor.raw_tensor, func)
# noinspection PyProtectedMember
out.dtype = tensor._raw_backend.get_dtype_name_raw(out_raw)
out.raw_tensor = out_raw
return out
@staticmethod
def activation_raw(raw_tensor: T, func: str) -> T:
"""
:param raw_tensor:
:param func: "tanh", "sigmoid", "relu", ...
:return: raw tensor with elementwise activation applied
"""
raise NotImplementedError
@staticmethod
def safe_log(tensor: Tensor, *, eps: float) -> Tensor:
"""
:param tensor:
:param eps:
:return: log(tensor + eps) in the default case. but some backends might do more things,
like if tensor = softmax(logits), then this would be log_softmax(logits) instead.
"""
return rf.log(rf.maximum(tensor, eps))
@staticmethod
def softmax(tensor: Tensor, *, axis: Dim, use_mask: bool = True) -> Tensor:
"""
:param tensor:
:param axis:
:param use_mask:
:return: softmax over axis
"""
raise NotImplementedError
@staticmethod
def log_softmax(tensor: Tensor, *, axis: Dim, use_mask: bool = True) -> Tensor:
"""
:param tensor:
:param axis:
:param use_mask:
:return: log_softmax over axis
"""
raise NotImplementedError
@staticmethod
def softmax_cross_entropy_with_logits(*, logits: Tensor, targets: Tensor, axis: Dim):
"""
Efficient cross entropy.
:param logits: target estimates given as inputs to softmax (i.e. unnormalized)
:param targets: probabilities, i.e. normalized, can also be sparse
:param axis: class labels dim over which softmax is computed
:return: cross entropy (same Dims as 'logits' but without 'axis')
"""
raise NotImplementedError
@staticmethod
def ctc_loss(
*,
logits: Tensor,
targets: Tensor,
input_spatial_dim: Dim,
targets_spatial_dim: Dim,
blank_index: int,
max_approx: bool = False,
) -> Tensor:
"""
Calculates the CTC loss.
"""
raise NotImplementedError
@staticmethod
def have_sequence_mask_raw() -> bool:
"""
:return: whether we have a sequence_mask_raw implementation
"""
return False
@staticmethod
def sequence_mask_raw(lengths: T, *, batch_major: bool = True) -> T:
"""
Like tf.sequence_mask().
:param lengths: shape (batch,)
:param batch_major:
:return: tensor mask of shape (batch,maxlen) if batch_major else (maxlen,batch) of type bool
"""
raise NotImplementedError
@staticmethod
@contextlib.contextmanager
def name_scope_raw(name: str) -> Any:
"""
Default implementation for eager-based frameworks:
Do nothing, tensors do not have a name.
:param name:
:return: context manager
"""
# Default implementation for eager-based frameworks
yield # nothing to do
@staticmethod
@contextlib.contextmanager
def control_dependencies_raw(dependencies: Sequence[Any]) -> Any:
"""
Default implementation for eager-based frameworks:
Do nothing, we expect that the dependencies are already executed.
:param dependencies: raw tensors or ops
:return: context manager
"""
# Default implementation for eager-based frameworks
yield
@staticmethod
def identity_with_control_dependencies_raw(raw_tensor: T, dependencies: Sequence[Any]) -> T:
"""
Default implementation for eager-based frameworks:
Do nothing, we expect that the dependencies are already executed.
:param raw_tensor: raw tensor
:param dependencies: raw tensors or ops
:return: raw tensor
"""
# Default implementation for eager-based frameworks
return raw_tensor
@staticmethod
def create_placeholder_raw(tensor: Tensor) -> T:
"""
:return: tf.placeholder in TF
This is really only for TensorFlow for the deprecated option auto_create_placeholders
and should not be used in other backends,
even in graph-based backends.
Rather, the logic to create placeholders should be done elsewhere.
"""
raise Exception("create_placeholder not supported by backend")
@staticmethod
def create_parameter_raw(tensor: rf.Parameter, *, device: Optional[str] = None) -> T:
"""
:return: parameter (by default trainable)
"""
raise NotImplementedError
@staticmethod
def set_parameter_initial_value(param: rf.Parameter, value: Union[None, Tensor, rf.RawTensorTypes]) -> None:
"""
:param param: parameter
:param value: initial value
"""
raise NotImplementedError
@staticmethod
def set_parameter_trainable(param: rf.Parameter, trainable: bool) -> None:
"""
:param param: parameter
:param trainable: whether the parameter should be trainable
"""
raise NotImplementedError
@staticmethod
def parameter_assign(param: rf.Parameter, value: Tensor, *, op: str = "assign") -> None:
"""
:param param: parameter
:param value: new value
:param op: "assign" or "add"
"""
raise NotImplementedError
@staticmethod
def parameter_assign_key(
param: rf.Parameter,
key: ItemKeyType,
value: Tensor,
*,
op: str = "assign",
axis: Optional[Union[Dim, Sequence[Dim]]] = None,
key_dim: Union[None, Dim, Sequence[Union[None, Dim]]] = None,
) -> None:
"""
:param param: parameter
:param key: optional key for slice assign, like var[key] = value or var[key] += value.
:param value: new value
:param op: "assign" or "add"
:param axis: if key is given, this axis is used.
if key are indices (without specified sparse_dim), axis must be specified.
:param key_dim: resulting dim after slicing with key
"""
raise NotImplementedError
@staticmethod
def parameter_move_to(param: rf.Parameter, *, device: Optional[str] = None, dtype: Optional[str] = None):
"""
Updates `param` inplace, but `param.raw_tensor` might be a new instance.
:param param:
:param device:
:param dtype:
"""
raise NotImplementedError
@staticmethod
def runtime_sanity_checks(tensor: Tensor) -> Any:
"""
Checks whether the tensor.raw_tensor is consistent with the tensor metadata.
In graph-based frameworks (TF graph), we return some operation here.
In eager frameworks, we would not return anything but instead directly perform the checks.
"""
# By default, we do not do any checks. This is optional for the backend.
pass
@staticmethod
def is_valid_in_current_graph(tensor: Tensor) -> bool:
"""
:return: whether the raw tensor is valid in the current graph.
In eager-mode frameworks, this is always true -- there is no graph.
"""
return True
@staticmethod
def format_graph_output(raw_tensor: T, *, max_depth: Optional[int] = None) -> str:
"""
:return: the computation graph leading to this tensor formatted.
In eager-mode frameworks, this is not supported and returns None.
"""
return "<no-graph>"
@staticmethod
def convert_to_tensor(
value: Union[Tensor, T, RawTensorTypes],
*,
dims: Sequence[Dim],
dtype: str,
sparse_dim: Optional[Dim] = None,
device: Optional[str] = None,
name: Optional[str] = None,
) -> Tensor[T]:
"""
:param value: tensor, or scalar raw tensor or some other scalar value
:param dims:
:param dtype:
:param sparse_dim:
:param device:
:param name:
:return: tensor
"""
raise NotImplementedError
@staticmethod
def full(
dims: Sequence[Dim],
fill_value: Union[RawTensorTypes, Tensor],
*,
dtype: str,
device: Optional[str] = None,
sparse_dim: Optional[Dim] = None,
feature_dim: Optional[Dim] = None,
) -> Tensor:
"""
https://data-apis.org/array-api/latest/API_specification/generated/array_api.full.html
:param dims:
:param fill_value:
:param dtype:
:param device:
:param sparse_dim:
:param feature_dim:
:return: tensor
"""
raise NotImplementedError
@classmethod
def compare(
cls,
a: Union[Tensor, RawTensorTypes],
kind: str,
b: Union[Tensor, RawTensorTypes],
*,
allow_broadcast_all_sources: Optional[bool] = None,
dim_order: Optional[Sequence[Dim]] = None,
) -> Tensor:
"""compare, default implementation using compare_raw"""
from . import _utils
out, a_raw, b_raw = _utils.bin_op_out_template(
cls,
a,
b,
name=kind,
copy_sparse_dim=False,
allow_broadcast_all_sources=allow_broadcast_all_sources,
dim_order=dim_order,
)
out_raw = cls.compare_raw(a_raw, kind, b_raw)
out.dtype = cls.get_dtype_name_raw(out_raw)
out.raw_tensor = out_raw
return out
@classmethod
def combine(
cls,
a: Union[Tensor, RawTensorTypes],
kind: str,
b: Union[Tensor, RawTensorTypes],
*,
allow_broadcast_all_sources: Optional[bool] = None,
dim_order: Optional[Sequence[Dim]] = None,
) -> Tensor:
"""combine, default implementation using combine_raw"""
from . import _utils
out, a_raw, b_raw = _utils.bin_op_out_template(
cls,
a,
b,
name=kind,
allow_broadcast_all_sources=allow_broadcast_all_sources,
dim_order=dim_order,
)
out_raw = cls.combine_raw(a_raw, kind, b_raw)
out.dtype = cls.get_dtype_name_raw(out_raw)
out.raw_tensor = out_raw
return out
@staticmethod
def gather(
source: Tensor,
*,
indices: Union[Tensor, int],
axis: Dim,
clip_to_valid: bool = False,
) -> Tensor:
"""
Gathers slices on a specified axis from the source using indices.
If the source is of the shape ``[B,D,F1]``, and indices of shape ``[B,F2]``,
this will yield output of the shape ``[B,F2,F1]`` where
``output[b,f2,f1] = source[b,indices[b,f2],f1]``
(if ``D`` is the axis to gather from).
In general, all shared axes of the input and the positions will be considered as batch-axes.
The ``indices`` argument can also be an ``int``.
In this case, this simply gives ``source[indices]`` on the specified ``axis``.
:param source:
:param indices: indices used to select the slices of the source from.
If another tensor, must be of type ``int32`` or ``int64``.
Can also specify a constant ``int``.
:param axis: The axis into which we gather the indices into
:param clip_to_valid: if True, the indices will be clipped to the valid range of the input
Also taking seq lengths into account.
:return: gathered values
"""
raise NotImplementedError
@staticmethod
def scatter(
source: Tensor,
*,
indices: Tensor,
indices_dim: Union[Dim, Sequence[Dim]],
out_dim: Union[Dim, Sequence[Dim]],
) -> Tensor:
"""
Scatters into new zero-tensor.
If entries in indices are duplicated, the corresponding values in source will be added together
(scatter_add in PyTorch).
(TF segment_sum can be implemented via this.)
:param source: [batch_dims..., indices_dim(s)..., feature_dims...]
:param indices: [batch_dims..., indices_dim(s)...] -> out_dim
:param indices_dim:
:param out_dim:
:return: [batch_dims..., out_dim, feature_dims...]
"""
raise NotImplementedError
@staticmethod
def slice(
source: Tensor,
*,
axis: Dim,
start: Optional[Union[int, Tensor]] = None,
end: Optional[Union[int, Tensor]] = None,
step: Optional[Union[int, Tensor]] = None,
size: Optional[Union[int, Tensor, Dim]] = None,
out_dim: Dim,
) -> Tensor:
"""slice"""
raise NotImplementedError
@staticmethod
def where(
cond: Tensor,
true_: Union[Tensor, rf.RawTensorTypes],
false_: Union[Tensor, rf.RawTensorTypes],
*,
allow_broadcast_all_sources: bool = False,
) -> Tensor:
"""where"""
raise NotImplementedError
@staticmethod
def clip_by_value(
x: Tensor,
clip_value_min: Union[Tensor, rf.RawTensorTypes],
clip_value_max: Union[Tensor, rf.RawTensorTypes],
*,
allow_broadcast_all_sources: bool = False,
) -> Tensor:
"""clip by value"""
raise NotImplementedError
@staticmethod
def matmul(a: Tensor[T], b: Tensor[T], *, reduce: Union[Dim, Sequence[Dim]], use_mask: bool = True) -> Tensor[T]:
"""
This performs a batched matmul of two sources a and b
(non-batched matmul and dot product are special cases).
The underlying operation is a batched matmul (shared..., I, J) * (shared..., J, K) -> (shared..., I, K).
The inputs a and b are transformed internally into the required shapes in the following way:
The axis J is specified via the Dim given as 'reduce'. If multiple reduce Dims are given the corresponding axes
are merged into one before the matmul via a reshape. All other matching Dims in a and b will be treated as
batch dimensions ('shared...'). Dims unique to a and b define the axes I and K, respectively. (Multiple or no
unique axes in a and b are supported too.)
Depending on which Dims exist in a, b and reduce this dot operation can be used to compute scaling, scalar
product, outer product, matrix-vector multiplication, matrix-matrix multiplication etc. (all possibly batched).
:param a:
:param b:
:param reduce: Dims over which to perform the product, have to be present in both a and b
:param use_mask: If the reduction is over dynamic axes, to get the correct sum reduction,
we need to apply masking to one of the inputs. This is done automatically.
By disabling this flag, this would be disabled.
:return: result of dot product, Dim order: common axes as sorted in a, unique axes of a (in order),
unique axes of b (in order)
"""
raise NotImplementedError
@staticmethod
def range_over_dim(dim: Dim, *, dtype: Optional[str] = None, device: Optional[str] = None) -> Tensor[T]:
"""
:param dim:
:param dtype:
:param device:
:return: tensor with shape [dim]
"""