Run this model with HF Jobs

Run TreeLoys/MicroLLM-64M-ru-en on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/TreeLoys/MicroLLM-64M-ru-en. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/TreeLoys/MicroLLM-64M-ru-en on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/TreeLoys/MicroLLM-64M-ru-en. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/TreeLoys/MicroLLM-64M-ru-en. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.

MicroLLM-64M-ru-en

A bilingual (Russian + English) instruction-tuned language model with exactly 67 108 864 parameters (2²⁶), trained from scratch on a single consumer GPU: an NVIDIA GeForce RTX 5070, 12 GB. About 14 GPU-hours in total: 2.0B tokens of pretraining followed by 0.62B tokens of instruction tuning. No cloud, no multi-GPU, no framework — a plain PyTorch loop, a custom data pipeline and a tokenizer trained from scratch.

It is the third model of the micro-series after microRL-20M-TinyStories and microRL-20M-ru-en, and the first one that answers questions instead of only continuing text. On held-out Russian web text it scores 0.749 bits/byte (the 20M ru-en model: 0.811, Qwen2.5-0.5B-Instruct: 0.672).

Status: research artefact. It speaks grammatical Russian and English, keeps the format of an assistant and answers simple questions correctly some of the time. It has almost no reliable factual knowledge, cannot do arithmetic, and loops under greedy decoding. It is a baseline for small-model experiments, not a usable assistant.

Quick start

from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("TreeLoys/MicroLLM-64M-ru-en")
tok = AutoTokenizer.from_pretrained("TreeLoys/MicroLLM-64M-ru-en")

messages = [{"role": "user", "content": "What is photosynthesis? Answer in one sentence."}]
inputs = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
out = model.generate(**inputs, max_new_tokens=100, do_sample=True, temperature=0.3, top_k=40,
                     pad_token_id=tok.pad_token_id)
print(tok.decode(out[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True))

No trust_remote_code needed: the weights are a native LlamaForCausalLM. The chat template uses <|im_start|>role … <|im_end|> turns; a system prompt is optional (the model was trained with short system prompts such as "Ты — полезный ассистент."). Greedy decoding (do_sample=False) tends to repeat sentences — use sampling with temperature 0.2–0.3.

Architecture

Type decoder-only Transformer, Llama-style
Attention causal, RoPE (theta 10 000), GQA: 8 query heads × 64 dims, 4 key/value heads
FFN SwiGLU, intermediate 1536
Norm RMSNorm (eps 1e-6), pre-norm
Layers 16
Hidden size 512
Context length 1024
Vocabulary 32 735 byte-level BPE, trained from scratch
Embeddings input and output tied
Parameters 67 108 864 total (exactly 2²⁶), 50.35M without embeddings
Biases none

The size was chosen to land on a power of two: the vocabulary was sized so that embeddings (16.76M) plus 16 blocks (3 146 752 each) plus the final norm add up to 2²⁶ exactly. A byte-level BPE with ~33k tokens instead of a 128k one leaves three quarters of the parameters for the blocks instead of one half.

The tokenizer was trained on a 1.75 GB sample with a Russian emphasis: Russian Wikipedia (260 MB), Russian FineWeb-2 (260 MB), FineWeb-Edu (220 MB), StarCoder Python (200 MB), Cosmopedia (120 MB), GitHub code (80 MB), Saiga and SmolTalk dialogs (120 MB), 4chan /pol/ (40 MB), smaller Russian instruction sets (30 MB). It encodes 3.4 characters of Russian and 4.4 characters of English per token. Special tokens: <|endoftext|> (0, document separator and padding), <|im_start|> (1), <|im_end|> (2, end of answer).

Training data

Everything was downloaded from the Hub and tokenized locally: 44.1B tokens in total (37.7B pretraining text, 6.4B dialogs). The model saw 2.6B of them (6 %).

Pretraining mixture (share of the 2.0B tokens; the corpus holds far more of every source, so nothing was repeated to exhaustion):

Share Source Corpus size
20 % Russian Wikipedia (wikimedia/wikipedia, 20231101.ru) 3.21B tokens
20 % Russian web, HuggingFaceFW/fineweb-2 (rus, one shard) 2.21B
16 % English educational web, HuggingFaceFW/fineweb-edu (sample-10BT, 6 shards) 5.05B
14 % Synthetic textbooks, HuggingFaceTB/cosmopedia (stanford, auto_math_text, wikihow, openstax, khanacademy) 2.73B unique
5 + 5 % Python, bigcode/starcoderdata (python, 59 shards) 18.7B
4 % Code, codeparrot/github-code-clean (10 shards) 3.08B
4 % Saiga (IlyaGusev/saiga_scored, score ≥ 6), as plain text 61M
4 % kjj0/4chanpol, posts of 200–20 000 characters, capped at 113k posts 13M
3 % HuggingFaceTB/smoltalk (subset all), as plain text 0.96B
2 + 2 % lksy/ru_instruct_gpt4, IlyaGusev/ru_turbo_alpaca, as plain text 11M
1 % IlyaGusev/oasst1_ru_main_branch, as plain text 1M

About half of the pretraining tokens are Russian. The sources were sampled by weight in shuffled 4M-token blocks, so the mix was constant throughout training.

Instruction tuning (loss on assistant tokens only, loss mask 1 on answers, 0 on system/user turns; dialogues longer than 8192 tokens dropped; unfinished trailing turns removed):

Share Source
18 % IlyaGusev/saiga_scored (Russian)
15 + 15 % HuggingFaceTB/smoltalk (subset all), HuggingFaceTB/smoltalk2 (SFT splits without reasoning traces)
10 % HuggingFaceTB/smol-smoltalk
7 % allenai/tulu-3-sft-mixture
4 % HuggingFaceH4/ultrachat_200k
3 + 3 + 3 % oasst1_ru_main_branch, lksy/ru_instruct_gpt4, IlyaGusev/ru_turbo_alpaca (Russian)
3 % HuggingFaceH4/no_robots
3 % meta-math/MetaMathQA
2 % each MathInstruct, GSM8K train, MATH train (EleutherAI/hendrycks_math), Magicoder-Evol-Instruct-110K, Magicoder-OSS-Instruct-75K, alpaca-cleaned, Open-Platypus
1 % each alpaca, HuggingFaceH4/CodeAlpaca_20K

27 % of the instruction tokens are Russian. Test splits of GSM8K, MATH, no_robots and UltraChat were never used for training.

Training

Pretraining Instruction tuning
Hardware 1 × NVIDIA GeForce RTX 5070, 12 GB (Blackwell) same
Software PyTorch 2.14.1 + CUDA 13.2, plain torch loop, no frameworks same
Precision bf16 autocast, fp32 master weights same
Batch 16 sequences × 1024 tokens per pass, 131 072 tokens per optimizer step same
Optimizer AdamW, betas (0.9, 0.95), weight decay 0.1 on matrices, none on norms and embeddings same
Learning rate 3e-3, 153 warm-up steps, cosine decay to 10 % 3e-4, cosine decay to 10 % (schedule restarted for the second round)
Grad clipping global norm 1.0 same
Steps 15 259 1 526 (round 1) + 3 199 (round 2)
Tokens seen 2.00B 0.62B (rounds of 0.20B and 0.42B)
Speed ~62 000 tokens/s ~57 000 tokens/s
Time ~9.0 hours ~5.0 hours wall-clock (1.6 h + 3.4 h; part of the second round ran with the GPU shared with other programs)
Peak GPU memory ~10 GB allocated, 11.7 GB in use same

Total tokenization time (CPU, 44B tokens): 7.4 hours.

Training loss

Left: pretraining loss 9.98 → 2.55 nats/token. Right: loss on assistant tokens during instruction tuning; the second round continues the first (1.76 → 1.70 nats/token, then 1.61 → about 1.55, with the best logged batches at 1.39) and was stopped by hand at 0.62B tokens.

Two implementation details mattered a lot on this GPU. The output layer computes the loss in chunks of 2048 positions against a vocabulary padded to a multiple of 64: with the raw odd vocabulary size of 32 735 the matmul and softmax kernels ran about 6× slower and the float32 logits did not fit in memory. With the chunked loss one optimizer step takes 2.1 s.

Evaluation

Held-out text that was never used in training, every model scored with its own tokenizer over 512-token windows. Numbers are in bits per byte of the scored text (lower is better) so that tokenizers with different token lengths stay comparable. The nats/token column depends on the tokenizer and is not comparable across models.

Model Total params en web (FineWeb-Edu, held-out shard) ru web (FineWeb-2, test split) en chat, nats/token
Qwen/Qwen2.5-0.5B-Instruct 494.0M 0.847 0.672 2.41
MicroLLM-64M-ru-en (this) 67.1M 1.210 0.749 2.93
TreeLoys/microRL-20M-ru-en 19.6M 1.890 0.811 —
TreeLoys/microRL-20M-TinyStories 19.6M 2.708 4.481 —

Test sets: 1 500 documents each. The chat column is the loss on the assistant answers of 500 no_robots test prompts given the chat-formatted prompt (models without a chat format are not listed). Raw numbers are in bench.json.

GSM8K (test split, 1 319 problems, zero-shot, greedy, the last number of the answer compared with the reference): this model 1.5 %, Qwen2.5-0.5B-Instruct 17.2 % under the same prompt. The harness has no chain-of-thought prompt, so both numbers are lower bounds; Qwen reports higher results with its own setup.

What the numbers mean. The gap to Qwen on English web text is large (1.21 vs 0.85 bits/byte); on Russian web text it is small (0.75 vs 0.67), because half of the pretraining data was Russian. Reading Russian is not the same as knowing things: the model predicts Russian prose well and still gets most facts wrong.

Generations

Chat format, greedy decoding:

Привет! Чем можешь помочь? Привет! Я могу помочь с различными вопросами и задачами, связанными с обработкой естественного языка. Если у тебя есть конкретный вопрос или задача, которую нужно решить, я постараюсь помочь!

What is photosynthesis? Answer in one sentence. Photosynthesis is the process by which plants convert sunlight into chemical energy, such as glucose and oxygen.

Write a Python function that reverses a string. Here is a Python function that reverses a string:

def reverse_string(s):
    return s[::-1]

This function uses a generator expression to iterate over the characters of the string, reversing the string using the [::-1] slice. The [::-1] slice is used to reverse the string, and the [::-1] slice is used to reverse the string.

Кто написал «Войну и мир»? «Война и мир» (1799) — одна из самых известных и значимых исторических фигур в истории России. Она была написана в период с 1805 по 1812 годы.

Напиши заявление в прокуратуру на некачественную уборку снега во дворе. Прокурору [город] [ФИО прокурора] [ФИО заявителя] *[номер]{номер]{номер предмет)} … (degenerates into bracket placeholders)

Chat format, sampling, temperature 0.3:

Расскажи коротко, что такое фотосинтез. Фотосинтез - это биохимический процесс, с помощью которого растения, водоросли и некоторые бактерии преобразуют солнечную энергию в химическую энергию. Это происходит в виде хлорофилла, который поглощает световую энергию солнца и используется для превращения углекислого газа и воды в глюкозу и кислород. Фотосинтез используется для синтеза органических веществ из солнца и кислорода, а также для роста и развития растений.

Raw text continuation, greedy (the base-model behaviour that instruction tuning suppresses):

def fibonacci(n):

def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

Test the function

print(fibonacci(10)) # Output: 0 print(fibonacci(10)) # Output: 1

The water cycle begins when The water cycle begins when the water enters the water cycle. The water cycle is the cycle of water that flows through the water cycle.

Negative results and pitfalls

  • An off-by-one in the loss packing produced a model with loss 0.000. The first instruction-tuning run put every target token one position early, so the model was trained to echo the token it had just seen. The loss fell from 11.4 to 0.10 in 40 steps and looked like a triumph. Smoke tests on a small sample did not expose it (the loss there only moved from 8.19 to 8.05). A loss that reaches exactly zero means the target is visible in the input — check the packing before anything else.
  • Training loss overstates instruction-following. The loss on assistant tokens fell from 1.76 to about 1.55 nats/token (best logged batches 1.39); the model got better at remembering the topic of a conversation and slightly better at simple facts, but it did not learn arithmetic, code logic or to follow constraints ("budget under 2000 rubles"). It also began to loop more and to answer more rudely, a sign of over-training on a dialog corpus that is small relative to the number of passes.
  • A 4 % share of a tiny source is many epochs. The 4chan /pol/ set was capped at 113k posts (13M tokens) but sampled at 4 %, so it was repeated about six times. Its effect on the model was not measured; the cap should have been paired with a lower weight.
  • Chat on the same GPU during training halves the throughput. Running a second model on the GPU while training lowered the speed from 62 000 to 25 000 tokens/s. Inference has to go to the CPU or to another time.
  • Tokenized size is 4–6× the compressed size. The download sizes suggested about 15B tokens; the corpus came out at 44B (Python files alone are 19B). Tokenization took 7.4 hours on CPU and was the longest step of the project.
  • HuggingFaceTB/smollm-corpus python-edu parquet files carry metadata only (ids, paths, scores, no code) — the content has to be fetched from the Software Heritage archive.
  • Greedy decoding loops; temperature 0.7 rambles. The usable range is 0.2–0.3. With temperature 0 the model answers some factual questions correctly that it misses when sampling.

Intended use and limitations

  • Intended: a baseline for experiments on small bilingual models (retrieval-augmented answering, preference tuning, distillation), teaching, and architecture or data-pipeline tests on consumer hardware.
  • Not intended: any factual, mathematical or general-purpose use. It invents facts confidently, cannot count beyond trivial sums, writes code with the right shape and wrong logic, and loses a constraint as soon as an answer is longer than two sentences.
  • Context length is 1024 tokens, about 3 500 characters of Russian: long documents do not fit and a conversation forgets its beginning after a few turns.
  • Trained in part on forum text (4chan /pol/) without a toxicity filter; rude phrasing is possible.
  • Greedy decoding repeats; sample at temperature 0.2–0.3.

Licence

Released for research use, same as the earlier models of the series. The model was trained on public datasets with different licences and conditions: the FineWeb corpora require attribution (ODC-By), StarCoderData is distributed under BigCode OpenRAIL-M with its use restrictions, and kjj0/4chanpol was published without a licence. Check the dataset cards before any use beyond research.

Citation

@article{penedo2024fineweb,
  title   = {The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale},
  author  = {Penedo, Guilherme and Kydl{\'i}{\v{c}}ek, Hynek and Ben Allal, Loubna and others},
  journal = {arXiv preprint arXiv:2406.17557},
  year    = {2024}
}

@article{benallal2024cosmopedia,
  title   = {Cosmopedia: How to create Large-Scale Synthetic Data for Pre-training Language Models},
  author  = {Ben Allal, Loubna and Lozhkov, Anton and Penedo, Guilherme and others},
  journal = {arXiv preprint arXiv:2402.03599},
  year    = {2024}
}
Downloads last month
-
Safetensors
Model size
67.1M params
Tensor type
F32
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Datasets used to train TreeLoys/MicroLLM-64M-ru-en

Papers for TreeLoys/MicroLLM-64M-ru-en