-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
creation.py
3259 lines (2798 loc) · 112 KB
/
creation.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 math
import re
from typing import TYPE_CHECKING, Any, overload
import numpy as np
import numpy.typing as npt
import paddle
from paddle import _C_ops
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,
convert_float_to_uint16,
)
from ..base.framework import Variable, device_guard
from ..base.param_attr import ParamAttr
from ..framework import (
LayerHelper,
_current_expected_place,
_current_expected_place_,
_get_paddle_place,
convert_np_dtype_to_dtype_,
core,
dygraph_only,
in_dynamic_mode,
in_dynamic_or_pir_mode,
in_pir_mode,
)
if TYPE_CHECKING:
from collections.abc import Sequence
from paddle._typing import (
DTypeLike,
NestedNumbericSequence,
Numberic,
ParamAttrLike,
PlaceLike,
ShapeLike,
TensorLike,
)
__all__ = []
def _complex_to_real_dtype(dtype: DTypeLike) -> DTypeLike:
if dtype == core.VarDesc.VarType.COMPLEX64:
return core.VarDesc.VarType.FP32
elif dtype == core.VarDesc.VarType.COMPLEX128:
return core.VarDesc.VarType.FP64
elif dtype == paddle.pir.core.DataType.COMPLEX64:
return paddle.pir.core.DataType.FLOAT32
elif dtype == paddle.pir.core.DataType.COMPLEX128:
return paddle.pir.core.DataType.FLOAT64
else:
return dtype
def _real_to_complex_dtype(dtype: DTypeLike) -> DTypeLike:
if dtype == core.VarDesc.VarType.FP32:
return core.VarDesc.VarType.COMPLEX64
elif dtype == core.VarDesc.VarType.FP64:
return core.VarDesc.VarType.COMPLEX128
elif dtype == paddle.pir.core.DataType.FLOAT32:
return paddle.pir.core.DataType.COMPLEX64
elif dtype == paddle.pir.core.DataType.FLOAT64:
return paddle.pir.core.DataType.COMPLEX128
else:
return dtype
def create_global_var(
shape: ShapeLike,
value: float,
dtype: DTypeLike,
persistable: bool = False,
force_cpu: bool = False,
name: str | None = None,
) -> paddle.Tensor:
"""
This function creates a new tensor variable with value in the global block(block 0).
Args:
shape (list[int]|tuple[int]): Shape of the variable
value (float): The value of the variable. The new created
variable will be filled with it.
dtype (str): Data type of the variable
persistable (bool, optional): If this variable is persistable.
Default: False
force_cpu (bool, optional): Force this variable to be on CPU.
Default: False
name (str|None, optional): For detailed information, please refer to
:ref:`api_guide_Name` . Usually name is no need to set and None by default.
Returns:
Variable: The created Variable
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.enable_static()
>>> var = paddle.static.create_global_var(shape=[2,3], value=1.0, dtype='float32',
... persistable=True, force_cpu=True, name='new_var')
"""
check_type(shape, 'shape', (list, tuple, np.ndarray), 'create_global_var')
for item in shape:
check_type(
item,
'item of shape',
(
int,
np.uint8,
np.int8,
np.int16,
np.int32,
np.int64,
),
'create_global_var',
)
check_dtype(
dtype,
'dtype',
[
'bool',
'float16',
'float32',
'float64',
'int8',
'int16',
'int32',
'int64',
'uint8',
'uint16',
],
'create_global_var',
)
helper = LayerHelper("global_var", **locals())
var = helper.create_global_variable(
dtype=dtype,
shape=shape,
persistable=persistable,
name=name,
stop_gradient=True,
)
helper.set_variable_initializer(
var,
initializer=paddle.nn.initializer.ConstantInitializer(
value=float(value), force_cpu=force_cpu
),
)
return var
def create_parameter(
shape: ShapeLike,
dtype: DTypeLike,
name: str | None = None,
attr: ParamAttrLike | None = None,
is_bias: bool = False,
default_initializer: paddle.nn.initializer.Initializer | None = None,
) -> paddle.Tensor:
"""
This function creates a parameter. The parameter is a learnable variable, which can have
gradient, and can be optimized.
Note:
This is a very low-level API. This API is useful when you create operator by your self, instead of using layers.
Args:
shape (list of int): Shape of the parameter
dtype (str): Data type of the parameter. It can be set as 'float16', 'float32', 'float64'.
name(str|None, optional): For detailed information, please refer to
:ref:`api_guide_Name` . Usually name is no need to set and None by default.
attr (ParamAttr|None, optional): Attribute object of the specified argument. For detailed information, please refer to
:ref:`api_paddle_ParamAttr` None by default, which means that ParamAttr will be initialized as it is.
is_bias (bool, optional): This can affect which default initializer is chosen
when default_initializer is None. If is_bias,
initializer.Constant(0.0) will be used. Otherwise,
Xavier() will be used.
default_initializer (Initializer|None, optional): Initializer for the parameter
Returns:
The created parameter.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.enable_static()
>>> W = paddle.create_parameter(shape=[784, 200], dtype='float32')
"""
check_type(shape, 'shape', (list, tuple, np.ndarray), 'create_parameter')
for item in shape:
check_type(
item,
'item of shape',
(
int,
np.uint8,
np.int8,
np.int16,
np.int32,
np.int64,
),
'create_parameter',
)
check_dtype(
dtype,
'dtype',
[
'bool',
'float16',
'uint16',
'float32',
'float64',
'int8',
'int16',
'int32',
'int64',
'uint8',
],
'create_parameter',
)
check_type(attr, 'attr', (type(None), ParamAttr), 'create_parameter')
check_type(
default_initializer,
'default_initializer',
(type(None), paddle.nn.initializer.Initializer),
'create_parameter',
)
helper = LayerHelper("create_parameter", **locals())
if attr is None:
attr = ParamAttr(name=name)
return helper.create_parameter(
attr, shape, convert_dtype(dtype), is_bias, default_initializer
)
def create_tensor(
dtype: DTypeLike, name: str | None = None, persistable: bool = False
) -> paddle.Tensor:
"""
Create a variable, which will hold a Tensor with data type dtype.
Args:
dtype(string|numpy.dtype): the data type of Tensor to be created, the
data type is bool, float16, float32, float64, int8, int16, int32 and int64.
name(string, optional): The default value is None. Normally there is no need for
user to set this property. For more information, please refer to :ref:`api_guide_Name`
persistable(bool): Set the persistable flag of the create tensor.
default value is False.
Returns:
Variable: The tensor to be created according to dtype.
Examples:
.. code-block:: python
>>> import paddle
>>> tensor = paddle.tensor.create_tensor(dtype='float32')
"""
check_dtype(
dtype,
'dtype',
[
'bool',
'float16',
'float32',
'float64',
'int8',
'int32',
'int32',
'int64',
],
'create_tensor',
)
helper = LayerHelper("create_tensor", **locals())
return helper.create_variable(
name=helper.name, dtype=dtype, persistable=persistable
)
def linspace(
start: float | paddle.Tensor,
stop: float | paddle.Tensor,
num: int | paddle.Tensor,
dtype: DTypeLike | None = None,
name: str | None = None,
) -> paddle.Tensor:
r"""
Return fixed number of evenly spaced values within a given interval. Note: no gradient calculation is performed.
Args:
start(int|float|Tensor): The input :attr:`start` is start of range. It is a int, float, \
or a 0-D Tensor with data type int32, int64, float32 or float64.
stop(int|float|Tensor): The input :attr:`stop` is end of range. It is a int, float, \
or a 0-D Tensor with data type int32, int64, float32 or float64.
num(int|Tensor): The input :attr:`num` is given num of the sequence. It is an int, \
or a 0-D Tensor with data type int32.
dtype(str|paddle.dtype|np.dtype|None, optional): The data type of output tensor, it could be
int32, int64, float32 and float64. Default: if None, the data type is float32.
name(str|None, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
Tensor: the output data type will be float32, float64. The 1-D tensor with fixed number of evenly spaced values, \
the data shape of this tensor is :math:`[num]` . If the :attr:`num` is set 1, the output tensor just has \
the value with input :attr:`start`.
Examples:
.. code-block:: python
>>> import paddle
>>> data = paddle.linspace(0, 10, 5, 'float32')
>>> print(data.numpy())
[0. 2.5 5. 7.5 10.]
>>> data = paddle.linspace(0, 10, 1, 'float32')
>>> print(data.numpy())
[0.]
"""
if dtype is None:
dtype = paddle.get_default_dtype()
tensor_num = num
tensor_start = start
tensor_stop = stop
if not isinstance(num, (Variable, paddle.pir.Value)):
check_type(num, 'num', (int), 'linspace')
if not isinstance(dtype, (core.VarDesc.VarType, paddle.pir.core.DataType)):
dtype = convert_np_dtype_to_dtype_(dtype)
if not isinstance(start, (Variable, paddle.pir.Value)):
with device_guard("cpu"):
tensor_start = fill_constant([1], dtype, start, force_cpu=True)
if not isinstance(stop, (Variable, paddle.pir.Value)):
with device_guard("cpu"):
tensor_stop = fill_constant([1], dtype, stop, force_cpu=True)
if not isinstance(num, (Variable, paddle.pir.Value)):
with device_guard("cpu"):
tensor_num = fill_constant([1], 'int32', num, force_cpu=True)
if in_dynamic_mode():
return _C_ops.linspace(
tensor_start,
tensor_stop,
tensor_num,
dtype,
_current_expected_place(),
)
elif in_pir_mode():
helper = LayerHelper("linspace", **locals())
start_dtype = convert_dtype(tensor_start.dtype)
stop_dtype = convert_dtype(tensor_stop.dtype)
out_dtype = convert_dtype(dtype)
if isinstance(start, paddle.pir.Value):
check_dtype(
start.dtype,
'start',
['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
'linspace',
)
else:
check_type(start, 'start', (int, float), 'linspace')
if isinstance(stop, paddle.pir.Value):
check_dtype(
stop.dtype,
'stop',
['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
'linspace',
)
else:
check_type(stop, 'stop', (int, float), 'linspace')
if isinstance(num, paddle.pir.Value):
check_dtype(num.dtype, 'num', ['int32'], 'linspace')
check_dtype(
dtype,
'dtype',
['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
'linspace',
)
if (
(stop_dtype == "float64" or start_dtype == "float64")
and out_dtype in ["float32", "int32"]
) or (
(stop_dtype == "int64" or start_dtype == "int64")
and out_dtype == "int32"
):
raise ValueError(
f"The dtype of start/stop is {start_dtype}/{stop_dtype} but the attr(dtype) of linspace is {dtype}, "
"which may cause data type overflows. Please reset attr(dtype) of linspace."
)
if isinstance(dtype, paddle.base.core.VarDesc.VarType):
dtype = paddle.pir.core.vartype_to_datatype[dtype]
return _C_ops.linspace(
tensor_start,
tensor_stop,
tensor_num,
dtype,
_current_expected_place(),
)
else:
helper = LayerHelper("linspace", **locals())
start_dtype = convert_dtype(tensor_start.dtype)
stop_dtype = convert_dtype(tensor_stop.dtype)
out_dtype = convert_dtype(dtype)
if isinstance(start, Variable):
check_dtype(
start.dtype,
'start',
['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
'linspace',
)
else:
check_type(start, 'start', (int, float), 'linspace')
if isinstance(stop, Variable):
check_dtype(
stop.dtype,
'stop',
['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
'linspace',
)
else:
check_type(stop, 'stop', (int, float), 'linspace')
if isinstance(num, Variable):
check_dtype(num.dtype, 'num', ['int32'], 'linspace')
check_dtype(
dtype,
'dtype',
['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
'linspace',
)
if (
(stop_dtype == "float64" or start_dtype == "float64")
and out_dtype in ["float32", "int32"]
) or (
(stop_dtype == "int64" or start_dtype == "int64")
and out_dtype == "int32"
):
raise ValueError(
f"The dtype of start/stop is {start_dtype}/{stop_dtype} but the attr(dtype) of linspace is {dtype}, "
"which may cause data type overflows. Please reset attr(dtype) of linspace."
)
out = helper.create_variable_for_type_inference(dtype=dtype)
helper.append_op(
type='linspace',
inputs={
'Start': tensor_start,
'Stop': tensor_stop,
'Num': tensor_num,
},
attrs={'dtype': dtype},
outputs={'Out': [out]},
)
if isinstance(num, int):
out.desc.set_shape((num,))
return out
def logspace(
start: float | paddle.Tensor,
stop: float | paddle.Tensor,
num: int | paddle.Tensor,
base: float | paddle.Tensor = 10.0,
dtype: DTypeLike | None = None,
name: str | None = None,
) -> paddle.Tensor:
r"""
Return fixed number of logarithmical-evenly spaced values within the interval \
:math:`[base^{start}, base^{stop}]`.
Notes:
This API does not compute the gradient.
Args:
start(int|float|Tensor): The input :attr:`start` is exponent of first entry in \
the sequence. It is a scalar, or a 0-D Tensor of shape [] with input data \
type int32, int64, float32 or float64.
stop(int|float|Tensor): The input :attr:`stop` is exponent of last entry in the \
sequence. It is a scalar, or a 0-D Tensor of shape [] with input data \
type int32, int64, float32 or float64.
num(int|Tensor): The input :attr:`num` is given number of items in the sequence. \
It is an int scalar, or a 0-D Tensor of shape [] with data type int32.
base(int|float|Tensor): The input :attr:`base` is base of the logarithm function. \
It is a scalar, or a 0-D Tensor of shape [] with input data type int32, int64, \
float32 or float64.
dtype(np.dtype|str, optional): The data type of output tensor, it could be \
int32, int64, float32 or float64. Default: if None, the data type is float32. \
name(str|None, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
Tensor: The output data type will be float32, float64. The 1-D tensor with \
fixed number of logarithmical-evenly spaced values, the data shape of this \
tensor is :math:`[num]`. If the :attr:`num` is set 1, the output tensor \
just has the value with exponential of :attr:`start` with base :attr:`base`.
Examples:
.. code-block:: python
>>> import paddle
>>> data = paddle.logspace(0, 10, 5, 2, 'float32')
>>> print(data.numpy())
[1.0000000e+00 5.6568542e+00 3.2000000e+01 1.8101933e+02 1.0240000e+03]
>>> data = paddle.logspace(0, 10, 1, 2, 'float32')
>>> print(data.numpy())
[1.]
"""
if dtype is None:
dtype = paddle.get_default_dtype()
tensor_num = num
tensor_start = start
tensor_stop = stop
tensor_base = base
if not isinstance(num, (Variable, paddle.pir.Value)):
check_type(num, 'num', (int), 'logspace')
if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
dtype = convert_np_dtype_to_dtype_(dtype)
if not isinstance(start, (Variable, paddle.pir.Value)):
with device_guard("cpu"):
tensor_start = fill_constant([1], dtype, start)
if not isinstance(stop, (Variable, paddle.pir.Value)):
with device_guard("cpu"):
tensor_stop = fill_constant([1], dtype, stop)
if not isinstance(num, (Variable, paddle.pir.Value)):
with device_guard("cpu"):
tensor_num = fill_constant([1], 'int32', num)
if not isinstance(base, (Variable, paddle.pir.Value)):
with device_guard("cpu"):
tensor_base = fill_constant([1], dtype, base)
if in_dynamic_mode():
return _C_ops.logspace(
tensor_start,
tensor_stop,
tensor_num,
tensor_base,
dtype,
_current_expected_place(),
)
elif in_pir_mode():
start_dtype = convert_dtype(tensor_start.dtype)
stop_dtype = convert_dtype(tensor_stop.dtype)
base_dtype = convert_dtype(tensor_base.dtype)
out_dtype = convert_dtype(dtype)
if (
(
stop_dtype == "float64"
or start_dtype == "float64"
or base_dtype == "float64"
)
and out_dtype in ["float32", "int32"]
) or (
(
stop_dtype == "int64"
or start_dtype == "int64"
or base_dtype == "int64"
)
and out_dtype == "int32"
):
raise ValueError(
f"The dtype of start/stop/base is {start_dtype}/{stop_dtype}/{base_dtype} but the attr(dtype) of logspace is {dtype}, "
"which may cause data type overflows. Please reset attr(dtype) of logspace."
)
if isinstance(num, paddle.pir.Value):
check_dtype(num.dtype, 'num', ['int32'], 'logspace')
return _C_ops.logspace(
tensor_start,
tensor_stop,
tensor_num,
tensor_base,
dtype,
_current_expected_place(),
)
else:
helper = LayerHelper("logspace", **locals())
start_dtype = convert_dtype(tensor_start.dtype)
stop_dtype = convert_dtype(tensor_stop.dtype)
base_dtype = convert_dtype(tensor_base.dtype)
out_dtype = convert_dtype(dtype)
if isinstance(start, Variable):
check_dtype(
start.dtype,
'start',
['float32', 'float64', 'int32', 'int64'],
'logspace',
)
else:
check_type(start, 'start', (int, float), 'logspace')
if isinstance(stop, Variable):
check_dtype(
stop.dtype,
'stop',
['float32', 'float64', 'int32', 'int64'],
'logspace',
)
else:
check_type(stop, 'stop', (int, float), 'logspace')
if isinstance(num, Variable):
check_dtype(num.dtype, 'num', ['int32'], 'logspace')
if isinstance(base, Variable):
check_dtype(
base.dtype,
'base',
['float32', 'float64', 'int32', 'int64'],
'logspace',
)
else:
check_type(base, 'base', (int, float), 'logspace')
check_dtype(
dtype, 'dtype', ['int32', 'int64', 'float32', 'float64'], 'logspace'
)
if (
(
stop_dtype == "float64"
or start_dtype == "float64"
or base_dtype == "float64"
)
and out_dtype in ["float32", "int32"]
) or (
(
stop_dtype == "int64"
or start_dtype == "int64"
or base_dtype == "int64"
)
and out_dtype == "int32"
):
raise ValueError(
f"The dtype of start/stop/base is {start_dtype}/{stop_dtype}/{base_dtype} but the attr(dtype) of logspace is {dtype}, "
"which may cause data type overflows. Please reset attr(dtype) of logspace."
)
out = helper.create_variable_for_type_inference(dtype=dtype)
helper.append_op(
type='logspace',
inputs={
'Start': tensor_start,
'Stop': tensor_stop,
'Num': tensor_num,
'Base': tensor_base,
},
attrs={'dtype': dtype},
outputs={'Out': [out]},
)
if isinstance(num, int):
out.desc.set_shape((num,))
return out
def _to_tensor_non_static(
data: TensorLike,
dtype: DTypeLike | None = None,
place: PlaceLike | None = None,
stop_gradient: bool = True,
) -> paddle.Tensor:
def _handle_tensor_dtype(
tensor: paddle.Tensor, dtype: DTypeLike
) -> paddle.Tensor:
if dtype:
if convert_dtype(dtype) != convert_dtype(tensor.dtype):
return tensor.astype(convert_dtype(dtype))
return tensor
def _handle_np_dtype(
ndarray: npt.NDArray[Any], dtype: DTypeLike
) -> npt.NDArray[Any]:
if dtype:
if convert_dtype(dtype) != convert_dtype(ndarray.dtype):
# should not ndarray.astype('uint16') directly, data bits is wrong
if convert_dtype(dtype) in ['uint16']:
return convert_float_to_uint16(ndarray.astype('float32'))
else:
return ndarray.astype(convert_dtype(dtype))
return ndarray
if isinstance(data, np.number): # Special case for numpy scalars
data = np.array(data)
if not isinstance(data, np.ndarray):
if np.isscalar(data) and not isinstance(data, str):
data = np.array(data)
elif isinstance(data, (list, tuple)):
data = np.array(data)
if data.dtype == np.object_:
raise ValueError(
"\n\tFailed to convert input data to a regular ndarray :\n\t - Usually "
"this means the input data contains nested lists with different lengths. "
)
elif isinstance(data, paddle.Tensor):
data = data._copy_to(place, False)
data = _handle_tensor_dtype(data, dtype)
data.stop_gradient = stop_gradient
return data
elif isinstance(data, core.Tensor):
# should't expose it to users, just for internal use.
# convert core.Tensor/core.LoDTensor to Tensor first
# Currently, there is no copy when places are same
data = paddle.Tensor(data, place=place)
data = _handle_tensor_dtype(data, dtype)
data.stop_gradient = stop_gradient
return data
else:
raise TypeError(
f"Can't constructs a 'paddle.Tensor' with data type {type(data)}, data type must be scalar|list|tuple|np.ndarray|paddle.Tensor"
)
if not dtype:
if data.dtype in [
'float16',
'float32',
'float64',
'complex64',
'complex128',
]:
default_type = paddle.get_default_dtype()
if np.iscomplexobj(data):
default_type = (
'complex64'
if default_type in ['float16', 'float32']
else 'complex128'
)
data = _handle_np_dtype(data, default_type)
# Windows default type is 'int32', while Linux/Mac is 'int64'. Unify they.
if data.dtype in ['int32']:
data = data.astype("int64")
if dtype:
data = _handle_np_dtype(data, dtype)
if isinstance(data, np.ndarray):
return core.eager.Tensor(
value=data,
place=place,
persistable=False,
zero_copy=False,
name=None,
stop_gradient=stop_gradient,
)
else:
return paddle.Tensor(
value=data,
place=place,
persistable=False,
zero_copy=False,
stop_gradient=stop_gradient,
)
def _to_tensor_static(
data: TensorLike,
dtype: DTypeLike | None = None,
stop_gradient: bool = True,
) -> paddle.Tensor:
if isinstance(data, (Variable, paddle.pir.Value)):
output = data
if dtype is not None and dtype != data.dtype:
output = paddle.cast(output, dtype)
else:
if isinstance(data, np.number): # Special case for numpy scalars
data = np.array(data)
if not isinstance(data, np.ndarray):
if np.isscalar(data) and not isinstance(data, str):
data = np.array(data)
elif isinstance(data, (list, tuple)):
try:
'''
In numpy version >= 1.24.0, case like:
np.array([Variable, 1, 2])
is not supported, it will raise error (numpy returns an numpy array with dtype='object' in version <= 1.23.5)
Thus, process nested structure in except block
'''
array_data = np.array(data)
# for numpy version <= 1.23.5
if array_data.dtype == 'object':
raise RuntimeError("Numpy get dtype `object`.")
data = array_data
except:
to_stack_list = [None] * len(data)
for idx, d in enumerate(data):
to_stack_list[idx] = _to_tensor_static(
d, dtype, stop_gradient
)
data = paddle.stack(to_stack_list)
else:
raise RuntimeError(
f"Do not support transform type `{type(data)}` to tensor"
)
# fix numpy default dtype
if data.dtype in ['float16', 'float32', 'float64']:
data = data.astype(paddle.get_default_dtype())
# Windows default type is 'int32', while Linux/Mac is 'int64'. Unify they.
elif data.dtype in ['int32']:
data = data.astype("int64")
if dtype:
target_dtype = dtype
elif hasattr(data, 'dtype') and data.dtype != 'object':
target_dtype = data.dtype
else:
target_dtype = paddle.get_default_dtype()
target_dtype = convert_dtype(target_dtype)
if data.dtype == "int16":
data = data.astype("int32")
output = assign(data)
if convert_dtype(output.dtype) != target_dtype:
output = paddle.cast(output, target_dtype)
output.stop_gradient = stop_gradient
return output
def to_tensor(
data: TensorLike | NestedNumbericSequence,
dtype: DTypeLike | None = None,
place: PlaceLike | None = None,
stop_gradient: bool = True,
) -> paddle.Tensor:
r"""
Constructs a ``paddle.Tensor`` from ``data`` ,
which can be scalar, tuple, list, numpy\.ndarray, paddle\.Tensor.
If the ``data`` is already a Tensor, copy will be performed and return a new tensor.
If you only want to change stop_gradient property, please call ``Tensor.stop_gradient = stop_gradient`` directly.
.. code-block:: text
We use the dtype conversion rules following this:
Keep dtype
np.number ───────────► paddle.Tensor
(0-D Tensor)
default_dtype
Python Number ───────────────► paddle.Tensor
(0-D Tensor)
Keep dtype
np.ndarray ───────────► paddle.Tensor
Args:
data(scalar|tuple|list|ndarray|Tensor): Initial data for the tensor.
Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor.
dtype(str|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' ,
'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8',
'complex64' , 'complex128'. Default: None, infers dtype from ``data``
except for python float number which gets dtype from ``get_default_type`` .
place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str, optional): The place to allocate Tensor. Can be
CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is
string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs.
stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True.
Returns:
Tensor: A Tensor constructed from ``data`` .
Examples:
.. code-block:: python
>>> import paddle
>>> type(paddle.to_tensor(1))
<class 'paddle.Tensor'>
>>> paddle.to_tensor(1)
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
1)
>>> x = paddle.to_tensor(1, stop_gradient=False)
>>> print(x)
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=False,
1)
>>> paddle.to_tensor(x) # A new tensor will be created with default stop_gradient=True
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
1)
>>> paddle.to_tensor([[0.1, 0.2], [0.3, 0.4]], place=paddle.CPUPlace(), stop_gradient=False)
Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
[[0.10000000, 0.20000000],
[0.30000001, 0.40000001]])
>>> type(paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64'))
<class 'paddle.Tensor'>
>>> paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64')
Tensor(shape=[2, 2], dtype=complex64, place=Place(cpu), stop_gradient=True,
[[(1+1j), (2+0j)],
[(3+2j), (4+0j)]])
"""
place = _get_paddle_place(place)
if place is None:
place = _current_expected_place_()
if in_dynamic_mode():
return _to_tensor_non_static(data, dtype, place, stop_gradient)
# call assign for static graph
else:
re_exp = re.compile(r'[(](.+?)[)]', re.DOTALL)
place_str = re.findall(re_exp, str(place))[0]
with paddle.static.device_guard(place_str):
return _to_tensor_static(data, dtype, stop_gradient)
def full_like(
x: paddle.Tensor,
fill_value: bool | float,
dtype: DTypeLike | None = None,
name: str | None = None,
) -> paddle.Tensor:
"""
This function creates a tensor filled with ``fill_value`` which has identical shape of ``x`` and ``dtype``.
If the ``dtype`` is None, the data type of Tensor is same with ``x``.
Args:
x(Tensor): The input tensor which specifies shape and data type. The data type can be bool, float16, float32, float64, int32, int64.
fill_value(bool|float|int): The value to fill the tensor with. Note: this value shouldn't exceed the range of the output data type.
dtype(np.dtype|str, optional): The data type of output. The data type can be one
of bool, float16, float32, float64, int32, int64. The default value is None, which means the output
data type is the same as input.
name(str|None, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
Tensor: Tensor which is created according to ``x``, ``fill_value`` and ``dtype``.
Examples:
.. code-block:: python
>>> import paddle
>>> input = paddle.full(shape=[2, 3], fill_value=0.0, dtype='float32', name='input')
>>> output = paddle.full_like(input, 2.0)
>>> print(output.numpy())
[[2. 2. 2.]
[2. 2. 2.]]
"""
if dtype is None:
dtype = x.dtype
else:
if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
dtype = convert_np_dtype_to_dtype_(dtype)
if in_dynamic_mode():
return _C_ops.full_like(x, fill_value, dtype, x.place)
elif in_pir_mode():
return _C_ops.full_like(x, fill_value, dtype, core.Place())
else:
helper = LayerHelper("full_like", **locals())
check_variable_and_dtype(
x,
'x',
[
'bool',
'float16',
'float32',
'float64',
'int16',
'int32',
'int64',