-
-
Notifications
You must be signed in to change notification settings - Fork 154
/
subtensor.py
2837 lines (2402 loc) · 89 KB
/
subtensor.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
import logging
import sys
from itertools import chain, groupby
from textwrap import dedent
from typing import Callable, Iterable, List, Optional, Tuple, Union
import numpy as np
import aesara
from aesara import scalar as aes
from aesara.configdefaults import config
from aesara.gradient import DisconnectedType
from aesara.graph.basic import Apply, Constant, Variable
from aesara.graph.op import Op
from aesara.graph.type import Type
from aesara.graph.utils import MethodNotDefined
from aesara.link.c.op import COp
from aesara.link.c.params_type import ParamsType
from aesara.misc.safe_asarray import _asarray
from aesara.printing import Printer, pprint, set_precedence
from aesara.scalar.basic import ScalarConstant
from aesara.tensor import _get_vector_length, as_tensor_variable, get_vector_length
from aesara.tensor.basic import alloc, get_scalar_constant_value
from aesara.tensor.elemwise import DimShuffle
from aesara.tensor.exceptions import (
AdvancedIndexingError,
NotScalarConstantError,
ShapeError,
)
from aesara.tensor.math import clip
from aesara.tensor.shape import Reshape, specify_broadcastable
from aesara.tensor.type import (
TensorType,
bscalar,
complex_dtypes,
cscalar,
discrete_dtypes,
dscalar,
fscalar,
integer_dtypes,
iscalar,
lscalar,
tensor,
ubscalar,
uiscalar,
ulscalar,
uwscalar,
wscalar,
zscalar,
)
from aesara.tensor.type_other import NoneConst, NoneTypeT, SliceType, make_slice
_logger = logging.getLogger("aesara.tensor.subtensor")
invalid_scal_types = (aes.float64, aes.float32, aes.float16)
scal_types = (
aes.int64,
aes.int32,
aes.int16,
aes.int8,
aes.uint64,
aes.uint32,
aes.uint16,
aes.uint8,
)
tensor_types = (
lscalar,
iscalar,
wscalar,
bscalar,
ulscalar,
uiscalar,
uwscalar,
ubscalar,
)
invalid_tensor_types = (
fscalar,
dscalar,
cscalar,
zscalar,
)
def indices_from_subtensor(
op_indices: Iterable[ScalarConstant],
idx_list: Optional[List[Union[Type, slice, Variable]]],
) -> Tuple[Union[slice, Variable]]:
"""Recreate the index tuple from which a ``*Subtensor**`` ``Op`` was created.
Parameters
==========
op_indices
The flattened indices obtained from ``x.inputs``, when ``x`` is a
``*Subtensor*`` node.
idx_list
The values describing the types of each dimension's index. This is
obtained from ``op.idx_list``, when ``op`` is a ``*Subtensor*``
``Op``.
Example
=======
array, *op_indices = subtensor_node.inputs
idx_list = getattr(subtensor_node.op, "idx_list", None)
indices = indices_from_subtensor(op_indices, idx_list)
"""
def convert_indices(indices, entry):
"""Reconstruct ``*Subtensor*`` index input parameter entries."""
if indices and isinstance(entry, Type):
rval = indices.pop(0)
return rval
elif isinstance(entry, slice):
return slice(
convert_indices(indices, entry.start),
convert_indices(indices, entry.stop),
convert_indices(indices, entry.step),
)
else:
return entry
op_indices = list(op_indices)
return (
tuple(convert_indices(op_indices, idx) for idx in idx_list)
if idx_list
else tuple(op_indices)
)
def as_index_constant(
a: Optional[Union[slice, int, np.integer, Variable]]
) -> Optional[Union[Variable, slice]]:
r"""Convert Python literals to Aesara constants--when possible--in `Subtensor` arguments.
This will leave `Variable`\s untouched.
"""
if a is None:
return a
elif isinstance(a, slice):
return slice(
as_index_constant(a.start),
as_index_constant(a.stop),
as_index_constant(a.step),
)
elif isinstance(a, (int, np.integer)):
return aes.ScalarConstant(aes.int64, a)
elif not isinstance(a, Variable):
return as_tensor_variable(a)
else:
return a
def as_index_literal(
idx: Optional[Union[Variable, slice]]
) -> Optional[Union[int, slice]]:
"""Convert a symbolic index element to its Python equivalent.
This is like the inverse of `as_index_constant`
Raises
------
NotScalarConstantError
"""
if idx == np.newaxis or isinstance(getattr(idx, "type", None), NoneTypeT):
return np.newaxis
if isinstance(idx, Constant):
return idx.data.item() if isinstance(idx, np.ndarray) else idx.data
if isinstance(getattr(idx, "type", None), SliceType):
idx = slice(*idx.owner.inputs)
if isinstance(idx, slice):
return slice(
as_index_literal(idx.start),
as_index_literal(idx.stop),
as_index_literal(idx.step),
)
raise NotScalarConstantError()
def get_idx_list(inputs, idx_list):
return indices_from_subtensor(inputs[1:], idx_list)
def get_canonical_form_slice(
theslice: Union[slice, Variable], length: Variable
) -> Tuple[Variable, int]:
"""Convert slices to canonical form.
Given a slice [start:stop:step] transform it into a canonical form
that respects the conventions imposed by python and numpy.
In a canonical form a slice is represented by a canonical form slice,
in which 0 <= start <= stop <= length and step > 0, and a flag which says
if the resulting set of numbers needs to be reversed or not.
"""
from aesara.tensor import ge, lt, sgn, switch
if not isinstance(theslice, slice):
try:
value = as_index_literal(theslice)
except NotScalarConstantError:
value = theslice
value = switch(lt(value, 0), (value + length), value)
return value, 1
def analyze(x):
try:
x_constant = as_index_literal(x)
is_constant = True
except NotScalarConstantError:
x_constant = x
is_constant = False
return x_constant, is_constant
start, is_start_constant = analyze(theslice.start)
stop, is_stop_constant = analyze(theslice.stop)
step, is_step_constant = analyze(theslice.step)
length, is_length_constant = analyze(length)
if step is None:
step = 1
is_step_constant = True
# First handle the easier and common case where `step` is 1 and
# either `start` or `stop` is a range boundary. More specializations
# could be added later. This makes the resulting graph smaller than
# in the generic case below.
if step == 1:
is_start_0 = (
start is None
or start == 0
or (
is_start_constant
and is_length_constant
and start < 0
and start + length <= 0
)
)
is_stop_length = (
stop is None
or stop in [length, sys.maxsize]
or (is_stop_constant and is_length_constant and stop >= length)
)
if is_start_0:
# 0:stop:1
if is_stop_length:
# Full slice.
return slice(0, length, 1), 1
if is_stop_constant and stop >= 0:
return (slice(0, switch(lt(stop, length), stop, length), 1), 1)
stop_plus_len = stop + length
stop = switch(
lt(stop, 0),
# stop < 0
switch(
lt(stop_plus_len, 0),
# stop + len < 0
0,
# stop + len >= 0
stop_plus_len,
),
# stop >= 0: use min(stop, length)
switch(lt(stop, length), stop, length),
)
return slice(0, stop, 1), 1
elif is_stop_length:
# start:length:1
if is_start_constant and start >= 0:
return slice(switch(lt(start, length), start, length), length, 1), 1
start_plus_len = start + length
start = switch(
lt(start, 0),
# start < 0
switch(
lt(start_plus_len, 0),
# start + len < 0
0,
# start + len >= 0
start_plus_len,
),
# start >= 0: use min(start, length)
switch(lt(start, length), start, length),
)
return slice(start, length, 1), 1
# This is the generic case.
if is_step_constant:
# When we know the sign of `step`, the graph can be made simpler.
assert step != 0
if step > 0:
def switch_neg_step(a, b):
return b
abs_step = step
sgn_step = 1
else:
def switch_neg_step(a, b):
return a
abs_step = -step
sgn_step = -1
else:
is_step_neg = lt(step, 0)
def switch_neg_step(a, b):
return switch(is_step_neg, a, b)
abs_step = abs(step)
sgn_step = sgn(step)
defstart = switch_neg_step(length - 1, 0)
defstop = switch_neg_step(-1, length)
if start is None:
start = defstart
else:
start = switch(lt(start, 0), start + length, start)
start = switch(lt(start, 0), switch_neg_step(-1, 0), start)
start = switch(ge(start, length), switch_neg_step(length - 1, length), start)
if stop is None or stop == sys.maxsize:
# The special "maxsize" case is probably not needed here,
# as slices containing maxsize are not generated by
# __getslice__ anymore.
stop = defstop
else:
stop = switch(lt(stop, 0), stop + length, stop)
stop = switch(lt(stop, 0), -1, stop)
stop = switch(ge(stop, length), length, stop)
nw_stop = switch_neg_step(start + 1, stop)
slice_len = (start - stop - 1) // abs_step + 1
slice_len = switch(lt(slice_len, 0), 0, slice_len)
neg_start = nw_stop - (slice_len - 1) * abs_step - 1
neg_start = switch(lt(neg_start, 0), (nw_stop - 1), neg_start)
nw_start = switch_neg_step(neg_start, start)
nw_start = switch(lt(nw_start, 0), 0, nw_start)
nw_stop = switch(lt(nw_stop, 0), 0, nw_stop)
# Ensure start <= stop.
nw_start = switch(lt(nw_start, nw_stop), nw_start, nw_stop)
nw_step = abs_step
if step != 1:
reverse = sgn_step
return slice(nw_start, nw_stop, nw_step), reverse
else:
return slice(nw_start, nw_stop, nw_step), 1
def range_len(slc):
"""Length of a `range` object.
Adapted from CPython.
"""
from aesara.tensor import and_, gt, lt, switch
start, stop, step = tuple(
as_index_constant(a) for a in [slc.start, slc.stop, slc.step]
)
return switch(
and_(gt(step, 0), lt(start, stop)),
1 + (stop - 1 - start) // step,
switch(
and_(lt(step, 0), gt(start, stop)),
1 + (start - 1 - stop) // (-step),
aes.ScalarConstant(aes.int64, 0),
),
)
def slice_len(slc, n):
"""Compute the length of a slice for an array of a given length.
We're essentially computing `len(range(*slc.indices(n)))`.
"""
# TODO: Do we need to do this or should we expect `slc` to
# already be canonicalized?
canon_slc, _ = get_canonical_form_slice(slc, n)
return range_len(canon_slc)
def is_basic_idx(idx):
"""Determine if an index is of the NumPy basic type.
XXX: This only checks a single index, so an integer is *not* considered a
basic index, because--depending on the other indices its used with--an
integer can indicate advanced indexing.
"""
return isinstance(idx, (slice, type(None))) or isinstance(
getattr(idx, "type", None), (SliceType, NoneTypeT)
)
def basic_shape(shape, indices):
r"""Computes the shape resulting from basic NumPy indexing.
Basic indices are either ``slice``\s or ``None``\s. ``Ellipsis`` are not
supported here; convert them to ``slice``\s first.
Parameters
----------
shape: Tuple[int]
The shape of the array being indexed
indices: Sequence[Or[slice, NoneType]]
A sequence of basic indices used to index an array.
"""
res_shape = ()
for idx, n in zip(indices, shape):
if isinstance(idx, slice):
res_shape += (slice_len(idx, n),)
elif isinstance(getattr(idx, "type", None), SliceType):
if idx.owner:
idx_inputs = idx.owner.inputs
else:
idx_inputs = (None,)
res_shape += (slice_len(slice(*idx_inputs), n),)
elif idx is None:
res_shape += (aes.ScalarConstant(aes.int64, 1),)
elif isinstance(getattr(idx, "type", None), NoneTypeT):
res_shape += (aes.ScalarConstant(aes.int64, 1),)
else:
raise ValueError(f"Invalid index type: {idx}")
return res_shape
def group_indices(indices):
"""Group indices sequentially by whether or not they're basic or advanced.
Returns
-------
Tuple[Boolean, List[Tuple[Integer, Any]]]
The boolean indicates whether or not the group is a set of basic
indices. The list contains the contiguous set of indices paired with their
corresponding dimension number in the array being indexed.
"""
idx_groups = []
dim_num = -1
for basic, grp_indices in groupby(indices, key=is_basic_idx):
enum_grp_indices = []
for idx in grp_indices:
# We "zip" the dimension number to each index, which means we can't
# count indices that add new axes
if (idx is not None) and not isinstance(
getattr(idx, "type", None), NoneTypeT
):
dim_num += 1
enum_grp_indices.append((dim_num, idx))
idx_groups.append((basic, enum_grp_indices))
return idx_groups
def indexed_result_shape(array_shape, indices, indices_are_shapes=False):
"""Compute the symbolic shape resulting from `a[indices]` for `a.shape == array_shape`.
This function uses NumPy's basic and advanced indexing logic. It can also
handle combinations of advanced and basic indices.
Parameters
----------
array_shape: Tuple[Variable]
Shape of the array being indexed.
indices: Sequence[Union[TensorVariable, Tuple[Union[None, slice, Variable]]]]
Either the indices themselves or the shapes of each index--depending
on the value of `indices_are_shapes`.
indices_are_shapes: bool (Optional)
Indicates whether or not the `indices` contains shape tuples instead of
the actual index arrays. If you use this approach, make sure that the
broadcastable dimensions are (scalar) constants with the value `1`, or `1`
exactly.
"""
res_shape = ()
remaining_dims = range(aesara.tensor.basic.get_vector_length(array_shape))
idx_groups = group_indices(indices)
if len(idx_groups) > 2 or len(idx_groups) > 1 and not idx_groups[0][0]:
# Bring adv. index groups to the front and merge each group
idx_groups = sorted(idx_groups, key=lambda x: x[0])
idx_groups = groupby(
chain.from_iterable(d_idx for _, d_idx in idx_groups),
key=lambda x: is_basic_idx(x[1]),
)
for basic, grp_dim_indices in idx_groups:
dim_nums, grp_indices = zip(*grp_dim_indices)
remaining_dims = tuple(dim for dim in remaining_dims if dim not in dim_nums)
if basic:
grp_shapes = tuple(array_shape[dim] for dim in dim_nums)
res_shape += basic_shape(grp_shapes, grp_indices)
else:
from aesara.tensor.extra_ops import broadcast_shape
res_shape += broadcast_shape(
*grp_indices, arrays_are_shapes=indices_are_shapes
)
res_shape += tuple(array_shape[dim] for dim in remaining_dims)
return res_shape
def get_slice_elements(idxs: List, cond: Callable) -> List:
"""Extract slice elements conditional on a given predicate function.
Parameters
----------
idxs : a list of indices or slices.
cond : a callable that returns a bool
Returns
-------
list
idxs, with the slices flattened out into a list.
If cond is true for an entry, does not flatten it.
"""
ret = []
def helper(entry):
if cond(entry):
ret.append(entry)
elif isinstance(entry, slice):
helper(entry.start)
helper(entry.stop)
helper(entry.step)
for idx in idxs:
helper(idx)
return ret
def index_vars_to_types(entry, slice_ok=True):
r"""Change references to `Variable`s into references to `Type`s.
The `Subtensor.idx_list` field is unique to each `Subtensor` instance. It
is not unique to each `Apply` node, so it should not refer to specific
`Variable`s.
TODO WRITEME: This function also accepts an `entry` already being a `Type`;
when would that happen?
"""
if (
isinstance(entry, (np.ndarray, Variable))
and hasattr(entry, "dtype")
and entry.dtype == "bool"
):
raise AdvancedIndexingError("Invalid index type or slice for Subtensor")
if isinstance(entry, Variable) and (
entry.type in invalid_scal_types or entry.type in invalid_tensor_types
):
raise TypeError("Expected an integer")
if isinstance(entry, Variable) and entry.type in scal_types:
return entry.type
elif isinstance(entry, Type) and entry in scal_types:
return entry
if (
isinstance(entry, Variable)
and entry.type in tensor_types
and all(entry.type.broadcastable)
):
return aes.get_scalar_type(entry.type.dtype)
elif isinstance(entry, Type) and entry in tensor_types and all(entry.broadcastable):
return aes.get_scalar_type(entry.dtype)
elif slice_ok and isinstance(entry, slice):
a = entry.start
b = entry.stop
c = entry.step
if a is not None:
slice_a = index_vars_to_types(a, False)
else:
slice_a = None
if b is not None and b != sys.maxsize:
# The special "maxsize" case is probably not needed here,
# as slices containing maxsize are not generated by
# __getslice__ anymore.
slice_b = index_vars_to_types(b, False)
else:
slice_b = None
if c is not None:
slice_c = index_vars_to_types(c, False)
else:
slice_c = None
return slice(slice_a, slice_b, slice_c)
elif isinstance(entry, (int, np.integer)):
raise TypeError()
else:
raise AdvancedIndexingError("Invalid index type or slice for Subtensor")
def get_constant_idx(
idx_list, inputs, allow_partial=False, only_process_constants=False, elemwise=True
):
r"""Return an `idx_list` with its constant inputs replaced by their Python scalar equivalents.
May raise `NotScalarConstantError` if the indices contain non-constant entries.
If `allow_partial` is ``True``, then entries that are not constant will
stay as their input variable rather than raising an exception.
``None`` entries are always left as-is.
Parameters
----------
only_process_constants
If ``True``, we only attempt to obtain the value of an index/slice if
it's directly constant and don't try to dig through `DimShuffle`\s,
fills, `Alloc`\s, and other to figure out its value.
Examples
--------
Example usage where `v` and `a` are appropriately typed Aesara variables :
>>> b = a[v, 1:3]
>>> b.owner.op.idx_list
(ScalarType(int64), slice(ScalarType(int64), ScalarType(int64), None))
>>> get_constant_idx(b.owner.op.idx_list, b.owner.inputs, allow_partial=True)
[v, slice(1, 3, None)]
>>> get_constant_idx(b.owner.op.idx_list, b.owner.inputs)
NotScalarConstantError: v
"""
real_idx = get_idx_list(inputs, idx_list)
# TODO: Combine this with `as_index_literal`
def conv(val):
if val is None:
return None
elif isinstance(val, slice):
return slice(conv(val.start), conv(val.stop), conv(val.step))
else:
try:
return get_scalar_constant_value(
val,
only_process_constants=only_process_constants,
elemwise=elemwise,
)
except NotScalarConstantError:
if allow_partial:
return val
else:
raise
return list(map(conv, real_idx))
def as_nontensor_scalar(a: Variable) -> aes.ScalarVariable:
"""Convert a value to a `ScalarType` variable."""
# Since aes.as_scalar does not know about tensor types (it would
# create a circular import) , this method converts either a
# TensorVariable or a ScalarVariable to a scalar.
if isinstance(a, Variable) and isinstance(a.type, TensorType):
return aesara.tensor.scalar_from_tensor(a)
else:
return aes.as_scalar(a)
class Subtensor(COp):
"""Basic NumPy indexing operator."""
check_input = False
view_map = {0: [0]}
_f16_ok = True
__props__ = ("idx_list",)
def __init__(self, idx_list):
# TODO: Provide the type of `self.idx_list`
self.idx_list = tuple(map(index_vars_to_types, idx_list))
def make_node(self, x, *inputs):
"""
Parameters
----------
x
The tensor to take a subtensor of.
inputs
A list of aesara Scalars.
"""
x = as_tensor_variable(x)
inputs = tuple(as_nontensor_scalar(a) for a in inputs)
idx_list = list(self.idx_list)
if len(idx_list) > x.type.ndim:
raise IndexError("too many indices for array")
input_types = get_slice_elements(
idx_list, lambda entry: isinstance(entry, Type)
)
assert len(inputs) == len(input_types)
for input, expected_type in zip(inputs, input_types):
if not expected_type.is_super(input.type):
raise TypeError(
f"Incompatible types for Subtensor template. Expected {input.type}, got {expected_type}."
)
# infer the broadcasting pattern
padded = get_constant_idx(
self.idx_list, (None,) + inputs, allow_partial=True
) + [slice(None, None, None)] * (x.type.ndim - len(idx_list))
broadcastable = []
for i, (p, bc) in enumerate(zip(padded, x.type.broadcastable)):
if isinstance(p, slice):
if bc:
start = p.start
try:
start = get_scalar_constant_value(start)
except NotScalarConstantError:
pass
if start is None or start == 0:
start = p.start
if start is None:
start = 0
if p.stop is None or (
isinstance(p.stop, (int, np.integer, np.ndarray))
and p.stop > start
):
broadcastable.append(True)
continue
broadcastable.append(False)
return Apply(
self,
(x,) + inputs,
[tensor(dtype=x.type.dtype, shape=broadcastable)],
)
def perform(self, node, inputs, out_):
(out,) = out_
x = inputs[0]
cdata = get_idx_list(inputs, self.idx_list)
if len(cdata) == 1:
cdata = cdata[0]
out[0] = np.asarray(x.__getitem__(cdata))
def infer_shape(self, fgraph, node, shapes):
xshp = shapes[0]
assert len(xshp) == node.inputs[0].ndim
outshp = []
actual_idx_list = list(get_idx_list(node.inputs, self.idx_list))
padded = actual_idx_list + [slice(None, None, None)] * (
len(xshp) - len(self.idx_list)
)
i = 0
for idx, xl in zip(padded, xshp):
if isinstance(idx, slice):
# If it is the default (None, None, None) slice, or a variant,
# the shape will be xl
if (
(idx.start in [None, 0])
and (idx.stop in [None, sys.maxsize])
and (idx.step is None or idx.step == 1)
):
outshp.append(xl)
else:
cnf = get_canonical_form_slice(idx, xl)[0]
if cnf.step == 1:
length = cnf.stop - cnf.start
else:
length = (cnf.stop - cnf.start - 1) // cnf.step + 1
outshp.append(length)
i += 1
else:
# That dimension is dropped
pass
assert i == node.outputs[0].ndim
assert len(outshp) == node.outputs[0].ndim
return [outshp]
def grad(self, inputs, grads):
(gz,) = grads
x = inputs[0]
rest = inputs[1:]
if x.dtype in discrete_dtypes:
first = x.zeros_like().astype(config.floatX)
else:
# For best optimization, we let this as an inc.
# This allow the opt local_IncSubtensor_serialize to apply first.
# We have an optimization that will convert this to a
# set subtensor here at:
# aesara/tensor/opt.py:local_incsubtensor_of_zeros_to_setsubtensor()
first = IncSubtensor(self.idx_list)(x.zeros_like(), gz, *rest)
return [first] + [DisconnectedType()()] * len(rest)
def connection_pattern(self, node):
rval = [[True]]
for ipt in node.inputs[1:]:
rval.append([False])
return rval
def __hash__(self):
msg = []
for entry in self.idx_list:
if isinstance(entry, slice):
msg += [(entry.start, entry.stop, entry.step)]
else:
msg += [entry]
idx_list = tuple(msg)
# backport
# idx_list = tuple((entry.start, entry.stop, entry.step)
# if isinstance(entry, slice)
# else entry
# for entry in self.idx_list)
return hash(idx_list)
@staticmethod
def str_from_slice(entry):
msg = []
for x in [entry.start, entry.stop, entry.step]:
if x is None:
msg.append("")
else:
msg.append(str(x))
return ":".join(msg)
def __str__(self):
indices = []
for entry in self.idx_list:
if isinstance(entry, slice):
indices.append(self.str_from_slice(entry))
else:
indices.append(str(entry))
return f"{self.__class__.__name__}{{{', '.join(indices)}}}"
@staticmethod
def default_helper_c_code_args():
"""
Returns a dictionary of default arguments to helper_c_code.
"""
return {"c_prefix": "PyArray", "strides_mul": 1}
@staticmethod
def helper_c_code(
node,
name,
inputs,
outputs,
sub,
idx_list,
view_ndim,
c_prefix=None,
strides_mul=None,
):
"""
The parameters c_prefix are there to allow reusing this
function on PyArray object.
This fct take as input the x.
"""
default_args = Subtensor.default_helper_c_code_args()
if strides_mul is None:
strides_mul = default_args["strides_mul"]
if c_prefix is None:
c_prefix = default_args["c_prefix"]
#
# two arrays are created in C code:
# is_slice: len == ndim, 0 means int, 1 means slice
# subtensor_spec: len = n_ints + 3 * n_slices
#
fail = sub["fail"]
init_cmds = [] # initialization for subtensor_spec
is_slice = []
# TODO: change that, it might lead to unexpected results,
# see assembla-#767
NONE_CODE = sys.maxsize - 1
pos = [0, 1] # annoying version of global variable for init_entry
def inc_spec_pos(amt):
pos[0] += amt
def inc_input_pos(amt):
pos[1] += amt
def spec_pos():
return pos[0]
def input_pos():
return pos[1]
def init_entry(entry, depth=0):
if isinstance(entry, (np.integer, int)):
init_cmds.append("subtensor_spec[%i] = %i;" % (spec_pos(), entry))
inc_spec_pos(1)
if depth == 0:
is_slice.append(0)
elif isinstance(entry, Type):
init_cmds.append(
"subtensor_spec[%i] = %s;" % (spec_pos(), inputs[input_pos()])
)
inc_spec_pos(1)
inc_input_pos(1)
if depth == 0:
is_slice.append(0)
elif entry is None:
init_cmds.append("subtensor_spec[%i] = %i;" % (spec_pos(), NONE_CODE))
inc_spec_pos(1)
if depth == 0:
is_slice.append(0)
elif depth == 0 and isinstance(entry, slice):
init_entry(entry.start, depth + 1)
init_entry(entry.stop, depth + 1)
init_entry(entry.step, depth + 1)
is_slice.append(1)
else:
assert 0, entry
for entry in idx_list:
init_entry(entry)
# make sure we used all inputs
assert input_pos() == len(inputs), input_pos()
assert len(is_slice) <= node.inputs[0].ndim, node.inputs[0].ndim
len_is_slice = len(is_slice)
len_subtensor_spec = spec_pos()
subensor_spec = f"npy_intp subtensor_spec[{len_subtensor_spec}];"
if len_subtensor_spec == 0:
subensor_spec = "npy_intp * subtensor_spec = NULL;"
if is_slice:
is_slice_init = (
"int is_slice[] = {" + ",".join([str(s) for s in is_slice]) + "};"
)
else:
is_slice_init = "int* is_slice = NULL;"
subtensor_init = "\n".join(init_cmds)
(x,) = inputs[:1]
(z,) = outputs
if view_ndim:
rval = f"""
// Argument of the view
npy_intp xview_dims[{view_ndim}];
npy_intp xview_strides[{view_ndim}];
"""
else:
rval = """
// Argument of the view
npy_intp* xview_dims = NULL;
npy_intp* xview_strides = NULL;
"""
rval += (
"""
// One more argument of the view
npy_intp xview_offset = 0;
// The subtensor is created by iterating over the dimensions
// and updating stride, shape, and data pointers
%(is_slice_init)s
%(subensor_spec)s
%(subtensor_init)s;
int spec_pos = 0; //position in subtensor_spec
int inner_ii = 0; // the current dimension of zview
int outer_ii = 0; // current dimension of z