device.py 1014 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """Device selection for TSPulse training/inference.
  2. Supports CUDA, Apple MPS, Huawei Ascend NPU and CPU, chosen automatically in
  3. that priority order. Set TSPULSE_DEVICE to force a specific backend.
  4. """
  5. import os
  6. import torch
  7. def get_device() -> torch.device:
  8. forced = os.getenv("TSPULSE_DEVICE", "").strip().lower()
  9. if forced:
  10. return torch.device(forced)
  11. if torch.cuda.is_available():
  12. return torch.device("cuda")
  13. if torch.backends.mps.is_available():
  14. return torch.device("mps")
  15. try:
  16. import torch_npu # noqa: F401
  17. if torch.npu.is_available():
  18. return torch.device("npu")
  19. except ImportError:
  20. pass
  21. return torch.device("cpu")
  22. def describe(device: torch.device) -> str:
  23. if device.type == "cuda":
  24. name = torch.cuda.get_device_name(device)
  25. return f"CUDA ({name})"
  26. if device.type == "mps":
  27. return "Apple MPS"
  28. if device.type == "npu":
  29. return "Huawei Ascend NPU"
  30. return "CPU"