ACT icon indicating copy to clipboard operation
ACT copied to clipboard

InputSpec.eps device mismatch on non-CPU devices (MPS/CUDA)

Open jiachenhan opened this issue 7 months ago • 8 comments

Summary

InputSpec.__post_init__ creates the eps tensor without specifying a device, so it always lands on CPU. When center is on a non-CPU device (e.g. MPS or CUDA), the arithmetic center - eps raises a RuntimeError.

Location

act/front_end/specs.py — InputSpec.__post_init__

# before fix: no device= argument
self.eps = torch.tensor([float(self.eps)], dtype=torch.get_default_dtype())

Reproduction

def test_mps_eps_follows_center_device(self):
        """MPS: scalar eps must land on mps, not cpu, when center is on mps."""
        if not _mps_available():
            self.skipTest("MPS not available")
        from act.front_end.specs import InputSpec, InKind
        center = torch.zeros(1, 4, device='mps', dtype=torch.float32)
        spec = InputSpec(kind=InKind.LINF_BALL, center=center, eps=0.1)
        self._check_eps_matches(spec, torch.device('mps'))
        assert isinstance(spec.center, torch.Tensor) and isinstance(spec.eps, torch.Tensor)
        # This was the line that raised RuntimeError before the fix
        _ = spec.center - spec.eps

This is a latent bug that affects any non-CPU device, and it was not introduced by MPS support, only surfaced by it.

jiachenhan avatar Apr 14 '26 13:04 jiachenhan

Thanks for reporting this. We've traced the root cause — it's not just specs.py, but a broader pattern across the codebase where tensors are created without explicit device=/dtype=. We've applied fixes in PR #52 following these principles:

  1. Derive device/dtype from the nearest tensor in scope — e.g. device=center.device, device=weight_ih.device
  2. Use device_manager.get_default_dtype() for tensors created without a reference tensor — instead of torch.get_default_dtype(), to ensure a single source of truth
  3. Do not inject device_manager into transfer functions or solver internals — those derive device/dtype from their input tensors directly Affected files: verifier.py, tf_rnn.py, create_specs.py, specs.py, model_synthesis.py. The specs.py case you reported is covered — though the real fix there is at tensor creation time in the callers (e.g. create_specs.py), not in post_init, since VerifiableModel already handles device migration via register_buffer.

guanqin-123 avatar Apr 14 '26 23:04 guanqin-123

Thanks, maybe torchvision dataloader was missed in #52

Reproduce:

python -m act.pipeline --verify all --device mps --dtype float32

RuntimeError: Expected all tensors to be on the same device, but found mps:0 and cpu! # at model_synthesis.py:140 — s.center - s.eps

Root cause:

torch.set_default_device only affects factory functions, not DataLoader outputs. In torchvision_loader/create_specs.py, images from the DataLoader is always CPU.

Fix:

move DataLoader outputs to the target device at collection time in front_end/torchvision_loader/create_specs.py:209

jiachenhan avatar Apr 15 '26 10:04 jiachenhan

@guanqin-123 could you check?

yuleisui avatar Apr 15 '26 10:04 yuleisui

@guanqin-123 could you check?

I double checked and resolved here: #53. You can squash merge.

guanqin-123 avatar Apr 15 '26 22:04 guanqin-123

Thanks, maybe torchvision dataloader was missed in #52

Reproduce:

python -m act.pipeline --verify all --device mps --dtype float32

RuntimeError: Expected all tensors to be on the same device, but found mps:0 and cpu! # at model_synthesis.py:140 — s.center - s.eps

Root cause:

torch.set_default_device only affects factory functions, not DataLoader outputs. In torchvision_loader/create_specs.py, images from the DataLoader is always CPU.

Fix:

move DataLoader outputs to the target device at collection time in front_end/torchvision_loader/create_specs.py:209

I can I see the newly fixed part is already loaded on MPS #53 . But on my side, some of the Torch vision models are not accessible or properly loaded.


see below: 
`python -m act.front_end --download MNIST                                            
✅ Device Manager Initialized: device=mps, dtype=torch.float64

====================================================================================================
DOWNLOADING: MNIST (creator: torchvision)
====================================================================================================

Downloading dataset 'MNIST' with 4 models...

/opt/miniconda3/envs/act-py312/lib/python3.12/site-packages/torchvision/io/image.py:14: UserWarning: Failed to load image Python extension: 'dlopen(/opt/miniconda3/envs/act-py312/lib/python3.12/site-packages/torchvision/image.so, 0x0006): Library not loaded: @rpath/libjpeg.9.dylib
  Referenced from: <367D4265-B20F-34BD-94EB-4F3EE47C385B> /opt/miniconda3/envs/act-py312/lib/python3.12/site-packages/torchvision/image.so
  Reason: tried: '/opt/miniconda3/envs/act-py312/lib/python3.12/site-packages/torchvision/../../../libjpeg.9.dylib' (no such file), '/opt/miniconda3/envs/act-py312/lib/python3.12/site-packages/torchvision/../../../libjpeg.9.dylib' (no such file), '/opt/miniconda3/envs/act-py312/lib/python3.12/lib-dynload/../../libjpeg.9.dylib' (no such file), '/opt/miniconda3/envs/act-py312/bin/../lib/libjpeg.9.dylib' (no such file)'If you don't plan on using image functionality from `torchvision.io`, you can ignore this warning. Otherwise, there might be something wrong with your environment. Did you have `libjpeg` or `libpng` installed before building `torchvision` from source?
  warn(

================================================================================
PRE-DOWNLOAD VALIDATION: MNIST + simple_cnn
================================================================================
Model Type: custom (model_definitions.py)
Validation Results:
  • Model Loadable: False
  • Dataset-Model Compatible: False

❌ VALIDATION FAILED: Model 'simple_cnn' cannot be loaded.
   • Standard models must exist in torchvision.models
   • Custom models must be defined in model_definitions.py with get_model() support
✗ MNIST + simple_cnn - Error: ❌ VALIDATION FAILED: Model 'simple_cnn' cannot be loaded.
   • Standard models must exist in torchvision.models
   • Custom models must be defined in model_definitions.py with get_model() support` 

But when I download some by myself, it can be loaded. But now I cannot reproduce this above issue anymore. So can you try in you side? @jiachenhan If we have the same issue, I can make a plan to resolve it later.

guanqin-123 avatar Apr 15 '26 23:04 guanqin-123

@guanqin-123 With the fix of #53, the issue was resolved.

I try to remove the MNIST dataset, and redownload it successfully, although same warning about lack of libjpeg.

Some log as below:

UserWarning: Failed to load image Python extension: 'dlopen(/Users/jiachenhan/miniconda3/envs/act-py312/lib/python3.12/site-packages/torchvision/image.so, 0x0006): Library not loaded: @rpath/libjpeg.9.dylib
  Referenced from: <367D4265-B20F-34BD-94EB-4F3EE47C385B> /Users/jiachenhan/miniconda3/envs/act-py312/lib/python3.12/site-packages/torchvision/image.so
  Reason: tried: '/Users/jiachenhan/miniconda3/envs/act-py312/lib/python3.12/site-packages/torchvision/../../../libjpeg.9.dylib' (no such file), '/Users/jiachenhan/miniconda3/envs/act-py312/lib/python3.12/site-packages/torchvision/../../../libjpeg.9.dylib' (no such file), '/Users/jiachenhan/miniconda3/envs/act-py312/lib/python3.12/lib-dynload/../../libjpeg.9.dylib' (no such file), '/Users/jiachenhan/miniconda3/envs/act-py312/bin/../lib/libjpeg.9.dylib' (no such file)'If you don't plan on using image functionality from `torchvision.io`, you can ignore this warning. Otherwise, there might be something wrong with your environment. Did you have `libjpeg` or `libpng` installed before building `torchvision` from source?
  warn(

================================================================================
PRE-DOWNLOAD VALIDATION: MNIST + simple_cnn
================================================================================
Model Type: custom (model_definitions.py)
Validation Results:
  • Model Loadable: True
  • Dataset-Model Compatible: True
  • Inference Test: ✓ PASSED
  • Inference test: True

✓ Validation passed! Proceeding with download...
================================================================================

jiachenhan avatar Apr 16 '26 06:04 jiachenhan

ok. Good. The issue has been resolved.

guanqin-123 avatar Apr 16 '26 09:04 guanqin-123

Please close it, thanks

yuleisui avatar Apr 16 '26 09:04 yuleisui