Text Generation
MLX
Safetensors
English
Chinese
sensenova_loop
SenseNova
quantized
custom-runtime
conversational
custom_code
8-bit precision
Instructions to use NeosQ/SenseNova-Loop-9B-MLX-8bit with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use NeosQ/SenseNova-Loop-9B-MLX-8bit with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("NeosQ/SenseNova-Loop-9B-MLX-8bit") prompt = "Write a story about Einstein" messages = [{"role": "user", "content": prompt}] prompt = tokenizer.apply_chat_template( messages, add_generation_prompt=True ) text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Pi
How to use NeosQ/SenseNova-Loop-9B-MLX-8bit with Pi:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "NeosQ/SenseNova-Loop-9B-MLX-8bit"
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "mlx-lm": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "NeosQ/SenseNova-Loop-9B-MLX-8bit" } ] } } }Run Pi
# Start Pi in your project directory: pi
- MLX LM
How to use NeosQ/SenseNova-Loop-9B-MLX-8bit with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Interactive chat REPL mlx_lm.chat --model "NeosQ/SenseNova-Loop-9B-MLX-8bit"
Run an OpenAI-compatible server
# Install MLX LM uv tool install mlx-lm # Start the server mlx_lm.server --model "NeosQ/SenseNova-Loop-9B-MLX-8bit" # Calling the OpenAI-compatible server with curl curl -X POST "http://localhost:8080/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "NeosQ/SenseNova-Loop-9B-MLX-8bit", "messages": [ {"role": "user", "content": "Hello"} ] }' - Hermes Agent
How to use NeosQ/SenseNova-Loop-9B-MLX-8bit with Hermes Agent:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "NeosQ/SenseNova-Loop-9B-MLX-8bit"
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default NeosQ/SenseNova-Loop-9B-MLX-8bit
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use NeosQ/SenseNova-Loop-9B-MLX-8bit with OpenClaw:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "NeosQ/SenseNova-Loop-9B-MLX-8bit"
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "NeosQ/SenseNova-Loop-9B-MLX-8bit" \ --custom-provider-id mlx-lm \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
添加 8-bit MLX 量化模型及中英文说明
Browse files- .gitattributes +1 -0
- README.md +120 -0
- README.zh-CN.md +120 -0
- chat_template.jinja +154 -0
- config.json +136 -0
- generation_config.json +12 -0
- mlx_sensenova_loop.py +382 -0
- model-00001-of-00002.safetensors +3 -0
- model-00002-of-00002.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_sensenova_loop.py +395 -0
- tokenizer.json +3 -0
- tokenizer_config.json +34 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
- zh
|
| 6 |
+
library_name: mlx
|
| 7 |
+
pipeline_tag: text-generation
|
| 8 |
+
base_model: sensenova/SenseNova-Loop-9B
|
| 9 |
+
tags:
|
| 10 |
+
- mlx
|
| 11 |
+
- SenseNova
|
| 12 |
+
- quantized
|
| 13 |
+
- text-generation
|
| 14 |
+
- custom-runtime
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# SenseNova-Loop-9B — Unofficial MLX 8-bit
|
| 18 |
+
|
| 19 |
+
[简体中文说明](README.zh-CN.md)
|
| 20 |
+
|
| 21 |
+
This is an **unofficial, text-only MLX conversion** of [sensenova/SenseNova-Loop-9B](https://huggingface.co/sensenova/SenseNova-Loop-9B), quantized to 8-bit weights. It is not an official SenseNova release.
|
| 22 |
+
|
| 23 |
+
## Important runtime requirement
|
| 24 |
+
|
| 25 |
+
SenseNova-Loop-9B uses a custom looped, dual-stream mHC architecture. **Stock mlx-lm does not support this architecture.** These weights require an MLX/oMLX runtime with a compatible `SenseNova_loop` implementation.
|
| 26 |
+
|
| 27 |
+
The customized implementation used in our tests is included as `mlx_sensenova_loop.py` for integration and reference. Merely downloading this repository into a stock mlx-lm installation is not sufficient.
|
| 28 |
+
|
| 29 |
+
The conversion contains text-generation weights only; vision inputs are not supported by this package.
|
| 30 |
+
|
| 31 |
+
## Quantization
|
| 32 |
+
|
| 33 |
+
- Tool: `mlx_lm.convert`
|
| 34 |
+
- Method: MLX affine weight quantization
|
| 35 |
+
- Bits: **8**
|
| 36 |
+
- Group size: **64**
|
| 37 |
+
- Source: BF16 Hugging Face weights
|
| 38 |
+
- Custom runtime flags used in testing: `SENSENOVA_MHC_METAL=1` and `SENSENOVA_MHC_MERGE_METAL=1`
|
| 39 |
+
|
| 40 |
+
## Recommended generation settings
|
| 41 |
+
|
| 42 |
+
The source repository's default generation configuration is `temperature=1.0`, `top_p=0.95`, with sampling enabled. In our Chinese long-form tests, that setting could produce irrelevant foreign words in **all** tested precisions, including unquantized BF16.
|
| 43 |
+
|
| 44 |
+
For formal Chinese long-form generation, we recommend:
|
| 45 |
+
|
| 46 |
+
```json
|
| 47 |
+
{
|
| 48 |
+
"temperature": 0,
|
| 49 |
+
"top_p": 1
|
| 50 |
+
}
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
This recommendation targets language artifacts; it does not guarantee factual correctness. Reasoning may also be in English while the final answer is entirely Chinese.
|
| 54 |
+
|
| 55 |
+
## Speed on the test machine
|
| 56 |
+
|
| 57 |
+
Test environment: Apple Silicon Mac with 128 GB unified memory, oMLX 0.7.3, customized mlx-lm, MLX 0.32.4. Each result is the median of three OpenAI-compatible requests generating 64 tokens. Results depend on hardware, prompt, runtime, and workload.
|
| 58 |
+
|
| 59 |
+
| Variant | Generation speed |
|
| 60 |
+
| --- | ---: |
|
| 61 |
+
| BF16 baseline | 8.50 token/s |
|
| 62 |
+
| **8-bit** | **13.51 token/s** |
|
| 63 |
+
| 4-bit | 20.90 token/s |
|
| 64 |
+
|
| 65 |
+
For the 4-bit variant, enabling compiled mHC router subgraphs increased speed from 16.44 to 20.90 token/s (about **27.1%** faster). The compilation optimization passed 32-token output and logit-equivalence checks. That equivalence applies to compilation, not to quantization.
|
| 66 |
+
|
| 67 |
+
## Quantization quality checks
|
| 68 |
+
|
| 69 |
+
Evaluation covered 614 token positions across Chinese, English, Python, and math text. Lower perplexity is better; top-1 agreement is measured against BF16.
|
| 70 |
+
|
| 71 |
+
| Variant | Perplexity | Top-1 agreement with BF16 |
|
| 72 |
+
| --- | ---: | ---: |
|
| 73 |
+
| BF16 | 2.7127 | reference |
|
| 74 |
+
| **8-bit** | **2.6938** | **99.02%** |
|
| 75 |
+
| 4-bit | 2.7875 | 93.81% |
|
| 76 |
+
|
| 77 |
+
Small differences in perplexity can arise from evaluation variation; the table should not be interpreted as proof that 8-bit improves the base model.
|
| 78 |
+
|
| 79 |
+
## Chinese long-form language tests
|
| 80 |
+
|
| 81 |
+
### Official default sampling (`temperature=1.0`, `top_p=0.95`)
|
| 82 |
+
|
| 83 |
+
Three fixed seeds were run for each precision. All nine essays finished naturally. Every matched foreign word below was manually reviewed and was inappropriate in context.
|
| 84 |
+
|
| 85 |
+
| Variant | Foreign words across 3 essays | Foreign words per 1,000 Chinese characters |
|
| 86 |
+
| --- | ---: | ---: |
|
| 87 |
+
| BF16 | 7 | 1.21 |
|
| 88 |
+
| 8-bit | 23 | 3.32 |
|
| 89 |
+
| 4-bit | 18 | 2.76 |
|
| 90 |
+
|
| 91 |
+
This small sample shows that the artifact exists in the base model too. Quantization may aggravate it, but the results do **not** show a monotonic relationship with quantization depth.
|
| 92 |
+
|
| 93 |
+
### Deterministic decoding (`temperature=0`, `top_p=1`)
|
| 94 |
+
|
| 95 |
+
The 4-bit variant was tested on five different approximately 2,000-character Chinese tasks: two book reflections, one argumentative essay, one literary essay, and one popular-science article.
|
| 96 |
+
|
| 97 |
+
- 5/5 articles finished naturally.
|
| 98 |
+
- Total output: 12,109 characters, including 10,034 Chinese characters.
|
| 99 |
+
- No meaningless foreign words, scripts, or Unicode replacement characters were found.
|
| 100 |
+
- Contextually appropriate terms such as `ChatGPT`, `AI`, and `REM` were not counted as errors.
|
| 101 |
+
|
| 102 |
+
Five tasks do not prove that artifacts are impossible under all prompts.
|
| 103 |
+
|
| 104 |
+
## Limitations
|
| 105 |
+
|
| 106 |
+
- Quantization is not lossless, especially at 4-bit.
|
| 107 |
+
- Deterministic decoding does not prevent factual errors, fabricated quotations, or invented personal experiences. Review factual content before use.
|
| 108 |
+
- The language tests targeted foreign-token artifacts, not overall writing quality or factual accuracy.
|
| 109 |
+
- A customized runtime is required; stock mlx-lm is insufficient.
|
| 110 |
+
|
| 111 |
+
## Download
|
| 112 |
+
|
| 113 |
+
```bash
|
| 114 |
+
hf download NeosQ/SenseNova-Loop-9B-MLX-8bit \
|
| 115 |
+
--local-dir SenseNova-Loop-9B-MLX-8bit
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
## License and attribution
|
| 119 |
+
|
| 120 |
+
Apache-2.0. Please also follow the base model's license and terms. All quantization and testing described here are unofficial community work.
|
README.zh-CN.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- zh
|
| 5 |
+
- en
|
| 6 |
+
library_name: mlx
|
| 7 |
+
pipeline_tag: text-generation
|
| 8 |
+
base_model: sensenova/SenseNova-Loop-9B
|
| 9 |
+
tags:
|
| 10 |
+
- mlx
|
| 11 |
+
- SenseNova
|
| 12 |
+
- quantized
|
| 13 |
+
- text-generation
|
| 14 |
+
- custom-runtime
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# SenseNova-Loop-9B — 非官方 MLX 8-bit 量化版
|
| 18 |
+
|
| 19 |
+
[English model card](README.md)
|
| 20 |
+
|
| 21 |
+
本仓库是 [sensenova/SenseNova-Loop-9B](https://huggingface.co/sensenova/SenseNova-Loop-9B) 的**非官方、纯文本 MLX 转换与 8-bit 量化版本**,不是商汤官方发布产物。
|
| 22 |
+
|
| 23 |
+
## 重要:运行时要求
|
| 24 |
+
|
| 25 |
+
SenseNova-Loop-9B 使用自定义循环层和双流 mHC 架构。**官方通用版 mlx-lm 不支持此架构。** 本模型需要包含兼容 `SenseNova_loop` 实现的定制 MLX/oMLX 运行时。
|
| 26 |
+
|
| 27 |
+
仓库中的 `mlx_sensenova_loop.py` 是我们测试时使用的定制实现,供集成和参考。仅把本仓库下载到普通 mlx-lm 环境中,并不能直接运行。
|
| 28 |
+
|
| 29 |
+
本转换只包含文本生成权重,不支持图像输入。
|
| 30 |
+
|
| 31 |
+
## 量化方式
|
| 32 |
+
|
| 33 |
+
- 工具:`mlx_lm.convert`
|
| 34 |
+
- 方法:MLX 仿射权重量化
|
| 35 |
+
- 位宽:**8 bit**
|
| 36 |
+
- 分组大小:**64**
|
| 37 |
+
- 来源:Hugging Face BF16 原始权重
|
| 38 |
+
- 测试时使用的定制运行时开关:`SENSENOVA_MHC_METAL=1`、`SENSENOVA_MHC_MERGE_METAL=1`
|
| 39 |
+
|
| 40 |
+
## 推荐生成参数
|
| 41 |
+
|
| 42 |
+
官方仓库的默认生成配置为 `temperature=1.0`、`top_p=0.95`,并开启随机采样。我们的中文长文测试发现,该设置下所有精度都可能混入不合适的外文词,包括未量化的 BF16。
|
| 43 |
+
|
| 44 |
+
正式中文长文写作建议改为:
|
| 45 |
+
|
| 46 |
+
```json
|
| 47 |
+
{
|
| 48 |
+
"temperature": 0,
|
| 49 |
+
"top_p": 1
|
| 50 |
+
}
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
此建议只针对语言乱码,不保证事实正确。模型也可能用英文思考,但最终正文完全是中文,两者需要分开判断。
|
| 54 |
+
|
| 55 |
+
## 本机速度测试
|
| 56 |
+
|
| 57 |
+
测试环境:128 GB 统一内存的 Apple Silicon Mac,oMLX 0.7.3,定制 mlx-lm,MLX 0.32.4。每组数据为 3 次 OpenAI 兼容请求、每次生成 64 token 的中位数。速度会随硬件、提示词、运行时和任务长度变化。
|
| 58 |
+
|
| 59 |
+
| 版本 | 生成速度 |
|
| 60 |
+
| --- | ---: |
|
| 61 |
+
| BF16 对照 | 8.50 token/s |
|
| 62 |
+
| **8-bit** | **13.51 token/s** |
|
| 63 |
+
| 4-bit | 20.90 token/s |
|
| 64 |
+
|
| 65 |
+
4-bit 版本开启 mHC 路由子图编译后,从 16.44 提升至 20.90 token/s,约快 **27.1%**。编译优化通过了 32 token 输出及 logits 一致性检查;该一致性只针对编译优化,不代表量化前后完全一致。
|
| 66 |
+
|
| 67 |
+
## 量化质量对照
|
| 68 |
+
|
| 69 |
+
评估覆盖中文、英文、Python 和数学文本,共 614 个 token 位置。困惑度越低越好;Top-1 一致率以 BF16 为参照。
|
| 70 |
+
|
| 71 |
+
| 版本 | 困惑度 | 与 BF16 的 Top-1 一致率 |
|
| 72 |
+
| --- | ---: | ---: |
|
| 73 |
+
| BF16 | 2.7127 | 参照 |
|
| 74 |
+
| **8-bit** | **2.6938** | **99.02%** |
|
| 75 |
+
| 4-bit | 2.7875 | 93.81% |
|
| 76 |
+
|
| 77 |
+
困惑度的小幅差异可能来自评估波动;不能把该表理解为 8-bit 一定改善了原模型。
|
| 78 |
+
|
| 79 |
+
## 中文长文语言稳定性测试
|
| 80 |
+
|
| 81 |
+
### 官方默认随机采样(`temperature=1.0`、`top_p=0.95`)
|
| 82 |
+
|
| 83 |
+
每种精度使用相同的 3 组固定随机种子,9 篇文章均自然结束。下列外文词已逐条检查上下文,均属于不合适混入。
|
| 84 |
+
|
| 85 |
+
| 版本 | 3 篇正文中的异常外文词数 | 每千个汉字的异常外文词数 |
|
| 86 |
+
| --- | ---: | ---: |
|
| 87 |
+
| BF16 | 7 | 1.21 |
|
| 88 |
+
| 8-bit | 23 | 3.32 |
|
| 89 |
+
| 4-bit | 18 | 2.76 |
|
| 90 |
+
|
| 91 |
+
这组小样本说明原模型本身也存在该现象。量化可能加重问题,但数据**没有**呈现量化越重、异常越多的单调关系。
|
| 92 |
+
|
| 93 |
+
### 固定最优词生成(`temperature=0`、`top_p=1`)
|
| 94 |
+
|
| 95 |
+
对 4-bit 版本使用 5 种不同的约 2000 字中文任务:两篇读后感、一篇议论文、一篇散文和一篇科普文。
|
| 96 |
+
|
| 97 |
+
- 5/5 篇均自然结束。
|
| 98 |
+
- 正文合计 12109 个字符,其中 10034 个汉字。
|
| 99 |
+
- 未发现无意义外文、外来文字或 Unicode 替换字符。
|
| 100 |
+
- `ChatGPT`、`AI`、`REM` 等符合上下文的专业术语不计为错误。
|
| 101 |
+
|
| 102 |
+
5 种任务不能证明所有提示词下都绝不会出现异常。
|
| 103 |
+
|
| 104 |
+
## 局限性
|
| 105 |
+
|
| 106 |
+
- 量化并非无损,4-bit 尤其明显。
|
| 107 |
+
- 温度 0 不能阻止事实错误、虚构引语或编造个人经历,正式使用前必须核查内容。
|
| 108 |
+
- 长文测试针对异常外文,不代表整体写作质量或事实准确率。
|
| 109 |
+
- 必须使用定制运行时,普通 mlx-lm 不能直接加载。
|
| 110 |
+
|
| 111 |
+
## 下载
|
| 112 |
+
|
| 113 |
+
```bash
|
| 114 |
+
hf download NeosQ/SenseNova-Loop-9B-MLX-8bit \
|
| 115 |
+
--local-dir SenseNova-Loop-9B-MLX-8bit
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
## 许可证与归属
|
| 119 |
+
|
| 120 |
+
Apache-2.0。使用时也请遵守原模型的许可证和条款。本仓库的量化与测试均为非官方社区工作。
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- set image_count = namespace(value=0) %}
|
| 2 |
+
{%- set video_count = namespace(value=0) %}
|
| 3 |
+
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
|
| 4 |
+
{%- if content is string %}
|
| 5 |
+
{{- content }}
|
| 6 |
+
{%- elif content is iterable and content is not mapping %}
|
| 7 |
+
{%- for item in content %}
|
| 8 |
+
{%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
|
| 9 |
+
{%- if is_system_content %}
|
| 10 |
+
{{- raise_exception('System message cannot contain images.') }}
|
| 11 |
+
{%- endif %}
|
| 12 |
+
{%- if do_vision_count %}
|
| 13 |
+
{%- set image_count.value = image_count.value + 1 %}
|
| 14 |
+
{%- endif %}
|
| 15 |
+
{%- if add_vision_id %}
|
| 16 |
+
{{- 'Picture ' ~ image_count.value ~ ': ' }}
|
| 17 |
+
{%- endif %}
|
| 18 |
+
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
|
| 19 |
+
{%- elif 'video' in item or item.type == 'video' %}
|
| 20 |
+
{%- if is_system_content %}
|
| 21 |
+
{{- raise_exception('System message cannot contain videos.') }}
|
| 22 |
+
{%- endif %}
|
| 23 |
+
{%- if do_vision_count %}
|
| 24 |
+
{%- set video_count.value = video_count.value + 1 %}
|
| 25 |
+
{%- endif %}
|
| 26 |
+
{%- if add_vision_id %}
|
| 27 |
+
{{- 'Video ' ~ video_count.value ~ ': ' }}
|
| 28 |
+
{%- endif %}
|
| 29 |
+
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
|
| 30 |
+
{%- elif 'text' in item %}
|
| 31 |
+
{{- item.text }}
|
| 32 |
+
{%- else %}
|
| 33 |
+
{{- raise_exception('Unexpected item type in content.') }}
|
| 34 |
+
{%- endif %}
|
| 35 |
+
{%- endfor %}
|
| 36 |
+
{%- elif content is none or content is undefined %}
|
| 37 |
+
{{- '' }}
|
| 38 |
+
{%- else %}
|
| 39 |
+
{{- raise_exception('Unexpected content type.') }}
|
| 40 |
+
{%- endif %}
|
| 41 |
+
{%- endmacro %}
|
| 42 |
+
{%- if not messages %}
|
| 43 |
+
{{- raise_exception('No messages provided.') }}
|
| 44 |
+
{%- endif %}
|
| 45 |
+
{%- if tools and tools is iterable and tools is not mapping %}
|
| 46 |
+
{{- '<|im_start|>system\n' }}
|
| 47 |
+
{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
|
| 48 |
+
{%- for tool in tools %}
|
| 49 |
+
{{- "\n" }}
|
| 50 |
+
{{- tool | tojson }}
|
| 51 |
+
{%- endfor %}
|
| 52 |
+
{{- "\n</tools>" }}
|
| 53 |
+
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
|
| 54 |
+
{%- if messages[0].role == 'system' %}
|
| 55 |
+
{%- set content = render_content(messages[0].content, false, true)|trim %}
|
| 56 |
+
{%- if content %}
|
| 57 |
+
{{- '\n\n' + content }}
|
| 58 |
+
{%- endif %}
|
| 59 |
+
{%- endif %}
|
| 60 |
+
{{- '<|im_end|>\n' }}
|
| 61 |
+
{%- else %}
|
| 62 |
+
{%- if messages[0].role == 'system' %}
|
| 63 |
+
{%- set content = render_content(messages[0].content, false, true)|trim %}
|
| 64 |
+
{{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
|
| 65 |
+
{%- endif %}
|
| 66 |
+
{%- endif %}
|
| 67 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
| 68 |
+
{%- for message in messages[::-1] %}
|
| 69 |
+
{%- set index = (messages|length - 1) - loop.index0 %}
|
| 70 |
+
{%- if ns.multi_step_tool and message.role == "user" %}
|
| 71 |
+
{%- set content = render_content(message.content, false)|trim %}
|
| 72 |
+
{%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
|
| 73 |
+
{%- set ns.multi_step_tool = false %}
|
| 74 |
+
{%- set ns.last_query_index = index %}
|
| 75 |
+
{%- endif %}
|
| 76 |
+
{%- endif %}
|
| 77 |
+
{%- endfor %}
|
| 78 |
+
{%- if ns.multi_step_tool %}
|
| 79 |
+
{{- raise_exception('No user query found in messages.') }}
|
| 80 |
+
{%- endif %}
|
| 81 |
+
{%- for message in messages %}
|
| 82 |
+
{%- set content = render_content(message.content, true)|trim %}
|
| 83 |
+
{%- if message.role == "system" %}
|
| 84 |
+
{%- if not loop.first %}
|
| 85 |
+
{{- raise_exception('System message must be at the beginning.') }}
|
| 86 |
+
{%- endif %}
|
| 87 |
+
{%- elif message.role == "user" %}
|
| 88 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
|
| 89 |
+
{%- elif message.role == "assistant" %}
|
| 90 |
+
{%- set reasoning_content = '' %}
|
| 91 |
+
{%- if message.reasoning_content is string %}
|
| 92 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 93 |
+
{%- else %}
|
| 94 |
+
{%- if '</think>' in content %}
|
| 95 |
+
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
|
| 96 |
+
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
|
| 97 |
+
{%- endif %}
|
| 98 |
+
{%- endif %}
|
| 99 |
+
{%- set reasoning_content = reasoning_content|trim %}
|
| 100 |
+
{%- if loop.index0 > ns.last_query_index %}
|
| 101 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
|
| 102 |
+
{%- else %}
|
| 103 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 104 |
+
{%- endif %}
|
| 105 |
+
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
|
| 106 |
+
{%- for tool_call in message.tool_calls %}
|
| 107 |
+
{%- if tool_call.function is defined %}
|
| 108 |
+
{%- set tool_call = tool_call.function %}
|
| 109 |
+
{%- endif %}
|
| 110 |
+
{%- if loop.first %}
|
| 111 |
+
{%- if content|trim %}
|
| 112 |
+
{{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 113 |
+
{%- else %}
|
| 114 |
+
{{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 115 |
+
{%- endif %}
|
| 116 |
+
{%- else %}
|
| 117 |
+
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 118 |
+
{%- endif %}
|
| 119 |
+
{%- if tool_call.arguments is defined %}
|
| 120 |
+
{%- for args_name, args_value in tool_call.arguments|items %}
|
| 121 |
+
{{- '<parameter=' + args_name + '>\n' }}
|
| 122 |
+
{%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
|
| 123 |
+
{{- args_value }}
|
| 124 |
+
{{- '\n</parameter>\n' }}
|
| 125 |
+
{%- endfor %}
|
| 126 |
+
{%- endif %}
|
| 127 |
+
{{- '</function>\n</tool_call>' }}
|
| 128 |
+
{%- endfor %}
|
| 129 |
+
{%- endif %}
|
| 130 |
+
{{- '<|im_end|>\n' }}
|
| 131 |
+
{%- elif message.role == "tool" %}
|
| 132 |
+
{%- if loop.previtem and loop.previtem.role != "tool" %}
|
| 133 |
+
{{- '<|im_start|>user' }}
|
| 134 |
+
{%- endif %}
|
| 135 |
+
{{- '\n<tool_response>\n' }}
|
| 136 |
+
{{- content }}
|
| 137 |
+
{{- '\n</tool_response>' }}
|
| 138 |
+
{%- if not loop.last and loop.nextitem.role != "tool" %}
|
| 139 |
+
{{- '<|im_end|>\n' }}
|
| 140 |
+
{%- elif loop.last %}
|
| 141 |
+
{{- '<|im_end|>\n' }}
|
| 142 |
+
{%- endif %}
|
| 143 |
+
{%- else %}
|
| 144 |
+
{{- raise_exception('Unexpected message role.') }}
|
| 145 |
+
{%- endif %}
|
| 146 |
+
{%- endfor %}
|
| 147 |
+
{%- if add_generation_prompt %}
|
| 148 |
+
{{- '<|im_start|>assistant\n' }}
|
| 149 |
+
{%- if enable_thinking is defined and enable_thinking is false %}
|
| 150 |
+
{{- '<think>\n\n</think>\n\n' }}
|
| 151 |
+
{%- else %}
|
| 152 |
+
{{- '<think>\n' }}
|
| 153 |
+
{%- endif %}
|
| 154 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SenseNovaLoopForConditionalGeneration"
|
| 4 |
+
],
|
| 5 |
+
"attn_implementation": "sdpa",
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "modeling_sensenova_loop.SenseNovaLoopConfig",
|
| 8 |
+
"AutoModel": "modeling_sensenova_loop.SenseNovaLoopModel",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_sensenova_loop.SenseNovaLoopForConditionalGeneration",
|
| 10 |
+
"AutoModelForImageTextToText": "modeling_sensenova_loop.SenseNovaLoopForConditionalGeneration"
|
| 11 |
+
},
|
| 12 |
+
"bos_token_id": null,
|
| 13 |
+
"dtype": "bfloat16",
|
| 14 |
+
"eos_token_id": [
|
| 15 |
+
248044,
|
| 16 |
+
248046
|
| 17 |
+
],
|
| 18 |
+
"hidden_size": 4096,
|
| 19 |
+
"image_token_id": 248056,
|
| 20 |
+
"loop_settings": {
|
| 21 |
+
"counts": [
|
| 22 |
+
2
|
| 23 |
+
],
|
| 24 |
+
"end": 28,
|
| 25 |
+
"eval_count": 2,
|
| 26 |
+
"start": 4
|
| 27 |
+
},
|
| 28 |
+
"mhc": {
|
| 29 |
+
"end": 28,
|
| 30 |
+
"fixed_identity": false,
|
| 31 |
+
"iterations": 20,
|
| 32 |
+
"pre_scale": 1.0,
|
| 33 |
+
"start": 4,
|
| 34 |
+
"streams": 2
|
| 35 |
+
},
|
| 36 |
+
"model_name": "SenseNova-Loop-9B",
|
| 37 |
+
"model_type": "sensenova_loop",
|
| 38 |
+
"pad_token_id": 248044,
|
| 39 |
+
"patch_conv3d": true,
|
| 40 |
+
"quantization": {
|
| 41 |
+
"group_size": 64,
|
| 42 |
+
"bits": 8,
|
| 43 |
+
"mode": "affine"
|
| 44 |
+
},
|
| 45 |
+
"quantization_config": {
|
| 46 |
+
"group_size": 64,
|
| 47 |
+
"bits": 8,
|
| 48 |
+
"mode": "affine"
|
| 49 |
+
},
|
| 50 |
+
"text_config": {
|
| 51 |
+
"attention_bias": false,
|
| 52 |
+
"attention_dropout": 0.0,
|
| 53 |
+
"attn_output_gate": true,
|
| 54 |
+
"bos_token_id": null,
|
| 55 |
+
"dtype": "bfloat16",
|
| 56 |
+
"eos_token_id": 248044,
|
| 57 |
+
"full_attention_interval": 4,
|
| 58 |
+
"head_dim": 256,
|
| 59 |
+
"hidden_act": "silu",
|
| 60 |
+
"hidden_size": 4096,
|
| 61 |
+
"initializer_range": 0.02,
|
| 62 |
+
"intermediate_size": 12288,
|
| 63 |
+
"layer_types": [
|
| 64 |
+
"linear_attention",
|
| 65 |
+
"linear_attention",
|
| 66 |
+
"linear_attention",
|
| 67 |
+
"full_attention",
|
| 68 |
+
"linear_attention",
|
| 69 |
+
"linear_attention",
|
| 70 |
+
"linear_attention",
|
| 71 |
+
"full_attention",
|
| 72 |
+
"linear_attention",
|
| 73 |
+
"linear_attention",
|
| 74 |
+
"linear_attention",
|
| 75 |
+
"full_attention",
|
| 76 |
+
"linear_attention",
|
| 77 |
+
"linear_attention",
|
| 78 |
+
"linear_attention",
|
| 79 |
+
"full_attention",
|
| 80 |
+
"linear_attention",
|
| 81 |
+
"linear_attention",
|
| 82 |
+
"linear_attention",
|
| 83 |
+
"full_attention",
|
| 84 |
+
"linear_attention",
|
| 85 |
+
"linear_attention",
|
| 86 |
+
"linear_attention",
|
| 87 |
+
"full_attention",
|
| 88 |
+
"linear_attention",
|
| 89 |
+
"linear_attention",
|
| 90 |
+
"linear_attention",
|
| 91 |
+
"full_attention",
|
| 92 |
+
"linear_attention",
|
| 93 |
+
"linear_attention",
|
| 94 |
+
"linear_attention",
|
| 95 |
+
"full_attention"
|
| 96 |
+
],
|
| 97 |
+
"linear_conv_kernel_dim": 4,
|
| 98 |
+
"linear_key_head_dim": 128,
|
| 99 |
+
"linear_num_key_heads": 16,
|
| 100 |
+
"linear_num_value_heads": 32,
|
| 101 |
+
"linear_value_head_dim": 128,
|
| 102 |
+
"mamba_ssm_dtype": "float32",
|
| 103 |
+
"max_position_embeddings": 524288,
|
| 104 |
+
"mlp_only_layers": [],
|
| 105 |
+
"model_type": "qwen3_5_text",
|
| 106 |
+
"mtp_num_hidden_layers": 0,
|
| 107 |
+
"mtp_use_dedicated_embeddings": false,
|
| 108 |
+
"num_attention_heads": 16,
|
| 109 |
+
"num_hidden_layers": 32,
|
| 110 |
+
"num_key_value_heads": 4,
|
| 111 |
+
"pad_token_id": 248044,
|
| 112 |
+
"partial_rotary_factor": 0.25,
|
| 113 |
+
"rms_norm_eps": 1e-06,
|
| 114 |
+
"rope_parameters": {
|
| 115 |
+
"mrope_interleaved": true,
|
| 116 |
+
"mrope_section": [
|
| 117 |
+
11,
|
| 118 |
+
11,
|
| 119 |
+
10
|
| 120 |
+
],
|
| 121 |
+
"partial_rotary_factor": 0.25,
|
| 122 |
+
"rope_theta": 10000000,
|
| 123 |
+
"factor": 2.0,
|
| 124 |
+
"original_max_position_embeddings": 262144,
|
| 125 |
+
"type": "yarn"
|
| 126 |
+
},
|
| 127 |
+
"tie_word_embeddings": false,
|
| 128 |
+
"use_cache": true,
|
| 129 |
+
"vocab_size": 248320
|
| 130 |
+
},
|
| 131 |
+
"tie_word_embeddings": false,
|
| 132 |
+
"use_cache": true,
|
| 133 |
+
"video_token_id": 248057,
|
| 134 |
+
"vision_end_token_id": 248054,
|
| 135 |
+
"vision_start_token_id": 248053
|
| 136 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"eos_token_id": [
|
| 4 |
+
248044,
|
| 5 |
+
248046
|
| 6 |
+
],
|
| 7 |
+
"transformers_version": "5.18.0",
|
| 8 |
+
"use_cache": true,
|
| 9 |
+
"temperature": 1.0,
|
| 10 |
+
"do_sample": true,
|
| 11 |
+
"top_p": 0.95
|
| 12 |
+
}
|
mlx_sensenova_loop.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import mlx.core as mx
|
| 6 |
+
import mlx.nn as nn
|
| 7 |
+
|
| 8 |
+
from mlx_lm.models.base import BaseModelArgs, create_attention_mask, create_ssm_mask
|
| 9 |
+
from mlx_lm.models.cache import ArraysCache, KVCache
|
| 10 |
+
from mlx_lm.models.qwen3_5 import Model as Qwen3_5Model
|
| 11 |
+
from mlx_lm.models.qwen3_5 import Qwen3_5TextModel, TextModel as Qwen3_5TextModelWrapper
|
| 12 |
+
from mlx_lm.models.qwen3_5 import TextModelArgs, DecoderLayer
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def execution_plan(config):
|
| 16 |
+
loop = config["loop_settings"]
|
| 17 |
+
text = config["text_config"]
|
| 18 |
+
start, end, count = loop["start"], loop["end"], loop["eval_count"]
|
| 19 |
+
num_layers = text["num_hidden_layers"]
|
| 20 |
+
if loop.get("counts") != [count] or not (0 <= start < end <= num_layers):
|
| 21 |
+
raise ValueError("Invalid Loop configuration")
|
| 22 |
+
return tuple(range(start)) + tuple(range(start, end)) * count + tuple(range(end, num_layers))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def sinkhorn_reference(logits, iterations):
|
| 26 |
+
logits = logits.astype(mx.float32)
|
| 27 |
+
for _ in range(iterations):
|
| 28 |
+
logits = logits - mx.logsumexp(logits, axis=-1, keepdims=True)
|
| 29 |
+
logits = logits - mx.logsumexp(logits, axis=-2, keepdims=True)
|
| 30 |
+
return mx.exp(logits)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
_SINKHORN_KERNELS = {}
|
| 34 |
+
_SINKHORN_METAL = os.getenv("SENSENOVA_MHC_METAL", "1") != "0"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _sinkhorn_metal_kernel(streams, iterations):
|
| 38 |
+
key = (streams, iterations)
|
| 39 |
+
if key in _SINKHORN_KERNELS:
|
| 40 |
+
return _SINKHORN_KERNELS[key]
|
| 41 |
+
size = streams * streams
|
| 42 |
+
source = f"""
|
| 43 |
+
using namespace metal;
|
| 44 |
+
constexpr uint STREAMS = {streams};
|
| 45 |
+
constexpr uint SIZE = {size};
|
| 46 |
+
constexpr uint ITERATIONS = {iterations};
|
| 47 |
+
|
| 48 |
+
uint gid = thread_position_in_grid.x;
|
| 49 |
+
if (gid >= nmat) {{ return; }}
|
| 50 |
+
const uint offset = gid * SIZE;
|
| 51 |
+
float values[SIZE];
|
| 52 |
+
for (uint i = 0; i < SIZE; ++i) {{ values[i] = logits[offset + i]; }}
|
| 53 |
+
|
| 54 |
+
for (uint iteration = 0; iteration < ITERATIONS; ++iteration) {{
|
| 55 |
+
for (uint row = 0; row < STREAMS; ++row) {{
|
| 56 |
+
float maximum = values[row * STREAMS];
|
| 57 |
+
for (uint col = 1; col < STREAMS; ++col) {{
|
| 58 |
+
maximum = metal::max(maximum, values[row * STREAMS + col]);
|
| 59 |
+
}}
|
| 60 |
+
float sum = 0.0f;
|
| 61 |
+
for (uint col = 0; col < STREAMS; ++col) {{
|
| 62 |
+
sum += metal::exp(values[row * STREAMS + col] - maximum);
|
| 63 |
+
}}
|
| 64 |
+
float normalizer = maximum + metal::log(sum);
|
| 65 |
+
for (uint col = 0; col < STREAMS; ++col) {{
|
| 66 |
+
values[row * STREAMS + col] -= normalizer;
|
| 67 |
+
}}
|
| 68 |
+
}}
|
| 69 |
+
for (uint col = 0; col < STREAMS; ++col) {{
|
| 70 |
+
float maximum = values[col];
|
| 71 |
+
for (uint row = 1; row < STREAMS; ++row) {{
|
| 72 |
+
maximum = metal::max(maximum, values[row * STREAMS + col]);
|
| 73 |
+
}}
|
| 74 |
+
float sum = 0.0f;
|
| 75 |
+
for (uint row = 0; row < STREAMS; ++row) {{
|
| 76 |
+
sum += metal::exp(values[row * STREAMS + col] - maximum);
|
| 77 |
+
}}
|
| 78 |
+
float normalizer = maximum + metal::log(sum);
|
| 79 |
+
for (uint row = 0; row < STREAMS; ++row) {{
|
| 80 |
+
values[row * STREAMS + col] -= normalizer;
|
| 81 |
+
}}
|
| 82 |
+
}}
|
| 83 |
+
}}
|
| 84 |
+
for (uint i = 0; i < SIZE; ++i) {{ out[offset + i] = metal::exp(values[i]); }}
|
| 85 |
+
"""
|
| 86 |
+
kernel = mx.fast.metal_kernel(
|
| 87 |
+
name=f"sensenova_sinkhorn_s{streams}_it{iterations}_v1",
|
| 88 |
+
input_names=["logits", "nmat"],
|
| 89 |
+
output_names=["out"],
|
| 90 |
+
source=source,
|
| 91 |
+
compile_options={"math_mode": "safe"},
|
| 92 |
+
)
|
| 93 |
+
_SINKHORN_KERNELS[key] = kernel
|
| 94 |
+
return kernel
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def sinkhorn_metal(logits, iterations):
|
| 98 |
+
streams = logits.shape[-1]
|
| 99 |
+
lead = logits.shape[:-2]
|
| 100 |
+
nmat = logits.size // (streams * streams)
|
| 101 |
+
flat = logits.reshape(nmat, streams, streams)
|
| 102 |
+
kernel = _sinkhorn_metal_kernel(streams, iterations)
|
| 103 |
+
(out,) = kernel(
|
| 104 |
+
inputs=[flat, nmat],
|
| 105 |
+
grid=(nmat, 1, 1),
|
| 106 |
+
threadgroup=(min(nmat, 256), 1, 1),
|
| 107 |
+
output_shapes=[(nmat, streams, streams)],
|
| 108 |
+
output_dtypes=[mx.float32],
|
| 109 |
+
)
|
| 110 |
+
return out.reshape(*lead, streams, streams)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def sinkhorn(logits, iterations):
|
| 114 |
+
logits = logits.astype(mx.float32)
|
| 115 |
+
if (
|
| 116 |
+
_SINKHORN_METAL
|
| 117 |
+
and logits.shape[-1] == logits.shape[-2]
|
| 118 |
+
and logits.shape[-1] in (2, 4)
|
| 119 |
+
and mx.metal.is_available()
|
| 120 |
+
and mx.default_device() == mx.gpu
|
| 121 |
+
):
|
| 122 |
+
return sinkhorn_metal(logits, iterations)
|
| 123 |
+
return sinkhorn_reference(logits, iterations)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
_MHC_MERGE_KERNELS = {}
|
| 127 |
+
_MHC_MERGE_METAL = os.getenv("SENSENOVA_MHC_MERGE_METAL", "1") != "0"
|
| 128 |
+
_COMPILE_DECODE = os.getenv("SENSENOVA_COMPILE_DECODE", "1") != "0"
|
| 129 |
+
_COMPILE_ROUTER = os.getenv("SENSENOVA_COMPILE_ROUTER", "1") != "0"
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _mhc_merge_metal_kernel(hidden):
|
| 133 |
+
if hidden in _MHC_MERGE_KERNELS:
|
| 134 |
+
return _MHC_MERGE_KERNELS[hidden]
|
| 135 |
+
source = f"""
|
| 136 |
+
using namespace metal;
|
| 137 |
+
constexpr uint STREAMS = 2;
|
| 138 |
+
constexpr uint HIDDEN = {hidden};
|
| 139 |
+
|
| 140 |
+
uint gid = thread_position_in_grid.x;
|
| 141 |
+
if (gid >= nvalues) {{ return; }}
|
| 142 |
+
uint token = gid / (STREAMS * HIDDEN);
|
| 143 |
+
uint row = (gid / HIDDEN) % STREAMS;
|
| 144 |
+
uint column = gid % HIDDEN;
|
| 145 |
+
float mixed = 0.0f;
|
| 146 |
+
for (uint stream = 0; stream < STREAMS; ++stream) {{
|
| 147 |
+
T coefficient = static_cast<T>(mix[token * STREAMS * STREAMS + row * STREAMS + stream]);
|
| 148 |
+
mixed += static_cast<float>(coefficient) * static_cast<float>(
|
| 149 |
+
residual[token * STREAMS * HIDDEN + stream * HIDDEN + column]
|
| 150 |
+
);
|
| 151 |
+
}}
|
| 152 |
+
T mixed_value = static_cast<T>(mixed);
|
| 153 |
+
T post_value = static_cast<T>(post[token * STREAMS + row]);
|
| 154 |
+
T update = static_cast<T>(
|
| 155 |
+
static_cast<float>(post_value) *
|
| 156 |
+
static_cast<float>(branch[token * HIDDEN + column])
|
| 157 |
+
);
|
| 158 |
+
out[gid] = static_cast<T>(static_cast<float>(mixed_value) + static_cast<float>(update));
|
| 159 |
+
"""
|
| 160 |
+
kernel = mx.fast.metal_kernel(
|
| 161 |
+
name=f"sensenova_mhc_merge_h{hidden}_v1",
|
| 162 |
+
input_names=["residual", "branch", "post", "mix", "nvalues"],
|
| 163 |
+
output_names=["out"],
|
| 164 |
+
source=source,
|
| 165 |
+
compile_options={"math_mode": "safe"},
|
| 166 |
+
)
|
| 167 |
+
_MHC_MERGE_KERNELS[hidden] = kernel
|
| 168 |
+
return kernel
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def mhc_merge_metal(residual, branch, post, mix):
|
| 172 |
+
lead = residual.shape[:-2]
|
| 173 |
+
streams, hidden = residual.shape[-2:]
|
| 174 |
+
nmat = residual.size // (streams * hidden)
|
| 175 |
+
nvalues = nmat * streams * hidden
|
| 176 |
+
kernel = _mhc_merge_metal_kernel(hidden)
|
| 177 |
+
(out,) = kernel(
|
| 178 |
+
inputs=[
|
| 179 |
+
residual.reshape(nmat, streams, hidden),
|
| 180 |
+
branch.reshape(nmat, hidden),
|
| 181 |
+
post.reshape(nmat, streams),
|
| 182 |
+
mix.reshape(nmat, streams, streams),
|
| 183 |
+
nvalues,
|
| 184 |
+
],
|
| 185 |
+
template=[("T", residual.dtype)],
|
| 186 |
+
grid=(nvalues, 1, 1),
|
| 187 |
+
threadgroup=(256, 1, 1),
|
| 188 |
+
output_shapes=[(nmat, streams, hidden)],
|
| 189 |
+
output_dtypes=[residual.dtype],
|
| 190 |
+
)
|
| 191 |
+
return out.reshape(*lead, streams, hidden)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class MHCRouter(nn.Module):
|
| 195 |
+
def __init__(self, dim, settings):
|
| 196 |
+
super().__init__()
|
| 197 |
+
self.streams = settings["streams"]
|
| 198 |
+
self.iterations = settings["iterations"]
|
| 199 |
+
self.fixed_identity = settings["fixed_identity"]
|
| 200 |
+
self.pre_scale = settings.get("pre_scale", 1.0)
|
| 201 |
+
streams = self.streams
|
| 202 |
+
output_size = 2 * streams + (0 if self.fixed_identity else streams * streams)
|
| 203 |
+
self.weight = mx.zeros((output_size, streams * dim), dtype=mx.float32)
|
| 204 |
+
self.bias = mx.zeros((output_size,), dtype=mx.float32)
|
| 205 |
+
|
| 206 |
+
def __call__(self, residual):
|
| 207 |
+
if (
|
| 208 |
+
_COMPILE_DECODE
|
| 209 |
+
and _COMPILE_ROUTER
|
| 210 |
+
and residual.shape[:-2] == (1, 1)
|
| 211 |
+
and mx.metal.is_available()
|
| 212 |
+
and mx.default_device() == mx.gpu
|
| 213 |
+
):
|
| 214 |
+
compiled = getattr(self, "_compiled_forward", None)
|
| 215 |
+
if compiled is None:
|
| 216 |
+
compiled = mx.compile(self._forward)
|
| 217 |
+
self._compiled_forward = compiled
|
| 218 |
+
if compiled is not False:
|
| 219 |
+
try:
|
| 220 |
+
return compiled(residual)
|
| 221 |
+
except Exception:
|
| 222 |
+
self._compiled_forward = False
|
| 223 |
+
return self._forward(residual)
|
| 224 |
+
|
| 225 |
+
def _forward(self, residual):
|
| 226 |
+
streams = self.streams
|
| 227 |
+
flat = residual.astype(mx.float32).reshape(*residual.shape[:-2], -1)
|
| 228 |
+
normalized = flat * mx.rsqrt(mx.mean(flat * flat, axis=-1, keepdims=True) + 1e-6)
|
| 229 |
+
logits = normalized @ self.weight.T + self.bias
|
| 230 |
+
pre = mx.sigmoid(logits[..., :streams])
|
| 231 |
+
post = 2 * mx.sigmoid(logits[..., streams : 2 * streams])
|
| 232 |
+
if self.fixed_identity:
|
| 233 |
+
mix = mx.broadcast_to(
|
| 234 |
+
mx.eye(streams, dtype=mx.float32),
|
| 235 |
+
(*flat.shape[:-1], streams, streams),
|
| 236 |
+
)
|
| 237 |
+
else:
|
| 238 |
+
mix = sinkhorn(
|
| 239 |
+
logits[..., 2 * streams :].reshape(*flat.shape[:-1], streams, streams),
|
| 240 |
+
self.iterations,
|
| 241 |
+
)
|
| 242 |
+
branch = mx.matmul(pre.astype(residual.dtype)[..., None, :], residual)[..., 0, :]
|
| 243 |
+
if self.pre_scale != 1.0:
|
| 244 |
+
branch = branch * self.pre_scale
|
| 245 |
+
return branch, post, mix
|
| 246 |
+
|
| 247 |
+
@staticmethod
|
| 248 |
+
def merge(residual, branch, post, mix):
|
| 249 |
+
nmat = residual.size // residual.shape[-2] // residual.shape[-1]
|
| 250 |
+
if (
|
| 251 |
+
_SINKHORN_METAL
|
| 252 |
+
and _MHC_MERGE_METAL
|
| 253 |
+
and residual.shape[-2] == 2
|
| 254 |
+
and nmat <= 32
|
| 255 |
+
and mx.metal.is_available()
|
| 256 |
+
and mx.default_device() == mx.gpu
|
| 257 |
+
):
|
| 258 |
+
return mhc_merge_metal(residual, branch, post, mix)
|
| 259 |
+
mixed_residual = mx.matmul(mix.astype(residual.dtype), residual)
|
| 260 |
+
branch_update = post.astype(branch.dtype)[..., :, None] * branch[..., None, :]
|
| 261 |
+
return mixed_residual + branch_update
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class MHCDecoderLayer(DecoderLayer):
|
| 268 |
+
def __init__(self, args, layer_idx, settings):
|
| 269 |
+
super().__init__(args, layer_idx)
|
| 270 |
+
self._mhc_physical = layer_idx
|
| 271 |
+
self._mhc_settings = dict(settings)
|
| 272 |
+
self.mhc_attn = MHCRouter(args.hidden_size, settings)
|
| 273 |
+
self.mhc_ffn = MHCRouter(args.hidden_size, settings)
|
| 274 |
+
|
| 275 |
+
def _enter(self, hidden):
|
| 276 |
+
settings = self._mhc_settings
|
| 277 |
+
if self._mhc_physical == settings["start"]:
|
| 278 |
+
shape = (*hidden.shape[:-1], settings["streams"], hidden.shape[-1])
|
| 279 |
+
return mx.contiguous(mx.broadcast_to(hidden[..., None, :], shape))
|
| 280 |
+
return hidden.reshape(*hidden.shape[:-1], settings["streams"], -1)
|
| 281 |
+
|
| 282 |
+
def _leave(self, residual):
|
| 283 |
+
if self._mhc_physical == self._mhc_settings["end"] - 1:
|
| 284 |
+
return mx.mean(residual, axis=-2)
|
| 285 |
+
return residual.reshape(*residual.shape[:-2], -1)
|
| 286 |
+
|
| 287 |
+
def __call__(self, x, mask=None, cache=None):
|
| 288 |
+
residual = self._enter(x)
|
| 289 |
+
branch, post, mix = self.mhc_attn(residual)
|
| 290 |
+
branch = self.input_layernorm(branch)
|
| 291 |
+
if self.is_linear:
|
| 292 |
+
branch = self.linear_attn(branch, mask, cache)
|
| 293 |
+
else:
|
| 294 |
+
branch = self.self_attn(branch, mask, cache)
|
| 295 |
+
residual = MHCRouter.merge(residual, branch, post, mix)
|
| 296 |
+
branch, post, mix = self.mhc_ffn(residual)
|
| 297 |
+
branch = self.mlp(self.post_attention_layernorm(branch))
|
| 298 |
+
return self._leave(MHCRouter.merge(residual, branch, post, mix))
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class SenseNovaLoopTextModel(Qwen3_5TextModel):
|
| 302 |
+
def __init__(self, args, loop_settings, mhc):
|
| 303 |
+
super().__init__(args)
|
| 304 |
+
self._loop_plan = execution_plan(
|
| 305 |
+
{
|
| 306 |
+
"loop_settings": loop_settings,
|
| 307 |
+
"text_config": {"num_hidden_layers": args.num_hidden_layers},
|
| 308 |
+
}
|
| 309 |
+
)
|
| 310 |
+
if mhc is not None:
|
| 311 |
+
for index in range(mhc["start"], mhc["end"]):
|
| 312 |
+
self.layers[index] = MHCDecoderLayer(args, index, mhc)
|
| 313 |
+
|
| 314 |
+
def __call__(self, inputs, cache=None, input_embeddings=None):
|
| 315 |
+
hidden = input_embeddings if input_embeddings is not None else self.embed_tokens(inputs)
|
| 316 |
+
if cache is None:
|
| 317 |
+
cache = [None] * len(self._loop_plan)
|
| 318 |
+
if len(cache) != len(self._loop_plan):
|
| 319 |
+
raise ValueError(f"SenseNova Loop requires {len(self._loop_plan)} cache slots")
|
| 320 |
+
|
| 321 |
+
linear_visit = next(i for i, p in enumerate(self._loop_plan) if self.layers[p].is_linear)
|
| 322 |
+
full_visit = next(i for i, p in enumerate(self._loop_plan) if not self.layers[p].is_linear)
|
| 323 |
+
ssm_mask = create_ssm_mask(hidden, cache[linear_visit])
|
| 324 |
+
full_mask = create_attention_mask(hidden, cache[full_visit])
|
| 325 |
+
|
| 326 |
+
for visit, physical in enumerate(self._loop_plan):
|
| 327 |
+
layer = self.layers[physical]
|
| 328 |
+
mask = ssm_mask if layer.is_linear else full_mask
|
| 329 |
+
hidden = layer(hidden, mask=mask, cache=cache[visit])
|
| 330 |
+
return self.norm(hidden)
|
| 331 |
+
|
| 332 |
+
def make_cache(self):
|
| 333 |
+
return [
|
| 334 |
+
ArraysCache(size=2) if self.layers[physical].is_linear else KVCache()
|
| 335 |
+
for physical in self._loop_plan
|
| 336 |
+
]
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class TextModel(Qwen3_5TextModelWrapper):
|
| 340 |
+
def __init__(self, args, loop_settings, mhc):
|
| 341 |
+
super().__init__(args)
|
| 342 |
+
self.model = SenseNovaLoopTextModel(args, loop_settings, mhc)
|
| 343 |
+
|
| 344 |
+
def make_cache(self):
|
| 345 |
+
return self.model.make_cache()
|
| 346 |
+
|
| 347 |
+
def sanitize(self, weights):
|
| 348 |
+
weights = {k: v for k, v in weights.items() if "loop_gate" not in k}
|
| 349 |
+
return super().sanitize(weights)
|
| 350 |
+
|
| 351 |
+
@property
|
| 352 |
+
def cast_predicate(self):
|
| 353 |
+
def predicate(path):
|
| 354 |
+
if path.endswith("A_log") or "mhc_attn" in path or "mhc_ffn" in path:
|
| 355 |
+
return False
|
| 356 |
+
return True
|
| 357 |
+
|
| 358 |
+
return predicate
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
@dataclass
|
| 362 |
+
class ModelArgs(BaseModelArgs):
|
| 363 |
+
model_type: str
|
| 364 |
+
text_config: dict
|
| 365 |
+
loop_settings: dict
|
| 366 |
+
mhc: Optional[dict] = None
|
| 367 |
+
|
| 368 |
+
@classmethod
|
| 369 |
+
def from_dict(cls, params):
|
| 370 |
+
if "text_config" not in params:
|
| 371 |
+
raise ValueError("SenseNova Loop requires text_config and loop_settings")
|
| 372 |
+
return super().from_dict(params)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class Model(Qwen3_5Model):
|
| 376 |
+
def __init__(self, args: ModelArgs):
|
| 377 |
+
nn.Module.__init__(self)
|
| 378 |
+
self.args = args
|
| 379 |
+
self.model_type = args.model_type
|
| 380 |
+
self.language_model = TextModel(
|
| 381 |
+
TextModelArgs.from_dict(args.text_config), args.loop_settings, args.mhc
|
| 382 |
+
)
|
model-00001-of-00002.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:59d8e7483c12c90a1f6eec02d659d0cb2c356fab39922834e6900ce018f7f5cd
|
| 3 |
+
size 5353954795
|
model-00002-of-00002.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3e6c9c34e2b3b6ab184cca847c097a45bd03aca22ade62e567b6609e5133eb87
|
| 3 |
+
size 4173174590
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modeling_sensenova_loop.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hugging Face remote-code support for shared-weight SenseNova Loop and MHC.
|
| 2 |
+
|
| 3 |
+
This single file contains configuration, plan validation, MHC routing and the
|
| 4 |
+
model implementation. The original physical layer weights are reused on every
|
| 5 |
+
Loop visit; autoregressive cache states are independent per visit.
|
| 6 |
+
"""
|
| 7 |
+
import copy
|
| 8 |
+
import math
|
| 9 |
+
from contextvars import ContextVar
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch import nn
|
| 13 |
+
from transformers import Qwen3_5Config
|
| 14 |
+
from transformers.cache_utils import DynamicCache
|
| 15 |
+
from transformers.models.qwen3_5 import modeling_qwen3_5 as hf
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
_attention_capture = ContextVar("sensenova_attention_capture", default=None)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SenseNovaLoopConfig(Qwen3_5Config):
|
| 22 |
+
model_type = "sensenova_loop"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def execution_plan(config):
|
| 26 |
+
"""Return physical layer indices in the order they execute during inference."""
|
| 27 |
+
loop = config.get("loop_settings")
|
| 28 |
+
if not isinstance(loop, dict):
|
| 29 |
+
raise ValueError("This implementation requires explicit loop_settings")
|
| 30 |
+
|
| 31 |
+
text_config = config["text_config"]
|
| 32 |
+
num_layers = text_config["num_hidden_layers"]
|
| 33 |
+
start, end, count = loop.get("start"), loop.get("end"), loop.get("eval_count")
|
| 34 |
+
if any(type(value) is not int for value in (num_layers, start, end, count)) or not (
|
| 35 |
+
0 <= start < end <= num_layers and count >= 1
|
| 36 |
+
):
|
| 37 |
+
raise ValueError("Invalid Loop interval or eval_count")
|
| 38 |
+
if loop.get("counts") != [count]:
|
| 39 |
+
raise ValueError("Only fixed-count Loop checkpoints are supported")
|
| 40 |
+
|
| 41 |
+
layer_types = text_config["layer_types"]
|
| 42 |
+
if len(layer_types) != num_layers or set(layer_types) - {"full_attention", "linear_attention"}:
|
| 43 |
+
raise ValueError("Unexpected physical layer types")
|
| 44 |
+
if "full_attention" not in layer_types:
|
| 45 |
+
raise ValueError("At least one full-attention layer is required for sequence-length tracking")
|
| 46 |
+
|
| 47 |
+
mhc = config.get("mhc")
|
| 48 |
+
if mhc is not None:
|
| 49 |
+
mhc_start, mhc_end, streams, iterations = (
|
| 50 |
+
mhc.get(key) for key in ("start", "end", "streams", "iterations")
|
| 51 |
+
)
|
| 52 |
+
if (
|
| 53 |
+
any(type(value) is not int for value in (mhc_start, mhc_end, streams, iterations))
|
| 54 |
+
or not 0 <= mhc_start < mhc_end <= num_layers
|
| 55 |
+
or streams not in (2, 4)
|
| 56 |
+
or iterations < 1
|
| 57 |
+
):
|
| 58 |
+
raise ValueError("Invalid MHC range, stream count, or iterations")
|
| 59 |
+
if type(mhc.get("fixed_identity")) is not bool:
|
| 60 |
+
raise ValueError("MHC fixed_identity must be a boolean")
|
| 61 |
+
scale = mhc.get("pre_scale", 1.0)
|
| 62 |
+
if not isinstance(scale, (int, float)) or not math.isfinite(scale) or scale <= 0:
|
| 63 |
+
raise ValueError("Invalid MHC pre_scale")
|
| 64 |
+
allowed = {"start", "end", "streams", "iterations", "fixed_identity", "pre_scale"}
|
| 65 |
+
if set(mhc) - allowed:
|
| 66 |
+
raise ValueError("Unknown MHC configuration fields")
|
| 67 |
+
phase_boundaries = (0, start, end, num_layers)
|
| 68 |
+
if not any(
|
| 69 |
+
left <= mhc_start < mhc_end <= right
|
| 70 |
+
for left, right in zip(phase_boundaries, phase_boundaries[1:])
|
| 71 |
+
):
|
| 72 |
+
raise ValueError("MHC cannot cross a Loop phase boundary")
|
| 73 |
+
|
| 74 |
+
return tuple(range(start)) + tuple(range(start, end)) * count + tuple(range(end, num_layers))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def sinkhorn(logits, iterations):
|
| 78 |
+
"""Normalize routing logits across rows and columns in log space."""
|
| 79 |
+
logits = logits.float()
|
| 80 |
+
for _ in range(iterations):
|
| 81 |
+
logits = logits - torch.logsumexp(logits, dim=-1, keepdim=True)
|
| 82 |
+
logits = logits - torch.logsumexp(logits, dim=-2, keepdim=True)
|
| 83 |
+
return logits.exp()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class MHCRouter(nn.Module):
|
| 87 |
+
def __init__(self, dim, settings):
|
| 88 |
+
super().__init__()
|
| 89 |
+
self.streams = settings["streams"]
|
| 90 |
+
self.iterations = settings["iterations"]
|
| 91 |
+
self.fixed_identity = settings["fixed_identity"]
|
| 92 |
+
self.pre_scale = settings.get("pre_scale", 1.0)
|
| 93 |
+
streams = self.streams
|
| 94 |
+
output_size = 2 * streams + (0 if self.fixed_identity else streams * streams)
|
| 95 |
+
self.weight = nn.Parameter(torch.zeros(output_size, streams * dim, dtype=torch.float32))
|
| 96 |
+
self.bias = nn.Parameter(torch.zeros(output_size, dtype=torch.float32))
|
| 97 |
+
with torch.no_grad():
|
| 98 |
+
initial_probabilities = {2: (0.25, 0.75), 4: (0.0625, 0.1875, 0.25, 0.5)}[streams]
|
| 99 |
+
self.bias[:streams].copy_(torch.logit(torch.tensor(initial_probabilities, device=self.bias.device)))
|
| 100 |
+
if not self.fixed_identity:
|
| 101 |
+
diagonal = math.log((1 - (streams - 1) / 16) * 16)
|
| 102 |
+
self.bias[2 * streams:].copy_((torch.eye(streams, device=self.bias.device) * diagonal).flatten())
|
| 103 |
+
|
| 104 |
+
def _apply(self, fn, recurse=True):
|
| 105 |
+
# Keep the original FP32 values when the surrounding model is cast to BF16.
|
| 106 |
+
def keep_fp32(tensor):
|
| 107 |
+
result = fn(tensor)
|
| 108 |
+
if tensor.is_floating_point() and result.dtype != torch.float32:
|
| 109 |
+
if tensor.device.type == "meta" and result.device.type != "meta":
|
| 110 |
+
return torch.empty_like(result, dtype=torch.float32)
|
| 111 |
+
return tensor.to(device=result.device, dtype=torch.float32)
|
| 112 |
+
return result
|
| 113 |
+
|
| 114 |
+
return super()._apply(keep_fp32, recurse=recurse)
|
| 115 |
+
|
| 116 |
+
def forward(self, residual):
|
| 117 |
+
if self.weight.dtype != torch.float32 or self.bias.dtype != torch.float32:
|
| 118 |
+
raise RuntimeError("mHC routers require FP32 parameters; configure FSDP per-module precision")
|
| 119 |
+
with torch.autocast(device_type=residual.device.type, enabled=False):
|
| 120 |
+
flat = residual.flatten(-2).float()
|
| 121 |
+
normalized = flat * torch.rsqrt(flat.square().mean(-1, keepdim=True) + 1e-6)
|
| 122 |
+
logits = torch.nn.functional.linear(normalized, self.weight, self.bias)
|
| 123 |
+
streams = self.streams
|
| 124 |
+
pre = logits[..., :streams].sigmoid()
|
| 125 |
+
post = 2 * logits[..., streams:2 * streams].sigmoid()
|
| 126 |
+
if self.fixed_identity:
|
| 127 |
+
mix = torch.eye(streams, device=flat.device, dtype=torch.float32).expand(
|
| 128 |
+
*flat.shape[:-1], streams, streams
|
| 129 |
+
)
|
| 130 |
+
else:
|
| 131 |
+
mix = sinkhorn(logits[..., 2 * streams:].unflatten(-1, (streams, streams)), self.iterations)
|
| 132 |
+
branch = torch.matmul(pre.to(residual.dtype).unsqueeze(-2), residual).squeeze(-2)
|
| 133 |
+
if self.pre_scale != 1.0:
|
| 134 |
+
branch = branch * self.pre_scale
|
| 135 |
+
return branch, post, mix
|
| 136 |
+
|
| 137 |
+
@staticmethod
|
| 138 |
+
def merge(residual, branch, post, mix):
|
| 139 |
+
"""Mix residual streams and add the branch output to each stream."""
|
| 140 |
+
with torch.autocast(device_type=residual.device.type, enabled=False):
|
| 141 |
+
mixed_residual = torch.matmul(mix.to(residual.dtype), residual)
|
| 142 |
+
branch_update = post.to(branch.dtype).unsqueeze(-1) * branch.unsqueeze(-2)
|
| 143 |
+
return mixed_residual + branch_update
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def enter(hidden, physical, settings):
|
| 147 |
+
"""Expand to residual streams at the first mHC layer, or restore their shape."""
|
| 148 |
+
if physical == settings["start"]:
|
| 149 |
+
return hidden.unsqueeze(-2).expand(
|
| 150 |
+
*hidden.shape[:-1], settings["streams"], hidden.shape[-1]
|
| 151 |
+
).contiguous()
|
| 152 |
+
return hidden.unflatten(-1, (settings["streams"], -1))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def leave(residual, physical, settings):
|
| 156 |
+
"""Reduce streams at the last mHC layer; otherwise carry them forward."""
|
| 157 |
+
return residual.mean(-2) if physical == settings["end"] - 1 else residual.flatten(-2)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class _CacheLayersView:
|
| 161 |
+
"""Expose the execution slot when a layer accesses its physical index."""
|
| 162 |
+
def __init__(self, cache, physical, virtual):
|
| 163 |
+
self.cache = cache
|
| 164 |
+
self.physical = physical
|
| 165 |
+
self.virtual = virtual
|
| 166 |
+
|
| 167 |
+
def __getitem__(self, index):
|
| 168 |
+
if index != self.physical:
|
| 169 |
+
raise IndexError("A physical layer may only access its own virtual cache slot")
|
| 170 |
+
return self.cache.layers[self.virtual]
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class _VisitCache:
|
| 174 |
+
"""Map a physical attention module's layer_idx to one execution slot.
|
| 175 |
+
|
| 176 |
+
Mapping is local to this forward call: shared modules and their layer_idx are
|
| 177 |
+
never mutated. `layers` supports Transformers 5.12; state accessors support
|
| 178 |
+
newer official backbone cache APIs as well.
|
| 179 |
+
"""
|
| 180 |
+
def __init__(self, cache, physical, virtual):
|
| 181 |
+
self.cache = cache
|
| 182 |
+
self.virtual = virtual
|
| 183 |
+
self.layers = _CacheLayersView(cache, physical, virtual)
|
| 184 |
+
|
| 185 |
+
def update(self, key_states, value_states, layer_idx, **kwargs):
|
| 186 |
+
return self.cache.update(key_states, value_states, self.virtual, **kwargs)
|
| 187 |
+
|
| 188 |
+
def has_previous_state(self, layer_idx=None, **kwargs):
|
| 189 |
+
return self.cache.has_previous_state(self.virtual, **kwargs)
|
| 190 |
+
|
| 191 |
+
def update_conv_state(self, state, layer_idx, **kwargs):
|
| 192 |
+
return self.cache.update_conv_state(state, self.virtual, **kwargs)
|
| 193 |
+
|
| 194 |
+
def update_recurrent_state(self, state, layer_idx, **kwargs):
|
| 195 |
+
return self.cache.update_recurrent_state(state, self.virtual, **kwargs)
|
| 196 |
+
|
| 197 |
+
def get_conv_state(self, layer_idx, **kwargs):
|
| 198 |
+
return self.cache.get_conv_state(self.virtual, **kwargs)
|
| 199 |
+
|
| 200 |
+
def get_recurrent_state(self, layer_idx, **kwargs):
|
| 201 |
+
return self.cache.get_recurrent_state(self.virtual, **kwargs)
|
| 202 |
+
|
| 203 |
+
def is_recording_past(self, layer_idx):
|
| 204 |
+
return self.cache.is_recording_past(self.virtual)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class SenseNovaLoopTextModel(hf.Qwen3_5TextModel):
|
| 208 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 209 |
+
past_key_values=None, inputs_embeds=None, use_cache=None,
|
| 210 |
+
output_hidden_states=None, output_attentions=None, **kwargs):
|
| 211 |
+
"""Run Loop visits, optionally returning their states and attention weights.
|
| 212 |
+
|
| 213 |
+
Hidden states include the initial embedding and one state per visit.
|
| 214 |
+
MHC states between its boundaries retain their flattened residual streams.
|
| 215 |
+
Attention entries follow visit order, with None for linear-attention layers.
|
| 216 |
+
"""
|
| 217 |
+
if (input_ids is None) == (inputs_embeds is None):
|
| 218 |
+
raise ValueError("Specify exactly one of input_ids or inputs_embeds")
|
| 219 |
+
if inputs_embeds is None:
|
| 220 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 221 |
+
use_cache = self.config.use_cache if use_cache is None else use_cache
|
| 222 |
+
if output_hidden_states is None:
|
| 223 |
+
output_hidden_states = getattr(self.config, "output_hidden_states", False)
|
| 224 |
+
if output_attentions is None:
|
| 225 |
+
output_attentions = getattr(self.config, "output_attentions", False)
|
| 226 |
+
if not isinstance(output_hidden_states, bool):
|
| 227 |
+
raise TypeError("output_hidden_states must be a boolean.")
|
| 228 |
+
if output_attentions and self.config._attn_implementation != "eager":
|
| 229 |
+
raise ValueError(
|
| 230 |
+
"Attention weights require attn_implementation='eager' when loading the model."
|
| 231 |
+
)
|
| 232 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 233 |
+
raise ValueError("Disable use_cache when training with gradient checkpointing")
|
| 234 |
+
if not use_cache and past_key_values is not None:
|
| 235 |
+
raise ValueError("past_key_values requires use_cache=True")
|
| 236 |
+
if past_key_values is not None and not isinstance(past_key_values, DynamicCache):
|
| 237 |
+
raise TypeError("Loop generation currently supports DynamicCache only")
|
| 238 |
+
if use_cache:
|
| 239 |
+
if past_key_values is None:
|
| 240 |
+
past_key_values = DynamicCache(config=self._loop_cache_config)
|
| 241 |
+
past_key_values._loop_execution_plan = self._loop_plan
|
| 242 |
+
elif getattr(past_key_values, "_loop_execution_plan", None) != self._loop_plan:
|
| 243 |
+
# GenerationMixin may allocate an empty physical-depth cache.
|
| 244 |
+
# A populated foreign cache cannot be reinterpreted safely.
|
| 245 |
+
if past_key_values.get_seq_length() != 0 or past_key_values.has_previous_state():
|
| 246 |
+
raise ValueError("A populated cache from another execution plan cannot be reused")
|
| 247 |
+
past_key_values = DynamicCache(config=self._loop_cache_config)
|
| 248 |
+
past_key_values._loop_execution_plan = self._loop_plan
|
| 249 |
+
|
| 250 |
+
if position_ids is None:
|
| 251 |
+
seen = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 252 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + seen
|
| 253 |
+
position_ids = position_ids.view(1, 1, -1).expand(4, inputs_embeds.shape[0], -1)
|
| 254 |
+
elif position_ids.ndim == 2:
|
| 255 |
+
position_ids = position_ids.unsqueeze(0).expand(4, -1, -1)
|
| 256 |
+
if position_ids.ndim == 3 and position_ids.shape[0] == 4:
|
| 257 |
+
text_positions, position_ids = position_ids[0], position_ids[1:]
|
| 258 |
+
else:
|
| 259 |
+
text_positions = None
|
| 260 |
+
|
| 261 |
+
if isinstance(attention_mask, dict):
|
| 262 |
+
masks = attention_mask
|
| 263 |
+
else:
|
| 264 |
+
mask_args = dict(
|
| 265 |
+
config=self._loop_cache_config,
|
| 266 |
+
inputs_embeds=inputs_embeds,
|
| 267 |
+
attention_mask=attention_mask,
|
| 268 |
+
past_key_values=past_key_values,
|
| 269 |
+
position_ids=text_positions,
|
| 270 |
+
)
|
| 271 |
+
if hasattr(hf, "create_recurrent_attention_mask"):
|
| 272 |
+
linear_mask = hf.create_recurrent_attention_mask(**mask_args)
|
| 273 |
+
else:
|
| 274 |
+
linear_mask = self._update_linear_attn_mask(attention_mask, past_key_values)
|
| 275 |
+
masks = {
|
| 276 |
+
"full_attention": hf.create_causal_mask(**mask_args),
|
| 277 |
+
"linear_attention": linear_mask,
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
hidden = inputs_embeds
|
| 281 |
+
position_embeddings = self.rotary_emb(hidden, position_ids)
|
| 282 |
+
hidden_states = [hidden] if output_hidden_states else None
|
| 283 |
+
attentions = [] if output_attentions else None
|
| 284 |
+
hooks = []
|
| 285 |
+
capture_token = None
|
| 286 |
+
|
| 287 |
+
def record_attention(_module, _inputs, output):
|
| 288 |
+
if _attention_capture.get() is attentions:
|
| 289 |
+
if output[1] is None:
|
| 290 |
+
raise RuntimeError("The attention backend did not return attention weights.")
|
| 291 |
+
attentions.append(output[1])
|
| 292 |
+
|
| 293 |
+
# Repeated visits share weights, but each visit has its own cache slot.
|
| 294 |
+
try:
|
| 295 |
+
if attentions is not None:
|
| 296 |
+
for layer in self.layers:
|
| 297 |
+
if hasattr(layer, "self_attn"):
|
| 298 |
+
hooks.append(layer.self_attn.register_forward_hook(record_attention))
|
| 299 |
+
capture_token = _attention_capture.set(attentions)
|
| 300 |
+
for execution_index, physical_index in enumerate(self._loop_plan):
|
| 301 |
+
layer_type = self.config.layer_types[physical_index]
|
| 302 |
+
if attentions is not None and layer_type == "linear_attention":
|
| 303 |
+
attentions.append(None)
|
| 304 |
+
cache = (
|
| 305 |
+
_VisitCache(past_key_values, physical_index, execution_index)
|
| 306 |
+
if use_cache else None
|
| 307 |
+
)
|
| 308 |
+
hidden = self.layers[physical_index](
|
| 309 |
+
hidden, position_embeddings=position_embeddings,
|
| 310 |
+
attention_mask=masks[layer_type],
|
| 311 |
+
position_ids=text_positions, past_key_values=cache,
|
| 312 |
+
use_cache=use_cache, **kwargs,
|
| 313 |
+
)
|
| 314 |
+
if hidden_states is not None:
|
| 315 |
+
hidden_states.append(hidden)
|
| 316 |
+
finally:
|
| 317 |
+
if capture_token is not None:
|
| 318 |
+
_attention_capture.reset(capture_token)
|
| 319 |
+
for hook in hooks:
|
| 320 |
+
hook.remove()
|
| 321 |
+
|
| 322 |
+
hidden = self.norm(hidden)
|
| 323 |
+
if hidden_states is not None:
|
| 324 |
+
hidden_states[-1] = hidden
|
| 325 |
+
return hf.Qwen3_5ModelOutputWithPast(
|
| 326 |
+
last_hidden_state=hidden, past_key_values=past_key_values,
|
| 327 |
+
hidden_states=tuple(hidden_states) if hidden_states is not None else None,
|
| 328 |
+
attentions=tuple(attentions) if attentions is not None else None,
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
class MHCDecoderLayer(hf.Qwen3_5DecoderLayer):
|
| 333 |
+
def forward(self, hidden_states, position_embeddings, attention_mask=None,
|
| 334 |
+
position_ids=None, past_key_values=None, **kwargs):
|
| 335 |
+
residual = enter(hidden_states, self._mhc_physical, self._mhc_settings)
|
| 336 |
+
branch, post, mix = self.mhc_attn(residual)
|
| 337 |
+
branch = self.input_layernorm(branch)
|
| 338 |
+
kind = self.layer_type if hasattr(self, "layer_type") else self.block_type
|
| 339 |
+
if kind == "linear_attention":
|
| 340 |
+
branch = self.linear_attn(hidden_states=branch, cache_params=past_key_values,
|
| 341 |
+
attention_mask=attention_mask, **kwargs)
|
| 342 |
+
else:
|
| 343 |
+
branch, _ = self.self_attn(
|
| 344 |
+
hidden_states=branch, position_embeddings=position_embeddings,
|
| 345 |
+
attention_mask=attention_mask, position_ids=position_ids,
|
| 346 |
+
past_key_values=past_key_values, **kwargs)
|
| 347 |
+
residual = MHCRouter.merge(residual, branch, post, mix)
|
| 348 |
+
branch, post, mix = self.mhc_ffn(residual)
|
| 349 |
+
branch = self.mlp(self.post_attention_layernorm(branch))
|
| 350 |
+
return leave(MHCRouter.merge(residual, branch, post, mix),
|
| 351 |
+
self._mhc_physical, self._mhc_settings)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _configure_text_model(text, config):
|
| 355 |
+
raw = config.to_dict()
|
| 356 |
+
plan = execution_plan(raw)
|
| 357 |
+
# Change only these new model instances, preserving canonical state_dict
|
| 358 |
+
# names and avoiding a second allocation of the full backbone.
|
| 359 |
+
text.__class__ = SenseNovaLoopTextModel
|
| 360 |
+
text._loop_plan = plan
|
| 361 |
+
text._loop_cache_config = copy.deepcopy(text.config)
|
| 362 |
+
text._loop_cache_config.num_hidden_layers = len(plan)
|
| 363 |
+
text._loop_cache_config.layer_types = [text.config.layer_types[i] for i in plan]
|
| 364 |
+
if raw.get("mhc") is not None:
|
| 365 |
+
settings = raw["mhc"]
|
| 366 |
+
for i in range(settings["start"], settings["end"]):
|
| 367 |
+
layer = text.layers[i]
|
| 368 |
+
layer.__class__ = MHCDecoderLayer
|
| 369 |
+
layer._mhc_physical, layer._mhc_settings = i, dict(settings)
|
| 370 |
+
layer.mhc_attn = MHCRouter(text.config.hidden_size, settings)
|
| 371 |
+
layer.mhc_ffn = MHCRouter(text.config.hidden_size, settings)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class SenseNovaLoopModel(hf.Qwen3_5Model):
|
| 375 |
+
config_class = SenseNovaLoopConfig
|
| 376 |
+
_keep_in_fp32_modules = ["mhc_attn", "mhc_ffn"]
|
| 377 |
+
_no_split_modules = ["Qwen3_5DecoderLayer", "MHCDecoderLayer", "Qwen3_5VisionBlock"]
|
| 378 |
+
_keys_to_ignore_on_load_unexpected = [r"^mtp\."]
|
| 379 |
+
|
| 380 |
+
def __init__(self, config):
|
| 381 |
+
execution_plan(config.to_dict())
|
| 382 |
+
super().__init__(config)
|
| 383 |
+
_configure_text_model(self.language_model, config)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class SenseNovaLoopForConditionalGeneration(hf.Qwen3_5ForConditionalGeneration):
|
| 387 |
+
config_class = SenseNovaLoopConfig
|
| 388 |
+
_keep_in_fp32_modules = ["mhc_attn", "mhc_ffn"]
|
| 389 |
+
_no_split_modules = ["Qwen3_5DecoderLayer", "MHCDecoderLayer", "Qwen3_5VisionBlock"]
|
| 390 |
+
_keys_to_ignore_on_load_unexpected = [r"^mtp\."]
|
| 391 |
+
|
| 392 |
+
def __init__(self, config):
|
| 393 |
+
execution_plan(config.to_dict())
|
| 394 |
+
super().__init__(config)
|
| 395 |
+
_configure_text_model(self.model.language_model, config)
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:06b9509352d2af50381ab2247e083b80d32d5c0aba91c272ca9ff729b6a0e523
|
| 3 |
+
size 19989325
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"audio_bos_token": "<|audio_start|>",
|
| 4 |
+
"audio_eos_token": "<|audio_end|>",
|
| 5 |
+
"audio_token": "<|audio_pad|>",
|
| 6 |
+
"backend": "tokenizers",
|
| 7 |
+
"bos_token": null,
|
| 8 |
+
"clean_up_tokenization_spaces": false,
|
| 9 |
+
"eos_token": "<|im_end|>",
|
| 10 |
+
"errors": "replace",
|
| 11 |
+
"image_token": "<|image_pad|>",
|
| 12 |
+
"is_local": true,
|
| 13 |
+
"local_files_only": false,
|
| 14 |
+
"model_max_length": 262144,
|
| 15 |
+
"model_specific_special_tokens": {
|
| 16 |
+
"audio_bos_token": "<|audio_start|>",
|
| 17 |
+
"audio_eos_token": "<|audio_end|>",
|
| 18 |
+
"audio_token": "<|audio_pad|>",
|
| 19 |
+
"image_token": "<|image_pad|>",
|
| 20 |
+
"video_token": "<|video_pad|>",
|
| 21 |
+
"vision_bos_token": "<|vision_start|>",
|
| 22 |
+
"vision_eos_token": "<|vision_end|>"
|
| 23 |
+
},
|
| 24 |
+
"pad_token": "<|endoftext|>",
|
| 25 |
+
"pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
|
| 26 |
+
"processor_class": "Qwen3VLProcessor",
|
| 27 |
+
"split_special_tokens": false,
|
| 28 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 29 |
+
"tool_parser_type": "qwen3_coder",
|
| 30 |
+
"unk_token": null,
|
| 31 |
+
"video_token": "<|video_pad|>",
|
| 32 |
+
"vision_bos_token": "<|vision_start|>",
|
| 33 |
+
"vision_eos_token": "<|vision_end|>"
|
| 34 |
+
}
|