---
title: FRSMASH-v3.6
canonical_url: "https://www.modelscope.cn/models/dfytensor/FRSMASH-v3.6"
md_url: "https://www.modelscope.cn/models/dfytensor/FRSMASH-v3.6.md"
repository: dfytensor/FRSMASH-v3.6
last_updated: 2026-07-02
pipeline_tag: text-generation
tasks:
  - text-generation
library_name:
  - pytorch
frameworks:
  - Pytorch
downloads: 0
stars: 0
---

# FRSMASH-v3.6

> FRSMASH-v3.6 - dfytensor 在 ModelScope 开源的模型。Fast Recursive State machine with Multi-slot Attention-recall System using Hybrid (SSM+GLA) architecture SSM backbone(长程平滑) + GLA recall(精确召回) + SlowMemory(慢记忆) 三路融合架构 —— 训练快、推理显存恒定、长程外推稳定、具备 associative recall 能力。

- **Repository**: dfytensor/FRSMASH-v3.6
- **Tasks**: text-generation
- **Downloads**: 0
- **Stars**: 0
- **Last updated**: 2026-07-02

Source: https://www.modelscope.cn/models/dfytensor/FRSMASH-v3.6

---

# FRSMASH v3.6

> **F**ast **R**ecursive **S**tate machine with **M**ulti-slot **A**ttention-recall **S**ystem using **H**ybrid (SSM+GLA) architecture
>
> SSM backbone(长程平滑) + GLA recall(精确召回) + SlowMemory(慢记忆) 三路融合架构 ——
> 训练快、推理显存恒定、长程外推稳定、具备 associative recall 能力。

---

## 目录
- [架构](#架构)
- [架构优势](#架构优势)
- [测试数据](#测试数据)
- [环境安装](#环境安装任何机器)
- [训练指南](#训练指南)
- [推理指南](#推理指南)
- [版本演进](#版本演进)
- [文件说明](#文件说明)

---

## 架构

```
input tokens
    │  + Positional Encoding
    ▼
┌─────────────────────────────────────────────┐
│  SSM backbone  (多槽 F-layer, fla HGRN)      │ ← 长程平滑, O(T·D), state 固定
│  12 层 × [MultiSlotFLayer + SwiGLU FFN]      │
└─────────────────────────────────────────────┘
    │ x_ash                    ┌──────────────────────────────────┐
    │                          │ SlowMemory (线性化, fla HGRN)     │ ← 慢记忆, O(T·D)
    │                          │ h_t = A(x)·h + B(x), y=α(x)·h+x  │
    │                          └──────────────────────────────────┘
    │ x_mem                              │
    │                          ┌──────────────────────────────────┐
    │                          │ Recall (fla multi-head GLA)       │ ← 精确召回, O(T·D·d_h)
    │                          │ S_t=exp(g)·S+k⊗v, o=q·S (content) │
    │                          └──────────────────────────────────┘
    │                                    │ x_recall
    ▼                                    ▼
  Gated Fusion(x_ash, x_mem) + x_emb + x_recall  →  Head → logits
```

**三路分工**:
- **SSM backbone**(多槽 F-layer):`h = A·h + B`,A∈(0,1],对数域 parallel scan(fla `chunk_hgrn`/`fused_recurrent_hgrn`)。长程平滑、信息有界、可并行。
- **SlowMemory**(线性化):`h = A(x)·h + B(x)` + 输出门。慢尺度记忆,backward 友好(fla autograd)。
- **Recall**(GLA):`S_t = exp(g)·S_{t-1} + k⊗v`,`o = q·S`。**累积式 content addressing**,解决纯 SSM 的 recall 弱点。multi-head(d_h=64),g 初始弱遗忘(bias=8,强保留)。

**全 fla 实现**:backbone/slowmem/recall 都用 [flash-linear-attention](https://github.com/fla-org/flash-linear-attention) 的高效 triton kernel,**无 Python loop**,训练/推理都快。

---

## 架构优势

| 维度 | **FRSMASH v3.6** | Mamba | RWKV | Transformer |
|------|------------------|-------|------|-------------|
| backbone | SSM 多槽(fla) | 选择性 SSM | — | attention |
| **recall 能力** | **GLA 召回 ✓**(induction PASS) | 弱 ✗ | linear attn(=GLA 之一) | 强(O(T²)) |
| **训练 backward** | **自动(fla autograd)** | selective scan | wkv kernel | 标准反传 |
| **生成显存** | **O(1) 恒定**(state 固定) | O(1) | O(1) | **O(T) KV cache 涨** |
| **长程外推** | **128K 稳定**(A∈(0,1] 有界) | 外推有争议 | 衰减稳 | 需位置插值 |
| 召回复杂度 | O(T·D·d_h) | O(T·D) | O(T·D) | O(T²·D) |

**核心优势**:
1. **recall 强**:GLA 分支补上纯 SSM 的 associative recall 弱点(验证 induction PASS)。Mamba 做不到。
2. **生成显存恒定**:三路 state 固定,生成任意长 context 显存不变(实测 276 MB,不随 context)。attention 的 KV cache 随序列线性涨。
3. **训练快**:全 fla triton kernel + 自动 backward,无手写 backward(对比非线性 LSTM 的 backward 障碍)。
4. **长程外推稳**:A∈(0,1] + exp(g)∈(0,1] 数学有界,128K(训练仅 512/768)外推不崩溃。

**定位**:`v3.6 = Mamba-like SSM(效率) + RWKV-like GLA(recall) + SlowMemory(慢记忆) 融合`,三路各取所长。

---

## 测试数据

### 训练(60M,d=432 8层,minimind 全量数据)

| 阶段 | steps | loss | 时长 |
|------|-------|------|------|
| pretrain 2ep | 79388 | 6.37 → **2.21** | 2.4h |
| sft 1ep | 28303 | 2.63 → **1.97**(PPL≈7.2) | 1.5h |
| **总** | 107691 | — | **3.9h** |

训练吞吐:**125,000 tok/s**(sl=512, bs=32, bf16, 单 RTX 4090)。

### recall 能力(induction associative recall)

```
[序列 a1..aK marker a1..aK, 见 a_i 须输出后继]
v3.6: acc=1.000 PASS (step 800 学会)
对比: 纯 SSM(v3.4) acc=0.000 FAIL; cummax acc=0.058 FAIL; SKVR(slot EMA) acc=0.208 FAIL
```
**只有累积式 content addressing(GLA)能过 induction**,验证 recall 分支有效。

### 推理速度(60M)

| 测试 | 结果 |
|------|------|
| forward 吞吐(sl=8192) | **237,000 tok/s** |
| 生成 eager(fused_recurrent) | 102 tok/s |
| **生成 CUDA Graph** | **625 tok/s**(6.5× eager) |
| TTFT(prefill 7 tok) | 17.8 ms |

生成速度**不随 context 增长**(state carry,每步 O(1))。

### 长程稳定性(外推)

```
context     NLL        PPL      maxTokNLL   drift(vs 2K)
  2K      10.558    38490       24.4        +0.00
  8K      10.225    27593       25.7        -0.33
 32K      10.134    25194       26.5        -0.42
128K      10.129    25064       27.2        -0.43
=> STABLE (训练 seq=512/768, 128K 是 170× 外推, PPL 不爆炸)
```

### 推理显存(关键优势)

```
context    生成显存(state carry)    attention 等价 KV cache
  100        276 MB                  1.3 MB
 1000        276 MB                 13.2 MB
 4000        276 MB                 52.7 MB
16000        276 MB                210.9 MB
            ↑ 恒定!                 ↑ 随 context 线性涨
```
**生成显存 O(1)恒定**(276 MB),attention 的 KV cache 随 context 线性增长。

**prefill 峰值也恒定**:`generate`/`generate_cg` 内部走 `prefill_chunked`(chunk=512),分块 forward 只保留 state、丢弃中间 activation,峰值显存 = 单块(实测 375 MB,不随 prompt 长度增长)。所以超长 prompt(16K+)也不会 OOM,prefill 与生成两阶段显存都恒定。

---

## 环境安装(任何机器)

### 1. 系统要求
- NVIDIA GPU(CUDA 11.8+ 或 12.x),建议 8GB+ 显存
- Python 3.10 ~ 3.12(不建议 3.13,fla 兼容性)

### 2. 安装依赖
```bash
# 创建环境
python -m venv .venv && .venv\Scripts\activate   # Windows
# 或: python3 -m venv .venv && source .venv/bin/activate  # Linux

# 安装
pip install torch                           # 按官网选对应 CUDA 版本
pip install flash-linear-attention          # fla (核心, triton kernel)
pip install jieba                            # OpenASHVoc 分词
pip install numpy tqdm                       # 数据/进度
```

> **fla 是关键依赖**:提供 `chunk_hgrn`/`fused_recurrent_hgrn`(backbone/slowmem)和 `chunk_gla`(recall)的高效 triton kernel。纯 triton 实现,**无需 nvcc 编译**,Windows/Linux 通用。
>
> 若 fla 安装失败,可用 `uv pip install flash-linear-attention`(uv 处理依赖更稳)。

### 3. 准备数据与词表
需要 [minimind](https://github.com/jingyaogong/minimind) 数据集 + OpenASH 词表:
```
data/
  pretrain_t2t_mini.jsonl    # ~1.27M 条 pretrain
  sft_t2t_mini.jsonl         # ~905K 条 sft
  open_ash_voc_agent.json    # 词表 (23005 tokens)
```

---

## 训练指南

### 配置数据路径
编辑 `train/v36_train.py` 顶部:
```python
CACHE_DIR = '/path/to/data/cache'     # tokenized 缓存目录
OUT_DIR   = '/path/to/output'         # 权重输出目录
DEV       = 'cuda'
```

### 全量训练(pretrain + sft)
```bash
cd train
python v36_train.py --stage both --hidden 432 --layers 8 --heads 8 --pt_epochs 2 --sft_epochs 1
```
参数:
| 参数 | 默认 | 说明 |
|------|------|------|
| `--hidden` | 432 | 隐藏维度(432→~60M) |
| `--layers` | 8 | 层数 |
| `--heads` | 8 | 注意力头数 |
| `--pt_epochs` | 2 | pretrain 轮数 |
| `--sft_epochs` | 1 | sft 轮数 |
| `--pt_seq` | 512 | pretrain 序列长度 |
| `--sft_seq` | 768 | sft 序列长度 |
| `--pt_max` | 0 | 限制 pretrain 样本数(调试用) |

### 调试/冒烟
```bash
python v36_train.py --stage pretrain --max_steps 50   # 50 步验证
```

### 训练大规模(223M)
```bash
python v36_train.py --stage both --hidden 768 --layers 12 --pt_epochs 3 --sft_epochs 2
# ~48h (单 4090, 全量数据)
```

**断点续训**:自动从 `out/v36_{stage}_latest.pth` 恢复。

### 训练机制
- 优化器:AdamW(lr 5e-4 pretrain / 5e-5 sft, cosine schedule)
- 混合精度:bf16 autocast + GradScaler
- 梯度裁剪:1.0
- 缓存:首次 tokenize 后存 `.pt`,后续直接加载(省 jieba 分词)

---

## 推理指南

### 加载模型
```python
import torch
from model.frsmash_v36 import FRSMASHv36
from infer.frsmash_v36_infer import generate, generate_cg

VS = 23005
model = FRSMASHv36(VS, 432, 8, 8, n_slots=4).cuda().eval()
model.load_state_dict(torch.load('out/v36_sft_final.pth', map_location='cuda', weights_only=False)['model'])
```

### 生成(支持 top-k / top-p / 重复抑制 / temperature)
```python
prompt_ids = torch.tensor([[...]], device='cuda')   # tokenize 后的 ids

# eager 版 (调试友好, ~102 tok/s)
out = generate(model, prompt_ids, max_new=150,
               top_k=40, top_p=0.9, rep_penalty=1.3, temperature=0.9, eos=2)

# CUDA Graph 版 (生产用, ~625 tok/s, 显存恒定)
out = generate_cg(model, prompt_ids, max_new=150,
                  top_k=40, top_p=0.9, rep_penalty=1.3, temperature=0.9, eos=2)
```

### 三种生成方式对比
| 方式 | 速度 | 用途 |
|------|------|------|
| `generate` (eager, fused_recurrent) | 102 tok/s | 调试/灵活 |
| `generate_cg` (CUDA Graph) | **625 tok/s** | **生产/流式** |

两者都:
- **state carry**(backbone + slowmem + recall 三路 state 传递),长 context 生成不重算
- 支持 **top-k / top-p / repetition penalty / temperature** 采样
- **生成显存恒定**(276 MB,不随 context)
- **chunked prefill**(`prefill_chunked`,chunk=512):prefill 分块 forward + 三路 state carry(含 recall `initial_state` + `pos_offset` 位置编码偏移),峰值显存 = 单块,长 prompt 不 OOM

### 分词(OpenASHVoc)
```python
from open_ash_voc import OpenASHVoc
voc = OpenASHVoc(agent_voc_path='data/open_ash_voc_agent.json')
ids = voc.encode("你好")          # text → ids
text = voc.decode(ids)            # ids → text
```

---

## 版本演进

| 版本 | backbone | SlowMemory | recall | 训练 | induction | 关键 |
|------|---------|-----------|--------|------|-----------|------|
| v3.2 | 手写 scan | LSTM loop | cummax | 慢 | FAIL | 数值稳定基石 |
| v3.3 | fla HGRN | 手写 fused | — | ❌backward 障碍 | FAIL | 绕 nvcc |
| v3.4 | fla HGRN | 线性化(fla) | — | **20×** | FAIL | 全 fla,快但 recall 弱 |
| v3.5 | fla HGRN | 线性化 | 手写 LinAttn loop | 慢(recall) | PASS | recall 解决,但慢 |
| **v3.6** | fla HGRN | 线性化 | **fla chunk_gla** | **快** | **PASS** | **快+recall,完整解** |

**v3.6 是完整解**:v3.4 的速度(SSM 全 fla)+ v3.5 的 recall(GLA),fla 高效实现让两者兼得。

---

## 文件说明

```
FRSMASH-v3.6/
├── README.md                      # 本文档
├── model/
│   └── frsmash_v36.py             # 模型定义 (SSM + GLA recall + SlowMemory)
├── infer/
│   └── frsmash_v36_infer.py       # 推理模块 (generate / generate_cg + 采样)
└── train/
    └── v36_train.py               # 训练脚本 (pretrain → sft)
```

### 关键组件
- `model/frsmash_v36.py`:
  - `MultiSlotFLayer`:多槽 SSM F-layer(fla `chunk_hgrn`)
  - `LinearSlowMemory`:线性化慢记忆(fla `chunk_hgrn`)
  - `GlaRecall`:multi-head GLA 召回(fla `chunk_gla` + 手写 `step` for 生成)
  - `FRSMASHv36`:三路融合模型(forward 训练用,generate_step 推理用)
- `infer/frsmash_v36_infer.py`:
  - `prefill_chunked`:**分块 prefill**(chunk=512,三路 state carry,峰值显存恒定)
  - `generate`:eager 生成(fused_recurrent_hgrn 逐 token)
  - `generate_cg`:**CUDA Graph 加速生成**(6.5×,生产用)
  - `_sample`:top-k / top-p / repetition penalty / temperature
- `train/v36_train.py`:
  - `CachedDS`:tokenized 数据缓存(复用 minimind 缓存)
  - `train`:pretrain/sft 训练循环(bf16 + cosine lr + 断点续训)

---

## 引用

架构基于以下工作的思想融合:
- **fla**(flash-linear-attention):高效 triton kernel(`chunk_hgrn`, `chunk_gla`)
- **Mamba**(选择性 SSM):backbone 的 input-dependent 线性递推
- **RWKV / GLA**(gated linear attention):recall 分支的 content addressing
- **Jamba**(SSM + attention 混合):混合架构思路(v3.6 用更轻的 GLA 替代 full attention)

---

## License

MIT

---

## Citation

如果 FRSMASH v3.6 对你的研究或项目有帮助,欢迎引用:

```bibtex
@misc{frsmash_v36,
  title  = {FRSMASH v3.6: A Hybrid Architecture with SSM Backbone, GLA Recall and Linear SlowMemory},
  author = {dfytensor},
  year   = {2026},
  howpublished = {\url{https://www.modelscope.cn/dfytensor/FRSMASH-v3.6}},
  note   = {Three-branch fusion: multi-slot SSM F-layer (long-range, fla), 
            multi-head GLA recall (associative recall, fla), linear SlowMemory (slow memory). 
            Fully fla-based, O(1) inference memory, 128K extrapolation stable, induction recall PASS.}
}
```

**关键特性一句话**:SSM(长程效率) + GLA(精确召回) + SlowMemory(慢记忆) 三路融合,全 fla triton kernel,生成显存恒定 O(1),128K 长程外推稳定 —— 兼具 Mamba 的效率与 attention 的 recall 能力,且比 attention 推理显存更优。

欢迎在此基础上迭代(v3.7+),或应用到你的任务。如有问题/改进,欢迎 issue / PR。
