fairseq2.device¶
This module provides abstractions for managing PyTorch devices and handling CUDA contexts.
ABCs¶
- class fairseq2.device.CudaContext[source]¶
Bases:
ABCRepresents an interface for interacting with CUDA runtime and device information.
- class fairseq2.device.DeviceContext[source]¶
Bases:
ABCProvides methods to get and set the current device of the calling thread.
This interface can be used as an alternative to the corresponding standalone functions in object-oriented code.
- abstract get_current_device() device[source]¶
See
get_current_device().
- abstract set_device(device: device) AbstractContextManager[None][source]¶
See
set_device().
Functions¶
- fairseq2.device.detect_default_device() device[source]¶
Detects the default device of this process from environment variables.
The default device is determined by the following precedence:
If
FAIRSEQ2_DEVICEenvironment variable is set, the specified device will be used.If CUDA is enabled and
CUDA_VISIBLE_DEVICESenvironment variable contains a single device, the specified device will be used.If CUDA is enabled and
LOCAL_RANKenvironment variable is set, the CUDA device at the specified index will be used.CPU will be used.
- Raises:
EnvironmentVariableError –
FAIRSEQ2_DEVICEenvironment variable does not represent a device.EnvironmentVariableError –
LOCAL_RANKenvironment variable is not a positive integer.LocalRankOutOfRangeError –
LOCAL_RANKenvironment variable exceeds the number of available devices.
- fairseq2.device.get_current_device() device[source]¶
Returns the current device of the calling thread.
Warning
This function might impose a slight performance cost. Avoid calling it in hot code paths.
- fairseq2.device.set_device(device: device) AbstractContextManager[None][source]¶
Changes the device of the calling thread to the specified device.
This function acts as a context manager, ensuring that within its scope, any operation that constructs tensors uses the specified device - unless an explicit
deviceargument is provided.Note
This function is equivalent to using a
torch.deviceas a context manager.import torch from fairseq2.device import set_device cuda0_device = torch.device("cuda:0") with set_device(cuda0_device): t = torch.ones((4,4)) assert t.device == cuda0_device cuda1_device = torch.device("cuda:1") with set_device(cuda1_device): t = torch.ones((4, 4)) assert t.device == cuda1_device t = torch.ones((4, 4)) assert t.device == torch.device("cpu")