Girinath11 commited on
Commit
bf4aef4
Β·
verified Β·
1 Parent(s): c2d453b

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +355 -336
README.md CHANGED
@@ -1,5 +1,6 @@
1
  ---
2
- language: en
 
3
  license: mit
4
  tags:
5
  - text-generation
@@ -8,87 +9,80 @@ tags:
8
  - recursive-language-model
9
  - mixture-of-recursion
10
  - adaptive-computation
11
- - rotary-embeddings
12
  - perplexity-routing
 
13
  datasets:
14
  - Anthropic/hh-rlhf
15
- - OpenAssistant/oasst2
16
  - stingning/ultrachat
17
  metrics:
18
  - perplexity
19
  library_name: transformers
20
  pipeline_tag: text-generation
 
21
  ---
22
 
23
- # Recursive Language Model - 90M (Mixture of Recursion)
24
 
25
- A transformer-based conversational language model with **Mixture of Recursion** architecture featuring adaptive recursive processing, perplexity-based dynamic routing, and rotary positional embeddings (RoPE) for enhanced dialogue generation.
26
 
27
- ## Model Description
28
 
29
- This model implements a novel **Mixture of Recursion** architecture that dynamically determines the optimal number of recursive refinement passes based on **sample perplexity** during training. Unlike standard transformers that process all inputs uniformly, this model intelligently allocates computational resources based on actual difficulty.
30
 
31
- ### Key Innovations
32
 
33
- - 🧠 **Perplexity-Based Router**: Learns complexity from model's actual performance, not manual labels
34
- - πŸ”„ **Adaptive Recursion**: 1, 3, or 5 recursive transformer passes based on sample difficulty
35
- - πŸŒ€ **Rotary Positional Embeddings (RoPE)**: Superior positional encoding with better length generalization
36
- - ⚑ **Dynamic Computation**: Efficient processing that adapts to input difficulty
37
- - 🎯 **Self-Supervised Learning**: Router trained on model's own perplexity signals
38
- - πŸ“Š **Multi-Source Training**: Trained on diverse, high-quality conversational data from Anthropic, OpenAssistant, and UltraChat
39
 
40
- ### Architecture Philosophy
41
 
42
- Traditional transformers apply the same computational depth to all inputs. This model recognizes that some sequences (simple greetings, common phrases) need minimal processing, while others (complex reasoning, technical explanations) benefit from deeper iterative refinement. The router learns to make this decision automatically by observing which samples the model finds difficult (high perplexity = more thinking needed).
43
 
44
- ## Quick Start
 
 
45
 
46
- ### Installation
47
- ```bash
48
- pip install transformers torch
 
 
49
  ```
50
 
51
- ### Basic Usage
52
- ```python
53
- from transformers import AutoModelForCausalLM, AutoTokenizer
54
- import torch
55
 
56
- # Load model and tokenizer
57
- model = AutoModelForCausalLM.from_pretrained(
58
- "Girinath11/recursive-language-model-90m",
59
- trust_remote_code=True
60
- )
61
- tokenizer = AutoTokenizer.from_pretrained(
62
- "Girinath11/recursive-language-model-90m"
63
- )
64
 
65
- # Move to GPU if available
66
- device = "cuda" if torch.cuda.is_available() else "cpu"
67
- model = model.to(device)
68
- model.eval()
69
 
70
- print("βœ… Model loaded successfully!")
71
- print(f"Parameters: {model.num_parameters():,}")
 
 
 
 
72
 
73
- # Generate text (conversational format)
74
- prompt = "<|user|>\nWhat is artificial intelligence?\n<|assistant|>\n"
75
- inputs = tokenizer(prompt, return_tensors="pt").to(device)
76
-
77
- outputs = model.generate(
78
- **inputs,
79
- max_new_tokens=100,
80
- temperature=0.8,
81
- top_p=0.9,
82
- do_sample=True,
83
- pad_token_id=tokenizer.eos_token_id
84
- )
85
 
86
- print(tokenizer.decode(outputs[0], skip_special_tokens=True))
 
87
  ```
88
 
89
- ## Model Architecture
 
 
 
 
 
 
 
 
90
 
91
- ### Detailed Architecture Specifications
92
 
93
  | Component | Configuration |
94
  |-----------|--------------|
@@ -101,68 +95,165 @@ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
101
  | **FFN Intermediate Size** | 2240 |
102
  | **Max Sequence Length** | 512 tokens |
103
  | **Positional Encoding** | Rotary Positional Embeddings (RoPE) |
104
- | **Dropout Rate** | 0.1 (both hidden and attention) |
105
- | **Layer Normalization** | eps=1e-5 |
106
 
107
  ### Recursion Configuration
108
 
109
- | Complexity Class | Perplexity Range | Recursion Steps | Use Case |
110
- |-----------------|------------------|-----------------|----------|
111
- | **Simple** | < 20 | 1 step | Easy samples model is confident about |
112
- | **Medium** | 20-50 | 3 steps | Moderate difficulty samples |
113
- | **Complex** | > 50 | 5 steps | Hard samples requiring deep reasoning |
114
-
115
- **Note:** Complexity labels are automatically generated during training based on the model's own perplexity on each sample, enabling self-supervised curriculum learning.
116
 
117
  ### Architecture Components
118
 
119
- 1. **Embedding Layer** (~28.1M params)
120
- - Token embeddings (50,259 Γ— 560)
121
  - Special tokens: `<|user|>`, `<|assistant|>`, `<|endoftext|>`
122
- - Padding token handling (ID: 50256)
123
 
124
- 2. **Base Transformer Stack** (8 layers, ~30.5M params)
125
  - Multi-head self-attention with RoPE
126
  - Feed-forward networks (560 β†’ 2240 β†’ 560)
127
  - Pre-normalization with LayerNorm
128
  - Residual connections
129
- - Causal masking for autoregressive generation
130
 
131
  3. **Perplexity-Based Router** (~0.4M params)
132
- - Attention-weighted pooling over sequence
133
  - 2-layer MLP classifier (560 β†’ 280 β†’ 3)
134
- - Trained on pseudo-labels derived from sample perplexity
135
  - Outputs: complexity class (0=simple, 1=medium, 2=complex)
136
 
137
  4. **Recursive Refinement Layer** (~3.8M params)
138
- - Additional transformer block (reused 1-5 times)
139
  - Same architecture as base layers
140
- - Applied iteratively based on router decision
141
 
142
- 5. **Output Projection Head**
 
143
  - Linear layer (560 β†’ 50,259)
144
- - Final LayerNorm before projection
145
 
146
- ### Rotary Positional Embeddings
147
 
148
- Uses RoPE instead of learned positional embeddings for:
149
- - Better extrapolation to longer sequences
150
- - Relative position encoding
151
- - Improved performance on positional tasks
152
- - Base frequency: 10,000
153
 
154
- ## Training Details
 
 
 
155
 
156
- ### Training Dataset
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
- **Total Training Samples: 100,000** (premium conversational data, streaming mode)
 
 
159
 
160
- | Dataset | Source | Percentage | Samples | Description |
161
- |---------|--------|-----------|---------|-------------|
162
- | **Anthropic HH-RLHF** | Anthropic | 30% | ~30,000 | Claude-style helpful, harmless responses |
163
- | **OpenAssistant** | LAION | 40% | ~40,000 | Human feedback-curated conversations |
164
- | **UltraChat** | Tsinghua | 30% | ~30,000 | GPT-4 generated multi-turn dialogues |
165
- | **Validation** | Mixed | - | 1,000 | Held-out samples from all sources |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
  **Data Format:**
168
  ```
@@ -173,354 +264,282 @@ Assistant response here
173
  <|endoftext|>
174
  ```
175
 
176
- **Filtering Criteria:**
177
- - Minimum sequence length: 50 tokens
178
- - Maximum sequence length: 512 tokens
179
- - Streaming mode: Memory-efficient loading
 
 
 
180
 
181
  ### Training Configuration
182
  ```yaml
183
  Hardware:
184
  GPU: NVIDIA Tesla T4 (15.64 GB)
185
  Platform: Kaggle
186
- Framework: PyTorch with CUDA
 
187
 
188
  Hyperparameters:
189
  Batch Size: 8
190
  Gradient Accumulation: 8
191
  Effective Batch Size: 64
192
- Learning Rate: 2.5e-4
 
193
  Optimizer: AdamW
194
  Weight Decay: 0.01
195
- LR Schedule: Cosine Annealing
196
- Max Gradient Norm: 1.0
 
197
  Total Epochs: 3
198
- Max Sequence Length: 512 tokens
199
 
200
  Loss Function:
201
- Language Modeling: CrossEntropyLoss (ignore_index=-100)
202
  Router Loss: CrossEntropyLoss (weight: 0.1)
203
- Total Loss: LM Loss + 0.1 Γ— Router Loss
204
 
205
  Regularization:
206
  Hidden Dropout: 0.1
207
  Attention Dropout: 0.1
208
- Memory Management: Aggressive cleanup every 50 steps
209
  ```
210
 
211
  ### Training Schedule
212
 
213
- - **Total Training Steps:** 37,500 (12,500 per epoch)
214
- - **Steps per Epoch:** 12,500
215
- - **Evaluation Frequency:** After each epoch (50 batches)
216
- - **Checkpoint Saving:** After each epoch + best model
217
-
218
- ### Training Time
219
-
220
- - **Total Duration:** ~9 hours 17 minutes
221
- - **Epoch 1:** 3 hours 4 minutes
222
- - **Epoch 2:** 3 hours 8 minutes
223
- - **Epoch 3:** 3 hours 4 minutes
224
- - **Training Speed:** ~1.10-1.13 it/s
225
 
226
  ### Training Progression
227
 
228
- | Epoch | Training Loss | Eval Loss | Eval Perplexity | Status |
229
- |-------|--------------|-----------|-----------------|---------|
230
- | **1** | 3.6207 | 3.3350 | **28.08** | πŸ”₯ **BEST!** |
231
- | **2** | 3.9455 | 3.7622 | 43.04 | - |
232
- | **3** | 3.0986 | 4.3018 | 73.84 | - |
233
-
234
- **Best Model:** Epoch 1 (Perplexity: 28.08)
235
- **Loss Improvement:** Strong initial learning, later epochs showed overfitting
236
 
237
- ## Performance Metrics
 
 
 
 
238
 
239
- ### Final Evaluation Results
240
- ```
241
- πŸ“ŠMODEL METRICS:
242
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
243
- βœ“ Evaluation Loss: 3.34
244
- βœ“ Perplexity: 28.08
245
- βœ“ Training Loss: 3.62
246
- βœ“ Total Samples Seen: 100,000
247
- βœ“ Training Time: ~9.2 hours
248
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
249
- ```
250
-
251
- ### Generation Quality
252
-
253
- **Perplexity: 28.08** indicates **excellent quality** for a 90M parameter model:
254
-
255
- - βœ… Generates coherent and contextually appropriate responses
256
- - βœ… Maintains conversation context over multiple turns
257
- - βœ… Produces diverse and natural-sounding outputs
258
- - βœ… Handles various conversational styles and topics
259
- - βœ… Suitable for chatbots, dialogue systems, and creative applications
260
- - βœ… Comparable to GPT-2 Small (117M) in quality
261
- - ⚠️ May show repetition in very long conversations (500+ tokens)
262
- - ⚠️ Limited factual knowledge (trained on 100K samples)
263
- - ⚠️ Context window limited to 512 tokens
264
-
265
- ### Memory Requirements
266
 
267
- | Mode | RAM/VRAM | Disk Space |
268
- |------|----------|------------|
269
- | **Model Weights** | - | 346 MB |
270
- | **CPU Inference** | ~1.2 GB | - |
271
- | **GPU Inference (FP32)** | ~2.5 GB | - |
272
- | **GPU Inference (FP16)** | ~1.5 GB | - |
273
- | **GPU Training (batch=8)** | ~8-10 GB | - |
274
 
275
- ## Advanced Usage
 
 
276
 
277
- ### Conversational Generation
278
  ```python
279
- import torch
280
- from transformers import AutoModelForCausalLM, AutoTokenizer
281
 
282
- model = AutoModelForCausalLM.from_pretrained(
283
- "Girinath11/recursive-language-model-90m",
284
- trust_remote_code=True
285
- )
286
- tokenizer = AutoTokenizer.from_pretrained(
287
- "Girinath11/recursive-language-model-90m"
288
- )
289
 
290
- device = "cuda" if torch.cuda.is_available() else "cpu"
291
- model = model.to(device)
292
- model.eval()
293
 
294
- # Multi-turn conversation
295
- conversation = """<|user|>
296
- Hello! Can you help me understand machine learning?
297
- <|assistant|>
298
- """
299
 
300
- inputs = tokenizer(conversation, return_tensors="pt").to(device)
301
- outputs = model.generate(
302
- **inputs,
303
- max_new_tokens=150,
304
- temperature=0.8,
305
- top_p=0.9,
306
- do_sample=True,
307
- pad_token_id=tokenizer.eos_token_id
308
- )
309
 
310
- print(tokenizer.decode(outputs[0]))
311
- ```
 
 
 
312
 
313
- ### Temperature Control
314
- ```python
315
- # Creative/diverse responses (high temperature)
316
- creative = model.generate(
317
- **inputs,
318
- max_new_tokens=100,
319
- temperature=1.0, # More random
320
- top_p=0.95,
321
- do_sample=True
322
- )
323
 
324
- # Focused/deterministic responses (low temperature)
325
- focused = model.generate(
326
- **inputs,
327
- max_new_tokens=100,
328
- temperature=0.5, # More focused
329
- top_p=0.9,
330
- do_sample=True
331
- )
332
 
333
- # Greedy decoding (most likely)
334
- greedy = model.generate(
335
- **inputs,
336
- max_new_tokens=50,
337
- do_sample=False # Deterministic
338
- )
339
- ```
340
 
341
- ## Technical Architecture
342
 
343
- ### Model Structure
344
- ```
345
- Input Text
346
- ↓
347
- [Token Embedding Layer] (50,259 Γ— 560)
348
- ↓
349
- [8Γ— Base Transformer Blocks]
350
- β”œβ”€ Multi-Head Attention (8 heads, RoPE)
351
- β”œβ”€ Feed-Forward Network (560 β†’ 2240 β†’ 560)
352
- └─ LayerNorm + Residual Connections
353
- ↓
354
- [Perplexity-Based Router]
355
- β”œβ”€ Attention-Weighted Pooling
356
- β”œβ”€ MLP Classifier (560 β†’ 280 οΏ½οΏ½ 3)
357
- └─ Output: Complexity from Perplexity
358
- ↓
359
- [Adaptive Recursive Refinement]
360
- β”œβ”€ Simple (PPL<20): 1Γ— Recursion Layer
361
- β”œβ”€ Medium (PPL 20-50): 3Γ— Recursion Layer
362
- └─ Complex (PPL>50): 5Γ— Recursion Layer
363
- ↓
364
- [Final LayerNorm]
365
- ↓
366
- [LM Head] (560 β†’ 50,259)
367
- ↓
368
- Output Tokens
369
- ```
370
 
371
- ### Perplexity-Based Routing Innovation
 
 
 
 
 
372
 
373
- **Key Idea:** Instead of manually labeling samples as "simple" or "complex", the model learns from its own difficulty:
374
- ```python
375
- # During training:
376
- 1. Model predicts next tokens β†’ calculates loss
377
- 2. High loss = High perplexity = Hard sample β†’ Router learns to use 5 steps
378
- 3. Low loss = Low perplexity = Easy sample β†’ Router learns to use 1 step
379
 
380
- # Pseudo-label generation:
381
- if sample_perplexity < 20:
382
- label = 0 # Simple: model is confident
383
- elif sample_perplexity < 50:
384
- label = 1 # Medium: model is uncertain
385
- else:
386
- label = 2 # Complex: model is struggling
387
- ```
388
-
389
- **Benefits:**
390
- - βœ… No manual labeling required
391
- - βœ… Adapts as model learns (curriculum learning)
392
- - βœ… Objective measure of difficulty
393
- - βœ… Efficient computation allocation
394
 
395
- ## Limitations & Considerations
396
 
397
  ### Technical Limitations
398
 
399
- 1. **Context Window**: 512 token maximum
400
- 2. **Model Size**: 90M parameters - limited capacity vs billion-scale models
401
- 3. **Training Data**: 100K samples (streaming mode)
402
- 4. **Single Language**: Primarily English
403
- 5. **Domain Coverage**: Conversational data only
404
- 6. **Reasoning**: Basic dialogue, limited multi-step reasoning
405
 
406
  ### Known Issues
407
 
408
- - **Repetition**: May repeat phrases in very long generations (500+ tokens)
409
- - **Factual Knowledge**: Limited knowledge base (100K training samples)
410
- - **Consistency**: May occasionally lose context in very long conversations
411
- - **Overfitting**: Epochs 2-3 showed increased eval perplexity
412
- - **Early Stopping**: Best model from Epoch 1
413
 
414
- ## Ethical Considerations
 
 
 
 
 
 
 
415
 
416
  ### Bias & Fairness
417
 
418
  This model may exhibit biases from training data:
419
 
420
  **Potential Biases:**
421
- - Conversational style: Reflects training data distributions
422
- - Language: English-centric (GPT-2 tokenizer)
423
- - Content: Biases from Anthropic HH, OpenAssistant, UltraChat
 
424
 
425
  **Mitigation:**
426
- - Diverse multi-source training data
427
- - Best practices from source datasets (Anthropic HH-RLHF includes harmlessness training)
 
428
 
429
  ### Responsible Use
430
 
431
- **βœ… Recommended:**
432
- - Educational chatbot demos
433
- - Research on adaptive computation
434
- - Creative writing assistance
435
- - Conversational AI prototyping
436
- - Learning about language models
437
 
438
- **❌ Not Recommended:**
439
- - Production chatbots without human oversight
440
- - Medical, legal, or financial advice
441
- - Generating authoritative factual content
442
- - Automated content moderation
443
- - Safety-critical systems
444
-
445
- ## Comparison with Similar Models
446
-
447
- | Model | Params | Perplexity | Architecture | Training Data |
448
- |-------|--------|------------|--------------|---------------|
449
- | **This Model** | **90M** | **28.08** | **Mixture of Recursion** | **100K conversations** |
450
- | GPT-2 Small | 117M | ~29 | Standard Transformer | WebText (40GB) |
451
- | DistilGPT-2 | 82M | ~35 | Distilled GPT-2 | Distillation |
452
- | DialoGPT Small | 117M | ~30 | GPT-2 + Reddit | Reddit comments |
453
-
454
- **Advantages:**
455
- - βœ… Competitive perplexity with fewer parameters
456
- - βœ… Novel adaptive architecture
457
- - βœ… Conversational training data
458
- - βœ… Perplexity-based intelligent routing
459
 
460
- **Trade-offs:**
461
- - ⚠️ Smaller training dataset
462
- - ⚠️ Limited context window (512 vs 1024+)
463
- - ⚠️ Less knowledge breadth
464
 
465
- ## Model Card
 
 
 
 
 
 
466
 
467
  ### Intended Use
468
 
469
  **Primary Use Cases:**
470
- - πŸ“š **Education**: Teaching adaptive computation
471
- - πŸ”¬ **Research**: Experimenting with mixture of recursion
472
- - πŸ€– **Chatbots**: Dialogue system prototyping
473
- - πŸ’‘ **Learning**: Understanding perplexity-based routing
474
-
475
- ### Training Information
476
 
477
- - **Trained by:** Girinath11
478
- - **Training date:** February 2026
479
- - **Training platform:** Kaggle (T4 GPU)
480
- - **Training duration:** ~9.2 hours
481
- - **Framework:** PyTorch + Transformers
482
 
483
  ### Evaluation Methodology
484
 
485
  **Metrics:**
486
- - Primary: Perplexity on validation set (1,000 samples)
487
- - Evaluated after each epoch (50 validation batches)
488
- - Best model selection: Minimum perplexity
489
 
490
  **Evaluation Data:**
491
- - Mixed samples from all three training sources
492
  - Same preprocessing as training
493
  - No overlap with training data
494
 
495
- ## Citation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
  ```bibtex
497
  @misc{recursive-lm-90m-2026,
498
  author = {Girinath11},
499
- title = {Recursive Language Model with Perplexity-Based Routing},
500
  year = {2026},
501
  publisher = {Hugging Face},
502
- howpublished = {\url{https://huggingface.co/Girinath11/recursive-language-model-90m}}
 
503
  }
504
  ```
505
 
506
- ## Acknowledgments
507
 
508
  - **Anthropic** for HH-RLHF dataset
509
- - **LAION** for OpenAssistant dataset
510
  - **Tsinghua University** for UltraChat dataset
511
  - **Hugging Face** for Transformers library
512
  - **Kaggle** for free GPU access
 
513
 
514
- ## License
515
 
516
- MIT License - Free to use with attribution
 
 
 
 
 
 
 
517
 
518
- ## Contact
 
 
519
 
520
- For questions or issues, please open an issue on the model repository.
 
 
521
 
522
  ---
523
 
524
- **Model Version:** 1.0
525
- **Last Updated:** February 2026
526
- **Status:** Production-ready for research and prototyping
 
1
  ---
2
+ language:
3
+ - en
4
  license: mit
5
  tags:
6
  - text-generation
 
9
  - recursive-language-model
10
  - mixture-of-recursion
11
  - adaptive-computation
 
12
  - perplexity-routing
13
+ - self-supervised-learning
14
  datasets:
15
  - Anthropic/hh-rlhf
 
16
  - stingning/ultrachat
17
  metrics:
18
  - perplexity
19
  library_name: transformers
20
  pipeline_tag: text-generation
21
+ base_model: gpt2
22
  ---
23
 
24
+ # Recursive Language Model - 90M (Adaptive Computation)
25
 
26
+ A novel 90M parameter conversational language model featuring **adaptive recursive computation** through perplexity-based dynamic routing. Achieves better performance than GPT-2 Small (117M) with 30% fewer parameters.
27
 
28
+ ## πŸ† Key Achievement
29
 
30
+ **Perplexity: 17.45** - Outperforms GPT-2 Small (29 perplexity) despite being significantly smaller.
31
 
32
+ ## πŸ”₯ Innovation
33
 
34
+ This model introduces a **self-supervised curriculum learning** approach where the model learns to allocate computation based on sample difficulty without any manual labeling.
 
 
 
 
 
35
 
36
+ ### Novel Architecture: Mixture of Recursion
37
 
38
+ Instead of applying uniform computation to all inputs, this model features:
39
 
40
+ - **Perplexity-Based Router**: Neural classifier that learns sample difficulty from the model's own confidence
41
+ - **Adaptive Recursion**: Dynamically allocates 1, 3, or 5 recursive transformer passes based on input complexity
42
+ - **Self-Supervised Learning**: No manual labels - the model learns what's "hard" from its own perplexity signals
43
 
44
+ ### How It Works
45
+ ```
46
+ High Perplexity (>50) β†’ Model struggling β†’ Use 5 recursion steps
47
+ Medium Perplexity (20-50) β†’ Moderate difficulty β†’ Use 3 steps
48
+ Low Perplexity (<20) β†’ Model confident β†’ Use 1 step (efficient!)
49
  ```
50
 
51
+ This enables **intelligent compute allocation** - simple inputs get fast processing, complex inputs get deeper reasoning.
 
 
 
52
 
53
+ ## πŸ“Š Performance
 
 
 
 
 
 
 
54
 
55
+ ### Benchmark Comparison
 
 
 
56
 
57
+ | Model | Parameters | Perplexity | Notes |
58
+ |-------|-----------|------------|-------|
59
+ | **This Model** | **90.7M** | **17.45** | **Novel adaptive architecture** |
60
+ | GPT-2 Small | 117M | ~29 | Baseline comparison |
61
+ | GPT-2 Medium | 345M | ~22 | 3.8Γ— larger |
62
+ | Random Baseline | - | ~50,000 | Theoretical worst |
63
 
64
+ ### Training Metrics
65
+ ```
66
+ πŸ“ˆ Training Progression:
67
+ Epoch 1: 35.39 perplexity
68
+ Epoch 2: 20.27 perplexity (43% improvement)
69
+ Epoch 3: 17.45 perplexity (51% total improvement)
 
 
 
 
 
 
70
 
71
+ πŸ“‰ Loss Reduction:
72
+ Start: 4.50 β†’ Final: 2.86 (36% reduction)
73
  ```
74
 
75
+ ### Performance Highlights
76
+
77
+ βœ… **17.45 perplexity** on validation set (37K samples)
78
+ βœ… **Better than GPT-2 Small** with 30% fewer parameters
79
+ βœ… **Efficient inference** - adaptive computation saves resources
80
+ βœ… **84 minutes training** on single T4 GPU
81
+ βœ… **Novel architecture** - not just fine-tuning
82
+
83
+ ## 🎯 Model Architecture
84
 
85
+ ### Specifications
86
 
87
  | Component | Configuration |
88
  |-----------|--------------|
 
95
  | **FFN Intermediate Size** | 2240 |
96
  | **Max Sequence Length** | 512 tokens |
97
  | **Positional Encoding** | Rotary Positional Embeddings (RoPE) |
98
+ | **Dropout Rate** | 0.1 (hidden & attention) |
 
99
 
100
  ### Recursion Configuration
101
 
102
+ | Complexity Level | Perplexity Range | Steps | Use Case |
103
+ |-----------------|------------------|-------|----------|
104
+ | **Simple** | < 20 | 1 step | Model is confident |
105
+ | **Medium** | 20-50 | 3 steps | Moderate difficulty |
106
+ | **Complex** | > 50 | 5 steps | Model struggling, needs deep reasoning |
 
 
107
 
108
  ### Architecture Components
109
 
110
+ 1. **Token Embedding Layer** (50,259 Γ— 560)
 
111
  - Special tokens: `<|user|>`, `<|assistant|>`, `<|endoftext|>`
 
112
 
113
+ 2. **Base Transformer Stack** (8 layers)
114
  - Multi-head self-attention with RoPE
115
  - Feed-forward networks (560 β†’ 2240 β†’ 560)
116
  - Pre-normalization with LayerNorm
117
  - Residual connections
 
118
 
119
  3. **Perplexity-Based Router** (~0.4M params)
120
+ - Attention-weighted sequence pooling
121
  - 2-layer MLP classifier (560 β†’ 280 β†’ 3)
122
+ - Trained on pseudo-labels from sample perplexity
123
  - Outputs: complexity class (0=simple, 1=medium, 2=complex)
124
 
125
  4. **Recursive Refinement Layer** (~3.8M params)
126
+ - Transformer block applied 1-5 times adaptively
127
  - Same architecture as base layers
128
+ - Reused weights for parameter efficiency
129
 
130
+ 5. **Output Projection**
131
+ - Final LayerNorm
132
  - Linear layer (560 β†’ 50,259)
 
133
 
134
+ ## πŸš€ Quick Start
135
 
136
+ ### Installation
137
+ ```bash
138
+ pip install transformers torch
139
+ ```
 
140
 
141
+ ### Basic Usage
142
+ ```python
143
+ from transformers import AutoModelForCausalLM, AutoTokenizer
144
+ import torch
145
 
146
+ # Load model and tokenizer
147
+ model = AutoModelForCausalLM.from_pretrained(
148
+ "Girinath11/recursive-language-model-90m",
149
+ trust_remote_code=True
150
+ )
151
+ tokenizer = AutoTokenizer.from_pretrained(
152
+ "Girinath11/recursive-language-model-90m"
153
+ )
154
+
155
+ # Move to GPU if available
156
+ device = "cuda" if torch.cuda.is_available() else "cpu"
157
+ model = model.to(device)
158
+ model.eval()
159
 
160
+ print(f"βœ… Model loaded on {device}")
161
+ print(f"πŸ“Š Parameters: {model.num_parameters():,}")
162
+ ```
163
 
164
+ ### Conversational Format
165
+ ```python
166
+ # Model expects this format
167
+ prompt = """<|user|>
168
+ What is machine learning?
169
+ <|assistant|>
170
+ """
171
+
172
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
173
+
174
+ # Generate response
175
+ with torch.no_grad():
176
+ outputs = model.generate(
177
+ **inputs,
178
+ max_new_tokens=100,
179
+ temperature=0.7,
180
+ top_p=0.9,
181
+ do_sample=True,
182
+ pad_token_id=tokenizer.eos_token_id
183
+ )
184
+
185
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
186
+ print(response)
187
+ ```
188
+
189
+ ### Batch Generation
190
+ ```python
191
+ prompts = [
192
+ "<|user|>\nExplain quantum computing simply.\n<|assistant|>\n",
193
+ "<|user|>\nWrite a haiku about AI.\n<|assistant|>\n",
194
+ "<|user|>\nHow do neural networks work?\n<|assistant|>\n"
195
+ ]
196
+
197
+ # Tokenize all prompts
198
+ inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(device)
199
+
200
+ # Generate for all at once
201
+ with torch.no_grad():
202
+ outputs = model.generate(
203
+ **inputs,
204
+ max_new_tokens=80,
205
+ temperature=0.8,
206
+ top_p=0.9,
207
+ do_sample=True,
208
+ pad_token_id=tokenizer.eos_token_id
209
+ )
210
+
211
+ # Decode all outputs
212
+ for i, output in enumerate(outputs):
213
+ text = tokenizer.decode(output, skip_special_tokens=True)
214
+ print(f"\nPrompt {i+1}:\n{text}\n{'-'*60}")
215
+ ```
216
+
217
+ ### Generation Parameters
218
+ ```python
219
+ # Creative writing (high temperature)
220
+ creative_output = model.generate(
221
+ **inputs,
222
+ max_new_tokens=150,
223
+ temperature=1.0, # More random/creative
224
+ top_p=0.95,
225
+ top_k=50,
226
+ do_sample=True
227
+ )
228
+
229
+ # Focused/deterministic (low temperature)
230
+ focused_output = model.generate(
231
+ **inputs,
232
+ max_new_tokens=100,
233
+ temperature=0.5, # More focused
234
+ top_p=0.9,
235
+ do_sample=True
236
+ )
237
+
238
+ # Greedy decoding (most likely tokens)
239
+ greedy_output = model.generate(
240
+ **inputs,
241
+ max_new_tokens=50,
242
+ do_sample=False # Deterministic
243
+ )
244
+ ```
245
+
246
+ ## πŸ“š Training Details
247
+
248
+ ### Dataset
249
+
250
+ **Total Training Samples: 37,119** (high-quality conversational data)
251
+
252
+ | Dataset | Source | Samples | Percentage | Description |
253
+ |---------|--------|---------|------------|-------------|
254
+ | **Anthropic HH-RLHF** | Anthropic | 30,000 | 81% | Claude-style helpful & harmless responses |
255
+ | **UltraChat** | Tsinghua | 7,119 | 19% | GPT-4 generated multi-turn dialogues |
256
+ | **Validation** | Mixed | 2,000 | - | Held-out samples for evaluation |
257
 
258
  **Data Format:**
259
  ```
 
264
  <|endoftext|>
265
  ```
266
 
267
+ **Quality Control:**
268
+ - Minimum length: 80 characters
269
+ - Maximum length: 6,000 characters
270
+ - Minimum word count: 15 words
271
+ - Alphanumeric ratio: >65%
272
+ - Required: Proper punctuation
273
+ - Validation: Strict conversation structure
274
 
275
  ### Training Configuration
276
  ```yaml
277
  Hardware:
278
  GPU: NVIDIA Tesla T4 (15.64 GB)
279
  Platform: Kaggle
280
+ Framework: PyTorch + Transformers
281
+ Mixed Precision: FP16 (AMP)
282
 
283
  Hyperparameters:
284
  Batch Size: 8
285
  Gradient Accumulation: 8
286
  Effective Batch Size: 64
287
+ Max Sequence Length: 512
288
+ Learning Rate: 3e-4
289
  Optimizer: AdamW
290
  Weight Decay: 0.01
291
+ LR Schedule: OneCycleLR
292
+ Warmup: 10% of total steps
293
+ Gradient Clipping: 1.0
294
  Total Epochs: 3
295
+ Total Steps: 13,917
296
 
297
  Loss Function:
298
+ Language Modeling: CrossEntropyLoss
299
  Router Loss: CrossEntropyLoss (weight: 0.1)
300
+ Total: LM Loss + 0.1 Γ— Router Loss
301
 
302
  Regularization:
303
  Hidden Dropout: 0.1
304
  Attention Dropout: 0.1
 
305
  ```
306
 
307
  ### Training Schedule
308
 
309
+ - **Total Training Time:** 84 minutes (~1.4 hours)
310
+ - **Steps per Epoch:** 4,639
311
+ - **Training Speed:** ~2.7 it/s
312
+ - **GPU Utilization:** ~85-90%
313
+ - **Memory Usage:** ~8-9 GB (peak)
 
 
 
 
 
 
 
314
 
315
  ### Training Progression
316
 
317
+ | Epoch | Train Loss | Eval Loss | Perplexity | Status |
318
+ |-------|-----------|-----------|------------|---------|
319
+ | **1** | 4.4979 | 3.5665 | 35.39 | Initial learning |
320
+ | **2** | 3.2960 | 3.0091 | 20.27 | Rapid improvement |
321
+ | **3** | 2.8572 | 2.8595 | **17.45** | πŸ”₯ **BEST!** |
 
 
 
322
 
323
+ **Key Observations:**
324
+ - Loss decreased steadily across all epochs
325
+ - No overfitting (train/eval losses converged)
326
+ - 51% perplexity improvement from Epoch 1 to 3
327
+ - Stable training with consistent iteration speed
328
 
329
+ ## πŸ’‘ Technical Innovation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
 
331
+ ### Perplexity-Based Routing (Novel Contribution)
 
 
 
 
 
 
332
 
333
+ Traditional transformers apply the same computational depth to all inputs. This model recognizes that:
334
+ - **Simple inputs** (greetings, common phrases) need minimal processing
335
+ - **Complex inputs** (reasoning, technical content) benefit from deeper iterative refinement
336
 
337
+ **Key Innovation:** Instead of manual labeling, the model learns complexity from its own performance:
338
  ```python
339
+ # During training:
340
+ sample_perplexity = exp(sample_loss)
341
 
342
+ if sample_perplexity < 20:
343
+ label = 0 # Simple - model is confident
344
+ elif sample_perplexity < 50:
345
+ label = 1 # Medium - model is uncertain
346
+ else:
347
+ label = 2 # Complex - model struggling
 
348
 
349
+ # Router learns to predict this from input features
350
+ router_loss = CrossEntropyLoss(router_logits, label)
351
+ ```
352
 
353
+ **Benefits:**
354
+ - βœ… **No manual labeling required** - fully self-supervised
355
+ - βœ… **Adapts as model learns** - curriculum learning
356
+ - βœ… **Objective measure** - based on actual model performance
357
+ - βœ… **Efficient computation** - allocates resources intelligently
358
 
359
+ ### Rotary Positional Embeddings (RoPE)
 
 
 
 
 
 
 
 
360
 
361
+ Uses RoPE instead of learned positional embeddings:
362
+ - Better extrapolation to longer sequences
363
+ - Relative position awareness
364
+ - Improved performance on positional tasks
365
+ - No learned position parameters
366
 
367
+ ### Self-Supervised Curriculum Learning
 
 
 
 
 
 
 
 
 
368
 
369
+ The model implements automatic curriculum learning:
370
+ 1. **Early training**: Most samples are "complex" (high perplexity)
371
+ 2. **Mid training**: Distribution shifts as model learns
372
+ 3. **Late training**: More samples become "simple" (low perplexity)
 
 
 
 
373
 
374
+ This creates a natural curriculum without human intervention.
 
 
 
 
 
 
375
 
376
+ ## 🎯 Use Cases
377
 
378
+ ### βœ… Recommended
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
 
380
+ - **Educational demos** - Teaching language model concepts
381
+ - **Research** - Experimenting with adaptive computation
382
+ - **Prototyping** - Testing conversational AI applications
383
+ - **Learning** - Understanding transformer architectures
384
+ - **Creative writing assistance** - With human review
385
+ - **Code explanation** - Basic programming concepts
386
 
387
+ ### ⚠️ Not Recommended
 
 
 
 
 
388
 
389
+ - Production chatbots without human oversight
390
+ - Medical, legal, or financial advice
391
+ - Generating authoritative content without verification
392
+ - Automated content moderation
393
+ - Safety-critical systems
394
+ - High-stakes decision making
 
 
 
 
 
 
 
 
395
 
396
+ ## ⚠️ Limitations
397
 
398
  ### Technical Limitations
399
 
400
+ 1. **Context Window**: 512 tokens maximum (vs 2048+ for modern models)
401
+ 2. **Training Data**: 37K samples - relatively small dataset
402
+ 3. **Single Language**: Primarily English
403
+ 4. **Generation Quality**: Good but not perfect - may require post-processing
404
+ 5. **Knowledge Cutoff**: Training data up to early 2024
 
405
 
406
  ### Known Issues
407
 
408
+ - **Repetition**: May repeat phrases in very long generations (>200 tokens)
409
+ - **Factual Accuracy**: Small knowledge base, may generate plausible but incorrect information
410
+ - **Context Retention**: May lose track of earlier context in long conversations
411
+ - **Domain Specificity**: Limited knowledge in highly specialized fields
 
412
 
413
+ ### Generation Characteristics
414
+
415
+ - Occasionally incomplete sentences at sequence boundaries
416
+ - May generate generic filler phrases
417
+ - Temperature tuning recommended for optimal quality
418
+ - Best results with clear, specific prompts
419
+
420
+ ## πŸ”¬ Ethical Considerations
421
 
422
  ### Bias & Fairness
423
 
424
  This model may exhibit biases from training data:
425
 
426
  **Potential Biases:**
427
+ - Geographic: Western/English content overrepresentation
428
+ - Demographic: Biases from web text and conversational data
429
+ - Temporal: Reflects content patterns up to 2024
430
+ - Topic: Conversational data may skew certain perspectives
431
 
432
  **Mitigation:**
433
+ - Diverse training sources (Anthropic HH, UltraChat)
434
+ - Quality filtering applied
435
+ - Users should validate outputs for fairness-critical applications
436
 
437
  ### Responsible Use
438
 
439
+ **Environmental Impact:**
440
+ - Training: ~84 minutes on T4 GPU
441
+ - Estimated COβ‚‚: ~0.09 kg (single training run)
442
+ - Relatively low impact due to efficient training
 
 
443
 
444
+ ## πŸ“– Model Card
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445
 
446
+ ### Model Details
 
 
 
447
 
448
+ - **Developed by:** Girinath11
449
+ - **Model type:** Causal Language Model with Adaptive Recursion
450
+ - **Language:** English
451
+ - **License:** MIT
452
+ - **Base Model:** GPT-2 tokenizer
453
+ - **Training Date:** March 2026
454
+ - **Framework:** PyTorch + Transformers
455
 
456
  ### Intended Use
457
 
458
  **Primary Use Cases:**
459
+ - Research on adaptive computation
460
+ - Educational demonstrations
461
+ - Conversational AI prototyping
462
+ - Understanding mixture-of-experts concepts
463
+ - Curriculum learning research
 
464
 
465
+ **Out-of-Scope:**
466
+ - Production deployment without fine-tuning
467
+ - High-stakes decision making
468
+ - Content requiring domain expertise
469
+ - Real-time applications requiring <100ms latency
470
 
471
  ### Evaluation Methodology
472
 
473
  **Metrics:**
474
+ - Primary: Perplexity on held-out validation set
475
+ - Secondary: Training loss, generation quality
 
476
 
477
  **Evaluation Data:**
478
+ - 2,000 samples from Anthropic HH & UltraChat
479
  - Same preprocessing as training
480
  - No overlap with training data
481
 
482
+ ## πŸ“ Repository Structure
483
+ ```
484
+ recursive-language-model-90m/
485
+ β”œβ”€β”€ config.json # Model configuration
486
+ β”œβ”€β”€ model.safetensors # Model weights (363 MB)
487
+ β”œβ”€β”€ tokenizer.json # Tokenizer vocabulary
488
+ β”œβ”€β”€ tokenizer_config.json # Tokenizer settings
489
+ β”œβ”€β”€ special_tokens_map.json # Special token mappings
490
+ β”œβ”€β”€ model_info.json # Training metadata
491
+ β”œβ”€β”€ mixture_of_recursion.py # Model architecture code
492
+ └── README.md # This file
493
+ ```
494
+
495
+ ## πŸ”— Links
496
+
497
+ - **Model Card:** [Hugging Face](https://huggingface.co/Girinath11/recursive-language-model-90m)
498
+ - **GitHub:** [Repository](https://github.com/Giri530/recursive-language-model-90m)
499
+
500
+ ## πŸ“„ Citation
501
+
502
+ If you use this model in your research, please cite:
503
  ```bibtex
504
  @misc{recursive-lm-90m-2026,
505
  author = {Girinath11},
506
+ title = {Recursive Language Model with Perplexity-Based Dynamic Routing},
507
  year = {2026},
508
  publisher = {Hugging Face},
509
+ howpublished = {\url{https://huggingface.co/Girinath11/recursive-language-model-90m}},
510
+ note = {90M parameter model with adaptive computation achieving 17.45 perplexity}
511
  }
512
  ```
513
 
514
+ ## πŸ™ Acknowledgments
515
 
516
  - **Anthropic** for HH-RLHF dataset
 
517
  - **Tsinghua University** for UltraChat dataset
518
  - **Hugging Face** for Transformers library
519
  - **Kaggle** for free GPU access
520
+ - **OpenAI** for GPT-2 tokenizer
521
 
522
+ ## πŸ“ Version History
523
 
524
+ ### v1.0 (March 2026)
525
+ - Initial release
526
+ - 90.7M parameters
527
+ - Perplexity: 17.45
528
+ - Trained on 37K samples
529
+ - 3 epochs, 84 minutes training time
530
+
531
+ ## πŸ“§ Contact
532
 
533
+ For questions, issues, or collaboration:
534
+ - **GitHub Issues:** [Report a bug](https://github.com/Giri530/recursive-language-model-90m/issues)
535
+ - **Hugging Face Discussions:** [Ask a question](https://huggingface.co/Girinath11/recursive-language-model-90m/discussions)
536
 
537
+ ## πŸ“œ License
538
+
539
+ MIT License - Free to use with attribution
540
 
541
  ---
542
 
543
+ **Model Status:** βœ… Production Ready for Research & Prototyping
544
+
545
+ **Last Updated:** March 2, 2026