Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-s1): load Cua-S1-4B sequentially on Apple silicon mps (#4200)
Francesco Bonacci657a0c9ea576
diff --git a/libs/cua-s1/python/src/cua_s1/four_b.py b/libs/cua-s1/python/src/cua_s1/four_b.pyindex 242bafa952..529ff21c61 100644--- a/libs/cua-s1/python/src/cua_s1/four_b.py+++ b/libs/cua-s1/python/src/cua_s1/four_b.py@@ -31,7 +31,10 @@ libraries are only imported inside `FourBModel.load`.from __future__ import annotations+import osimport string+from collections.abc import Iterator+from contextlib import contextmanagerfrom dataclasses import dataclassfrom pathlib import Path@@ -39,6 +42,39 @@ DEFAULT_BASE_MODEL = "Qwen/Qwen3.5-4B"LETTERS = string.ascii_uppercase # "A".."Z" -- enough letters for any realistic option set+# Transformers 5 materializes checkpoint tensors on a thread pool unless this+# variable is true. On Apple silicon, concurrent dtype casts onto `mps` (for+# example bf16 checkpoint shards loaded as float16) can segfault or hang+# during `from_pretrained`, so `FourBModel.load` turns it on for `mps` loads.+ASYNC_LOAD_ENV = "HF_DEACTIVATE_ASYNC_LOAD"+++def needs_sync_weight_loading(device: str) -> bool:+ """Return whether weights for `device` must be materialized sequentially.++ Only Apple's `mps` backend (`"mps"` or `"mps:<index>"`) needs it; CUDA and+ CPU keep Transformers' default threaded loader.+ """+ return str(device).strip().lower().split(":", 1)[0] == "mps"+++@contextmanager+def sync_weight_loading(enabled: bool) -> Iterator[None]:+ """Set `HF_DEACTIVATE_ASYNC_LOAD=1` for the duration of a model load.++ Does nothing when `enabled` is false or when the caller already set the+ variable explicitly (any value), so an explicit environment choice always+ wins. The previous environment is restored afterwards.+ """+ if not enabled or ASYNC_LOAD_ENV in os.environ:+ yield+ return+ os.environ[ASYNC_LOAD_ENV] = "1"+ try:+ yield+ finally:+ os.environ.pop(ASYNC_LOAD_ENV, None)+@dataclass(frozen=True)class Option:@@ -275,13 +311,16 @@ class FourBModel:model_cls = (AutoModelForImageTextToText if self.modality == "multimodal" else AutoModelForCausalLM)- model = model_cls.from_pretrained(- self.base_model, torch_dtype=torch_dtype, device_map=self.device- )- if self.lora_adapter_path:- from peft import PeftModel+ # Sequential materialization on `mps` avoids a crash or hang in+ # Transformers' threaded loader; see `ASYNC_LOAD_ENV`.+ with sync_weight_loading(needs_sync_weight_loading(self.device)):+ model = model_cls.from_pretrained(+ self.base_model, torch_dtype=torch_dtype, device_map=self.device+ )+ if self.lora_adapter_path:+ from peft import PeftModel- model = PeftModel.from_pretrained(model, str(self._resolve_adapter_path()))+ model = PeftModel.from_pretrained(model, str(self._resolve_adapter_path()))model.eval()self._model = modeldiff --git a/libs/cua-s1/python/tests/test_four_b.py b/libs/cua-s1/python/tests/test_four_b.pyindex 30d488cc37..9cfb5b6fc4 100644--- a/libs/cua-s1/python/tests/test_four_b.py+++ b/libs/cua-s1/python/tests/test_four_b.py@@ -3,10 +3,13 @@ from __future__ import annotationsimport pytestfrom cua_s1.four_b import (+ ASYNC_LOAD_ENV,Option,OptionProbability,assign_letters,build_prompt,+ needs_sync_weight_loading,+ sync_weight_loading,)@@ -89,6 +92,49 @@ def test_build_prompt_rejects_unknown_modality():build_prompt(assignment, app="TestApp", task_family="forms", ax_tree="x", modality="bogus")+ ("device", "expected"),+ [+ ("mps", True),+ ("mps:0", True),+ (" MPS ", True),+ ("cuda", False),+ ("cuda:0", False),+ ("cpu", False),+ ("auto", False),+ ],+)+def test_needs_sync_weight_loading_only_for_mps(device, expected):+ assert needs_sync_weight_loading(device) is expected+++def test_sync_weight_loading_sets_and_restores_the_async_load_switch(monkeypatch):+ import os++ monkeypatch.delenv(ASYNC_LOAD_ENV, raising=False)++ with sync_weight_loading(True):+ assert os.environ[ASYNC_LOAD_ENV] == "1"+ assert ASYNC_LOAD_ENV not in os.environ++ with sync_weight_loading(False):+ assert ASYNC_LOAD_ENV not in os.environ++ with pytest.raises(RuntimeError), sync_weight_loading(True):+ raise RuntimeError("load failed")+ assert ASYNC_LOAD_ENV not in os.environ+++def test_sync_weight_loading_keeps_an_explicit_environment_choice(monkeypatch):+ import os++ monkeypatch.setenv(ASYNC_LOAD_ENV, "0")++ with sync_weight_loading(True):+ assert os.environ[ASYNC_LOAD_ENV] == "0"+ assert os.environ[ASYNC_LOAD_ENV] == "0"++torch = pytest.importorskip("torch")from cua_s1.four_b import FourBModel # noqa: E402@@ -197,3 +243,40 @@ def test_letter_token_ids_rejects_multi_token_letters():with pytest.raises(ValueError, match="single token"):model._letter_token_ids(assignment)++[email protected](("device", "expected"), [("mps", "1"), ("cpu", None), ("cuda", None)])+def test_load_disables_threaded_weight_loading_only_on_mps(monkeypatch, device, expected):+ import os++ import sys+ import types++ monkeypatch.delenv(ASYNC_LOAD_ENV, raising=False)+ seen: dict[str, object] = {}++ class _FakeAuto:+ @staticmethod+ def from_pretrained(name, **kwargs):+ seen["async_env"] = os.environ.get(ASYNC_LOAD_ENV)+ seen["device_map"] = kwargs.get("device_map")+ return _FakeModel(favored_index=0, num_positions=1, vocab_size=1)++ class _NoProcessor:+ @staticmethod+ def from_pretrained(name, **kwargs):+ raise OSError("no processor")++ # A stand-in `transformers` module keeps this test offline and independent+ # of whether the `four-b` extra is installed.+ fake_transformers = types.ModuleType("transformers")+ fake_transformers.AutoTokenizer = _FakeAuto+ fake_transformers.AutoProcessor = _NoProcessor+ fake_transformers.AutoModelForCausalLM = _FakeAuto+ fake_transformers.AutoModelForImageTextToText = _FakeAuto+ monkeypatch.setitem(sys.modules, "transformers", fake_transformers)++ FourBModel(base_model="local-base", device=device, dtype="float16").load()++ assert seen == {"async_env": expected, "device_map": device}+ assert ASYNC_LOAD_ENV not in os.environ