Here is the complete code for using PyTorch with DirectML on an AMD GPU:
python
"""
Complete code for using PyTorch with DirectML on an AMD GPU.
Requirements:
- Python 3.7 or later
- PyTorch (latest version recommended)
- torch-directml package
- diffusers package
Install the required packages using pip:
pip install torch torchvision torchaudio diffusers torch-directml
Note: Ensure you have a compatible AMD GPU and the latest drivers installed.
Troubleshooting:
1. If you encounter errors related to DirectML, ensure that your GPU is compatible and that you have the latest drivers installed.
2. If the model fails to load or run, check that all dependencies are correctly installed and that the model is compatible with DirectML.
3. Performance may vary compared to CUDA, so be patient with image generation times.
"""
import torch
from diffusers import DiffusionPipeline
import torch_directml
def main():
try:
# Check if DirectML is available
if not torch_directml.is_available():
raise RuntimeError("DirectML is not available. Please ensure you have a compatible GPU and the correct drivers installed.")
# Set the device to DirectML
device = torch_directml.device()
print(f"Using device: {device}")
# Load the model from local directory
pipe = DiffusionPipeline.from_pretrained(
r"G:\model\testmodel",
torch_dtype=torch.float16,
local_files_only=True # Optional: Force offline mode
)
# Send to DirectML device
pipe = pipe.to(device)
# Generate an image
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
image = pipe(prompt).images[0]
# Save the result
image.save("astronaut_jungle.png")
print("Image saved successfully!")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
This code includes all necessary steps to use PyTorch with DirectML on an AMD GPU. It checks for DirectML availability, sets the device, loads the model, generates an image, and saves it. It also includes error handling and troubleshooting tips.