/
device.py
1361 lines (1143 loc) · 35.6 KB
/
device.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
"""Collection of device Ivy functions."""
# global
import os
import gc
import abc
import math
import psutil
import warnings
import types
from typing import Type, Optional, Tuple
# noinspection PyUnresolvedReferences
try:
import pynvml
try:
pynvml.nvmlInit()
except pynvml.NVMLError:
pass
except ImportError:
warnings.warn(
"pynvml installation was not found in the environment, functionalities"
" of the Ivy's device module will be limited. Please install pynvml if"
" you wish to use GPUs with Ivy."
)
# nvidia-ml-py (pynvml) is not installed in CPU Dockerfile.
from typing import Union, Callable, Iterable, Any
# local
import ivy
from ivy.func_wrapper import (
handle_out_argument,
to_native_arrays_and_back,
handle_nestable,
handle_array_like_without_promotion,
)
from ivy.utils.exceptions import handle_exceptions
default_device_stack = list()
soft_device_mode_stack = list()
dev_handles = dict()
split_factors = dict()
max_chunk_sizes = dict()
# Extra #
# ------#
class DefaultDevice:
"""Ivy Device Class."""
def __init__(
self,
device: Union[ivy.Device, ivy.NativeDevice],
/,
) -> None:
"""
Initialize the DefaultDevice class.
Parameters
----------
device
The device string - as an ivy device or nativedevice class
Examples
--------
A "tpu" as device:
>>> x = ivy.DefaultDevice("tpu")
"""
self._dev = device
def __enter__(self):
"""
Enter the runtime context related to the specified device.
Returns
-------
ret
Self, an instance of the same class.
Examples
--------
A "cpu" as device:
>>> with ivy.DefaultDevice("cpu") as device:
>>> # with block calls device.__enter__()
>>> print(device._dev)
"cpu"
"""
ivy.set_default_device(self._dev)
ivy.set_soft_device_mode(True)
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[Type[BaseException]],
exc_tb: Optional[types.TracebackType],
) -> Union[ivy.Device, str]:
"""
Exit the runtime context related to the specified device.
Parameters
----------
exc_type
The type of the exception that was raised.
exc_val
The exception that was raised.
exc_tb
The traceback of the exception that was raised.
Returns
-------
ret
If no exception was raised, returns an instance of the same class.
Examples
--------
A "gpu" as device:
>>> with ivy.DefaultDevice("gpu") as device:
>>> pass
>>> # after with block device.__exit__() is called
>>> print(device._dev)
"cpu"
"""
ivy.unset_default_device()
ivy.unset_soft_device_mode()
if self and (exc_type is not None):
print(exc_tb)
raise exc_val
return self
def handle_soft_device_variable(*args, fn, **kwargs):
ivy.set_array_mode(False)
default_device = ivy.default_device()
args, kwargs = ivy.nested_map(
[args, kwargs],
lambda x: (
ivy.to_device(x, default_device)
if (ivy.is_native_array(x) and ivy.dev(x) != default_device)
else x
),
)
ivy.unset_array_mode()
return fn(*args, **kwargs)
# Helpers #
def _get_nvml_gpu_handle(device: Union[ivy.Device, ivy.NativeDevice], /) -> int:
global dev_handles
if device in dev_handles:
return dev_handles[device]
gpu_idx = int(device.split(":")[-1])
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_idx)
dev_handles[device] = handle
return handle
# Device Queries #
# Array Printing
@handle_exceptions
def get_all_ivy_arrays_on_dev(
device: Union[ivy.Device, ivy.NativeDevice],
/,
) -> ivy.Container:
"""
Get all ivy arrays which are currently alive on the specified device.
Parameters
----------
device
The device handle from which to get the arrays
Returns
-------
ret
Container with the arrays found for the specified device [identity, array]
Examples
--------
>>> x = ivy.array([1,0,2])
>>> y = ivy.dev(x)
>>> z = ivy.get_all_ivy_arrays_on_dev(y)
>>> print(z)
{139740789224448:ivy.array([1,0,2])},
"""
device = ivy.as_ivy_dev(device)
all_arrays = list()
for obj in gc.get_objects():
if (
type(obj) == ivy.data_classes.array.array.Array
and ivy.is_ivy_array(obj)
and ivy.dev(obj) == device
):
all_arrays.append(obj)
return ivy.Container(dict(zip([str(id(a)) for a in all_arrays], all_arrays)))
@handle_exceptions
def num_ivy_arrays_on_dev(device: Union[ivy.Device, ivy.NativeDevice], /) -> int:
"""
Return the number of arrays which are currently alive on the specified device.
Parameters
----------
device
The device handle from which to count the arrays
Returns
-------
ret
Number of arrays on the specified device
Examples
--------
>>> x1 = ivy.array([-1, 0, 5.2])
>>> x2 = ivy.array([-1, 0, 5.2, 4, 5])
>>> y = ivy.num_ivy_arrays_on_dev(ivy.default_device())
>>> print(y)
2
>>> x1 = ivy.native_array([-1, 0, 5.2])
>>> y = ivy.num_ivy_arrays_on_dev(ivy.default_device())
>>> print(y)
0
>>> x = ivy.Container(x1=ivy.array([-1]),
... x2=ivy.native_array([-1]))
>>> y = ivy.num_ivy_arrays_on_dev(ivy.default_device())
>>> print(y)
1
"""
return len(ivy.get_all_ivy_arrays_on_dev(device))
@handle_exceptions
@handle_nestable
def print_all_ivy_arrays_on_dev(
*,
device: Optional[Union[ivy.Device, ivy.NativeDevice]] = None,
attr_only: bool = True,
) -> None:
"""
Print the shape and dtype for all ivy arrays which are currently alive on the
specified device.
Parameters
----------
device
The device on which to print the arrays
attr_only
Whether or not to only print the `shape` and `dtype` attributes of the array
Examples
--------
>>> x = ivy.array([[1,0,2], [3,2,1]])
>>> y = ivy.dev(x)
>>> ivy.print_all_ivy_arrays_on_dev(y)
((3,), 'int32')
((3,), 'int32')
>>> x = ivy.array([[1,0,2], [3,2,1]])
>>> y = ivy.dev(x)
>>> ivy.print_all_ivy_arrays_on_dev(y, attr_only = False)
[1,0,2]
[3,2,1]
"""
arrs = ivy.get_all_ivy_arrays_on_dev(device).values()
if attr_only:
[print((arr.shape, arr.dtype)) for arr in arrs]
else:
[print(arr) for arr in arrs]
ivy.soft_device_mode = soft_device_mode_stack[-1] if soft_device_mode_stack else False
@handle_exceptions
def set_soft_device_mode(mode: bool) -> None:
"""
Set the mode of whether to move input arrays to `ivy.default_device()` before
performing an operation.
Parameter
---------
mode
boolean whether to move input arrays
Examples
--------
>>> ivy.set_soft_device_mode(False)
>>> ivy.soft_device_mode
False
>>> ivy.set_soft_device_mode(True)
>>> ivy.soft_device_mode
True
"""
global soft_device_mode_stack
ivy.utils.assertions.check_isinstance(mode, bool)
soft_device_mode_stack.append(mode)
ivy.__setattr__("soft_device_mode", mode, True)
@handle_exceptions
def unset_soft_device_mode() -> None:
"""
Reset the mode of moving input arrays to `ivy.default_device()` before performing an
operation.
Examples
--------
>>> ivy.set_soft_device_mode(False)
>>> ivy.soft_device_mode
False
>>> ivy.unset_soft_device_mode()
>>> ivy.soft_device_mode
True
"""
global soft_device_mode_stack
if soft_device_mode_stack:
soft_device_mode_stack.pop(-1)
mode = soft_device_mode_stack[-1] if soft_device_mode_stack else False
ivy.__setattr__("soft_device_mode", mode, True)
# Retrieval
@handle_exceptions
@handle_nestable
@to_native_arrays_and_back
def dev(
x: Union[ivy.Array, ivy.NativeArray], /, *, as_native: bool = False
) -> Union[ivy.Device, ivy.NativeDevice]:
"""
Get the native device handle for input array x.
Parameters
----------
x
array for which to get the device handle.
as_native
Whether or not to return the dev in native format. Default is ``False``.
Returns
-------
ret
Device handle for the array.
Examples
--------
With :class:`ivy.Array` input:
>>> x = ivy.array([3, 1, 4, 5])
>>> y = ivy.dev(x)
>>> print(y)
cpu
With :class:`ivy.NativeArray` input:
>>> x = ivy.native_array([[2, 5, 4], [3, 1, 5]])
>>> y = ivy.dev(x, as_native=True)
>>> print(y)
cpu
"""
return ivy.current_backend(x).dev(x, as_native=as_native)
# Conversions
@handle_exceptions
def as_ivy_dev(device: Union[ivy.Device, str], /) -> ivy.Device:
"""
Convert device to string representation.
Parameters
----------
device
The device handle to convert to string.
Returns
-------
ret
Device string e.g. 'cuda:0'.
Examples
--------
>>> y = ivy.as_ivy_dev('cuda:0')
>>> print(y)
cuda:0
"""
return ivy.current_backend().as_ivy_dev(device)
@handle_exceptions
def as_native_dev(device: Union[ivy.Device, ivy.NativeDevice], /) -> ivy.NativeDevice:
"""
Convert device string representation to native device type.
Parameters
----------
device
The device string to convert to native device handle.
A native device handle can be passed in instead - in this case
the unmodified parameter is returned.
Returns
-------
ret
Native device handle.
Examples
--------
With :class:`ivy.Device` input:
>>> ivy.set_backend("numpy")
>>> ivy.as_native_dev("cpu")
'cpu'
>>> ivy.set_backend("tensorflow")
>>> ivy.as_native_dev("tpu:3")
'/TPU:3'
With :class:`ivy.NativeDevice` input:
>>> import torch
>>> device = torch.device("cuda")
>>> device
device(type='cuda')
>>> ivy.as_native_dev(device)
device(type='cuda')
"""
return ivy.current_backend().as_native_dev(device)
# Memory
@handle_exceptions
def clear_cached_mem_on_dev(device: Union[ivy.Device, ivy.NativeDevice], /) -> None:
"""
Clear memory cache on target device.
Parameters
----------
device
The device string to convert to native device handle or native device handle.
Examples
--------
>>> import torch
>>> ivy.set_backend("torch")
>>> device = torch.device("cuda")
>>> ivy.clear_cached_mem_on_dev(device)
"""
ivy.current_backend().clear_cached_mem_on_dev(device)
@handle_exceptions
def total_mem_on_dev(device: Union[ivy.Device, ivy.NativeDevice], /) -> float:
"""
Get the total amount of memory (in GB) for a given device string. In case of CPU,
the total RAM is returned.
Parameters
----------
device
The device string to convert to native device handle.
Returns
-------
ret
The total memory on the device in GB.
Examples
--------
>>> x = ivy.total_mem_on_dev("cpu")
>>> print(x)
53.66700032
>>> x = ivy.total_mem_on_dev("gpu:0")
>>> print(x)
8.589934592
"""
if "gpu" in device:
handle = _get_nvml_gpu_handle(device)
info = pynvml.nvmlDeviceGetMemoryInfo(handle)
return info.total / 1e9
elif device == "cpu":
return psutil.virtual_memory().total / 1e9
else:
raise ivy.utils.exceptions.IvyException(
'Invalid device string input, must be on the form "gpu:idx" or "cpu", '
"but found {}".format(device)
)
@handle_exceptions
def used_mem_on_dev(
device: Union[ivy.Device, ivy.NativeDevice],
/,
*,
process_specific: bool = False,
) -> float:
"""
Get the used memory (in GB) for a given device string. In case of CPU, the used RAM
is returned.
Parameters
----------
device
The device string to convert to native device handle.
process_specific
Whether to check the memory used by this python process alone. Default is
False.
Returns
-------
ret
The used memory on the device in GB.
Examples
--------
>>> x = ivy.used_mem_on_dev("cpu", process_specific = False)
>>> print(x)
6.219563008
>>> x = ivy.used_mem_on_dev("cpu", process_specific = True)
>>> print(x)
0.902400346
>>> y = ivy.used_mem_on_dev("gpu:0", process_specific = False)
>>> print(y)
0.525205504
"""
ivy.clear_cached_mem_on_dev(device)
if "gpu" in device:
handle = _get_nvml_gpu_handle(device)
if process_specific:
pid = os.getpid()
for process in pynvml.nvmlDeviceGetComputeRunningProcesses(handle):
if process.pid == pid:
return process.usedGpuMemory / 1e9
info = pynvml.nvmlDeviceGetMemoryInfo(handle)
return info.used / 1e9
elif device == "cpu":
if process_specific:
return psutil.Process(os.getpid()).memory_info().rss / 1e9
vm = psutil.virtual_memory()
return (vm.total - vm.available) / 1e9
else:
raise ivy.utils.exceptions.IvyException(
'Invalid device string input, must be on the form "gpu:idx" or "cpu", '
"but found {}".format(device)
)
@handle_exceptions
def percent_used_mem_on_dev(
device: Union[ivy.Device, ivy.NativeDevice],
/,
*,
process_specific: bool = False,
) -> float:
"""
Get the percentage used memory for a given device string. In case of CPU, the used
RAM is returned.
Parameters
----------
device
The device string to convert to native device handle.
process_specific
Whether the check the memory used by this python process alone. Default is
False.
Returns
-------
ret
The percentage used memory on the device.
Examples
--------
>>> x = ivy.percent_used_mem_on_dev("cpu", process_specific = False)
>>> print(x)
94.036902561555
>>> x = ivy.percent_used_mem_on_dev("cpu", process_specific = True)
>>> print(x)
0.7024003467681645
>>> x = ivy.as_native_dev("gpu:0")
>>> y = ivy.percent_used_mem_on_dev(x, process_specific = False)
>>> print(y)
0.7095597456708771
"""
ivy.clear_cached_mem_on_dev(device)
if "gpu" in device:
handle = _get_nvml_gpu_handle(device)
info = pynvml.nvmlDeviceGetMemoryInfo(handle)
if process_specific:
pid = os.getpid()
for process in pynvml.nvmlDeviceGetComputeRunningProcesses(handle):
if process.pid == pid:
return (process.usedGpuMemory / info.total) * 100
return (info.used / info.total) * 100
elif device == "cpu":
vm = psutil.virtual_memory()
if process_specific:
return (psutil.Process(os.getpid()).memory_info().rss / vm.total) * 100
return (1 - (vm.available / vm.total)) * 100
else:
raise ivy.utils.exceptions.IvyException(
'Invalid device string input, must be on the form "gpu:idx" or "cpu", '
"but found {}".format(device)
)
# Utilization
@handle_exceptions
def dev_util(device: Union[ivy.Device, ivy.NativeDevice], /) -> float:
"""
Get the current utilization (%) for a given device.
Parameters
----------
device
The device string of the device to query utilization for.
Returns
-------
ret
The device utilization (%)
Example
-------
>>> ivy.dev_util('cpu')
13.4
>>> ivy.dev_util('gpu:0')
7.8
>>> ivy.dev_util('cpu')
93.4
>>> ivy.dev_util('gpu:2')
57.4
>>> ivy.dev_util('cpu')
84.2
"""
if device == "cpu":
return psutil.cpu_percent()
elif "gpu" in device:
handle = _get_nvml_gpu_handle(device)
return pynvml.nvmlDeviceGetUtilizationRates(handle).gpu
else:
raise ivy.utils.exceptions.IvyException(
'Invalid device string input, must be on the form "gpu:idx" or "cpu", '
"but found {}".format(device)
)
# Availability
@handle_exceptions
def gpu_is_available() -> bool:
"""
Determine whether a GPU is available to use, with the backend framework.
Returns
-------
ret
Boolean, as to whether a gpu is available.
Examples
--------
>>> print(ivy.gpu_is_available())
False
"""
return ivy.current_backend().gpu_is_available()
@handle_exceptions
def num_cpu_cores(*, logical: bool = True) -> int:
"""
Determine the number of cores available in the cpu.
Parameters
----------
logical
Whether request is for number of physical or logical cores available in CPU
Returns
-------
ret
Number of cores available in CPU
Examples
--------
>>> print(ivy.num_cpu_cores(logical=False))
2
"""
if logical:
return psutil.cpu_count(logical=logical)
else:
return psutil.cpu_count(logical=False)
@handle_exceptions
def num_gpus() -> int:
"""
Determine the number of available GPUs, with the backend framework.
Returns
-------
ret
Number of available GPUs.
Examples
--------
>>> print(ivy.num_gpus())
1
"""
return ivy.current_backend().num_gpus()
@handle_exceptions
def tpu_is_available() -> bool:
"""
Determine whether a TPU is available to use, with the backend framework.
Returns
-------
ret
Boolean, as to whether a tpu is available.
Examples
--------
>>> print(ivy.tpu_is_available())
False
"""
return ivy.current_backend().tpu_is_available()
# Default Device #
# noinspection PyShadowingNames
@handle_exceptions
def default_device(
device: Optional[Union[ivy.Device, ivy.NativeDevice]] = None,
/,
*,
item: Optional[Union[list, tuple, dict, ivy.Array, ivy.NativeArray]] = None,
as_native: bool = None,
) -> Union[ivy.Device, ivy.NativeDevice]:
"""
Return the input device or the default device. If the as_native flag is set, the
device will be converted to a native device. If the item is provided, the item's
device is returned. If the device is not provided, the last default device is
returned. If a default device has not been set, the first gpu is returned if
available, otherwise the cpu is returned.
Parameters
----------
device
The device to be returned or converted.
item
The item to get the device from.
as_native
Whether to convert the device to a native device.
Returns
-------
ret
Device handle or string.
Examples
--------
>>> ivy.default_device()
device(type='cpu')
>>> ivy.default_device("gpu:0")
'gpu:0'
>>> ivy.default_device(item=[], as_native=False)
'cpu'
>>> ivy.default_device(item=(), as_native=True)
device(type='cpu')
>>> ivy.default_device(item={"a": 1}, as_native=True)
device(type='cpu')
>>> x = ivy.array([1., 2., 3.])
>>> x = ivy.to_device(x, 'gpu:0')
>>> ivy.default_device(item=x, as_native=True)
device(type='gpu', id=0)
"""
if ivy.exists(device):
if as_native is True:
return ivy.as_native_dev(device)
elif as_native is False:
return ivy.as_ivy_dev(device)
return device
as_native = ivy.default(as_native, False)
if ivy.exists(item):
if isinstance(item, (list, tuple, dict)) and len(item) == 0:
pass
elif ivy.is_array(item):
return ivy.dev(item, as_native=as_native)
global default_device_stack
if not default_device_stack:
ret = "gpu:0" if ivy.gpu_is_available() else "cpu"
else:
ret = default_device_stack[-1]
if as_native:
return ivy.as_native_dev(ret)
return ivy.as_ivy_dev(ret)
@handle_exceptions
def set_default_device(device: Union[ivy.Device, ivy.NativeDevice], /) -> None:
"""
Set the default device to given device instance.
Parameters
----------
device
The device to set as the default device
Examples
--------
>>> ivy.set_default_device("cpu")
>>> ivy.default_device()
'cpu'
>>> ivy.set_backend("torch")
>>> ivy.set_default_device("gpu:0")
>>> ivy.default_device(as_native=True)
device(type='cuda', index=0)
>>> import torch
>>> ivy.set_backend("torch")
>>> device = torch.device("cuda")
>>> ivy.set_default_device(device)
>>> ivy.default_device(as_native=True)
device(type='cuda')
"""
global default_device_stack
default_device_stack.append(device)
@handle_exceptions
def unset_default_device() -> None:
"""
Reset the default device to "cpu".
Examples
--------
>>> ivy.set_default_device("gpu:0")
>>> ivy.default_device()
"gpu:0"
>>> ivy.unset_default_device()
>>> ivy.default_device()
"cpu"
"""
global default_device_stack
if default_device_stack:
default_device_stack.pop(-1)
# Device Allocation #
@handle_exceptions
@handle_nestable
@handle_array_like_without_promotion
@handle_out_argument
@to_native_arrays_and_back
def to_device(
x: Union[ivy.Array, ivy.NativeArray],
device: Union[ivy.Device, ivy.NativeDevice],
/,
*,
stream: Optional[Union[int, Any]] = None,
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
Move the input array x to the desired device, specified by device string.
Parameters
----------
x
input array to be moved to the desired device
device
device to move the input array `x` to
stream
stream object to use during copy. In addition to the types supported in
array.__dlpack__(), implementations may choose to support any library-specific
stream object with the caveat that any code using such an object would not be
portable.
out
optional output array, for writing the result to. It must have a shape that the
inputs broadcast to.
Returns
-------
ret
input array x placed on the desired device
Examples
--------
>>> x = ivy.array([1., 2., 3.])
>>> x = ivy.to_device(x, 'cpu')
>>> print(x.device)
cpu
"""
return ivy.current_backend(x).to_device(x, device, stream=stream, out=out)
# Function Splitting #
@handle_exceptions
def split_factor(
device: Optional[Union[ivy.Device, ivy.NativeDevice]] = None,
/,
) -> float:
"""
Get a device's global split factor, which can be used to scale the device's batch
splitting chunk sizes across the codebase.
If the global split factor is set for a given device,
returns the split factor value for the device from the split factors dictionary
If the global split factor for a device is not configured,
returns the default value which is 0.0
Parameters
----------
device
The device to query the split factor for. Sets the default device by default.
Returns
-------
ret
The split factor for the specified device.
Examples
--------
>>> x = ivy.split_factor()
>>> print(x)
0.0
>>> y = ivy.split_factor("gpu:0")
>>> print(y)
0.0
"""
global split_factors
device = ivy.default(device, default_device())
return split_factors.setdefault(device, 0.0)
@handle_exceptions
def set_split_factor(
factor: float, /, *, device: Optional[Union[ivy.Device, ivy.NativeDevice]] = None
) -> None:
"""
Set the global split factor for a given device, which can be used to scale batch
splitting chunk sizes for the device across the codebase.
Parameters
----------
factor
The factor to set the device-specific split factor to.
device
The device to set the split factor for. Sets the default device by default.
Examples
--------
>>> print(ivy.default_device())
cpu
>>> ivy.set_split_factor(0.5)
>>> print(ivy.split_factors)
{'cpu': 0.5}