# lucidrains/fast-weight-product-key-memory architecture

> Architecture diagram of the GitHub repository lucidrains/fast-weight-product-key-memory, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-27). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/lucidrains/fast-weight-product-key-memory
- Repository: https://github.com/lucidrains/fast-weight-product-key-memory

## Overview

1. **Repository purpose**
   - This is a small Python library plus example training code for **Fast Weight Product Key Memory (fwPKM)**, a learned memory module from the cited paper.
   - The architecture is centered on a reusable memory component, with separate scripts for toy validation and an Enwik8 language-model experiment.

2. **Core package boundary**
   - The installable library lives under `fast_weight_product_key_memory/`.
   - `fast_weight_product_key_memory/__init__.py` exposes the public API, so downstream users import the memory module from the package root.
   - `fast_weight_product_key_memory/fwPKM.py` is the main implementation file and is the architectural center of the repo.

3. **Primary runtime dependency**
   - The implementation is PyTorch-based, as shown by the usage example with `torch.randn(...)` and tensor-shaped inputs/outputs.
   - The module operates on batched token embeddings, so the key abstraction is a tensor pipeline rather than a service or data API.

4. **fwPKM module behavior**
   - The `fwPKM` object accepts token embeddings and returns:
     - `retrieved`: memory-augmented representations
     - `next_memories`: updated fast-weight / episodic memory state
   - The design supports **stateful chaining** across chunks by passing `past_memories` back into later calls, which is important for diagramming data flow.

5. **Chunked sequence processing**
   - The usage example shows the model processing sequences in fixed-size chunks (`chunk_size=256`).
   - This means memory updates and retrieval happen incrementally over subsequences, not only on full-length sequences at once.
   - For an architecture diagram, show a loop or pipeline over token chunks with state carried forward between chunks.

6. **Memory structure and parameters**
   - The module is configured by hyperparameters such as `dim`, `num_memories`, `dim_queries_keys`, `dim_values`, `topk`, `learning_rate`, and `chunk_size`.
   - These parameters indicate the module combines learned key/query matching with sparse top-k retrieval and a fast-weight update rule.
   - `num_memories` suggests a large associative memory table; `topk` implies sparse selection of candidate slots.

7. **Training / experiment entry points**
   - `train_toy_memory_task.py` is likely a minimal correctness or behavior demo for the memory module.
   - `train_enwik8.py` is the main benchmark script for character-level language modeling on Enwik8.
   - These scripts sit outside the library package and serve as consumers of the core `fwPKM` component.

8. **Dataset and local asset**
   - `data/enwik8.gz` is bundled in the repository, indicating the Enwik8 experiment can run from local data without fetching a remote dataset at runtime.
   - The data directory is not a general-purpose data layer; it is an experiment asset for the training script.

9. **Testing boundary**
   - `tests/test_memory.py` is the main automated test file and likely focuses on memory behavior, shape correctness, or state chaining.
   - This is the main verification boundary for the library portion of the repo.

10. **Packaging and developer workflow**
   - `pyproject.toml` defines the project as a Python package and supports installation via `pip`.
   - The README uses `uv run train_enwik8.py`, so `uv` is part of the intended local development/training workflow.
   - There are no external services, databases, or web endpoints; the architecture is entirely local computation around a PyTorch module and experiment scripts.

Main entry points: [`fast_weight_product_key_memory/fwPKM.py`](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/fast_weight_product_key_memory/fwPKM.py) (fwPKM), [`train_enwik8.py`](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/train_enwik8.py) (Enwik8 Train), [`README.md`](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/README.md) (README), [`fast_weight_product_key_memory/__init__.py`](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/fast_weight_product_key_memory/__init__.py) (Package API)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_pkg["Library"]
  node_n1["fwPKM<br/>memory module<br/>[fwPKM.py]"]
  node_n2["Package API<br/>public export<br/>[__init__.py]"]
  node_n7["Token Embeddings<br/>tensor input"]
  node_n8["Retrieved Output<br/>tensor output"]
  node_n9{{"Top-k Match<br/>sparse lookup"}}
  node_n10{{"Fast Update<br/>write rule"}}
  node_n11["Hyperparameters<br/>config surface"]
  node_n14["PyProject<br/>package config<br/>[pyproject.toml]"]
end

subgraph group_experiments["Experiments"]
  node_n3["Toy Train<br/>demo script"]
  node_n4["Enwik8 Train<br/>benchmark script<br/>[train_enwik8.py]"]
  node_n5(("Chunk Loop<br/>sequence pipeline"))
  node_n6[("Memory State<br/>fast state")]
  node_n15["README<br/>usage guide<br/>[README.md]"]
end

subgraph group_verification["Verification"]
  node_n12["Tests<br/>pytest suite<br/>[test_memory.py]"]
end

subgraph group_assets["Assets"]
  node_n13["Enwik8 Data<br/>dataset asset<br/>[enwik8.gz]"]
end

node_n2 -->|"exports"| node_n1
node_n3 -->|"uses"| node_n1
node_n4 -->|"uses"| node_n1
node_n1 -->|"consumes"| node_n7
node_n1 -->|"returns"| node_n8
node_n1 -->|"retrieves via"| node_n9
node_n1 -->|"updates via"| node_n10
node_n1 -->|"parameterized by"| node_n11
node_n4 -->|"reads"| node_n13
node_n4 -->|"runs"| node_n5
node_n5 -->|"threads state"| node_n6
node_n6 -->|"feeds back"| node_n1
node_n12 -->|"verifies"| node_n1
node_n14 -->|"packages"| node_n2
node_n15 -->|"documents"| node_n4
node_n15 -->|"documents"| node_n3

click node_n1 "https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/fast_weight_product_key_memory/fwPKM.py"
click node_n2 "https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/fast_weight_product_key_memory/__init__.py"
click node_n3 "https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/train_toy_memory_task.py"
click node_n4 "https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/train_enwik8.py"
click node_n12 "https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/tests/test_memory.py"
click node_n13 "https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/data/enwik8.gz"
click node_n14 "https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/pyproject.toml"
click node_n15 "https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/README.md"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_n1,node_n2,node_n7,node_n8,node_n9,node_n10,node_n11,node_n14 toneBlue
class node_n3,node_n4,node_n5,node_n6,node_n15 toneAmber
class node_n12 toneMint
class node_n13 toneRose
```

## Components

### Library

Installable fwPKM package and core implementation.

- [fwPKM](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/fast_weight_product_key_memory/fwPKM.py): memory module · Core fast-weight product key memory implementation. · `fast_weight_product_key_memory/fwPKM.py`
- [Package API](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/fast_weight_product_key_memory/__init__.py): public export · Package root that exposes the reusable memory module. · `fast_weight_product_key_memory/__init__.py`
- **Token Embeddings**: tensor input · Batched embeddings passed into fwPKM.
- **Retrieved Output**: tensor output · Memory-augmented representations returned by fwPKM.
- **Top-k Match**: sparse lookup · Selects candidate memory slots using key/query similarity.
- **Fast Update**: write rule · Updates episodic memory state after retrieval.
- **Hyperparameters**: config surface · Model settings such as dim, num_memories, topk, and chunk_size.
- [PyProject](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/pyproject.toml): package config · Project metadata and dependency definition for installation. · `pyproject.toml`

### Experiments

Training entry points that consume the memory module.

- [Toy Train](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/train_toy_memory_task.py): demo script · Minimal training script for validating memory behavior. · `train_toy_memory_task.py`
- [Enwik8 Train](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/train_enwik8.py): benchmark script · Main character-level language modeling experiment. · `train_enwik8.py`
- **Chunk Loop**: sequence pipeline · Processes token embeddings in fixed-size chunks.
- **Memory State**: fast state · Carries past memories forward across chunked calls.
- [README](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/README.md): usage guide · Documents the intended training and development workflow. · `README.md`

### Verification

Automated checks for memory behavior and interfaces.

- [Tests](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/tests/test_memory.py): pytest suite · Automated checks for shapes, chaining, and memory behavior. · `tests/test_memory.py`

### Assets

Bundled local data used by experiments.

- [Enwik8 Data](https://github.com/lucidrains/fast-weight-product-key-memory/blob/main/data/enwik8.gz): dataset asset · Bundled gzip-compressed corpus for the language-model experiment. · `data/enwik8.gz`

## Connections

- Package API → fwPKM: exports · Public package root exposes the fwPKM module.
- Toy Train → fwPKM: uses · Toy training script instantiates the core memory module.
- Enwik8 Train → fwPKM: uses · Enwik8 training script depends on fwPKM for sequence modeling.
- fwPKM → Token Embeddings: consumes · Accepts token embeddings as input tensors.
- fwPKM → Retrieved Output: returns · Produces retrieved representations and updated memory state.
- fwPKM → Top-k Match: retrieves via · Matches queries against memory slots using sparse top-k selection.
- fwPKM → Fast Update: updates via · Applies fast-weight updates to memory state.
- fwPKM → Hyperparameters: parameterized by · Behavior is controlled by model and chunking hyperparameters.
- Enwik8 Train → Enwik8 Data: reads · Enwik8 benchmark uses the bundled local dataset asset.
- Enwik8 Train → Chunk Loop: runs · Training proceeds over fixed-size sequence chunks.
- Chunk Loop → Memory State: threads state · Carries past memories from one chunk to the next.
- Memory State → fwPKM: feeds back · Previous memory state is passed into later fwPKM calls.
- Tests → fwPKM: verifies · Tests focus on the core memory module.
- PyProject → Package API: packages · Project metadata enables installation of the library package.
- README → Enwik8 Train: documents · README describes the Enwik8 training workflow.
- README → Toy Train: documents · README also covers toy validation usage.
