whiff_mamba2-50M-v0.1
💾 GGUF versions available in this same repository (limloop/whiff-mamba2-50M-v0.1):
bf16.gguf(brainscale float16) ·q8_0.gguf(quantized 8-bit)
🇷🇺 Нажмите, чтобы развернуть описание на русском
🧠 Что это такое
Это маленькая языковая модель на архитектуре Mamba-2. Всего 50 миллионов параметров. Обучалась несколько месяцев на 8-ядерном CPU, потому что GPU у меня нет, а Mamba жрёт меньше памяти и ресурсов, чем трансформеры.
Коротко: умеет писать грамматически правильные тексты на русском и английском, вести диалоги, выдавать образные описания. Не умеет отвечать на вопросы, держать связность дольше 100 токенов и не впадать в повторы, если ей скучно.
Длинно: читайте дальше.
📐 Архитектура
Конфиг — Mamba2Config. Цифры подбирались экспериментально, чтобы влезть в 50M и не умереть от OOM на CPU.
| Параметр | Значение | Почему так |
|---|---|---|
| vocab_size | 32064 | от Phi-3.5-mini, не пришлось учить свой токенизатор |
| hidden_size | 512 | маленькие модели — маленькие размерности |
| num_hidden_layers | 20 | глубокая, но узкая |
| state_size | 48 | меньше стандартного (128) |
| num_heads | 8 | для внутреннего внимания в Mamba2 |
| head_dim | 64 | 512/8 = 64 |
| conv_kernel | 4 | большое ядро для локальных паттернов, тут решил не экономить |
| expand | 1 | нет внутреннего расширения → d_inner = 512 |
| use_conv_bias | True | без него GGUF не конвертировался |
| tie_word_embeddings | False | с ним safetensors ругался |
Главное: вся память модели о контексте — это 20 слоёв × 48 состояний = 960 чисел. Запоминать на 512 токенов это объективно мало, поэтому после 100 токенов модель начинает "забывать", о чём писала.
📚 На чём обучена
Всего: 454К примеров, ~230M токенов. Русский + английский, билингва.
Источники (по убыванию объёма):
wikimedia/wikipedia— энциклопедия, чистый языкslon-hk/BooksSummarizationsRU— пересказы книгcommon-pile/pre_1929_books— старые английские книги (до истечения копирайта)Fascinat0r/taiga_corpus_subtitles— субтитры, диалоговая речьIlyaGusev/ficbook— фанфики, образность и стилиlimloop/fantasy_body_interactions— просто такlimloop/ru_en_story_pairs— параллельные тексты, помогает не путать языки
🏋️ Процесс обучения
Одна эпоха, прогрессивное увеличение контекста. Я не мог начать сразу с 512 токенов — модель бы не сошлась, да и я решил сэкономить время обучения. Поэтому 8 этапов, каждый увеличивал либо контекст, либо батч.
| Этап | Контекст | Batch size | Что поменялось |
|---|---|---|---|
| 1 | 64 | 64 | старт, есть 40+% Wikipedia и нет story_pairs |
| 2 | 128 | 64 | удвоил контекст |
| 3 | 256 | 64 | ещё удвоил |
| 4 | 256 | 96 | убрал Wikipedia, добавил story_pairs |
| 5 | 512 | 96 | наконец-то полный контекст |
| 6 | 512 | 256 | больше батч — стабильнее градиент |
| 7 | 512 | 360 | еще больше |
| 8 | 512 | 512 | максимальный батч |
Железо: Ryzen 7 5700G CPU, DDR4 32GB.
Время: В целом часов 200-300 (8-10 дней) чистого времени обучения.
📊 Результаты
Цифры:
- Train loss: 2.97
- Eval loss: 3.03
- Perplexity: exp(3.03) ≈ 20.7
Качество (температура 0.4, оптимальная):
- Грамматика на русском почти всегда правильная
- На английском — правильная, но иногда неидиоматичная ("you're not a doctor" вместо "you're not a doctor, are you?")
- Диалоги естественные, реплики осмысленные
- Образность есть (солнце садится, дождь стучит по крыше)
- Связность держится ~50-100 токенов, дальше начинает плавать
Что не умеет (честно):
- Отвечать на фактологические вопросы ("столица Франции" → "the United States")
- Считать (цифры превращаются в бесконечные последовательности)
- Следовать инструкциям (это base LM, не instruct)
- Помнить, что было 150 токенов назад
🔥 Примеры генерации
Все примеры — temperature 0.4, 512 новых токенов. Никакой ручной фильтрации, что сгенерировала модель, то и выложил.
🇬🇧 English examples (click)
Prompt: The sun was setting
The sun was setting 125, and the sun was setting down the sky. Suddenly a familiar silhouette appeared on the threshold - a girl with bright pink hair tied in a white dress. "Hi," he muttered under his breath. "I'm Denis," he said quietly. "You were just sitting here for three years. I've been waiting for you." "No, no, no," Denis shrugged. "And now we're both alone." "I'm not a detective," Denis replied calmly. "It's just... it's like that." "Don't be afraid," Denis whispered, stepping closer. "What are you doing here?" "Oh, just a little girl," Denis chuckled. "But I don't know what to do next." "That's exactly what I found out of my life!" Denis asked. "I'm not your mother." "No, this is impossible," Denis admitted. "It's all right. But I'm always free. And you know how much I've seen him before? Maybe we should have come back then?" "You won't believe what happened to me. You'll never get you out of here." "Maybe I could feel the cold water?" Denis shuddered. "You're in danger. I'm just... I'm not sure. And I'm afraid. I'm not going to work. And I think I'd never forgive. It's just... you're still trying to understand why I'm in love. You're not alone. What would you want to talk about? Why did you come from? And I'm not a doctor. He's not so much. But if I'm not saying anything. But I can't live without being afraid. Maybe I'm just afraid to make yourself alive. Or maybe I'm not afraid. But I'm not ready. I'm not afraid. Afraid that I'm not afraid. That's why I'm not a child. And I'm just afraid of losing you. I'm not a good guy. And I'm not so glad I'm not afraid. Just don't hurt you. I'm not really good. And you're not a
Prompt: What is the capital of
What is the capital of the United States? It was not to be done, but it was a matter that he had to do with this subject. He was a very great man, and he was a man of his own son, who had been in a large part of his country, and he would have been able to come back to the British Government, which was as well as his father's estate. His father was a little boy, and he was a man of about lasting age. He was at the time of the Jewish years, and was one of the most offered manhood, and now that he had been made a good deal of him. He was not an accountant; he was a man of their mother; and he was the best friend of Mrs. D. W. L. C. D. S. M. M. D. M. D. B. N. C. G. R. W. Duff. 2d. He was married in 1843, and had a wife of a young woman, and was married to Dr. J. M. S. Sawyer. She was a very young fellow, and her husband had died in the child's life. Her daughter was a father, and then she was married to Mrs. H. W. H. P. F. A. D. D. D. D. D. D. E. A. D. D. D. D. S. T. T. K. C. D. D. D. D. D. D. D. B. D. D. D. D. M. D. D. D. D. D. M. D. A. C. B. B. M. A. A. D. D. D. D. D. A. A. A. A. A. D. D. D. A. A. A. A. A. A. D. A. D. D. A. A. D. D. D. D. D. A. A. A. A. D. D. A. A. A. A. A. D. A. A. A. A. A. A. D. D.
(Да, модель не умеет отвечать на вопросы. Я предупреждал.)
🇷🇺 Русские примеры (нажми)
Prompt: За поворотом тропинки стоял
За поворотом тропинки стоял у входа в кафе, сжимая в руках потрепанный шарф и закат. Внезапно кто-то из них открылся, и в комнату вошла молодая женщина в черном плаще. — Что это? — прошептала она, не отрываясь от ощущения. — Да, я... Я не знаю, что ты сказал, но мысли не приходили. Но ведь это было уже не то, что теперь надо мной. Они молча сидели, не зная, как говорить, а не друг. Он был прав, только что просто так. — Ты же знаешь, что самое страшное? — спросил он, стараясь, чтобы голос звучал странно. — А ты думаешь, что я должен делать? — спросил он, стараясь, чтобы голос звучал странным. — Нет, — ответил мужчина, чувствуя себя полностью. — Потому что ты всегда будешь готов. — Именно поэтому я сейчас буду рядом. Сейчас же ты меня видел, что это невозможно. — Неужели ты не видишь? — спросил он, подходя ближе. — Знаешь, что я могу быть вместе, — продолжал он, не отрывая взгляда от экрана. — Просто... нужно сделать вид, что всё ещё закончится. — Как вы собираетесь сходить? — спросил он, стараясь, чтобы голос не дрожал. — Да, — ответила девушка, — я не знаю, где ты. Я люблю тебя, давайте поговорим. — Да, — ответил он, глядя на него. — Я не хочу, чтобы ты никогда не понимал, какой именно его. — Может, это была твоя помощь. О том, что ты помнишь, как ты узнал, что
Prompt: Почему небо
Почему небо стояла в кабинете, когда она пошла на кухню. Она была очень тяжелая, но забывала про нее снова. Но ей было не так хорошо. Она уже знала, что это был немного грустный и глупый. Иногда она могла увидеть его. — Ну, конечно же, — тихо сказал он. — Давай, — ответил он, — я не хочу спать, а теперь мы будем вместе. — Как ты? – спросил он. — Что ты делаешь? — Не знаю, — ответила девушка. — Я люблю тебя, — усмехнулся он. — А где же твои родители? — Ага, — вздохнула она. — Смотри, как всегда, — отвечал он, — я вас с тобой не допущу. — Идите, — сказал он, — но... — осторожно прошептал он. — У меня есть возможность быть правдой. — Тогда я могу поговорить с ней, — ответил парень, — а ты не знаешь, что я тебе не нужен. — Вставай, — заявил он, — давайте поговорим, — сказал он, — я бы не знаю, что ты мне не нравишься, но я не буду говорить. — Конечно, — сказал он, — но я не собираюсь никогда не рассказывать об этом. Он сказал, что сейчас, когда я сказал, что он живет рядом, а не потому, что я не слышал. — Если вы не смогли бы придумать, то я не знаю, — сказал он, — я не могу этого не думать, — признаться он. — Или я не могу, — сказал он, — я не скажу тебе. Это не справедливое лицо. Я понимаю, что ответить. И вот, когда я понял,
⚠️ Патологические случаи (что идёт не так)
Зацикливание на английском:
The population is approximately 15,000 people. The city was furnished by the country... 00.00.00 00.00 00.00 00.00.00 00.00 00.00 00.00
Зацикливание на русском:
Для начала нужно: 17 лет, 20 минут, 30 Секунды, 50 Мирата, 40 Как и захочет сделать это...
Это происходит, когда модель попадает в "аттрактор" — комбинацию состояний SSM, из которой трудно выйти. Лечится повышением температуры или регенерацией с другим seed.
🚀 Как использовать
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("limloop/whiff-mamba2-50M-v0.1")
tokenizer = AutoTokenizer.from_pretrained("limloop/whiff-mamba2-50M-v0.1")
# Важно: температура 0.4 — сладкая точка
prompt = "Однажды в лесу"
inputs = tokenizer.encode(prompt, return_tensors="pt")
outputs = model.generate(
**inputs,
max_new_tokens=512,
temperature=0.4,
do_sample=True,
top_p=0.95
)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
Советы по генерации:
- Температура 0.3-0.5 — оптимальный диапазон
- Ниже 0.3 — повторы усиливаются
- Выше 0.7 — начинается бред
📉 Ограничения
- Не instruct. Модель не понимает команд "напиши письмо" или "переведи текст". Она только продолжает.
- Не фактологическая. На вопрос "кто такой Пушкин" скорее начнёт писать художественный текст про человека в цилиндре.
- Короткая память. После 100 токенов детали начинают теряться. После 200 — может забыть имена персонажей.
- Повторы. Иногда зацикливается на слове или цифре. Лечится регенерацией.
- Английский корявый. Модель билингва, но английский выучен хуже. Фразы грамматически правильные, но неестественные.
- Не считает. Цифры для неё — просто токены, без математического смысла.
🎯 Для кого эта модель
- Исследователи SSM — посмотреть, как Mamba2 ведёт себя в минималистичной конфигурации
- Люди без GPU — модель работает на CPU
- Энтузиасты билингвальных моделей — русский и английский в одном флаконе
- Те, кто хочет дообучить LoRA — 50M легко дообучается даже на Google Colab
🧠 What is this
This is a small language model based on the Mamba-2 architecture. Only 50 million parameters. It was trained for several months on an 8-core CPU, because I don't have a GPU, and Mamba consumes less memory and resources than transformers.
In short: It can write grammatically correct texts in Russian and English, hold dialogues, and produce figurative descriptions. It cannot answer questions, maintain coherence beyond 100 tokens, or avoid repetition when it gets bored.
In long: Read on.
📐 Architecture
The config is Mamba2Config. The numbers were chosen experimentally to fit into 50M and not die from OOM on the CPU.
| Parameter | Value | Why |
|---|---|---|
| vocab_size | 32064 | from Phi-3.5-mini, didn't have to train my own tokenizer |
| hidden_size | 512 | small models — small dimensions |
| num_hidden_layers | 20 | deep but narrow |
| state_size | 48 | smaller than standard (128) |
| num_heads | 8 | for internal attention in Mamba2 |
| head_dim | 64 | 512/8 = 64 |
| conv_kernel | 4 | large kernel for local patterns, decided not to skimp here |
| expand | 1 | no internal expansion → d_inner = 512 |
| use_conv_bias | True | without it, GGUF wouldn't convert |
| tie_word_embeddings | False | safetensors complained with it on |
The main thing: the model's entire memory of the context is 20 layers × 48 states = 960 numbers. Remembering over 512 tokens is objectively too little, so after 100 tokens the model starts to "forget" what it was writing about.
📚 What it was trained on
Total: 454K examples, ~230M tokens. Russian + English, bilingual.
Sources (by decreasing volume):
wikimedia/wikipedia— encyclopedia, clean languageslon-hk/BooksSummarizationsRU— book summariescommon-pile/pre_1929_books— old English books (pre-copyright expiration)Fascinat0r/taiga_corpus_subtitles— subtitles, dialogue speechIlyaGusev/ficbook— fan fiction, imagery and styleslimloop/fantasy_body_interactions— just becauselimloop/ru_en_story_pairs— parallel texts, helps avoid language confusion
🏋️ Training process
One epoch, progressive context increase. I couldn't start with 512 tokens right away — the model wouldn't converge, and I also wanted to save training time. So 8 stages, each increasing either the context or the batch size.
| Stage | Context | Batch size | What changed |
|---|---|---|---|
| 1 | 64 | 64 | start, 40+% Wikipedia and no story_pairs |
| 2 | 128 | 64 | doubled context |
| 3 | 256 | 64 | doubled again |
| 4 | 256 | 96 | removed Wikipedia, added story_pairs |
| 5 | 512 | 96 | finally full context |
| 6 | 512 | 256 | larger batch — more stable gradient |
| 7 | 512 | 360 | even larger |
| 8 | 512 | 512 | maximum batch |
Hardware: Ryzen 7 5700G CPU, DDR4 32GB.
Time: About 200-300 hours (8-10 days) of pure training time.
📊 Results
Numbers:
- Train loss: 2.97
- Eval loss: 3.03
- Perplexity: exp(3.03) ≈ 20.7
Quality (temperature 0.4, optimal):
- Grammar in Russian is almost always correct
- In English — correct, but sometimes non-idiomatic ("you're not a doctor" instead of "you're not a doctor, are you?")
- Dialogues are natural, responses are meaningful
- Figurative language exists (sun sets, rain taps on the roof)
- Coherence holds for ~50-100 tokens, then starts to drift
What it cannot do (honestly):
- Answer factual questions ("capital of France" → "the United States")
- Count (numbers turn into endless sequences)
- Follow instructions (this is a base LM, not instruct)
- Remember what happened 150 tokens ago
🔥 Generation examples
All examples — temperature 0.4, 512 new tokens. No manual filtering, what the model generated is what was posted.
🇬🇧 English examples (click)
Prompt: The sun was setting
The sun was setting 125, and the sun was setting down the sky. Suddenly a familiar silhouette appeared on the threshold - a girl with bright pink hair tied in a white dress. "Hi," he muttered under his breath. "I'm Denis," he said quietly. "You were just sitting here for three years. I've been waiting for you." "No, no, no," Denis shrugged. "And now we're both alone." "I'm not a detective," Denis replied calmly. "It's just... it's like that." "Don't be afraid," Denis whispered, stepping closer. "What are you doing here?" "Oh, just a little girl," Denis chuckled. "But I don't know what to do next." "That's exactly what I found out of my life!" Denis asked. "I'm not your mother." "No, this is impossible," Denis admitted. "It's all right. But I'm always free. And you know how much I've seen him before? Maybe we should have come back then?" "You won't believe what happened to me. You'll never get you out of here." "Maybe I could feel the cold water?" Denis shuddered. "You're in danger. I'm just... I'm not sure. And I'm afraid. I'm not going to work. And I think I'd never forgive. It's just... you're still trying to understand why I'm in love. You're not alone. What would you want to talk about? Why did you come from? And I'm not a doctor. He's not so much. But if I'm not saying anything. But I can't live without being afraid. Maybe I'm just afraid to make yourself alive. Or maybe I'm not afraid. But I'm not ready. I'm not afraid. Afraid that I'm not afraid. That's why I'm not a child. And I'm just afraid of losing you. I'm not a good guy. And I'm not so glad I'm not afraid. Just don't hurt you. I'm not really good. And you're not a
Prompt: What is the capital of
What is the capital of the United States? It was not to be done, but it was a matter that he had to do with this subject. He was a very great man, and he was a man of his own son, who had been in a large part of his country, and he would have been able to come back to the British Government, which was as well as his father's estate. His father was a little boy, and he was a man of about lasting age. He was at the time of the Jewish years, and was one of the most offered manhood, and now that he had been made a good deal of him. He was not an accountant; he was a man of their mother; and he was the best friend of Mrs. D. W. L. C. D. S. M. M. D. M. D. B. N. C. G. R. W. Duff. 2d. He was married in 1843, and had a wife of a young woman, and was married to Dr. J. M. S. Sawyer. She was a very young fellow, and her husband had died in the child's life. Her daughter was a father, and then she was married to Mrs. H. W. H. P. F. A. D. D. D. D. D. D. E. A. D. D. D. D. S. T. T. K. C. D. D. D. D. D. D. D. B. D. D. D. D. M. D. D. D. D. D. M. D. A. C. B. B. M. A. A. D. D. D. D. D. A. A. A. A. A. D. D. D. A. A. A. A. A. A. D. A. D. D. A. A. D. D. D. D. D. A. A. A. A. D. D. A. A. A. A. A. D. A. A. A. A. A. A. D. D.
(Yes, the model cannot answer questions. I warned you.)
🇷🇺 Russian examples (click)
Prompt: За поворотом тропинки стоял
За поворотом тропинки стоял у входа в кафе, сжимая в руках потрепанный шарф и закат. Внезапно кто-то из них открылся, и в комнату вошла молодая женщина в черном плаще. — Что это? — прошептала она, не отрываясь от ощущения. — Да, я... Я не знаю, что ты сказал, но мысли не приходили. Но ведь это было уже не то, что теперь надо мной. Они молча сидели, не зная, как говорить, а не друг. Он был прав, только что просто так. — Ты же знаешь, что самое страшное? — спросил он, стараясь, чтобы голос звучал странно. — А ты думаешь, что я должен делать? — спросил он, стараясь, чтобы голос звучал странным. — Нет, — ответил мужчина, чувствуя себя полностью. — Потому что ты всегда будешь готов. — Именно поэтому я сейчас буду рядом. Сейчас же ты меня видел, что это невозможно. — Неужели ты не видишь? — спросил он, подходя ближе. — Знаешь, что я могу быть вместе, — продолжал он, не отрывая взгляда от экрана. — Просто... нужно сделать вид, что всё ещё закончится. — Как вы собираетесь сходить? — спросил он, стараясь, чтобы голос не дрожал. — Да, — ответила девушка, — я не знаю, где ты. Я люблю тебя, давайте поговорим. — Да, — ответил он, глядя на него. — Я не хочу, чтобы ты никогда не понимал, какой именно его. — Может, это была твоя помощь. О том, что ты помнишь, как ты узнал, что
Prompt: Почему небо
Почему небо стояла в кабинете, когда она пошла на кухню. Она была очень тяжелая, но забывала про нее снова. Но ей было не так хорошо. Она уже знала, что это был немного грустный и глупый. Иногда она могла увидеть его. — Ну, конечно же, — тихо сказал он. — Давай, — ответил он, — я не хочу спать, а теперь мы будем вместе. — Как ты? – спросил он. — Что ты делаешь? — Не знаю, — ответила девушка. — Я люблю тебя, — усмехнулся он. — А где же твои родители? — Ага, — вздохнула она. — Смотри, как всегда, — отвечал он, — я вас с тобой не допущу. — Идите, — сказал он, — но... — осторожно прошептал он. — У меня есть возможность быть правдой. — Тогда я могу поговорить с ней, — ответил парень, — а ты не знаешь, что я тебе не нужен. — Вставай, — заявил он, — давайте поговорим, — сказал он, — я бы не знаю, что ты мне не нравишься, но я не буду говорить. — Конечно, — сказал он, — но я не собираюсь никогда не рассказывать об этом. Он сказал, что сейчас, когда я сказал, что он живет рядом, а не потому, что я не слышал. — Если вы не смогли бы придумать, то я не знаю, — сказал он, — я не могу этого не думать, — признаться он. — Или я не могу, — сказал он, — я не скажу тебе. Это не справедливое лицо. Я понимаю, что ответить. И вот, когда я понял,
⚠️ Pathological cases (what goes wrong)
Looping in English:
The population is approximately 15,000 people. The city was furnished by the country... 00.00.00 00.00 00.00 00.00.00 00.00 00.00 00.00
Looping in Russian:
Для начала нужно: 17 лет, 20 минут, 30 Секунды, 50 Мирата, 40 Как и захочет сделать это...
This happens when the model falls into an "attractor" — a combination of SSM states from which it is difficult to escape. It can be fixed by raising the temperature or regenerating with a different seed.
🚀 How to use
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("limloop/whiff-mamba2-50M-v0.1")
tokenizer = AutoTokenizer.from_pretrained("limloop/whiff-mamba2-50M-v0.1")
# Important: temperature 0.4 is the sweet spot
prompt = "Once upon a time in the forest"
inputs = tokenizer.encode(prompt, return_tensors="pt")
outputs = model.generate(
**inputs,
max_new_tokens=512,
temperature=0.4,
do_sample=True,
top_p=0.95
)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
Generation tips:
- Temperature 0.3-0.5 is the optimal range
- Below 0.3 — repetitions increase
- Above 0.7 — hallucinations begin
📉 Limitations
- Not instruct. The model does not understand commands like "write a letter" or "translate text". It only continues.
- Not factual. To the question "who is Pushkin" it will likely start writing a fictional text about a man in a top hat.
- Short memory. After 100 tokens, details start to get lost. After 200 — it may forget character names.
- Repetitions. Sometimes it loops on a word or digit. Fix by regenerating.
- Clumsy English. The model is bilingual, but English is learned worse. Phrases are grammatically correct but unnatural.
- Cannot count. Numbers are just tokens to it, without mathematical meaning.
🎯 Who this model is for
- SSM researchers — to see how Mamba2 behaves in a minimalist configuration
- People without a GPU — the model runs on CPU
- Enthusiasts of bilingual models — Russian and English in one package
- Those who want to fine-tune LoRA — 50M is easy to fine-tune even on Google Colab
- Downloads last month
- 344