-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathmanipulation.py
7714 lines (6521 loc) · 279 KB
/
manipulation.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
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import functools
import math
from typing import TYPE_CHECKING, Any, Literal
import numpy as np
from typing_extensions import overload
import paddle
from paddle import _C_ops
from paddle.tensor import fill_constant
from paddle.utils.inplace_utils import inplace_apis_in_dygraph_only
from ..base.data_feeder import (
check_dtype,
check_type,
check_variable_and_dtype,
convert_dtype,
)
from ..base.framework import Variable, default_main_program
from ..framework import (
LayerHelper,
convert_np_dtype_to_dtype_,
core,
dygraph_only,
in_dynamic_mode,
in_dynamic_or_pir_mode,
in_pir_mode,
)
from .creation import _complex_to_real_dtype, _real_to_complex_dtype, zeros
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from paddle import Tensor
from paddle._typing import (
DTypeLike,
NestedList,
NestedSequence,
Numeric,
ShapeLike,
TensorOrTensors,
)
__all__ = []
def tensor_array_to_tensor(
input: Tensor | list[Tensor],
axis: int = 1,
use_stack: bool = False,
name: str | None = None,
) -> tuple[Tensor, Tensor]:
r"""
This function concatenates or stacks all tensors in the input DenseTensorArray
along the axis mentioned and returns that as the output.
For Example:
.. code-block:: text
Case 1:
Given:
input.data = {[[0.6, 0.1, 0.3],
[0.5, 0.3, 0.2]],
[[1.3],
[1.8]],
[[2.3, 2.1],
[2.5, 2.4]]}
axis = 1, use_stack = False
Then:
output.data = [[0.6, 0.1, 0.3, 1.3, 2.3, 2.1],
[0.5, 0.3, 0.2, 1.8, 2.5, 2.4]]
output_index.data = [3, 1, 2]
Case 2:
Given:
input.data = {[[0.6, 0.1],
[0.5, 0.3]],
[[0.3, 1.3],
[0.2, 1.8]],
[[2.3, 2.1],
[2.5, 2.4]]}
axis = 1, use_stack = True
Then:
output.data = [[[0.6, 0.1]
[0.3, 1.3]
[2.3, 2.1],
[[0.5, 0.3]
[0.2, 1.8]
[2.5, 2.4]]]
output_index.data = [2, 2, 2]
Args:
input(Tensor|list[Tensor]): A TensorArray variable.
axis(int, optional): The axis along which the tensors in attr::`input` will be
concatenated or stacked.
use_stack(bool, optional): Act as concat_op or stack_op. For stack mode, all
tensors in the tensor array must have the same shape.
name(str|None, optional): A name for this layer(optional). If set None, the layer
will be named automatically.
Returns:
Tensor: The concatenated or stacked tensor variable.
Tensor: A 1-D tensor variable with int32 data type. The data in this \
tensor contains all input including tensors' sizes along the axis.
Examples:
.. code-block:: python
>>> import numpy
>>> import paddle
>>> x0 = paddle.assign(numpy.random.rand(2, 2).astype("float32"))
>>> x1 = paddle.assign(numpy.random.rand(2, 2).astype("float32"))
>>> i = paddle.full(shape=[1], dtype="int64", fill_value=0)
>>> array = paddle.tensor.array.create_array(dtype='float32')
>>> paddle.tensor.array.array_write(x0, i, array)
>>> paddle.tensor.array.array_write(x1, i + 1, array)
>>> output, output_index = paddle.tensor.manipulation.tensor_array_to_tensor(input=array)
"""
if in_dynamic_mode():
assert isinstance(
input, list
), "The 'input' in tensor_array_to_tensor must be list"
from paddle import concat, stack
op = stack if use_stack else concat
res = op(input, axis=axis)
sizes = paddle.to_tensor(np.array([int(x.shape[axis]) for x in input]))
return res, sizes
elif in_pir_mode():
check_type(
input,
'input',
(list, paddle.pir.Value),
'tensor_array_to_tensor',
)
if isinstance(input, list):
for i, input_x in enumerate(input):
check_type(
input_x,
'input[' + str(i) + ']',
paddle.pir.Value,
'tensor_array_to_tensor',
)
if not input_x.is_dense_tensor_array_type():
raise TypeError("input should be tensor array variable")
else:
if not input.is_dense_tensor_array_type():
raise TypeError("input should be tensor array variable")
return paddle._pir_ops.array_to_tensor(input, axis, use_stack)
else:
check_type(input, 'input', (list, Variable), 'tensor_array_to_tensor')
if isinstance(input, list):
for i, input_x in enumerate(input):
check_type(
input_x,
'input[' + str(i) + ']',
Variable,
'tensor_array_to_tensor',
)
helper = LayerHelper('tensor_array_to_tensor', **locals())
out = helper.create_variable_for_type_inference(
dtype=helper.input_dtype()
)
out_index = helper.create_variable_for_type_inference(dtype="int32")
helper.append_op(
type='tensor_array_to_tensor',
inputs={'X': input},
outputs={'Out': [out], 'OutIndex': [out_index]},
attrs={'axis': axis, 'use_stack': use_stack},
)
return out, out_index
def cast(x: Tensor, dtype: DTypeLike) -> Tensor:
"""
Take in the Tensor :attr:`x` with :attr:`x.dtype` and cast it
to the output with :attr:`dtype`. It's meaningless if the output dtype
equals the input dtype, but it's fine if you do so.
The following picture shows an example where a tensor of type float64 is cast to a tensor of type uint8.
.. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/images/api_legend/cast.png
:width: 800
:alt: legend of reshape API
:align: center
Args:
x (Tensor): An input N-D Tensor with data type bool, float16,
float32, float64, int32, int64, uint8.
dtype (paddle.dtype|np.dtype|str): Data type of the output:
bool, float16, float32, float64, int8, int32, int64, uint8.
Returns:
Tensor, A Tensor with the same shape as input's.
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor([2, 3, 4], 'float64')
>>> y = paddle.cast(x, 'uint8')
"""
if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
dtype = convert_np_dtype_to_dtype_(dtype)
if in_dynamic_or_pir_mode():
return _C_ops.cast(x, dtype)
else:
check_variable_and_dtype(
x,
'x',
[
'bool',
'float16',
'float32',
'float64',
'int16',
'int32',
'int64',
'uint8',
'uint16',
'float8_e4m3fn',
'float8_e5m2',
],
'cast',
)
check_dtype(
dtype,
'dtype',
[
'bool',
'float16',
'float32',
'float64',
'int8',
'int16',
'int32',
'int64',
'uint8',
'uint16',
'float8_e4m3fn',
'float8_e5m2',
],
'cast',
)
helper = LayerHelper('cast', **locals())
out = helper.create_variable_for_type_inference(
dtype=dtype, stop_gradient=x.stop_gradient
)
helper.append_op(
type='cast',
inputs={'X': [x]},
outputs={'Out': [out]},
attrs={'in_dtype': x.dtype, 'out_dtype': out.dtype},
)
return out
@inplace_apis_in_dygraph_only
def cast_(x: Tensor, dtype: DTypeLike) -> Tensor:
"""
Inplace version of ``cast`` API, the output Tensor will be inplaced with input ``x``.
Please refer to :ref:`api_paddle_cast`.
"""
if in_dynamic_mode():
if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
dtype = convert_np_dtype_to_dtype_(dtype)
return _C_ops.cast_(x, dtype)
def slice(
input: Tensor,
axes: Sequence[int | Tensor],
starts: Sequence[int | Tensor] | Tensor,
ends: Sequence[int | Tensor] | Tensor,
) -> Tensor:
"""
This operator produces a slice of ``input`` along multiple axes. Similar to numpy:
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
Slice uses ``axes``, ``starts`` and ``ends`` attributes to specify the start and
end dimension for each axis in the list of axes and Slice uses this information
to slice the input data tensor. If a negative value is passed to
``starts`` or ``ends`` such as :math:`-i`, it represents the reverse position of the
axis :math:`i-1` (here 0 is the initial position).
If the value passed to ``starts`` or ``ends`` is greater than n
(the number of elements in this dimension), it represents n.
For slicing to the end of a dimension with unknown size, it is recommended
to pass in INT_MAX. The size of ``axes`` must be equal to ``starts`` and ``ends``.
Following examples will explain how slice works:
.. code-block:: text
Case1:
Given:
data = [ [1, 2, 3, 4], [5, 6, 7, 8], ]
axes = [0, 1]
starts = [1, 0]
ends = [2, 3]
Then:
result = [ [5, 6, 7], ]
Case2:
Given:
data = [ [1, 2, 3, 4], [5, 6, 7, 8], ]
axes = [0, 1]
starts = [0, 1]
ends = [-1, 1000] # -1 denotes the reverse 0th position of dimension 0.
Then:
result = [ [2, 3, 4], ] # result = data[0:1, 1:4]
The following figure illustrates the first case -- a 2D tensor of shape [2, 4] is transformed into a 2D tensor of shape [1, 3] through a slicing operation.
.. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/images/api_legend/slice.png
:width: 500
:alt: legend of slice API
:align: center
Args:
input (Tensor): A ``Tensor`` . The data type is ``float16``, ``float32``, ``float64``, ``int32`` or ``int64``.
axes (list|tuple): The data type is ``int32`` . Axes that `starts` and `ends` apply to .
starts (list|tuple|Tensor): The data type is ``int32`` . If ``starts`` is a list or tuple, each element of
it should be integer or 0-D int Tensor with shape []. If ``starts`` is an Tensor, it should be an 1-D Tensor.
It represents starting indices of corresponding axis in ``axes``.
ends (list|tuple|Tensor): The data type is ``int32`` . If ``ends`` is a list or tuple, each element of
it should be integer or 0-D int Tensor with shape []. If ``ends`` is an Tensor, it should be an 1-D Tensor .
It represents ending indices of corresponding axis in ``axes``.
Returns:
Tensor, A ``Tensor``. The data type is same as ``input``.
Examples:
.. code-block:: python
>>> import paddle
>>> input = paddle.rand(shape=[4, 5, 6], dtype='float32')
>>> # example 1:
>>> # attr starts is a list which doesn't contain tensor.
>>> axes = [0, 1, 2]
>>> starts = [-3, 0, 2]
>>> ends = [3, 2, 4]
>>> sliced_1 = paddle.slice(input, axes=axes, starts=starts, ends=ends)
>>> # sliced_1 is input[1:3, 0:2, 2:4].
>>> # example 2:
>>> # attr starts is a list which contain tensor.
>>> minus_3 = paddle.full([1], -3, "int32")
>>> sliced_2 = paddle.slice(input, axes=axes, starts=[minus_3, 0, 2], ends=ends)
>>> # sliced_2 is input[1:3, 0:2, 2:4].
"""
if isinstance(axes, (list, tuple)):
axes = list(axes)
if len(axes) == 0:
raise ValueError("Input axes should not be an empty list/tuple.")
for i in range(len(axes)):
if axes[i] < 0:
axes[i] = max(0, axes[i] + len(input.shape))
else:
axes[i] = min(len(input.shape) - 1, axes[i])
else:
raise ValueError(
f"Input axes must be a python list or tuple, but received {type(axes)}"
)
if in_dynamic_mode():
attrs = ()
starts_tensor = None
ends_tensor = None
infer_flags = [1 for i in range(len(axes))]
if isinstance(starts, (list, tuple)):
starts = [
item.item(0) if isinstance(item, core.eager.Tensor) else item
for item in starts
]
elif isinstance(starts, core.eager.Tensor):
tensor_t = starts.numpy(False)
starts = list(tensor_t)
infer_flags = [-1 for i in range(len(axes))]
if isinstance(ends, (list, tuple)):
ends = [
item.item(0) if isinstance(item, core.eager.Tensor) else item
for item in ends
]
elif isinstance(ends, core.eager.Tensor):
tensor_t = ends.numpy(False)
ends = list(tensor_t)
infer_flags = [-1 for i in range(len(axes))]
return _C_ops.slice(input, axes, starts, ends, infer_flags, [])
elif in_pir_mode():
if not isinstance(starts, (list, tuple, paddle.pir.Value)):
raise ValueError(
"Input starts must be an Value, python list or tuple."
)
if not isinstance(ends, (list, tuple, paddle.pir.Value)):
raise ValueError(
"Input ends must be an Value, python list or tuple."
)
infer_flags = [1 for i in range(len(axes))]
# starts
if isinstance(starts, paddle.pir.Value):
starts.stop_gradient = True
infer_flags = [-1 for i in range(len(axes))]
elif isinstance(starts, (list, tuple)):
if paddle.utils._contain_var(starts):
for i, dim in enumerate(starts):
if isinstance(dim, paddle.pir.Value):
infer_flags[i] = -1
starts = paddle.utils.get_int_tensor_list(starts)
# ends
if isinstance(ends, paddle.pir.Value):
ends.stop_gradient = True
infer_flags = [-1 for i in range(len(axes))]
elif isinstance(ends, (list, tuple)):
if paddle.utils._contain_var(ends):
for i, dim in enumerate(ends):
if isinstance(dim, paddle.pir.Value):
infer_flags[i] = -1
ends = paddle.utils.get_int_tensor_list(ends)
return _C_ops.slice(input, axes, starts, ends, infer_flags, [])
else:
if not isinstance(starts, (list, tuple, Variable)):
raise ValueError(
"Input starts must be an Variable, python list or tuple."
)
if not isinstance(ends, (list, tuple, Variable)):
raise ValueError(
"Input ends must be an Variable, python list or tuple."
)
helper = LayerHelper('slice', **locals())
inputs = {'Input': input}
attrs = {'axes': axes}
infer_flags = [1 for i in range(len(axes))]
# starts
if isinstance(starts, Variable):
starts.stop_gradient = True
inputs['StartsTensor'] = starts
infer_flags = [-1 for i in range(len(axes))]
elif isinstance(starts, (list, tuple)):
attrs['starts'] = []
if paddle.utils._contain_var(starts):
inputs['StartsTensorList'] = (
paddle.utils._convert_to_tensor_list(starts)
)
for i, dim in enumerate(starts):
if isinstance(dim, Variable):
attrs['starts'].append(-1)
infer_flags[i] = -1
else:
attrs['starts'].append(dim)
else:
attrs['starts'] = starts
# ends
if isinstance(ends, Variable):
ends.stop_gradient = True
inputs['EndsTensor'] = ends
infer_flags = [-1 for i in range(len(axes))]
elif isinstance(ends, (list, tuple)):
attrs['ends'] = []
if paddle.utils._contain_var(ends):
inputs['EndsTensorList'] = paddle.utils._convert_to_tensor_list(
ends
)
for i, dim in enumerate(ends):
if isinstance(dim, Variable):
attrs['ends'].append(-1)
infer_flags[i] = -1
else:
attrs['ends'].append(dim)
else:
attrs['ends'] = ends
# infer_flags
attrs['infer_flags'] = infer_flags
out = helper.create_variable_for_type_inference(
dtype=helper.input_dtype('input')
)
helper.append_op(
type='slice', inputs=inputs, attrs=attrs, outputs={'Out': out}
)
return out
def transpose(
x: Tensor, perm: Sequence[int], name: str | None = None
) -> Tensor:
"""
Permute the data dimensions of `input` according to `perm`.
The `i`-th dimension of the returned tensor will correspond to the
perm[i]-th dimension of `input`.
The image illustrates the second example of the transpose operation.
.. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/images/api_legend/transpose.png
:width: 500
:alt: legend of transpose API
Args:
x (Tensor): The input Tensor. It is a N-D Tensor of data types bool, float32, float64, int32.
perm (list|tuple): Permute the input according to the data of perm.
name (str|None, optional): The name of this layer. It is optional.
Returns:
Tensor, A transposed n-D Tensor, with data type being bool, float32, float64, int32, int64.
For Example:
.. code-block:: text
x = [[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
[[13 14 15 16] [17 18 19 20] [21 22 23 24]]]
shape(x) = [2,3,4]
# Example 1
perm0 = [1,0,2]
y_perm0 = [[[ 1 2 3 4] [13 14 15 16]]
[[ 5 6 7 8] [17 18 19 20]]
[[ 9 10 11 12] [21 22 23 24]]]
shape(y_perm0) = [3,2,4]
# Example 2
perm1 = [2,1,0]
y_perm1 = [[[ 1 13] [ 5 17] [ 9 21]]
[[ 2 14] [ 6 18] [10 22]]
[[ 3 15] [ 7 19] [11 23]]
[[ 4 16] [ 8 20] [12 24]]]
shape(y_perm1) = [4,3,2]
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.randn([2, 3, 4])
>>> x_transposed = paddle.transpose(x, perm=[1, 0, 2])
>>> print(x_transposed.shape)
[3, 2, 4]
"""
if in_dynamic_or_pir_mode():
return _C_ops.transpose(x, perm)
else:
check_variable_and_dtype(
x,
'x',
[
'bool',
'float16',
'float32',
'float64',
'int32',
'int64',
'uint16',
'complex64',
'complex128',
],
'transpose',
)
check_type(perm, 'perm', (list, tuple), 'transpose')
if isinstance(perm, tuple):
perm = list(perm)
if len(perm) != len(x.shape):
raise ValueError(
"Input(perm) is the permutation of dimensions of Input(x), "
"its length should be equal to dimensions of Input(x), "
f"but received dimension of Input(x) is {len(x.shape)}, "
f"the length of Input(perm) is {len(perm)}."
)
for idx, dim in enumerate(perm):
if dim >= len(x.shape):
raise ValueError(
"Each element in Input(perm) should be less than Input(x)'s dimension, "
f"but {idx}-th element in Input(perm) is {perm[idx]} which exceeds Input(x)'s "
f"dimension {len(x.shape)}."
)
helper = LayerHelper('transpose', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
x_shape = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='transpose2',
inputs={'X': [x]},
outputs={'Out': [out], 'XShape': [x_shape]},
attrs={'axis': perm},
)
return out
def unstack(x: Tensor, axis: int = 0, num: int | None = None) -> Tensor:
"""
This layer unstacks input Tensor :code:`x` into several Tensors along :code:`axis`.
If :code:`axis` < 0, it would be replaced with :code:`axis+rank(x)`.
If :code:`num` is None, it would be inferred from :code:`x.shape[axis]`,
and if :code:`x.shape[axis]` <= 0 or is unknown, :code:`ValueError` is
raised.
Args:
x (Tensor): Input Tensor. It is a N-D Tensors of data types float32, float64, int32, int64, complex64, complex128.
axis (int, optional): The axis along which the input is unstacked.
num (int|None, optional): The number of output variables.
Returns:
list(Tensor), The unstacked Tensors list. The list elements are N-D Tensors of data types float32, float64, int32, int64, complex64, complex128.
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.ones(name='x', shape=[2, 3, 5], dtype='float32') # create a tensor with shape=[2, 3, 5]
>>> y = paddle.unstack(x, axis=1) # unstack with second axis, which results 3 tensors with shape=[2, 5]
"""
if not (-x.ndim <= axis < x.ndim):
raise ValueError(f'`axis` must be in the range [-{x.ndim}, {x.ndim})')
if num is not None and (num < 0 or num > x.shape[axis]):
raise ValueError(f'`num` must be in the range [0, {x.shape[axis]})')
if in_dynamic_or_pir_mode():
if num is None:
num = x.shape[axis]
if num == 0:
return []
return _C_ops.unstack(x, axis, num)
else:
helper = LayerHelper('unstack', **locals())
if num is None:
if axis is None or x.shape[axis] <= 0:
raise ValueError('unknown unstack number')
else:
num = x.shape[axis]
outs = []
for _ in range(num):
outs.append(helper.create_variable_for_type_inference(x.dtype))
helper.append_op(
type='unstack',
inputs={'X': [x]},
outputs={'Y': outs},
attrs={'axis': axis, 'num': num},
)
return outs
def shard_index(
input: Tensor,
index_num: int,
nshards: int,
shard_id: int,
ignore_value: int = -1,
) -> Tensor:
"""
Reset the values of `input` according to the shard it belongs to.
Every value in `input` must be a non-negative integer, and
the parameter `index_num` represents the integer above the maximum
value of `input`. Thus, all values in `input` must be in the range
[0, index_num) and each value can be regarded as the offset to the beginning
of the range. The range is further split into multiple shards. Specifically,
we first compute the `shard_size` according to the following formula,
which represents the number of integers each shard can hold. So for the
i'th shard, it can hold values in the range [i*shard_size, (i+1)*shard_size).
::
shard_size = (index_num + nshards - 1) // nshards
For each value `v` in `input`, we reset it to a new value according to the
following formula:
::
v = v - shard_id * shard_size if shard_id * shard_size <= v < (shard_id+1) * shard_size else ignore_value
That is, the value `v` is set to the new offset within the range represented by the shard `shard_id`
if it in the range. Otherwise, we reset it to be `ignore_value`.
As shown below, a ``[2, 1]`` 2D tensor is updated with the ``shard_index`` operation. Given ``index_num = 20``, ``nshards = 2``, and ``shard_id = 0``, the shard size is ``shard_size = (20 + 2 - 1) // 2 = 10``.
For each label element: if its value is in [0, 10), it's adjusted to its offset; e.g., 1 becomes 1 - 0 * 10 = 1. Otherwise, it's set to the default ignore_value of -1, like 16 becoming -1.
.. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/images/api_legend/shard_index.png
:width: 500
:alt: Illustration of Case 2
:align: center
Args:
input (Tensor): Input tensor with data type int64 or int32. It's last dimension must be 1.
index_num (int): An integer represents the integer above the maximum value of `input`.
nshards (int): The number of shards.
shard_id (int): The index of the current shard.
ignore_value (int, optional): An integer value out of sharded index range. The default value is -1.
Returns:
Tensor.
Examples:
.. code-block:: python
>>> import paddle
>>> label = paddle.to_tensor([[16], [1]], "int64")
>>> shard_label = paddle.shard_index(input=label,
... index_num=20,
... nshards=2,
... shard_id=0)
>>> print(shard_label.numpy())
[[-1]
[ 1]]
"""
if in_dynamic_or_pir_mode():
return _C_ops.shard_index(
input, index_num, nshards, shard_id, ignore_value
)
check_variable_and_dtype(input, 'input', ['int64', 'int32'], 'shard_index')
op_type = 'shard_index'
helper = LayerHelper(op_type, **locals())
if shard_id < 0 or shard_id >= nshards:
raise ValueError(
f'The shard_id({shard_id}) should be in [0, {nshards})'
)
out = helper.create_variable_for_type_inference(dtype=input.dtype)
helper.append_op(
type=op_type,
inputs={'X': [input]},
outputs={'Out': out},
attrs={
'index_num': index_num,
'nshards': nshards,
'shard_id': shard_id,
'ignore_value': ignore_value,
},
stop_gradient=True,
)
return out
def crop(
x: Tensor,
shape: ShapeLike | None = None,
offsets: Sequence[int] | Tensor | None = None,
name: str | None = None,
) -> Tensor:
"""
Crop input into output, as specified by offsets and shape.
.. code-block:: text
* Case 1 (input is a 2-D Tensor):
Input:
X.shape = [3, 5]
X.data = [[0, 1, 2, 0, 0],
[0, 3, 4, 0, 0],
[0, 0, 0, 0, 0]]
Parameters:
shape = [2, 2]
offsets = [0, 1]
Output:
Out.shape = [2, 2]
Out.data = [[1, 2],
[3, 4]]
* Case 2 (input is a 3-D Tensor):
Input:
X.shape = [2, 3, 4]
X.data = [[[0, 1, 2, 3],
[0, 5, 6, 7],
[0, 0, 0, 0]],
[[0, 3, 4, 5],
[0, 6, 7, 8],
[0, 0, 0, 0]]]
Parameters:
shape = [2, 2, -1]
offsets = [0, 0, 1]
Output:
Out.shape = [2, 2, 3]
Out.data = [[[1, 2, 3],
[5, 6, 7]],
[[3, 4, 5],
[6, 7, 8]]]
The image below demonstrates the Case 2 that a 3D tensor with shape [2,3,4] is cropped into a 3D tensor with shape [2,2,3]
.. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/images/api_legend/crop.png
:width: 500
:alt: Illustration of Case 2
:align: center
Parameters:
x (Tensor): 1-D to 6-D Tensor, the data type is float32, float64, int32 or int64.
shape (list|tuple|Tensor, optional): The output shape is specified
by `shape`. Its data type is int32. If a list/tuple, it's length must be
the same as the dimension size of `x`. If a Tensor, it should be a 1-D Tensor.
When it is a list, each element can be an integer or a Tensor of shape: [1].
If Variable contained, it is suitable for the case that the shape may
be changed each iteration.
offsets (list|tuple|Tensor, optional): Specifies the cropping
offsets at each dimension. Its data type is int32. If a list/tuple, it's length
must be the same as the dimension size of `x`. If a Tensor, it should be a 1-D
Tensor. When it is a list, each element can be an integer or a Tensor of shape: [1].
If Variable contained, it is suitable for the case that the offsets may be changed
each iteration. Default: None, the offsets are 0 at each dimension.
name (str|None, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor, The cropped Tensor has same data type with `x`.
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> # x.shape = [3, 3]
>>> # x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> # shape can be a 1-D Tensor or list or tuple.
>>> shape = paddle.to_tensor([2, 2], dtype='int32')
>>> # shape = [2, 2]
>>> # shape = (2, 2)
>>> out = paddle.crop(x, shape)
>>> # out.shape = [2, 2]
>>> # out = [[1,2], [4,5]]
>>> # offsets can be a 1-D Tensor or list or tuple.
>>> offsets = paddle.to_tensor([0, 1], dtype='int32')
>>> # offsets = [1, 0]
>>> # offsets = (1, 1)
>>> out = paddle.crop(x, shape, offsets)
>>> # out.shape = [2, 2]
>>> # if offsets = [0, 0], out = [[1,2], [4,5]]
>>> # if offsets = [0, 1], out = [[2,3], [5,6]]
>>> # if offsets = [1, 0], out = [[4,5], [7,8]]
>>> # if offsets = [1, 1], out = [[5,6], [8,9]]
"""
helper = LayerHelper('crop_tensor', **locals())
check_variable_and_dtype(
x, 'x', ['float32', 'float64', 'int32', 'int64'], 'crop_tensor'
)
check_type(
shape,
'shape',
(list, tuple, Variable, type(None), paddle.pir.Value),
'crop_tensor',
)
check_type(
offsets,
'offsets',
(list, tuple, Variable, type(None), paddle.pir.Value),
'crop_tensor',
)
if offsets is None:
offsets = [0] * len(x.shape)
if shape is None:
shape = x.shape
if in_dynamic_mode():
return _C_ops.crop(x, shape, offsets)
def _attr_shape_check(shape_val):
if not isinstance(shape_val, int):
raise TypeError(
f"Attr(shape)'s dtype of Op(crop_tensor) should be int32, but received: {type(shape_val)}."
)
if shape_val == 0:
raise ValueError(
f"Attr(shape) of Op(crop_tensor) should not be zero, but received: {shape_val}."
)
if shape_val < -1:
raise ValueError(
f"When the element in Attr(shape) of Op(crop_tensor) is negative, only -1 is supported, but received: {shape_val}."
)
def _attr_offsets_check(offset_val):
if not isinstance(offset_val, int):
raise TypeError(
f"Attr(offsets)'s dtype of Op(crop_tensor) should be int32, but received: {type(offset_val)}."
)
if offset_val < 0:
raise ValueError(
f"Attr(offsets) of Op(crop_tensor) should be greater or equal to zero, but received: {offset_val}."
)
if in_pir_mode():
if isinstance(offsets, paddle.pir.Value):
offsets.stop_gradient = True
elif paddle.utils._contain_var(offsets):
new_offsets_tensor = []
for dim in offsets:
if isinstance(dim, paddle.pir.Value):
dim.stop_gradient = True
new_offsets_tensor.append(dim)
else:
_attr_offsets_check(dim)
temp_out = fill_constant([1], 'int32', dim, force_cpu=True)
new_offsets_tensor.append(temp_out)
offsets = new_offsets_tensor
else:
for offset in offsets:
_attr_offsets_check(offset)
if isinstance(shape, paddle.pir.Value):
shape.stop_gradient = True
elif paddle.utils._contain_var(shape):
new_shape_tensor = []
for dim_size in shape:
if isinstance(dim_size, paddle.pir.Value):
dim_size.stop_gradient = True
new_shape_tensor.append(dim_size)
else:
_attr_shape_check(dim_size)
temp_out = fill_constant(
[1], 'int32', dim_size, force_cpu=True
)
new_shape_tensor.append(temp_out)
shape = new_shape_tensor
else:
for dim_size in shape:
_attr_shape_check(dim_size)
return _C_ops.crop(x, shape, offsets)
out = helper.create_variable_for_type_inference(x.dtype)
ipts = {'X': x}
attrs = {}
if isinstance(offsets, Variable):
offsets.stop_gradient = True
ipts['Offsets'] = offsets
attrs['offsets'] = [-1] * len(x.shape)
elif paddle.utils._contain_var(offsets):
new_offsets_tensor = []
offsets_attr = []
for dim in offsets:
if isinstance(dim, Variable):
dim.stop_gradient = True
new_offsets_tensor.append(dim)
offsets_attr.append(-1)
else:
_attr_offsets_check(dim)
temp_out = helper.create_variable_for_type_inference('int32')
fill_constant([1], 'int32', dim, force_cpu=True, out=temp_out)
new_offsets_tensor.append(temp_out)
offsets_attr.append(dim)
ipts['OffsetsTensor'] = new_offsets_tensor
attrs['offsets'] = offsets_attr
else:
for offset in offsets:
_attr_offsets_check(offset)
attrs['offsets'] = offsets
if isinstance(shape, Variable):
shape.stop_gradient = True
ipts['Shape'] = shape
elif paddle.utils._contain_var(shape):
new_shape_tensor = []