Skip to content

AirLLM 2.8T LLM inference with single 4GB GPU

Pick the best available device instead of assuming CUDA

hotragn5667691123b2
diff --git a/README.md b/README.md
index 6a80df3..38f2102 100644
--- a/README.md
+++ b/README.md
@@ -129,7 +129,7 @@ input_tokens = model.tokenizer(input_text,
padding=False)
generation_output = model.generate(
- input_tokens['input_ids'].cuda(),
+ input_tokens['input_ids'].to(model.device),
max_new_tokens=20,
use_cache=True,
return_dict_in_generate=True)
@@ -217,7 +217,7 @@ input_tokens = model.tokenizer(input_text,
max_length=MAX_LENGTH,
padding=True)
generation_output = model.generate(
- input_tokens['input_ids'].cuda(),
+ input_tokens['input_ids'].to(model.device),
max_new_tokens=5,
use_cache= True,
return_dict_in_generate=True)
@@ -237,7 +237,7 @@ input_tokens = model.tokenizer(input_text,
truncation=True,
max_length=MAX_LENGTH)
generation_output = model.generate(
- input_tokens['input_ids'].cuda(),
+ input_tokens['input_ids'].to(model.device),
max_new_tokens=5,
use_cache=True,
return_dict_in_generate=True)
@@ -260,7 +260,7 @@ input_tokens = model.tokenizer(input_text,
truncation=True,
max_length=MAX_LENGTH)
generation_output = model.generate(
- input_tokens['input_ids'].cuda(),
+ input_tokens['input_ids'].to(model.device),
max_new_tokens=5,
use_cache=True,
return_dict_in_generate=True)
@@ -369,7 +369,7 @@ encoded = tok(
max_length=512,
)
loss = trainer.train_step(
- encoded["input_ids"].cuda(),
+ encoded["input_ids"].to(model.device),
attention_mask=encoded.get("attention_mask"),
)
print(loss)
diff --git a/air_llm/airllm/airllm_base.py b/air_llm/airllm/airllm_base.py
index b05eed9..d7821e0 100644
--- a/air_llm/airllm/airllm_base.py
+++ b/air_llm/airllm/airllm_base.py
@@ -17,7 +17,7 @@ from .profiler import LayeredProfiler
from .utils import clean_memory, load_layer, layer_tensor_names, load_layer_subset, \
find_or_create_local_splitted_path, load_merged_ngram_embedding, \
- open_ngram_mmap_table, MmapEmbedding, _force_meta_embeddings
+ open_ngram_mmap_table, MmapEmbedding, _force_meta_embeddings, default_device
from .persist import ModelPersister
try:
@@ -81,7 +81,7 @@ class AirLLMBaseModel:
'norm': 'model.norm',
'lm_head': 'lm_head'}
- def __init__(self, model_local_path_or_repo_id, device="cuda:0", dtype=None, max_seq_len=512,
+ def __init__(self, model_local_path_or_repo_id, device=None, dtype=None, max_seq_len=512,
layer_shards_saving_path=None, profiling_mode=False, compression=None,
hf_token=None, prefetching=True, delete_original=False,
install_hooks=True, load_resident=True):
@@ -91,7 +91,8 @@ class AirLLMBaseModel:
model_local_path_or_repo_id : str or Path
path to the local model checkpoint or huggingface repo id
device : str, optional
- device, by default "cuda:0"
+ runtime device. By default the best available is picked: CUDA, else Apple MPS,
+ else CPU. Pass an explicit value (e.g. "cuda:1", "cpu") to override.
dtype : torch.dtype, optional
runtime dtype; defaults to the model's own config.torch_dtype (usually bfloat16 for
modern models). float16 has too narrow a range for very deep models and overflows to
@@ -146,7 +147,7 @@ class AirLLMBaseModel:
hf_token=hf_token,
delete_original=delete_original)
- self.running_device = device
+ self.running_device = device if device is not None else default_device()
self.device = torch.device(self.running_device)
# Prefer transformers' native implementation; only trust the model's bundled remote code when
diff --git a/air_llm/airllm/utils.py b/air_llm/airllm/utils.py
index 75740db..a6d6407 100644
--- a/air_llm/airllm/utils.py
+++ b/air_llm/airllm/utils.py
@@ -85,6 +85,22 @@ def clean_memory():
torch.cuda.empty_cache()
+def default_device():
+ """Pick the best device available, instead of assuming CUDA.
+
+ AirLLM's public API defaulted to ``cuda:0``, so a plain
+ ``AutoModel.from_pretrained(repo_id)`` raised on any machine without an NVIDIA GPU -- Apple
+ silicon, a CPU-only box, or a container without the runtime -- even though the layer-streaming
+ path itself is device-agnostic. Prefer CUDA (where the VRAM savings matter), then Apple's MPS
+ backend, then CPU.
+ """
+ if torch.cuda.is_available():
+ return "cuda:0"
+ if getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available():
+ return "mps"
+ return "cpu"
+
+
def uncompress_layer_state_dict(layer_state_dict):
uncompressed_layer_state_dict = None
if any(['4bit' in k for k in layer_state_dict.keys()]):
diff --git a/air_llm/inference_example.py b/air_llm/inference_example.py
index 72f7d40..dddb4c7 100644
--- a/air_llm/inference_example.py
+++ b/air_llm/inference_example.py
@@ -20,7 +20,7 @@ input_tokens = model.tokenizer(input_text,
padding=True)
generation_output = model.generate(
- input_tokens['input_ids'].cuda(),
+ input_tokens['input_ids'].to(model.device),
max_new_tokens=2,
use_cache=True,
return_dict_in_generate=True)
diff --git a/air_llm/tests/test_default_device.py b/air_llm/tests/test_default_device.py
new file mode 100644
index 0000000..2397d71
--- /dev/null
+++ b/air_llm/tests/test_default_device.py
@@ -0,0 +1,66 @@
+import unittest
+
+import torch
+
+import airllm.utils as utils
+from airllm.airllm_base import AirLLMBaseModel
+from airllm.utils import default_device
+
+
+class TestDefaultDevice(unittest.TestCase):
+ """
+ A plain AutoModel.from_pretrained(repo_id) used to hard-code cuda:0, so it raised on any
+ machine without an NVIDIA GPU even though layer streaming is device-agnostic.
+ """
+
+ def setUp(self):
+ self._cuda = torch.cuda.is_available
+ self._mps = getattr(torch.backends, 'mps', None)
+
+ def tearDown(self):
+ torch.cuda.is_available = self._cuda
+ if self._mps is not None:
+ torch.backends.mps.is_available = self._mps.is_available
+
+ def _fake(self, cuda, mps):
+ torch.cuda.is_available = lambda: cuda
+ if getattr(torch.backends, 'mps', None) is not None:
+ torch.backends.mps.is_available = lambda: mps
+
+ def test_prefers_cuda_when_available(self):
+ self._fake(cuda=True, mps=False)
+ self.assertEqual(default_device(), 'cuda:0')
+
+ def test_falls_back_to_mps_on_apple_silicon(self):
+ if getattr(torch.backends, 'mps', None) is None:
+ self.skipTest('this torch build has no mps backend to fall back to')
+ self._fake(cuda=False, mps=True)
+ self.assertEqual(default_device(), 'mps')
+
+ def test_falls_back_to_cpu_when_no_accelerator(self):
+ self._fake(cuda=False, mps=False)
+ self.assertEqual(default_device(), 'cpu')
+
+ def test_cuda_preferred_over_mps(self):
+ self._fake(cuda=True, mps=True)
+ self.assertEqual(default_device(), 'cuda:0')
+
+ def test_init_uses_default_device_when_none_passed(self):
+ # The __init__ default is now None, resolved via default_device().
+ self._fake(cuda=False, mps=False)
+ obj = AirLLMBaseModel.__new__(AirLLMBaseModel) # skip the heavy __init__
+ device = None
+ obj.running_device = device if device is not None else utils.default_device()
+ self.assertEqual(obj.running_device, 'cpu')
+
+ def test_explicit_device_is_still_honoured(self):
+ # Control: an explicit device must win over auto-detection, even a "wrong" one.
+ self._fake(cuda=True, mps=False)
+ for explicit in ('cpu', 'cuda:1', 'mps'):
+ device = explicit
+ resolved = device if device is not None else utils.default_device()
+ self.assertEqual(resolved, explicit)
+
+
+if __name__ == '__main__':
+ unittest.main()