techfreakworm commited on
Commit
46728df
·
unverified ·
1 Parent(s): 5ac45ec

feat(device): auto-detect cuda/mps/cpu with env override

Browse files
Files changed (2) hide show
  1. server/device.py +32 -0
  2. tests/test_device.py +46 -0
server/device.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Device auto-detection for Chatterbox.
2
+
3
+ Order: env override → cuda → mps → cpu.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import os
8
+
9
+ import torch
10
+
11
+
12
+ _VALID = {"cuda", "mps", "cpu"}
13
+
14
+
15
+ def _cuda_available() -> bool:
16
+ return torch.cuda.is_available()
17
+
18
+
19
+ def _mps_available() -> bool:
20
+ backend = getattr(torch.backends, "mps", None)
21
+ return bool(backend and backend.is_available())
22
+
23
+
24
+ def select_device() -> str:
25
+ forced = (os.getenv("CHATTERBOX_DEVICE") or "").strip().lower()
26
+ if forced in _VALID:
27
+ return forced
28
+ if _cuda_available():
29
+ return "cuda"
30
+ if _mps_available():
31
+ return "mps"
32
+ return "cpu"
tests/test_device.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from unittest.mock import patch
3
+
4
+ from server.device import select_device
5
+
6
+
7
+ def test_env_override_cuda():
8
+ with patch.dict(os.environ, {"CHATTERBOX_DEVICE": "cuda"}):
9
+ assert select_device() == "cuda"
10
+
11
+
12
+ def test_env_override_mps():
13
+ with patch.dict(os.environ, {"CHATTERBOX_DEVICE": "MPS"}):
14
+ assert select_device() == "mps"
15
+
16
+
17
+ def test_env_override_cpu():
18
+ with patch.dict(os.environ, {"CHATTERBOX_DEVICE": "cpu"}):
19
+ assert select_device() == "cpu"
20
+
21
+
22
+ def test_invalid_env_falls_through_to_autodetect():
23
+ with patch.dict(os.environ, {"CHATTERBOX_DEVICE": "tpu"}, clear=False):
24
+ with patch("server.device._cuda_available", return_value=True):
25
+ assert select_device() == "cuda"
26
+
27
+
28
+ def test_autodetect_prefers_cuda_over_mps():
29
+ with patch.dict(os.environ, {}, clear=True):
30
+ with patch("server.device._cuda_available", return_value=True), \
31
+ patch("server.device._mps_available", return_value=True):
32
+ assert select_device() == "cuda"
33
+
34
+
35
+ def test_autodetect_uses_mps_when_no_cuda():
36
+ with patch.dict(os.environ, {}, clear=True):
37
+ with patch("server.device._cuda_available", return_value=False), \
38
+ patch("server.device._mps_available", return_value=True):
39
+ assert select_device() == "mps"
40
+
41
+
42
+ def test_autodetect_falls_back_to_cpu():
43
+ with patch.dict(os.environ, {}, clear=True):
44
+ with patch("server.device._cuda_available", return_value=False), \
45
+ patch("server.device._mps_available", return_value=False):
46
+ assert select_device() == "cpu"