Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

test(stream): resolve mps in the streamed builders and run the 32 skipped cases on MPS (#1355) (#1375)

Momoyeyu26111cf022bc
diff --git a/tests/conftest.py b/tests/conftest.py
index 15a64b67..b0f3a077 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -58,6 +58,31 @@ def cuda_available() -> bool:
return False
[email protected]_cache(maxsize=None)
+def mps_is_the_accelerator() -> bool:
+ """True on Apple Silicon with no CUDA, where ``TrainingArguments`` picks ``mps`` (#1355)."""
+ if cuda_available():
+ return False
+ try:
+ import torch
+
+ backend = getattr(torch.backends, "mps", None)
+ return bool(backend is not None and backend.is_available())
+ except Exception: # noqa: BLE001 — a broken torch install counts as no MPS
+ return False
+
+
+def accelerator_device() -> str:
+ """The device ``TrainingArguments`` picks by itself: cuda, else mps, else cpu (#1355).
+
+ A streamed-model test that runs a trainer step builds on it, so model and batches agree;
+ building on ``cpu`` on an MPS host fails the first step on a device mismatch.
+ """
+ if cuda_available():
+ return "cuda"
+ return "mps" if mps_is_the_accelerator() else "cpu"
+
+
#: Rich/Pygments emit SGR escapes *between* the tokens of one logical line, so a
#: multi-token substring like "modality: text" is absent from raw output and
#: yaml.safe_load rejects \x1b outright (#633). 38 test files had grown their
diff --git a/tests/test_issue1011_streamed_save_guard.py b/tests/test_issue1011_streamed_save_guard.py
index cfde4396..b123fe01 100644
--- a/tests/test_issue1011_streamed_save_guard.py
+++ b/tests/test_issue1011_streamed_save_guard.py
@@ -18,8 +18,6 @@ from types import SimpleNamespace
import pytest
-from tests.test_v07204 import _mps_is_the_accelerator
-
pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning")
STREAMABLE_TRAINERS = ("sft", "dpo", "orpo", "simpo", "kto")
@@ -299,10 +297,6 @@ def test_the_streamable_task_list_matches_the_schema():
assert trainers == set(STREAMABLE_TRAINERS)
- _mps_is_the_accelerator(),
- reason="MPS is untested for layer streaming (CUDA + CPU only)",
-)
@pytest.mark.parametrize("task", STREAMABLE_TRAINERS)
def test_a_real_streamed_train_checks_every_checkpoint_and_the_final_save(
tmp_path, monkeypatch, task
diff --git a/tests/test_issue1049_untied_streamed_preference.py b/tests/test_issue1049_untied_streamed_preference.py
index 8979919a..4e60f96d 100644
--- a/tests/test_issue1049_untied_streamed_preference.py
+++ b/tests/test_issue1049_untied_streamed_preference.py
@@ -23,7 +23,6 @@ from tests.test_v07204 import (
_build_streamed_wrapper,
_loss_of,
_match_streamed_dtype,
- _mps_is_the_accelerator,
_randomise_lora_b,
_sync_adapters,
)
@@ -31,9 +30,6 @@ from tests.test_v07204 import (
pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning")
- _mps_is_the_accelerator(), reason="MPS is untested for layer streaming (CUDA + CPU only)"
-)
@pytest.mark.parametrize("task", [*_ALL_PREFERENCE, "sft"])
def test_an_untied_streamed_train_step_completes(tmp_path, monkeypatch, task):
"""dpo and kto raise on main; orpo, simpo and sft pass there and must keep passing.
@@ -274,9 +270,6 @@ def test_a_real_lora_wrapped_embedding_is_still_exempt_from_the_private_copy():
assert layer._needs_a_private_weight() is False
- _mps_is_the_accelerator(), reason="MPS is untested for layer streaming (CUDA + CPU only)"
-)
@pytest.mark.parametrize("task", [*_ALL_PREFERENCE, "sft"])
def test_only_a_loss_with_a_reference_pass_takes_the_private_copy(tmp_path, monkeypatch, task):
"""The copy is a head-sized allocation held for the whole graph (~1.05 GiB for an
diff --git a/tests/test_issue1174_head_prefetch_after_lookup.py b/tests/test_issue1174_head_prefetch_after_lookup.py
index ebae8cd2..65475824 100644
--- a/tests/test_issue1174_head_prefetch_after_lookup.py
+++ b/tests/test_issue1174_head_prefetch_after_lookup.py
@@ -26,15 +26,9 @@ import pytest
from tests.test_v07204 import (
_batch_on,
_build_streamed_wrapper,
- _mps_is_the_accelerator,
_randomise_lora_b,
)
-_NO_MPS = pytest.mark.skipif(
- _mps_is_the_accelerator(),
- reason="MPS is untested for layer streaming (CUDA + CPU only)",
-)
-
# --------------------------------------------------------------------------
# the trigger, in isolation
@@ -225,7 +219,6 @@ def _assert_identical(arm_a, arm_b):
assert torch.equal(weights_a[name], weights_b[name]), f"final weight {name} differs"
-@_NO_MPS
class TestBothTimingsAreBitIdentical:
"""Moving the head's load must change WHEN the copy is issued, never what the
step computes. The arms differ only in `head_prefetch_layer`."""
@@ -261,7 +254,6 @@ class TestBothTimingsAreBitIdentical:
_assert_identical(arm_a, arm_b)
-@_NO_MPS
class TestTheInstalledDefault:
"""The arms above set `head_prefetch_layer` themselves, so nothing there covers
what `install_streaming` wires when nobody touches it."""
@@ -293,7 +285,6 @@ def _real(events, needle):
return [prev for key, prev, real in events if real and needle in key]
-@_NO_MPS
class TestTheLoadsMoveButDoNotMultiply:
def test_the_head_load_comes_at_the_configured_layer(self, tmp_path, monkeypatch):
_, _, _, events_last = _run_arm(tmp_path / "a", monkeypatch, head_layer=None)
diff --git a/tests/test_issue1355_accelerator_device.py b/tests/test_issue1355_accelerator_device.py
new file mode 100644
index 00000000..3e918abd
--- /dev/null
+++ b/tests/test_issue1355_accelerator_device.py
@@ -0,0 +1,47 @@
+"""#1355 — the streamed builders build on the device `TrainingArguments` picks by itself.
+
+Pinned without a Mac or a card: otherwise the MPS branch of the resolver only ever
+runs on the macOS cells, and the CUDA branch only on a GPU box.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from tests import conftest
+
+
+def fake_accelerators(monkeypatch):
+ """Fake `torch.cuda` and `torch.backends.mps`; both probes are cached, so clear them."""
+ import torch
+
+ def apply(*, cuda: bool, mps: bool | None) -> None:
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: cuda)
+ backend = None if mps is None else SimpleNamespace(is_available=lambda: mps)
+ monkeypatch.setattr(torch.backends, "mps", backend, raising=False)
+ conftest.cuda_available.cache_clear()
+ conftest.mps_is_the_accelerator.cache_clear()
+
+ yield apply
+ # Runs before monkeypatch restores torch, so the next caller re-probes the real one.
+ conftest.cuda_available.cache_clear()
+ conftest.mps_is_the_accelerator.cache_clear()
+
+
+ ("cuda", "mps", "expected"),
+ [
+ (True, True, "cuda"),
+ (True, False, "cuda"),
+ (False, True, "mps"),
+ (False, False, "cpu"),
+ (False, None, "cpu"), # a torch build with no torch.backends.mps at all
+ ],
+)
+def test_the_builders_device_is_cuda_then_mps_then_cpu(fake_accelerators, cuda, mps, expected):
+ fake_accelerators(cuda=cuda, mps=mps)
+ assert conftest.accelerator_device() == expected
+ assert conftest.mps_is_the_accelerator() is (expected == "mps")
diff --git a/tests/test_issue975_backward_tail_embed_prefetch.py b/tests/test_issue975_backward_tail_embed_prefetch.py
index e8ab404f..db06077e 100644
--- a/tests/test_issue975_backward_tail_embed_prefetch.py
+++ b/tests/test_issue975_backward_tail_embed_prefetch.py
@@ -28,10 +28,9 @@ from __future__ import annotations
import pytest
-from tests.conftest import cuda_available
+from tests.conftest import accelerator_device
from tests.test_v07204 import (
_TASK_ROWS,
- _mps_is_the_accelerator,
_stream_cfg,
_tiny_llama_dir,
_wrapper_for,
@@ -46,11 +45,11 @@ def _build_untied_wrapper(tmp_path, monkeypatch, task="sft", n_layers=2, **train
monkeypatch.chdir(tmp_path)
cfg = _stream_cfg(weights, tmp_path / "out", task=task, **training)
# The real accelerator when there is one, like `_build_streamed_wrapper`:
- # `TrainingArguments` picks CUDA on its own, so pinning the model to the CPU
- # there sends the batches to `cuda:0` and the embedding lookup fails on a
- # device mismatch. None of these tests compares floats, so nothing needs
- # the exact CPU arithmetic that pinning would buy.
- device = "cuda" if cuda_available() else "cpu"
+ # `TrainingArguments` picks CUDA or MPS on its own, so pinning the model to
+ # the CPU there sends the batches to the accelerator and the embedding lookup
+ # fails on a device mismatch. None of these tests compares floats, so nothing
+ # needs the exact CPU arithmetic that pinning would buy.
+ device = accelerator_device()
wrapper = _wrapper_for(task)(cfg, device=device)
wrapper.setup({"train": _TASK_ROWS[task](8)})
return wrapper, resident, weights
@@ -61,14 +60,6 @@ class TestBackwardTailEmbedPrefetch:
slot, and the fix moves the embedding's reload from the next step's
`_prime()` to this step's backward tail."""
- # With no CUDA, `_build_untied_wrapper` falls back to the CPU, and on a box
- # where MPS is the accelerator that is a device mismatch no user would ever
- # hit, not something this fix is responsible for.
- pytestmark = pytest.mark.skipif(
- _mps_is_the_accelerator(),
- reason="MPS is untested for layer streaming (CUDA + CPU only)",
- )
-
def test_untied_fixture_actually_shares_one_slot(self, tmp_path, monkeypatch):
"""Guard: if the fixture ever stopped being untied, the rest of this
file would pass vacuously (a tied model never re-copies at all)."""
diff --git a/tests/test_v07200.py b/tests/test_v07200.py
index 47b9a998..0ea0be4d 100644
--- a/tests/test_v07200.py
+++ b/tests/test_v07200.py
@@ -11,7 +11,7 @@ import os
import pytest
-from tests.conftest import cuda_available
+from tests.conftest import accelerator_device, mps_is_the_accelerator
# ==========================================================================
@@ -1227,25 +1227,6 @@ class TestStreamBufferBounds:
# runs and still converges. That is exactly why they are tests, not comments.
# ==========================================================================
-def _mps_is_the_accelerator():
- """True on an Apple-Silicon runner with no CUDA.
-
- transformers picks `mps` as its default device there, while this suite
- builds the streamed model on `cpu` — the two then disagree and any real
- training step raises "found at least two devices". Most historical step
- tests therefore stay on CPU; dedicated MPS controls exercise the hardware
- path explicitly.
- """
- try:
- import torch
-
- if cuda_available():
- return False
- backend = getattr(torch.backends, "mps", None)
- return bool(backend is not None and backend.is_available())
- except Exception:
- return False
-
def _tiny_llama_dir(tmp_path, n_layers=2, tie=True):
"""A real (tiny) Llama checkpoint on disk: config.json + model.safetensors."""
@@ -1739,7 +1720,7 @@ class TestStreamedForwardParityCpu:
assert torch.equal(two(input_ids=ids).logits, three(input_ids=ids).logits)
[email protected](not _mps_is_the_accelerator(), reason="needs Apple Silicon MPS")
[email protected](not mps_is_the_accelerator(), reason="needs Apple Silicon MPS")
class TestStreamedLargeLayerParityMps:
def test_untied_logits_match_resident(self, tmp_path):
"""Supplementary #324 hardware control; the required CI oracle is CPU."""
@@ -2495,10 +2476,10 @@ class TestStreamingEndToEndSetup:
for _ in range(4)
]
}
- # Use the REAL device: TrainingArguments picks cuda when it is
+ # Use the REAL device: TrainingArguments picks cuda or mps when one is
# available, so forcing the model to cpu here would only produce a
# device mismatch that no user would ever hit.
- device = "cuda" if cuda_available() else "cpu"
+ device = accelerator_device()
return SFTTrainerWrapper(cfg, device=device), dataset
def test_setup_builds_a_real_trl_trainer(self, tmp_path, monkeypatch):
@@ -2514,10 +2495,6 @@ class TestStreamingEndToEndSetup:
wrapper.setup(dataset)
assert wrapper.trainer.args.gradient_checkpointing is False
- @pytest.mark.skipif(
- _mps_is_the_accelerator(),
- reason="MPS is untested in v0.72.0 (measured on CUDA + CPU only)",
- )
def test_one_training_step_actually_runs(self, tmp_path, monkeypatch):
"""Forward + backward + optimizer step through the streamed layers."""
wrapper, dataset = self._wrapper(tmp_path, monkeypatch)
diff --git a/tests/test_v07202.py b/tests/test_v07202.py
index 780ff2f2..f663a28c 100644
--- a/tests/test_v07202.py
+++ b/tests/test_v07202.py
@@ -26,35 +26,14 @@ import sys
import pytest
-from tests.conftest import cuda_available
+from tests.conftest import accelerator_device, mps_is_the_accelerator
pytestmark = pytest.mark.filterwarnings("ignore::UserWarning")
-def _mps_is_the_accelerator() -> bool:
- """True on an Apple-Silicon runner with no CUDA.
-
- ``TrainingArguments`` picks ``mps`` as its device there, while this suite
- builds the streamed model on ``cpu``; a real training step then moves the
- batch to MPS and hits "Placeholder storage has not been allocated on MPS
- device". NF4 streaming is measured on CUDA and CPU only — bitsandbytes'
- 4-bit kernels are not supported on MPS at all — so the step is skipped
- rather than making an unverified claim about it. Mirrors the identical
- guard in tests/test_v07200.py.
- """
- try:
- import torch
-
- if cuda_available():
- return False
- backend = getattr(torch.backends, "mps", None)
- return bool(backend is not None and backend.is_available())
- except Exception:
- return False
-
-
+# Not one of the #1355 "untested" skips: bitsandbytes has no 4-bit MPS kernels.
skip_on_mps = pytest.mark.skipif(
- _mps_is_the_accelerator(),
+ mps_is_the_accelerator(),
reason="MPS is untested for NF4 streaming (measured on CUDA + CPU only)",
)
@@ -1829,7 +1808,7 @@ class TestNF4EndToEndSetup:
for _ in range(4)
]
}
- device = "cuda" if cuda_available() else "cpu"
+ device = accelerator_device()
return SFTTrainerWrapper(cfg, device=device), dataset
def test_setup_builds_a_real_trl_trainer_under_nf4(self, tmp_path, monkeypatch):
diff --git a/tests/test_v07204.py b/tests/test_v07204.py
index 42aa81c8..2603fd56 100644
--- a/tests/test_v07204.py
+++ b/tests/test_v07204.py
@@ -20,7 +20,7 @@ import os
import pytest
-from tests.conftest import cuda_available
+from tests.conftest import accelerator_device, cuda_available, mps_is_the_accelerator
# ==========================================================================
# fixtures (mirroring tests/test_v07200.py so the two cannot drift)
@@ -38,19 +38,6 @@ def _torch_version():
return "unknown"
-def _mps_is_the_accelerator():
- try:
- import torch
-
- return (
- hasattr(torch.backends, "mps")
- and torch.backends.mps.is_available()
- and not cuda_available()
- )
- except Exception: # pragma: no cover
- return False
-
-
def _tiny_llama_dir(tmp_path, n_layers=2, tie=True, vocab=64, hidden=64):
"""A real (tiny) Llama checkpoint on disk: config.json + model.safetensors.
@@ -248,7 +235,8 @@ def _loss_of(trainer, model, batch):
def _match_streamed_dtype(resident, streamed):
"""Put the resident reference on the streamed model's device AND dtype.
- Streaming picks bf16 on CUDA and float32 on CPU. Comparing a float32
+ Streaming picks bf16 on CUDA, bf16 on MPS when the runtime accepts it
+ (float32 otherwise), and float32 on CPU. Comparing a float32
resident model against a bf16 streamed one measures the dtype gap, not the
streaming path — that mistake produced a 9.96e-04 "failure" that was
entirely the test's own.
@@ -360,10 +348,11 @@ def _build_streamed_wrapper(
"""Build a task wrapper through the REAL `setup()` path, streaming.
``device`` defaults to the real accelerator, because `TrainingArguments`
- picks CUDA when it is available and forcing CPU there would only produce a
- device mismatch no user would ever hit. Numerical-equality tests pass
- ``device='cpu'`` deliberately: the streaming path uses float32 on CPU and
- bf16 on CUDA, and "bit-exact" is only a meaningful assertion in the former
+ picks CUDA or MPS when one is available and forcing CPU there would only
+ produce a device mismatch no user would ever hit. Numerical-equality tests pass
+ ``device='cpu'`` deliberately: the streaming path uses float32 on CPU, bf16
+ on CUDA, and bf16 on MPS when the runtime accepts it (float32 otherwise),
+ and "bit-exact" is only a meaningful assertion in float32
(a bf16 logp of -12.75 cannot represent a change smaller than ~0.05).
"""
weights, resident, _ = _tiny_llama_dir(
@@ -375,7 +364,7 @@ def _build_streamed_wrapper(
training.setdefault("batch_size", _MIN_BATCH.get(task, 1))
cfg = _stream_cfg(weights, tmp_path / "out", task=task, **training)
if device is None:
- device = "cuda" if cuda_available() else "cpu"
+ device = accelerator_device()
wrapper = _wrapper_for(task)(cfg, device=device)
wrapper.setup({"train": _TASK_ROWS[task](8)})
return wrapper, resident, weights
@@ -682,10 +671,6 @@ class TestBitExactVsResident:
assert next(matched.parameters()).device.type == "cpu"
assert next(matched.parameters()).dtype is torch.float64
- @pytest.mark.skipif(
- _mps_is_the_accelerator(),
- reason="MPS is untested for layer streaming (CUDA + CPU only)",
- )
@pytest.mark.parametrize("task", _ALL_PREFERENCE)
def test_loss_matches_a_resident_run_of_the_same_loss(self, tmp_path, monkeypatch, task):
import torch
@@ -726,10 +711,6 @@ class TestBitExactVsResident:
diff = (streamed_loss - resident_loss).abs().max().item()
assert diff == 0.0, f"{task}: streamed vs resident loss differs by {diff}"
- @pytest.mark.skipif(
- _mps_is_the_accelerator(),
- reason="MPS is untested for layer streaming (CUDA + CPU only)",
- )
@pytest.mark.parametrize("task", _ALL_PREFERENCE)
def test_layer_zero_adapter_receives_gradient(self, tmp_path, monkeypatch, task):
"""plan P2: a `detach()`/`no_grad()` anywhere in the base forward severs
@@ -990,10 +971,6 @@ class TestKtoNeedsMoreThanOneRow:
cfg = _stream_cfg(str(tmp_path / "m"), tmp_path / "o", task="kto", batch_size=2)
assert cfg.training.batch_size == 2
- @pytest.mark.skipif(
- _mps_is_the_accelerator(),
- reason="MPS is untested for layer streaming (CUDA + CPU only)",
- )
def test_kto_streams_at_batch_two(self, tmp_path, monkeypatch):
"""Runs EVERYWHERE, and tolerates exactly one known failure signature.
@@ -1015,7 +992,7 @@ class TestKtoNeedsMoreThanOneRow:
more ops, which is why only the newer stack surfaces it. Tracked as #328
rather than absorbed into a device rule.
- So: tolerate that one signature on CPU and nothing else. Any other
+ So: tolerate that one signature without CUDA (CPU or MPS) and nothing else. Any other
exception, and the same signature on CUDA, is a hard failure — and when
the leak is fixed this XPASSes instead of quietly staying skipped.
"""
@@ -1045,10 +1022,6 @@ class TestTheReferenceForwardActuallyHappens:
model. Pinned so an "optimisation" that silently drops or caches the
reference forward cannot pass unnoticed."""
- @pytest.mark.skipif(
- _mps_is_the_accelerator(),
- reason="MPS is untested for layer streaming (CUDA + CPU only)",
- )
@pytest.mark.parametrize("task", _REFERENCE_USING)
def test_a_reference_using_loss_reads_more_layers_than_sft(self, tmp_path, monkeypatch, task):
def reads_for(task, root):
@@ -1238,7 +1211,7 @@ class TestNf4CombinesWithEveryPreferenceLoss:
SmolLM2-135M). A name drift in any one copy is otherwise invisible."""
@pytest.mark.skipif(
- _mps_is_the_accelerator(),
+ mps_is_the_accelerator(),
reason="bitsandbytes has no 4-bit MPS kernels",
)
@pytest.mark.parametrize("task", _ALL_PREFERENCE)