In a new file quant_layouts/feather.py, create a new layout FeatherTensorWiseFP8Layout, similar to the existing layouts in @quant_layouts/fp8_variants.py , but use one scalar scale for the whole tensor, and use @kernels/feather.py to implement mm, addmm, linear. Then register it in @nodes/loader_nodes.py .
--- Content from referenced files ---
Content from @kernels/feather.py:
from functools import partial
from typing import Optional
import torch
import triton
import triton.language as tl
from .autotune import get_autotune_configs, prune_configs
I will read fp8_ops.py to understand how HybridFP8Ops interacts with layouts, which will guide the implementation of the new Feather layout and its integration.
Assistant
I will create quant_layouts/feather.py with the new layout FeatherTensorWiseFP8Layout, the operation registrations (linear, mm, addmm) using kernels/feather.py, and the FeatherOps class.
Assistant
I will update nodes/loader_nodes.py to register the new float8_e4m3fn_feather format. This involves adding it to the INPUT_TYPES of QuantizedModelLoader and QuantizedUNETLoader, and adding the corresponding logic to load FeatherOps in their respective load methods.
Assistant
I will list the directory quant_layouts to confirm the creation of feather.py.
Assistant
The FeatherTensorWiseFP8Layout and FeatherOps have been implemented in quant_layouts/feather.py, and the new quantization format float8_e4m3fn_feather has been registered in nodes/loader_nodes.py.
Summary of Changes
Created quant_layouts/feather.py:
FeatherTensorWiseFP8Layout: A new layout class implementing tensor-wise FP8 quantization (one scalar scale per tensor).
Ops Registration: Registered linear, mm, and addmm operations for this layout to use the custom scaled_mm kernel from kernels/feather.py.
The implementation handles on-the-fly quantization of activations using the same tensor-wise strategy.
class QuantizedModelLoader:
"""
Load models with custom quantization layouts and kernel backend selection.
code
Supports models quantized by convert_to_quant (with or without --comfy_quant flag).
Automatically handles legacy scale_weight -> weight_scale conversion.
FP8 Modes:
- float8_e4m3fn: Standard tensor-scaled FP8 (uses ComfyUI built-in handling)
- float8_e4m3fn_blockwise: Block-wise scaled FP8 (uses HybridFP8Ops)
- float8_e4m3fn_rowwise: Row-wise scaled FP8 (uses HybridFP8Ops)
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"ckpt_name": (folder_paths.get_filename_list("checkpoints"),),
"quant_format": (["auto", "int8", "float8_e4m3fn", "float8_e4m3fn_blockwise", "float8_e4m3fn_rowwise"],),
"kernel_backend": (["pytorch", "triton"],),
},
"optional": {
"force_dequant": (
"BOOLEAN",
{
"default": False,
"tooltip": "Force dequantize all weights at load time",
},
),
},
}
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
FUNCTION = "load_checkpoint"
CATEGORY = "loaders/quantized"
DESCRIPTION = "Load checkpoints with custom quantization support. float8_e4m3fn (tensor-scaled) uses ComfyUI built-in. INT8/FP8 blockwise/rowwise use custom layouts."
def load_checkpoint(
self, ckpt_name, quant_format, kernel_backend, force_dequant=False
):
"""Load a checkpoint with the specified quantization format and kernel backend."""
# Set the kernel backend for INT8 layout (only affects INT8 models)
if quant_format in ("auto", "int8"):
try:
from ..quant_layouts.int8_layout import BlockWiseINT8Layout
BlockWiseINT8Layout.set_backend(kernel_backend)
logging.debug(
f"QuantizedModelLoader: Configured INT8 backend to '{kernel_backend}'"
)
except Exception as e:
if kernel_backend == "triton":
logging.warning(f"Failed to configure Triton backend: {e}")
# Get full checkpoint path
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
# Select ops class based on quant_format
model_options = {}
if quant_format == "int8":
try:
from ..int8_ops import HybridINT8Ops
model_options = {"custom_operations": HybridINT8Ops}
logging.info(
"QuantizedModelLoader: Using HybridINT8Ops for INT8 models"
)
except ImportError as e:
logging.warning(f"HybridINT8Ops not available: {e}")
elif quant_format == "float8_e4m3fn":
# Standard tensor-scaled FP8 - use ComfyUI's built-in handling
# No custom ops needed, TensorCoreFP8Layout handles it correctly
logging.info(
"QuantizedModelLoader: Using ComfyUI built-in for tensor-scaled FP8"
)
elif quant_format in ("float8_e4m3fn_blockwise", "float8_e4m3fn_rowwise"):
# Block-wise or row-wise FP8 - use HybridFP8Ops for per-block/row scales
try:
from ..fp8_ops import HybridFP8Ops
model_options = {"custom_operations": HybridFP8Ops}
logging.info(
f"QuantizedModelLoader: Using HybridFP8Ops for {quant_format} models"
)
except ImportError as e:
logging.warning(f"HybridFP8Ops not available: {e}")
else: # auto
# Try INT8 as fallback for auto mode
try:
from ..int8_ops import HybridINT8Ops
model_options = {"custom_operations": HybridINT8Ops}
logging.info("QuantizedModelLoader: Auto-selected HybridINT8Ops")
except ImportError as e:
logging.warning(f"No quantized ops available: {e}")
# Load state dict with guaranteed float32 scales using our loader
try:
from ..utils.safetensors_loader import load_fp8_state_dict
sd, metadata = load_fp8_state_dict(ckpt_path, force_scale_float32=True)
logging.info("QuantizedModelLoader: Loaded state dict with float32 scales")
# Use ComfyUI's guess config with our pre-loaded state dict
out = comfy.sd.load_state_dict_guess_config(
sd,
output_vae=True,
output_clip=True,
embedding_directory=folder_paths.get_folder_paths("embeddings"),
model_options=model_options,
)
except Exception as e:
# Fallback to standard loading
logging.warning(f"QuantizedModelLoader: Custom loader failed, using fallback: {e}")
out = comfy.sd.load_checkpoint_guess_config(
ckpt_path,
output_vae=True,
output_clip=True,
embedding_directory=folder_paths.get_folder_paths("embeddings"),
model_options=model_options,
)
model = out[0]
clip = out[1]
vae = out[2]
# Force dequantize if requested (useful for debugging)
if force_dequant and model is not None:
logging.info("QuantizedModelLoader: Force dequantizing model weights")
pass
return (model, clip, vae)
class QuantizedUNETLoader:
"""
Load UNET/diffusion models with custom quantization layouts.
code
Handles legacy scale_weight format automatically.
FP8 Modes:
- float8_e4m3fn: Standard tensor-scaled FP8 (uses ComfyUI built-in handling)
- float8_e4m3fn_blockwise: Block-wise scaled FP8 (uses HybridFP8Ops)
- float8_e4m3fn_rowwise: Row-wise scaled FP8 (uses HybridFP8Ops)
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"unet_name": (folder_paths.get_filename_list("diffusion_models"),),
"quant_format": (["auto", "int8", "float8_e4m3fn", "float8_e4m3fn_blockwise", "float8_e4m3fn_rowwise"],),
"kernel_backend": (["pytorch", "triton"],),
},
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "load_unet"
CATEGORY = "loaders/quantized"
DESCRIPTION = "Load diffusion models with custom quantization support. float8_e4m3fn (tensor-scaled) uses ComfyUI built-in. INT8/FP8 blockwise/rowwise use custom layouts."
def load_unet(self, unet_name, quant_format, kernel_backend):
"""Load a UNET model with the specified settings."""
# Set kernel backend (only for INT8 format)
if quant_format in ("auto", "int8"):
try:
from ..quant_layouts.int8_layout import BlockWiseINT8Layout
BlockWiseINT8Layout.set_backend(kernel_backend)
logging.debug(
f"QuantizedUNETLoader: Configured INT8 backend to '{kernel_backend}'"
)
except Exception as e:
if kernel_backend == "triton":
logging.warning(f"Failed to configure Triton backend: {e}")
# Get model path
unet_path = folder_paths.get_full_path("diffusion_models", unet_name)
# Select ops class based on quant_format
model_options = {}
if quant_format == "int8":
try:
from ..int8_ops import HybridINT8Ops
model_options = {"custom_operations": HybridINT8Ops}
logging.info("QuantizedUNETLoader: Using HybridINT8Ops for INT8 models")
except ImportError as e:
logging.warning(f"HybridINT8Ops not available: {e}")
elif quant_format == "float8_e4m3fn":
# Standard tensor-scaled FP8 - use ComfyUI's built-in handling
logging.info(
"QuantizedUNETLoader: Using ComfyUI built-in for tensor-scaled FP8"
)
elif quant_format in ("float8_e4m3fn_blockwise", "float8_e4m3fn_rowwise"):
# Block-wise or row-wise FP8 - use HybridFP8Ops
try:
from ..fp8_ops import HybridFP8Ops
model_options = {"custom_operations": HybridFP8Ops}
logging.info(
f"QuantizedUNETLoader: Using HybridFP8Ops for {quant_format} models"
)
except ImportError as e:
logging.warning(f"HybridFP8Ops not available: {e}")
else: # auto
try:
from ..int8_ops import HybridINT8Ops
model_options = {"custom_operations": HybridINT8Ops}
logging.info("QuantizedUNETLoader: Auto-selected HybridINT8Ops")
except ImportError as e:
logging.warning(f"No quantized ops available: {e}")
# Load state dict with guaranteed float32 scales using our loader
try:
from ..utils.safetensors_loader import load_fp8_state_dict
sd, metadata = load_fp8_state_dict(unet_path, force_scale_float32=True)
logging.info("QuantizedUNETLoader: Loaded state dict with float32 scales")
except Exception as e:
# Fallback to standard loading
logging.warning(f"QuantizedUNETLoader: Custom loader failed, using fallback: {e}")
sd = comfy.utils.load_torch_file(unet_path, safe_load=True)
# Use load_diffusion_model_state_dict to build model from our state dict
model = comfy.sd.load_diffusion_model_state_dict(sd, model_options=model_options)
return (model,)
class QuantizedCLIPLoader:
"""
Load CLIP/text encoders with INT8 blockwise quantization.
code
Supports text encoders quantized by convert_to_quant with --int8 --comfy_quant.
"""
# CLIPType options matching built-in CLIPLoader from nodes.py
CLIP_TYPES = [
"stable_diffusion",
"stable_cascade",
"sd3",
"stable_audio",
"mochi",
"ltxv",
"pixart",
"cosmos",
"lumina2",
"wan",
"hidream",
"chroma",
"ace",
"omnigen2",
"qwen_image",
"hunyuan_image",
"flux",
"hunyuan_video",
"flux2",
"ovis",
]
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"clip_name": (folder_paths.get_filename_list("text_encoders"),),
"type": (cls.CLIP_TYPES,),
"kernel_backend": (["pytorch", "triton"],),
},
}
RETURN_TYPES = ("CLIP",)
FUNCTION = "load_clip"
CATEGORY = "loaders/quantized"
DESCRIPTION = "Load INT8-quantized text encoders (CLIP, T5, etc.)"
def load_clip(self, clip_name, type, kernel_backend):
"""Load a CLIP/text encoder with INT8 quantization support."""
import comfy.model_management
# Configure INT8 kernel backend
try:
from ..quant_layouts.int8_layout import BlockWiseINT8Layout
BlockWiseINT8Layout.set_backend(kernel_backend)
logging.debug(
f"QuantizedCLIPLoader: Configured INT8 backend to '{kernel_backend}'"
)
except Exception as e:
if kernel_backend == "triton":
logging.warning(f"Failed to configure Triton backend: {e}")
# Get clip path
clip_path = folder_paths.get_full_path("text_encoders", clip_name)
# Convert type string to CLIPType enum
clip_type = getattr(
comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION
)
# Load state dict
sd = comfy.utils.load_torch_file(clip_path, safe_load=True)
# Set up model options with our custom INT8 ops
model_options = {
"initial_device": comfy.model_management.text_encoder_offload_device()
}
try:
from ..int8_ops import HybridINT8Ops
model_options["custom_operations"] = HybridINT8Ops
logging.info(
"QuantizedCLIPLoader: Using HybridINT8Ops for INT8 text encoder"
)
except ImportError as e:
logging.warning(f"HybridINT8Ops not available: {e}")
# Load text encoder using ComfyUI's API
clip = comfy.sd.load_text_encoder_state_dicts(
state_dicts=[sd],
clip_type=clip_type,
model_options=model_options,
embedding_directory=folder_paths.get_folder_paths("embeddings"),
)
return (clip,)
class BNB4bitFluxConfig(comfy.supported_models_base.BASE):
"""Minimal model config for BNB 4-bit Flux models."""
unet_config = {}
unet_extra_config = {}
latent_format = comfy.latent_formats.Flux
memory_usage_factor = 2.8
supported_inference_dtypes = [torch.bfloat16, torch.float16, torch.float32]
code
def __init__(self, is_flux2=False):
self.unet_config = {}
self.latent_format = comfy.latent_formats.Flux2() if is_flux2 else comfy.latent_formats.Flux()
self.unet_config["disable_unet_model_creation"] = True
if is_flux2:
self.memory_usage_factor = 2.8 * 4 * 2.36 # Flux2 uses more memory
class BNB4bitFluxModel(comfy.model_base.BaseModel):
"""Base model class for BNB 4-bit Flux loading."""
code
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def extra_conds(self, **kwargs):
out = super().extra_conds(**kwargs)
cross_attn = kwargs.get("cross_attn", None)
if cross_attn is not None:
out['c_crossattn'] = comfy.conds.CONDRegular(cross_attn)
guidance = kwargs.get("guidance", 3.5)
if guidance is not None:
out['guidance'] = comfy.conds.CONDRegular(torch.FloatTensor([guidance]))
return out
class BNB4bitUNETLoader:
"""
Load UNET/diffusion models quantized to BNB 4-bit (NF4/FP4) format.
code
Supports models quantized by convert_to_quant with --bnb-4bit flag.
Dequantizes weights during forward pass using pure PyTorch.
Auto-detects Flux vs Flux2 from state dict keys (not shapes).
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"unet_name": (folder_paths.get_filename_list("diffusion_models"),),
},
"optional": {
"model_type_override": (["auto", "flux2", "flux", "chroma", "chroma_radiance", "chroma_radiance_x0"],),
},
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "load_unet"
CATEGORY = "loaders/quantized"
DESCRIPTION = "Load BNB 4-bit (NF4/FP4) quantized Flux/Chroma/Radiance models. Uses pure PyTorch dequantization."
def _detect_model_type(self, state_dict_keys):
"""
Detect model type from state dict keys (not shapes).
Detection logic:
- Flux2: has double_stream_modulation_img.lin.weight
- Chroma: has distilled_guidance_layer but NOT nerf and NOT __x0__
- Chroma Radiance: has distilled_guidance_layer AND nerf but NOT __x0__
- Chroma Radiance X0: has distilled_guidance_layer AND nerf AND __x0__
- Flux: default (has double_blocks but none of the above)
"""
# Helper to check key presence (handles BNB suffix keys)
def has_key_pattern(pattern):
return any(pattern in k for k in state_dict_keys)
# Check for Flux2 unique key
if has_key_pattern("double_stream_modulation_img.lin.weight"):
return "flux2"
# Check for Chroma/Radiance variants
has_distilled = has_key_pattern("distilled_guidance_layer.")
has_nerf = has_key_pattern("nerf_blocks.")
has_x0 = has_key_pattern("__x0__")
if has_distilled:
if has_nerf:
if has_x0:
return "chroma_radiance_x0"
else:
return "chroma_radiance"
else:
return "chroma"
# Default to Flux1
return "flux"
def load_unet(self, unet_name, model_type_override="auto"):
"""Load a BNB 4-bit quantized UNET model."""
import comfy.model_management as model_management
import comfy.ldm.flux.model as flux_model
try:
from ..bnb4bit_ops import HybridBNB4bitOps
except ImportError as e:
logging.error(f"Failed to import HybridBNB4bitOps: {e}")
raise
# Get model path and load state dict
unet_path = folder_paths.get_full_path("diffusion_models", unet_name)
sd = comfy.utils.load_torch_file(unet_path)
# Strip prefix if present
new_sd = {}
for k, v in sd.items():
if k.startswith("model.diffusion_model."):
new_sd[k[22:]] = v
else:
new_sd[k] = v
sd = new_sd
# Detect or use override
if model_type_override == "auto":
model_type = self._detect_model_type(sd.keys())
logging.info(f"BNB4bitUNETLoader: Auto-detected model type: {model_type}")
else:
model_type = model_type_override
logging.info(f"BNB4bitUNETLoader: Using override model type: {model_type}")
logging.info(f"BNB4bitUNETLoader: Loading {unet_name} as {model_type}")
is_flux2 = model_type == "flux2"
is_chroma = model_type in ("chroma", "chroma_radiance", "chroma_radiance_x0")
load_device = model_management.get_torch_device()
offload_device = model_management.unet_offload_device()
unet_dtype = torch.bfloat16
# Import shape extraction helper
from ..bnb4bit_ops import get_original_shape
# Extract dimensions from quant_state metadata (BNB stores original shapes)
img_in_shape = get_original_shape(sd, "img_in.weight")
txt_in_shape = get_original_shape(sd, "txt_in.weight")
guidance_in_shape = get_original_shape(sd, "guidance_in.in_layer.weight")
# Derive model dimensions from shapes
if img_in_shape:
hidden_size = img_in_shape[0]
# in_channels depends on patch_size
else:
hidden_size = 6144 if is_flux2 else 3072
if txt_in_shape:
context_in_dim = txt_in_shape[1]
else:
context_in_dim = 15360 if is_flux2 else 4096
if guidance_in_shape:
vec_in_dim = guidance_in_shape[1]
else:
vec_in_dim = 256 if is_flux2 else 768
# Count blocks from state dict keys
def count_blocks(keys, prefix):
max_idx = -1
for k in keys:
if prefix in k:
try:
idx = int(k.split(prefix)[1].split('.')[0])
max_idx = max(max_idx, idx)
except (ValueError, IndexError):
pass
return max_idx + 1 if max_idx >= 0 else 0
depth = count_blocks(sd.keys(), "double_blocks.")
depth_single_blocks = count_blocks(sd.keys(), "single_blocks.")
logging.info(f"BNB4bitUNETLoader: Extracted from quant_state:")
logging.info(f" hidden_size={hidden_size}, context_in_dim={context_in_dim}, vec_in_dim={vec_in_dim}")
logging.info(f" depth={depth}, depth_single_blocks={depth_single_blocks}")
# Build FluxParams based on detected model type + extracted dimensions
if model_type == "flux2":
patch_size = 1
in_channels = img_in_shape[1] // (patch_size * patch_size) if img_in_shape else 128
params = flux_model.FluxParams(
in_channels=in_channels,
out_channels=128,
vec_in_dim=vec_in_dim,
context_in_dim=context_in_dim,
hidden_size=hidden_size,
mlp_ratio=3.0,
num_heads=48,
depth=depth if depth > 0 else 8,
depth_single_blocks=depth_single_blocks if depth_single_blocks > 0 else 48,
axes_dim=[32, 32, 32, 32],
theta=2000,
patch_size=patch_size,
qkv_bias=False,
guidance_embed=True,
txt_ids_dims=[3],
global_modulation=True,
mlp_silu_act=True,
ops_bias=False,
)
elif model_type == "chroma":
patch_size = 2
in_channels = img_in_shape[1] // (patch_size * patch_size) if img_in_shape else 64
params = flux_model.FluxParams(
in_channels=in_channels,
out_channels=64,
vec_in_dim=vec_in_dim,
context_in_dim=context_in_dim,
hidden_size=hidden_size,
mlp_ratio=4.0,
num_heads=24,
depth=depth if depth > 0 else 19,
depth_single_blocks=depth_single_blocks if depth_single_blocks > 0 else 38,
axes_dim=[16, 56, 56],
theta=10000,
patch_size=patch_size,
qkv_bias=True,
guidance_embed=False,
txt_ids_dims=[],
)
elif model_type in ("chroma_radiance", "chroma_radiance_x0"):
patch_size = 16
params = flux_model.FluxParams(
in_channels=3,
out_channels=3,
vec_in_dim=vec_in_dim,
context_in_dim=context_in_dim,
hidden_size=hidden_size,
mlp_ratio=4.0,
num_heads=24,
depth=depth if depth > 0 else 19,
depth_single_blocks=depth_single_blocks if depth_single_blocks > 0 else 38,
axes_dim=[16, 56, 56],
theta=10000,
patch_size=patch_size,
qkv_bias=True,
guidance_embed=False,
txt_ids_dims=[],
)
else: # flux (default)
patch_size = 2
in_channels = img_in_shape[1] // (patch_size * patch_size) if img_in_shape else 16
params = flux_model.FluxParams(
in_channels=in_channels,
out_channels=16,
vec_in_dim=vec_in_dim,
context_in_dim=context_in_dim,
hidden_size=hidden_size,
mlp_ratio=4.0,
num_heads=24,
depth=depth if depth > 0 else 19,
depth_single_blocks=depth_single_blocks if depth_single_blocks > 0 else 38,
axes_dim=[16, 56, 56],
theta=10000,
patch_size=patch_size,
qkv_bias=True,
guidance_embed=True,
txt_ids_dims=[],
)
# Create model config and base model
model_conf = BNB4bitFluxConfig(is_flux2=is_flux2)
model_conf.set_inference_dtype(unet_dtype, unet_dtype) # Set compute dtype
model = BNB4bitFluxModel(
model_conf,
model_type=comfy.model_base.ModelType.FLUX,
device=load_device
)
logging.info(f"BNB4bitUNETLoader: Creating Flux model with HybridBNB4bitOps")
# Create diffusion model with our custom ops
model.diffusion_model = flux_model.Flux(
device=offload_device,
dtype=unet_dtype,
operations=HybridBNB4bitOps,
**{k: getattr(params, k) for k in params.__dataclass_fields__}
)
model.diffusion_model.eval()
model.diffusion_model.dtype = unet_dtype
# Load weights from packed state dict using our custom ops
m, u = model.diffusion_model.load_state_dict(sd, strict=False)
if len(m) > 0:
logging.warning(f"BNB4bitUNETLoader: missing keys: {len(m)}")
logging.debug(f"Missing: {m[:10]}...")
if len(u) > 0:
logging.warning(f"BNB4bitUNETLoader: unexpected keys: {len(u)}")
logging.debug(f"Unexpected: {u[:10]}...")
logging.info(f"BNB4bitUNETLoader: Successfully loaded {unet_name}")
patcher = comfy.model_patcher.ModelPatcher(model, load_device=load_device, offload_device=offload_device)
return (patcher,)
NODE_DISPLAY_NAME_MAPPINGS = {
"QuantizedModelLoader": "Load Checkpoint (Quantized)",
"QuantizedUNETLoader": "Load Diffusion Model (Quantized)",
"QuantizedCLIPLoader": "Load CLIP (Quantized)",
"BNB4bitUNETLoader": "Load Diffusion Model (BNB 4-bit)",
}
Content from @quant_layouts/fp8_variants.py:
"""
FP8 Variant Layouts (Row-wise and Block-wise scaling)
These layouts extend ComfyUI's base TensorCoreFP8Layout with finer-grained scaling:
RowWiseFP8Layout: One scale per row (M scales for MxN weight)
BlockWiseFP8Layout: One scale per 2D block (MxN blocks)
When Triton is available, these layouts use native FP8 matmul kernels.
Otherwise, they fall back to dequantization.
"""
import torch
import logging
from dataclasses import dataclass
from typing import Tuple, Optional
Import from ComfyUI core (which re-exports from comfy_kitchen)
from comfy.quant_ops import QuantizedTensor, register_layout_op
Import base layout types from comfy_kitchen
try:
from comfy_kitchen.tensor import QuantizedLayout, BaseLayoutParams
except ImportError:
# Fallback for older versions
from comfy.quant_ops import QuantizedLayout
BaseLayoutParams = object # Will fail at runtime if used
Check comfy-kitchen triton backend first, then independent check
def _should_use_fp8_kernels():
"""Check FP8 Triton kernel availability using ck or independent check."""
try:
from .. import is_ck_triton_available
if is_ck_triton_available():
return True
except ImportError:
pass
code
# Fall back to independent check
try:
from ..kernels.fp8_kernels import _check_triton_available
return _check_triton_available()
except ImportError:
return False
@register_layout_op(torch.ops.aten.linear.default, RowWiseFP8Layout)
def rowwise_fp8_linear(func, args, kwargs):
"""Row-wise FP8 linear operation with native kernel support."""
input_tensor = args[0]
weight = args[1]
bias = args[2] if len(args) > 2 else None
code
# Try native FP8 kernel if weight is quantized and Triton available
if _HAS_FP8_KERNELS and isinstance(weight, QuantizedTensor):
w_qdata, w_scale = RowWiseFP8Layout.get_plain_tensors(weight)
# Check if weight is on CUDA (required for Triton)
if w_qdata.is_cuda:
orig_dtype = weight._params.orig_dtype
# Use a reasonable block size for activation quantization
act_block_size = 128
# Input needs to be quantized for rowwise kernel
if input_tensor.dtype in [torch.float16, torch.bfloat16, torch.float32]:
try:
# Quantize input to FP8 blockwise
a_qdata, a_scale = fp8_act_quant(
input_tensor.to(device=w_qdata.device),
block_size=act_block_size,
dtype=w_qdata.dtype,
)
logging.debug(
f"FP8 rowwise: Native kernel (dynamic quant), "
f"input={a_qdata.shape}, weight={w_qdata.shape}"
)
# For rowwise, bias needs manual addition (no fused kernel yet)
result = fp8_gemm_rowwise(
a_qdata,
a_scale,
w_qdata,
w_scale,
input_block_size=act_block_size,
)
if bias is not None:
result = result + bias.to(
device=result.device, dtype=result.dtype
)
return result.to(orig_dtype)
except Exception as e:
logging.warning(f"FP8 rowwise native kernel failed: {e}")
# Fallback: dequantize
logging.debug("FP8 rowwise: Using dequant fallback")
if isinstance(weight, QuantizedTensor):
weight = weight.dequantize()
if isinstance(input_tensor, QuantizedTensor):
input_tensor = input_tensor.dequantize()
return torch.nn.functional.linear(input_tensor, weight, bias)
if isinstance(bias, QuantizedTensor):
bias = bias.dequantize()
if isinstance(input_tensor, QuantizedTensor):
input_tensor = input_tensor.dequantize()
if isinstance(weight, QuantizedTensor):
weight = weight.dequantize()
return func(bias, input_tensor, weight, **kwargs)
@register_layout_op(torch.ops.aten.view.default, BlockWiseFP8Layout)
@register_layout_op(torch.ops.aten.t.default, BlockWiseFP8Layout)
def blockwise_fp8_func(func, args, kwargs):
"""Handle view/transpose for block-wise FP8 tensors."""
input_tensor = args[0]
if isinstance(input_tensor, QuantizedTensor):
plain_input, scale, block_size = BlockWiseFP8Layout.get_plain_tensors(
input_tensor
)
ar = list(args)
ar[0] = plain_input
# Use _copy_with to preserve params
return input_tensor._copy_with(qdata=func(*ar, **kwargs))
return func(*args, **kwargs)
--- End of content ---
It transposes the weight tensor on-the-fly to match the contiguous memory requirement of the scaled_mm kernel.
FeatherOps: A custom operations class inheriting from HybridFP8Ops. It overrides _load_from_state_dict to automatically wrap loaded FP8 weights into FeatherTensorWiseFP8Layout when this ops class is selected.
Updated nodes/loader_nodes.py:
QuantizedModelLoader: Added "float8_e4m3fn_feather" to the quant_format input list.
QuantizedUNETLoader: Added "float8_e4m3fn_feather" to the quant_format input list.
Logic Update: Added logic in both loaders to use FeatherOps when the float8_e4m3fn_feather format is selected.
You can now use the float8_e4m3fn_feather format in ComfyUI when loading models with these custom nodes.