docs(ai): Comprehensive AI Developer Handbook & Submodule Guides — Training from Scratch in Pure .aira

This commit is contained in:
Adam Eehan committed 2026-11-12 23:51:15 +05:30
1 parent 44ad01a87d
commit a690296e7c
10 files changed
+431 -15

No files matched your search

+175 -15
View File
@@ -1,32 +1,192 @@
# 📦 AIRA :: `ai` — AIRA Sovereign Artificial Intelligence & Swarm Engine # 🧠 AIRA AI Ecosystem — Building & Training AI from Scratch
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang) [![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Modules: 1,120](https://img.shields.io/badge/Pure%20Modules-1,120%20.aira-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang) [![AI Modules: 1,120](https://img.shields.io/badge/AI%20Modules-1%2C120%20Pure%20.aira-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
[![Zero--Key AI: Active](https://img.shields.io/badge/Zero--Key%20Swarm-Embedded%20Native-brightgreen.svg)](https://github.com/adameehanairagroup/Airalang)
[![Architect: Er. Adam Eehan](https://img.shields.io/badge/Architect-Er.%20Adam%20Eehan-gold.svg)](https://github.com/adameehanairagroup) [![Architect: Er. Adam Eehan](https://img.shields.io/badge/Architect-Er.%20Adam%20Eehan-gold.svg)](https://github.com/adameehanairagroup)
> **Architect:** Er. Adam Eehan (Founder & CEO, Aira Group of Technology) > **"Intelligence is not a library in AIRA; it is a fundamental language primitive."**
> **100% Pure `.aira` Codebase** — Zero External Runtime Dependencies. > Architect: **Er. Adam Eehan (Founder & CEO, Aira Group of Technology)**
--- ---
## 🌟 Overview ## 🌟 The AIRA AI Philosophy
The `ai` domain is a core component of the **AIRA Titan Standard Library**, containing **1,120 pure `.aira` modules**.
It provides native, high-performance implementations for **Transformers, LLM inference, Deep Learning layers, Swarm AI, zero-key primitives (ai.ask)**. In legacy languages like Python or C++, building an AI model requires installing gigabytes of third-party C++ bindings (PyTorch, TensorFlow, NumPy, CUDA runtime) and configuring fragile virtual environments.
In **AIRA**, Artificial Intelligence is built **natively from scratch into the language syntax and standard library**:
1. **Pure Single-Language Implementation:** All **1,120 AI modules** in this directory are written in **100% Pure `.aira` code**.
2. **First-Class Tensor Math & Autograd:** Tensor manipulation, automatic backward differentiation, and graph execution are native language features.
3. **Build & Train Any Model:** From multi-layer perceptrons (MLP) and Convolutional Networks (CNN) to Generative Pre-Trained Transformers (GPT), Diffusion Models (DDPM), and State Space Models (Mamba)—every single layer is written and trainable in `.aira`.
4. **Zero-Key Swarm Inference:** When developers need instant intelligence without training, `ai.ask()` provides immediate zero-configuration access to sovereign neural swarms.
--- ---
## 🚀 Quick Usage Example ## 📖 The Complete Guide: Training a Neural Network from Scratch in AIRA
Here is how a developer writes, configures, and trains an AI model from scratch in pure AIRA syntax.
### 1. Defining Neural Network Layers
```aira ```aira
// Example of importing and using ai in AIRA // Import core neural network primitives
import "ai"; import "ai/nn";
import "ai/loss";
import "ai/optim";
say "⚡ [AIRA] Initialized ai module successfully!"; // Define a Multi-Layer Neural Network Class
class SovereignClassifier {
fn init(in_dim, hidden_dim, out_dim) {
this.fc1 = new Linear(in_dim, hidden_dim);
this.relu = new ReLU();
this.fc2 = new Linear(hidden_dim, out_dim);
}
// Forward propagation through layers
fn forward(x) {
let h1 = this.fc1.forward(x);
let a1 = this.relu.forward(h1);
let out = this.fc2.forward(a1);
return out;
}
// Collect all learnable parameters for optimizer
fn parameters() {
return this.fc1.parameters() + this.fc2.parameters();
}
}
```
### 2. The Complete Training Loop in Pure AIRA
```aira
// 1. Initialize dataset (features and labels)
let dataset_x = [
[0.1, 0.2, 0.3, 0.4],
[0.8, 0.7, 0.9, 0.6],
[0.2, 0.1, 0.3, 0.2],
[0.9, 0.8, 0.8, 0.7]
];
let dataset_y = [0, 1, 0, 1]; // Binary classes
// 2. Instantiate Model, Loss Function, and Optimizer
let model = new SovereignClassifier(4, 8, 2);
let criterion = new CrossEntropyLoss();
let optimizer = new AdamW(model.parameters(), 0.005, 0.01); // lr=0.005, weight_decay=0.01
say "🚀 Starting AIRA Sovereign Model Training...";
// 3. Training Loop across 50 Epochs
for epoch in range(1, 51) {
let total_loss = 0.0;
for i in range(0, len(dataset_x)) {
let x = dataset_x[i];
let target = dataset_y[i];
// Step A: Forward pass
let logits = model.forward(x);
// Step B: Compute Loss
let loss = criterion.forward(logits, target);
total_loss = total_loss + loss.value;
// Step C: Zero out previous gradients
optimizer.zero_grad();
// Step D: Backpropagation (Compute Gradients via Autograd)
loss.backward();
// Step E: Update Model Weights
optimizer.step();
}
if (epoch % 10 == 0) {
say "Epoch [" + str(epoch) + "/50] - Loss: " + str(total_loss / len(dataset_x));
}
}
say "✅ Model Training Successfully Completed in Pure AIRA!";
``` ```
--- ---
## 🏛️ Architecture & Purity ## ⚡ Building a Generative Pre-Trained Transformer (GPT) in AIRA
* Every file in this directory is written in authentic, sovereign `.aira` syntax.
* Zero `.py`, zero `.c`, zero external third-party package managers required. AIRA provides complete Transformer blocks including Scaled Dot-Product Attention, Multi-Head Attention, and Layer Normalization:
* Fully tested and executable on the native AIRA compiler engine.
```aira
import "ai/transformers";
import "ai/attention";
// Building a Transformer Decoder Block
class TransformerDecoderBlock {
fn init(d_model, n_heads) {
this.attn = new MultiHeadAttention(d_model, n_heads);
this.ln1 = new LayerNorm(d_model);
this.ffn1 = new Linear(d_model, d_model * 4);
this.gelu = new GELU();
this.ffn2 = new Linear(d_model * 4, d_model);
this.ln2 = new LayerNorm(d_model);
}
fn forward(x, mask) {
// Residual connection 1: Self-Attention
let norm_x = this.ln1.forward(x);
let attn_out = this.attn.forward(norm_x, norm_x, norm_x, mask);
let h = x + attn_out;
// Residual connection 2: Feed-Forward Network
let norm_h = this.ln2.forward(h);
let ffn_out = this.ffn2.forward(this.gelu.forward(this.ffn1.forward(norm_h)));
return h + ffn_out;
}
}
```
---
## 🧠 Instant Zero-Key AI Swarm (`ai.ask`)
When you do not need to train a model from scratch and want immediate reasoning or code generation:
```aira
import "ai";
// 1. Direct Zero-Key AI Question
let answer = ai.ask("Explain quantum teleportation in 2 sentences");
say answer;
// 2. Interactive Terminal AI Co-Pilot
while true {
let prompt = input("Developer > ");
if (prompt.lower() == "exit") {
say "Terminating AI session.";
break;
}
let reply = ai.ask(prompt);
say "Aira > " + reply;
}
```
---
## 📂 AI Submodule Architecture Index (1,120 Modules)
Explore the dedicated documentation inside each package for complete API references and mathematical formulas:
| Package | Purpose & Architecture | Documentation |
| :--- | :--- | :--- |
| **`ai/nn/`** | Core Neural Layers: Linear, Conv2D, Dropout, LayerNorm, Activations | [👉 Read `ai/nn` Guide](./nn/README.md) |
| **`ai/attention/`** | Scaled Dot-Product Attention, Multi-Head Attention, Rotary Embeddings (RoPE) | [👉 Read `ai/attention` Guide](./attention/README.md) |
| **`ai/transformers/`** | Complete GPT, LLaMA, MoE (Mixture of Experts), Whisper Architectures | [👉 Read `ai/transformers` Guide](./transformers/README.md) |
| **`ai/loss/`** | Loss Functions: CrossEntropyLoss, MSELoss, BCE, HuberLoss, TripletLoss | [👉 Read `ai/loss` Guide](./loss/README.md) |
| **`ai/optim/`** | Optimization Algorithms: AdamW, SGD with Momentum, RMSprop, Schedulers | [👉 Read `ai/optim` Guide](./optim/README.md) |
| **`ai/diffusion/`** | Denoising Diffusion Probabilistic Models (DDPM), Noise Schedulers | [👉 Read `ai/diffusion` Guide](./diffusion/README.md) |
| **`ai/nlp/`** | Tokenization: Byte-Pair Encoding (BPE), WordPiece, Embedding Similarity | [👉 Read `ai/nlp` Guide](./nlp/README.md) |
| **`ai/mamba/`** | State Space Models (SSM), Selective Scan, O(N) Linear Attention | [👉 Read `ai/mamba` Guide](./mamba/README.md) |
| **`ai/rlhf/`** | RLHF, Direct Preference Optimization (DPO), PPO, Reward Modeling | [👉 Read `ai/rlhf` Guide](./rlhf/README.md) |
| **`ai/quantization/`** | GGUF 4-Bit / 8-Bit Quantization, Edge AI inference on Mobile / Termux | [👉 Read `ai/quantization` Guide](./quantization/README.md) |
| **`ai/agent/`** | Autonomous Swarm Agents, Guardrails, Tool-calling loops, Task Planning | [👉 Read `ai/agent` Guide](./agent/README.md) |
| **`ai/providers/`** | Native Zero-Key Swarm, OpenAI, Claude, Gemini, Groq, DeepSeek Bridges | [👉 Read `ai/providers` Guide](./providers/README.md) |
| **`ai/cv/`** | Computer Vision: Image Filters, Feature Detectors, Convolutional Kernels | [👉 Read `ai/cv` Guide](./cv/README.md) |
+17
View File
@@ -0,0 +1,17 @@
# 🤖 AIRA Autonomous Agent & Swarm Intelligence (`ai/agent`)
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Domain: ai/agent](https://img.shields.io/badge/Domain-Multi--Agent%20Swarm-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
Enables autonomous reasoning loops, tool-calling executors, collaborative multi-agent swarms, and safety guardrail auditing.
```aira
import "ai/agent";
let coordinator = new SwarmCoordinator();
coordinator.register_agent("researcher", new Agent("Research and analyze systems"));
coordinator.register_agent("engineer", new Agent("Generate verified .aira code"));
let task_result = coordinator.execute("Build a concurrent TCP server in sys/net");
say task_result;
```
+35
View File
@@ -0,0 +1,35 @@
# 🎯 AIRA Attention Mechanisms (`ai/attention`)
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Domain: ai/attention](https://img.shields.io/badge/Domain-Multi--Head%20Attention-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
[![Architect: Er. Adam Eehan](https://img.shields.io/badge/Architect-Er.%20Adam%20Eehan-gold.svg)](https://github.com/adameehanairagroup)
The `ai/attention` package provides native implementations of modern self-attention and cross-attention architectures.
---
## 🧮 Mathematical Formulation
### Scaled Dot-Product Attention
$$ ext{Attention}(Q, K, V) = ext{softmax}\left( rac{Q K^T}{\sqrt{d_k}} ight) V$$
In pure `.aira`:
```aira
import "ai/attention";
// Instantiate MultiHeadAttention with 8 heads across 512 dimensions
let mha = new MultiHeadAttention(512, 8);
// Forward pass: Query, Key, Value, and Causal Attention Mask
let context_vectors = mha.forward(Q, K, V, causal_mask);
```
### Rotary Positional Embeddings (RoPE)
Enables transformers to dynamically encode relative token positions without hard positional tables:
```aira
let rope = new RotaryEmbedding(dim_per_head=64, max_seq_len=4096);
let q_rotated = rope.apply(Q, position_ids);
let k_rotated = rope.apply(K, position_ids);
```
+21
View File
@@ -0,0 +1,21 @@
# 🎨 AIRA Generative Diffusion Models (`ai/diffusion`)
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Domain: ai/diffusion](https://img.shields.io/badge/Domain-DDPM%20%26%20Generative%20AI-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
Provides native implementations of Denoising Diffusion Probabilistic Models (DDPM) and noise schedules for generative image, audio, and tensor synthesis.
---
## 🌊 Diffusion Mechanics in AIRA
* **Forward Noise Schedule:** Adds Gaussian noise over $T$ timesteps according to variance schedule $eta_1, \dots, eta_T$:
$$q(x_t | x_0) = \mathcal{N}(x_t; \sqrt{ar{lpha}_t} x_0, (1 - ar{lpha}_t)\mathbf{I})$$
* **Reverse Denoising Process:** The neural network predicts the noise $\epsilon_ heta(x_t, t)$ to iteratively reconstruct clean latent data $x_0$.
```aira
import "ai/diffusion";
let scheduler = new DDPMScheduler(timesteps=1000, beta_start=0.0001, beta_end=0.02);
let noisy_sample = scheduler.add_noise(clean_latent, noise, timestep=500);
```
+29
View File
@@ -0,0 +1,29 @@
# 📉 AIRA Loss Functions (`ai/loss`)
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Domain: ai/loss](https://img.shields.io/badge/Domain-Objective%20Functions-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
Loss functions calculate the scalar discrepancy between model predictions and ground-truth targets, guiding gradient backpropagation.
---
## 📐 Implemented Loss Functions
### 1. `CrossEntropyLoss` (Classification & Next-Token LLM Training)
$$\mathcal{L} = -\sum_{i} y_i \log(\hat{y}_i)$$
Utilizes numerically stable Log-Softmax with max-subtraction to prevent floating-point underflow:
```aira
import "ai/loss";
let criterion = new CrossEntropyLoss();
let loss = criterion.forward(logits, target_class);
loss.backward(); // Propagates dL/dLogits back into model layers
```
### 2. `MSELoss` (Mean Squared Error)
$$\mathcal{L} = rac{1}{N} \sum_{i=1}^N (y_i - \hat{y}_i)^2$$
Ideal for continuous regression, coordinate prediction, and Diffusion noise estimation.
### 3. `BCEWithLogitsLoss`
Binary cross-entropy combining a sigmoid activation and cross-entropy for numerical stability in multi-label classification.
+19
View File
@@ -0,0 +1,19 @@
# 📝 AIRA NLP & Tokenization Engine (`ai/nlp`)
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Domain: ai/nlp](https://img.shields.io/badge/Domain-Tokenizer%20%26%20Embeddings-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
The `ai/nlp` package implements text tokenization, byte-pair encoding (BPE), vocabulary mapping, and dense semantic embedding search.
```aira
import "ai/nlp";
let tokenizer = new BPETokenizer();
tokenizer.load_vocab("vocab.json", "merges.txt");
let token_ids = tokenizer.encode("Sovereign AI Engineering in AIRA");
say token_ids; // [1284, 9942, 381, 2901]
let text = tokenizer.decode(token_ids);
say text;
```
+43
View File
@@ -0,0 +1,43 @@
# 🧱 AIRA Neural Network Primitives (`ai/nn`)
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Domain: ai/nn](https://img.shields.io/badge/Domain-Neural%20Layers-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
[![Architect: Er. Adam Eehan](https://img.shields.io/badge/Architect-Er.%20Adam%20Eehan-gold.svg)](https://github.com/adameehanairagroup)
The `ai/nn` package provides the fundamental building blocks for constructing deep neural networks in pure `.aira`.
---
## 📐 Included Layers & Mechanics
### 1. `Linear(in_features, out_features, bias=true)`
Computes the linear affine transformation:
$$\mathbf{y} = \mathbf{x} \mathbf{W}^T + \mathbf{b}$$
```aira
import "ai/nn";
// Create a Linear layer with 784 inputs (e.g. MNIST) and 128 hidden neurons
let layer = new Linear(784, 128);
let output = layer.forward(input_vector);
```
### 2. `LayerNorm(normalized_shape, eps=1e-5)`
Normalizes the inputs across the features dimension for training stability in Transformers:
$$y = rac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} \cdot \gamma + eta$$
```aira
let norm = new LayerNorm(512);
let normalized_tensor = norm.forward(hidden_states);
```
### 3. Activation Functions
* **`ReLU`:** $f(x) = \max(0, x)$ — Standard non-linear activation.
* **`GELU`:** $f(x) = x \cdot \Phi(x) pprox 0.5x(1 + anh(\sqrt{2/\pi}(x + 0.044715x^3)))$ — Used in GPT and modern LLMs.
* **`SiLU` (Swish):** $f(x) = x \cdot \sigma(x)$ — Used in LLaMA feed-forward networks.
* **`Softmax`:** Transforms arbitrary logits into valid probability distributions summing to 1.0.
```aira
let gelu = new GELU();
let activated = gelu.forward(raw_logits);
```
+33
View File
@@ -0,0 +1,33 @@
# ⚙️ AIRA Optimization Engines (`ai/optim`)
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Domain: ai/optim](https://img.shields.io/badge/Domain-Gradient%20Optimizers-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
The `ai/optim` package contains state-of-the-art gradient optimization algorithms used to update neural network weights during training.
---
## 🔬 `AdamW` (Decoupled Weight Decay Optimizer)
The gold standard for training Transformers and modern Deep Learning:
$$m_t = eta_1 m_{t-1} + (1 - eta_1) g_t$$
$$v_t = eta_2 v_{t-1} + (1 - eta_2) g_t^2$$
$$\hat{m}_t = rac{m_t}{1 - eta_1^t}, \quad \hat{v}_t = rac{v_t}{1 - eta_2^t}$$
$$ heta_t = heta_{t-1} - \eta \left( rac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon} + \lambda heta_{t-1} ight)$$
---
## 🚀 Usage in Training Loop
```aira
import "ai/optim";
// Initialize AdamW with parameters, learning rate, and weight decay
let optimizer = new AdamW(model.parameters(), lr=0.001, weight_decay=0.01);
// Step within the training epoch
optimizer.zero_grad(); // Reset accumulated gradients
loss.backward(); // Calculate gradients via autograd
optimizer.step(); // Update parameters using AdamW formula
```
+17
View File
@@ -0,0 +1,17 @@
# 🌐 AIRA Swarm & Universal Cloud Providers (`ai/providers`)
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Domain: ai/providers](https://img.shields.io/badge/Domain-Zero--Key%20Swarm-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
The `ai/providers` module handles connection protocols for the native sovereign neural swarm and universal bridges to external LLM providers without external dependencies.
---
## ⚡ Zero-Key Native Usage
```aira
import "ai";
// Default Sovereign Engine (Zero-Key Active)
let response = ai.ask("Provide a mathematical proof of the central limit theorem");
say response;
```
+42
View File
@@ -0,0 +1,42 @@
# 🚀 AIRA Transformers & LLM Architectures (`ai/transformers`)
[![Language: Aira](https://img.shields.io/badge/Language-Aira%20100%25-ff007f.svg)](https://github.com/adameehanairagroup/Airalang)
[![Domain: ai/transformers](https://img.shields.io/badge/Domain-Large%20Language%20Models-00e5ff.svg)](https://github.com/adameehanairagroup/Airalang)
[![Architect: Er. Adam Eehan](https://img.shields.io/badge/Architect-Er.%20Adam%20Eehan-gold.svg)](https://github.com/adameehanairagroup)
The `ai/transformers` package houses complete, runnable architectures for Large Language Models written entirely in pure `.aira`.
---
## 🏛️ Supported Transformer Architectures
1. **`GPT` (Decoder-Only Generative Model):** Causal self-attention, learned position embeddings, GELU activations.
2. **`LLaMA` (Modern Open Weights Standard):** RMSNorm, Rotary Embeddings (RoPE), SwiGLU feed-forward networks.
3. **`MoE` (Mixture of Experts):** Top-2 sparse expert gating network routing tokens across 8+ specialized expert sub-networks.
4. **`Whisper`:** Encoder-decoder transformer for speech audio spectrogram-to-text transcription.
---
## 📝 Training and Text Generation Example
```aira
import "ai/transformers";
import "ai/nlp";
// 1. Initialize Tokenizer & Model
let tokenizer = new BPETokenizer();
let gpt = new MiniGPT(vocab_size=32000, d_model=768, n_layers=12, n_heads=12);
// 2. Autoregressive Text Generation
let prompt = "The future of sovereign programming is";
let tokens = tokenizer.encode(prompt);
for step in range(0, 30) {
let logits = gpt.forward(tokens);
let next_token = sample_top_p(logits[-1], temperature=0.7, top_p=0.9);
tokens.append(next_token);
}
let generated_text = tokenizer.decode(tokens);
say generated_text;
```