/ Модель

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

Контекст
2 048 токенов
Параметры
37 млн
Лицензия
Apache 2.0
Архитектура
gemma4-nano · dense
Библиотека
pytorch
Опубликована
16 апр 2026

gemma4-nano-tinystories

Генерация текстаТекст → текст

Компактная модель на архитектуре Gemma 4 для генерации коротких детских историй на английском языке.

102скачиваний за 30 дней2лайкавеса обновлены16 апр 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

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

Gemma 4 Nano — TinyStories — компактная языковая модель на 37,4 млн параметров, созданная разработчиком lakhera2023 с нуля на PyTorch по архитектурным принципам Gemma 4. Она обучена на наборе TinyStories и предназначена для генерации коротких детских историй на английском языке. В модели 20 слоёв: 17 со скользящим вниманием и 3 с полным вниманием; используются собственная архитектура и SentencePiece BPE-токенизатор с 8 тысячами токенов. Контекст составляет до 2048 токенов, а для лучших результатов README рекомендует запросы короче 500 токенов.

Модель подходит для экспериментов с генерацией простых сказок и изучения компактных языковых моделей. Она не настроена на выполнение инструкций или диалог, обучена только на детских историях и может плохо работать с другими темами, редкими словами и неанглийским текстом. Из-за нестандартной архитектуры её нельзя напрямую запускать через llama.cpp или Ollama и конвертировать в GGUF или ONNX. Лицензия — Apache-2.0.

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

  • генерация коротких детских сказок по затравке
  • продолжение простой истории на английском языке
  • создание сюжетов для детских рассказов
  • эксперименты с обучением и запуском компактных языковых моделей

Ограничения

Модель обучена только на детских историях и не предназначена для следования инструкциям или диалога; за пределами английских историй и на редких словах качество может быть низким. Для лучших результатов рекомендуются запросы короче 500 токенов при максимальном контексте 2048 токенов; нестандартная архитектура ограничивает совместимость с llama.cpp, Ollama, GGUF и ONNX.

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

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

Открыть на Hugging Face

Gemma 4 Nano — TinyStories (37M parameters)

A 37 million parameter language model built entirely from scratch using the Gemma 4 architecture, trained on the TinyStories dataset to generate children's stories.

This is not a fine-tuned model. Every layer — attention, feed-forward, normalization, positional encoding — was implemented from the ground up in PyTorch, following the Gemma 4 design principles.

Try the live demo

Gemma 4 Architectural Features

Despite being ~8,000x smaller than the full Gemma 4 (31B), this model implements 9 core architectural innovations:

FeatureDescription
Dual Head Dimensionshead_dim=48 for sliding attention, global_head_dim=96 for full attention
Proportional RoPEtheta=10,000 for sliding layers, theta=1,000,000 with partial_rotary_factor=0.25 for global layers
Shared KV CacheLast 6 layers reuse key/value states from earlier donor layers
K=V AttentionGlobal attention layers share key and value projections
Value NormalizationRMSNorm (without learned scale) applied to value states
Logit Softcappingtanh-based capping at 30.0 to prevent extreme logit values
Embedding Weight TyingInput embedding and output head share the same weight matrix
QK NormalizationRMSNorm on queries and keys; attention scaling = 1.0
Zero-centered RMSNormWeights initialized to 0, applied as (1 + weight) * normalized

Model Details

ParameterValue
Total parameters37.4M
Embedding dimension384
Layers20 (17 sliding + 3 full attention)
Attention heads8
KV heads (sliding)2 (GQA group size = 4)
KV heads (global)1 (GQA group size = 8)
Feed-forward dim1,152 (GeGLU)
Sliding window512 tokens
Context length2,048 tokens
Vocabulary8,000 (custom SentencePiece BPE)

Layer Pattern

3 groups of (5 sliding + 1 full) + 2 extra sliding = 20 layers:

S S S S S F | S S S S S F | S S S S S F | S S

Usage

Quick Start

import torch
import torch.nn as nn
import torch.nn.functional as F
import sentencepiece as spm
from huggingface_hub import hf_hub_download

# Download files
repo = "lakhera2023/gemma4-nano-tinystories"
ckpt_path = hf_hub_download(repo_id=repo, filename="pytorch_model.bin")
tok_path = hf_hub_download(repo_id=repo, filename="tinystories_tokenizer.model")

# Load tokenizer
sp = spm.SentencePieceProcessor()
sp.load(tok_path)

# Load model (requires the model class definitions — see inference.py in this repo)
model = Gemma4Model(CONFIG)
state = torch.load(ckpt_path, map_location="cpu", weights_only=True)
cleaned = {k.replace("_orig_mod.", ""): v.float() for k, v in state.items()}
model.load_state_dict(cleaned, strict=False)
model.eval()

# Generate
prompt = "Once upon a time there was a little rabbit"
ids = torch.tensor([sp.encode(prompt)], dtype=torch.long)
output = model.generate(ids, max_new_tokens=200, temperature=0.8, top_k=50)
print(sp.decode(output[0].tolist()))

Standalone Inference

Download and run inference.py from this repo:

pip install torch sentencepiece huggingface_hub
python inference.py --prompt "Once upon a time" --max_tokens 200 --temperature 0.8

Training Details

SettingValue
HardwareNVIDIA A100 40GB
Datasetroneneldan/TinyStories
TokenizerCustom SentencePiece BPE (8,000 vocab, trained on TinyStories)
Precisionbfloat16 with torch.compile
OptimizerAdamW (lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
SchedulerLinear warmup (500 steps) + cosine decay to 1e-5
Batch size32 (effective 64 with gradient accumulation = 2)
Sequence length1,024 tokens
Total steps50,000
Effective tokens/step65,536

Tokenizer

A custom 8,000-vocabulary SentencePiece BPE tokenizer trained specifically on TinyStories. Using a domain-specific tokenizer instead of GPT-2's 50,257-token vocabulary saved ~16M embedding parameters — critical for keeping the model under 40M total.

Files:

  • tinystories_tokenizer.model — SentencePiece model file (load with spm.SentencePieceProcessor)
  • tinystories_tokenizer.vocab — Human-readable vocabulary

Limitations

  • Domain-specific: Trained only on children's stories. Will not perform well on other text domains.
  • Small vocabulary: The 8K tokenizer is optimized for TinyStories English text. It may struggle with uncommon words, names, or non-English text.
  • No instruction following: This is a base language model, not fine-tuned for instructions or chat.
  • Short context: Best results with prompts under ~500 tokens; maximum context is 2,048 tokens.
  • Custom architecture: This model uses non-standard tensor names and architecture details. It cannot be converted to GGUF/ONNX or run with llama.cpp/Ollama directly.

Files

FileSizeDescription
pytorch_model.bin74.9 MBModel weights (PyTorch state_dict, bfloat16)
tinystories_tokenizer.model371 KBSentencePiece tokenizer model
tinystories_tokenizer.vocab110 KBHuman-readable vocabulary
config.json~2 KBFull model configuration
inference.py~8 KBStandalone inference script

Citation

If you use this model, please cite the original Gemma 4 paper and the TinyStories dataset:

@article{tinystories2023,
  title={TinyStories: How Small Can Language Models Be and Still Speak Coherent English?},
  author={Eldan, Ronen and Li, Yuanzhi},
  journal={arXiv preprint arXiv:2305.07759},
  year={2023}
}

License

Apache 2.0

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

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

GPU в ailist

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

Нельзя запустить

Архитектура gemma4-nano неизвестна transformers в образе рантайма.

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

0 моделей