Skip to content

Fix FP8 conversion corruption by separating value-preserving and scaled quantization - #4

Merged
lmangani merged 10 commits into
mainfrom
copilot/extend-float8-e4m3fn-support-another-one
Feb 13, 2026
Merged

lmangani merged 10 commits into
mainfrom
copilot/extend-float8-e4m3fn-support-another-one

Conversation

Copilot AI commented Feb 13, 2026 •

Copy link
Copy Markdown

FP8 conversions on MPS produced corrupted results (values scaled 100-400x) because fp8_quantize() applied automatic scaling to use the full FP8 range but the scale was lost since torch.float8_e4m3fn doesn't store metadata.

# Before: values corrupted
x = torch.tensor([1.0, 2.0, 3.0], device="mps")
x_fp8 = x.to(torch.float8_e4m3fn)
x_fp8.to(torch.float32)  # Returns [~149.33, ~298.67, ~448.0] ❌

# After: values preserved
x_fp8.to(torch.float32)  # Returns [~1.0, ~2.0, ~3.0] ✓

Changes

Core implementation:

  • Added fp8_encode() for value-preserving conversion (no automatic scaling)
  • Updated _metal_tensor_to() to use fp8_encode() for .to(dtype=torch.float8_e4m3fn)
  • Updated _metal_tensor_copy() to use fp8_encode() for float→FP8 copies
  • Added FP8→float dequantization support (uses scale=1.0)
  • Kept fp8_quantize() with scaling for torch._scaled_mm (backward compatible)

Affected code paths:

  • .to(torch.float8_e4m3fn): now preserves value semantics via fp8_encode()
  • .to(torch.float32) from FP8: now works via dequantization
  • .copy_() with FP8 destination: uses fp8_encode() for conversions
  • torch._scaled_mm: unchanged, still uses fp8_quantize() with explicit scales

The distinction: fp8_encode() treats FP8 as a data type (preserve values), while fp8_quantize() treats it as a storage format (maximize precision with separate scale management).

Original prompt

This section details on the original issue you should resolve

<issue_title>Float8_e4m3fn</issue_title>
<issue_description>```
Trying to convert Float8_e4m3fn to the MPS backend but it does not have support for that dtype.


Let's extend our patches to support Float8_e4m3fn conversions as per other types

</issue_description>

<agent_instructions>Resolve the re-opened issue carefully analyzing the problem and correcting the fp8 copy /conversion on MPS</agent_instructions>

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

<comments>
<comment_new><author>@lmangani</author><body>
Reopening the issue. The failure still persists for the .copy() operations on MPS fails:


# ComfyUI Error Report
## Error Details
- **Node ID:** 92:70
- **Node Type:** SamplerCustomAdvanced
- **Exception Type:** TypeError
- **Exception Message:** Trying to convert Float8_e4m3fn to the MPS backend but it does not have support for that dtype.

## Stack Trace

File "/Applications/ComfyUI.app/Contents/Resources/ComfyUI/execution.py", line 530, in execute
output_data, output_ui, has_subgraph, has_pending_tasks = await get_output_data(prompt_id, unique_id, obj, input_data_all, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb, v3_data=v3_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "/Applications/ComfyUI.app/Contents/Resources/ComfyUI/execution.py", line 334, in get_output_data
return_values = await _async_map_node_over_list(prompt_id, unique_id, obj, input_data_all, obj.FUNCTION, allow_interrupt=True, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb, v3_data=v3_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "/Applications/ComfyUI.app/Contents/Resources/ComfyUI/execution.py", line 308, in _async_map_node_over_list
await process_inputs(input_dict, i)

File "/Applications/ComfyUI.app/Contents/Resources/ComfyUI/execution.py", line 296, in process_inputs
result = f(**inputs)
^^^^^^^^^^^

File "/Applications/ComfyUI.app/Contents/Resources/ComfyUI/comfy_api/internal/init.py", line 149, in wrapped_func
return method(locked_class, **inputs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "/Applications/ComfyUI.app/Contents/Resour...</comment_new>
<comment_new>@lmangani
Reopening for fine tuning. The conversion now apparently works (no errors) but the results are completely corrupted.

This was the original CPU-fallback version, producing CORRECT results/conversions:

import torch
import sys

NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}

# Patch 1: ComfyUI's stochastic_rounding function
try:
    import comfy.float as comfy_float
    
    _original_stochastic_rounding = comfy_float.stochastic_rounding
    
    def patched_stochastic_rounding(value, dtype=torch.float8_e4m3fn, seed=0, generator=None):
        # MPS compatibility: perform float8 operations on CPU
        original_device = value.device
        needs_cpu = original_device.type == 'mps'
        
        if needs_cpu:
            value = value.cpu()
        
        if generator is None:
            generator = torch.Generator(device=value.device)
            generator.manual_seed(seed)
        
        output = torch.empty_like(value, dtype=dtype)
        
        slice_size = 2**24
        for i in range(0, value.numel(), slice_size):
            output[i:i+slice_size].copy_(comfy_float.manual_stochastic_round_to_float8(
                value[i:i+slice_size], dtype, generator=generator
            ))
        
        if needs_cpu:
            output = output.to(original_device)
        
        return output
    
    comfy_float.stochastic_rounding = patched_stochastic_rounding
    print("✓ Patched comfy.float.stochastic_rounding for MPS")
    
except Exception as e:
    print(f"⚠ Could not patch stochastic_rounding: {e}")

# Patch 2: comfy_kitchen dequantization
try:
    import comfy_kitchen.backends.eager.quantization as ck_quant
    
    _original_dequantize = ck_quant.dequantize_per_tensor_fp8
    
    def patched_dequantize_per_tensor_fp8(x, scale, output_type):
        original_device = x.device
        needs_cpu = original_device.type == 'mps'
        
        if needs_cpu:
            x = x.cpu()
            if isinstance(scale, torch.Tensor):
...</body></comment_new>
</comments>


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI and others added 9 commits February 13, 2026 05:27
Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Co-authored-by: lmangani <1423657+lmangani@users.noreply.github.com>
Copilot AI changed the title [WIP] Add support for Float8_e4m3fn conversion to MPS backend Fix FP8 conversion corruption by separating value-preserving and scaled quantization Feb 13, 2026
Copilot AI requested a review from lmangani February 13, 2026 05:35
@lmangani
lmangani marked this pull request as ready for review February 13, 2026 05:49
@lmangani
lmangani merged commit afc9ecc into main Feb 13, 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.

Float8_e4m3fn

2 participants