Downloads · 30 days
103
52% of all-time downloads
lakhera2023/rnj1-tinystories
rnj1-tinystories is a machine learning model from lakhera2023. Use it for the machine learning task on the model card, and read the license before you ship it in a product.
A complete PyTorch implementation of the RNJ-1 (pronounced "range-1") architecture, following the design principles of the model developed by Essential AI, led by Ashish Vaswani (co-author of "Attention Is All You Nee…
Downloads · 30 days
103
52% of all-time downloads
All-time downloads
198
Public
Repo size
907 MB
Likes
1
Public
Click a slice to open those files.
.bin889 MB · 98%
From the Hugging Face model README
A complete PyTorch implementation of the RNJ-1 (pronounced "range-1") architecture, following the design principles of the model developed by Essential AI, led by Ashish Vaswani (co-author of "Attention Is All You Need").
This is a configurable implementation of the RNJ-1 architecture that allows you to build models of various sizes. The original RNJ-1 is an 8.3B parameter model optimized for code generation, agentic tasks, and STEM problem solving, but this implementation lets you adjust the model size based on your needs and available resources.
The actual parameter count is calculated at runtime and depends on your configuration in RNJ1_CONFIG. The default configuration targets the full RNJ-1 architecture (~8.3B), but you can easily modify it to create smaller models for testing or limited GPU memory.
RNJ1_CONFIG in rnj1.py)The model configuration is defined in RNJ1_CONFIG in rnj1.py. You can modify these values to create models of any size:
| Hyperparameter | Default Value | Config Key | Notes |
|---|---|---|---|
| Number of Layers | 32 | n_layers | Main size factor |
| Model Dimension | 4096 | emb_dim | Affects all layers |
| MLP Dimension | 16384 | hidden_dim | Typically 4x emb_dim |
| Number of Attention Heads | 32 | n_heads | Should divide emb_dim |
| Number of Key-Value Heads | 8 | n_kv_groups | GQA ratio |
| Attention Head Dimension | 128 | head_dim | Typically emb_dim/n_heads |
| Vocabulary Size | From tokenizer | vocab_size | Affects embedding size |
| Tokenizer | SentencePiece BPE | Auto-detected | With fallback options |
| Context Length | 32768 | context_length | Can be reduced |
| Activation Function | GeGLU | Fixed | In FeedForward class |
| Tied Embeddings | Yes | Fixed | Embedding and output head share weights |
Important:
count_parameters() function and printed when you run the scriptTotal trainable parameters: X,XXX,XXX (~X.XXB)RNJ1_CONFIG in rnj1.py before runningvocab_size × emb_dim, which can be significantemb_dim from 4096 to 1024 and n_layers from 32 to 12 creates a much smaller modelGlobal Attention Only: Unlike Gemma 3's hybrid sliding window + global attention, RNJ-1 uses only global attention throughout all layers. This provides full context awareness at every layer, which is beneficial for code and agentic tasks.
Standard RoPE: Uses single RoPE (Rotary Position Embeddings) with theta_base = 10,000. Context extension from 8K to 32K is handled via YaRN (Yet another RoPE extensioN) during mid-training.
GeGLU Activation: Uses GeGLU (Gated GeLU) activation function in the feedforward network, which provides better expressiveness compared to standard GeLU.
Grouped Query Attention (GQA): 32 query heads with 8 KV heads (4:1 ratio), providing memory efficiency while maintaining performance.
QK Normalization: Uses query-key normalization for training stability.
4 RMSNorm Layers: Pre-norm architecture with 4 normalization layers per transformer block:
input_layernorm (pre-attention)post_attention_layernorm (post-attention, pre-residual)pre_feedforward_layernorm (pre-feedforward)post_feedforward_layernorm (post-feedforward, pre-residual)| Feature | Gemma 3 | RNJ-1 |
|---|---|---|
| Attention | Hybrid sliding window (5:1 pattern) | Global attention only |
| RoPE | Dual RoPE (10K for local, 1M for global) | Single RoPE (10K, extended via YaRN) |
| Activation | GeLU | GeGLU |
| Context Length | 128K (native) | 32K (extended from 8K) |
| Optimizer | AdamW | Muon (custom) |
| Focus | General-purpose | Code & STEM |
pip install torch numpy transformers datasets tqdm matplotlib
The memory requirements depend on your model configuration:
Memory requirements depend on your model configuration:
With default config (targeting ~8.3B):
For smaller models (modify RNJ1_CONFIG):
emb_dim, n_layers, and hidden_dim in RNJ1_CONFIGemb_dim=1024, n_layers=12, hidden_dim=4096from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
# Load model and tokenizer
model_id = "EssentialAI/rnj-1-instruct"
model = AutoModelForCausalLM.from_pretrained(
model_id,
dtype=torch.bfloat16,
device_map="auto",
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Generate text
messages = [
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "Write a Python function to calculate factorial"}
]
input_ids = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt"
).to(model.device)
output_ids = model.generate(
input_ids,
max_new_tokens=200,
temperature=0.2,
top_p=0.95
)
response = tokenizer.decode(output_ids[0][input_ids.shape[-1]:], skip_special_tokens=True)
print(response)
The complete training script is provided in rnj1.py. It includes:
# Training hyperparameters (from rnj1.py)
batch_size = 16
block_size = 128
learning_rate = 1e-4
max_iters = 150000
warmup_steps = 1000
gradient_accumulation_steps = 32
The model size is determined by RNJ1_CONFIG in the script. The actual parameter count is calculated at runtime and printed during initialization. To create a smaller model, modify the configuration:
# Example: Smaller model for testing
RNJ1_CONFIG = {
"vocab_size": vocab_size, # From tokenizer
"emb_dim": 1024, # Reduced from 4096
"n_heads": 16, # Reduced from 32
"head_dim": 64, # Reduced from 128
"n_kv_groups": 4, # Reduced from 8
"n_layers": 12, # Reduced from 32
"hidden_dim": 4096, # Reduced from 16384
"context_length": 2048, # Reduced from 32K
"rope_base": 10_000.0,
"qk_norm": True,
"dtype": torch.bfloat16,
}
python rnj1.py
What the script does:
train.bin doesn't exist)RNJ1_CONFIG settingsrnj1_model.pt)To see your actual model size, look for this output when running:
Total trainable parameters: X,XXX,XXX (~X.XXB)
The implementation includes:
(1 + weight) scalingCode Generation:
Mathematical Reasoning:
STEM:
EssentialAI/rnj-1 tokenizer with fallback optionstorch.amp.autocastModel Size: The actual parameter count is calculated and printed at runtime. The default RNJ1_CONFIG targets ~8.3B parameters, but:
vocab_size (from tokenizer) and all config valuesRNJ1_CONFIG to create much smaller modelsemb_dim, n_layers, and hidden_dim significantlyvocab_size × emb_dim) is often the largest componentOptimizer: This implementation uses AdamW, but the original RNJ-1 uses Muon optimizer (custom optimizer by Essential AI). Muon provides superior token efficiency but is not publicly available.
Training Scale: The provided script uses TinyStories dataset for demonstration. Full RNJ-1 training requires:
Memory Requirements: Memory usage depends on model size. For the full 8.3B model, you need significant GPU memory. For smaller models, adjust batch_size and block_size based on available hardware. You can also reduce model dimensions in RNJ1_CONFIG.
Tokenizer Fallback: If RNJ-1 tokenizer is unavailable, the script falls back to Llama 3.1 tokenizer (also 128K vocab, SentencePiece BPE). The actual vocab_size affects the embedding layer size significantly.
rnj-1/
├── README.md # This file
├── rnj1.py # Complete training script
├── RNJ1_QUICK_REFERENCE.md # Quick reference guide
├── RNJ1_REVIEW.md # Detailed model review
├── RNJ1_TOKENIZER_INFO.md # Tokenizer details
├── RNJ1_VS_GEMMA3_COMPARISON.md # Architecture comparison
└── linkedin_post_rnj1.md # Social media post about implementation
This implementation follows the Apache 2.0 license, matching the original RNJ-1 model.
This is an educational implementation. For improvements or corrections:
For questions about:
RNJ1_REVIEW.md and RNJ1_VS_GEMMA3_COMPARISON.mdRNJ1_TOKENIZER_INFO.mdRNJ1_QUICK_REFERENCE.mdrnj1.pyLast Updated: December 2025
Model Version: RNJ-1 (Base and Instruct)
Implementation Version: 1.0