/ Модель

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

Лицензия
Apache 2.0
Архитектура
gemma4_assistant · dense
Базовая модель
gemma-4-E2B-it-assistant
Библиотека
transformers
Опубликована
29 окт 2026

gemma-4-E2B-it-assistant-tr-medical

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

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

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

Дообученный драфтер для ускорения спекулятивного декодирования Gemma 4 E2B, в первую очередь при генерации медицинских текстов на турецком языке.

Это дообученный вспомогательный драфтер Gemma 4 E2B, разработанный автором репозитория senpaicq на базе google/gemma-4-E2B-it-assistant. Он предназначен для ускорения генерации модели google/gemma-4-E2B-it методом спекулятивного декодирования, особенно при создании медицинских текстов на турецком языке. Это плотная языковая модель с causal LM-архитектурой Gemma4AssistantForCausalLM; веса опубликованы в формате Safetensors. Драфтер использует общее KV-кэш-хранилище целевой модели и рассчитан только на Gemma 4 E2B.

В описанных автором тестах ускорение генерации турецких медицинских текстов составило примерно 1,7 раза относительно обычного декодирования при рекомендуемом K=4. Драфтер предлагает токены, а целевая модель проверяет их, поэтому он не предназначен для самостоятельных медицинских ответов и не меняет целевую модель. Качество и точность медицинских ответов остаются свойствами Gemma 4 E2B; не используйте результат как медицинскую консультацию.

Проверки проводились в Transformers при жадном декодировании и размере пакета 1; фактическое ускорение в других движках может отличаться. Модель тестировалась только с Gemma 4 E2B, не подходит для других размеров Gemma 4. Лицензия — Apache-2.0.

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

  • ускорение генерации турецких медицинских текстов в Gemma 4 E2B
  • ускорение ответов на медицинские вопросы на турецком языке
  • ускорение генерации общих текстов на турецком языке с Gemma 4 E2B
  • снижение задержки генерации Gemma 4 E2B при спекулятивном декодировании

Ограничения

Работает только как вспомогательный драфтер с целевой моделью Gemma 4 E2B; проверялся при жадном декодировании и размере пакета 1. Скорость зависит от движка инференса, а сама модель не является медицинской моделью и не должна использоваться для медицинских советов.

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

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

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

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

Источники: 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

Gemma 4 E2B MTP drafter, fine-tuned for Turkish medical text

This is a fine-tuned version of google/gemma-4-E2B-it-assistant, the speculative-decoding (MTP) drafter that ships with Gemma 4 E2B. Use it as the assistant model for google/gemma-4-E2B-it.

What it does: it makes Gemma 4 E2B generate Turkish medical text about 1.7x faster than plain decoding. With the original drafter the speedup was about 1.2x. Other domains do not get worse.

What it does not do: it does not change what the model says. In speculative decoding the target model checks every drafted token, so the output is the same as running gemma-4-E2B-it alone. This is a speed add-on and not a medical model. The target model was not modified.

Results

Speedup is measured with HF generate, greedy decoding, batch size 1, 128 new tokens, on an A100-80GB with bf16. It is compared with the same target without an assistant. τ is the number of tokens accepted per target forward pass. Brackets show 95% bootstrap confidence intervals over prompts.

Test set (prompts)Original drafter, K=4This drafter, K=4Original, K=2This drafter, K=2
Turkish medical, fully held-out (20)1.15x (τ 1.73)1.66x [1.58, 1.76] (τ 2.54)1.24x1.64x
Turkish medical (48)1.17x (τ 1.78)1.73x [1.68, 1.79] (τ 2.65)1.26x1.66x
Turkish general (32)1.24x1.44x1.31x1.47x
English medical (24)1.46x1.65x1.46x1.58x
English general (24)1.49x1.48x1.48x1.49x

K is the number of draft tokens per step. K=4 is recommended.

Teacher-forced acceptance on held-out responses: τ̂ at K=4, averaged over 3 seeds. The seed-to-seed std is about 0.001.

Test setOriginalThis drafterDifference [95% CI]
Turkish medical, held-out set1.9052.544+0.64 [+0.54, +0.74]
Turkish general, held-out set2.0492.243+0.20 [+0.16, +0.22]
English medical, held-out set2.1992.344+0.15 [+0.10, +0.20]
English general, held-out set2.4232.424+0.00 [−0.02, +0.02]

Lossless check: on 16 Turkish medical prompts at K=2 and K=4 in fp32 with TF32 off, the output with this drafter is identical token by token to the output without it in 100% of cases. In bf16 a fraction of outputs diverge after a few dozen tokens. That divergence happens at exactly the same rate and positions with the original drafter, so it is bf16 numerical noise and not caused by the drafter.

Why the original drafter is slow on Turkish

The Gemma 4 drafter does not score the full 262k vocabulary. An ordered embedding head first picks the top 32 of 2,048 token clusters, then scores only the tokens in those clusters, which is about 1.6% of the vocabulary. If the target's next token is outside the selected clusters, the drafter cannot predict it.

On Turkish, the correct token was inside the selected clusters only 83% of the time, compared with 92–94% on English. Fine-tuning the cluster selector together with the drafter raises this to 96% for Turkish medical text. That one change gives most of the gain:

Variant (3 seeds each)Turkish medical held-out τ̂ (K=4)Cluster recall
Original1.90582.9%
Fine-tune drafter body, KL to target2.23285.3%
+ train cluster selector2.47095.5%
+ train lm_head (this model)2.54495.4%

Training

  • Data: about 16,500 prompt–response pairs (Turkish medical 10,000, Turkish general 4,500, English medical 1,000, English general 1,000). The responses are greedy generations from gemma-4-E2B-it itself (self-distillation, at most 512 tokens), so the drafter learns the target's own distribution.
  • Prompts:
    • Turkish patient questions from the kayrab/patient-doctor-qa-tr-* datasets. Only the questions were used, with PII-like strings removed; the original doctor answers were not used.
    • Turkish and English medical and general questions synthesized by the E2B model.
    • A mix of all four categories prevented regressions. Training on Turkish medical data alone made English medical slightly worse.
  • Held-out sets:
    • The "held-out" test sets are hand-written prompts from a separate earlier set, never seen in training.
    • The other test sets are held-out questions from the same sources as training.
  • Objective: forward KL from the drafter to the target's full next-token distribution, unrolled over 3 draft steps with teacher forcing, plus a KL term on the cluster selector (the target's probabilities summed per cluster, weight 0.5).
  • Setup:
    • The target is frozen.
    • The drafter cross-attends to the target's shared KV cache, exactly as at inference.
    • AdamW, lr 5e-5, 2 epochs (1090 steps), cosine schedule, bf16 autocast, one A100-80GB.

Usage

import torch
from transformers import AutoProcessor, AutoModelForCausalLM

target_id, drafter_id = "google/gemma-4-E2B-it", "senpaicq/gemma-4-E2B-it-assistant-tr-medical"
processor = AutoProcessor.from_pretrained(target_id)
target = AutoModelForCausalLM.from_pretrained(target_id, dtype=torch.bfloat16, device_map="auto")
assistant = AutoModelForCausalLM.from_pretrained(drafter_id, dtype=torch.bfloat16, device_map="auto")
assistant.generation_config.num_assistant_tokens = 4
assistant.generation_config.num_assistant_tokens_schedule = "constant"

messages = [{"role": "user", "content": [{"type": "text", "text": "Tip 2 diyabet hastaları sabah kahvaltısında nelere dikkat etmeli?"}]}]
inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True,
                                       return_dict=True, return_tensors="pt").to(target.device)
out = target.generate(**inputs, assistant_model=assistant, max_new_tokens=512, do_sample=False)
print(processor.decode(out[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True))

Tested with transformers==5.21.1.

Limitations

  • The speedups above were measured only in HF transformers. Serving engines such as vLLM and SGLang have different overheads, so wall-clock gains there will differ. τ (acceptance length) transfers better than wall-clock speedup.
  • Only tested with Gemma 4 E2B. It will not work with other Gemma 4 sizes, because the drafter reads the target's hidden states and KV cache.
  • Tested with greedy decoding and batch size 1.
  • Gains for other Turkish domains (law, finance, …) are expected to fall between the Turkish general and Turkish medical numbers, but were not measured.
  • The outputs are Gemma 4 E2B's outputs. Do not use them as medical advice.

Files

  • model.safetensors, config.json, generation_config.json: the drafter. It is a drop-in replacement for google/gemma-4-E2B-it-assistant.
  • train_cfg.json: the training configuration.
  • eval_results.json: all evaluation numbers, including per-arm, per-seed and paired-bootstrap results.
  • notebooks/: data generation, training/ablation and robustness notebooks, with outputs stripped.

The training data is not released because it contains real patient questions.

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей