Tiny Recursive Model
Neural Networks untuk Struktur Tree
๐ณ Apa itu Recursive Model?
Recursive Model adalah jenis neural network yang dirancang khusus untuk memproses data dengan struktur hierarkis atau tree.
Kenapa Perlu Recursive Model?
- โ Bahasa alami memiliki struktur tree (parse trees)
- โ Banyak data real-world berbentuk hierarki
- โ Bisa menangkap komposisi makna
- โ Berbagi parameter di semua node (efficient)
๐ Contoh Sederhana
Bayangkan kalimat: "not very good"
Model memproses dari leaves (kata) ke root, mengkombinasikan makna di setiap level
๐ฏ Apa yang Akan Dipelajari?
Rekursi
Konsep recursion & tree traversal
Model
Arsitektur Tiny Recursive Model
Forward Pass
Bagaimana data mengalir dalam tree
Training
Backpropagation through structure
Konsep Rekursi
Memahami recursion dan tree structures
๐ Apa itu Rekursi?
Rekursi adalah teknik di mana fungsi memanggil dirinya sendiri untuk menyelesaikan masalah yang lebih kecil.
Contoh: Faktorial
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
return n * factorial(n - 1)
# factorial(4) = 4 * factorial(3)
# = 4 * 3 * factorial(2)
# = 4 * 3 * 2 * factorial(1)
# = 4 * 3 * 2 * 1 = 24
๐ฒ Tree Structures
Tree adalah struktur data hierarkis dengan nodes dan edges:
Root
Node paling atas (tidak punya parent)
Leaf
Node yang tidak punya children
Internal Node
Node yang punya children
๐ Tree Traversal
Ada beberapa cara traverse tree:
Pre-order
Root โ Left โ Right
[Root, L1, L2, R1, R2]
Post-order โญ
Left โ Right โ Root
[L1, L2, R1, R2, Root]
Digunakan di Recursive Model!
In-order
Left โ Root โ Right
[L1, Root, L2, R1, R2]
Recursive Neural Networks
Neural networks yang memproses tree structures
๐ง Dari Recursion ke Neural Networks
Bagaimana jika kita terapkan neural network pada tree structure?
Analogi:
Bayangkan setiap node dalam tree adalah sebuah mini neural network yang:
- Menerima input dari children-nya
- Memproses dengan weights & activation
- Menghasilkan output untuk parent-nya
๐๏ธ Ide Dasar
Recursive NN memproses tree dari bottom-up (leaves โ root):
Leaves (Input)
Kata-kata diubah jadi vectors
Internal Nodes
Combine children dengan NN
Root (Output)
Representasi seluruh tree
๐ Key Insight: Parameter Sharing
Semua internal nodes menggunakan weights yang sama:
Keuntungan:
- โ Lebih efisien (parameter sedikit)
- โ Generalisasi lebih baik
- โ Bisa handle tree dengan size berbeda
Tiny Recursive Model
Arsitektur model sederhana
๐ Arsitektur Sederhana
Tiny Recursive Model menggunakan satu layer untuk combine children:
Formula Komputasi Node:
Dimana [;] adalah concatenation
๐งฎ Komponen Model
Input Layer
Word embeddings untuk leaves
Composition Function
Combine 2 children
Output Layer
Classification dari root
๐ Dimensi
Contoh untuk sentiment analysis (positive/negative):
| Component | Dimension | Contoh |
|---|---|---|
| Embedding (d) | 50 | Setiap kata โ vector 50-dim |
| Hidden (h) | 50 | Node representation 50-dim |
| W matrix | 50 ร 100 | Transform [hโ;hโ] (100-dim) โ 50-dim |
| Output classes | 2 | Positive / Negative |
๐จ Visualisasi Arsitektur
Forward Pass
Bagaimana data mengalir dari leaves ke root
โก Proses Forward Pass
Data mengalir bottom-up menggunakan post-order traversal:
Leaf Nodes
Lookup word embeddings
Internal Nodes
Compute h = f(h_left, h_right)
Root Node
Final classification
๐ฌ Animasi Forward Pass
Lihat bagaimana representasi dihitung step-by-step:
๐ Contoh Perhitungan
Kalimat: "very good"
Step 1: Leaf Embeddings
h_very = E["very"] = [0.2, 0.5, -0.3, ...]h_good = E["good"] = [0.8, -0.1, 0.4, ...]
Step 2: Internal Node
concat = [h_very; h_good] = [0.2, 0.5, ..., 0.8, -0.1, ...]h_parent = tanh(W ยท concat + b)h_parent = [0.6, 0.3, -0.2, ...]
Step 3: Classification
y = softmax(U ยท h_parent)y = [0.85, 0.15] โ "Positive" dengan 85% confidence
Training Process
Backpropagation Through Structure
๐ Bagaimana Training Bekerja?
Training menggunakan Backpropagation Through Structure (BPTS):
Forward Pass
Compute representations bottom-up
Loss Calculation
Compare prediction vs label
Backward Pass
Gradient flows top-down
Parameter Update
W, b, E updated dengan gradient
๐ Backpropagation Animation
Lihat bagaimana gradient mengalir dari root ke leaves:
โ๏ธ Training Loop
for epoch in range(num_epochs):
total_loss = 0
for tree, label in training_data:
# Forward pass
h_root = forward_pass(tree)
prediction = softmax(U @ h_root)
# Compute loss
loss = cross_entropy(prediction, label)
total_loss += loss
# Backward pass
gradients = backprop(tree, loss)
# Update parameters
W -= learning_rate * gradients['W']
b -= learning_rate * gradients['b']
E -= learning_rate * gradients['E']
print(f"Epoch {epoch}: Loss = {total_loss}")
๐ Training Progress Visualization
Implementasi & Contoh
Dari konsep ke code
๐ป Implementasi PyTorch
Tiny Recursive Model Class:
import torch
import torch.nn as nn
class TinyRecursiveModel(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes):
super().__init__()
# Word embeddings
self.embedding = nn.Embedding(vocab_size, embed_dim)
# Composition function
self.W = nn.Linear(2 * hidden_dim, hidden_dim)
# Output classifier
self.classifier = nn.Linear(hidden_dim, num_classes)
def forward_node(self, node):
"""Recursive forward pass"""
if node.is_leaf():
# Leaf: return word embedding
return self.embedding(node.word_id)
else:
# Internal: combine children
h_left = self.forward_node(node.left)
h_right = self.forward_node(node.right)
# Concatenate and transform
h_concat = torch.cat([h_left, h_right], dim=0)
h_parent = torch.tanh(self.W(h_concat))
return h_parent
def forward(self, tree):
"""Process entire tree"""
h_root = self.forward_node(tree.root)
logits = self.classifier(h_root)
return logits
๐ณ Use Cases
Sentiment Analysis
Klasifikasi sentimen dari parse tree kalimat
"not very good" โ Negative
Semantic Composition
Memahami makna komposisional
"red car" vs "car that is red"
Question Answering
Memproses struktur pertanyaan
Parse tree untuk complex questions
Image Segmentation
Hierarchical scene parsing
Object decomposition trees
๐ฏ Interactive Demo
Build tree Anda sendiri dan lihat hasilnya:
Build Your Tree:
๐ Selamat!
Anda telah menyelesaikan tutorial Tiny Recursive Model!
Yang Telah Dipelajari:
- โ Konsep recursion dan tree structures
- โ Recursive Neural Networks
- โ Tiny Recursive Model architecture
- โ Forward pass computation
- โ Backpropagation through structure
- โ Implementasi PyTorch