Skip to content
Other

AttnRes-Qwen3-4B

компактный адаптер на 5,12 МБ для усиления Qwen3-4B без LoRA

2 min readupdated

Автор Liyew представил лёгкую надстройку для языковой модели Qwen/Qwen3-4B, которая улучшает решение математических задач и генерацию кода без изменения весов самой нейросети. В основе лежит метод Retroactive Cross-Layer Attention Residuals (межслоевые остаточные связи внимания): адаптер подключается к полностью замороженной базовой модели через 8 хуков PyTorch на границах слоёв (L4, L8, L12, L16, L20, L24, L28, L32). В отличие от привычных LoRA (метода адаптации через низкоранговые матрицы) и предыдущей версии v1, модуль весит всего 5,12 МБ, не требует переобучения базовых весов и почти не влияет на скорость генерации. Решение пригодится разработчикам и исследователям, которые хотят повысить точность Qwen3-4B в рассуждениях и коде с минимальными затратами памяти.

Ключевые особенности

  • Сверхмалый размер: 2 682 880 обучаемых параметров занимают 5,12 МБ в формате BF16 (0,067% от размера Qwen3-4B).
  • Полностью замороженная база и 0 весов LoRA: исходные веса модели не меняются, а на старте адаптер инициализирован тождественно (максимальное отклонение логитов равно нулю).
  • Практически нулевые накладные расходы при генерации: модуль работает за один проход, полностью совместим с KV-cache и показывает скорость 24,25 tok/s против 22,91 tok/s у стоковой модели на NVIDIA A100-80GB.
  • Обучение с проверкой ответов: адаптер обучен на 1 152 проверенных решениях самой Qwen3-4B (задачи GSM8K, Competition Math и тесты MBPP) с регуляризацией forward-KL (β = 0,3) относительно исходной модели.

Что можно сделать

  • Подключить адаптер поверх стандартной Qwen3-4B в Python-скрипте через библиотеку attnres, чтобы повысить качество ответов на математические и логические задачи без скачивания нового полного чекпоинта.
  • Использовать связку для локальной генерации и проверки кода на Python в задачах уровня HumanEval, сохраняя исходную скорость инференса.
  • Изучить или воспроизвести архитектуру межслоевых остаточных связей на своих проектах благодаря открытому коду и визуальному разбору от автора.

Пример

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-4B", dtype=torch.bfloat16, device_map="cuda")
ckpt = hf_hub_download("Liyew/AttnRes-Qwen3-4B", "attnres_qwen3_4b_v2.pt")
ctrl = AttnResController.load_adapter(ckpt, device="cuda", dtype=torch.bfloat16)
ctrl.attach(model)
out = model.generate(**inputs, max_new_tokens=256, do_sample=False)
ПодробнееБенчмарки (714 задач, greedy-режим с enable_thinking=False, A100-80GB): GSM8K вырос с 88,00% до 91,50% (+3,50 п.п.), HumanEval — с 79,27% до 79,88% (+0,61 п.п.), ARC-Challenge — с 84,00% до 84,50% (+0,50 п.п.), MATH-500 остался на уровне 59,33%.
Средний прирост по четырём наборам тестов составил +1,15 п.п. (78,80% против 77,65% у базовой версии) без деградации ни в одной дисциплине.
Для запуска в примере используется GPU с поддержкой CUDA и точность bfloat16; замеры скорости проводились на видеокарте NVIDIA A100-80GB при batch=1.
Примеры
Discuss TelegramReport 0

Will it run?

Runs in BF16

Fits without quantisation.

  • BF16weights 0.0 GB · ready files0.5 GB
  • FP8 / INT8recommendedweights 0.0 GB0.5 GB
  • 4-bitweights 0.0 GB0.5 GB

Tip: go 8-bit.FP8 / INT8 is within about a percent of full precision in quality, takes half the memory and runs faster on RTX 40/50 and H100. Full precision only pays off for fine-tuning.

What to get for this model

Massed ComputeOpen Massed Compute

Your own GPU: FP8 / INT8 — from RTX 2060 · BF16 — from RTX 2060

Massed Compute hourly prices, November 2026. The discounted price applies with the coupon at checkout.

Estimate: weights plus working memory. Long videos, high resolutions and long contexts need more.

Run it on Massed Compute

The script downloads the model to the rented machine. How to run it is in the model card.

  1. 1. Rent a machine with a fitting GPU

    Open Massed Compute
  2. 2. Paste the script into the machine's terminal

    Connect over SSH (the Massed Compute panel shows the command) or open a terminal on the machine's desktop.

    HF_TOKEN / CIVITAI_TOKENThe script starts with token lines: paste yours between the quotes. The Hugging Face token is for gated models, the Civitai one for Civitai models.

    # Liyew/AttnRes-Qwen3-4B
    mkdir -p ~/models
    curl -LsSf https://astral.sh/uv/install.sh | sh
    source "$HOME/.local/bin/env"
    uv tool install "huggingface_hub[cli]"
    hf download Liyew/AttnRes-Qwen3-4B --local-dir ~/models/AttnRes-Qwen3-4B
    # The model is in ~/models. How to run it is in the model card (link above).
    Add more LoRAs to AttnRes-Qwen3-4B
  3. 3. Use it

    The model is in ~/models. How to run it is in the model card (link above).

Stop the machine in the panel when you are done: it bills by the minute while it runs.

How to speed it up

Picked for this model type. Choose your hardware above to see what fits you exactly.

  • FlashAttention 44.0.0b42from December 2, 2026new release

    fastest exact attention on B200

    Kernels for Blackwell (beta). Exact attention without quantisation — fine for everything, LLMs included.

    How to enable: pip install flash-attn-4; vLLM and SGLang pick it up themselves.

    Earlier generations (2)
    • FlashAttention 3 — The Hopper (H100/H200) version with FP8.
    • FlashAttention 2 — The standard for RTX 30/40/50 and A100: exact attention without the memory cost of long contexts.
  • torch.compile2.15.0from October 28, 2026

    10–30% for free

    Compiles the model for your GPU. Slower first run, faster afterwards.

    How to enable: model = torch.compile(model); in ComfyUI the TorchCompileModel node.

Model family

  1. Qwen3-4B-Basefamily root
  2. Qwen3-4B
  3. AttnRes-Qwen3-4B

New posts about versions of Qwen3-4B-Base (quants, finetunes, LoRAs) will show up under the bell.

Quantised versions 12All on Hugging Face
Fine-tunes 12All on Hugging Face
LoRAs and adapters 2All on Hugging Face
Merges 1All on Hugging Face

About the model

Liyew/AttnRes-Qwen3-4B
Author
Liyew
Category
Other
Released
Posted

On NeyroLearn

Hugging Face

00

Ask AI about this model

Generated by external AI (Google Gemini) · chat stays only in this tab · Privacy Policy

Comments