forked from PaddlePaddle/Paddle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensor_patch_methods.py
More file actions
1619 lines (1376 loc) · 58 KB
/
tensor_patch_methods.py
File metadata and controls
1619 lines (1376 loc) · 58 KB
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) 2019 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 copy
import hashlib
import inspect
import warnings
from typing import TYPE_CHECKING, Any, Callable
import numpy as np
import numpy.typing as npt
from typing_extensions import overload
import paddle
from paddle import _C_ops, profiler
from paddle.base.data_feeder import (
_PADDLE_DTYPE_2_NUMPY_DTYPE,
convert_uint16_to_float,
)
from paddle.base.libpaddle import Place
from paddle.profiler.utils import in_profiler_mode
from paddle.utils import deprecated
from paddle.utils.dlpack import DLDeviceType
from paddle.utils.download import check_and_create_dir
from .. import core, framework, unique_name
from ..framework import (
EagerParamBase,
Parameter,
Variable,
convert_np_dtype_to_dtype_,
)
from .base import switch_to_static_graph
from .math_op_patch import monkey_patch_math_tensor
if TYPE_CHECKING:
from enum import IntEnum
from paddle import Tensor
from paddle._typing import DTypeLike, PlaceLike, TensorIndex
_grad_scalar = None
class TensorHookRemoveHelper:
"""
A helper class that for removing Tensor gradient's hook.
NOTE(wuweilong):the operation weakref.ref(tensor) will cause some unexpected errors in eager mode.
"""
def __init__(self, tensor: Tensor, hook_id: int) -> None:
self._tensor = tensor
self._hook_id = hook_id
def remove(self) -> bool:
"""
Remove reference Tensor's hook.
Returns:
bool: Return True if removed successfully
"""
tensor = self._tensor
if tensor is not None:
res = tensor._remove_grad_hook(self._hook_id)
if res is True:
return True
else:
warnings.warn(
f"The backward hook (ID: {self._hook_id}) of Tensor `{tensor.name}` you want to remove does not exist or has been removed.",
RuntimeWarning,
)
return False
_already_patch_repr = False
def monkey_patch_tensor():
# TODO(cleanup-legacy-ir): This method is for dy2st in legacy ir only
# and should be removed after legacy ir is removed.
@switch_to_static_graph
def _to_static_var(self, to_parameter=False, **kwargs):
"""
**Notes**:
**This API is ONLY available in Dygraph mode**
Transform a Tensor into static Variable with same attributes. It's a low level interface used
in dy2static and shall not be called directly.
Args:
to_parameter (bool): It takes effect only if the input a Tensor. If set True,
the Tensor will be converted into framework.Parameters. Otherwise, it will
be converted into framework.Variable. Default False.
Examples:
.. code-block:: python
>>> import paddle.base as base
>>> import paddle
>>> import numpy as np
>>> data = np.ones([3, 1024], dtype='float32')
>>> with base.dygraph.guard():
... tensor = paddle.to_tensor(data)
... static_var = tensor._to_static_var()
"""
# Note: getattr(self, attr, None) will call x.grad=x.gradient(), but gradient() only available in dygraph.
# It will fail. So, for property that different between dynamic and static graph, should not getattr(self, attr, None).
attr_not_need_keys = [
'grad',
'T',
'mT',
'place',
'_place_str',
'data',
'grad_',
'strides',
'offset',
'__cuda_array_interface__',
'itemsize',
'is_cuda',
]
param_keys = ['stop_gradient', 'trainable']
if isinstance(self, EagerParamBase):
attr_kwargs = self.__dict__.copy()
for key in param_keys:
attr_kwargs[key] = getattr(self, key)
else:
attr_names = []
for name in dir(self):
if name not in attr_not_need_keys:
if not inspect.ismethod(
getattr(self, name)
) and not name.startswith('_'):
attr_names.append(name)
attr_kwargs = {name: getattr(self, name) for name in attr_names}
attr_keys = ['block', 'shape', 'dtype', 'type', 'name', 'persistable']
for attr in attr_keys:
attr_kwargs[attr] = getattr(self, attr, None)
# If specify block, use it instead of self.block
if 'block' in kwargs:
attr_kwargs['block'] = kwargs['block']
attr_kwargs.update(kwargs)
if to_parameter or isinstance(self, EagerParamBase):
del attr_kwargs['persistable']
# NOTE(Aurelius84): All parameters should be placed into global block.
attr_kwargs['block'] = attr_kwargs['block'].program.global_block()
static_var = Parameter(**attr_kwargs)
else:
static_var = Variable(**attr_kwargs)
if self.placements is not None: # import for shard tensor api
import paddle.distributed as dist
static_var = dist.shard_tensor(
static_var,
self.process_mesh,
self.placements,
stop_gradient=static_var.stop_gradient,
)
return static_var
# TODO(jiabin): move this to cplusplus end if we find some performance issue on it
@framework.dygraph_only
def set_value(
self: Tensor, value: Tensor | npt.NDArray[Any] | dict[str, int] | str
) -> None:
"""
**Notes**:
**This API is ONLY available in Dygraph mode**
Set a new value for this Variable.
Args:
value (Variable|np.ndarray): the new value.
Examples:
.. code-block:: python
>>> import paddle.base as base
>>> import paddle
>>> from paddle.nn import Linear
>>> import numpy as np
>>> data = np.ones([3, 1024], dtype='float32')
>>> with base.dygraph.guard():
... linear = Linear(1024, 4)
... t = paddle.to_tensor(data)
... linear(t) # call with default weight
... custom_weight = np.random.randn(1024, 4).astype("float32")
... linear.weight.set_value(custom_weight) # change existing weight
... out = linear(t) # call with different weight
"""
if id(self) == id(value):
return
assert isinstance(value, (np.ndarray, paddle.Tensor, dict, str)), (
"Variable set_value function, arguments type only support Variable, numpy, Tensor, dict, string."
)
if self.is_dist():
assert isinstance(value, (np.ndarray, paddle.Tensor)), (
"For set_value function of dist tensor, arguments type only support numpy or Tensor."
)
if isinstance(value, (dict, str)):
assert len(self) == len(value), (
f"Variable length not match, Variable [ {self.name} ] need tensor with length {len(self)} but load set tensor with length {len(value)}"
)
if isinstance(value, dict):
self.value().set_vocab(value)
else:
self.value().set_string_list(value)
else:
assert self.shape == list(value.shape), (
f"Variable Shape not match, Variable [ {self.name} ] need tensor with shape {self.shape} but load set tensor with shape {value.shape}"
)
if isinstance(value, paddle.Tensor):
dtype = value.dtype
elif paddle.framework.use_pir_api():
dtype = paddle.pir.core.convert_np_dtype_to_dtype_(value.dtype)
else:
dtype = convert_np_dtype_to_dtype_(value.dtype)
assert self.dtype == dtype, (
f"Variable dtype not match, Variable [ {self.name} ] need tensor with dtype {self.dtype} but load tensor with dtype {dtype}"
)
# NOTE(wuweilong): self could be Tensor, the subsequent behavior are defined in different files
# if self is Tensor, method value() return self that defined in this file, get_tensor() defined in eager_method.cc
# this Interface behavior will be unified in the future.
if self.is_dist():
if isinstance(value, paddle.Tensor) and value.is_dist():
from paddle.distributed.auto_parallel.placement_type import (
check_placements_equal,
)
# TODO: support reshard later
assert (
value.process_mesh == self.value().process_mesh
or check_placements_equal(
value.placements, self.value().placements
)
), (
f"process_mesh:{value.process_mesh} != {self.value().process_mesh} or placements:{value.placements} != {self.value().placements} not match"
)
else:
# calling set method bound for DistTensor
value = paddle.distributed.shard_tensor(
value,
self.value().process_mesh,
self.value().placements,
)
if isinstance(value, paddle.Tensor):
self.value().set_tensor(value)
else:
self.value().get_tensor().set(value.get_tensor())
return
if isinstance(value, paddle.Tensor):
self.value().set_tensor(value)
else:
self.value().get_tensor().set(
value, framework._current_expected_place()
)
@framework.dygraph_only
def backward(
self: Tensor,
grad_tensor: Tensor | None = None,
retain_graph: bool = False,
*,
dump_backward_graph_path: str | None = None,
) -> None:
"""
Run backward of current Graph which starts from current Tensor.
The new gradient will accumulate on previous gradient.
You can clear gradient by ``Tensor.clear_grad()`` .
Args:
grad_tensor(Tensor|None, optional): initial gradient values of the current Tensor. If `grad_tensor` is None,
the initial gradient values of the current Tensor would be Tensor filled with 1.0;
if `grad_tensor` is not None, it must have the same length as the current Tensor.
The default value is None.
retain_graph(bool, optional): If False, the graph used to compute grads will be freed. If you would
like to add more ops to the built graph after calling this method( :code:`backward` ), set the parameter
:code:`retain_graph` to True, then the grads will be retained. Thus, setting it to False is much more memory-efficient.
Defaults to False.
dump_backward_graph_path(str, optional): Specifies the directory path for storing the debug file.
If this parameter is specified, the backward-related graph (in dot format)
and the debugging call stack information will be generated in this directory.
Returns:
None
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor(5., stop_gradient=False)
>>> for i in range(5):
... y = paddle.pow(x, 4.0)
... y.backward()
... print("{}: {}".format(i, x.grad))
0: 500.0
1: 1000.0
2: 1500.0
3: 2000.0
4: 2500.0
>>> x.clear_grad()
>>> print("{}".format(x.grad))
0.0
>>> grad_tensor=paddle.to_tensor(2.)
>>> for i in range(5):
... y = paddle.pow(x, 4.0)
... y.backward(grad_tensor)
... print("{}: {}".format(i, x.grad))
0: 1000.0
1: 2000.0
2: 3000.0
3: 4000.0
4: 5000.0
"""
if framework.in_dygraph_mode():
if in_profiler_mode():
record_event = profiler.RecordEvent(
"Gradient Backward", profiler.TracerEventType.Backward
)
record_event.begin()
if grad_tensor is not None:
assert isinstance(grad_tensor, core.eager.Tensor), (
"The type of grad_tensor must be paddle.Tensor"
)
assert grad_tensor.shape == self.shape, (
f"Tensor shape not match, Tensor of grad_tensor [ {grad_tensor.name} ] with shape {grad_tensor.shape} mismatch Tensor [ {self.name} ] with shape {self.shape}"
)
if grad_tensor is None:
grad_tensor = []
else:
grad_tensor = [grad_tensor]
if _grad_scalar:
# When using amp with Fleet DistributedStrategy, we do loss scaling implicitly.
self = _grad_scalar.scale(self)
check_and_create_dir(dump_backward_graph_path)
core.eager.run_backward(
[self], grad_tensor, retain_graph, dump_backward_graph_path
)
if in_profiler_mode():
record_event.end()
else:
raise ValueError(
"Variable.backward() is only available in DyGraph mode"
)
@framework.dygraph_only
@deprecated(
since="2.1.0",
level=1,
reason="Please use tensor.grad, which returns the tensor value of the gradient.",
)
def gradient(
self: Tensor,
) -> npt.NDArray[Any] | tuple[npt.NDArray[Any], npt.NDArray[Any]] | None:
"""
.. warning::
This API will be deprecated in the future, it is recommended to use
:code:`x.grad` which returns the tensor value of the gradient.
Get the Gradient of Current Tensor.
Returns:
ndarray: Numpy value of the gradient of current Tensor
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor(5., stop_gradient=False)
>>> y = paddle.pow(x, 4.0)
>>> y.backward()
>>> print("grad of x: {}".format(x.gradient()))
grad of x: 500.0
"""
if self.grad is None:
return None
if self.grad.is_selected_rows():
return (np.array(self.grad), np.array(self.grad.rows()))
return np.array(self.grad)
@framework.dygraph_only
def apply_(self: Tensor, func: Callable[[Tensor], Tensor]) -> Tensor:
"""
Inplace apply the python function to the tensor.
Returns:
None
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>> [0.9, 0.9, 0.7],
>>> [0.4, 0.8, 0.2]]).to("cpu", "float64")
>>> f = lambda x: 3*x+2
>>> x.apply_(f)
>>> print(x)
Tensor(shape=[3, 3], dtype=float64, place=Place(cpu), stop_gradient=True,
[[2.90000004, 3.50000000, 2.30000000],
[4.69999993, 4.69999993, 4.09999996],
[3.20000002, 4.40000004, 2.60000001]])
>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>> [0.9, 0.9, 0.7],
>>> [0.4, 0.8, 0.2]]).to("cpu", "float16")
>>> x.apply_(f)
>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>> [0.9, 0.9, 0.7],
>>> [0.4, 0.8, 0.2]]).to("cpu", "bfloat16")
>>> x.apply_(f)
>>> if paddle.is_compiled_with_cuda():
>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>> [0.9, 0.9, 0.7],
>>> [0.4, 0.8, 0.2]]).to("gpu", "float32")
>>> x.apply_(f)
"""
if not self.stop_gradient:
raise RuntimeError(
"Cannot apply function on a tensor that required gradient."
)
return self._apply_(func)
def apply(self, func: Callable[[Tensor], Tensor]) -> Tensor:
"""
Apply the python function to the tensor.
Returns:
None
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>> [0.9, 0.9, 0.7],
>>> [0.4, 0.8, 0.2]]).to("cpu", "float64")
>>> f = lambda x: 3*x+2
>>> y = x.apply(f)
>>> print(y)
Tensor(shape=[3, 3], dtype=float64, place=Place(cpu), stop_gradient=True,
[[2.90000004, 3.50000000, 2.30000000],
[4.69999993, 4.69999993, 4.09999996],
[3.20000002, 4.40000004, 2.60000001]])
>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>> [0.9, 0.9, 0.7],
>>> [0.4, 0.8, 0.2]]).to("cpu", "float16")
>>> y = x.apply(f)
>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>> [0.9, 0.9, 0.7],
>>> [0.4, 0.8, 0.2]]).to("cpu", "bfloat16")
>>> y = x.apply(f)
>>> if paddle.is_compiled_with_cuda():
>>> x = paddle.to_tensor([[0.3, 0.5, 0.1],
>>> [0.9, 0.9, 0.7],
>>> [0.4, 0.8, 0.2]]).to("gpu", "float32")
>>> y = x.apply(f)
"""
if not self.stop_gradient:
raise RuntimeError(
"Cannot apply function on a tensor that required gradient."
)
return self._apply(func)
@framework.dygraph_only
def register_hook(
self: Tensor, hook: Callable[[Tensor], Tensor | None]
) -> TensorHookRemoveHelper:
"""
Registers a backward hook for current Tensor.
The hook will be called every time the gradient Tensor of current Tensor is computed.
The hook should not modify the input gradient Tensor, but it can optionally return
a new gradient Tensor which will be used in place of current Tensor's gradient.
The hook should have the following signature:
hook(grad) -> Tensor or None
Args:
hook(function): A backward hook to be registered for Tensor.grad
Returns:
TensorHookRemoveHelper: A helper object that can be used to remove the registered hook by calling `remove()` method.
Examples:
.. code-block:: python
>>> import paddle
>>> # hook function return None
>>> def print_hook_fn(grad):
... print(grad)
...
>>> # hook function return Tensor
>>> def double_hook_fn(grad):
... grad = grad * 2
... return grad
...
>>> x = paddle.to_tensor([0., 1., 2., 3.], stop_gradient=False)
>>> y = paddle.to_tensor([4., 5., 6., 7.], stop_gradient=False)
>>> z = paddle.to_tensor([1., 2., 3., 4.])
>>> # one Tensor can register multiple hooks
>>> h = x.register_hook(print_hook_fn)
>>> x.register_hook(double_hook_fn)
>>> w = x + y
>>> # register hook by lambda function
>>> w.register_hook(lambda grad: grad * 2)
>>> o = z.matmul(w)
>>> o.backward()
>>> # print_hook_fn print content in backward
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=False,
[2., 4., 6., 8.])
>>> print("w.grad:", w.grad)
w.grad: None
>>> print("x.grad:", x.grad)
x.grad: Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=False,
[4. , 8. , 12., 16.])
>>> print("y.grad:", y.grad)
y.grad: Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=False,
[2., 4., 6., 8.])
>>> # remove hook
>>> h.remove()
"""
if self.stop_gradient is True:
raise RuntimeError(
"Cannot register hook on a tensor that stop gradient."
)
hook_id = self._register_grad_hook(hook)
helper = TensorHookRemoveHelper(self, hook_id)
return helper
@framework.dygraph_only
def _to(
self: Tensor,
device: PlaceLike | None = None,
dtype: DTypeLike | None = None,
blocking: bool | None = None,
copy_tensor: bool | None = None,
) -> Tensor:
if device is None and dtype is None and blocking is None:
return self
def is_cuda_place(place: PlaceLike):
return isinstance(place, core.CUDAPlace) or (
isinstance(place, Place) and place.is_gpu_place()
)
def get_device_id(place: PlaceLike):
if isinstance(
place,
(
core.CUDAPlace,
core.XPUPlace,
core.IPUPlace,
core.CustomPlace,
),
):
return place.get_device_id()
elif isinstance(place, Place):
if place.is_gpu_place():
return place.gpu_device_id()
elif place.is_xpu_place():
return place.xpu_device_id()
elif place.is_ipu_place():
return place.ipu_device_id()
elif place.is_custom_place():
return place.custom_device_id()
else:
raise ValueError(
f"Invalid place: {place}, only support getting device id from CUDAPlace/XPUPlace/IPUPlace/CustomPlace"
)
if device is not None:
if isinstance(device, str):
device = paddle.device._convert_to_place(device)
elif isinstance(
device,
(
core.Place,
core.CPUPlace,
core.CUDAPlace,
core.CUDAPinnedPlace,
core.XPUPlace,
core.CustomPlace,
),
):
pass
else:
raise ValueError(
"device value error, must be str, paddle.CPUPlace(), paddle.CUDAPlace(), paddle.CUDAPinnedPlace(), paddle.XPUPlace() or paddle.CustomPlace(), but the type of device is "
+ type(device).__name__
)
if blocking is None:
blocking = True
else:
assert isinstance(blocking, bool), (
"blocking value error, must be the True, False or None"
)
def transform(t, device, dtype, blocking, copy_tensor):
if device is None:
device = t.place
if dtype is None:
dtype = t.dtype
# 1. gpu place need to determine whether the memory is sufficient for allocation.
if t.place.is_gpu_place() and (
# NOTE: Only copy memory when place or device id is different,
# otherwise, it may frequently call GpuMemGetInfo in
# core.gpu_memory_available, leading to abnormal overhead.
not is_cuda_place(device)
or t.place.gpu_device_id() != get_device_id(device)
):
proto_dtype = framework.convert_to_proto_type(dtype)
size_dtype = core.size_of_dtype(proto_dtype)
# Note(weilong wu): Paddle GPU minimum memory allocation unit is 256 bytes,
# waiting_alloc_memory will compute the memory space occupied by 't'.
# Coefficient 1.2 is used to avoid OOM that may occur in this critical state when the memory is just enough.
waiting_alloc_memory = (
((t._numel() * size_dtype) / 256 + 1) * 256 * 1.2
)
gpu_memory_available = core.gpu_memory_available()
if gpu_memory_available < waiting_alloc_memory:
# Copy Tensor to cpu if needed
t_used = t._copy_to(paddle.CPUPlace(), blocking)
# Release memory of t
t._clear()
copy_tensor = False
else:
# Tensor still in GPU
t_used = t
else:
t_used = t
# 2. cast Tensor to dtype if needed
if dtype is not None and dtype != t_used.dtype:
with paddle.base.framework._dygraph_place_guard(
place=t_used.place
):
t_casted = t_used.cast(dtype=dtype)
copy_tensor = False
else:
t_casted = t_used
# 3. Copy casted Tensor(in CPU or GPU) to device if needed
if device is not None and not t_casted.place._equals(device):
new_t = t_casted._copy_to(device, blocking)
copy_tensor = False
else:
new_t = t_casted
new_t.stop_gradient = t.stop_gradient
if copy_tensor:
return copy.deepcopy(new_t)
else:
return new_t
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UserWarning)
return transform(self, device, dtype, blocking, copy_tensor)
@overload
def to(
self: Tensor,
device: PlaceLike,
dtype: DTypeLike | None = ...,
blocking: bool | None = ...,
) -> Tensor: ...
@overload
def to(
self: Tensor, dtype: DTypeLike, blocking: bool | None = ...
) -> Tensor: ...
@overload
def to(
self: Tensor, other: Tensor, blocking: bool | None = ...
) -> Tensor: ...
@framework.dygraph_only
def to(self: Tensor, *args, **kwargs):
"""
Performs Tensor dtype and/or device conversion. A paddle.dtype and place
are inferred from the arguments of ``self.to(*args, **kwargs)``.There are
three ways to call `to`:
1. to(dtype, blocking=True)
2. to(device, dtype=None, blocking=True)
3. to(other, blocking=True)
**Notes**:
**If the self Tensor already has the correct dtype and device,
then self is returned. Otherwise, the returned tensor is a copy of self with
the desired dtype and device.**
Returns:
Tensor: self
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor([1,2,3])
>>> print(x)
Tensor(shape=[3], dtype=int64, place=Place(gpu:0), stop_gradient=True,
[1, 2, 3])
>>> x = x.to("cpu")
>>> print(x.place)
Place(cpu)
>>> x = x.to("float32")
>>> print(x.dtype)
paddle.float32
>>> x = x.to("gpu", "int16")
>>> print(x)
Tensor(shape=[3], dtype=int16, place=Place(gpu:0), stop_gradient=True,
[1, 2, 3])
>>> y = paddle.to_tensor([4,5,6])
>>> y
Tensor(shape=[3], dtype=int64, place=Place(gpu:0), stop_gradient=True,
[4, 5, 6])
>>> y = y.to(x)
>>> print(y)
Tensor(shape=[3], dtype=int16, place=Place(gpu:0), stop_gradient=True,
[4, 5, 6])
"""
device = None
dtype = None
blocking = None
if "non_blocking" in kwargs:
non_blocking = kwargs.pop("non_blocking")
else:
non_blocking = False
if "copy" in kwargs:
copy_tensor = kwargs.pop("copy")
else:
copy_tensor = False
size_args = len(args)
size_kwargs = len(kwargs)
def get_device_dtype_from_tensor(other):
if other is not None:
device = str(other.place)[6:-1]
dtype = other.dtype
return device, dtype
else:
return None, None
if size_args + size_kwargs > 3 or size_args + size_kwargs == 0:
raise TypeError(
"to() received too many arguments - expected one of:\n \
* (Union[str, paddle.CPUPlace(), paddle.CUDAPlace(), paddle.CUDAPinnedPlace(), paddle.XPUPlace(), paddle.CustomPlace()] \
device, Union[str, paddle.dtype, numpy.dtype] dtype, bool blocking)\n \
* (Union[str, paddle.dtype, numpy.dtype] dtype, bool blocking)\n \
* (paddle.Tensor other, bool blocking) "
)
valid_keys = {"device", "dtype", "blocking", "other"}
valid_dtypes = [
"bfloat16",
"float16",
"float32",
"float64",
"int8",
"int16",
"int32",
"int64",
"uint8",
"complex64",
"complex128",
"bool",
]
invalid_keys = set(kwargs.keys()) - valid_keys
if len(invalid_keys) != 0:
raise TypeError(
"to() got an unexpected keyword argument "
+ next(iter(invalid_keys))
)
if size_args > 0:
if isinstance(args[0], paddle.Tensor):
device, dtype = get_device_dtype_from_tensor(args[0])
if size_args == 2:
blocking = args[1]
else:
blocking = kwargs.get("blocking", None)
elif (
isinstance(args[0], (paddle.dtype, np.dtype))
or isinstance(args[0], str)
and args[0].lower() in valid_dtypes
):
dtype = args[0]
if size_args == 2:
blocking = args[1]
else:
blocking = kwargs.get("blocking", None)
else:
device = args[0]
if size_args == 2:
dtype = args[1]
elif size_args == 3:
dtype, blocking = args[1], args[2]
else:
dtype = kwargs.get("dtype", None)
blocking = kwargs.get("blocking", None)
else:
device = kwargs.get("device", None)
dtype = kwargs.get("dtype", None)
blocking = kwargs.get("blocking", None)
if device is None and dtype is None:
device, dtype = get_device_dtype_from_tensor(
kwargs.get("other", None)
)
blocking = False if not blocking or non_blocking else True
return self._to(device, dtype, blocking, copy_tensor)
def clear_grad(self: Tensor) -> None:
"""
The alias of clear_gradient().
"""
self.clear_gradient()
def item(self: Tensor, *args: int) -> float | bool | complex:
"""
Convert element at specific position in Tensor into Python scalars. If the position is not specified, the Tensor must be a
single-element Tensor.
Args:
*args(int): The input coordinates. If it's single int, the data in the corresponding order of flattened Tensor will be returned.
Default: None, and it must be in the case where Tensor has only one element.
Returns(Python scalar): A Python scalar, whose dtype is corresponds to the dtype of Tensor.
Raises:
ValueError: If the Tensor has more than one element, there must be coordinates.
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor(1)
>>> print(x.item())
1
>>> print(type(x.item()))
<class 'int'>
>>> x = paddle.to_tensor(1.0)
>>> print(x.item())
1.0
>>> print(type(x.item()))
<class 'float'>
>>> x = paddle.to_tensor(True)
>>> print(x.item())
True
>>> print(type(x.item()))
<class 'bool'>
>>> x = paddle.to_tensor(1+1j)
>>> print(x.item())
(1+1j)
>>> print(type(x.item()))
<class 'complex'>
>>> x = paddle.to_tensor([[1.1, 2.2, 3.3]])
>>> print(x.item(2))
3.299999952316284
>>> print(x.item(0, 2))
3.299999952316284
"""
# resolve the error issue in scenario of pipeline parallel
# where some devices do not have self data, return None does not affect
# the execution result in those devices, so currently we return None
if self.is_dist() and not self._is_initialized():
return None
scalar = self._getitem_from_offset(*args)
if scalar.dtype == np.uint16:
return convert_uint16_to_float(scalar).item()
return scalar.item()
@property
def inplace_version(self: Tensor) -> int:
"""
The inplace version of current Tensor.
The version number is incremented whenever the current Tensor is modified through an inplace operation.
**Notes: This is a read-only property**
Examples:
.. code-block:: python
>>> import paddle
>>> var = paddle.ones(shape=[4, 2, 3], dtype="float32")
>>> print(var.inplace_version)
0
>>> var[1] = 2.2
>>> print(var.inplace_version)
1
"""
return self._inplace_version()
def __str__(self: Tensor) -> str:
"""
Convert a Tensor object to a readable string.
Returns(str): A readable string.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.seed(2023)
>>> x = paddle.rand([2, 5])
>>> print(x)
Tensor(shape=[2, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.86583614, 0.52014720, 0.25960937, 0.90525323, 0.42400089],
[0.40641287, 0.97020894, 0.74437362, 0.51785129, 0.73292869]])
"""
from paddle.tensor.to_string import tensor_to_string
return tensor_to_string(self)
def __format__(self, format_spec: str) -> str:
if self.ndim == 0:
return self.item().__format__(format_spec)
return object.__format__(self, format_spec)
def __deepcopy__(self, memo: dict[int, Tensor]) -> Tensor:
"""
Deep copy Tensor, it will always performs Tensor copy.
Examples:
.. code-block:: python
>>> import paddle
>>> import copy