Skip to content

Fix MPS tensor threshold to properly tile 2048×2048 VAE decodes - #12

Merged
lmangani merged 2 commits into
mainfrom
copilot/patch-mps-tensor-size-limit
Feb 18, 2026
Merged

lmangani merged 2 commits into
mainfrom
copilot/patch-mps-tensor-size-limit

Conversation

Copilot AI commented Feb 18, 2026 •

Copy link
Copy Markdown

The MPS tensor size threshold was set too high (100M elements), causing 2048×2048 images (~16.7M output elements) to bypass tiling and fail the strategy validation test.

Changes

  • Lowered MPS_TENSOR_SIZE_THRESHOLD from 100M to 15M elements

    • Creates proper strategy tiers based on actual image sizes:
      • < 15M: Pass through (512×512, 1024×1024)
      • 15M–75M: Tiled decode on MPS (2048×2048, 4096×4096)
      • > 75M: CPU fallback (8192×8192+)
  • Updated threshold documentation

    • Clarifies the rationale for 15M threshold
    • Explains the three-tier strategy with concrete image size examples

Impact

2048×2048 images now correctly trigger tiled decode instead of pass-through, aligning implementation with validation expectations and preventing potential MPS INT_MAX failures on larger intermediate tensors.

The environment variable PYTORCH_ENABLE_MPS_FALLBACK=1 remains set for uncaught edge cases.

Original prompt

This section details on the original issue you should resolve

<issue_title>Exception during processing: MPSGaph does not support tensor dims larger than INT_MAX on Apple MPS</issue_title>
<issue_description>Exception during processing: MPSGaph does not support tensor dims larger than INT_MAX

The following patch has been proposed:

monkey-patch from your custom node. Add this to your fp8-mps-metal init.py:
pythondef patch_vae_decode_for_mps_limits():
"""Force large VAE decodes to CPU to avoid MPS INT_MAX tensor size limit"""
import comfy.sd

original_decode = comfy.sd.VAE.decode

def patched_decode(self, samples_in, disable_patcher=False, **kwargs):
    # Check if samples are huge and on MPS
    if hasattr(samples_in, 'device') and samples_in.device.type == 'mps':
        numel = samples_in.numel()
        # If tensor has >100M elements, move to CPU to avoid MPS INT_MAX limit
        if numel > 100_000_000:
            print(f"[fp8-mps-metal] VAE decode tensor too large for MPS ({numel:,} elements), falling back to CPU")
            samples_in = samples_in.to('cpu')
            self.first_stage_model = self.first_stage_model.to('cpu')
            self.output_device = torch.device('cpu')
    
    return original_decode(self, samples_in, disable_patcher=disable_patcher, **kwargs)

comfy.sd.VAE.decode = patched_decode

Then in the install() function in fp8_mps_patch.py, add:
pythondef install():
"""Monkey-patch torch.scaled_mm, Tensor.to(), Tensor.copy(), and VAE.decode to use Metal FP8 kernels on MPS."""
global _original_scaled_mm, _original_tensor_to, _original_tensor_copy

# ... existing patches ...

# Patch VAE.decode for MPS tensor size limits
patch_vae_decode_for_mps_limits()

print("=" * 70)
print("✓ FP8 MPS Metal patch installed successfully!")
print("=" * 70)
# ... rest of install ...

Add the import at the top of fp8_mps_patch.py:
pythonimport torch
import comfy.sd # Add this
This way the patch lives entirely in your custom node and doesn't touch ComfyUI core files. The VAE will automatically fall back to CPU when tensors are too large for MPS.

We also want our extension to force export PYTORCH_ENABLE_MPS_FALLBACK=1 for any other uncaught exception.</issue_description>

<agent_instructions>The issue was reopened. We need to correct the previous patch according to the report.</agent_instructions>

Comments on the Issue (you are @copilot in this section)

@lmangani REOPENING. Strategy Thresholds Test fails with

% python3 mps_validation_script.py

======================================================================
FP8-MPS-METAL: Apple MPS Hardware Validation

This script validates the VAE tiling strategy on real MPS hardware

======================================================================
MPS AVAILABILITY CHECK

✓ MPS is available
PyTorch version: 2.8.0
MPS built: True

======================================================================
BASIC MPS TENSOR OPERATIONS

✓ Created tensor on MPS: torch.Size([100, 100]), device: mps:0
✓ Matrix multiply successful: torch.Size([100, 100])
✓ Device transfers working: CPU ↔ MPS

======================================================================
PATCH INSTALLATION TEST

[fp8-mps-metal] Set PYTORCH_ENABLE_MPS_FALLBACK=1 for automatic CPU fallback
[fp8-mps-metal] ComfyUI not available, skipping VAE decode patch
✓ Patch installed
✓ PYTORCH_ENABLE_MPS_FALLBACK = 1
✓ Patch state: installed

======================================================================
VAE TILING WITH MPS TENSORS

Test 1: Small tensor on MPS (no tiling)
Input: torch.Size([1, 4, 64, 64]), device: mps:0
Tiles: 1
✓ Pass

Test 2: Large tensor on MPS (requires tiling)
Input: torch.Size([1, 4, 512, 512]), device: mps:0, elements: 1,048,576
Tiles: 3
Tile 0: torch.Size([1, 4, 171, 512]), device: mps:0, elements: 350,208
Tile 1: torch.Size([1, 4, 171, 512]), device: mps:0, elements: 350,208
Tile 2: torch.Size([1, 4, 170, 512]), device: mps:0, elements: 348,160
✓ Pass: All tiles remain on MPS

Test 3: Tile reconstruction
Reconstructed: torch.Size([1, 3, 4096, 4096]), device: mps:0
Expected: (1, 3, 4096, 4096)
✓ Pass: Reconstruction preserves MPS device

======================================================================
STRATEGY THRESHOLD VALIDATION

MPS Threshold: 100,000,000 elements
VAE Upscale Factor: 64x

✓ 512×512 image (SD 1.5)
...


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix exception for large tensor dims on Apple MPS Fix MPS tensor threshold to properly tile 2048×2048 VAE decodes Feb 18, 2026
Copilot AI requested a review from lmangani February 18, 2026 11:19
@lmangani
lmangani marked this pull request as ready for review February 18, 2026 11:47
@lmangani
lmangani merged commit ca8c3b9 into main Feb 18, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Exception during processing: MPSGaph does not support tensor dims larger than INT_MAX on Apple MPS

2 participants