/ Модель

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

Контекст
512 токенов
Параметры
75 млн
Лицензия
Apache 2.0
Архитектура
llama · dense
Библиотека
transformers
Опубликована
15 ноя 2026

tinystories-llama-75m-from-scratch

Генерация текстаТекст → текст
107скачиваний за 30 дней0лайковвеса обновлены15 ноя 2026

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

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

Небольшая англоязычная Llama-модель, обученная с нуля для генерации коротких детских историй и экспериментов с языковым моделированием.

Модель TinyStories Llama-75M разработана Jawaher и Leen как учебный эксперимент по масштабным закономерностям языковых моделей. Это причинная языковая модель с 75 млн параметров, обученная с нуля на датасете TinyStories; она не является дообучением предварительно обученной модели. Архитектура — декодерный Transformer семейства Llama с 24 слоями, Grouped-Query Attention, RoPE, RMSNorm и SwiGLU. Метаданные указывают контекст 512 токенов, а README описывает обучение на последовательностях длиной 256 токенов.

Модель предназначена прежде всего для генерации коротких англоязычных детских историй и учебных экспериментов с языковым моделированием. В улучшенном запуске она обучалась 5 000 шагов на 20,48 млн входных токенов; README сообщает тестовую perplexity 8,4594. Модель небольшая, не настроена на выполнение инструкций и не подходит как универсальный помощник. Известны повторы, слабая связность длинных сюжетов, грамматические ошибки, ограниченные общие знания и возможные выдуманные утверждения; качество за пределами детских историй ограничено. Лицензия модели — Apache-2.0.

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

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

Ограничения

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Открыть на Hugging Face

TinyStories Llama-75M — Trained From Scratch

Developed by: Jawaher & Leen

Project: Scaling Laws and Training a 75M-Parameter Language Model

Model Repository: jawaher-leen-ai/tinystories-llama-75m-from-scratch

1. Project Overview

This project implements and trains a 75-million-parameter Llama-style causal language model from scratch using the TinyStories dataset.

The objective is to explore the relationship between model size, training tokens, computational budget, and language modeling performance through scaling-law calculations and practical experimentation.

The model uses a decoder-only Transformer architecture with Grouped-Query Attention (GQA), Rotary Position Embeddings (RoPE), RMSNorm, and SwiGLU.

The initial experiment used 30,000 stories and 300 training steps. An improved experiment increased the dataset to 120,000 stories and extended training to 5,000 optimizer steps while preserving the same model architecture.

The improved model achieved:

  • 74,998,272 trainable parameters
  • 5,000 training steps
  • 20.48 million processed training tokens
  • Full Validation Loss: 2.1244
  • Full Validation Perplexity: 8.3682
  • Full Test Loss: 2.1353
  • Full Test Perplexity: 8.4594

The model was initialized with random weights and trained from scratch. It was not fine-tuned from a pretrained language model.


2. Model Architecture

ComponentConfiguration
ArchitectureLlama-style Causal Language Model
Model TypeDecoder-only Transformer
Trainable Parameters74,998,272
Decoder Layers24
Hidden Size512
Intermediate Size1408
Attention Heads8
Key/Value Heads4
Attention TypeGrouped-Query Attention (GQA)
ActivationSwiGLU
Positional EmbeddingsRoPE
NormalizationRMSNorm
Vocabulary Size8192
Training Context Length256
Maximum Position Embeddings512
Weight TyingEnabled

Architecture Rationale

The architecture was designed to approximately match a 75M-parameter target derived from the assignment's scaling-law calculations.

Grouped-Query Attention (GQA) was selected to reduce key/value parameters and KV-cache requirements compared with standard Multi-Head Attention (MHA).

The attention configurations were compared:

Attention TypeKV HeadsParameters
Multi-Query Attention (MQA)170,279,680
Grouped-Query Attention (GQA)474,998,272
Multi-Head Attention (MHA)881,289,728

GQA provides a balance between model capacity and computational efficiency.

The model retains 24 decoder layers, a hidden size of 512, and a training context length of 256 tokens.


3. Dataset and Preprocessing

Dataset: TinyStories

Language: English

Dataset License: CDLA-Sharing-1.0, as declared by the dataset provider.

TinyStories contains short synthetic children's stories designed for language modeling experiments.

Dataset Preparation

A total of 120,000 stories were sampled from the published training split.

The preprocessing pipeline included:

  1. Whitespace normalization.
  2. SHA-256 exact duplicate removal.
  3. Splitting complete stories into training, validation, and test sets.
  4. Training a byte-level BPE tokenizer using training stories only.
  5. Appending EOS tokens between stories.
  6. Packing tokens into non-overlapping sequences of 256 tokens.
  7. Discarding incomplete final token blocks.

Dataset Split

SplitStoriesPercentage
Training108,00090%
Validation6,0005%
Test6,0005%
Total120,000100%

Random Seed: 42

Tokenized Training Data

  • Packed training blocks: 89,770
  • Packed training tokens: 22,981,120
  • Vocabulary size: 8,192
  • Context length: 256 tokens

Validation and test data were kept separate from gradient-based training.


4. Scaling Laws and Compute Budget

This project applies a simplified scaling-law planning approximation:

Compute approximation:

C ≈ 6ND

Where:

  • C = training compute in FLOPs
  • N = number of model parameters
  • D = number of training tokens

Using the planning assumption:

D = 20N

The assignment specifies a compute budget of:

C = 6.75 × 10^17 FLOPs

Therefore:

N = sqrt(C / 120)

N = 75,000,000 parameters

D = 20 × 75,000,000

D = 1,500,000,000 tokens

Theoretical Targets

MetricValue
Compute Budget6.75e17 FLOPs
Target Parameters75,000,000
Target Training Tokens1,500,000,000
Actual Model Parameters74,998,272
Updated Token Target1,499,965,440

These values represent theoretical planning targets, not the actual training budget used in the experiment.

Actual Improved Training Run

MetricValue
Training Steps5,000
Input Tokens per Step4,096
Total Input Tokens20,480,000
Scored Next-Token Targets20,400,000
Approximate Training Compute9.216e15 FLOPs
Coverage of Theoretical Token Target1.3654%

The improved experiment increased training compute while keeping the model architecture and parameter count fixed.

This demonstrates the effect of increasing the training budget, although a single pair of experiments is insufficient to establish a general scaling law.


5. Training Configuration

The model was trained using PyTorch and Hugging Face Transformers on Google Colab.

Hardware

  • GPU: NVIDIA Tesla T4
  • Framework: PyTorch
  • Model Library: Hugging Face Transformers 4.46.3

Hyperparameters

HyperparameterValue
OptimizerAdamW
Beta 10.9
Beta 20.95
Weight Decay0.1
Learning Rate3e-4
Learning Rate SchedulerCosine Decay
Warmup Steps100
Microbatch Size4
Gradient Accumulation Steps4
Effective Batch Size16
Context Length256
Maximum Training Steps5,000
Evaluation Interval250 steps
Evaluation Batches20

Training Statistics

MetricResult
Successful Optimizer Steps5,000
Processed Input Tokens20,480,000
Scored Training Targets20,400,000
Training Duration118.21 minutes
Training SpeedApproximately 3,092 tokens/s
Peak Allocated GPU Memory1.48 GiB

Training duration includes periodic evaluation and checkpoint saving within the training loop.


6. Model Evaluation

The model was evaluated using next-token cross-entropy loss and perplexity.

Perplexity is calculated as:

Perplexity = exp(Cross-Entropy Loss)

Lower loss and perplexity indicate better next-token prediction performance on the evaluated data.

Final Evaluation Results

Evaluation SplitLossPerplexity
Full Validation2.12448.3682
Full Test2.13538.4594

The final evaluation used complete held-out validation and test splits.

Training Progress

The fixed validation subset was evaluated every 250 optimizer steps.

Training StepValidation LossPerplexity
2503.878148.33
5003.239725.53
7502.969419.48
1,0002.791816.31
1,5002.559412.93
2,0002.425011.30
2,5002.302510.00
3,0002.22379.24
5,0002.08658.06

The fixed-subset evaluation differs from the final evaluation performed over the complete validation split.

Training and Validation Loss

Training and validation loss

The training and validation losses decreased substantially throughout the experiment.

The improvement became more gradual during later training steps, with no clear evidence of severe overfitting in the observed validation curve.


7. Baseline vs. Improved Model

Two experiments were conducted using the same 75M-parameter architecture.

Experimental Configurations

SettingBaselineImproved V2
Dataset Size30,000 stories120,000 stories
Training Steps3005,000
Training Tokens1.23M20.48M
Model Parameters74.998M74.998M
Context Length256256
AttentionGQAGQA
Learning Rate3e-43e-4

Observed Results

MetricBaselineImproved V2
Full Validation Loss4.33172.1244
Full Validation Perplexity76.078.37
Full Test Loss4.33832.1353
Full Test Perplexity76.578.46

The improved experiment produced substantially lower evaluation losses and perplexities.

Important comparison limitation: The dataset size, data splits, and tokenizer training corpus changed between experiments. Therefore, the numerical differences are descriptive and should not be interpreted as a controlled, directly comparable perplexity improvement.

A strictly controlled comparison would require using the same tokenizer and identical held-out evaluation data.

Key Observation

Increasing the amount of training data and the number of optimizer steps was associated with substantially better language modeling performance without modifying the model's architecture.


8. Text Generation Examples

Prompt

Once upon a time, a little robot found a book.

Before Training

Once upon a time, a little robot found a book.."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."."ardenardenardenardenardenardenardenardenardenardenardenardenardenarden

After Training

Once upon a time, a little robot found a book. The robot was very happy and said, "Thank you, little robot! You are so kind!" The robot and the robot became good friends. They played together every day. The robot was very happy and never wanted to leave. The robot and the robot became best friends. They would play together every

Observations

Before training, the randomly initialized model produced repetitive and largely meaningless sequences.

After training, the model demonstrated:

  • More grammatically coherent sentences.
  • Improved next-token prediction.
  • Better retention of the story topic.
  • More recognizable children's story structure.

However, repetitive phrases and limited narrative development remain noticeable.


9. How to Use the Model

Installation

pip install transformers==4.46.3 torch safetensors

Load the Model

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

model_id = (
    "jawaher-leen-ai/"
    "tinystories-llama-75m-from-scratch"
)

tokenizer = AutoTokenizer.from_pretrained(model_id)

model = AutoModelForCausalLM.from_pretrained(
    model_id
)

model.eval()

prompt = "Once upon a time, a little robot found a book."

inputs = tokenizer(
    prompt,
    return_tensors="pt"
)

with torch.no_grad():
    outputs = model.generate(
        **inputs,
        max_new_tokens=60,
        do_sample=False,
        pad_token_id=tokenizer.pad_token_id,
        eos_token_id=tokenizer.eos_token_id
    )

generated_text = tokenizer.decode(
    outputs[0],
    skip_special_tokens=True
)

print(generated_text)

Optional: Sample More Diverse Stories

For more varied output, sampling can be enabled:

with torch.no_grad():
    outputs = model.generate(
        **inputs,
        max_new_tokens=160,
        do_sample=True,
        temperature=0.8,
        top_p=0.9,
        repetition_penalty=1.1,
        pad_token_id=tokenizer.pad_token_id,
        eos_token_id=tokenizer.eos_token_id
    )

print(
    tokenizer.decode(
        outputs[0],
        skip_special_tokens=True
    )
)

Sampling may produce more diverse text, but does not improve the model's learned predictive ability.


10. Limitations

This is a small research and educational language model trained on a narrow English storytelling dataset.

Known limitations include:

  • Repetition of words, sentences, and story patterns.
  • Limited long-range narrative coherence.
  • Possible grammatical errors.
  • Restricted general knowledge.
  • Potentially inaccurate or fabricated statements.
  • Limited performance outside children's story generation.
  • A relatively small training token budget compared with the theoretical scaling-law target.

The model is not instruction-tuned and is not intended to function as a general-purpose assistant.

It is also not intended for high-stakes or production decision-making.


11. Conclusion

This project demonstrates the complete process of designing, initializing, training, evaluating, and documenting a small Llama-style language model from scratch.

The experiment connects scaling-law calculations with practical model architecture selection and training.

By increasing the dataset from 30,000 to 120,000 stories and extending training from 300 to 5,000 steps, the improved experiment achieved substantially lower evaluation loss and perplexity.

The model architecture remained fixed at approximately 75M parameters, using Grouped-Query Attention.

The results illustrate how additional training data and compute can improve a small language model, while also highlighting the importance of controlled evaluation when comparing experiments.


12. Credits and References

Project Authors:

  • Jawaher
  • Leen

Dataset:

Research:

Frameworks:

  • PyTorch
  • Hugging Face Transformers
  • Hugging Face Datasets
  • Hugging Face Tokenizers

License

The model is released under the Apache License 2.0.

The TinyStories dataset is distributed separately under the license declared by its provider (CDLA-Sharing-1.0). Users should review the dataset's applicable terms independently.

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
LlamaForCausalLM
Ревизия весов
6f0e7c4

0 моделей