Okay, here's the complete code adapted to use torch-directml for AMD (or Intel) GPUs on Windows.
Important Prerequisites:
-
Install torch-directml:
pip uninstall torch torchvision torchaudio # Uninstall any existing CPU/CUDA PyTorch
pip install torch-directml
This command installs a version of PyTorch that is built to work with DirectML, along with the DirectML plugin itself.
-
Model Path: Ensure G:\model\testmodel actually contains your downloaded Stable Diffusion model files (e.g., model_index.json, unet/, vae/, text_encoder/, etc.).
-
GPU Drivers: Make sure your AMD GPU drivers are up-to-date.
import torch
from diffusers import DiffusionPipeline
import os # For checking model path
# --- Configuration ---
MODEL_PATH = r"G:\model\testmodel" # Your local model directory
PROMPT = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
OUTPUT_IMAGE_NAME = "astronaut_jungle_directml.png"
# For DirectML, float16 is generally preferred if your GPU supports it well.
# Some older AMD cards might work better with float32, but it will be slower and use more VRAM.
# If you encounter "not implemented" errors with float16, try torch.float32.
DTYPE = torch.float16
# --- Check if model path exists ---
if not os.path.isdir(MODEL_PATH):
print(f"Error: Model path not found: {MODEL_PATH}")
print("Please ensure the path is correct and contains the model files.")
exit()
# --- Device Setup (Attempt DirectML, fallback to CPU) ---
device = None
try:
import torch_directml
if torch_directml.is_available():
# Get the default DirectML device (usually your dedicated GPU)
device = torch_directml.device()
# You can also get specific device info if needed:
# device_name = torch_directml.device_name(0) # 0 for the first DML device
# print(f"Using DirectML device: {device_name}")
print(f"Successfully initialized DirectML. Using device: {device}")
else:
print("DirectML is installed, but no suitable device was found or it's not enabled.")
print("Falling back to CPU. This will be very slow.")
device = torch.device("cpu")
except ImportError:
print("torch-directml is not installed.")
print("Please install it by running: pip install torch-directml")
print("Falling back to CPU. This will be very slow.")
device = torch.device("cpu")
except Exception as e:
print(f"An error occurred while trying to initialize DirectML: {e}")
print("Falling back to CPU. This will be very slow.")
device = torch.device("cpu")
print(f"Selected device: {device}")
# --- 1. Load the model ---
print(f"Loading model from: {MODEL_PATH}")
try:
pipe = DiffusionPipeline.from_pretrained(
MODEL_PATH,
torch_dtype=DTYPE,
local_files_only=True, # Ensures it only uses local files
# use_safetensors=True, # Add this if your model uses .safetensors weights
)
print("Model loaded successfully.")
except Exception as e:
print(f"Error loading the model: {e}")
print("Check if the model files are complete and compatible.")
if "fp16" in str(e).lower() and DTYPE == torch.float16:
print("Try changing DTYPE to torch.float32 if your GPU or model has issues with float16.")
exit()
# --- 2. Send to the selected device (DirectML or CPU) ---
print(f"Sending model to device: {device}...")
try:
pipe = pipe.to(device)
print("Model sent to device successfully.")
except Exception as e:
print(f"Error sending model to device: {e}")
if DTYPE == torch.float16 and "half" in str(e).lower() or "fp16" in str(e).lower():
print("The model or parts of it might not support float16 on DirectML with your current setup.")
print("Try changing DTYPE to torch.float32 in the script and re-run.")
exit()
# --- Optional: Safety Checker (if you have it and want to use it) ---
# If your model download included a safety checker and you want to use it:
# from diffusers.utils import load_image
# safety_checker_path = os.path.join(MODEL_PATH, "safety_checker") # Adjust if different
# if os.path.exists(safety_checker_path):
# from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
# from transformers import AutoFeatureExtractor
#
# safety_checker = StableDiffusionSafetyChecker.from_pretrained(safety_checker_path, torch_dtype=DTYPE).to(device)
# feature_extractor = AutoFeatureExtractor.from_pretrained(safety_checker_path, torch_dtype=DTYPE)
# pipe.safety_checker = safety_checker
# pipe.feature_extractor = feature_extractor
# print("Safety checker loaded and attached.")
# else:
# print("Safety checker not found or disabled. Proceeding without it.")
# pipe.safety_checker = None # Explicitly disable if not found or not wanted
# To explicitly disable the safety checker if it's causing issues or you don't need it:
pipe.safety_checker = None
print("Safety checker explicitly disabled.")
# --- 3. Generate an image ---
print(f"Generating image with prompt: \"{PROMPT}\"")
try:
# For some models/setups, you might need to specify generator for reproducibility
# generator = torch.Generator(device=device).manual_seed(0) # Example seed
# image = pipe(PROMPT, generator=generator).images[0]
# Simpler generation:
image = pipe(PROMPT).images[0]
print("Image generated successfully.")
except Exception as e:
print(f"Error during image generation: {e}")
if "implemented" in str(e).lower() and DTYPE == torch.float16:
print("An operation might not be implemented for float16 on DirectML.")
print("Try changing DTYPE to torch.float32 in the script and re-run.")
exit()
# --- 4. Save the result ---
try:
image.save(OUTPUT_IMAGE_NAME)
print(f"Image saved successfully as {OUTPUT_IMAGE_NAME}!")
except Exception as e:
print(f"Error saving image: {e}")
Explanation of Changes and Key Points:
-
torch-directml Import and Device Setup:
- It tries to import
torch_directml.
torch_directml.is_available(): Checks if DirectML can be used.
torch_directml.device(): Gets the DirectML device object. This is what you pass to .to().
- Fallback to CPU: If
torch-directml isn't installed or a DirectML device isn't found, it gracefully falls back to using the CPU (which will be very slow for diffusion models but allows the script to run).
-
DTYPE = torch.float16:
- DirectML generally supports
float16 (half-precision), which is crucial for running larger models on GPUs with limited VRAM and for faster inference.
- Important: If you encounter errors like "not implemented for Half" or similar, it might mean either your specific AMD GPU has limited FP16 support through DirectML for certain operations, or the model itself has operations not yet fully optimized/supported in the DirectML backend for FP16. In such cases, changing
DTYPE = torch.float32 is a good troubleshooting step, though it will consume more VRAM and be slower.
-
pipe.to(device): The model is sent to the device object, which will either be the DirectML device or the CPU device.
-
Error Handling: Added more try-except blocks to catch potential issues at different stages (model loading, sending to device, generation) and provide more informative error messages.
-
Safety Checker:
- The original code didn't explicitly handle the safety checker. By default,
DiffusionPipeline will try to load it if present.
- I've added a line
pipe.safety_checker = None to explicitly disable it. This is a common step if you don't need it or if it causes issues (sometimes it can be slow or have its own compatibility quirks on non-CUDA backends). If you do have the safety checker files and want to use them, you'd load them separately and assign them to pipe.safety_checker and pipe.feature_extractor (commented-out example provided).
-
Model Path Check: Added a simple check to see if the MODEL_PATH directory exists.
To Run This Code:
- Save it as a Python file (e.g.,
generate_dml.py).
- Make sure your
MODEL_PATH is correct.
- Open a terminal or command prompt where you have Python and
torch-directml installed.
- Run the script:
python generate_dml.py
You should see output indicating whether DirectML is being used and then the progress of model loading and image generation. Performance will depend heavily on your specific AMD GPU.