From Layers to a Hybrid Model

Introduction

Project introduction

From Layers to a Hybrid Model

You have now written every layer a hybrid model is made of. These are a sliding window mask, grouped-query attention, linear attention as a running state, and the gated delta rule. You can also count, to the byte, how much memory any mix of layers keeps.

In the notebook these layers run inside seven small trained models. Each one read sequences with 8 facts at the start, a long stretch of filler text, and then questions about the facts. Every model uses your attention functions, so its scores come from your code.

What you will see

The sliding window model and the linear attention models predict the filler text as well as full attention does, yet once the facts are far enough back they answer few of the questions. The window model and the gated one answer about as often as a guess, and the plain linear one about one in seven, falling further as the gap grows. Adding a single full attention layer brings the answers back, while keeping a fraction of the full model's cache.

You will measure the cache by generating with each model token by token, check it against your own count, and then apply the same count to Llama 3.1 8B, Gemma 3's layer pattern and Qwen3.5 9B. The models here are tiny and trained on a toy task on a CPU, so the numbers show the shape of the tradeoff, not the exact behavior of large models.

Cache as the text grows

2,048 tokens read
FFFFFFFF
64.0 MB

all full: can recall far back

SSSSSSSS
32.0 MB

all window: loses facts from far back

LLLLLLLL
2.0 MB

all linear: loses facts from far back

SSSFSSSF
40.0 MB

hybrid: can recall far back

F full attention · S sliding window of 1024 · L linear attention · 8 layers, 8 key/value heads of 128, 16-bit

How the notebook is organized

01

Full attention and its cache

Causal and grouped-query attention, and what the cache costs.

02

What cheap layers forget

Sliding window and linear attention models that match on local text but lose the facts.

03

The hybrid fix

One full layer among cheap ones, then the same choice at real model sizes.

Build hybrid attention in the notebook

Plug your layers into trained models in the browser, about 45 minutes.

Open the notebook project