/ Модель

Характеристики

Контекст
32 768 токенов
Параметры
494 млн
Лицензия
MIT
Архитектура
qwen2 · dense
Базовая модель
Qwen2.5-0.5B
Библиотека
neuralops
Опубликована
9 ноя 2026

qwen-2.5-0.5b-adaptive-sparse-attention-wikitext2

Генерация текстаТекст → текст3 профессии
318скачиваний за 30 дней0лайковвеса обновлены11 ноя 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

Экспериментальная версия Qwen2.5-0.5B с адаптивным разреженным вниманием для авторегрессионной генерации текста и исследований эффективности внимания.

Это экспериментальный чекпойнт NeuralOps на основе Qwen/Qwen2.5-0.5B с адаптивным разреженным вниманием. В 18 из 24 блоков декодера заменён стандартный механизм внимания на AdaptiveSparseAttention, а шесть блоков сохраняют исходное Grouped-Query Attention. Модель дообучена дистилляцией скрытых представлений на WikiText-2; в репозитории есть полные веса и веса модулей внимания в FP16. По метаданным модель содержит 494 млн параметров и поддерживает контекст до 32 768 токенов.

Модель предназначена для авторегрессионной генерации текста и экспериментов с разреженными механизмами внимания. В README приведена оценка perplexity 2738,78 на валидационной части WikiText-2 при длине последовательности 512 после дистилляции, что указывает на существенное ухудшение относительно базовой Qwen2.5-0.5B с perplexity 15,38 на том же наборе. Указанная лицензия — MIT. Английский язык следует из языковых метаданных и обучающего датасета.

Сценарии применения

  • эксперименты с адаптивным разреженным вниманием в языковых моделях
  • генерация английского текста на основе WikiText
  • сравнение гибридного внимания с обычным Grouped-Query Attention

Ограничения

На WikiText-2 при длине последовательности 512 указана perplexity 2738,78 после дистилляции против 15,38 у базовой модели, что свидетельствует о крайне слабом качестве языкового моделирования в этой оценке. Метрики приведены только для WikiText-2 и не подтверждают качество на других задачах.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Бенчмарки пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь рядом с другими моделями теста

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы по шкале 0–100.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Qwen-2.5-0.5B (adaptive_sparse_attention) — NeuralOps Attention Surgery Zoo

Post-KD PPL Teacher PPL Surgery Topology Weights Format Base Model License

This repository contains a surgically transplanted and distilled checkpoint of Qwen/Qwen2.5-0.5B where 18 out of 24 decoder attention blocks (3:1 hybrid layout) have been replaced with the adaptive_sparse_attention (AdaptiveSparseAttention) operator from the NeuralOps Library, followed by 2-stage hidden-representation knowledge distillation on WikiText-2 (Salesforce/wikitext, wikitext-2-raw-v1).


Architecture & Operator Profile

AdaptiveSparseAttention: AdaptiveSparseAttention neural operator. Adaptive Sparse Attention Module (Production-Hardened). Implements dynamic top-k and threshold-based adaptive sparse attention with LoRA adapters, multi-architecture weight extraction, RoPE rotary embeddings, causal/bidirectional masking, and safe injection. Attributes: supports_causal (bool): Whether causal autoregressive masking is supported. is_custom_attention (bool): Flag indicating specialized non-standard attention mechanics.

PropertySpecification
Registry Key (ATTENTION_REGISTRY)adaptive_sparse_attention
NeuralOps Class & FamilyAdaptiveSparseAttention (sparse)
Source Implementationneuralops/layers/sparse/adaptive_sparse_attention.py
Base ArchitectureQwen/Qwen2.5-0.5B (494M params, 24 layers, $D=896$, $H_q=14$, $H_{kv}=2$, $d_h=64$)
Causal Autoregressive SupportYes
Grouped-Query Attention (GQA) HandlingYes
Rotary Position Embedding (RoPE)Yes ($ heta = 1{,}000{,}000$)
3-Level Kernel DispatchCUDA / Triton / PyTorch 3-Level

Surgical Architecture & Hybrid Topology (hybrid_3_1)

To balance subquadratic/linear-complexity efficiency against full induction-head recall in compact 0.5B causal language models, NeuralOps applies a deterministic hybrid_3_1 surgery ratio across the 24 Qwen2 decoder blocks:

  • Transplanted Layers (18 / 24 layers — 75%): Layer indices [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14, 16, 17, 18, 20, 21, 22] use adaptive_sparse_attention wrapped in QwenAttentionAdapter.
  • Native GQA Anchor Layers (6 / 24 layers — 25%): Layer indices [3, 7, 11, 15, 19, 23] preserve exact pretrained Qwen2 Grouped-Query Softmax Attention to maintain global contextual routing and retrieval anchors.
  • Single-o_proj Weight Inheritance: Each transplanted layer initializes from the teacher's exact pretrained q_proj, k_proj, v_proj, and o_proj tensors (with zero duplicated output projections and GQA KV-head expansion from 2 -> 14 heads), avoiding uninitialized projection collapse.

Empirical Evaluation

Empirical Verification Guarantee: Distillation trained via the NeuralOps Offline Representation Caching Architecture (§21.1) on an NVIDIA GeForce RTX 3090 (24GB) with 0 MB Teacher GPU VRAM and deterministic weight serialization. & Distillation Telemetry

All metrics below are directly measured on the WikiText-2 (wikitext-2-raw-v1) validation split at sequence length 512 (batch_size=8, grad_accum=4) on physical cluster hardware (NVIDIA GeForce RTX 3090 24GB):

MetricValueNotes
Teacher Baseline (Qwen/Qwen2.5-0.5B)15.38Reference exact GQA Softmax causal perplexity
Pre-KD Zero-Shot Student PPL244,977.47Immediately after 18/24 layer surgical transplant
Post-KD Distilled Student PPL2,738.78After 2-stage hidden-state representation distillation
Absolute Perplexity Delta ($\Delta$)-242,238.69Perplexity change achieved via distillation
Relative PPL Reduction98.88%Percentage recovery from zero-shot post-surgery spike

Two-Stage Knowledge Distillation Protocol

  1. Stage 1 — Frozen-Backbone Subspace Alignment (30% budget, 79 steps):
    • Trainable Parameters: Attention modules (self_attn) and layer normalizations (layernorm) only; embeddings, MLPs, and lm_head stay frozen.
    • Optimizer & Objective: FP32 master weights with AMP FP16 GradScaler, AdamW (lr=2.0e-4, weight_decay=0.01, gradient clipping 1.0), minimizing layer-wise hidden-state $ ext{MSE} + 0.25 \cdot (1 - \cos(\mathbf{h}_s, \mathbf{h}_t))$.
  2. Stage 2 — End-to-End Representation Distillation (70% budget, 182 steps):
    • Objective: Tightened layer-wise alignment loss $ ext{MSE} + 0.50 \cdot (1 - \cos(\mathbf{h}_s, \mathbf{h}_t))$ at lr=6.0e-5 across all 24 transformer residual streams (lm_head bypassed to maximize throughput).

Execution Telemetry

  • Dataset: Salesforce/wikitext (wikitext-2-raw-v1, seq_len=512)
  • Total Optimization Steps: 261 (Stage 1: 79 | Stage 2: 182)
  • Wall-Clock Distillation Time: 180.7s
  • Peak GPU VRAM Allocated: 18025 MB
  • Timestamp (UTC): 2026-11-10T00:13:22.899329Z

Packaged Artifacts & Weight Formats

This repository ships both standalone full-model weights and modular parameter-efficient adapter weights in FP16:

ArtifactSizeDescription
pytorch_model.bin1021.32 MBComplete standalone Qwen2 model weights (FP16)
attention_weights.safetensors277.31 MBTransplanted attention adapter & projection weights only (FP16)
config.json< 4 KBArchitecture config tagged with "attention_type": "adaptive_sparse_attention"
training_metrics.json< 1 KBVerifiable machine-readable telemetry & PPL log
Tokenizer (tokenizer.json, vocab.json, merges.txt)~15 MBStandard Qwen2.5 BPE tokenizer assets

Quick Start & Reproducible Loading

Option 1: Reconstruct & Load via NeuralOps Surgery + Modular Adapter Weights

import torch
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
from transformers import AutoModelForCausalLM, AutoTokenizer
from neuralops.core.registry import create_attention
from neuralops.layers.adapters.qwen_adapter import QwenAttentionAdapter

repo_id = "tahamajs/qwen-2.5-0.5b-adaptive-sparse-attention-wikitext2"
tokenizer = AutoTokenizer.from_pretrained(repo_id)
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", torch_dtype=torch.float16)

# Re-apply hybrid_3_1 surgery onto 18/24 decoder layers
hidden_size = model.config.hidden_size
num_heads = model.config.num_attention_heads
num_kv_heads = getattr(model.config, "num_key_value_heads", num_heads)
head_dim = getattr(model.config, "head_dim", hidden_size // num_heads)

for idx, layer in enumerate(model.model.layers):
    if idx % 4 == 3:
        continue
    core_attn = create_attention("adaptive_sparse_attention", dim=hidden_size, num_heads=num_heads, config=model.config)
    layer.self_attn = QwenAttentionAdapter(
        core_attention=core_attn,
        embed_dim=hidden_size,
        num_heads=num_heads,
        num_kv_heads=num_kv_heads,
        head_dim=head_dim,
        inherit_weights_from=layer.self_attn,
        is_causal=True,
        bypass_internal_out_proj=True,
    )

# Load distilled attention parameters from Hugging Face Hub
weights_path = hf_hub_download(repo_id=repo_id, filename="attention_weights.safetensors")
model.load_state_dict(load_file(weights_path), strict=False)
model = model.to("cuda" if torch.cuda.is_available() else "cpu").eval()

prompt = "Subquadratic attention surgery in large language models enables"
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
    out = model.generate(**inputs, max_new_tokens=64, do_sample=True, temperature=0.7)
print(tokenizer.decode(out[0], skip_special_tokens=True))

Option 2: Direct Standalone Model Loading

Because pytorch_model.bin and attention_weights.safetensors are both tracked in this repository, you can inspect all distilled parameters directly:

from huggingface_hub import hf_hub_download
from safetensors.torch import load_file

state = load_file(hf_hub_download("tahamajs/qwen-2.5-0.5b-adaptive-sparse-attention-wikitext2", "attention_weights.safetensors"))
print(f"Loaded {len(state)} transplanted attention parameter tensors.")

Quick Start (Universal NeuralOps Hub API)

import torch
from neuralops.hub import load_surgeried_model

# Load model and tokenizer/processor in one line directly from Hugging Face Hub
model, tokenizer = load_surgeried_model("tahamajs/qwen-2.5-0.5b-adaptive-sparse-attention-wikitext2")
model.eval()
print(f"Successfully loaded tahamajs/qwen-2.5-0.5b-adaptive-sparse-attention-wikitext2 with NeuralOps modular surgical weights!")

Citation

@software{neuralops2026qwenzoo,
  title   = {NeuralOps: Subquadratic & Hybrid Attention Surgery Zoo for Qwen-2.5-0.5B},
  author  = {Majlesi, Taha},
  year    = {2026},
  url     = {https://github.com/tahamajs/NeuralOps}
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · neuralops

Можно запустить

Подбираем GPU…

Класс архитектуры
Qwen2ForCausalLM
Ревизия весов
ffaa24b

0 моделей