Instructions to use squ11z1/Gravity-2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use squ11z1/Gravity-2 with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf squ11z1/Gravity-2:Q4_K_M # Run inference directly in the terminal: llama cli -hf squ11z1/Gravity-2:Q4_K_M
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf squ11z1/Gravity-2:Q4_K_M # Run inference directly in the terminal: llama cli -hf squ11z1/Gravity-2:Q4_K_M
Use pre-built binary
# Download pre-built binary from: # https://github.com/ggerganov/llama.cpp/releases # Start a local OpenAI-compatible server with a web UI: ./llama-server -hf squ11z1/Gravity-2:Q4_K_M # Run inference directly in the terminal: ./llama-cli -hf squ11z1/Gravity-2:Q4_K_M
Build from source code
git clone https://github.com/ggerganov/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-server llama-cli # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama-server -hf squ11z1/Gravity-2:Q4_K_M # Run inference directly in the terminal: ./build/bin/llama-cli -hf squ11z1/Gravity-2:Q4_K_M
Use Docker
docker model run hf.co/squ11z1/Gravity-2:Q4_K_M
- LM Studio
- Jan
- vLLM
How to use squ11z1/Gravity-2 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "squ11z1/Gravity-2" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "squ11z1/Gravity-2", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/squ11z1/Gravity-2:Q4_K_M
- Ollama
How to use squ11z1/Gravity-2 with Ollama:
ollama run hf.co/squ11z1/Gravity-2:Q4_K_M
- Unsloth Studio
How to use squ11z1/Gravity-2 with Unsloth Studio:
Install Unsloth Studio (macOS, Linux, WSL)
curl -fsSL https://unsloth.ai/install.sh | sh # Run unsloth studio unsloth studio -H 0.0.0.0 -p 8888 # Then open http://localhost:8888 in your browser # Search for squ11z1/Gravity-2 to start chatting
Install Unsloth Studio (Windows)
irm https://unsloth.ai/install.ps1 | iex # Run unsloth studio unsloth studio -H 0.0.0.0 -p 8888 # Then open http://localhost:8888 in your browser # Search for squ11z1/Gravity-2 to start chatting
Using HuggingFace Spaces for Unsloth
# No setup required # Open https://huggingface.co/spaces/unsloth/studio in your browser # Search for squ11z1/Gravity-2 to start chatting
- Pi
How to use squ11z1/Gravity-2 with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf squ11z1/Gravity-2:Q4_K_M
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "squ11z1/Gravity-2:Q4_K_M" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use squ11z1/Gravity-2 with Docker Model Runner:
docker model run hf.co/squ11z1/Gravity-2:Q4_K_M
- Lemonade
How to use squ11z1/Gravity-2 with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull squ11z1/Gravity-2:Q4_K_M
Run and chat with the model
lemonade run user.Gravity-2-Q4_K_M
List all available models
lemonade list
- Hermes Agent
How to use squ11z1/Gravity-2 with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf squ11z1/Gravity-2:Q4_K_M
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 squ11z1/Gravity-2:Q4_K_M
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use squ11z1/Gravity-2 with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf squ11z1/Gravity-2:Q4_K_M
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 "squ11z1/Gravity-2:Q4_K_M" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Gravity-2 stage-1: VibeThinker-3B with gravity attention (LoRA merged + trained masses)
Browse files- .gitattributes +1 -0
- README.md +31 -0
- chat_template.jinja +54 -0
- config.json +69 -0
- generation_config.json +6 -0
- gravity_attention_qwen.py +110 -0
- gravity_mass_log.pt +3 -0
- load_gravity2.py +16 -0
- model.safetensors +3 -0
- tokenizer.json +3 -0
- tokenizer_config.json +16 -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,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
base_model: WeiboAI/VibeThinker-3B
|
| 4 |
+
tags: [gravity-attention, qwen2, research, experimental]
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# Gravity-2 (VibeThinker-3B)
|
| 8 |
+
|
| 9 |
+
Research model: standard `softmax(QKᵀ/√d)` attention replaced with **gravity attention**
|
| 10 |
+
|
| 11 |
+
score(i,j) = M_h² / (||q_i − k_j||² + ε) → softmax over j
|
| 12 |
+
|
| 13 |
+
`M_h` = `softplus(gravity_mass_log[h])`, one learnable mass per query head (16/layer,
|
| 14 |
+
GQA: 2 KV heads repeated to 16). Stage-1: LoRA on q/k/v/o_proj + full-trained masses,
|
| 15 |
+
~600 steps on OpenR1-Math. **Experimental** — early-stage, not production quality.
|
| 16 |
+
|
| 17 |
+
## Loading (REQUIRES the gravity patch — vanilla load gives garbage)
|
| 18 |
+
```bash
|
| 19 |
+
python load_gravity2.py
|
| 20 |
+
```
|
| 21 |
+
The weights are LoRA-merged into the base, but were trained under gravity scoring, so
|
| 22 |
+
you must `patch_qwen_with_gravity(model)` and load `gravity_mass_log.pt` after loading
|
| 23 |
+
(see `load_gravity2.py`). `config.json` ships `_attn_implementation="eager"` only so the
|
| 24 |
+
checkpoint loads; the patch switches it to gravity.
|
| 25 |
+
|
| 26 |
+
## ⚠️ GGUF files
|
| 27 |
+
GGUF builds (`*.gguf`) are provided for convenience, **but gravity attention does NOT
|
| 28 |
+
work in GGUF**. llama.cpp has no kernel for `M²/(||q−k||²+ε)` scoring, so it runs
|
| 29 |
+
standard `softmax(QKᵀ)` attention over weights trained for gravity attention — output
|
| 30 |
+
is degraded/incorrect. The GGUF is a format placeholder only; use the safetensors +
|
| 31 |
+
`load_gravity2.py` path for the actual gravity model.
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- if tools %}
|
| 2 |
+
{{- '<|im_start|>system\n' }}
|
| 3 |
+
{%- if messages[0]['role'] == 'system' %}
|
| 4 |
+
{{- messages[0]['content'] }}
|
| 5 |
+
{%- else %}
|
| 6 |
+
{{- 'You are a helpful assistant.' }}
|
| 7 |
+
{%- endif %}
|
| 8 |
+
{{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
|
| 9 |
+
{%- for tool in tools %}
|
| 10 |
+
{{- "\n" }}
|
| 11 |
+
{{- tool | tojson }}
|
| 12 |
+
{%- endfor %}
|
| 13 |
+
{{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
|
| 14 |
+
{%- else %}
|
| 15 |
+
{%- if messages[0]['role'] == 'system' %}
|
| 16 |
+
{{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
|
| 17 |
+
{%- else %}
|
| 18 |
+
{{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}
|
| 19 |
+
{%- endif %}
|
| 20 |
+
{%- endif %}
|
| 21 |
+
{%- for message in messages %}
|
| 22 |
+
{%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
|
| 23 |
+
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
|
| 24 |
+
{%- elif message.role == "assistant" %}
|
| 25 |
+
{{- '<|im_start|>' + message.role }}
|
| 26 |
+
{%- if message.content %}
|
| 27 |
+
{{- '\n' + message.content }}
|
| 28 |
+
{%- endif %}
|
| 29 |
+
{%- for tool_call in message.tool_calls %}
|
| 30 |
+
{%- if tool_call.function is defined %}
|
| 31 |
+
{%- set tool_call = tool_call.function %}
|
| 32 |
+
{%- endif %}
|
| 33 |
+
{{- '\n<tool_call>\n{"name": "' }}
|
| 34 |
+
{{- tool_call.name }}
|
| 35 |
+
{{- '", "arguments": ' }}
|
| 36 |
+
{{- tool_call.arguments | tojson }}
|
| 37 |
+
{{- '}\n</tool_call>' }}
|
| 38 |
+
{%- endfor %}
|
| 39 |
+
{{- '<|im_end|>\n' }}
|
| 40 |
+
{%- elif message.role == "tool" %}
|
| 41 |
+
{%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
|
| 42 |
+
{{- '<|im_start|>user' }}
|
| 43 |
+
{%- endif %}
|
| 44 |
+
{{- '\n<tool_response>\n' }}
|
| 45 |
+
{{- message.content }}
|
| 46 |
+
{{- '\n</tool_response>' }}
|
| 47 |
+
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
|
| 48 |
+
{{- '<|im_end|>\n' }}
|
| 49 |
+
{%- endif %}
|
| 50 |
+
{%- endif %}
|
| 51 |
+
{%- endfor %}
|
| 52 |
+
{%- if add_generation_prompt %}
|
| 53 |
+
{{- '<|im_start|>assistant\n' }}
|
| 54 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"Qwen2ForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.0,
|
| 6 |
+
"bos_token_id": 151643,
|
| 7 |
+
"dtype": "bfloat16",
|
| 8 |
+
"eos_token_id": 151643,
|
| 9 |
+
"hidden_act": "silu",
|
| 10 |
+
"hidden_size": 2048,
|
| 11 |
+
"initializer_range": 0.02,
|
| 12 |
+
"intermediate_size": 11008,
|
| 13 |
+
"layer_types": [
|
| 14 |
+
"full_attention",
|
| 15 |
+
"full_attention",
|
| 16 |
+
"full_attention",
|
| 17 |
+
"full_attention",
|
| 18 |
+
"full_attention",
|
| 19 |
+
"full_attention",
|
| 20 |
+
"full_attention",
|
| 21 |
+
"full_attention",
|
| 22 |
+
"full_attention",
|
| 23 |
+
"full_attention",
|
| 24 |
+
"full_attention",
|
| 25 |
+
"full_attention",
|
| 26 |
+
"full_attention",
|
| 27 |
+
"full_attention",
|
| 28 |
+
"full_attention",
|
| 29 |
+
"full_attention",
|
| 30 |
+
"full_attention",
|
| 31 |
+
"full_attention",
|
| 32 |
+
"full_attention",
|
| 33 |
+
"full_attention",
|
| 34 |
+
"full_attention",
|
| 35 |
+
"full_attention",
|
| 36 |
+
"full_attention",
|
| 37 |
+
"full_attention",
|
| 38 |
+
"full_attention",
|
| 39 |
+
"full_attention",
|
| 40 |
+
"full_attention",
|
| 41 |
+
"full_attention",
|
| 42 |
+
"full_attention",
|
| 43 |
+
"full_attention",
|
| 44 |
+
"full_attention",
|
| 45 |
+
"full_attention",
|
| 46 |
+
"full_attention",
|
| 47 |
+
"full_attention",
|
| 48 |
+
"full_attention",
|
| 49 |
+
"full_attention"
|
| 50 |
+
],
|
| 51 |
+
"max_position_embeddings": 131072,
|
| 52 |
+
"max_window_layers": 36,
|
| 53 |
+
"model_type": "qwen2",
|
| 54 |
+
"num_attention_heads": 16,
|
| 55 |
+
"num_hidden_layers": 36,
|
| 56 |
+
"num_key_value_heads": 2,
|
| 57 |
+
"pad_token_id": null,
|
| 58 |
+
"rms_norm_eps": 1e-06,
|
| 59 |
+
"rope_parameters": {
|
| 60 |
+
"rope_theta": 1000000.0,
|
| 61 |
+
"rope_type": "default"
|
| 62 |
+
},
|
| 63 |
+
"sliding_window": null,
|
| 64 |
+
"tie_word_embeddings": true,
|
| 65 |
+
"transformers_version": "5.12.1",
|
| 66 |
+
"use_cache": false,
|
| 67 |
+
"use_sliding_window": false,
|
| 68 |
+
"vocab_size": 151936
|
| 69 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 151643,
|
| 3 |
+
"eos_token_id": 151643,
|
| 4 |
+
"max_new_tokens": 2048,
|
| 5 |
+
"transformers_version": "5.12.1"
|
| 6 |
+
}
|
gravity_attention_qwen.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gravity-2 attention for Qwen2 / VibeThinker-3B (transformers 5.x interface).
|
| 3 |
+
|
| 4 |
+
Replaces softmax(QKᵀ·scaling) with a physically-motivated score:
|
| 5 |
+
|
| 6 |
+
score(i,j) = M_h² / (||q_i − k_j||² + eps) # then standard softmax over j
|
| 7 |
+
|
| 8 |
+
• M_h = softplus(gravity_mass_log[h]) — one learnable mass per QUERY head (16/layer)
|
| 9 |
+
• ||q_i − k_j||² = ||q||² + ||k||² − 2·q·k # GQA: K repeated 2→16 first
|
| 10 |
+
• eps guards the singularity at q==k
|
| 11 |
+
|
| 12 |
+
Integration uses the transformers-5.x AttentionInterface dispatch (NOT a forward
|
| 13 |
+
monkeypatch): we register a "gravity" attention fn + alias its mask to "eager" so
|
| 14 |
+
the framework keeps building the additive causal mask, handling RoPE/cache itself.
|
| 15 |
+
"""
|
| 16 |
+
import math
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
from transformers.models.qwen2.modeling_qwen2 import repeat_kv
|
| 21 |
+
from transformers.modeling_utils import AttentionInterface
|
| 22 |
+
from transformers.masking_utils import ALL_MASK_ATTENTION_FUNCTIONS
|
| 23 |
+
|
| 24 |
+
ATTN_NAME = "gravity"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def gravity_attention_forward(module, query, key, value, attention_mask,
|
| 28 |
+
scaling=None, dropout=0.0, **kwargs):
|
| 29 |
+
"""AttentionInterface contract.
|
| 30 |
+
|
| 31 |
+
query: (B, Hq, Tq, D) key/value: (B, Hkv, Tk, D)
|
| 32 |
+
returns: (attn_output (B, Tq, Hq, D), attn_weights (B, Hq, Tq, Tk))
|
| 33 |
+
`scaling` is intentionally ignored — gravity replaces the 1/√d scale.
|
| 34 |
+
"""
|
| 35 |
+
# GQA: expand 2 KV heads up to 16 so distances live in per-query-head space
|
| 36 |
+
key = repeat_kv(key, module.num_key_value_groups)
|
| 37 |
+
value = repeat_kv(value, module.num_key_value_groups)
|
| 38 |
+
|
| 39 |
+
# ||q_i - k_j||^2 in fp32 for numerical stability
|
| 40 |
+
q = query.float()
|
| 41 |
+
k = key.float()
|
| 42 |
+
q_sq = (q * q).sum(-1, keepdim=True) # (B,Hq,Tq,1)
|
| 43 |
+
k_sq = (k * k).sum(-1, keepdim=True).transpose(-2, -1) # (B,Hq,1,Tk)
|
| 44 |
+
qk = torch.matmul(q, k.transpose(-2, -1)) # (B,Hq,Tq,Tk)
|
| 45 |
+
d_sq = (q_sq + k_sq - 2.0 * qk).clamp_min(0.0)
|
| 46 |
+
|
| 47 |
+
mass = F.softplus(module.gravity_mass_log).float().view(1, -1, 1, 1) # (1,Hq,1,1)
|
| 48 |
+
scores = (mass * mass) / (d_sq + module.gravity_eps) # (B,Hq,Tq,Tk), fp32
|
| 49 |
+
|
| 50 |
+
if attention_mask is not None:
|
| 51 |
+
# additive causal mask (eager-style), already correct length
|
| 52 |
+
scores = scores + attention_mask[..., : key.shape[-2]].float()
|
| 53 |
+
|
| 54 |
+
attn = F.softmax(scores, dim=-1, dtype=torch.float32)
|
| 55 |
+
|
| 56 |
+
# AER: optionally stash mean per-row attention entropy (flag-gated, ~free when off)
|
| 57 |
+
if getattr(module, "_capture_entropy", False):
|
| 58 |
+
ent = -(attn.clamp_min(1e-12) * attn.clamp_min(1e-12).log()).sum(-1)
|
| 59 |
+
module._last_entropy = ent.mean().detach()
|
| 60 |
+
|
| 61 |
+
attn = F.dropout(attn, p=dropout, training=module.training)
|
| 62 |
+
attn = attn.to(value.dtype)
|
| 63 |
+
|
| 64 |
+
out = torch.matmul(attn, value) # (B,Hq,Tq,D)
|
| 65 |
+
out = out.transpose(1, 2).contiguous() # (B,Tq,Hq,D)
|
| 66 |
+
return out, attn
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
_REGISTERED = False
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _register():
|
| 73 |
+
global _REGISTERED
|
| 74 |
+
if _REGISTERED:
|
| 75 |
+
return
|
| 76 |
+
AttentionInterface.register(ATTN_NAME, gravity_attention_forward)
|
| 77 |
+
# reuse the eager additive-mask builder for our custom impl
|
| 78 |
+
ALL_MASK_ATTENTION_FUNCTIONS.register(ATTN_NAME, ALL_MASK_ATTENTION_FUNCTIONS["eager"])
|
| 79 |
+
_REGISTERED = True
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def patch_qwen_with_gravity(model, eps: float = 0.1, init_mass: float = 0.5):
|
| 83 |
+
"""Add per-head gravity_mass_log to every Qwen2 self-attn and switch dispatch.
|
| 84 |
+
|
| 85 |
+
Leaves q/k/v/o_proj weights untouched. gravity_mass_log kept in fp32.
|
| 86 |
+
"""
|
| 87 |
+
_register()
|
| 88 |
+
init_log = math.log(math.exp(init_mass) - 1.0) # softplus^{-1}(init_mass)
|
| 89 |
+
H = model.config.num_attention_heads
|
| 90 |
+
n = 0
|
| 91 |
+
for layer in model.model.layers:
|
| 92 |
+
attn = layer.self_attn
|
| 93 |
+
dev = attn.q_proj.weight.device
|
| 94 |
+
attn.gravity_mass_log = nn.Parameter(
|
| 95 |
+
torch.full((H,), init_log, device=dev, dtype=torch.float32)
|
| 96 |
+
)
|
| 97 |
+
attn.gravity_eps = float(eps)
|
| 98 |
+
# config object is shared, but set defensively
|
| 99 |
+
attn.config._attn_implementation = ATTN_NAME
|
| 100 |
+
n += 1
|
| 101 |
+
model.config._attn_implementation = ATTN_NAME
|
| 102 |
+
print(f"[gravity] patched {n} Qwen2 layers (heads={H}, eps={eps}, init_mass={init_mass})")
|
| 103 |
+
return model
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def gravity_mass_state_dict(model):
|
| 107 |
+
"""Extract only the gravity_mass_log params (for saving separately from base)."""
|
| 108 |
+
return {f"model.layers.{i}.self_attn.gravity_mass_log":
|
| 109 |
+
layer.self_attn.gravity_mass_log.detach().cpu()
|
| 110 |
+
for i, layer in enumerate(model.model.layers)}
|
gravity_mass_log.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b37e7594676837dbf0b980970007938a992c059effcd5989c46e98ca1ced4c84
|
| 3 |
+
size 14513
|
load_gravity2.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
+
from gravity_attention_qwen import patch_qwen_with_gravity
|
| 4 |
+
|
| 5 |
+
REPO = "." # or "squ11z1/Gravity-2"
|
| 6 |
+
tok = AutoTokenizer.from_pretrained(REPO)
|
| 7 |
+
model = AutoModelForCausalLM.from_pretrained(REPO, dtype=torch.bfloat16,
|
| 8 |
+
device_map="cuda", attn_implementation="eager")
|
| 9 |
+
patch_qwen_with_gravity(model) # re-enable gravity attention
|
| 10 |
+
masses = torch.load(f"{REPO}/gravity_mass_log.pt", map_location="cuda")
|
| 11 |
+
for i, layer in enumerate(model.model.layers):
|
| 12 |
+
layer.self_attn.gravity_mass_log.data.copy_(masses[f"model.layers.{i}.self_attn.gravity_mass_log"].cuda())
|
| 13 |
+
model.eval()
|
| 14 |
+
ids = tok.apply_chat_template([{"role":"user","content":"What is 24*17?"}],
|
| 15 |
+
add_generation_prompt=True, return_tensors="pt", return_dict=True)["input_ids"].cuda()
|
| 16 |
+
print(tok.decode(model.generate(ids, max_new_tokens=200)[0, ids.shape[1]:], skip_special_tokens=True))
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e645da04da9ff8321fa0f2f9894b7db9975d416ecd55e70e03af4dde88ccdfac
|
| 3 |
+
size 6171933008
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b17e16899b7fab7e695509f84bac5f10ed12804f0a590e935941e5af7f092f7f
|
| 3 |
+
size 11422263
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"backend": "tokenizers",
|
| 4 |
+
"bos_token": null,
|
| 5 |
+
"clean_up_tokenization_spaces": false,
|
| 6 |
+
"eos_token": "<|endoftext|>",
|
| 7 |
+
"errors": "replace",
|
| 8 |
+
"is_local": false,
|
| 9 |
+
"local_files_only": false,
|
| 10 |
+
"model_max_length": 131072,
|
| 11 |
+
"pad_token": "<|endoftext|>",
|
| 12 |
+
"padding_side": "right",
|
| 13 |
+
"split_special_tokens": false,
|
| 14 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 15 |
+
"unk_token": null
|
| 16 |
+
}
|