Metadata-Version: 2.4
Name: fade-kv
Version: 1.1.0
Summary: FADE: Frequency-Adaptive Decay Encoding — attention-aware tiered KV cache compression for LLM inference.
Author-email: Omodaka9375 <branislav.djalic@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for describing the origin of the Work and
              reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Branislav Đalić
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/Omodaka9375/fade
Project-URL: Issues, https://github.com/Omodaka9375/fade/issues
Project-URL: Changelog, https://github.com/Omodaka9375/fade/blob/main/CHANGELOG.md
Keywords: llm,inference,kv-cache,quantization,transformers
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: torch>=2.2
Requires-Dist: transformers<5.4,>=4.45
Requires-Dist: numpy>=1.26
Requires-Dist: tqdm>=4.66
Provides-Extra: cuda
Requires-Dist: accelerate>=0.34; extra == "cuda"
Provides-Extra: eval
Requires-Dist: datasets>=2.20; extra == "eval"
Requires-Dist: accelerate>=0.34; extra == "eval"
Provides-Extra: codebook
Requires-Dist: scikit-learn>=1.4; extra == "codebook"
Provides-Extra: turbo
Requires-Dist: turboquant-kv>=1.0; extra == "turbo"
Provides-Extra: server
Requires-Dist: fastapi>=0.100; extra == "server"
Requires-Dist: uvicorn>=0.20; extra == "server"
Requires-Dist: pydantic>=2.0; extra == "server"
Provides-Extra: serving
Provides-Extra: dev
Requires-Dist: pytest>=7.4; extra == "dev"
Requires-Dist: pytest-xdist>=3.5; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: pyright>=1.1.380; extra == "dev"
Requires-Dist: pre-commit>=3.7; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Dynamic: license-file

# FADE

[![CI](https://github.com/Omodaka9375/fade/actions/workflows/ci.yml/badge.svg)](https://github.com/Omodaka9375/fade/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-brightgreen.svg)](https://python.org)
[![PyPI](https://img.shields.io/pypi/v/fade-kv.svg?cacheSeconds=3600)](https://pypi.org/project/fade-kv/)
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Omodaka9375/fade/blob/main/examples/quickstart.ipynb)

**Frequency-Adaptive Decay Encoding** — drop-in KV cache compression for HuggingFace transformers. Shrinks the KV cache **3.5–12×** with near-baseline quality (up to 23× in aggressive mode — validate on your workload).

```python
from fade import FadeConfig, create_tiered_cache

cache = create_tiered_cache(model, config=FadeConfig.safe())
out = model.generate(input_ids, past_key_values=cache, max_new_tokens=256)
```

Works with `model.generate()` — greedy, sampling, beam search. No manual decode loop needed.

## How it works

Tokens live in tiers based on age and attention importance:

| Tier | What's stored | When |
|------|--------------|------|
| **FP16** | Full precision | First `N_SINK` tokens + last `RECENT_WINDOW` tokens |
| **INT4** | Bit-packed 4-bit | Middle-aged tokens (the bulk of the cache) |
| **INT2** | Grouped 2-bit | Optional deeper compression (lossy) |
| **PQ** | Product-quantized codes | ~2 bits/element via trained codebook (Phase 3) |
| **Evicted** | Nothing | Dropped when `INT4_BUDGET` is finite |

When tokens are evicted, surviving K tensors are un-RoPE'd at old positions and re-RoPE'd with contiguous StreamingLLM positions.

```mermaid
flowchart LR
    A["New Token"] --> B["FP16 Tier\n(sinks + recent)"]
    B -->|reassign| C["INT4 Tier\n(middle)"]
    C -->|budget full| D["INT2 / PQ\n(deep compress)"]
    D -->|evict| E["Dropped\n(re-RoPE survivors)"]
    style A fill:#4CAF50,color:#fff
    style B fill:#2196F3,color:#fff
    style C fill:#FF9800,color:#fff
    style D fill:#f44336,color:#fff
    style E fill:#9E9E9E,color:#fff
```

### Compression at a glance

| Config | KV cache | Compression |
|--------|----------|:-----------:|
| Baseline FP16 | 112.00 MiB | 1× |
| Safe (INT4) | 31.24 MiB | **3.6×** |
| Rotated 2-bit | 17.70 MiB | **6.3×** |
| Balanced (eviction) | 9.30 MiB | **12.0×** |
| Aggressive | 4.77 MiB | **23.5×** |

> Qwen2.5-7B-Instruct, 2048 tokens, DGX Spark. Needle: 4/4 PASS (512–4096). WikiText-2 PPL: 6.56.

### Fused kernel speed

| Path | Latency | vs FP16 |
|------|:-------:|:-------:|
| FP16 FlashAttention | 0.133 ms | 1.0× |
| **Fused INT4 (FADE)** | **0.189 ms** | **1.4×** |
| Dequant + SDPA (old) | 0.932 ms | 7.0× |

### How FADE compares (2026)

| | **FADE** | **kvpress** (NVIDIA) | **TurboQuant** (Google, ICLR 2026) | **KVTC** (NVIDIA, ICLR 2026) |
|---|---|---|---|---|
| **Approach** | Tiered quant + eviction + re-RoPE | Token eviction / scoring (30+ methods) | Rotation + Lloyd-Max codebook | PCA + DP bit allocation + entropy coding |
| **Compression** | 3.5–12× (23× aggressive) | 2–10× (eviction only) | 4–6× (3.5-bit zero-loss claimed) | 6–20× (up to 40× with entropy) |
| **Quantization** | INT4/INT2/PQ + rotated 2-bit | Via HF `QuantizedCache` | 3–4 bit | 1–6 bit adaptive |
| **Eviction** | H2O, EMA, position, adaptive, learned | 30+ methods (SnapKV, TOVA, KVzap, etc.) | None | None |
| **Re-RoPE** | ✅ StreamingLLM contiguous | Partial (KeyRerotationPress, FinchPress) | ❌ | ✅ (undo before PCA) |
| **Fused kernel** | ✅ Triton INT4 FlashAttn | ❌ | ✅ Triton fused | ✅ Triton |
| **HF generate()** | ✅ Drop-in | Pipeline + context manager | ✅ Drop-in | ❌ |
| **Serving** | ✅ fade-server (OpenAI API) | ❌ | ✅ vLLM / SGLang integration | ❌ |
| **Hybrid models** | ✅ Qwen 3.5 DeltaNet skip | ❌ | ❌ | ❌ |
| **Per-sequence batching** | ✅ Ragged tiers | ❌ | ❌ | ❌ |
| **Stars** | New | 1K+ | 1K+ (across implementations) | ~10 |
| **Install** | `pip install fade-kv` | `pip install kvpress` | `pip install turboquant-kv` | From source |

**FADE's unique advantage**: only system that combines quantization + attention-aware eviction + correct re-RoPE in one drop-in cache.

## Install

**From PyPI:**
```pwsh
pip install fade-kv
pip install fade-kv[server]  # adds fade-server CLI
```

**From source (development):**
```pwsh
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install torch  # match your CUDA version: https://pytorch.org/get-started/locally/
pip install -e ".[dev]"
```

Optional extras: `pip install fade-kv[cuda]` (accelerate), `fade-kv[eval]` (datasets), `fade-kv[codebook]` (scikit-learn for PQ).

## Quick start

### Presets

```python
from fade import FadeConfig, create_tiered_cache

# Safe: ~3-4x compression, no eviction.
cache = create_tiered_cache(model, config=FadeConfig.safe())

# Balanced: ~5x compression with H2O eviction.
cache = create_tiered_cache(model, config=FadeConfig.balanced())

# Aggressive: ~7-8x compression. Validate on your workload first.
cache = create_tiered_cache(model, config=FadeConfig.aggressive())
```

### Custom config

```python
cache = create_tiered_cache(model, config=FadeConfig(
    phase="2",
    n_sink=4,
    recent_window=64,
    int4_budget=400,
    eviction_policy="h2o",       # "h2o", "ema", "position", or "learned"
    middle_k_bits=4,             # K stays INT4 (outlier-sensitive)
    middle_v_bits=2,             # V at INT2 (~30% more compression)
))
```

### Rotated 2-bit backend (~6× compression)

```python
from fade.backends import get_backend

cache = create_tiered_cache(model, config=FadeConfig.safe(),
    quant_backend=get_backend("rotated", head_dim=64, bits=2))
```

Random orthogonal rotation spreads per-channel outliers before quantization, making 2-bit viable. Uses native PyTorch — no external dependencies.

### Manual decode with tier reassignment

```python
from fade.patch import forward_with_tracking, load_model
from fade.policy import reassign_tiers
from fade.tracker import AttentionTracker

model, tokenizer = load_model("Qwen/Qwen2.5-3B-Instruct", attn_impl="auto", need_attentions=True)
cache = create_tiered_cache(model, config=FadeConfig.balanced())
tracker = AttentionTracker(num_layers=model.config.num_hidden_layers)

out = forward_with_tracking(model, input_ids, cache, tracker=tracker)
for step in range(max_tokens):
    out = forward_with_tracking(model, next_token, cache, tracker=tracker)
    if (step + 1) % 64 == 0:
        reassign_tiers(cache, tracker, model.config.num_hidden_layers)
```

## Eviction policies

| Policy     | Quality | Speed  | Needs attention?   |
|------------|---------|--------|--------------------|
| `h2o`      | Best    | Normal | Yes (prefill only) |
| `ema`      | Good    | Normal | Yes (decode only)  |
| `adaptive` | Good    | Normal | Yes (decode EMA)   |
| `position` | Fair    | Fast   | No                 |
| `learned`  | Good*   | Fast   | No                 |

`adaptive` splits middle tokens by attention score: high→INT4, low→INT2, lowest→evict.

*Learned policy requires a trained checkpoint: `python scripts/train_eviction_mlp.py`

## Supported models

FADE auto-detects the RoPE scheme from the model config:

- **Qwen2 / Qwen3** — vanilla RoPE, GQA
- **Llama / Llama-3.1** — vanilla + frequency-dependent scaling
- **Mistral** — vanilla RoPE, sliding-window
- **Phi-3** — vanilla RoPE
- **Gemma-2** — vanilla RoPE
- **Gemma 4** — proportional RoPE with `partial_rotary_factor` + per-layer-type dispatch
- **Falcon** — ALiBi (non-RoPE; re-RoPE is a no-op)
- **Qwen 3.5 / 3.6** — hybrid DeltaNet + softmax attention. FADE auto-detects `layer_types` and skips DeltaNet layers (only full-attention layers are tiered).

RoPE scaling types: `linear`, `llama3`, `ntk`, `dynamic`, `yarn`, `proportional`. Non-RoPE models (ALiBi, Bloom, MPT) work via the `NoRope` sentinel.

## Batching

Two modes:
- **Shared-tier** (default): all rows share positions and tier decisions. For lockstep decoding.
- **Per-sequence** (`apply_tier_assignment_per_sequence`): each row gets independent `[B, S]` tiers. For continuous-batching where sequences diverge.

## Performance

- **Fused INT4 FlashAttention kernel** — single Triton kernel reads packed INT4 K/V, computes attention with online softmax, writes fp16 output. Never materializes fp16 K/V. **4.9× faster** than the old dequant+SDPA path, within 1.4× of pure fp16 FlashAttention on RTX 3060.
- **Pre-allocated FP16 buffer** — doubling buffer eliminates `torch.cat` on every decode step.
- **torch.compile** — `cache.enable_compile()` wraps `_materialize` between graph-break boundaries.
- **Dequant-cache age eviction** — `cache.max_dequant_age = N` periodically refreshes cached dequant buffers.
- **Benchmarks** — `python benchmarks/tps.py` (decode throughput), `python benchmarks/divergence.py` (quality).

```python
# Use the fused kernel directly:
from fade.kernels.fused_int4_attn import fused_int4_sdpa
out = fused_int4_sdpa(q, k_packed, k_scale, v_packed, v_scale)
```

## Inference server

OpenAI-compatible API with automatic tier management:

```pwsh
fade-server --model Qwen/Qwen2.5-0.5B-Instruct --preset balanced --port 8000
```

```pwsh
curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d "{\"messages\":[{\"role\":\"user\",\"content\":\"Hello!\"}],\"max_tokens\":100}"
```

Endpoints: `/v1/chat/completions` (greedy + sampling), `/v1/models`, `/health`.

## Checkpointing

```python
sd = cache.cache_state_dict()
torch.save(sd, "cache.pt")
cache.load_cache_state_dict(torch.load("cache.pt"))
```

## Observability

```python
from fade.telemetry import JsonlExporter, attach_telemetry
attach_telemetry(cache, JsonlExporter("events.jsonl"))
```

Debug dump: `cache.dump_debug("snapshot.json")`

## PQ codebook

```python
from fade.codebook import PQCodebook
cb = PQCodebook.train(calibration_vectors, sub_dim=32, num_centroids=256)
cache.set_codebooks(cb)  # enables TIER_PQ in tier assignment
```

Train codebooks from a real model: `python scripts/train_codebook.py`

## Results

### DGX Spark — Qwen2.5-7B-Instruct (2048 tokens)

| Config | KV cache | Compression | Δ PPL | Decode TPS |
|--------|----------|:-----------:|:-----:|:----------:|
| Baseline FP16 | 112.00 MiB | 1.0× | — | 13.3 tok/s |
| Safe (INT4) | 31.24 MiB | **3.6×** | **0.00** | 13.3 tok/s |
| Rotated 2-bit | 17.70 MiB | **6.3×** | **0.00** | 13.3 tok/s |
| Balanced (eviction) | 9.30 MiB | **12.0×** | **0.00** | 13.3 tok/s |
| Aggressive | 4.77 MiB | **23.5×** | **0.00** | 13.3 tok/s |

> Needle: 4/4 PASS (512–4096 tokens). WikiText-2 PPL: 6.56. Δ PPL = 0.00 across all presets.

### DGX Spark — Mistral-7B-Instruct-v0.3 (2048 tokens)

| Config | KV cache | Compression | Decode TPS |
|--------|----------|:-----------:|:----------:|
| Baseline FP16 | 256.00 MiB | 1.0× | 15.3 tok/s |
| Safe (INT4) | 71.40 MiB | **3.6×** | 15.2 tok/s |
| Rotated 2-bit | 40.47 MiB | **6.3×** | 15.2 tok/s |
| Balanced (eviction) | 21.26 MiB | **12.0×** | 15.2 tok/s |
| Aggressive | 10.91 MiB | **23.5×** | 15.2 tok/s |

> Needle: 4/4 PASS (512–4096 tokens). WikiText-2 baseline PPL: 4.98.

### DGX Spark — Llama-3.1-8B-Instruct (2048 tokens)

| Config | KV cache | Compression | Decode TPS |
|--------|----------|:-----------:|:----------:|
| Baseline FP16 | 256.00 MiB | 1.0× | 14.4 tok/s |
| Safe (INT4) | 71.40 MiB | **3.6×** | 14.3 tok/s |
| Rotated 2-bit | 40.47 MiB | **6.3×** | 14.3 tok/s |
| Balanced (eviction) | 21.26 MiB | **12.0×** | 14.3 tok/s |
| Aggressive | 10.91 MiB | **23.5×** | 14.3 tok/s |

> Needle: 4/4 PASS (512–4096 tokens). WikiText-2 baseline PPL: 6.45. Llama-3.1 frequency-dependent RoPE scaling.

> All DGX Spark benchmarks: NVIDIA DGX Spark (Grace Blackwell, 128 GB unified memory).

### RTX 3060 — Qwen2.5-0.5B-Instruct (2048 tokens)

| Config | KV cache | Compression | Decode TPS |
|--------|----------|:-----------:|:----------:|
| Baseline FP16 | 24.00 MiB | 1.0× | 128.5 tok/s |
| Safe (INT4) | 6.78 MiB | **3.5×** | 125.8 tok/s |
| Rotated 2-bit | 3.88 MiB | **6.2×** | 125.9 tok/s |
| Balanced (eviction) | 2.01 MiB | **11.9×** | 125.8 tok/s |
| Aggressive | 1.03 MiB | **23.3×** | 125.9 tok/s |

> Needle: 4/4 PASS (512–4096 tokens). Baseline FP16 PPL: 1.24. TPS overhead: ~2%.

### Fused Triton kernel (RTX 3060)

| Path | Time | vs FP16 |
|------|------|---------|
| FP16 SDPA | 0.133 ms | 1.0× |
| Dequant + SDPA (old) | 0.932 ms | 7.0× slower |
| **Fused INT4 (new)** | **0.189 ms** | **1.4×** |

Run benchmarks yourself: `python benchmarks/production_suite.py`, `python benchmarks/full_suite.py`

## Project layout

```
fade/
  cache.py           # TieredKVCache with 5 tiers (FP16/INT4/INT2/PQ/evict)
  config.py          # FadeConfig with presets
  quant.py           # INT4/INT2 quantization + bit-packing
  rope.py            # 7 RoPE schemes incl. Gemma 4 proportional
  policy.py          # Tier assignment: h2o, ema, position
  learned_policy.py  # Learned eviction MLP
  tracker.py         # AttentionTracker (per-layer EMA)
  patch.py           # load_model, create_tiered_cache, forward_with_tracking
  codebook.py        # PQ codebook train/encode/decode
  telemetry.py       # Structured telemetry + exporters
  kernels/           # Fused INT4 FlashAttention kernel + unpack kernel + fallback
  serving/           # vLLM / SGLang adapter stubs
  eval/              # Perplexity, needle, quality suite
examples/            # quickstart.py
experiments/         # run_baseline.py, run_tiered.py
benchmarks/          # tps.py, divergence.py
scripts/             # train_eviction_mlp.py, train_codebook.py
tests/               # 136 tests, all CPU, no downloads
```

## Gotchas

1. **Attention impl**: `eager` only needed for H2O prefill. Use `load_model(attn_impl="auto")`.
2. **Transformers version**: verified on 4.45 and 5.3. Weekly canary CI runs against `transformers@main`.
3. **Memory**: use `cache.compressed_storage_bytes()`, not `nvidia-smi`.
4. **RoPE precision**: all math in float32, cast through model dtype to match rounding.
5. **Hybrid models**: Qwen 3.5/3.6 DeltaNet layers are auto-skipped — only full-attention layers are tiered.
6. **Triton kernels**: fused attention via `fused_int4_sdpa()`, unpack-only via `int4_sdpa(force_triton=True)`. Run `check_fused_parity()` to validate on your hardware.

## Citations

FADE builds on ideas from these papers (all independently reimplemented — see [NOTICE](NOTICE) for details):

- **H2O** — Zhang et al., 2023. *Heavy-Hitter Oracle for Efficient Generative Inference of LLMs.* [arXiv:2306.14048](https://arxiv.org/abs/2306.14048)
- **StreamingLLM** — Xiao et al., 2023. *Efficient Streaming Language Models with Attention Sinks.* [arXiv:2309.17453](https://arxiv.org/abs/2309.17453)
- **KIVI** — Liu et al., 2024. *A Tuning-Free KV Cache Quantization Algorithm.* [arXiv:2402.02750](https://arxiv.org/abs/2402.02750)
- **TurboQuant** — Zandieh et al., ICLR 2026. *Online Vector Quantization with Near-optimal Distortion Rate.* [arXiv:2504.19874](https://arxiv.org/abs/2504.19874)
- **KVTC** — Staniszewski & Łańcucki, ICLR 2026. *KV Cache Transform Coding for Compact Storage in LLM Inference.* [arXiv:2511.01815](https://arxiv.org/abs/2511.01815)
- **KnormPress** — Devoto et al., 2024. *A Simple and Effective L2 Norm-Based Strategy for KV Cache Compression.* [arXiv:2406.11430](https://arxiv.org/abs/2406.11430)

If you use FADE in your work:
```bibtex
@software{fade2026,
  title  = {FADE: Frequency-Adaptive Decay Encoding},
  author = {Branislav Đalić},
  url    = {https://github.com/Omodaka9375/fade},
  year   = {2026},
}
```

## License

Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
