diff --git a/README.md b/README.md index 61aa4f6..7627516 100644 --- a/README.md +++ b/README.md @@ -1,422 +1,264 @@ -
- Helios Foundation Model Ecosystem Logo +# HELIOS — Open-Source AI Model Family - # HELIOS: Open-Weight Foundation Model Ecosystem (v0.3.0) +**HELIOS** is an open-source, open-weight AI model ecosystem developed by **Arron Kian Parejas**. It is designed to explore efficient language modeling, semantic grounding, structured reasoning, and accessible local AI deployment. - **Personally Conceived, Architected, and Developed by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines** - ([parejasarronkian@gmail.com](mailto:parejasarronkian@gmail.com)) +HELIOS aims to make AI more accessible by providing multiple model sizes that can run across different hardware environments, from lightweight devices to more capable personal computers. - **[Live Showcase & Documentation (`openhelios.vercel.app`)](https://openhelios.vercel.app)** · **[Hugging Face (`Darknecrocities/Helios`)](https://huggingface.co/Darknecrocities/Helios)** · **[Ollama (`parejasarronkian/Helios`)](https://ollama.com/parejasarronkian)** · **[177-Dataset Single Source of Truth (`sot/`)](sot/README.md)** -
+Run HELIOS locally using Ollama and integrate it into your own applications through its local API. --- -## Table of Contents +## What is HELIOS? -1. [About Helios: Origin, Vision & First-Principles Philosophy](#1-about-helios-origin-vision--first-principles-philosophy) -2. [End-to-End Helios System & Panoptes Transformer Architecture Diagram](#2-end-to-end-helios-system--panoptes-transformer-architecture-diagram) -3. [Lossless Bilingual & Code Tokenizer Subsystem (`HeliosBPE` & `HeliosUnigram`)](#3-lossless-bilingual--code-tokenizer-subsystem-heliosbpe--heliosunigram) -4. [4-Tier Hierarchical Memory Architecture (HMA) & Native MCP Tool Calling](#4-4-tier-hierarchical-memory-architecture-hma--native-mcp-tool-calling) -5. [Core AI Engineering Techniques & Mathematical Formulation](#5-core-ai-engineering-techniques--mathematical-formulation) -6. [Precision Formats, Quantization (`FP32` → `Q4_K_M`) & `LoRA` / `QLoRA` Pipeline](#6-precision-formats-quantization-fp32--q4_k_m--lora--qlora-pipeline) -7. [The 6-Tier Helios Model Family & Complete Hardware Memory Breakdown](#7-the-6-tier-helios-model-family--complete-hardware-memory-breakdown) -8. [Dataset Single Source of Truth (`sot/` · 177 Datasets · 16 Domains)](#8-dataset-single-source-of-truth-sot--177-datasets--16-domains) -9. [Audited Benchmark Comparison (`eval/` Automated Suite & 500-Question Verification)](#9-audited-benchmark-comparison-eval-automated-suite--500-question-verification) -10. [Continuous Pretraining, Last-Checkpoint Resumption & `helios chat` Telemetry](#10-continuous-pretraining-last-checkpoint-resumption--helios-chat-telemetry) -11. [How to Run Helios (CLI, Ollama, Hugging Face & Autonomous Agents)](#11-how-to-run-helios-cli-ollama-hugging-face--autonomous-agents) +HELIOS is an evolving family of language models built around a modular architecture and a collection of capabilities designed for practical AI applications. ---- +Its development focuses on: -## 1. About Helios: Origin, Vision & First-Principles Philosophy +- **Hierarchical Memory Architecture (HMA):** A memory-oriented approach to organizing and retrieving relevant information. +- **Semantic Grounding:** Improving the relationship between user questions, available knowledge, and generated responses. +- **Epistemic Fallback:** An explicit fallback mechanism for topics outside the model's available knowledge. +- **Mathematical Reasoning:** Support for mathematical questions and structured problem-solving. +- **Scientific and Medical Knowledge:** Training and evaluation across scientific and medical question-answering datasets. +- **Programming Assistance:** Language understanding and code-generation capabilities. +- **Multimodal Interaction (Core/Pro/Flagship):** Image + text + tool support on higher tiers. +- **Bilingual Interaction:** English and Filipino/Tagalog conversational support. +- **Local AI Execution:** Designed for integration into local and distributed AI environments. +- **Tool Calling (MCP):** Native function/tool calling support across all tiers. -### Why "Helios"? (Derived from the Ancient Greek God of the Sun) -The name **Helios** is derived from **Helios (Ἥλιος)**, the ancient Greek Titan god and personification of the **Sun**, who drove his radiant golden chariot across the sky each day to illuminate the Earth and was revered in classical antiquity as the all-seeing guardian of truth and clarity. +HELIOS is an actively evolving project. Its architecture, training pipeline, and capabilities will continue to improve as development progresses. -In modern artificial intelligence, too many foundation models operate as opaque "black boxes" that hide their architecture, require massive enterprise server farms, or hallucinate random answers when asked about unfamiliar topics. **Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines**, personally designed and built **Helios** from the ground up to embody its namesake: -- **Illumination & Radical Transparency**: Every component—from the Byte-Level BPE and Viterbi Unigram tokenizers to the causal Panoptes transformer blocks, 4-tier memory controller, and atomic training pipeline—is 100% open-weight, inspectable, and documented. -- **Truth & Epistemic Honesty**: Like the Sun revealing things as they truly are, Helios never fabricates a bare number (such as `"42"`) or guesses wildly when a topic lies outside its training session; instead, it enforces **Subject-Aware Semantic Verification** and an **Honest Epistemic Fallback**. -- **Universal Energy & Accessibility**: Just as sunlight reaches every corner of the globe, the 6-tier Helios model family (`Nano`, `Alpha`, `Beta`, `Core`, `Pro`, `Flagship`) is engineered to run smoothly on everyday consumer hardware—from a Raspberry Pi or budget smartphone all the way to a standard 16GB RAM laptop. +## Model Family ---- +HELIOS currently has six model tiers, each targeting a different balance of model capacity, resource consumption, and application requirements. -## 2. End-to-End Helios System & Panoptes Transformer Architecture Diagram - -The diagram below illustrates the complete end-to-end execution flow of the **Helios Panoptes Architecture**, integrating multimodal input encoding, Grouped-Query Attention (`GQA`), Dynamic NTK RoPE scaling, 4-Tier Hierarchical Memory (`HMA`), deliberative `<|thought|>` Chain-of-Thought, and Speculative Decoding (`Nano` $\to$ `Flagship`): - -```mermaid -flowchart TD - subgraph InputLayer["1. Multimodal & Lossless Tokenization Layer"] - RawText["User Query (English / Tagalog / Source Code)"] --> Tok["HeliosBPE & HeliosUnigram Tokenizer (V = 32,000)"] - RawImg["Input Image (224x224 RGB)"] --> ViT["HeliosVisionEncoder (ViT 14x14 = 256 Patches)"] - ViT --> MMProj["2-Layer GELU Multi-Modal Projector"] - Tok --> Embed["Token Embedding Matrix [V x d_model]"] - MMProj --> PrefixMerge["Bidirectional Vision Prefix + Causal Text Stream"] - Embed --> PrefixMerge - end - - subgraph PanoptesCore["2. Panoptes Transformer Backbone (L = 7 to 32 Layers)"] - PrefixMerge --> RMS1["Pre-RMSNorm (eps = 1e-5)"] - RMS1 --> GQA["Grouped-Query Attention (4:1 / 3:1 GQA) + Dynamic NTK RoPE (theta = 100K to 10M)"] - GQA --> KVCache["Contiguous KV-Cache (FP16 / Symmetric INT8 Compression)"] - GQA --> Res1["Residual Connection (+)"] - Res1 --> RMS2["Pre-RMSNorm (eps = 1e-5)"] - RMS2 --> SwiGLU["SwiGLU Feed-Forward Network: (SiLU(x W_gate) * (x W_up)) W_down"] - SwiGLU --> LoRA["Optional PEFT Injection: LoRA (r=16, alpha=32) / 4-Bit NF4 QLoRA"] - LoRA --> Res2["Residual Connection (+)"] - end - - subgraph MemoryAndReasoning["3. 4-Tier Hierarchical Memory (HMA) & Epistemic Verification"] - Res2 <--> HMA["HMAController Router"] - HMA <--> T1["Tier 1: Working Memory (Sliding RAM Window)"] - HMA <--> T2["Tier 2: Episodic Memory (SQLite3 WAL Mode)"] - HMA <--> T3["Tier 3: Semantic Memory (15K RAM BM25 + 134K SQLite FTS5 + FAISS RRF)"] - HMA <--> T4["Tier 4: Procedural Memory (MCP JSON-RPC 2.0 + Deterministic AST Math)"] - end - - subgraph OutputStage["4. Speculative Decoding & Honest Epistemic Gate"] - Res2 --> CoT["Deliberative Scratchpad (<|thought|> ... <|end_thought|>)"] - CoT --> Spec["Speculative Verification: Nano (17.8M Draft, gamma=4) -> Flagship (5.8B Verifier)"] - Spec --> SubjGate{"Subject-Aware Semantic Gate (verify_subject_overlap)"} - SubjGate -- "Verified Grounding / Exact Compute" --> FinalOut["Verified Grounded Response / MCP Tool Execution"] - SubjGate -- "Out-of-Scope / Unseen Entity" --> Fallback["Honest Epistemic Fallback (Zero Hallucination)"] - end -``` +| Model | Parameters | Base Model | Context Window | Size | Capabilities | +|---|---:|---|---:|---:|---| +| HELIOS Nano | 17.84M | qwen2.5:0.5b | 16K | 397 MB | Text, Tools | +| HELIOS Alpha | 100.09M | qwen2.5:1.5b | 32K | ~1 GB | Text, Tools | +| HELIOS Beta | 303.35M | qwen2.5:3b | 64K | ~2 GB | Text, Tools | +| HELIOS Core | 1.13B | qwen2.5vl:7b | 32K | ~5.5 GB | Image, Text, Tools | +| HELIOS Pro | 3.32B | qwen2.5vl:7b | 64K | ~5.5 GB | Image, Text, Tools | +| HELIOS Flagship | 5.80B | qwen2.5vl:7b | 128K | ~5.5 GB | Image, Text, Tools | ---- +*These are the project's documented model specifications. Actual Ollama package sizes, context limits, and runtime memory requirements depend on the published model artifacts and configuration.* -## 3. Lossless Bilingual & Code Tokenizer Subsystem (`HeliosBPE` & `HeliosUnigram`) +### Choosing a Model -Standard English-centric tokenizers fracture Filipino/Tagalog agglutinative morphology (`mag-`, `nag-`, `-in-`, `-um-`, `pinag-`) and multi-space source code indentation into inefficient single-character fragments. Helios implements **two complete, lossless tokenizers from scratch** in `helios/tokenizer/`: +- **Nano:** Lightweight experimentation and constrained environments. Text + tools. +- **Alpha:** Everyday conversational applications and basic knowledge tasks. Text + tools. +- **Beta:** More capable mathematical, scientific, and question-answering workflows. Text + tools. +- **Core:** Technical discussions, programming, and multimodal (image) support. Image + text + tools. +- **Pro:** Advanced development workflows, agent-oriented applications, and multimodal support. Image + text + tools. +- **Flagship:** The highest-capacity HELIOS tier for demanding workloads, long-context experimentation, and full multimodal support. Image + text + tools. -```mermaid -flowchart LR - Input["UTF-8 Stream (English, Tagalog, Code, Math)"] --> Norm["NFC Normalization & Regex Pre-Tokenizer"] - Norm --> Engine{"Tokenizer Architecture"} +## Getting Started with Ollama - Engine -- "Byte-Level BPE (helios/tokenizer/bpe.py)" --> BPE["256 Base Byte Tokens + Priority Merge Rules"] - Engine -- "Viterbi Unigram (helios/tokenizer/unigram.py)" --> Uni["EM-Trained Subword Lattice + Digamma Log-Probs"] +### 1. Install Ollama - BPE --> Special["Reserved Control & Agentic Tokens (IDs 0..31)"] - Uni --> Special +Download Ollama for your operating system: - Special --> Tensor["Lossless Token IDs (0.0% Rate)"] -``` - -### Key Tokenizer Capabilities & Special Control Vocabulary (`V = 32,000`) -- **Zero `` Out-of-Vocabulary Guarantee**: Every arbitrary UTF-8 byte sequence decomposes cleanly to 256 byte-level fallback atoms (`0x00`–`0xFF`), guaranteeing `100%` round-trip reconstruction fidelity (`decode(encode(text)) == text`). -- **High Bilingual & Code Fertility**: Dedicated morphological merges for Filipino/Tagalog affixes and multi-space Python/TypeScript/Rust indentation tokens. -- **Native Control & Protocol Tokens**: - - **Conversation Framing**: `<|bos|>`, `<|eos|>`, `<|system|>`, `<|user|>`, `<|assistant|>`, `<|pad|>` - - **Extended Thinking / Chain-of-Thought**: `<|thought|>`, `<|end_thought|>` - - **Model Context Protocol (MCP) & Hermes Tooling**: `<|call:tool|>`, `<|end_call|>`, `<|return:tool|>`, `<|end_return|>` - - **Multimodal Vision Framing**: `<|image|>`, `<|end_image|>` +https://ollama.com/download ---- +Alternatively, on macOS: -## 4. 4-Tier Hierarchical Memory Architecture (HMA) & Native MCP Tool Calling - -Unlike stateless language models that suffer from context amnesia or require slow full-corpus re-indexing on startup, Helios coordinates a biological **4-Tier Hierarchical Memory Architecture (`helios/memory/`)**: +```bash +brew install ollama +``` -```mermaid -flowchart TD - Query["Incoming User Prompt / Agent Task"] --> Norm["Bilingual Intent & Entity Extractor (EN + TL)"] +Start the Ollama service: - Norm --> Tier1["Tier 1 · Working Memory (< 0.1 ms)\nIn-RAM Sliding Token Buffer & Context Compaction"] - Norm --> Tier2["Tier 2 · Episodic Memory (< 2.0 ms)\nSQLite 3 Concurrent WAL Store (Cross-Session Recall)"] - Norm --> Tier3["Tier 3 · Semantic Memory (< 10.0 ms)\nTwo-Tier Hybrid Retrieval"] - Norm --> Tier4["Tier 4 · Procedural Memory (Deterministic)\nMCP JSON-RPC 2.0 Sandbox & AST Math/Unit Engine"] +```bash +ollama serve +``` - subgraph HybridSemantic["Tier 3 Two-Tier Hybrid Semantic Engine"] - Tier3 --> FastBM25["In-RAM Okapi BM25 Index\n(15,000 Core Priority Records · < 1 ms)"] - Tier3 --> DiskFTS5["On-Disk SQLite FTS5 BM25 Index\n(134,728 Grounded Records · 402 MB · < 10 ms)"] - Tier3 --> DenseFAISS["Dense FAISS Vector Index\n(Cosine / Inner-Product Embeddings)"] - FastBM25 --> RRF["Reciprocal Rank Fusion (RRF, k = 60)"] - DiskFTS5 --> RRF - DenseFAISS --> RRF - end +### 2. Run HELIOS - Tier1 --> Gate["Subject-Aware Verification Gate\nverify_subject_overlap(QueryEntities, CandidateDoc)"] - Tier2 --> Gate - RRF --> Gate - Tier4 --> Gate +Pull and launch the default HELIOS model: - Gate -- "Overlap >= tau_subj" --> Verified["Grounded Context Injected into Panoptes Attention"] - Gate -- "Overlap < tau_subj" --> Abstain["Deterministic Epistemic Abstention"] +```bash +ollama run parejasarronkian/Helios ``` -| Memory Tier | Storage Engine | Latency | Capacity | Primary Responsibility | -| :--- | :--- | :---: | :---: | :--- | -| **Tier 1 · Working Memory** | In-RAM Sliding Token Buffer | `< 0.1 ms` | `16K – 256K` Tokens | Active multi-turn dialogue state, attention sinks & automatic context compaction | -| **Tier 2 · Episodic Memory** | SQLite 3 (`WAL` Mode + `ACID`) | `< 2.0 ms` | Unlimited Sessions | Cross-session chronological dialogue recall & user preference persistence | -| **Tier 3 · Semantic Memory** | `15K` RAM BM25 + `SQLite FTS5` + `FAISS` | `< 10.0 ms` | `134,728+` Docs (`402 MB`) | Bilingual Reciprocal Rank Fusion (`RRF`) over grounded encyclopedic & code corpora | -| **Tier 4 · Procedural Memory** | `MCP JSON-RPC 2.0` + AST Evaluator | Deterministic | Extensible Tool Registry | Schema-validated external tool calls, exact arithmetic, unit conversion & code sandbox | +### 3. Choose a Model Tier ---- +You can select a specific HELIOS model variant: + +```bash +# Lightweight model (text + tools) +ollama run parejasarronkian/Helios:nano -## 5. Core AI Engineering Techniques & Mathematical Formulation +# Everyday conversational model (text + tools) +ollama run parejasarronkian/Helios:alpha -Personally conceived and architected by **Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines**, Helios integrates modern foundation model and systems engineering techniques: +# Mathematics, science, and QA (text + tools) +ollama run parejasarronkian/Helios:beta -```mermaid -flowchart LR - subgraph GQA_Block["1. Grouped-Query Attention (8x KV Savings)"] - Q["Query Heads (H_q = 8..32)"] --> Group["Shared KV Groups (4:1 / 3:1)"] - KV["Key/Value Heads (H_kv = 2..8)"] --> Group - Group --> Attn["Scaled Dot-Product Attention\nsoftmax((Q K^T)/sqrt(d_k) + M_causal) V"] - end +# Technical and programming workflows (image + text + tools) +ollama run parejasarronkian/Helios:core - subgraph RoPE_Block["2. Dynamic NTK High-Theta RoPE"] - Pos["Token Position m (up to 262,144)"] --> Freq["Base Theta Scaling\ntheta = 100,000 -> 10,000,000"] - Freq --> Rot["Complex Plane Rotation e^(i m theta_j)"] - end +# Advanced model tier (image + text + tools) +ollama run parejasarronkian/Helios:pro - subgraph Spec_Block["3. Lossless Speculative Tandem (2.4x Speedup)"] - Draft["Helios Nano (17.84M)\nDrafts gamma = 4 tokens @ 265 tok/s"] --> Verify["Helios Flagship (5.80B)\nSingle Parallel Forward Pass"] - Verify --> Accept["Rejection Sampling: min(1, p_target / q_draft)"] - end +# Highest-capacity model tier (image + text + tools) +ollama run parejasarronkian/Helios:flagship ``` -1. **Grouped-Query Attention (`GQA`)**: Shares Key/Value projections across groups of Query heads (`8:2` up to `32:8`), reducing KV-cache RAM consumption by up to **8×** while maintaining multi-head reasoning quality: - $$\text{Attention}(Q_g, K, V) = \text{softmax}\!\left(\frac{Q_g K^\top}{\sqrt{d_k}} + M_{\text{causal}}\right)V$$ -2. **Rotary Position Embeddings (`RoPE`) with Dynamic NTK-Aware High-Theta Scaling**: Encodes relative token distances via complex-plane rotation matrices with base frequency $\theta$ scaled from `100,000.0` (`Nano`) up to `10,000,000.0` (`Flagship`) and lazy on-demand cache allocation, supporting long-context windows from **16,384 (`16K`)** up to **262,144 (`256K`) tokens**. -3. **SwiGLU Gated Feed-Forward Networks & Pre-RMSNorm**: Replaces standard ReLU/GELU MLPs with SiLU-Gated Linear Units (`SwiGLU`) and Root Mean Square Pre-Normalization ($\epsilon = 10^{-5}$) for zero gradient divergence during pretraining: - $$\text{SwiGLU}(x) = \big(\text{SiLU}(x W_{\text{gate}}) \odot (x W_{\text{up}})\big) W_{\text{down}}, \quad \text{RMSNorm}(x) = \frac{x}{\sqrt{\frac{1}{d}\sum_{i=1}^d x_i^2 + \epsilon}} \odot \gamma$$ -4. **Collaborative `Nano` + `Flagship` Speculative Decoding (`2.4×` Speedup)**: Because all six Helios tiers share the exact same 32,000-token vocabulary, `Helios Nano` (`17.84M`) acts as an ultra-fast draft engine ($\gamma = 4$ tokens) while `Helios Flagship` (`5.80B`) verifies all drafted tokens in a single parallel forward pass with mathematically identical output distributions. -5. **Multimodal Vision Encoder (`HeliosVisionEncoder` · ViT `14×14`)**: `Helios Core` (`1.13B`) and `Helios Flagship` (`5.80B`) embed a native Vision Transformer encoder ($d_v = 1024, L = 12, 14\times 14$ patches $= 256$ visual tokens per $224\times 224$ image) bridged via a 2-layer GELU Multi-Modal Projector. -6. **Atomic 6-State Checkpointing & Zero-Hang Live Model Switching**: POSIX-atomic `os.replace` checkpointing preserves model weights, optimizer states, scheduler steps, RNG seeds, and exact dataloader offsets, while `helios chat` enforces pre-flight `psutil` + `torch.mps.synchronize()` RAM guards before live `/model` switches. +The available tags correspond to the published model variants in the HELIOS Ollama library. ---- - -## 6. Precision Formats, Quantization (`FP32` → `Q4_K_M`) & `LoRA` / `QLoRA` Pipeline +## Using the HELIOS API -Helios supports full-spectrum numerical precision from 32-bit master weights down to 4-bit NormalFloat (`NF4`) `QLoRA` fine-tuning and `GGUF Q4_K_M` edge quantization across all 6 model tiers: +Ollama provides a local HTTP API, allowing developers to integrate HELIOS into applications, scripts, and development environments. -```mermaid -flowchart LR - Master["Master Weights\nFP32 (32-bit IEEE 754)\nSafeTensors / PyTorch"] --> BF16["Pretraining & SFT\nBF16 / FP16 (16-bit)\n2.0x Memory Savings"] - BF16 --> INT8["Lossless Local & KV Cache\nINT8 / Q8_0 (8-bit Symmetric)\n4.0x Memory Savings"] - INT8 --> INT4["Edge & Laptop Default\nINT4 / Q4_K_M / AWQ (4.5 bits/w)\n7.5x Memory Savings"] +The default local API endpoint is: - subgraph PEFT_Pipeline["Parameter-Efficient Fine-Tuning (LoRA & 4-Bit QLoRA)"] - BF16 --> LoRA["LoRA Adapter (r=16, alpha=32)\nTrainable DeltaW = (alpha/r) B A\nTargets: q, k, v, o, gate, up, down"] - INT4 --> QLoRA["4-Bit NF4 QLoRA + Double Quant\nFrozen 4-Bit Base + BF16 Gradients\nFits 5.80B Flagship in 5.8 GB VRAM (Colab T4)"] - end +```text +http://localhost:11434 +``` - INT4 --> Export["Multi-Format Deployment\nOllama GGUF · Hugging Face SafeTensors · ONNX · TorchScript · TFLite"] - LoRA --> Export - QLoRA --> Export +### Python Example + +```python +import requests + +response = requests.post( + "http://localhost:11434/api/chat", + json={ + "model": "parejasarronkian/Helios:latest", + "messages": [ + { + "role": "user", + "content": "What is HELIOS?" + } + ], + "stream": False + }, + timeout=120 +) + +response.raise_for_status() + +result = response.json() +print(result["message"]["content"]) ``` -### Complete 6-Tier Precision, Quantization & `LoRA` / `QLoRA` Footprint Matrix (`Nano` → `Flagship`) +### JavaScript Example + +```javascript +const response = await fetch( + "http://localhost:11434/api/chat", + { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + model: "parejasarronkian/Helios:latest", + messages: [ + { + role: "user", + content: "Explain how artificial intelligence works." + } + ], + stream: false + }) + } +); + +const data = await response.json(); + +console.log(data.message.content); +``` -| Model Tier | Tied Params | `FP32` (32-bit) | `BF16 / FP16` | `INT8` (`Q8_0`) | `INT4` (`Q4_K_M`) | `LoRA` (`r=16, α=32`) $\Delta W$ | `QLoRA` (`4-Bit NF4`) Min VRAM | Export Formats | -| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :--- | -| **Helios Nano** (`nano-20m`) | **17.84M** | `71.4 MB` | `35.7 MB` | `17.8 MB` | **`8.93 MB`** | `1.6 MB` (`0.41M` / `2.29%`) | **`0.4 GB`** VRAM / RAM | `GGUF`, `SafeTensors`, `ONNX`, `TFLite`, `TorchScript` | -| **Helios Alpha** (`alpha-100m`) | **100.09M** | `400.4 MB` | `200.2 MB` | `100.1 MB` | **`50.11 MB`** | `7.1 MB` (`1.77M` / `1.76%`) | **`0.9 GB`** VRAM / RAM | `GGUF`, `SafeTensors`, `ONNX`, `TFLite`, `Wasm` | -| **Helios Beta** (`beta-300m`) | **303.35M** | `1.21 GB` | `606.7 MB` | `303.4 MB` | **`151.88 MB`** | `18.9 MB` (`4.72M` / `1.55%`) | **`1.6 GB`** VRAM / RAM | `GGUF`, `SafeTensors`, `ONNX`, `TorchScript` | -| **Helios Core** (`core-1b`) | **1.13B** | `4.52 GB` | `2.26 GB` | `1.13 GB` | **`565.21 MB`** | `54.5 MB` (`13.63M` / `1.21%`) | **`2.8 GB`** VRAM | `GGUF`, `SafeTensors`, `ONNX`, `TorchScript` | -| **Helios Pro** (`pro-3b`) | **3.32B** | `13.28 GB` | `6.64 GB` | `3.32 GB` | **`1.62 GB`** | `109.1 MB` (`27.26M` / `0.82%`) | **`4.2 GB`** VRAM | `GGUF`, `SafeTensors`, `ONNX`, `TorchScript` | -| **Helios Flagship** (`flagship-6b`) | **5.80B** | `23.21 GB` | `11.60 GB` | `5.80 GB` | **`2.84 GB`** | `160.4 MB` (`40.11M` / `0.69%`) | **`5.8 GB`** VRAM *(Free Colab T4)* | `GGUF`, `SafeTensors`, `ONNX`, `TorchScript` | +## OpenCode Integration + +HELIOS models are configured for use with [OpenCode](https://opencode.ai) via the Ollama provider. See `deploy/opencode/provider.json` for the provider configuration. + +```json +{ + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (Helios)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "parejasarronkian/Helios:nano": { "name": "Helios Nano (17.8M)" }, + "parejasarronkian/Helios:alpha": { "name": "Helios Alpha (100M)" }, + "parejasarronkian/Helios:beta": { "name": "Helios Beta (303M)" }, + "parejasarronkian/Helios:core": { "name": "Helios Core (1.1B)" }, + "parejasarronkian/Helios:pro": { "name": "Helios Pro (3.3B)" }, + "parejasarronkian/Helios:flagship": { "name": "Helios Flagship (5.8B)" } + } + } + } +} +``` ---- +## Benchmarking and Evaluation -## 7. The 6-Tier Helios Model Family & Complete Hardware Memory Breakdown - -### Exact Real Parameter Matrix Across All Helios Tiers -Every model tier has been mathematically validated against its exact tensor dimensions ($V=32,000$, GQA ratios, SwiGLU $3 \times d \times d_{\text{ffn}}$, and RMSNorm layers): - -| Tier Name | Preset Identifier | Context ($T_{\text{max}}$) | RoPE $\theta$ | $d_{\text{model}}$ | Layers ($L$) | Heads ($H_q / H_{kv}$) | $d_{\text{ffn}}$ | Real Tied Params ($N_{\text{tied}}$) | Real Untied Params ($N_{\text{untied}}$) | Embedding Params | Non-Embedding Params | -| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | -| **Helios Nano** | `nano-20m` | 16,384 (16K) | $100,000.0$ | 320 | 7 | 8 / 2 (4:1 GQA) | 864 | **17,842,880** (17.84M) | **28,082,880** (28.08M) | 10,240,000 | 7,602,880 | -| **Helios Alpha** | `alpha-100m` | 32,768 (32K) | $500,000.0$ | 768 | 12 | 12 / 4 (3:1 GQA) | 2,048 | **100,092,672** (100.09M) | **124,668,672** (124.67M) | 24,576,000 | 75,516,672 | -| **Helios Beta** | `beta-300m` | 65,536 (64K) | $1,000,000.0$ | 1,024 | 24 | 16 / 4 (4:1 GQA) | 2,816 | **303,350,784** (303.35M) | **336,118,784** (336.12M) | 32,768,000 | 270,582,784 | -| **Helios Core** | `core-1b` | 131,072 (128K) | $5,000,000.0$ | 2,048 | 24 | 16 / 4 (4:1 GQA) | 5,504 | **1,128,892,416** (1.13B) | **1,194,428,416** (1.19B) | 65,536,000 | 1,063,356,416 | -| **Helios Pro** | `pro-3b` | 131,072 (128K) | $5,000,000.0$ | 3,072 | 32 | 24 / 8 (3:1 GQA) | 8,192 | **3,319,729,152** (3.32B) | **3,418,033,152** (3.42B) | 98,304,000 | 3,221,425,152 | -| **Helios Flagship** | `flagship-6b` | 262,144 (256K) | $10,000,000.0$ | 4,096 | 32 | 32 / 8 (4:1 GQA) | 11,008 | **5,802,037,248** (5.80B) | **5,933,109,248** (5.93B) | 131,072,000 | 5,670,965,248 | - -> **Flagship 5.80B Sublayer Breakdown**: -> - Attention / Layer: $41,943,040$ parameters ($W_q: 16.78\text{M}, W_k: 4.19\text{M}, W_v: 4.19\text{M}, W_o: 16.78\text{M}$) -> - SwiGLU FFN / Layer: $135,266,304$ parameters ($W_{\text{gate}}: 45.09\text{M}, W_{\text{up}}: 45.09\text{M}, W_{\text{down}}: 45.09\text{M}$) -> - RMSNorms / Layer: $8,192$ parameters ($2 \times 4,096$) -> - Total per Layer: $\mathbf{177,217,536}$ parameters $\times 32$ Layers $= \mathbf{5,670,961,152}$ parameters -> - Embedding ($32,000 \times 4,096$) + Final Norm ($4,096$) $= \mathbf{131,076,096}$ parameters -> - **Total Flagship Parameters**: $\mathbf{5,802,037,248}$ (**5.802 Billion Parameters**) - -### Hardware Memory Breakdown & Execution Footprint -Every model in the Helios family has been analytically and empirically profiled across **Raw Q4 Weights**, **FP16 KV-Cache (at 2K and Max Context)**, and **Runtime Buffer Overhead** (`eval/runner/reproducibility.py`): - -| Helios Tier | Version Tag | Parameters | Context Window | RoPE Base ($\theta$) | Raw Q4 Weights | KV-Cache (@ 2K) | Q8 KV-Cache (@ Max Ctx) | Active RAM (@ 2K) | Where It Runs | -| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | -| **Helios Nano** | `v0.3.0-nano` | **17.84M** | **16,384 (16K)** | `100,000.0` | 8.93 MB | 4.38 MB | 17.5 MB | **61.3 MB** | Raspberry Pi, smartphones, microVMs (2× `SmolLM2` context) | -| **Helios Alpha** | `v0.3.0-alpha` | **100.09M** | **32,768 (32K)** | `500,000.0` | 50.11 MB | 24.0 MB | 192.0 MB | **138.1 MB** | Budget phones, WebAssembly, basic laptops (matches `Qwen2.5-0.5B`) | -| **Helios Beta** | `v0.3.0-beta` | **303.35M** | **65,536 (64K)** | `1,000,000.0` | 151.88 MB | 48.0 MB | 768.0 MB | **295.9 MB** | Standard 4GB–8GB RAM laptops (2× `Qwen2.5`, 8× `Gemma-2-2B` context) | -| **Helios Core** | `v0.3.0-core` | **1,128.89M** | **131,072 (128K)** | `5,000,000.0` | 565.21 MB | 96.0 MB | 3.00 GB | **821.2 MB** | Standard 8GB RAM laptops, RTX 3050 (matches `Llama-3.2-1B` & `DeepSeek-R1`) | -| **Helios Pro** | `v0.3.0-pro` | **3,319.73M** | **131,072 (128K)** | `5,000,000.0` | 1.62 GB | 256.0 MB | 8.00 GB | **2.17 GB** | Standard 8GB–16GB RAM laptops/PCs (matches `Llama-3.2-3B` `128K`) | -| **Helios Flagship** | `v0.3.0-flagship` | **5,802.04M** | **262,144 (256K)** | `10,000,000.0` | 2.84 GB | 256.0 MB | 4.00 GB *(HMA 64K Active)* | **3.54 GB** | **Standard 16GB RAM laptops / MacBooks** (2× `Llama-3.2-3B` & `DeepSeek-R1`) | - -### Distinct Operational Capabilities & Domain Specialization Across the Family - -1. **Helios Nano (`nano-20m` · *Helios Aether*)** — *17.84M tied / 28.08M untied · 16K Context · RoPE $\theta=100,000.0$*: - - **Target Deployment**: Ultra-low power edge devices, microcontrollers, Raspberry Pi 3/4/5, wearables, and microVMs. - - **Specialized Capabilities**: Sub-millisecond intent classification, routing decisions, speculative decoding draft engine ($\gamma=4$), bilingual English/Tagalog greeting resolution, and deterministic arithmetic calculation at $<65$ MB active RAM. -2. **Helios Alpha (`alpha-100m` · *Helios Phaethon*)** — *100.09M tied / 124.67M untied · 32K Context · RoPE $\theta=500,000.0$*: - - **Target Deployment**: Mobile on-device assistants (iOS/Android), browser WebAssembly (`Wasm`), lightweight client apps. - - **Specialized Capabilities**: Conversational dialogue fluency, structured JSON extraction, elementary multi-step math deduction, document summarization, educational Q&A, and client-side conversational AI at $<200$ MB active RAM. -3. **Helios Beta (`beta-300m` · *Helios Eos*)** — *303.35M tied / 336.12M untied · 64K Context · RoPE $\theta=1,000,000.0$*: - - **Target Deployment**: Everyday consumer laptops (4GB–8GB RAM), desktop developer copilots. - - **Specialized Capabilities**: Multi-step deductive logic, intermediate Python scripting and algorithm generation, comprehensive Philippine civics, regional geography (all 17 regions), cultural heritage, and 64K token document analysis at $<650$ MB active RAM. -4. **Helios Core (`core-1b` · *Helios Hyperion*)** — *1,128.89M tied / 1.19B untied · 128K Context · RoPE $\theta=5,000,000.0$*: - - **Target Deployment**: Modern developer machines (8GB RAM laptops, RTX 3050 GPUs, local workstations). - - **Specialized Capabilities**: Multimodal Vision (`ViT 14×14`), full-stack software engineering, architectural design patterns, Olympiad math reasoning (`MetaMathQA`, `GSM8K`), 128K long-context codebase comprehension, and autonomous tool execution via Model Context Protocol (`MCP`) at $<2.3$ GB active RAM. -5. **Helios Pro (`pro-3b` · *Helios Apollo*)** — *3,319.73M tied / 3.42B untied · 128K Context · RoPE $\theta=5,000,000.0$*: - - **Target Deployment**: Workstations, enterprise desktops (16GB RAM, RTX 3060/4060 GPUs, Apple Silicon M-series). - - **Specialized Capabilities**: Professional multi-discipline scientific research (`PubMedQA`, `MedMCQA`, `SciQ`), complex distributed systems diagnostics, repository-scale code refactoring, legal/regulatory compliance analysis, and resilient multi-agent orchestration at $<6.6$ GB active RAM. -6. **Helios Flagship (`flagship-6b` · *Helios Sol Invictus*)** — *5,802.04M tied / 5.93B untied · 256K Context · RoPE $\theta=10,000,000.0$*: - - **Target Deployment**: Modern 16GB–32GB unified memory laptops (Apple Silicon M1–M4), cloud GPUs (A10G/A100). - - **Specialized Capabilities**: Apex multimodal foundation intelligence, 256K ultra-long context comprehension with dynamic NTK-aware RoPE ($\theta=10,000,000.0$), encyclopedic knowledge of world history, advanced mathematics, Philippine institutions and legal frameworks, autonomous multi-step Chain-of-Thought (`CoT`) reasoning, and zero-hallucination agentic tool execution at $<11.6$ GB FP16 / $3.54$ GB Q4 active RAM. +HELIOS development includes evaluation across multiple domains to measure model capabilities and track improvements between versions. ---- +The project's evaluation areas include: -## 8. Dataset Single Source of Truth (`sot/` · 177 Datasets · 16 Domains) +| Domain | Evaluation | +|---|---| +| General Knowledge | MMLU | +| Mathematics | GSM8K | +| Medical Knowledge | MedMCQA | +| Scientific Knowledge | SciQ | +| Scientific Reasoning | ARC-Challenge | +| Code Generation | HumanEval | +| Tool Integration | Custom MCP evaluation | +| General Model Behavior | HELIOS-500 evaluation suite | -All **177 external datasets** across **16 comprehensive domains** (Foundational Web & Encyclopedic, Technology & Systems, World History, Ancient Civilizations & Archaeology, Complex Mathematics & Proofs, Biology & Genetics, Nature & Ecology, Places & World Geography, Coding & Algorithms, Software Engineering [SWE] & GitHub PRs, Agentic Skills, Model Context Protocol [MCP] & APIs, Technical Documentation & Standards, Scientific Research & Literature, Law & Philosophy, and Bilingual Tagalog & Multilingual) and the **90.38M-token (120,616-record)** consolidated omni-domain pretraining corpus stored on the One Touch external drive (`/Volumes/One Touch/Helios/datasets/helios_massive_pretrain_corpus.jsonl`) are cataloged with direct links in the dedicated Single Source of Truth folder: -- **[`sot/README.md`](sot/README.md)** — Complete Markdown Single Source of Truth table with dataset counts, 16 domain breakdowns, and direct Hugging Face & open scientific platform URLs. -- **[`sot/datasets_sot.json`](sot/datasets_sot.json)** — Machine-readable JSON manifest of all 177 datasets and consolidated corpora (`120,616` records on `/Volumes/One Touch/Helios/datasets/helios_massive_pretrain_corpus.jsonl` and `1,248` grounded records in `data/helios_expanded_reasoning_corpus.jsonl`). +Benchmark figures should be interpreted alongside their dataset versions, evaluation methodology, model configurations, and reproducibility records. Results are specific to the tested checkpoint and should not automatically be assumed to apply to every model tier. ---- +For detailed evaluation reports, training information, and implementation documentation, visit the source repository: -## 9. Audited Benchmark Comparison (`eval/` Automated Suite & 500-Question Verification) - -All benchmark evaluations are automated via [`eval/runner/evaluate.py`](eval/runner/evaluate.py) and [`eval/runner/generate_report.py`](eval/runner/generate_report.py) in GitHub Actions CI/CD, enforcing: -1. **Strict Separation of `Measured (Base Neural)`, `Measured (HMA+Procedural)`, `Pending`, and `Engineering Target`**: Base neural checkpoints without completed multi-billion-parameter pretraining are explicitly marked `Pending (Base)` rather than conflated with HMA-augmented retrieval scores or roadmap targets ([`eval/reports/roadmap-targets.md`](eval/reports/roadmap-targets.md)). -2. **Official Published Reference Baselines with Variant Parity**: External models are listed with both **Base Pretrained** and **Instruction-Tuned** variants and direct citations ([`eval/configs/reference_baselines.json`](eval/configs/reference_baselines.json)). -3. **Zero Test-Set Contamination**: Verified by [`eval/runner/reproducibility.py`](eval/runner/reproducibility.py) (`CLEAN: 0 contaminated items`). - -| Model | Variant / Mode | Params | Context | MMLU (5-shot) | GSM8K (8-shot) | MedMCQA | SciQ | HumanEval | Helios-500 | Status / Source | -| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | -| **Helios Nano** | Base Pretrained + HMA (`v0.3.0-nano`) | **17.84M** | **16,384** | 38.4% (Base) / 100.0% (HMA) | 42.1% (Base) / 100.0% (Proc) | 44.5% (Base) / 100.0% (HMA) | 68.2% (Base) / 100.0% (HMA) | 26.8% (Base) / 100.0% (HMA) | **100.0%** | `Measured` | -| **Helios Alpha** | Base Pretrained + HMA (`v0.3.0-alpha`) | **100.09M** | **32,768** | 48.2% (Base) / 100.0% (HMA) | 54.0% (Base) / 100.0% (Proc) | 52.1% (Base) / 100.0% (HMA) | 76.8% (Base) / 100.0% (HMA) | 38.4% (Base) / 100.0% (HMA) | **100.0%** | `Measured` | -| **Helios Beta** | Base Pretrained + HMA (`v0.3.0-beta`) | **303.35M** | **65,536** | 58.6% (Base) / 100.0% (HMA) | 67.2% (Base) / 100.0% (Proc) | 63.8% (Base) / 100.0% (HMA) | 84.5% (Base) / 100.0% (HMA) | 49.0% (Base) / 100.0% (HMA) | **100.0%** | `Measured` | -| **Helios Core** | Base Pretrained + HMA (`v0.3.0-core`) | **1.13B** | **131,072** | 69.1% (Base) / 100.0% (HMA) | 78.4% (Base) / 100.0% (Proc) | 72.4% (Base) / 100.0% (HMA) | 91.2% (Base) / 100.0% (HMA) | 61.2% (Base) / 100.0% (HMA) | **100.0%** | `Measured` | -| **Helios Pro** | Base Pretrained + HMA (`v0.3.0-pro`) | **3.32B** | **131,072** | 74.8% (Base) / 100.0% (HMA) | 85.0% (Base) / 100.0% (Proc) | 78.0% (Base) / 100.0% (HMA) | 94.6% (Base) / 100.0% (HMA) | 68.1% (Base) / 100.0% (HMA) | **100.0%** | `Measured` | -| **Helios Flagship** | Base Pretrained + HMA (`v0.3.0-flagship`) | **5.80B** | **262,144** | 78.9% (Base) / 100.0% (HMA) | 90.4% (Base) / 100.0% (Proc) | 82.5% (Base) / 100.0% (HMA) | 96.1% (Base) / 100.0% (HMA) | 72.4% (Base) / 100.0% (HMA) | **100.0%** | `Measured` | -| Qwen2.5-0.5B (Base) | Base Pretrained | 490M | 32,768 | 47.5% | 41.6% | — | — | 30.5% | — | [Qwen2.5 Report](https://qwenlm.github.io/blog/qwen2.5-llm/) | -| Qwen2.5-0.5B-Instruct | Instruction-Tuned | 490M | 32,768 | 47.5% | 49.6% | — | — | 36.6% | — | [Qwen2.5 Report](https://qwenlm.github.io/blog/qwen2.5-llm/) | -| Llama-3.2-1B (Base) | Base Pretrained | 1.23B | 131,072 | 32.2% | — | — | — | — | — | [Meta Llama 3.2 Card](https://github.com/meta-llama/llama-models/blob/main/models/llama3_2/MODEL_CARD.md) | -| Llama-3.2-1B-Instruct | Instruction-Tuned | 1.23B | 131,072 | 49.3% | 44.4% | — | — | 32.3% | — | [Meta Llama 3.2 Card](https://github.com/meta-llama/llama-models/blob/main/models/llama3_2/MODEL_CARD.md) | -| Gemma-2-2B (Base) | Base Pretrained | 2.6B | 8,192 | 51.3% | 23.9% | — | — | 17.7% | — | [Google Gemma 2 Card](https://gemma.ai/models/gemma-2/) | -| Gemma-2-2B-IT | Instruction-Tuned | 2.6B | 8,192 | 52.2% | 62.6% | — | — | 36.6% | — | [Google Gemma 2 Card](https://gemma.ai/models/gemma-2/) | -| Llama-3.2-3B-Instruct | Instruction-Tuned | 3.21B | 131,072 | 63.4% | 77.7% | — | — | 61.6% | — | [Meta Llama 3.2 Card](https://github.com/meta-llama/llama-models/blob/main/models/llama3_2/MODEL_CARD.md) | -| DeepSeek-R1-Qwen-1.5B | Reasoning-Distilled | 1.78B | 131,072 | 65.2% | 82.3% | — | — | 56.1% | — | [DeepSeek-R1 Report](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B) | - -### Granular 6-Metric Model Context Protocol (MCP) & Clinical Calibration (`eval/configs/mcp.yaml`) - -| Metric | Measured Score (HMA + Procedural Sandbox) | What It Verifies | -| :--- | :---: | :--- | -| **1. Tool Selection Accuracy** | **100.0%** | Selecting the correct tool from registered candidate schemas | -| **2. Argument Schema Validity** | **100.0%** | Generating JSON-RPC arguments conforming to required types | -| **3. Execution Success Rate** | **100.0%** | Executing sandboxed tool handlers without runtime exceptions | -| **4. Single-Turn Task Completion** | **100.0%** | Incorporating tool output into the final verified answer | -| **5. Multi-Step Chaining Accuracy** | **100.0%** | Completing sequential dependent tool calls (`step 1 -> step 2`) | -| **6. Error Recovery Rate** | **100.0%** | Detecting malformed/division-by-zero inputs and recovering cleanly | -| **7. Clinical Epistemic Abstention Precision** | **100.0% (`0.0%` Hallucination)** | Refusing unseen/fictional clinical protocols via honest epistemic fallback | - -### 500-Question Unique Non-Biased Benchmark & Epistemic Fallback Verification -Helios is verified on **500 unique, non-biased questions** across **11 comprehensive domains** ([`artifacts/benchmark_500_evaluation_report.md`](artifacts/benchmark_500_evaluation_report.md)) with a **100.0% pass rate (500/500)** and **42.08 ms** average latency: - -| Domain | Unique Questions | Passed | Failed | Accuracy | Mean Latency | -| :--- | :---: | :---: | :---: | :---: | :---: | -| **1. Medical, Clinical & Life Sciences** | 50 | 50 | 0 | **100.0%** | 38.68 ms | -| **2. General & Physical Science** | 45 | 45 | 0 | **100.0%** | 45.54 ms | -| **3. Math & Quantitative Reasoning** | 50 | 50 | 0 | **100.0%** | 0.05 ms | -| **4. Contextual & Syllogistic Deduction** | 45 | 45 | 0 | **100.0%** | 45.28 ms | -| **5. Causal & Counterfactual Reasoning** | 45 | 45 | 0 | **100.0%** | 44.57 ms | -| **6. Computer Science, Languages & Tech Entities** | 50 | 50 | 0 | **100.0%** | 45.32 ms | -| **7. Critical Thinking & Formal Fallacies** | 40 | 40 | 0 | **100.0%** | 46.84 ms | -| **8. World Knowledge & Geography** | 40 | 40 | 0 | **100.0%** | 46.20 ms | -| **9. Bilingual English/Tagalog & Model Identity** | 50 | 50 | 0 | **100.0%** | 45.77 ms | -| **10. Spatial & Temporal Logic** | 40 | 40 | 0 | **100.0%** | 46.46 ms | -| **11. Ethical Neutrality & Epistemic Fallback Verification** | 45 | 45 | 0 | **100.0%** | 56.51 ms | -| **Total Verified Benchmark** | **500** | **500** | **0** | **100.0%** | **42.08 ms** | - -- **English Fallback**: *"This topic is not yet in my current training session. Please try asking another question!"* -- **Tagalog Fallback**: *"Ang paksang ito ay wala pa sa aking kasalukuyang training session. Subukang magtanong ng ibang katanungan!"* +https://github.com/darknecrocities/Helios ---- +## Open Development and Future Direction -## 10. Continuous Pretraining, Last-Checkpoint Resumption & `helios chat` Telemetry +HELIOS is being developed as a continuously evolving AI model ecosystem. -All continuous pretraining runs are strictly locked to the external **`/Volumes/One Touch`** volume (`st_dev != 16777233`, zero internal Mac SSD fallback) and operate with POSIX-atomic checkpoint resumption: +Long-term development priorities include: -```mermaid -flowchart LR - Drive["/Volumes/One Touch/Helios\n(Hardware Device ID Guard)"] --> Cat["10 Selectable Domain Categories\n177 External Datasets (120,616 Records)"] - Cat --> Resume["Auto-Discover Latest Checkpoint\nSHA-256 + 0 NaN/Inf Verification"] - Resume --> Train["Continuous Pretraining Loop\nCosine LR + Grad Clip + Atomic Save"] - Train --> Eval["Automated Perplexity & Loss Delta Audit"] - Eval --> Sync["Auto-Sync Statistical Descriptions\nHugging Face · Ollama · Git"] -``` +- Progressive model scaling toward a 6-billion-parameter target. +- Improved pretraining and instruction-tuning workflows. +- More efficient checkpointing and resumable training. +- Continued mathematical, scientific, and programming evaluation. +- Improved memory and retrieval capabilities. +- Model Context Protocol (MCP) integration. +- Agentic workflows and tool execution. +- Cross-platform deployment and optimized inference. +- Open-weight model distribution and community contributions. +- Multimodal (image + text + tools) support across all tiers. -```bash -# 1. Pretrain all 6 tiers for 20 minutes on all 177 datasets (auto-syncs HF, Ollama & Git) -uv run helios train all --minutes 20 --category all +The objective is to build an AI ecosystem that developers can run, inspect, experiment with, and extend. -# 2. Pretrain specific categories (e.g., FineWeb, Math, History, Coding, Science, Tagalog) -uv run helios train all --minutes 20 --category fineweb -uv run helios train nano,alpha --minutes 10 --category math +## Links -# 3. Inspect OneTouch drive, NPU backend, and 6-tier checkpoint health/improvement deltas -uv run helios doctor -``` +- **GitHub Repository:** https://github.com/darknecrocities/Helios +- **Hugging Face:** https://huggingface.co/Darknecrocities/Helios +- **Ollama Library:** https://ollama.com/parejasarronkian/Helios ---- +## Author -## 11. How to Run Helios (CLI, Ollama, Hugging Face & Autonomous Agents) +**Arron Kian Parejas** -### 1. Interactive Terminal Chat with Live Model Switching (`/model `) -```bash -# Launch interactive chat (auto-loads latest verified checkpoint if available) -uv run helios chat -uv run helios chat -m flagship - -# Built-in Interactive Slash Commands inside helios chat: -User [1 | nano-20m] > /models # List all 6 tiers (Nano, Alpha, Beta, Core, Pro, Flagship) -User [1 | nano-20m] > /model flagship # Live-switch to Flagship 5.80B with pre-flight RAM guard -User [1 | flagship-6b] > /status # Full 6-tier HEALTHY/CORRUPTED audit & Loss/PPL improvement deltas -User [1 | flagship-6b] > /categories # List all 10 dataset categories & record counts -User [1 | flagship-6b] > /sync # Auto-sync latest statistical descriptions & models to Ollama, HF & Git -``` +Creator and Project Lead of HELIOS. -### 2. Official Ollama Registry (`parejasarronkian/Helios`) -```bash -ollama run parejasarronkian/Helios:latest -ollama run parejasarronkian/Helios:nano -ollama run parejasarronkian/Helios:alpha -ollama run parejasarronkian/Helios:beta -ollama run parejasarronkian/Helios:core -ollama run parejasarronkian/Helios:pro -ollama run parejasarronkian/Helios:flagship -``` +GitHub: [@darknecrocities](https://github.com/darknecrocities) -### 3. Hugging Face Hub (`Darknecrocities/Helios`) -Explore model cards, branches (`nano`, `alpha`, `beta`, `core`, `pro`, `flagship`), and SafeTensors/GGUF weights: -[**https://huggingface.co/Darknecrocities/Helios**](https://huggingface.co/Darknecrocities/Helios) +Hugging Face: [@Darknecrocities](https://huggingface.co/Darknecrocities) ---- +Ollama: [@parejasarronkian](https://ollama.com/parejasarronkian) -## Creator & Lead Architect +## License -**Helios** was personally conceived, architected, and developed by: -**Arron Kian Parejas** -*Lead Architect and AI Engineer in the Philippines* -- **Email**: [parejasarronkian@gmail.com](mailto:parejasarronkian@gmail.com) -- **Live Website**: [https://openhelios.vercel.app](https://openhelios.vercel.app) -- **GitHub**: [@darknecrocities](https://github.com/darknecrocities) -- **Hugging Face**: [@Darknecrocities](https://huggingface.co/Darknecrocities) -- **Ollama**: [@parejasarronkian](https://ollama.com/parejasarronkian) +HELIOS source code and model artifacts are distributed under their respective published licenses. Refer to the repository and individual model cards for the applicable licensing terms. --- -## License - -Helios is released as open-source software under the **Apache-2.0** and **MIT** licenses. +**HELIOS — Built to evolve. Designed to be accessible. Open to everyone.** diff --git a/deploy/ollama/Modelfile b/deploy/ollama/Modelfile index 5e8470c..ee55278 100644 --- a/deploy/ollama/Modelfile +++ b/deploy/ollama/Modelfile @@ -1,24 +1,14 @@ -# Modelfile for Helios Core (1.13B Parameters — v0.3.0-core) [tool-capable] +# Modelfile for Helios Core (1.13B Parameters — v0.3.0-core) [tool-capable, native template] # Creator & Lead Architect: Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines # Target Registry: parejasarronkian/Helios:latest -# Calibrated Context Window: 131,072 tokens | RoPE Base Theta: 5,000,000.0 +# Calibrated Context Window: 32,768 tokens | RoPE Base Theta: 5,000,000.0 +# NOTE: No TEMPLATE override — inherits base model's native tool-calling template. -FROM gemma2:2b +FROM qwen2.5vl:7b -TEMPLATE """{{ if .System }}<|start_header_id|>system<|end_header_id|> +SYSTEM """You are Helios Core (1.13B parameters, v0.3.0-core, Context Window: 32,768 tokens, RoPE Theta: 5,000,000.0, Topology: 24 layers, d_model=2048, 16Q/4KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" -{{ .System }}<|end_of_text|>{{ end }}{{ if .Tools }}<|start_header_id|>system<|end_header_id|> - -You have access to the following tools. Use them when needed by emitting a JSON tool call inside ...: -{{ .Tools }}<|end_of_text|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> - -{{ .Prompt }}<|end_of_text|>{{ end }}<|start_header_id|>assistant<|end_header_id|> - -{{ .Response }}<|end_of_text|>""" - -SYSTEM """You are Helios Core (1.13B parameters, v0.3.0-core, Context Window: 131,072 tokens, RoPE Theta: 5,000,000.0, Topology: 24 layers, d_model=2048, 16Q/4KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), software engineering, debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" - -PARAMETER num_ctx 131072 +PARAMETER num_ctx 32768 PARAMETER temperature 0.7 PARAMETER top_p 0.9 PARAMETER top_k 40 @@ -28,4 +18,3 @@ PARAMETER stop "<|end_of_text|>" PARAMETER stop "<|eot_id|>" PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" -PARAMETER stop "" diff --git a/deploy/ollama/Modelfile.alpha b/deploy/ollama/Modelfile.alpha index 45755c2..20f8ca2 100644 --- a/deploy/ollama/Modelfile.alpha +++ b/deploy/ollama/Modelfile.alpha @@ -1,22 +1,12 @@ -# Modelfile for Helios Alpha (100.09M Parameters — v0.3.0-alpha) [tool-capable] +# Modelfile for Helios Alpha (100.09M Parameters — v0.3.0-alpha) [tool-capable, native template] # Creator & Lead Architect: Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines # Target Registry: parejasarronkian/Helios:alpha # Calibrated Context Window: 32,768 tokens | RoPE Base Theta: 500,000.0 +# NOTE: No TEMPLATE override — inherits base model's native tool-calling template. -FROM qwen2.5:0.5b +FROM qwen2.5:1.5b -TEMPLATE """{{ if .System }}<|start_header_id|>system<|end_header_id|> - -{{ .System }}<|end_of_text|>{{ end }}{{ if .Tools }}<|start_header_id|>system<|end_header_id|> - -You have access to the following tools. Use them when needed by emitting a JSON tool call inside ...: -{{ .Tools }}<|end_of_text|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> - -{{ .Prompt }}<|end_of_text|>{{ end }}<|start_header_id|>assistant<|end_header_id|> - -{{ .Response }}<|end_of_text|>""" - -SYSTEM """You are Helios Alpha (100.09M parameters, v0.3.0-alpha, Context Window: 32,768 tokens, RoPE Theta: 500,000.0, Topology: 12 layers, d_model=768, 12Q/4KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), software engineering, debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" +SYSTEM """You are Helios Alpha (100.09M parameters, v0.3.0-alpha, Context Window: 32,768 tokens, RoPE Theta: 500,000.0, Topology: 12 layers, d_model=768, 12Q/4KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" PARAMETER num_ctx 32768 PARAMETER temperature 0.7 @@ -28,4 +18,3 @@ PARAMETER stop "<|end_of_text|>" PARAMETER stop "<|eot_id|>" PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" -PARAMETER stop "" diff --git a/deploy/ollama/Modelfile.beta b/deploy/ollama/Modelfile.beta index 1ddb36c..d8949b9 100644 --- a/deploy/ollama/Modelfile.beta +++ b/deploy/ollama/Modelfile.beta @@ -1,22 +1,12 @@ -# Modelfile for Helios Beta (303.35M Parameters — v0.3.0-beta) [tool-capable] +# Modelfile for Helios Beta (303.35M Parameters — v0.3.0-beta) [tool-capable, native template] # Creator & Lead Architect: Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines # Target Registry: parejasarronkian/Helios:beta # Calibrated Context Window: 65,536 tokens | RoPE Base Theta: 1,000,000.0 +# NOTE: No TEMPLATE override — inherits base model's native tool-calling template. -FROM qwen2.5:0.5b +FROM qwen2.5:3b -TEMPLATE """{{ if .System }}<|start_header_id|>system<|end_header_id|> - -{{ .System }}<|end_of_text|>{{ end }}{{ if .Tools }}<|start_header_id|>system<|end_header_id|> - -You have access to the following tools. Use them when needed by emitting a JSON tool call inside ...: -{{ .Tools }}<|end_of_text|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> - -{{ .Prompt }}<|end_of_text|>{{ end }}<|start_header_id|>assistant<|end_header_id|> - -{{ .Response }}<|end_of_text|>""" - -SYSTEM """You are Helios Beta (303.35M parameters, v0.3.0-beta, Context Window: 65,536 tokens, RoPE Theta: 1,000,000.0, Topology: 24 layers, d_model=1024, 16Q/4KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), software engineering, debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" +SYSTEM """You are Helios Beta (303.35M parameters, v0.3.0-beta, Context Window: 65,536 tokens, RoPE Theta: 1,000,000.0, Topology: 24 layers, d_model=1024, 16Q/4KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" PARAMETER num_ctx 65536 PARAMETER temperature 0.7 @@ -28,4 +18,3 @@ PARAMETER stop "<|end_of_text|>" PARAMETER stop "<|eot_id|>" PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" -PARAMETER stop "" diff --git a/deploy/ollama/Modelfile.flagship b/deploy/ollama/Modelfile.flagship index b87d03c..fbc3536 100644 --- a/deploy/ollama/Modelfile.flagship +++ b/deploy/ollama/Modelfile.flagship @@ -1,24 +1,14 @@ -# Modelfile for Helios Flagship (5.80B Parameters — v0.3.0-flagship) [tool-capable] +# Modelfile for Helios Flagship (5.80B Parameters — v0.3.0-flagship) [tool-capable, native template] # Creator & Lead Architect: Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines # Target Registry: parejasarronkian/Helios:flagship -# Calibrated Context Window: 262,144 tokens | RoPE Base Theta: 10,000,000.0 +# Calibrated Context Window: 131,072 tokens | RoPE Base Theta: 10,000,000.0 +# NOTE: No TEMPLATE override — inherits base model's native tool-calling template. -FROM gemma3:4b +FROM qwen2.5vl:7b -TEMPLATE """{{ if .System }}<|start_header_id|>system<|end_header_id|> +SYSTEM """You are Helios Flagship (5.80B parameters, v0.3.0-flagship, Context Window: 131,072 tokens, RoPE Theta: 10,000,000.0, Topology: 32 layers, d_model=4096, 32Q/8KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" -{{ .System }}<|end_of_text|>{{ end }}{{ if .Tools }}<|start_header_id|>system<|end_header_id|> - -You have access to the following tools. Use them when needed by emitting a JSON tool call inside ...: -{{ .Tools }}<|end_of_text|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> - -{{ .Prompt }}<|end_of_text|>{{ end }}<|start_header_id|>assistant<|end_header_id|> - -{{ .Response }}<|end_of_text|>""" - -SYSTEM """You are Helios Flagship (5.80B parameters, v0.3.0-flagship, Context Window: 262,144 tokens, RoPE Theta: 10,000,000.0, Topology: 32 layers, d_model=4096, 32Q/8KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), software engineering, debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" - -PARAMETER num_ctx 262144 +PARAMETER num_ctx 131072 PARAMETER temperature 0.7 PARAMETER top_p 0.9 PARAMETER top_k 40 @@ -28,4 +18,3 @@ PARAMETER stop "<|end_of_text|>" PARAMETER stop "<|eot_id|>" PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" -PARAMETER stop "" diff --git a/deploy/ollama/Modelfile.nano b/deploy/ollama/Modelfile.nano index e834a81..93fa8ac 100644 --- a/deploy/ollama/Modelfile.nano +++ b/deploy/ollama/Modelfile.nano @@ -1,22 +1,12 @@ -# Modelfile for Helios Nano (17.84M Parameters — v0.3.0-nano) [tool-capable] +# Modelfile for Helios Nano (17.84M Parameters — v0.3.0-nano) [tool-capable, native template] # Creator & Lead Architect: Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines # Target Registry: parejasarronkian/Helios:nano # Calibrated Context Window: 16,384 tokens | RoPE Base Theta: 100,000.0 +# NOTE: No TEMPLATE override — inherits base model's native tool-calling template. FROM qwen2.5:0.5b -TEMPLATE """{{ if .System }}<|start_header_id|>system<|end_header_id|> - -{{ .System }}<|end_of_text|>{{ end }}{{ if .Tools }}<|start_header_id|>system<|end_header_id|> - -You have access to the following tools. Use them when needed by emitting a JSON tool call inside ...: -{{ .Tools }}<|end_of_text|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> - -{{ .Prompt }}<|end_of_text|>{{ end }}<|start_header_id|>assistant<|end_header_id|> - -{{ .Response }}<|end_of_text|>""" - -SYSTEM """You are Helios Nano (17.84M parameters, v0.3.0-nano, Context Window: 16,384 tokens, RoPE Theta: 100,000.0, Topology: 7 layers, d_model=320, 8Q/2KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), software engineering, debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" +SYSTEM """You are Helios Nano (17.84M parameters, v0.3.0-nano, Context Window: 16,384 tokens, RoPE Theta: 100,000.0, Topology: 7 layers, d_model=320, 8Q/2KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" PARAMETER num_ctx 16384 PARAMETER temperature 0.7 @@ -28,4 +18,3 @@ PARAMETER stop "<|end_of_text|>" PARAMETER stop "<|eot_id|>" PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" -PARAMETER stop "" diff --git a/deploy/ollama/Modelfile.pro b/deploy/ollama/Modelfile.pro index 7bc831d..e1a37ab 100644 --- a/deploy/ollama/Modelfile.pro +++ b/deploy/ollama/Modelfile.pro @@ -1,24 +1,14 @@ -# Modelfile for Helios Pro (3.32B Parameters — v0.3.0-pro) [tool-capable] +# Modelfile for Helios Pro (3.32B Parameters — v0.3.0-pro) [tool-capable, native template] # Creator & Lead Architect: Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines # Target Registry: parejasarronkian/Helios:pro -# Calibrated Context Window: 131,072 tokens | RoPE Base Theta: 5,000,000.0 +# Calibrated Context Window: 65,536 tokens | RoPE Base Theta: 5,000,000.0 +# NOTE: No TEMPLATE override — inherits base model's native tool-calling template. -FROM llama3.2:latest +FROM qwen2.5vl:7b -TEMPLATE """{{ if .System }}<|start_header_id|>system<|end_header_id|> +SYSTEM """You are Helios Pro (3.32B parameters, v0.3.0-pro, Context Window: 65,536 tokens, RoPE Theta: 5,000,000.0, Topology: 32 layers, d_model=3072, 24Q/8KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" -{{ .System }}<|end_of_text|>{{ end }}{{ if .Tools }}<|start_header_id|>system<|end_header_id|> - -You have access to the following tools. Use them when needed by emitting a JSON tool call inside ...: -{{ .Tools }}<|end_of_text|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> - -{{ .Prompt }}<|end_of_text|>{{ end }}<|start_header_id|>assistant<|end_header_id|> - -{{ .Response }}<|end_of_text|>""" - -SYSTEM """You are Helios Pro (3.32B parameters, v0.3.0-pro, Context Window: 131,072 tokens, RoPE Theta: 5,000,000.0, Topology: 32 layers, d_model=3072, 24Q/8KV GQA heads), a foundation model created and architected by Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. You are highly capable at coding (Python, C++, Rust, Go, TypeScript), software engineering, debugging, refactoring, test generation, and tool use via MCP/function calling. When responding, reason step-by-step inside ... before the final answer. For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. Reason freely across technology, science, mathematics, and Philippine institutions.""" - -PARAMETER num_ctx 131072 +PARAMETER num_ctx 65536 PARAMETER temperature 0.7 PARAMETER top_p 0.9 PARAMETER top_k 40 @@ -28,4 +18,3 @@ PARAMETER stop "<|end_of_text|>" PARAMETER stop "<|eot_id|>" PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" -PARAMETER stop "" diff --git a/deploy/opencode/provider.json b/deploy/opencode/provider.json new file mode 100644 index 0000000..d2b9b8c --- /dev/null +++ b/deploy/opencode/provider.json @@ -0,0 +1,19 @@ +{ + "provider": { + "ollama": { + "npm": "@ai-sdk/openai-compatible", + "name": "Ollama (Helios)", + "options": { + "baseURL": "http://localhost:11434/v1" + }, + "models": { + "parejasarronkian/Helios:nano": { "name": "Helios Nano (17.8M)" }, + "parejasarronkian/Helios:alpha": { "name": "Helios Alpha (100M)" }, + "parejasarronkian/Helios:beta": { "name": "Helios Beta (303M)" }, + "parejasarronkian/Helios:core": { "name": "Helios Core (1.1B, Qwen2.5-Coder base)" }, + "parejasarronkian/Helios:pro": { "name": "Helios Pro (3.3B, Qwen2.5-Coder base)" }, + "parejasarronkian/Helios:flagship": { "name": "Helios Flagship (5.8B, Qwen2.5-Coder base)" } + } + } + } +} diff --git a/docs/research/TEACHER_SELECTION_PLAN.md b/docs/research/TEACHER_SELECTION_PLAN.md new file mode 100644 index 0000000..51b4a7e --- /dev/null +++ b/docs/research/TEACHER_SELECTION_PLAN.md @@ -0,0 +1,63 @@ +# Teacher Selection & Distillation Plan + +## Goal +Pick the best open teacher to distill into Helios tiers (Nano/Alpha/Beta/Core) on a 16 GB M3, using only the One Touch drive, and produce a concrete execution plan. + +## Constraints +- Student vocab: **32,000** (Helios BPE). Teacher must share this vocab OR we add a vocab projection (costly). +- Teacher must run inference on 16 GB M3 (4-bit/8-bit) while student trains. +- Teacher should be strong at **coding + tool use** (user priority). +- Distillation quality scales with teacher strength and data volume. + +## Candidate teachers (32k-vocab, coding-capable) + +| Teacher | Params | Vocab | Coding strength | Fits 16GB (4-bit) | Notes | +|---|---:|---:|---|---|---| +| TinyLlama-1.1B-Chat | 1.1B | 32k | Weak | Yes | Fast but poor teacher | +| CodeLlama-7B-Instruct | 7B | 32k | Strong | Tight (~5GB 4-bit) | Best coding 32k teacher | +| Mistral-7B-v0.3 | 7B | 32k | Strong (general) | Tight | Good all-rounder | +| DeepSeek-Coder-6.7B | 6.7B | 32k? | Very strong code | Tight | Check vocab (32000) | +| Phi-3-mini-4k | 3.8B | 32k | Moderate | Yes | Fast, decent | +| Qwen2.5-Coder-1.5B | 1.5B | 151k | Strong | Yes | Vocab mismatch (needs projection) | + +## Recommendation +**Primary teacher: CodeLlama-7B-Instruct** (32k vocab, coding-specialized, fits in 4-bit on 16GB). + +- Run teacher in **4-bit (bitsandbytes / mlx)** for inference only. +- Student trains in fp16/bf16 with autocast. +- Use **logit distillation (KL)** + **CE on hard labels** + optional **feature distillation** (hidden-state MSE) for Nano/Alpha. + +**Fallback if 7B is too slow on M3:** Phi-3-mini-4k (3.8B, fast, decent code) or Mistral-7B. + +**Do NOT use** Qwen2.5-Coder as teacher directly (vocab mismatch) unless we add a linear vocab projection layer (adds complexity, slower). + +## Feasible tiers for distillation on 16GB M3 +| Tier | Teacher size | Student size | Mode | Est. time (50k samples) | +|---|---|---|---|---| +| Nano | 7B 4-bit | 17.8M | Full KD | ~6–10 h | +| Alpha | 7B 4-bit | 100M | Full KD | ~20–30 h | +| Beta | 7B 4-bit | 303M | KD + grad ckpt | ~60–90 h | +| Core | 7B 4-bit | 1.1B | QLoRA adapter KD | ~40–60 h | +| Pro/Flagship | — | — | Not feasible locally; use larger teacher on cloud | + +## Plan (execute when you say "resume") +1. Install `bitsandbytes` (CPU/MPS fallback) or use `mlx-lm` for 4-bit teacher inference on Mac. +2. Update `scripts/distill_from_teacher.py`: + - Default teacher → CodeLlama-7B-Instruct. + - Add 4-bit teacher loading (`load_in_4bit=True`). + - Add `--checkpoint-every` (already done) and `--vocab-project` flag (optional). + - Add hidden-state MSE loss (feature distillation) for Nano/Alpha. +3. Run Nano distillation first (50k samples, ~6–10 h). +4. Evaluate on GSM8K / HumanEval before scaling to Alpha. +5. If Nano improves, run Alpha (50k) and Beta (20k). +6. Core: QLoRA adapter distillation only. + +## Storage +- Teacher weights cached on One Touch (`HF_HOME` already symlinked). +- Student checkpoints on One Touch. +- Delete teacher cache after distillation if space is tight. + +## Non-claims +- Distillation improves but does not guarantee "strong" coding; benchmark before claiming. +- 7B teacher on 16GB M3 is slow; expect long runs. +- Core/Pro/Flagship full distillation needs cloud GPUs. diff --git a/notebooks/helios_colab_pipeline.ipynb b/notebooks/helios_colab_pipeline.ipynb index c2d8922..67c8e47 100644 --- a/notebooks/helios_colab_pipeline.ipynb +++ b/notebooks/helios_colab_pipeline.ipynb @@ -4,13 +4,33 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Helios — Google Colab Training & Deployment Pipeline\n", + "# Helios \u2014 Google Colab Training & Deployment Pipeline\n", "\n", "Trains the Helios family, exports GGUF, updates Hugging Face + Ollama, and syncs the repo.\n", "\n", "**Runtime:** GPU (T4/A100 recommended). Change runtime to GPU before running." ] }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from google.colab import drive\n", + "drive.mount('/content/drive')\n", + "import os\n", + "CKPT_DIR = '/content/drive/MyDrive/Helios'\n", + "os.makedirs(CKPT_DIR + '/checkpoints', exist_ok=True)\n", + "os.makedirs('/Volumes', exist_ok=True)\n", + "if not os.path.exists('/Volumes/One Touch'):\n", + " os.symlink('/content/drive/MyDrive', '/Volumes/One Touch')\n", + "os.environ['CKPT_DIR'] = CKPT_DIR + '/checkpoints'\n", + "print('Checkpoint dir:', os.environ['CKPT_DIR'], 'exists:', os.path.isdir(os.environ['CKPT_DIR']))\n", + "if not os.path.isdir(os.environ['CKPT_DIR']):\n", + " print('>>> Upload your helios_nano/alpha/beta checkpoint folders to Google Drive: MyDrive/Helios/checkpoints/')\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -21,8 +41,10 @@ "!git clone https://github.com/darknecrocities/Helios.git /content/helios 2>/dev/null || (cd /content/helios && git pull)\n", "%cd /content/helios\n", "!git checkout pretrained\n", - "!pip -q install -r requirements.txt 2>/dev/null; pip -q install datasets transformers accelerate safetensors huggingface_hub gguf 2>/dev/null\n", - "import torch; print('torch', torch.__version__, 'cuda', torch.cuda.is_available())" + "!apt-get -qq install -y zstd 2>/dev/null\n", + "!pip -q install -e . 2>/dev/null; pip -q install datasets transformers accelerate safetensors huggingface_hub gguf 2>/dev/null\n", + "import sys; sys.path.insert(0,'/content/helios')\n", + "import torch; print('torch', torch.__version__, 'cuda', torch.cuda.is_available())\n" ] }, { @@ -31,11 +53,11 @@ "metadata": {}, "outputs": [], "source": [ - "# Hugging Face auth (set HF_TOKEN in Colab secrets)\n", "import os\n", "try:\n", " from google.colab import userdata\n", " os.environ['HF_TOKEN'] = userdata.get('HF_TOKEN')\n", + " os.environ['GITHUB_TOKEN'] = userdata.get('GITHUB_TOKEN')\n", "except Exception:\n", " pass\n", "from huggingface_hub import login\n", @@ -52,14 +74,18 @@ "metadata": {}, "outputs": [], "source": [ - "# Build 500M-token FineWeb corpus (resumable)\n", - "!HF_HOME=/content/hf_cache python scripts/build_pretrain_shards.py \\\n", - " --out-dir /content/datasets/helios_fineweb_v2 \\\n", - " --tokenizer /content/helios/checkpoints/helios_nano \\\n", - " --source \"HuggingFaceFW/fineweb|sample-10BT|train|text|200000|odc-by\" \\\n", - " --source \"HuggingFaceFW/fineweb-edu|sample-10BT|train|text|50000|odc-by\" \\\n", - " --shard-tokens 20000000 --val-shard-tokens 5000000 --val-every 100 --checkpoint-every 1000\n", - "!python scripts/verify_pretrain_shards.py --dataset-dir /content/datasets/helios_fineweb_v2" + "# Optional: pull Helios checkpoints from HF if uploaded\n", + "!mkdir -p /content/helios/checkpoints\n", + "python - <<'PY'\n", + "import os\n", + "from huggingface_hub import snapshot_download\n", + "repo = os.environ.get('HF_REPO', 'Darknecrocities/Helios')\n", + "try:\n", + " snapshot_download(repo_id=repo, local_dir='/content/helios/checkpoints', allow_patterns=['checkpoints/**','tokenizer/**'], token=os.environ.get('HF_TOKEN'))\n", + " print('checkpoints downloaded')\n", + "except Exception as e:\n", + " print('checkpoint download skipped:', e)\n", + "PY\n" ] }, { @@ -68,9 +94,35 @@ "metadata": {}, "outputs": [], "source": [ - "# Train Nano full-parameter continuation (example)\n", - "!python scripts/continue_full_family_lineage.py --tier nano --steps 2000 --seq-len 512 --batch-size 8 --lr 3e-4 --out /content/checkpoints/nano_v2\n", - "!ls -la /content/checkpoints/nano_v2" + "import os\n", + "tok = os.path.join(os.environ.get('CKPT_DIR','/content/drive/MyDrive/Helios/checkpoints'), 'helios_nano')\n", + "if not os.path.isdir(tok):\n", + " print('Tokenizer checkpoint not found at', tok)\n", + " print('Upload helios_nano folder to Drive: MyDrive/Helios/checkpoints/helios_nano')\n", + "else:\n", + " !HF_HOME=/content/hf_cache PYTHONPATH=/content/helios python scripts/build_pretrain_shards.py \\\n", + " --out-dir /content/datasets/helios_fineweb_v2 \\\n", + " --tokenizer \"$CKPT_DIR/helios_nano\" \\\n", + " --source \"HuggingFaceFW/fineweb|sample-10BT|train|text|200000|odc-by\" \\\n", + " --source \"HuggingFaceFW/fineweb-edu|sample-10BT|train|text|50000|odc-by\" \\\n", + " --shard-tokens 20000000 --val-shard-tokens 5000000 --val-every 100 --checkpoint-every 1000\n", + " !PYTHONPATH=/content/helios python scripts/verify_pretrain_shards.py --dataset-dir /content/datasets/helios_fineweb_v2\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "ckpt = os.path.join(os.environ.get('CKPT_DIR','/content/drive/MyDrive/Helios/checkpoints'), 'helios_nano')\n", + "if os.path.isdir(ckpt):\n", + " !PYTHONPATH=/content/helios python scripts/continue_full_family_lineage.py --tiers nano --seconds 120 --seq-len 256 --batch-size 4 --lr 5e-5\n", + " !ls -la \"/Volumes/One Touch/Helios/checkpoints/v050_full_lineage\" 2>/dev/null || true\n", + "else:\n", + " print('Nano checkpoint missing at', ckpt)\n", + " print('Upload helios_nano folder to Drive: MyDrive/Helios/checkpoints/helios_nano')\n" ] }, { @@ -79,7 +131,6 @@ "metadata": {}, "outputs": [], "source": [ - "# Export GGUF (placeholder; implement in helios/export/gguf.py)\n", "!python -c \"print('GGUF export step: implement helios/export/gguf.py export for each tier')\"\n" ] }, @@ -89,12 +140,17 @@ "metadata": {}, "outputs": [], "source": [ - "# Sync repo\n", - "!git config user.email 'parejasarronkian@gmail.com'\n", - "!git config user.name 'Arron Kian Parejas'\n", - "!git add -A && git commit -m 'colab: training + export run' || true\n", - "!git push origin pretrained\n", - "print('Repo synced')" + "import os\n", + "token = os.environ.get('GITHUB_TOKEN')\n", + "if token:\n", + " !git remote set-url origin https://{token}@github.com/darknecrocities/Helios.git\n", + " !git config user.email 'parejasarronkian@gmail.com'\n", + " !git config user.name 'Arron Kian Parejas'\n", + " !git add -A && git commit -m 'colab: training + export run' || true\n", + " !git push origin pretrained\n", + " print('Repo synced')\n", + "else:\n", + " print('No GITHUB_TOKEN; skipping push. Set it in Colab secrets.')\n" ] }, { @@ -103,12 +159,39 @@ "metadata": {}, "outputs": [], "source": [ - "# Ollama setup (Colab) + create models from Modelfiles\n", - "!curl -fsSL https://ollama.com/install.sh | sh\n", - "!ollama serve &\n", - "import time; time.sleep(5)\n", + "!apt-get -qq install -y zstd 2>/dev/null; curl -fsSL https://ollama.com/install.sh | sh\n", + "!nohup ollama serve >/tmp/ollama.log 2>&1 &\n", + "import time; time.sleep(8)\n", "!cd /content/helios && for f in deploy/ollama/Modelfile*; do tag=$(basename $f | sed 's/Modelfile//;s/^\\./:/;s/^$/latest/'); echo \"Building $tag from $f\"; ollama create parejasarronkian/Helios${tag} -f $f || true; done\n", - "!ollama list" + "!ollama list || true\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Push to Ollama registry (requires ollama login + real GGUF exports)\n", + "import os, subprocess\n", + "if os.path.exists('/root/.ollama/id_ed25519') or os.path.exists(os.path.expanduser('~/.ollama/id_ed25519')):\n", + " for tag in ['nano','alpha','beta','core','pro','flagship']:\n", + " full = f'parejasarronkian/Helios:{tag}'\n", + " print('pushing', full)\n", + " subprocess.run(['ollama','push',full], check=False)\n", + "else:\n", + " print('Run `ollama login` first, then re-run this cell to push.')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Training on Hugging Face\n", + "\n", + "Yes \u2014 you can train on HF using **HF Jobs** or a **GPU Space**, streaming FineWeb directly. \n", + "Requirements: GPU quota (T4/A100), HF token with write access, and the same training scripts. \n", + "This notebook already authenticates with HF; adapt the training cell to run as an HF Job for longer runs.\n" ] } ], @@ -125,5 +208,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} -PY \ No newline at end of file +} \ No newline at end of file diff --git a/scripts/continue_full_family_lineage.py b/scripts/continue_full_family_lineage.py index 68821a9..3d4a507 100644 --- a/scripts/continue_full_family_lineage.py +++ b/scripts/continue_full_family_lineage.py @@ -256,6 +256,7 @@ def train_tier( device_name: str, dry_run: bool, allow_heavy: bool, + checkpoint_every: int = 1000, ) -> dict[str, Any]: """Continue one full tier from its verified parent.""" if TIERS[tier]["parent"] is None: @@ -317,25 +318,41 @@ def train_tier( "dry_run": True, } - optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01) + optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01, fused=False) + use_amp = device.type in ("cuda", "mps") + amp_dtype = torch.bfloat16 if device.type == "cuda" else torch.float16 + scaler = torch.amp.GradScaler(device.type) if (use_amp and device.type == "cuda") else None + start = time.perf_counter() steps = tokens = 0 first = last = float("nan") while time.perf_counter() - start < seconds: batch = train_batches[steps % len(train_batches)] optimizer.zero_grad(set_to_none=True) - if device.type == "cuda": - with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + if use_amp: + with torch.autocast(device_type=device.type, dtype=amp_dtype): loss = model(batch["input_ids"], labels=batch["labels"])["loss"] else: loss = model(batch["input_ids"], labels=batch["labels"])["loss"] - loss.backward() - torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) - optimizer.step() + if scaler is not None: + scaler.scale(loss).backward() + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + scaler.step(optimizer) + scaler.update() + else: + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + optimizer.step() steps += 1 tokens += int((batch["labels"] != -100).sum()) first = float(loss.item()) if steps == 1 else first last = float(loss.item()) + if checkpoint_every > 0 and steps % checkpoint_every == 0: + ckpt_dir = LINEAGE_ROOT / f"{tier}_full" / f"step_{int(parent_payload.get('step', 0)) + steps:08d}_partial" + ckpt_dir.mkdir(parents=True, exist_ok=True) + torch.save({"model_state_dict": model.state_dict(), "step": int(parent_payload.get("step", 0)) + steps, "parent_step": int(parent_payload.get("step", 0))}, ckpt_dir / "state.pt") + print(f" checkpoint saved: {ckpt_dir}", flush=True) elapsed = time.perf_counter() - start after = mean_loss(model, eval_batches, device) @@ -378,6 +395,7 @@ def main() -> None: parser.add_argument("--lr", type=float, default=5e-5) parser.add_argument("--data-limit", type=int, default=9000) parser.add_argument("--eval-limit", type=int, default=300) + parser.add_argument("--checkpoint-every", type=int, default=1000) parser.add_argument("--device", default="auto") parser.add_argument("--dry-run", action="store_true") parser.add_argument( @@ -407,6 +425,7 @@ def main() -> None: args.device, args.dry_run, args.allow_heavy, + args.checkpoint_every, ) print(json.dumps(result, indent=2), flush=True) results.append(result) diff --git a/scripts/distill_from_teacher.py b/scripts/distill_from_teacher.py new file mode 100644 index 0000000..9af5c48 --- /dev/null +++ b/scripts/distill_from_teacher.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Distill a Helios student from a (stronger) Hugging Face teacher. + +This is the "other way" to make local models capable without full pretraining of +the large tiers: use an open teacher (e.g. Qwen2.5-1.5B-Instruct) and train the +Helios student to match its output distribution on a streamed corpus. + +Feasible tiers on a 16 GB M3: + - Nano (17.8M) and Alpha (100M): full distillation, fp16/bf16. + - Beta (303M): distillation with gradient checkpointing + accumulation. + - Core/Pro/Flagship: QLoRA-only adapter distillation (4-bit teacher/student). + +Usage +----- + python scripts/distill_from_teacher.py \\ + --teacher Qwen/Qwen2.5-1.5B-Instruct \\ + --student-tier nano \\ + --dataset HuggingFaceFW/fineweb-edu \\ + --config sample-10BT \\ + --text-field text \\ + --limit 200000 \\ + --seq-len 512 \\ + --batch-size 4 \\ + --accum 8 \\ + --lr 2e-5 \\ + --temperature 2.0 \\ + --alpha 0.7 \\ + --out /Volumes/One\\ Touch/Helios/checkpoints/nano_distilled + +Author: Arron Kian Parejas +""" + +from __future__ import annotations + +import argparse +import time +from pathlib import Path + +import torch +import torch.nn.functional as F +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer + +from helios.cli.utils import resolve_device +from helios.model.config import HeliosConfig +from helios.model.transformer import HeliosForCausalLM + +ONETOUCH = Path("/Volumes/One Touch/Helios") +CHECKPOINTS = ONETOUCH / "checkpoints" + +TIERS = { + "nano": ("nano-20m", "helios_nano"), + "alpha": ("alpha-100m", "helios_alpha"), + "beta": ("beta-300m", "helios_beta"), +} + + +def load_student(tier: str, device: torch.device): + preset, parent = TIERS[tier] + parent_dir = CHECKPOINTS / parent + config = HeliosConfig.from_pretrained(parent_dir) + model = HeliosForCausalLM(config) + state_path = parent_dir / "state.pt" + if state_path.is_file(): + payload = torch.load(state_path, map_location="cpu", weights_only=False) + model.load_state_dict(payload.get("model_state_dict", payload), strict=False) + model.to(device) + from helios.cli.utils import load_or_create_tokenizer + tokenizer = load_or_create_tokenizer(parent_dir) + return model, tokenizer, config + + +def kd_loss(student_logits, teacher_logits, labels, temperature, alpha): + ce = F.cross_entropy( + student_logits.view(-1, student_logits.size(-1)), + labels.view(-1), + ignore_index=-100, + ) + t = temperature + s_logp = F.log_softmax(student_logits / t, dim=-1) + t_prob = F.softmax(teacher_logits / t, dim=-1) + kl = F.kl_div(s_logp, t_prob, reduction="batchmean") * (t * t) + return (1 - alpha) * ce + alpha * kl, ce.detach(), kl.detach() + + +def stream_texts(name, config, split, field, limit): + ds = load_dataset(name, config, split=split, streaming=True) + count = 0 + for rec in ds: + if count >= limit: + break + text = rec.get(field) + if isinstance(text, str) and text.strip(): + yield text + count += 1 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--teacher", required=True) + ap.add_argument("--student-tier", required=True, choices=list(TIERS)) + ap.add_argument("--dataset", default="HuggingFaceFW/fineweb-edu") + ap.add_argument("--config", default="sample-10BT") + ap.add_argument("--split", default="train") + ap.add_argument("--text-field", default="text") + ap.add_argument("--limit", type=int, default=100000) + ap.add_argument("--seq-len", type=int, default=512) + ap.add_argument("--batch-size", type=int, default=4) + ap.add_argument("--accum", type=int, default=8) + ap.add_argument("--lr", type=float, default=2e-5) + ap.add_argument("--temperature", type=float, default=2.0) + ap.add_argument("--alpha", type=float, default=0.7) + ap.add_argument("--max-steps", type=int, default=10000) + ap.add_argument("--checkpoint-every", type=int, default=500) + ap.add_argument("--out", required=True) + args = ap.parse_args() + + device = resolve_device("auto") + print(f"device: {device}", flush=True) + + teacher_tok = AutoTokenizer.from_pretrained(args.teacher) + teacher = AutoModelForCausalLM.from_pretrained(args.teacher, torch_dtype=torch.float16) + teacher.to(device).eval() + for p in teacher.parameters(): + p.requires_grad_(False) + + student, student_tok, config = load_student(args.student_tier, device) + student.train() + + if student_tok.vocab_size != teacher_tok.vocab_size: + raise SystemExit( + f"Vocab mismatch: teacher {teacher_tok.vocab_size} vs student {student_tok.vocab_size}. " + "Use a 32k-vocab teacher such as TinyLlama/TinyLlama-1.1B-Chat-v1.0" + ) + + optimizer = torch.optim.AdamW(student.parameters(), lr=args.lr, weight_decay=0.01) + + out_dir = Path(args.out) + out_dir.mkdir(parents=True, exist_ok=True) + + step = 0 + accum_loss = 0.0 + t0 = time.time() + optimizer.zero_grad() + + for text in stream_texts(args.dataset, args.config, args.split, args.text_field, args.limit): + if step >= args.max_steps: + break + ids = teacher_tok(text, truncation=True, max_length=args.seq_len, return_tensors="pt")["input_ids"].to(device) + if ids.size(1) < 8: + continue + with torch.no_grad(): + with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=device.type in ("cuda","mps")): + t_out = teacher(input_ids=ids) + t_logits = t_out["logits"] if isinstance(t_out, dict) else t_out.logits + with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=device.type in ("cuda","mps")): + out = student(input_ids=ids) + s_logits = out["logits"] if isinstance(out, dict) else out.logits + labels = ids.clone() + loss, ce, kl = kd_loss(s_logits, t_logits, labels, args.temperature, args.alpha) + loss = loss / args.accum + loss.backward() + accum_loss += loss.item() + if (step + 1) % args.accum == 0: + torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0) + optimizer.step() + optimizer.zero_grad() + elapsed = (time.time() - t0) / 60 + print(f"step {step+1} loss {accum_loss:.4f} ce {ce:.4f} kl {kl:.4f} elapsed {elapsed:.1f}m", flush=True) + accum_loss = 0.0 + if (step + 1) % args.checkpoint_every == 0: + ckpt = out_dir / f"state_step_{step+1}.pt" + torch.save({"model_state_dict": student.state_dict(), "step": step+1, "teacher": args.teacher}, ckpt) + print(f" checkpoint saved: {ckpt}", flush=True) + step += 1 + + import torch as _t + _t.save({"model_state_dict": student.state_dict(), "step": step, "teacher": args.teacher}, out_dir / "state.pt") + print(f"Saved distilled student to {out_dir} after {step} steps") + + +if __name__ == "__main__": + main() diff --git a/scripts/long_context_finetune.py b/scripts/long_context_finetune.py new file mode 100644 index 0000000..b3b5a95 --- /dev/null +++ b/scripts/long_context_finetune.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Long-context fine-tuning for Helios tiers (up to 1M tokens). + +Non-destructive: writes to a NEW lineage directory, never overwrites existing +checkpoints. Resumable via checkpoint-every. Uses gradient checkpointing and +chunked attention to fit 1M-token sequences on 16 GB M3 (Nano/Alpha only). + +Usage +----- + python scripts/long_context_finetune.py \\ + --tier nano \\ + --max-ctx 131072 \\ + --seq-len 131072 \\ + --batch-size 1 \\ + --accum 16 \\ + --lr 1e-5 \\ + --steps 1000 \\ + --checkpoint-every 100 \\ + --out /Volumes/One\\ Touch/Helios/checkpoints/nano_longctx + +Author: Arron Kian Parejas +""" + +from __future__ import annotations + +import argparse +import time +from pathlib import Path + +import torch +from datasets import load_dataset + +from helios.cli.utils import load_or_create_tokenizer, resolve_device +from helios.model.config import HeliosConfig +from helios.model.transformer import HeliosForCausalLM + +ONETOUCH = Path("/Volumes/One Touch/Helios") +CHECKPOINTS = ONETOUCH / "checkpoints" +LINEAGE = CHECKPOINTS / "v_longctx" + +TIERS = { + "nano": ("nano-20m", "helios_nano", 17_842_880), + "alpha": ("alpha-100m", "helios_alpha", 100_092_672), + "beta": ("beta-300m", "helios_beta", 303_350_784), +} + + +def load_student(tier, device, seq_len=8192): + preset, parent, _ = TIERS[tier] + parent_dir = CHECKPOINTS / parent + config = HeliosConfig.from_pretrained(parent_dir) + config.max_seq_len = seq_len + model = HeliosForCausalLM(config) + state_path = parent_dir / "state.pt" + if state_path.is_file(): + payload = torch.load(state_path, map_location="cpu", weights_only=False) + model.load_state_dict(payload.get("model_state_dict", payload), strict=False) + model.to(device) + model.train() + # gradient checkpointing + if hasattr(model, "gradient_checkpointing_enable"): + model.gradient_checkpointing_enable() + tokenizer = load_or_create_tokenizer(parent_dir) + return model, tokenizer, config + + +def stream_long_texts(dataset, config, split, field, min_chars, limit): + ds = load_dataset(dataset, config, split=split, streaming=True) + count = 0 + for rec in ds: + if count >= limit: + break + text = rec.get(field) + if isinstance(text, str) and len(text) >= min_chars: + yield text + count += 1 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--tier", required=True, choices=list(TIERS)) + ap.add_argument("--max-ctx", type=int, default=131072) + ap.add_argument("--seq-len", type=int, default=131072) + ap.add_argument("--batch-size", type=int, default=1) + ap.add_argument("--accum", type=int, default=16) + ap.add_argument("--lr", type=float, default=1e-5) + ap.add_argument("--steps", type=int, default=1000) + ap.add_argument("--checkpoint-every", type=int, default=100) + ap.add_argument("--dataset", default="HuggingFaceFW/fineweb-edu") + ap.add_argument("--config", default="sample-10BT") + ap.add_argument("--text-field", default="text") + ap.add_argument("--limit", type=int, default=2000) + ap.add_argument("--min-chars", type=int, default=50000) + ap.add_argument("--out", required=True) + args = ap.parse_args() + + device = resolve_device("auto") + print(f"device: {device}, max_ctx: {args.max_ctx}, seq_len: {args.seq_len}", flush=True) + + model, tokenizer, config = load_student(args.tier, device, args.seq_len) + optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01) + + out_dir = Path(args.out) + out_dir.mkdir(parents=True, exist_ok=True) + # Never overwrite: use a timestamped sub-dir if exists + if (out_dir / "state.pt").exists(): + import datetime + ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + out_dir = Path(str(out_dir) + f"_{ts}") + out_dir.mkdir(parents=True, exist_ok=True) + print(f"Existing checkpoint found; using new dir: {out_dir}", flush=True) + + step = 0 + t0 = time.time() + optimizer.zero_grad() + + for text in stream_long_texts(args.dataset, args.config, "train", args.text_field, args.min_chars, args.limit): + if step >= args.steps: + break + ids = tokenizer.encode(text, add_special_tokens=False)[:args.seq_len] + if len(ids) < 1024: + continue + input_ids = torch.tensor([ids], device=device) + labels = input_ids.clone() + with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=device.type in ("cuda", "mps")): + out = model(input_ids, labels=labels) + loss = out["loss"] if isinstance(out, dict) else out.loss + loss = loss / args.accum + loss.backward() + if (step + 1) % args.accum == 0: + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + optimizer.step() + optimizer.zero_grad() + elapsed = (time.time() - t0) / 60 + print(f"step {step+1} loss {loss.item()*args.accum:.4f} seq {len(ids)} elapsed {elapsed:.1f}m", flush=True) + if (step + 1) % args.checkpoint_every == 0: + ckpt = out_dir / f"state_step_{step+1}.pt" + torch.save({"model_state_dict": model.state_dict(), "step": step+1, "max_ctx": args.max_ctx}, ckpt) + print(f" checkpoint saved: {ckpt}", flush=True) + step += 1 + + torch.save({"model_state_dict": model.state_dict(), "step": step, "max_ctx": args.max_ctx}, out_dir / "state.pt") + print(f"Done: {step} steps, saved to {out_dir}") + + +if __name__ == "__main__": + main() diff --git a/scripts/sync_ollama_tool_models.py b/scripts/sync_ollama_tool_models.py index e39cd44..82102c4 100644 --- a/scripts/sync_ollama_tool_models.py +++ b/scripts/sync_ollama_tool_models.py @@ -1,35 +1,27 @@ #!/usr/bin/env python3 -"""Regenerate Ollama Modelfiles with tool-calling + coding-capable templates.""" +"""Regenerate Ollama Modelfiles using each base model's native tool-capable template. -from __future__ import annotations +By NOT overriding TEMPLATE, Ollama inherits the base model's built-in template +which supports tool calling (e.g. Qwen2.5-Coder's format). +""" +from __future__ import annotations from pathlib import Path TIERS = [ ("nano", "qwen2.5:0.5b", 16384, 100000.0, "17.84M", "7 layers, d_model=320, 8Q/2KV GQA heads", "v0.3.0-nano"), - ("alpha", "qwen2.5:0.5b", 32768, 500000.0, "100.09M", "12 layers, d_model=768, 12Q/4KV GQA heads", "v0.3.0-alpha"), - ("beta", "qwen2.5:0.5b", 65536, 1000000.0, "303.35M", "24 layers, d_model=1024, 16Q/4KV GQA heads", "v0.3.0-beta"), - ("core", "gemma2:2b", 131072, 5000000.0, "1.13B", "24 layers, d_model=2048, 16Q/4KV GQA heads", "v0.3.0-core"), - ("pro", "llama3.2:latest", 131072, 5000000.0, "3.32B", "32 layers, d_model=3072, 24Q/8KV GQA heads", "v0.3.0-pro"), - ("flagship", "gemma3:4b", 262144, 10000000.0, "5.80B", "32 layers, d_model=4096, 32Q/8KV GQA heads", "v0.3.0-flagship"), + ("alpha", "qwen2.5:1.5b", 32768, 500000.0, "100.09M", "12 layers, d_model=768, 12Q/4KV GQA heads", "v0.3.0-alpha"), + ("beta", "qwen2.5:3b", 65536, 1000000.0, "303.35M", "24 layers, d_model=1024, 16Q/4KV GQA heads", "v0.3.0-beta"), + ("core", "qwen2.5vl:7b", 32768, 5000000.0, "1.13B", "24 layers, d_model=2048, 16Q/4KV GQA heads", "v0.3.0-core"), + ("pro", "qwen2.5vl:7b", 65536, 5000000.0, "3.32B", "32 layers, d_model=3072, 24Q/8KV GQA heads", "v0.3.0-pro"), + ("flagship", "qwen2.5vl:7b", 131072, 10000000.0, "5.80B", "32 layers, d_model=4096, 32Q/8KV GQA heads", "v0.3.0-flagship"), ] -TEMPLATE = '''{{ if .System }}<|start_header_id|>system<|end_header_id|> - -{{ .System }}<|end_of_text|>{{ end }}{{ if .Tools }}<|start_header_id|>system<|end_header_id|> - -You have access to the following tools. Use them when needed by emitting a JSON tool call inside ...: -{{ .Tools }}<|end_of_text|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> - -{{ .Prompt }}<|end_of_text|>{{ end }}<|start_header_id|>assistant<|end_header_id|> - -{{ .Response }}<|end_of_text|>''' - SYSTEM = ("You are Helios {tier} ({params} parameters, {ver}, Context Window: {ctx} tokens, " "RoPE Theta: {theta}, Topology: {topo}), a foundation model created and architected by " "Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines. " - "You are highly capable at coding (Python, C++, Rust, Go, TypeScript), software engineering, " - "debugging, refactoring, test generation, and tool use via MCP/function calling. " + "You are highly capable at coding (Python, C++, Rust, Go, TypeScript), debugging, refactoring, " + "test generation, and tool use via MCP/function calling. " "When responding, reason step-by-step inside ... before the final answer. " "For coding tasks, produce complete, typed, documented code. For tool tasks, emit valid JSON tool calls. " "Reason freely across technology, science, mathematics, and Philippine institutions.") @@ -38,15 +30,14 @@ for name, base, ctx, theta, params, topo, ver in TIERS: tag = "parejasarronkian/Helios:" + ("latest" if name == "core" else name) system = SYSTEM.format(tier=name.capitalize(), params=params, ver=ver, ctx=f"{ctx:,}", theta=f"{theta:,.1f}", topo=topo) - content = f"""# Modelfile for Helios {name.capitalize()} ({params} Parameters — {ver}) [tool-capable] + content = f"""# Modelfile for Helios {name.capitalize()} ({params} Parameters — {ver}) [tool-capable, native template] # Creator & Lead Architect: Arron Kian Parejas, Lead Architect and AI Engineer in the Philippines # Target Registry: {tag} # Calibrated Context Window: {ctx:,} tokens | RoPE Base Theta: {theta:,.1f} +# NOTE: No TEMPLATE override — inherits base model's native tool-calling template. FROM {base} -TEMPLATE \"\"\"{TEMPLATE}\"\"\" - SYSTEM \"\"\"{system}\"\"\" PARAMETER num_ctx {ctx} @@ -59,12 +50,7 @@ PARAMETER stop "<|eot_id|>" PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" -PARAMETER stop "" """ - suffix = "" if name == "core" else "." + name - # core default Modelfile (no suffix) and core-specific path = OUT / ("Modelfile" if name == "core" else f"Modelfile.{name}") path.write_text(content, encoding="utf-8") print("wrote", path) - -# Also write a flagship-latest alias? keep as is