Instructions to use kernels-community/metal-flash-sdpa with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Kernels
How to use kernels-community/metal-flash-sdpa with Kernels:
# !pip install kernels from kernels import get_kernel # a version (or an explicit revision) is required; see the "Files and versions" tab for the available ones kernel = get_kernel("kernels-community/metal-flash-sdpa", version=1) - Notebooks
- Google Colab
- Kaggle
Build uploaded using `kernels`.
Browse filesFiles changed (12)
- build/torch210-metal-aarch64-darwin/__init__.pyAdded+11
- build/torch210-metal-aarch64-darwin/_custom_ops.pyAdded+117
- build/torch210-metal-aarch64-darwin/_metal_flash_sdpa_metal_8924527.abi3.soAdded+3
- build/torch210-metal-aarch64-darwin/_ops.pyAdded+9
- build/torch210-metal-aarch64-darwin/metadata.jsonAdded+5
- build/torch210-metal-aarch64-darwin/metal_flash_sdpa/__init__.pyAdded+26
- build/torch29-metal-aarch64-darwin/__init__.pyAdded+11
- build/torch29-metal-aarch64-darwin/_custom_ops.pyAdded+117
- build/torch29-metal-aarch64-darwin/_metal_flash_sdpa_metal_8924527.abi3.soAdded+3
- build/torch29-metal-aarch64-darwin/_ops.pyAdded+9
- build/torch29-metal-aarch64-darwin/metadata.jsonAdded+5
- build/torch29-metal-aarch64-darwin/metal_flash_sdpa/__init__.pyAdded+26
1234567891011from ._custom_ops import ( flash_attention_varlen, flash_attn_varlen_func,)from ._ops import ops
__all__ = [ "flash_attention_varlen", "flash_attn_varlen_func", "ops",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117from typing import List, Optional
import torch
from ._ops import ops
def flash_attention_varlen( out: torch.Tensor, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, cu_seqlens_q: torch.Tensor, cu_seqlens_k: torch.Tensor, max_seqlen_q: int, max_seqlen_k: int, do_causal: bool = False, scale: Optional[float] = None, softcapping: float = 1.0,) -> None: """ Flash Attention with variable-length sequences. Args: out: Output tensor of shape [total_q_tokens, num_heads, head_dim] query: Query tensor of shape [total_q_tokens, num_heads, head_dim] key: Key tensor of shape [total_k_tokens, num_heads_kv, head_dim] value: Value tensor of shape [total_k_tokens, num_heads_kv, head_dim] cu_seqlens_q: Cumulative sequence lengths for queries, shape [batch_size + 1], dtype must be torch.int32 cu_seqlens_k: Cumulative sequence lengths for keys, shape [batch_size + 1], dtype must be torch.int32 max_seqlen_q: Maximum sequence length in the query batch max_seqlen_k: Maximum sequence length in the key batch do_causal: Whether to apply causal masking scale: Attention scale factor (default: 1/sqrt(head_dim)) softcapping: Softcapping value (default: 1.0, must be 1.0 for this implementation) Note: - cu_seqlens_q and cu_seqlens_k must have dtype torch.int32 for Metal compatibility - Supported head dimensions: 32, 64, 72, 80, 96, 128 - Masks are not supported """ if scale is None: scale = query.shape[-1] ** -0.5 ops.flash_attention_varlen( out, query, key, value, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, do_causal, scale, softcapping, )
def flash_attn_varlen_func( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens_q: torch.Tensor, cu_seqlens_k: torch.Tensor, max_seqlen_q: int, max_seqlen_k: int, dropout_p: float = 0.0, softmax_scale: Optional[float] = None, causal: bool = False, window_size: tuple = (-1, -1), alibi_slopes: Optional[torch.Tensor] = None, deterministic: bool = False, return_attn_probs: bool = False,) -> torch.Tensor: """ Flash Attention function with API compatible with the original Flash Attention. Note: This implementation does not support: - dropout - window attention - alibi slopes - returning attention probabilities """ if dropout_p > 0: raise NotImplementedError("Dropout is not supported in this implementation") if window_size != (-1, -1): raise NotImplementedError("Window attention is not supported") if alibi_slopes is not None: raise NotImplementedError("ALiBi is not supported") if return_attn_probs: raise NotImplementedError("Returning attention probabilities is not supported") # Create output tensor out = torch.empty_like(q) # Call the kernel flash_attention_varlen( out=out, query=q, key=k, value=v, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlen_k, do_causal=causal, scale=softmax_scale, softcapping=1.0, ) return out
__all__ = [ "flash_attention_varlen", "flash_attn_varlen_func",]123version https://git-lfs.github.com/spec/v1oid sha256:1e1e601611f0ce3c144c37ab6bd20b807ed4d4bd27053ffc8fa56eb3e470d2a9size 732920123456789import torchfrom . import _metal_flash_sdpa_metal_8924527ops = torch.ops._metal_flash_sdpa_metal_8924527
def add_op_namespace_prefix(op_name: str): """ Prefix op by namespace. """ return f"_metal_flash_sdpa_metal_8924527::{op_name}"12345{ "version": 1, "license": "Apache-2.0", "python-depends": []}1234567891011121314151617181920212223242526import ctypesimport sys
import importlibfrom pathlib import Pathfrom types import ModuleType
def _import_from_path(file_path: Path) -> ModuleType: # We cannot use the module name as-is, after adding it to `sys.modules`, # it would also be used for other imports. So, we make a module name that # depends on the path for it to be unique using the hex-encoded hash of # the path. path_hash = "{:x}".format(ctypes.c_size_t(hash(file_path.absolute())).value) module_name = path_hash spec = importlib.util.spec_from_file_location(module_name, file_path) if spec is None: raise ImportError(f"Cannot load spec for {module_name} from {file_path}") module = importlib.util.module_from_spec(spec) if module is None: raise ImportError(f"Cannot load module {module_name} from spec") sys.modules[module_name] = module spec.loader.exec_module(module) # type: ignore return module
globals().update(vars(_import_from_path(Path(__file__).parent.parent / "__init__.py")))1234567891011from ._custom_ops import ( flash_attention_varlen, flash_attn_varlen_func,)from ._ops import ops
__all__ = [ "flash_attention_varlen", "flash_attn_varlen_func", "ops",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117from typing import List, Optional
import torch
from ._ops import ops
def flash_attention_varlen( out: torch.Tensor, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, cu_seqlens_q: torch.Tensor, cu_seqlens_k: torch.Tensor, max_seqlen_q: int, max_seqlen_k: int, do_causal: bool = False, scale: Optional[float] = None, softcapping: float = 1.0,) -> None: """ Flash Attention with variable-length sequences. Args: out: Output tensor of shape [total_q_tokens, num_heads, head_dim] query: Query tensor of shape [total_q_tokens, num_heads, head_dim] key: Key tensor of shape [total_k_tokens, num_heads_kv, head_dim] value: Value tensor of shape [total_k_tokens, num_heads_kv, head_dim] cu_seqlens_q: Cumulative sequence lengths for queries, shape [batch_size + 1], dtype must be torch.int32 cu_seqlens_k: Cumulative sequence lengths for keys, shape [batch_size + 1], dtype must be torch.int32 max_seqlen_q: Maximum sequence length in the query batch max_seqlen_k: Maximum sequence length in the key batch do_causal: Whether to apply causal masking scale: Attention scale factor (default: 1/sqrt(head_dim)) softcapping: Softcapping value (default: 1.0, must be 1.0 for this implementation) Note: - cu_seqlens_q and cu_seqlens_k must have dtype torch.int32 for Metal compatibility - Supported head dimensions: 32, 64, 72, 80, 96, 128 - Masks are not supported """ if scale is None: scale = query.shape[-1] ** -0.5 ops.flash_attention_varlen( out, query, key, value, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, do_causal, scale, softcapping, )
def flash_attn_varlen_func( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens_q: torch.Tensor, cu_seqlens_k: torch.Tensor, max_seqlen_q: int, max_seqlen_k: int, dropout_p: float = 0.0, softmax_scale: Optional[float] = None, causal: bool = False, window_size: tuple = (-1, -1), alibi_slopes: Optional[torch.Tensor] = None, deterministic: bool = False, return_attn_probs: bool = False,) -> torch.Tensor: """ Flash Attention function with API compatible with the original Flash Attention. Note: This implementation does not support: - dropout - window attention - alibi slopes - returning attention probabilities """ if dropout_p > 0: raise NotImplementedError("Dropout is not supported in this implementation") if window_size != (-1, -1): raise NotImplementedError("Window attention is not supported") if alibi_slopes is not None: raise NotImplementedError("ALiBi is not supported") if return_attn_probs: raise NotImplementedError("Returning attention probabilities is not supported") # Create output tensor out = torch.empty_like(q) # Call the kernel flash_attention_varlen( out=out, query=q, key=k, value=v, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlen_k, do_causal=causal, scale=softmax_scale, softcapping=1.0, ) return out
__all__ = [ "flash_attention_varlen", "flash_attn_varlen_func",]123version https://git-lfs.github.com/spec/v1oid sha256:c876534ff49ce35e464a4b282a44207bb291604fd3fafc3adff2c1c6a27111c6size 732216123456789import torchfrom . import _metal_flash_sdpa_metal_8924527ops = torch.ops._metal_flash_sdpa_metal_8924527
def add_op_namespace_prefix(op_name: str): """ Prefix op by namespace. """ return f"_metal_flash_sdpa_metal_8924527::{op_name}"12345{ "version": 1, "license": "Apache-2.0", "python-depends": []}1234567891011121314151617181920212223242526import ctypesimport sys
import importlibfrom pathlib import Pathfrom types import ModuleType
def _import_from_path(file_path: Path) -> ModuleType: # We cannot use the module name as-is, after adding it to `sys.modules`, # it would also be used for other imports. So, we make a module name that # depends on the path for it to be unique using the hex-encoded hash of # the path. path_hash = "{:x}".format(ctypes.c_size_t(hash(file_path.absolute())).value) module_name = path_hash spec = importlib.util.spec_from_file_location(module_name, file_path) if spec is None: raise ImportError(f"Cannot load spec for {module_name} from {file_path}") module = importlib.util.module_from_spec(spec) if module is None: raise ImportError(f"Cannot load module {module_name} from spec") sys.modules[module_name] = module spec.loader.exec_module(module) # type: ignore return module
globals().update(vars(_import_from_path(Path(__file__).parent.parent / "__init__.py")))build/torch210-metal-aarch64-darwin/__init__.pyAdded+11
build/torch210-metal-aarch64-darwin/_custom_ops.pyAdded+117
build/torch210-metal-aarch64-darwin/_metal_flash_sdpa_metal_8924527.abi3.soAdded+3
build/torch210-metal-aarch64-darwin/_ops.pyAdded+9
build/torch210-metal-aarch64-darwin/metadata.jsonAdded+5
build/torch210-metal-aarch64-darwin/metal_flash_sdpa/__init__.pyAdded+26
build/torch29-metal-aarch64-darwin/__init__.pyAdded+11
build/torch29-metal-aarch64-darwin/_custom_ops.pyAdded+117
build/torch29-metal-aarch64-darwin/_metal_flash_sdpa_metal_8924527.abi3.soAdded+3
build/torch29-metal-aarch64-darwin/_ops.pyAdded+9
build/torch29-metal-aarch64-darwin/metadata.jsonAdded+5
build/torch29-metal-aarch64-darwin/metal_flash_sdpa/__init__.pyAdded+26