Views
No views yet

| ✅ Bisa | ❌ Belum Bisa |
|---|---|
| Load model architecture | Generate teks bermakna |
| Test forward pass | Menjawab pertanyaan |
| Measure memory & speed | Reasoning & understanding |
| Start training | Production deployment |
| Fine-tuning experiments | Real-world applications |
📖 Tentang Project CacaCaca adalah eksperimen open-source Indonesian LLM yang dibuat dari nol secara individual dan bertahap. Bukan kompetitor siapa-siapa, cuma pengen eksplorasi apa yang bisa dilakukan dengan budget terbatas, passion unlimited, dan mindset collaborative.Kalau berguna buat orang lain, alhamdulillah. Kalau enggak, ya tetap fun kok. Ini proyek eksplorasi, jadi kalau gagal ya bagian dari proses belajar. Kalau berhasil, itu bonus.— Lyon, Creator
| Fitur | Caca caca-30M | LLaMA-2 29.60M | GPT-3 29.60M |
|---|---|---|---|
| Attention Type | GQA | GQA | MHA |
| Position Encoding | RoPE + ALiBI | RoPE | Learned |
| Activation | SwiGLU | SwiGLU | GELU |
| Flash Attention | ✅ v2 | ✅ v1/v2 | ❌ |
| Long Context | Sliding Window + Sink | ✅ | Limited |
| MoE Support | ✅ Optional | ❌ | ❌ |
| Multimodal | ✅ Optional | ❌ | ❌ |
| Quantization | 4/8-bit | 4/8-bit | Limited |
|
🔬 Research & Development
📚 Academic & Education
|
🚀 Base Model for Fine-tuning
💡 Prototyping
|
| Parameter | Value | Parameter | Value |
| Total Parameters | 29,597,120 | Vocab Size | 16,000 |
| Hidden Size | 448 | Intermediate Size | 1280 |
| Num Layers | 7 | Attention Heads | 7 |
| KV Heads (GQA) | 1 | Head Dimension | 64 |
| Max Context Length | 1,024 | RoPE Base (θ) | 10,000 |
| Model Size (FP16) | 0.06 GB | Formatted Size | 29.60M |
| Configuration | Model Weights | + Optimizer States | Total Training |
|---|---|---|---|
| FP32 (AdamW) | 0.12 GB | +0.36 GB | 0.47 GB |
| Mixed Precision | 0.06 GB | +0.41 GB | 0.47 GB |
| + Gradient Checkpointing | Menghemat ~30-50% activation memory | ~0.28 GB |
| Precision | Model Size | KV Cache (2K ctx) | Total Memory | Memory Saving |
|---|---|---|---|---|
| FP16 / BF16 | 0.06 GB | 0.00 GB | 0.06 GB | Baseline |
| INT8 | 0.03 GB | 0.00 GB | 0.03 GB | ~50% ↓ |
| INT4 (NF4) | 0.01 GB | 0.00 GB | 0.02 GB | ~75% ↓ |
💡 Note: KV cache bertambah secara linear dengan panjang sequence. Untuk context 8K, kalikan nilai KV cache dengan 4.
| Metric | Value | Notes |
|---|---|---|
| FLOPs per Token | 59,194,240 | Forward pass only |
| TFLOPs per Token | 0.0001 | ≈ 6× untuk backward |
| Bandwidth (FP16) | 0.06 GB/token | Memory bandwidth requirement |
CacaForCausalLM (29.60M)
│
├─ Embedding: 16,000 × 448
│
├─ Transformer Layers (7x)
│ ├─ RMSNorm
│ ├─ Attention (GQA)
│ │ ├─ Q: 7 heads × 64 dim
│ │ ├─ KV: 1 heads × 64 dim
│ │ ├─ RoPE (θ=10,000)
│ │ └─ Flash Attention v2
│ ├─ Residual
│ ├─ RMSNorm
│ ├─ FFN (SwiGLU)
│ │ ├─ Gate: 448 → 1280
│ │ ├─ Up: 448 → 1280
│ │ └─ Down: 1280 → 448
│ └─ Residual
│
├─ Final RMSNorm
└─ LM Head: 448 → 16,000
═══════════════════════════════════════════════════════════
📊 PARAMETER BREAKDOWN:
═══════════════════════════════════════════════════════════
Embeddings: 7,168,000 ( 24.2%)
Transformer Layers: 15,253,504 ( 51.5%)
├─ Attention: 3,211,264
└─ FFN: 12,042,240
Final Norm: 448 ( 0.0%)
───────────────────────────────────────────────────────────
TOTAL: 29,597,120 (100.0%)
═══════════════════════════════════════════════════════════1# Core dependencies (REQUIRED)
2pip install torch>=2.0.0 transformers>=4.35.0 accelerate safetensors
3
4# Optional: Untuk performa maksimal
5pip install flash-attn --no-build-isolation # Flash Attention 2 (3x speedup)
6pip install xformers # Memory efficient attention
7pip install bitsandbytes # 4/8-bit quantization
8
9# Optional: Untuk monitoring & profiling
10pip install tensorboard wandb # Training monitoring
11pip install gputil psutil # Resource monitoring| Component | Version | Note |
|---|---|---|
| Python | 3.8 - 3.11 | 3.11 recommended |
| PyTorch | ≥ 2.0.0 | 2.1+ untuk SDPA optimal |
| CUDA | 11.8 / 12.1 | Untuk Flash Attention |
| Transformers | ≥ 4.35.0 | Untuk AutoModel support |
1from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
2import torch
3
4# Load configuration
5config = AutoConfig.from_pretrained(
6 "Lyon28/caca-30M-untrained",
7 trust_remote_code=True
8)
9
10# Load model (FP16 untuk efisiensi)
11model = AutoModelForCausalLM.from_pretrained(
12 "Lyon28/caca-30M-untrained",
13 config=config,
14 trust_remote_code=True,
15 torch_dtype=torch.float16,
16 device_map="auto" # Automatic device placement
17)
18
19# Model ini UNTRAINED - butuh training dulu!
20print(f"Model loaded: {model.num_parameters():,} parameters")
21print("⚠️ Model ini belum dilatih dan belum bisa digunakan untuk inference")1from transformers import AutoModelForCausalLM, BitsAndBytesConfig
2import torch
3
4# 4-bit quantization config
5bnb_config = BitsAndBytesConfig(
6 load_in_4bit=True,
7 bnb_4bit_quant_type="nf4",
8 bnb_4bit_compute_dtype=torch.bfloat16,
9 bnb_4bit_use_double_quant=True
10)
11
12# Load model dengan quantization
13model = AutoModelForCausalLM.from_pretrained(
14 "Lyon28/caca-30M-untrained",
15 trust_remote_code=True,
16 quantization_config=bnb_config,
17 device_map="auto"
18)
19
20print(f"Memory footprint: ~0.01GB (4-bit)")1from transformers import TrainingArguments, Trainer
2
3# Training configuration
4training_args = TrainingArguments(
5 output_dir="./output",
6 per_device_train_batch_size=1,
7 gradient_accumulation_steps=16,
8 learning_rate=2e-4,
9 max_steps=10000,
10 lr_scheduler_type="cosine",
11 warmup_steps=500,
12 logging_steps=10,
13 save_steps=500,
14 fp16=True, # Mixed precision
15 gradient_checkpointing=True, # Memory efficient
16)
17
18# Initialize trainer
19trainer = Trainer(
20 model=model,
21 args=training_args,
22 train_dataset=train_dataset,
23)
24
25# Start training
26trainer.train()1model.gradient_checkpointing_enable()
2print("✅ Gradient checkpointing enabled - saves ~40% memory")1from torch.optim import AdamW
2from torch.cuda.amp import autocast, GradScaler
3
4optimizer = AdamW(model.parameters(), lr=2e-4)
5scaler = GradScaler()
6
7for batch in dataloader:
8 # Mixed precision forward
9 with autocast(dtype=torch.bfloat16):
10 outputs = model(**batch)
11 loss = outputs.loss
12
13 # Backward with gradient scaling
14 scaler.scale(loss).backward()
15 scaler.step(optimizer)
16 scaler.update()
17 optimizer.zero_grad()1import torch.distributed as dist
2from torch.nn.parallel import DistributedDataParallel
3
4# Initialize process group
5dist.init_process_group(backend="nccl")
6
7# Wrap model
8model = DistributedDataParallel(
9 model,
10 device_ids=[local_rank],
11 find_unused_parameters=False
12)1{
2 "architectures": ["CacaForCausalLM"],
3 "model_type": "caca",
4 "vocab_size": 16000,
5 "hidden_size": 448,
6 "intermediate_size": 1280,
7 "num_hidden_layers": 7,
8 "num_attention_heads": 7,
9 "num_key_value_heads": 1,
10 "head_dim": 64,
11 "max_position_embeddings": 1024,
12 "rope_theta": 10000,
13 "rms_norm_eps": 1e-06,
14 "use_cache": true,
15 "use_qk_norm": true,
16 "use_flash_attn": true,
17 "attention_dropout": 0.0,
18 "hidden_dropout": 0.1,
19 "torch_dtype": "float16"
20}1from transformers import AutoConfig
2
3# Load dan modifikasi config
4config = AutoConfig.from_pretrained("Lyon28/caca-30M-untrained")
5
6# Custom modifications
7config.max_position_embeddings = 16384 # Extend context
8config.rope_scaling = {"type": "linear", "factor": 2.0}
9config.use_flash_attn = True
10config.hidden_dropout = 0.05
11
12# Save custom config
13config.save_pretrained("./custom_config")Input Tokens
↓
Embedding Layer (16,000 → 448)
↓
┌─────────────────────────────────────┐
│ Decoder Block × 7 │
│ │
│ ┌─ RMSNorm │
│ ├─ Multi-Head Attention (GQA) │
│ │ - Flash Attention v2 │
│ │ - 7 Query heads, 1 KV heads │
│ │ - RoPE position encoding │
│ ├─ Residual Connection │
│ │ │
│ ├─ RMSNorm │
│ ├─ Feed-Forward Network (SwiGLU) │
│ │ - Gate: 448 → 1280 │
│ │ - Up: 448 → 1280 │
│ │ - Down: 1280 → 448 │
│ └─ Residual Connection │
│ │
└─────────────────────────────────────┘
↓
RMSNorm (Final)
↓
LM Head (448 → 16,000)
↓
Output LogitsQuery: [7 heads × 64 dim] = 448
Key: [1 heads × 64 dim] = 64
Value: [1 heads × 64 dim] = 64
Grouped Query Attention:
- Setiap 7 query heads berbagi 1 KV head
- Memory KV cache: 86% lebih kecil dari Multi-Head Attention
- Kualitas mendekati MHA, speed mendekati MQAFFN(x) = (SiLU(xW_gate) ⊙ xW_up) W_down
Where:
- W_gate: 448 × 1280
- W_up: 448 × 1280
- W_down: 1280 × 448
- SiLU(x) = x · sigmoid(x)
- ⊙ = element-wise multiplication1# Format chat template bawaan
2chat_template = """
3{% for message in messages %}
4{% if message['role'] == 'system' %}
5System: {{ message['content'] }}
6
7{% elif message['role'] == 'user' %}
8User: {{ message['content'] }}
9
10{% elif message['role'] == 'assistant' %}
11Assistant: {{ message['content'] }}
12
13{% endif %}
14{% endfor %}
15{% if add_generation_prompt %}Assistant:{% endif %}
16"""
17
18# Contoh penggunaan
19messages = [
20 {"role": "system", "content": "Kamu adalah asisten AI yang membantu dan ramah."},
21 {"role": "user", "content": "Jelaskan tentang fotosintesis"},
22 {"role": "assistant", "content": "Fotosintesis adalah proses di mana tumbuhan mengubah cahaya matahari menjadi energi kimia..."},
23 {"role": "user", "content": "Apa manfaatnya bagi manusia?"},
24]
25
26# Apply template
27formatted = tokenizer.apply_chat_template(
28 messages,
29 tokenize=False,
30 add_generation_prompt=True
31)
32
33print(formatted)
34# Output:
35# System: Kamu adalah asisten AI yang membantu dan ramah.
36#
37# User: Jelaskan tentang fotosintesis
38# Assistant: Fotosintesis adalah proses di mana tumbuhan...
39# User: Apa manfaatnya bagi manusia?
40# Assistant:⚠️ Model belum melalui evaluasi karena status untrained
1# Rule of thumb untuk 29.60M model
2# GPU Memory → Batch size per device
3
4if gpu_memory >= 80: # A100 80GB
5 batch_size = 540
6 gradient_accumulation = 1
7elif gpu_memory >= 40: # A100 40GB
8 batch_size = 270
9 gradient_accumulation = 1
10elif gpu_memory >= 24: # RTX 3090/4090
11 batch_size = 1
12 gradient_accumulation = 1
13
14# Effective batch size = batch_size × gradient_accumulation × num_gpus1# Recommended untuk 29.60M model
2learning_rate = 0.0005 # Base LR
3warmup_ratio = 0.05 # 5% of total steps
4lr_scheduler = "cosine" # atau "linear"
5
6# Learning rate scaling rule:
7# LR ∝ sqrt(batch_size)
8# Untuk batch size 256: LR = 0.0005
9# Untuk batch size 512: LR = 7.07e-041# Prevent gradient explosion
2max_grad_norm = 1.0 # Clip at 1.0
3
4# Monitor gradients
5from torch.nn.utils import clip_grad_norm_
6
7grad_norm = clip_grad_norm_(model.parameters(), max_grad_norm)
8if grad_norm > 10.0:
9 print(f"⚠️ High gradient norm: {grad_norm:.2f}")1# Tips untuk stable training:
2
31. **Warmup**: Mulai dengan LR rendah
42. **Gradient Checkpointing**: Kurangi memory footprint
53. **Mixed Precision**: Gunakan BF16 jika tersedia (lebih stable dari FP16)
64. **Batch Size**: Start small, increase gradually
75. **Monitor**: Track loss, perplexity, gradient norms1# Solusi OOM saat training:
2
3✅ 1. Enable gradient checkpointing
4model.gradient_checkpointing_enable()
5
6✅ 2. Reduce batch size
7per_device_train_batch_size = 1
8
9✅ 3. Increase gradient accumulation
10gradient_accumulation_steps = 32
11
12✅ 4. Use quantization
13load_in_8bit = True # atau load_in_4bit
14
15✅ 5. Reduce sequence length
16max_length = 1024 # Start dengan ini
17
18✅ 6. CPU offloading (jika perlu)
19device_map = "auto"
20offload_folder = "offload"1# Optimasi kecepatan training:
2
3✅ 1. Flash Attention
4config.use_flash_attn = True # 2-3x speedup
5
6✅ 2. Compile model (PyTorch 2.0+)
7model = torch.compile(model, mode="reduce-overhead")
8
9✅ 3. DataLoader optimization
10dataloader = DataLoader(
11 dataset,
12 batch_size=batch_size,
13 num_workers=4, # Parallel data loading
14 pin_memory=True, # Faster GPU transfer
15 prefetch_factor=2
16)
17
18✅ 4. Mixed precision
19use_fp16 = True # atau bf16
20
21✅ 5. Optimize communication (multi-GPU)
22find_unused_parameters = False
23gradient_as_bucket_view = True1# Jika loss menjadi NaN:
2
3✅ 1. Reduce learning rate
4learning_rate = learning_rate * 0.1
5
6✅ 2. Check gradient norms
7clip_grad_norm_(model.parameters(), 1.0)
8
9✅ 3. Use BF16 instead of FP16
10torch_dtype = torch.bfloat16 # Lebih stable
11
12✅ 4. Add epsilon to RMSNorm
13rms_norm_eps = 1e-5 # Increase jika perlu
14
15✅ 5. Check data
16# Pastikan tidak ada inf/nan di dataset
17assert not torch.isnan(input_ids).any()
18assert not torch.isinf(attention_mask).any()1@misc{cacacaca30m,
2 author = {Lyon},
3 title = {Caca-caca-30M: Modern Transformer Architecture with Grouped Query Attention},
4 year = {2026},
5 publisher = {Hugging Face},
6 journal = {Hugging Face Model Hub},
7 howpublished = {\url{https://huggingface.co/Lyon28/caca-30M-untrained}},
8 note = {Untrained model with 29,597,120 parameters}
9}Lyon. (2026). Caca-caca-30M: Modern Transformer Architecture with Grouped
Query Attention [Untrained model]. Hugging Face.
https://huggingface.co/Lyon28/caca-30M-untrainedLyon. "Caca-caca-30M: Modern Transformer Architecture with Grouped Query Attention."
Hugging Face, 2026, huggingface.co/Lyon28/caca-30M-untrained.
| ⭐ Star Repo Show your support | 🔗 Share Tell your friends | 💬 Join Discussion Ask questions | 🤝 Contribute Make it better |
| Metric | Value |
|---|---|
| 💎 Total Parameters | 29,597,120 |
| 🏗️ Layers | 7 |
| 🎯 Attention Heads | 7 |
| 📖 Max Context | 1,024 tokens |
| 💾 Size (FP16) | 0.06 GB |
| 💾 Size (INT4) | 0.01 GB |