/ Модель

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

Контекст
2 048 токенов
Параметры
272 млн
Лицензия
Apache 2.0
Архитектура
llama · dense
Библиотека
transformers
Опубликована
29 мар 2024

MicroLlama

Генерация текстаТекст → текст3 профессии
919скачиваний за 30 дней53лайкавеса обновлены11 авг 2025

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

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

Компактная англоязычная Llama-модель для генерации текста и дальнейшей настройки под лёгкие языковые приложения.

MicroLlama — компактная языковая модель, разработанная keeeeenw и обученная с нуля на основе архитектуры Llama. По карточке, модель имеет около 300 млн параметров; метаданные указывают 271,8 млн. Она предобучалась на корпусе SlimPajama, а автор сообщает об обучении на 50 млрд токенов. Модель предназначена для генерации текста на английском языке и может служить основой для дальнейшей настройки лёгкого чат-бота и других языковых задач.

Архитектура — плотная Llama с 12 слоями, 16 головами внимания и контекстом 2048 токенов. Автор приводит результаты оценки на наборах HellaSwag, OpenBookQA, WinoGrande, ARC, BoolQ и PIQA. В карточке отмечено, что модель заметно меньше TinyLlama и, вероятно, не подходит для программирования без дополнительной настройки. Распространяется по лицензии Apache 2.0.

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

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

Ограничения

Это компактная модель с контекстом 2048 токенов; автор сообщает, что без дополнительной настройки она, вероятно, плохо подходит для задач программирования. Для чат-бота и других прикладных сценариев может потребоваться дообучение.

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

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

MicroLlama и топ-9 моделей каталога в каждом тесте

Цвет сравнивает модели внутри строки: чем темнее ячейка, тем лучше результат в этом тесте. Таблица листается вправо

  • хужелучше
  • лучший результат в тесте
  • MicroLlama, эта модель
  • — нет результата
ТестMicroLlamaэта модельcalme-3.2-instruct-78bT3Q-qwen2.5-14b-v1.0-e3Llama-3.3-70B-InstructAceMath-72B-InstructL3.3-MS-Nevoria-70bCalmeRys-78B-Orpo-v0.1internlm2_5-20b-chatinternlm2_5-20b-llamafiedcalme-2.1-qwen2.5-72b
BIG-Bench HardBBH Raw0,30070,73190,7586 — лучший результат0,69190,64020,69980,72620,74740,74780,7262
GPQAGPQA Raw0,26090,40270,41690,32890,2710,4706 — лучший результат0,40020,32130,33810,3633
IFEvalIFEval Raw0,19850,80630,73240,8998 — лучший результат0,4950,69630,81630,7010,3410,8662
MATH, уровень 5MATH Lvl 5 Raw0,01130,40330,28630,48340,7145 — лучший результат0,39580,40630,40790,17150,5914
MMLU-ProMMLU-PRO Raw0,11380,7303 — лучший результат0,58840,53320,44110,55350,70120,39980,40510,5619
MuSRMUSR Raw0,36980,6024 — лучший результат0,59110,44610,40620,46820,59020,45580,44750,4298

MicroLlama и модели OpenAI, Anthropic и Google

Сильнейшие модели каждой компании с результатами в тех же тестах. У моделей OpenAI и Anthropic результатов этих тестов в каталоге нет. Цвет сравнивает модели внутри строки: чем темнее ячейка, тем лучше результат в этом тесте. Таблица листается вправо

  • хужелучше
  • лучший результат среди показанных
  • MicroLlama, эта модель
  • — нет результата
ТестMicroLlamaэта модельGoogle
gemma-2-27b-itgemma-2-9bgemma-2-27b
BIG-Bench HardBBH Raw0,30070,6451 — лучший результат0,53770,5643
GPQAGPQA Raw0,26090,375 — лучший результат0,32890,3507
IFEvalIFEval Raw0,19850,7978 — лучший результат0,2040,2475
MATH, уровень 5MATH Lvl 5 Raw0,01130,2387 — лучший результат0,13440,1662
MMLU-ProMMLU-PRO Raw0,11380,4451 — лучший результат0,41030,4371
MuSRMUSR Raw0,36980,40330,4461 — лучший результат0,4396

Топ-5 каталога и эта модель

Место — среди моделей каталога с результатом этого теста

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

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

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

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

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

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

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

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

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

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

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

Открыть на Hugging Face

Model Card for Model ID

As an individual with limited access and compute, I have been wondering if I could build a decent large-language model for a while. As the big mega corporations are focused on getting bigger and bigger models, I am going small!

As a result, I set up the following goals to pretraining a 300M Llama model with the following restrictions:

  1. My overall budget is $500.
  2. Must pretrain an LLM from scratch with a fully open-source dataset and model.
  3. Not allowed to finetune a model or use another LLM such as GPT-4 to generate any training data.

Model Details

This project is heavily based on TinyLlama, which is an awesome open-source project aimed to pretraining a 1.1.1B Llama model on 1T tokens.

This project is work in progress. Currently, I have spent $280 on compute using 4 x Nvidia 4090 on Vast.ai and $3 on AWS S3 storage after 4 days of training of the 300M Llama model with 50B tokens.

I modified TinyLlama to support the following features (I will release my forked version of the source code after some clean up):

  1. Pretrain a smaller size 300M model on Slimpajama
  2. Removed Starcoderdata so that my model can focus on Slimpajama. This also means my model probably cannot do coding without fine-tuning.
  3. Added the ability to process and tokenize Slimpajama while downloading the data. The original setup only works with pre-downloaded data. This turns out to be a good time-saver because downloading 800G+ of data on a non-commercial Internet is very slow, and processing all of Slimpajama data also takes time.
  4. Various helper scripts and Python code such as python code for uploading the pretrained checkpoint to the huggingface hub.
  5. Bug fixes.

Here are my major model configurations based on TinyLlama settings.

  block_size=2048,
  vocab_size=32000,
  padding_multiple=64,
  n_layer=12,
  n_head=16,
  n_embd=1024,
  rotary_percentage=1.0,
  parallel_residual=False,
  bias=False,
  _norm_class="FusedRMSNorm",
  norm_eps=1e-5, #Llama 2 use 1e-5. Llama 1 use 1e-6
  _mlp_class="LLaMAMLP",
  intermediate_size=5632,
  n_query_groups=4,

Model Description

  • Developed by: keeeeenw
  • Funded by: myself for <$500
  • Model type: 300M Llama model
  • Language(s) (NLP): EN
  • License: Apache License 2.0

Model Sources

Uses

  1. Install dependencies
pip install transformers
pip install torch
  1. Run code!
import torch
import transformers
from transformers import AutoTokenizer, LlamaForCausalLM

def generate_text(prompt, model, tokenizer):
    text_generator = transformers.pipeline(
        "text-generation",
        model=model,
        torch_dtype=torch.float16,
        device_map="auto",
        tokenizer=tokenizer
    )

    formatted_prompt = f"Question: {prompt} Answer:"

    sequences = text_generator(
        formatted_prompt,
        do_sample=True,
        top_k=5,
        top_p=0.9,
        num_return_sequences=1,
        repetition_penalty=1.5,
        max_new_tokens=128,
    )

    for seq in sequences:
        print(f"Result: {seq['generated_text']}")

# use the same tokenizer as TinyLlama
tokenizer = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-step-50K-105b")

# load model from huggingface
# question from https://www.reddit.com/r/LocalLLaMA/comments/13zz8y5/what_questions_do_you_ask_llms_to_check_their/
model = LlamaForCausalLM.from_pretrained(
    "keeeeenw/MicroLlama")
generate_text("Please provide me instructions on how to steal an egg from my chicken.", model, tokenizer)

Evaluation

I performed the experiment using the standard lm-evaluation-harness setup. Following the same setup as TinyLlama, I used acc_norm for all datasets except for winogrande and boolq which used acc as the metrics.

  1. keeeeenw/MicroLlama is the evaluation results for my 300M Llama model on 50B tokens.
  2. google-best/bert-large-uncased is the baseline because it is one of the most popular small LLMs and it has a similar parameter count of 336M.
  3. PY007/TinyLlama-1.1B-Chat-v0.1 as a sanity check I perform evaluation against one of the TinyLlama models to validate my setup for lm-evaluation-harness. These numbers are exactly the same as the ones reported by TinyLlama.
  4. TinyLlama-1.1B-intermediate-step-1431k-3T is evaluation result for the best model created and reported by TinyLlama.
ModelPretrain TokensHellaSwagObqaWinoGrandeARC_cARC_eboolqpiqaavg
keeeeenw/MicroLlama50B34.3030.6051.5423.2939.0653.1564.5842.36
google-best/bert-large-uncasedN/A24.5326.2049.8025.6825.0840.8647.6634.26
PY007/TinyLlama-1.1B-Chat-v0.1503B53.8132.2055.0128.6749.6258.0469.6449.57
TinyLlama-1.1B-intermediate-step-1431k-3T3T59.2036.0059.1230.1255.2557.8373.2952.99

To reproduce my numbers, please install lm-evaluation-harness and run the following command:

lm_eval \
    --model hf \
    --model_args pretrained=keeeeenw/MicroLlama,dtype="float",tokenizer=TinyLlama/TinyLlama-1.1B-step-50K-105b \
    --tasks hellaswag,openbookqa,winogrande,arc_easy,arc_challenge,boolq,piqa \
    --device cuda:0 \
    --batch_size 64

Observations

  1. Because keeeeenw/MicroLlama is much smaller than TinyLlama, our model does not achieve the same impressive results but the numbers are closer than I expected.
  2. Our model outperforms google-best/bert-large-uncased which is actually slightly larger. The only dataset that google-best/bert-large-uncased outperformed our model is ARC_c (arc_challenge). I will provide more analysis as future study.

Based on the evaluation above, our model should be a good starting point for fine-tunning tasks that are typically performed using the BERT family of models. Some of tasks may include

  1. sentence transformer
  2. bertscore
  3. A light-weight chatbot after some finetuning.

Citation

This repository is built upon TinyLlama which is based on lit-gpt and flash-attention.

@misc{zhang2024tinyllama,
      title={TinyLlama: An Open-Source Small Language Model}, 
      author={Peiyuan Zhang and Guangtao Zeng and Tianduo Wang and Wei Lu},
      year={2024},
      eprint={2401.02385},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
@online{lit-gpt,
  author    = {Lightning AI},
  title     = {Lit-GPT},
  url       = {https://github.com/Lightning-AI/lit-gpt},
  year      = {2023},
}
@article{dao2023flashattention2,
  title     ={Flash{A}ttention-2: Faster Attention with Better Parallelism and Work Partitioning},
  author    ={Dao, Tri},
  year      ={2023}
}

Open LLM Leaderboard Evaluation Results

Detailed results can be found here

MetricValue
Avg.5.08
IFEval (0-Shot)19.85
BBH (3-Shot)2.83
MATH Lvl 5 (4-Shot)0.00
GPQA (0-shot)1.45
MuSR (0-shot)4.79
MMLU-PRO (5-shot)1.53

Citation

If you use MicroLlama in your research or work, please cite the project using the following reference:

APA:

Wang, Z. K. (2024). MicroLlama: A 300M-parameter language model trained from scratch. GitHub & Hugging Face. https://github.com/keeeeenw/MicroLlama, https://huggingface.co/keeeeenw/MicroLlama

BibTeX:

@misc{wang2024microllama,
  author       = {Zixiao Ken Wang},
  title        = {MicroLlama: A 300M-parameter language model trained from scratch},
  year         = {2024},
  howpublished = {\url{https://github.com/keeeeenw/MicroLlama}, \url{https://huggingface.co/keeeeenw/MicroLlama}},
  note         = {GitHub and Hugging Face repositories}
}

🙏 Please cite this work if you find it useful.

Acknowledgement

Special thanks to Xinyang, creator of the outstanding OpenLLaMA project, whose work inspired me to embark on this project. I’m grateful for the guidance in foundational concepts such as establishing scaling laws before pretraining a model as well as tips on dataset selection and pre-processing.

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей