Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
711 changes: 711 additions & 0 deletions areno/accel/kernels/kivi.py

Large diffs are not rendered by default.

45 changes: 45 additions & 0 deletions areno/engine/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ class RuntimeConfig:
# checkpoint's MTP layer and verify them in one target forward. 0 = off.
# Requires the flash attention backend and a model with MTP layers.
speculative_draft_tokens: int = 0
# Rollout/serving KV-cache storage. "auto" keeps the model dtype; "kivi2"
# and "kivi4" store KIVI asymmetric 2/4-bit codes (keys per channel,
# values per token) and keep the most recent tokens in full precision.
kv_cache_dtype: Literal["auto", "kivi2", "kivi4"] = "auto"
kivi_group_size: int = 32
kivi_residual_length: int = 128
decode_graph_buckets: list[int] = field(
default_factory=lambda: [1, 2, 4, 8, 12, 16, 24, 32, 40, 48, 56, 64, 96, 128, 192, 256]
)
Expand Down Expand Up @@ -123,6 +129,12 @@ def __post_init__(self) -> None:
raise ValueError("runtime.optimizer_state_offload_batch_size must be positive")
if self.speculative_draft_tokens < 0:
raise ValueError("runtime.speculative_draft_tokens must be non-negative")
if self.kv_cache_dtype not in {"auto", "kivi2", "kivi4"}:
raise ValueError("runtime.kv_cache_dtype must be one of: auto, kivi2, kivi4")
if self.kivi_group_size < 32 or self.kivi_group_size & (self.kivi_group_size - 1):
raise ValueError("runtime.kivi_group_size must be a power of two >= 32")
if self.kivi_residual_length < 0:
raise ValueError("runtime.kivi_residual_length must be non-negative")

def resolve_attn_backend(self, *, model: ModelConfig, devices: list[int]) -> None:
"""Switch flash-attn unsupported hardware or model shapes to native attention."""
Expand Down Expand Up @@ -187,6 +199,38 @@ def resolve_eager_decode(self, *, model: ModelConfig, lora: LoraConfig | None) -
)
self.eager_decode = True

def resolve_kv_cache_dtype(self, *, model: ModelConfig) -> None:
"""Fall back to the model-dtype KV cache where KIVI storage is unsupported."""

if self.kv_cache_dtype == "auto":
return
reasons = []
if self.device_type != "cuda":
reasons.append("KIVI kernels require CUDA")
if model.model_type not in KIVI_MODEL_TYPES:
reasons.append(f"model_type {model.model_type!r} has no KIVI attention cache")
if self.speculative_draft_tokens > 0:
reasons.append("speculative decoding verifies several tokens per step")
group = self.kivi_group_size
if model.head_dim & (model.head_dim - 1) or model.head_dim % group:
reasons.append(f"head_dim {model.head_dim} is not a power of two divisible by kivi_group_size {group}")
if self.kv_block_size % group:
reasons.append(f"kivi_group_size {group} does not divide kv_block_size {self.kv_block_size}")
if not reasons:
return
warnings.warn(
f"KIVI KV cache is unavailable for the detected configuration ({'; '.join(reasons)}); "
"falling back to kv_cache_dtype='auto' (model-dtype KV cache).",
RuntimeWarning,
stacklevel=2,
)
self.kv_cache_dtype = "auto"


# Model families whose decoder attention is the shared dense CausalSelfAttention
# with full (non-windowed) causal masks; others keep the model-dtype cache.
KIVI_MODEL_TYPES = frozenset({"qwen3"})


@dataclass(slots=True)
class ModelConfig:
Expand Down Expand Up @@ -408,6 +452,7 @@ def __post_init__(self) -> None:
self.runtime.resolve_attn_backend(model=self.model, devices=self.devices)
self.runtime.resolve_compile_model(model=self.model, devices=self.devices)
self.runtime.resolve_eager_decode(model=self.model, lora=self.lora)
self.runtime.resolve_kv_cache_dtype(model=self.model)
self.model.attn_backend = self.runtime.attn_backend
# Train and rollout partitions share this runtime, so both sides agree
# on whether MTP tensors exist and the policy-sync plans stay aligned.
Expand Down
33 changes: 31 additions & 2 deletions areno/engine/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,37 @@ def _init_infer_cache(self, spec: InferCacheSpec) -> None:
)
if self.config.runtime.speculative_draft_tokens > 0:
self._enable_speculative_draft()
caches = self.model.allocate_kv_caches(self._infer_cache_blocks, block_size, self.device)
self.model.set_kv_caches(caches, num_slots=max_running_seqs + 1)
runtime = self.config.runtime
if runtime.kv_cache_dtype == "auto":
caches = self.model.allocate_kv_caches(self._infer_cache_blocks, block_size, self.device)
self.model.set_kv_caches(caches, num_slots=max_running_seqs + 1)
else:
from areno.engine.layers.attention_backend.kivi import KIVI_BITS, KiviSpec, attach_kivi_kv_caches

# KIVI keeps the paged block budget and adds one residual ring per
# rollout slot, including the scratch slot used by padded graph rows.
kivi_caches = attach_kivi_kv_caches(
self.model,
KiviSpec(
bits=KIVI_BITS[runtime.kv_cache_dtype],
group_size=runtime.kivi_group_size,
residual_length=runtime.kivi_residual_length,
),
num_blocks=self._infer_cache_blocks,
block_size=block_size,
num_slots=max_running_seqs + 1,
device=self.device,
dtype=self.config.model.dtype,
)
logger.info(
"KIVI KV cache: dtype=%s group_size=%d residual_length=%d blocks=%d slots=%d bytes=%d",
runtime.kv_cache_dtype,
runtime.kivi_group_size,
runtime.kivi_residual_length,
self._infer_cache_blocks,
max_running_seqs + 1,
sum(cache.nbytes() for cache in kivi_caches),
)
self._train_state_ready = False
# Materialise infer weights from train weights (e.g. dequantize / fuse),
# then drop the train copies for the rollout's duration.
Expand Down
17 changes: 17 additions & 0 deletions areno/engine/layers/attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

from areno.engine.config import ModelConfig
from areno.engine.layers.attention_backend.infer import FlashAttnInferBackend, build_infer_attention_backend
from areno.engine.layers.attention_backend.kivi import KiviInferBackend, KiviKVCache
from areno.engine.layers.attention_backend.train import build_train_attention_backend
from areno.engine.layers.linear import QKVParallelLinear, RowParallelLinear
from areno.engine.layers.norm import RMSNorm
Expand Down Expand Up @@ -72,6 +73,9 @@ def __init__(self, config: ModelConfig, layer_idx: int, *, rotary_embedding: nn.
self.infer_backend: FlashAttnInferBackend | None = None
self.k_cache = torch.tensor([])
self.v_cache = torch.tensor([])
# Opt-in KIVI low-bit cache; replaces k_cache/v_cache when attached.
self.kivi_cache: KiviKVCache | None = None
self.kivi_backend: KiviInferBackend | None = None

def forward(
self,
Expand Down Expand Up @@ -130,6 +134,12 @@ def forward_train(
def forward_infer(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, infer_meta: InferMeta) -> torch.Tensor:
"""Run inference attention against the per-layer paged KV cache."""

if self.kivi_cache is not None:
if self.kivi_backend is None:
self.kivi_backend = KiviInferBackend(self.attn_backend)
out = self.kivi_backend(q, k, v, self.kivi_cache, infer_meta)
out = out.contiguous().view(q.shape[0], q.shape[1], self.local_heads * self.head_dim)
return self.o_proj(out)
if self.k_cache.numel() == 0 or self.v_cache.numel() == 0:
raise RuntimeError("inference requires per-layer KV cache tensors")
# Lazy backend init so the FlashAttention functions are only bound when
Expand All @@ -146,9 +156,16 @@ def set_kv_cache(self, k_cache: torch.Tensor, v_cache: torch.Tensor) -> None:
self.k_cache = k_cache
self.v_cache = v_cache

def set_kivi_cache(self, cache: KiviKVCache) -> None:
"""Attach a KIVI low-bit cache owned by the runtime."""

self.kivi_cache = cache

def clear_kv_cache(self) -> None:
"""Detach KV-cache buffers and the cached inference backend."""

self.k_cache = torch.tensor([])
self.v_cache = torch.tensor([])
self.infer_backend = None
self.kivi_cache = None
self.kivi_backend = None
Loading