8000 RuntimeError: "cuda_scatter_gather_base_kernel_func" not implemented for 'Float8_e4m3fn' · Issue #153621 · pytorch/pytorch · GitHub
[go: up one dir, main page]

Skip to content
RuntimeError: "cuda_scatter_gather_base_kernel_func" not implemented for 'Float8_e4m3fn' #153621
@vgoklani

Description

@vgoklani

🐛 Describe the bug

RuntimeError: "cuda_scatter_gather_base_kernel_func" not implemented for 'Float8_e4m3fn'

This occurs when trying to implement an efficient FP8 KV-Cache for my Llama model (see below).

from typing import Optional, Tuple

import torch
import torch.nn as nn


def to_float8(x: torch.Tensor, dtype: torch.dtype) -> Tuple[torch.Tensor, torch.Tensor]:
    """Convert a tensor to float8 with scaling, as in the original example."""
    finfo = torch.finfo(dtype)
    # Calculate scale as dtype max divided by absmax
    scale = finfo.max / x.abs().max(dim=-1, keepdim=True).values.clamp(min=1e-12)
    # Scale and clamp to float8 range
    x_scl_sat = (x * scale).clamp(min=finfo.min, max=finfo.max)
    # Return float8 tensor and inverse scale
    return x_scl_sat.to(dtype), scale.float().reciprocal()


class FP8KVCache(nn.Module):
    def __init__(
        self,
        max_batch_size: int,
        max_seq_length: int,
        num_kv_heads: int,
        head_dim: int,
        scale_dtype: Optional[torch.dtype] = torch.bfloat16,
        fp8_dtype: Optional[torch.dtype] = torch.float8_e4m3fn,
    ):
        super().__init__()
        assert max_batch_size > 0 and max_seq_length > 0
        self.scale_dtype = scale_dtype
        self.fp8_dtype = fp8_dtype

        cache_shape = (max_batch_size, num_kv_heads, max_seq_length, head_dim)

        self.register_buffer("k_cache", torch.zeros(cache_shape, dtype=fp8_dtype))
        self.register_buffer("v_cache", torch.zeros(cache_shape, dtype=fp8_dtype))

        scale_shape = (max_batch_size, num_kv_heads, max_seq_length, 1)
        self.register_buffer("k_scale", torch.ones(scale_shape, dtype=scale_dtype))
        self.register_buffer("v_scale", torch.ones(scale_shape, dtype=scale_dtype))

    def reset(self) -> None:
        """Reset caches to zeros and scales to ones."""
        self.k_cache.zero_()
        self.v_cache.zero_()
        self.k_scale.fill_(1.0)
        self.v_scale.fill_(1.0)

    def update(
        self, input_pos: torch.LongTensor, k_val: torch.Tensor, v_val: torch.Tensor
    ) -> Tuple[torch.Tensor, torch.Tensor]:
        """
        Update the FP8 KV cache with new key and value tensors.

        Args:
            input_pos: LongTensor of shape [B, T], positions into the cache for each batch element.
            k_val: Tensor of shape [B, H, T, D], key values in bf16 or fp16.
            v_val: Tensor of shape [B, H, T, D], value values in bf16 or fp16.

        Returns:
            Tuple (k_out, v_out) of dequantized cache slices, both of shape [B, H, S, D],
            where S is the maximum position in input_pos plus 1 (current sequence length).
        """
        B, H, T, D = k_val.shape

        assert input_pos.shape == (B, T), (
            f"Expected input_pos shape {(B, T)}, got {input_pos.shape}"
        )

        # Convert input key/value to float8
        k_f8, k_inv_scale = to_float8(k_val, dtype=self.fp8_dtype)
        v_f8, v_inv_scale = to_float8(v_val, dtype=self.fp8_dtype)

        # Expand input_pos for indexing: [B, T] -> [B, H, T, D]
        idx = input_pos[:, None, :, None].expand(B, H, T, D)

        # Update caches using scatter_
        self.k_cache[:B].scatter_(dim=2, index=idx, src=k_f8)
        self.v_cache[:B].scatter_(dim=2, index=idx, src=v_f8)

        # Update scales: inverse scale is stored as the actual scale for dequantization
        scale_idx = input_pos[:, None, :, None].expand(B, H, T, 1)
        self.k_scale[:B].scatter_(dim=2, index=scale_idx, src=k_inv_scale.reciprocal())
        self.v_scale[:B].scatter_(dim=2, index=scale_idx, src=v_inv_scale.reciprocal())

        # Dequantize only the relevant cache slice (up to max position)
        max_pos = input_pos.max() + 1
        k_out = self.k_cache[:B, :, :max_pos] * self.k_scale[:B, :, :max_pos]
        v_out = self.v_cache[:B, :, :max_pos] * self.v_scale[:B, :, :max_pos]
        k_out = k_out.to(k_val.dtype)
        v_out = v_out.to(v_val.dtype)

        return k_out, v_out

    @classmethod
    def from_float(
        cls,
        max_batch_size: int,
        max_seq_length: int,
        num_kv_heads: int,
        head_dim: int,
        scale_dtype: torch.dtype,
        fp8_dtype: torch.dtype,
    ) -> "FP8KVCache":
        """Create an FP8 KV cache with the specified parameters."""
        return cls(
            max_batch_size=max_batch_size,
            max_seq_length=max_seq_length,
            num_kv_heads=num_kv_heads,
            head_dim=head_dim,
            scale_dtype=scale_dtype,
            fp8_dtype=fp8_dtype,
        )

Versions

--2025-05-15 14:08:25-- https://raw.githubusercontent.com/pytorch/pytorch/main/torch/utils/collect_env.py
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.110.133, 185.199.111.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 24503 (24K) [text/plain]
Saving to: ‘collect_env.py’

collect_env.py 100%[===================>] 23.93K --.-KB/s in 0.001s

2025-05-15 14:08:25 (16.7 MB/s) - ‘collect_env.py’ saved [24503/24503]

Collecting environment information...
PyTorch version: 2.7.0a0+79aa17489c.nv25.04
Is debug build: False
CUDA used to build PyTorch: 12.9
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.2 LTS (x86_64)
GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0
Clang version: Could not collect
CMake version: version 3.31.6
Libc version: glibc-2.39

Python version: 3.12.3 (main, Feb 4 2025, 14:48:35) [GCC 13.3.0] (64-bit runtime)
Python platform: Linux-5.15.0-135-generic-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 12.9.41
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA RTX 6000 Ada Generation
Nvidia driver version: 570.86.15
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.9.0
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 46 bits physical, 48 bits virtual
Byte Order: Little Endian
CPU(s): 36
On-line CPU(s) list: 0-35
Vendor ID: GenuineIntel
Model name: Intel(R) Core(TM) i9-10980XE CPU @ 3.00GHz
CPU family: 6
Model: 85
Thread(s) per core: 2
Core(s) per socket: 18
Socket(s): 1
Stepping: 7
CPU(s) scaling MHz: 28%
CPU max MHz: 4800.0000
CPU min MHz: 1200.0000
BogoMIPS: 6000.00
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization: VT-x
L1d cache: 576 KiB (18 instances)
L1i cache: 576 KiB (18 instances)
L2 cache: 18 MiB (18 instances)
L3 cache: 24.8 MiB (1 instance)
NUMA node(s): 1
NUMA node0 CPU(s): 0-35
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] nvidia-cudnn-frontend==1.11.0
[pip3] nvtx==0.2.11
[pip3] onnx==1.17.0
[pip3] optree==0.14.1
[pip3] pynvjitlink==0.3.0
[pip3] pytorch-triton==3.2.0+git4b3bb1f8b.nvinternal
[pip3] torch==2.7.0a0+79aa17489c.nv25.4
[pip3] torch-geometric==2.6.1
[pip3] torch_tensorrt==2.7.0a0
[pip3] torchao==0.10.0
[pip3] torchprofile==0.0.4
[pip3] torchvision==0.22.0a0
[conda] Could not collect

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0