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"

NEG not POS 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):

1

Leaves (Input)

Kata-kata diubah jadi vectors

โ†’
2

Internal Nodes

Combine children dengan NN

โ†’
3

Root (Output)

Representasi seluruh tree

๐Ÿ”‘ Key Insight: Parameter Sharing

Semua internal nodes menggunakan weights yang sama:

Shared Parameters:

W (Weight matrix)
b (Bias vector)

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:

hparent = tanh(W ยท [hleft; hright] + b)

Dimana [;] adalah concatenation

๐Ÿงฎ Komponen Model

Input Layer

Word embeddings untuk leaves

hleaf = E[word]

Composition Function

Combine 2 children

f(hโ‚, hโ‚‚) = tanh(W[hโ‚;hโ‚‚] + b)

Output Layer

Classification dari root

y = softmax(Uยทhroot)

๐Ÿ“ 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:

1

Leaf Nodes

Lookup word embeddings

2

Internal Nodes

Compute h = f(h_left, h_right)

3

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

Belajar Lebih Lanjut:

๐Ÿ“š Paper: "Recursive Deep Models for Semantic Compositionality"

๐Ÿ”ฌ Advanced: TreeLSTM, Recursive Autoencoder

๐Ÿ’ป Practice: Implement on Stanford Sentiment Treebank