-
Notifications
You must be signed in to change notification settings - Fork 6k
Expand file tree
/
Copy path__init__.py
More file actions
2268 lines (1780 loc) · 70.3 KB
/
Copy path__init__.py
File metadata and controls
2268 lines (1780 loc) · 70.3 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) 2021 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 ctypes
import importlib
import os
import re
import sys
import types
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, TypeAlias, overload
import paddle
from paddle.amp import autocast as _autocast
from paddle.amp.grad_scaler import GradScaler as _GradScaler
from paddle.base import core, framework
from paddle.base.framework import (
is_compiled_with_cinn,
is_compiled_with_cuda,
is_compiled_with_distribute,
is_compiled_with_rocm,
)
from paddle.tensor.creation import (
BFloat16Tensor,
BoolTensor,
ByteTensor,
CharTensor,
DoubleTensor,
FloatTensor,
HalfTensor,
IntTensor,
LongTensor,
ShortTensor,
)
from . import ( # noqa: F401
cuda,
xpu,
)
if TYPE_CHECKING:
from collections.abc import Generator
from contextlib import AbstractContextManager
from types import TracebackType
from paddle import IPUPlace as _IPUPlace, XPUPlace as _XPUPlace
from paddle._typing.device_like import PlaceLike
from paddle.base.core import Place
_InitStreamBase = core.CUDAStream | core.CustomDeviceStream | core.XPUStream
_InitEventBase = core.CUDAEvent | core.CustomDeviceEvent | core.XPUEvent
from paddle import CUDAPlace, CustomPlace
from paddle.base.libpaddle import _customDeviceProperties
_CustomPlaceLike: TypeAlias = (
CUDAPlace
| CustomPlace
| str # some string like "iluvatar_gpu" "metax_gpu:0", etc.
| int # some int like 0, 1, etc.
)
# Dynamically import device functions based on available devices
current_device_is_cpu = 0
if core.is_compiled_with_cuda():
from .cuda import (
create_event as _create_event_base,
create_stream as _create_stream_base,
device_count,
empty_cache,
get_device_properties as _get_device_properties,
get_rng_state,
manual_seed,
max_memory_allocated,
max_memory_reserved,
memory_allocated,
memory_reserved,
reset_max_memory_allocated,
reset_max_memory_reserved,
set_rng_state,
)
elif core.is_compiled_with_xpu():
from .xpu import (
create_event as _create_event_base,
create_stream as _create_stream_base,
device_count,
empty_cache,
get_device_properties as _get_device_properties,
get_rng_state,
manual_seed,
max_memory_allocated,
max_memory_reserved,
memory_allocated,
memory_reserved,
reset_max_memory_allocated,
reset_max_memory_reserved,
set_rng_state,
)
else:
if hasattr(core, 'get_all_custom_device_type'):
dev_types = core.get_all_custom_device_type()
else:
dev_types = []
if dev_types and core.is_compiled_with_custom_device(dev_types[0]):
from .custom_device import (
create_event as _create_event_base,
create_stream as _create_stream_base,
device_count,
empty_cache,
get_device_properties as _get_device_properties,
get_rng_state,
manual_seed,
max_memory_allocated,
max_memory_reserved,
memory_allocated,
memory_reserved,
reset_max_memory_allocated,
reset_max_memory_reserved,
set_rng_state,
)
else:
current_device_is_cpu = 1
from .cpu import (
device_count,
get_rng_state,
manual_seed,
max_memory_allocated,
max_memory_reserved,
reset_max_memory_allocated,
reset_max_memory_reserved,
set_rng_state,
)
__all__ = [
'get_cudnn_version',
'set_device',
'get_device',
'XPUPlace',
'IPUPlace',
'is_compiled_with_xpu',
'is_compiled_with_ipu',
'is_compiled_with_cinn',
'is_compiled_with_cuda',
'is_compiled_with_rocm',
'is_compiled_with_distribute',
'is_compiled_with_custom_device',
'get_all_device_type',
'get_all_custom_device_type',
'get_available_device',
'get_available_custom_device',
'get_device_properties',
'Stream',
'Event',
'current_stream',
'set_stream',
'stream_guard',
'device_guard',
'synchronize',
'device_count',
'empty_cache',
'max_memory_allocated',
'max_memory_reserved',
'reset_max_memory_allocated',
'reset_max_memory_reserved',
'memory_allocated',
'memory_reserved',
'is_available',
'is_current_stream_capturing',
'get_device_name',
'get_device_capability',
'get_rng_state',
'set_rng_state',
'FloatTensor',
'DoubleTensor',
'HalfTensor',
'BFloat16Tensor',
'ByteTensor',
'CharTensor',
'ShortTensor',
'IntTensor',
'LongTensor',
'BoolTensor',
'device',
'is_bf16_supported',
'manual_seed',
'reset_peak_memory_stats',
'ipc_collect',
'get_stream_from_external',
'StreamContext',
]
_cudnn_version = None
def is_compiled_with_custom_device(device_type: str) -> bool:
"""
Whether paddle was built with Paddle_CUSTOM_DEVICE .
Args:
device_type (str): the registered device type, like "npu".
Return:
bool, ``True`` if CustomDevice is supported, otherwise ``False``.
Examples:
.. code-block:: pycon
>>> import paddle
>>> support_npu = paddle.device.is_compiled_with_custom_device("npu")
"""
return core.is_compiled_with_custom_device(device_type)
def is_compiled_with_ipu() -> bool:
"""
Whether paddle was built with WITH_IPU=ON to support Graphcore IPU.
Returns (bool): `True` if IPU is supported, otherwise `False`.
Examples:
.. code-block:: pycon
>>> import paddle
>>> support_ipu = paddle.is_compiled_with_ipu()
"""
return core.is_compiled_with_ipu()
def IPUPlace() -> _IPUPlace:
"""
Return a Graphcore IPU Place
Examples:
.. code-block:: pycon
>>> # doctest: +REQUIRES(env:IPU)
>>> import paddle
>>> paddle.device.set_device('ipu')
>>> place = paddle.device.IPUPlace()
"""
return core.IPUPlace()
def is_compiled_with_xpu() -> bool:
"""
Whether paddle was built with WITH_XPU=ON to support Baidu Kunlun
Returns (bool): whether paddle was built with WITH_XPU=ON
Examples:
.. code-block:: pycon
>>> import paddle
>>> support_xpu = paddle.device.is_compiled_with_xpu()
"""
return core.is_compiled_with_xpu()
def XPUPlace(dev_id: int) -> _XPUPlace:
"""
Return a Baidu Kunlun Place
Args:
dev_id(int): Baidu Kunlun device id
Examples:
.. code-block:: pycon
>>> # doctest: +REQUIRES(env:XPU)
>>> import paddle
>>> paddle.device.set_device('xpu')
>>> place = paddle.device.XPUPlace(0)
"""
return core.XPUPlace(dev_id)
def is_available() -> bool:
"""
Check whether **any supported device** is available in the current environment.
This function checks whether Paddle is built with support for at least one
type of accelerator (e.g., CUDA, XPU, CustomDevice) and whether there is
at least one device of that type available.
If any supported device is available, this function returns True. Otherwise,
it returns False.
Returns:
bool: True if there is at least one available device (GPU/XPU/CustomDevice),
False otherwise.
Examples:
.. code-block:: pycon
>>> import paddle
>>> if paddle.device.is_available():
... print("At least one device is available")
... else:
... print("No supported devices available")
"""
return device_count() >= 1
def is_current_stream_capturing() -> bool:
"""
Check whether the current stream is in CUDA graph capturing state.
Returns:
bool: True if the current stream is capturing, False otherwise.
Examples:
.. code-block:: pycon
>>> import paddle
>>> if paddle.device.is_available():
... graph = paddle.device.cuda.graphs.CUDAGraph()
... graph.capture_begin()
... print(paddle.device.is_current_stream_capturing()) # True
... graph.capture_end()
"""
return core.is_cuda_graph_capturing()
def get_cudnn_version() -> int | None:
"""
This function return the version of cudnn. the return value is int which represents the
cudnn version. For example, if it return 7600, it represents the version of cudnn is 7.6.
Returns:
int: A int value which represents the cudnn version. If cudnn version is not installed, it return None.
Examples:
.. code-block:: pycon
>>> import paddle
>>> cudnn_version = paddle.device.get_cudnn_version()
"""
global _cudnn_version
if not core.is_compiled_with_cuda():
return None
if _cudnn_version is None:
cudnn_version = int(core.cudnn_version())
_cudnn_version = cudnn_version
if _cudnn_version < 0:
return None
else:
return cudnn_version
else:
return _cudnn_version
def device_to_place(device: Place | int | str | None = None) -> Place:
"""
Convert input device(Place | int | str | None) into corresponding Place object.
"""
device = _device_to_paddle(device)
device = _convert_to_place(device)
return device
def _convert_to_place(device: PlaceLike) -> Place:
if not isinstance(device, str):
if type(device) is core.Place:
if device.is_gpu_place():
return core.CUDAPlace(device.gpu_device_id())
elif device.is_cpu_place():
return core.CPUPlace()
elif device.is_xpu_place():
return core.XPUPlace(device.xpu_device_id())
elif device.is_custom_place():
return core.CustomPlace(
device.custom_device_type(), device.custom_device_id()
)
return device
lower_device = device.lower()
if lower_device.startswith("cuda"):
lower_device = lower_device.replace("cuda", "gpu")
if device in core.get_all_custom_device_type():
selected_devices = os.getenv(f"FLAGS_selected_{device}s", "0").split(
","
)
device_id = int(selected_devices[0])
place = core.CustomPlace(device, device_id)
elif lower_device == 'cpu':
place = core.CPUPlace()
elif lower_device == 'gpu' or lower_device == 'dcu':
if not core.is_compiled_with_cuda():
raise ValueError(
"The device should not be 'gpu', "
"since PaddlePaddle is not compiled with CUDA"
)
place = core.CUDAPlace(paddle.distributed.ParallelEnv().dev_id)
elif lower_device == 'xpu':
if not core.is_compiled_with_xpu():
raise ValueError(
"The device should not be 'xpu', "
"since PaddlePaddle is not compiled with XPU"
)
selected_xpus = os.getenv("FLAGS_selected_xpus", "0").split(",")
device_id = int(selected_xpus[0])
place = core.XPUPlace(device_id)
elif lower_device == 'ipu':
if not core.is_compiled_with_ipu():
raise ValueError(
"The device should not be 'ipu', "
"since PaddlePaddle is not compiled with IPU"
)
place = core.IPUPlace()
else:
available_gpu_device = re.match(r'gpu:\d+', lower_device) or re.match(
r'dcu:\d+', lower_device
)
available_xpu_device = re.match(r'xpu:\d+', lower_device)
if available_gpu_device:
if not core.is_compiled_with_cuda():
raise ValueError(
f"The device should not be {available_gpu_device}, since PaddlePaddle is "
"not compiled with CUDA"
)
device_info_list = device.split(':', 1)
device_id = device_info_list[1]
device_id = int(device_id)
place = core.CUDAPlace(device_id)
if available_xpu_device:
if not core.is_compiled_with_xpu():
raise ValueError(
f"The device should not be {available_xpu_device}, since PaddlePaddle is "
"not compiled with XPU"
)
device_info_list = device.split(':', 1)
device_id = device_info_list[1]
device_id = int(device_id)
place = core.XPUPlace(device_id)
if not available_gpu_device and not available_xpu_device:
device_info_list = device.split(':', 1)
device_type = device_info_list[0]
if device_type in core.get_all_custom_device_type():
device_id = device_info_list[1]
device_id = int(device_id)
place = core.CustomPlace(device_type, device_id)
else:
raise ValueError(
"The device must be a string which is like 'cpu', {}".format(
', '.join(
f"'{x}', '{x}:x'"
for x in [
'gpu',
'dcu',
'xpu',
'npu',
*core.get_all_custom_device_type(),
]
)
)
)
return place
class device:
r"""Context-manager that changes the selected device.
Args:
device (paddle.Place, int or str): device index to select.
Examples:
.. code-block:: pycon
>>> import paddle
>>> print(paddle.device.get_device()) # gpu:0
>>> with paddle.device.device("cpu"):
... print(paddle.device.get_device()) # cpu
>>> # paddle.cuda.device is an alias of paddle.device.device
>>> with paddle.cuda.device("cpu"):
... print(paddle.device.get_device()) # cpu
>>> print(paddle.device.get_device())
"""
def __init__(self, device: Place | int | str | None = None):
self.place = device_to_place(device)
self.prev_place_str = "-1"
def __enter__(self):
self.prev_place_str = get_device()
set_device(self.place)
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: types.TracebackType | None,
) -> bool | None:
set_device(self.prev_place_str)
return False
def current_device() -> int:
"""
Return the index of a currently selected device.
Returns:
int: The index of the currently selected device.
Examples:
.. code-block:: pycon
>>> # doctest: +REQUIRES(env:GPU)
>>> import paddle
>>> device_id = paddle.device.current_device() # this is equivalent to paddle.cuda.current_device()
>>> print(f"Current device index: {device_id}")
"""
# Use paddle.device.get_device() to get the current device string
device_str = get_device()
# Parse the device string to extract the device index
# Format examples: 'gpu:0', 'xpu:0', 'custom_device:0'
if ':' in device_str:
device_id = int(device_str.split(':')[1])
else:
# If no device index is specified, default to 0
device_id = 0
return device_id
def is_bf16_supported(including_emulation: bool = True) -> bool:
"""
Return a bool indicating if the current CUDA/ROCm device supports dtype bfloat16.
Args:
including_emulation (bool = True): Whether to treat software-emulated BF16 as supported; if False, only native hardware BF16 support is considered.
Returns:
bool: A boolean value which indicates whether the current CUDA/ROCm device supports dtype bfloat16.
Examples:
.. code-block:: pycon
>>> import paddle
>>> paddle.device.is_bf16_supported()
>>> # paddle.cuda.is_bf16_supported() is an alias of paddle.device.is_bf16_supported()
>>> paddle.cuda.is_bf16_supported()
"""
# including_emulation is not used here, but kept for compatibility with the original implementation
if core.is_bfloat16_supported(paddle.framework._current_expected_place_()):
return True
# If CUDA is not available, than it does not support bf16 either
if not is_available():
return False
device = get_device()
# Check for CUDA version and device compute capability.
# This is a fast way to check for it.
if not including_emulation:
return False
# Finally try to create a bfloat16 device.
try:
paddle.tensor([1.0], dtype=paddle.bfloat16, device=device)
return True
except:
return False
def set_device(device: PlaceLike | int) -> PlaceLike:
"""
Paddle supports running calculations on various types of devices, including CPU, GPU, XPU, NPU and IPU.
They are represented by string identifiers. This function can specify the global device
which the OP will run.
Args:
device(str, Place or int): This parameter determines the specific running device.
It can be ``cpu``, ``gpu``, ``xpu``, ``npu``, ``gpu:x``, ``xpu:x``, ``npu:x`` and ``ipu``,
where ``x`` is the index of the GPUs, XPUs or NPUs.
Returns:
Place,the Place to set.
Examples:
.. code-block:: pycon
>>> # doctest: +REQUIRES(env:GPU)
>>> import paddle
>>> paddle.device.set_device("cpu")
>>> x1 = paddle.ones(name='x1', shape=[1, 2], dtype='int32')
>>> print(x1.place)
Place(cpu)
>>> paddle.device.set_device("gpu:0")
>>> x2 = paddle.zeros(name='x2', shape=[1, 2], dtype='int32')
>>> print(x2.place)
Place(gpu:0)
>>> # x1 is still on cpu
>>> print(x1.place)
Place(cpu)
"""
place = device_to_place(device)
framework._set_expected_place(place)
if framework.in_dygraph_mode():
core.eager_set_device_id()
return place
@overload
def get_device(input: None = None) -> str: ...
@overload
def get_device(input: paddle.Tensor) -> int: ...
def get_device(input: paddle.Tensor | None = None) -> str | int:
"""
This function can get the current global device of the program is running.
It's a string which is like 'cpu', 'gpu:x', 'xpu:x' and 'npu:x'. if the global device is not
set, it will return a string which is 'gpu:x' when cuda is available or it
will return a string which is 'cpu' when cuda is not available.
Returns:
if input is Tensor, this function will return the device ID where the given Tensor is located.
int:
- -1, if the Tensor is on CPU.
- The device ID (e.g., 0, 1, ...) if the Tensor is on GPU.
if input is not Tensor, this function will return the device name where the program is running.
str:
- 'cpu': If the program is running on CPU.
- 'gpu:x': If the program is running on GPU, where `x` is the index of the GPU.
- 'xpu:x': If the program is running on XPU, where `x` is the index of the XPU.
- 'npu:x': If the program is running on NPU, where `x` is the index of
Examples:
.. code-block:: pycon
>>> import paddle
>>> device = paddle.device.get_device()
>>> x_cpu = paddle.to_tensor([1, 2, 3], place=paddle.CPUPlace())
>>> id = paddle.get_device(x_cpu) # -1
"""
if isinstance(input, paddle.Tensor):
if 'cpu' in str(input.place):
return -1
return input.place.gpu_device_id()
device = ''
place = framework._current_expected_place_()
if isinstance(place, core.CPUPlace):
device = 'cpu'
elif isinstance(place, core.CUDAPlace):
device_id = place.get_device_id()
device = 'gpu:' + str(device_id)
elif isinstance(place, core.XPUPlace):
device_id = place.get_device_id()
device = 'xpu:' + str(device_id)
elif isinstance(place, core.IPUPlace):
num_devices = core.get_ipu_device_count()
device = f"ipus:{{0-{num_devices - 1}}}"
elif isinstance(place, core.CustomPlace):
device_id = place.get_device_id()
device_type = place.get_device_type()
device = device_type + ':' + str(device_id)
else:
raise ValueError(f"The device specification {place} is invalid")
return device
def get_default_device() -> paddle.device:
"""
Returns:
str: The default device for PaddlePaddle.
Example:
.. code-block:: pycon
>>> import paddle
>>> print(paddle.get_default_device())
"""
dev = get_device()
# Only replace exact "gpu" device type, not substrings in custom device names
if dev.startswith("gpu"):
dev = "cuda" + dev[3:]
return paddle.device(dev)
def set_default_device(device: PlaceLike | int) -> None:
"""
Paddle supports running calculations on various types of devices, including CPU, GPU, XPU, NPU and IPU.
This function can specify the global device which the OP will run.
Args:
device(str, Place or int): This parameter determines the specific running device.
It can be ``cpu``, ``gpu``, ``xpu``, ``npu``, ``gpu:x``, ``xpu:x``, ``npu:x`` and ``ipu``,
where ``x`` is the index of the GPUs, XPUs or NPUs.
Examples:
.. code-block:: pycon
>>> import paddle
>>> paddle.device.set_device("cpu")
"""
set_device(device)
def get_all_device_type() -> list[str]:
"""
Get all available device types.
Returns:
A list of all available device types.
Examples:
.. code-block:: pycon
>>> import paddle
>>> paddle.device.get_all_device_type()
>>> # Case 1: paddlepaddle-cpu package installed, and no custom device registered.
>>> # Output: []
>>> # Case 2: paddlepaddle-gpu package installed, and no custom device registered.
>>> # Output: ['gpu']
>>> # Case 3: paddlepaddle-cpu package installed, and custom device 'CustomCPU' is registered.
>>> # Output: ['CustomCPU']
>>> # Case 4: paddlepaddle-gpu package installed, and custom device 'CustomCPU' and 'CustomGPU' is registered.
>>> # Output: ['gpu', 'CustomCPU', 'CustomGPU']
"""
return core.get_all_device_type()
def get_all_custom_device_type() -> list[str] | None:
"""
Get all available custom device types.
Returns:
A list of all available custom device types.
Examples:
.. code-block:: pycon
>>> import paddle
>>> paddle.device.get_all_custom_device_type()
>>> # Case 1: paddlepaddle-gpu package installed, and no custom device registered.
>>> # Output: None
>>> # Case 2: paddlepaddle-gpu package installed, and custom device 'CustomCPU' and 'CustomGPU' is registered.
>>> # Output: ['CustomCPU', 'CustomGPU']
"""
return core.get_all_custom_device_type()
def get_available_device() -> list[str]:
"""
Get all available devices.
Returns:
A list of all available devices.
Examples:
.. code-block:: pycon
>>> import paddle
>>> paddle.device.get_available_device()
>>> # Case 1: paddlepaddle-cpu package installed, and no custom device registered.
>>> # Output: []
>>> # Case 2: paddlepaddle-gpu package installed, and no custom device registered.
>>> # Output: ['gpu:0', 'gpu:1']
>>> # Case 3: paddlepaddle-cpu package installed, and custom device 'CustomCPU' is registered.
>>> # Output: ['CustomCPU']
>>> # Case 4: paddlepaddle-gpu package installed, and custom device 'CustomCPU' and 'CustomGPU' is registered.
>>> # Output: ['gpu:0', 'gpu:1', 'CustomCPU', 'CustomGPU:0', 'CustomGPU:1']
"""
return core.get_available_device()
def get_available_custom_device() -> list[str] | None:
"""
Get all available custom devices.
Returns:
A list of all available custom devices.
Examples:
.. code-block:: pycon
>>> import paddle
>>> paddle.device.get_available_custom_device()
>>> # Case 1: paddlepaddle-gpu package installed, and no custom device registered.
>>> # Output: None
>>> # Case 2: paddlepaddle-gpu package installed, and custom device 'CustomCPU' and 'CustomGPU' is registered.
>>> # Output: ['CustomCPU', 'CustomGPU:0', 'CustomGPU:1']
"""
return core.get_available_custom_device()
def get_device_properties(
device: _CustomPlaceLike | None = None,
) -> _customDeviceProperties:
"""
Return the properties of given device.
Args:
device(|paddle.CustomPlace|int|str|None, optional): The device, the id of the device or
the string name of device like npu:x' which to get the properties of the
device from. If device is None, the device is the current device.
Default: None.
Returns:
_customDeviceProperties: The properties of the device which include ASCII string
identifying device, major compute capability, minor compute capability, global
memory available and the number of multiprocessors on the device.
Examples:
.. code-block:: pycon
>>> # import paddle
>>> # paddle.device.set_device('npu')
>>> # paddle.device.get_device_properties('npu:0')
>>> # _customDeviceProperties(name='', major=0, minor=0, total_memory=0MB, multi_processor_count=0)
>>> # paddle.device.get_device_properties('npu')
>>> # _customDeviceProperties(name='', major=0, minor=0, total_memory=0MB, multi_processor_count=0)
"""
device = device_to_place(device)
return _get_device_properties(device)
def get_device_module(device: _CustomPlaceLike = None):
"""
Returns the Paddle module associated with a given device.
Args:
device (_CustomPlaceLike, optional): The device to query.
Can be one of the following:
- paddle.Place object (e.g., paddle.CUDAPlace(0))
- str (e.g., "gpu:0", "xpu", "npu")
- int (device index, e.g., 0 -> "gpu:0")
- None (use current expected place)
Returns:
module: The corresponding Paddle device module (e.g., paddle.cuda, paddle.device.xpu)
Raises:
RuntimeError: If the device type is CPU (Paddle does not expose `paddle.cpu`)
or if no matching device module is found.
Example:
.. code-block:: pycon
>>> paddle.get_device_module("gpu:0")
<module 'paddle.cuda' ...>
>>> # paddle.get_device_module(paddle.XPUPlace(0))
>>> # <module 'paddle.device.xpu' ...>
"""
device = _device_to_paddle(device)
if isinstance(device, str):
device = device.lower().split(':')[0]
custom_device_types = {
"metax_gpu",
"biren_gpu",
"custom_cpu",
"gcu",
"iluvatar_gpu",
"intel_gpu",
"intel_hpu",
"mlu",
"mps",
"npu",
"sdaa",
}
if device in ("cuda", "gpu"):
return paddle.cuda
elif device == "xpu":
return paddle.device.xpu
elif device in custom_device_types:
return paddle.device.custom_device
elif device == "cpu":
return paddle.device.cpu
else:
raise RuntimeError(f"Unsupported device type: {device}")
place = (
paddle.framework._current_expected_place_()
if device is None
else _convert_to_place(device)
)
place_to_module = {
core.CUDAPlace: paddle.cuda,
core.CustomPlace: paddle.device.custom_device,
core.XPUPlace: paddle.device.xpu,
core.CPUPlace: paddle.device,
}
for place_type, module in place_to_module.items():
if isinstance(place, place_type):
return module
def get_device_name(
device: _CustomPlaceLike | None = None,
) -> str:
"""
Return the properties of given device.
Args:
device(|paddle.CustomPlace|int|str|None, optional): The device, the id of the device or
the string name of device like npu:x' which to get the properties of the
device from. If device is None, the device is the current device.
Default: None.
Returns:
str: The name of the CUDA device.
Examples:
.. code-block:: pycon
>>> # doctest: +REQUIRES(env:CUSTOM_DEVICE)
>>> import paddle
>>> name = paddle.device.get_device_name()
>>> print(name)
"""
return get_device_properties(device).name
def get_device_capability(
device: _CustomPlaceLike | None = None,
) -> tuple[int, int]:
"""
Return the device_capability of given device.