Guard
Background
The Device Guard abstraction in PyTorch provides RAII-based device and stream management, allowing code to temporarily switch device contexts and automatically restore the original device upon exiting a scope. This is essential for operations that need to ensure they execute on a specific device regardless of the current global device state.
For custom accelerators, a CustomDeviceGuardImpl that implements c10::impl::DeviceGuardImplInterface enables seamless integration with PyTorch’s device management infrastructure. For example, the OpenReg (Open Registration) integration example in PyTorch provides an OpenRegGuardImpl for the PrivateUse1 dispatch key, with the following capabilities:
Device Management: Save, switch, and restore the current device index