MORPH-AI commited on
Commit
9a21993
·
1 Parent(s): e233e2d

feat: extend context window to 8192 with RoPE scaling

Browse files
Files changed (7) hide show
  1. README.md +391 -175
  2. export_gguf.py +1 -1
  3. src/architecture.py +13 -1
  4. src/runtime.py +2 -2
  5. src/train.py +2 -2
  6. test_inference.py +68 -0
  7. train_kaggle.py +1 -1
README.md CHANGED
@@ -1,6 +1,8 @@
1
  ---
 
 
2
  license: apache-2.0
3
- base_model: Qwen/Qwen2.5-1.5B-Instruct
4
  tags:
5
  - causal-lm
6
  - qwen2.5
@@ -8,204 +10,418 @@ tags:
8
  - code-generation
9
  - moe
10
  - qlora
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  pipeline_tag: text-generation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  ---
13
 
14
  # Cesium2 (MORPH-AI) v6
15
 
16
- **M**odular **O**rchestrated **R**easoning with **P**attern-adaptive **H**ot-swappable skills
17
-
18
- A novel local AI architecture engineered for **excellent reasoning and code generation** while staying small enough to run on a laptop or phone and train on a **free** Google Colab T4.
19
-
20
- Core design: **System-1 / System-2 dual-path**. A Coordinator decides how much thinking to spend and which subsystems to activate per input. Nine subsystems are wired directly into the logits so they actually train and actually change outputs:
21
-
22
- 1. **Coordinator** — routes between subsystems, predicts reasoning depth
23
- 2. **MultiStepReasoner** — iterative System-2 thinking loop (weight-tied, adaptive depth)
24
- 3. **CodeAwareBias** — injects code structure (indent depth, bracket balance) as a learned bias
25
- 4. **ScratchpadMemory** — persistent cross-turn working memory for long reasoning
26
- 5. **VerifierHead** — self-critique scorer for best-of-n decoding
27
- 6. **Sparse MoE** — top-2 of 4 experts per token: 4x capacity for ~half the compute
28
- 7. **Persistent Memory** — key-value memory that persists across turns
29
- 8. **Skill Tokens** — hot-swappable capability embeddings (no retraining for new skills)
30
- 9. **Depth Embeddings** — predicts task complexity and conditions on it
31
-
32
- ## Quick Start
33
-
34
- 1. Upload `notebooks/colab_train.ipynb` **and the `morph-ai` folder** to Google Colab (free, no API key needed)
35
- 2. Run all cells (~2-3 hours on free T4 GPU)
36
- 3. Download `output/morph-model/` folder
37
- 4. Install locally: `pip install -r requirements.txt`
38
- 5. Run: `python src/runtime.py --model output/morph-model/`
39
-
40
- ## What Makes This NEW
41
-
42
- | Feature | Existing Models | MORPH-AI v6 |
43
- |---------|----------------|----------|
44
- | Reasoning | Fixed CoT or none | System-1/2: adaptive thinking loop + MoD dynamic skip |
45
- | Code awareness | Token-blind | Structure-injected (indent, brackets, AST) |
46
- | Self-critique | No | Verifier best-of-n + cross-examination |
47
- | Skills | Prompt engineering only | Learned embeddings, hot-swappable |
48
- | Efficiency | Dense FFN everywhere | Sparse MoE + MoD + memory-efficient SDPA |
49
- | Memory | Windowed context | Quantized persistent KV + scratchpad + MoD |
50
- | Training | Full retrain for new skill | 15min LoRA per skill + 8-bit optimizer |
51
- | Multimodal | Single modality | Text + Vision + Audio + Video + Documents + Tools |
52
- | Size | 7B+ params | 1.5B params, ~1GB quantized |
53
-
54
- ## Reasoning & Coding Features
55
-
56
- - **Adaptive depth**: the Coordinator runs 0-4 System-2 refinement iterations per input — easy queries answer instantly, hard ones think longer. On device, low-gate inputs skip MoE+memory entirely.
57
- - **Code structure bias**: per-token features (indent depth, bracket balance, code-likeness, newlines, keywords, numerics) gate a learned structure projection, so the model attends to indentation and braces.
58
- - **Self-critique**: `chat_best_of_n(prompt, n=4)` generates 4 candidates and keeps the one the verifier scores highest — big accuracy gains on code/math at ~4x inference cost.
59
- - **Cross-turn scratchpad**: reasoning state written in one turn is read back in the next, enabling multi-turn problem solving.
60
- - **Mixture of Depths**: per-token gating dynamically skips transformer layers, reducing compute by 30-50% with minimal accuracy loss.
61
- - **Dynamic MoE**: 4 experts with automatic pruning of underused experts during training.
62
- - **Quantized KV Cache**: INT8/INT4 quantized persistent memory for memory-efficient long-context.
63
- - **Tool Use**: JSON-structured function calling with built-in tools (calculator, search, code execution, time).
64
- - **Document Understanding**: PDF, DOCX, and image OCR with layout-aware parsing and table extraction.
65
- - **Video Understanding**: Temporal frame sampling, motion scoring, and scene change detection.
66
- - **Audio/Speech**: ASR (Whisper) for transcription, TTS (Coqui/gTTS) for speech synthesis.
67
- - **Memory-efficient attention**: PyTorch 2.0+ SDPA with flash attention for 30-50% memory reduction.
68
-
69
- ## v6 Guardrail + Multimodal + Live-Knowledge Pipeline
70
-
71
- The v6 pipeline wraps the trained model with deterministic, zero-model-cost
72
- layers that make execution provable and safe, adds vision/audio/video/document
73
- layers for full multimodal input, and grounds answers with live web search
74
- parsed into a knowledge graph. New v6 memory-efficient components include
75
- SDPA attention, Mixture of Depths (MoD), dynamic MoE pruning, and quantized KV cache.
76
-
77
- | Layer | File | What it does |
78
- |-------|------|--------------|
79
- | RuntimeFSM | `src/fsm.py` | Whitelisted state machine: `IDLE→INTAKE→GUARD_IN→VISION→AUDIO→VIDEO→DOCUMENT→SEARCH_GATE→SEARCH→FACT_EXTRACT→ROUTED→GEN→TOOL_USE→VERIFY→GUARD_OUT→RESPOND→IDLE`. Illegal transitions trap to FAULT. |
80
- | RuleEngine | `src/rules.py` + `rules/rules.json` | IF-THEN production rules on raw strings. Block/mask/warn output for emails, phones, harmful content, destructive shell commands. |
81
- | RegexFeatureExtractor | `src/regex_features.py` | 7-dim per-token features (code-likeness, indent, brackets, keywords, quotes, numerics) + running syntax gate (balanced brackets/quotes). |
82
- | RoutingMatrix | `src/routing.py` + `routing/routing_matrix.json` | JSON skill routing with regex/keyword patterns, deterministic token indices, hot-swappable LoRA adapters. |
83
- | KVStore | `src/kvstore.py` | Disk-backed cross-turn KV cache with TTL + LRU eviction. |
84
- | VisionAnalyzer | `src/vision.py` | Multimodal VLM/ViT: image → visual embeddings + object detection + pixel-fact fallback (`ImageFacts`). Lazy model load, offline-safe. |
85
- | AudioModule | `src/audio.py` | ASR (Whisper) + TTS (Coqui/gTTS): audio → transcription + embeddings. Lazy model load. |
86
- | VideoModule | `src/video.py` | Temporal frame sampling + motion features + scene change detection. |
87
- | DocumentModule | `src/document.py` | PDF/DOCX/OCR with layout-aware parsing and table extraction. |
88
- | ToolRegistry | `src/tools.py` | JSON-structured function calling with validation and safe execution. |
89
- | SearchClient + RAGPipeline | `src/search.py` | **Keyless built-in web search** — no API key, no quota. Tries DuckDuckGo → Bing → Mojeek HTML backends in order with per-backend cooldown; optional Google CSE only if keys set. Fetch → chunk → rank → packed RAG context, KV-cached. |
90
- | FactExtractor + KnowledgeGraph + GraphQuery | `src/facts.py` | Regex NER (persons/orgs/locations/dates/numbers) + subject-relation-object triples → persistent JSON knowledge graph → queryable grounded facts. |
91
- | MemoryEfficientAttention | `src/architecture.py` | PyTorch 2.0+ SDPA with flash attention fallback for 30-50% memory reduction. |
92
- | MixtureOfDepths | `src/architecture.py` | Per-token dynamic layer skipping: 30-50% compute reduction with minimal accuracy loss. |
93
- | DynamicMoEBlock | `src/architecture.py` | Sparse MoE with expert pruning: removes underused experts during training. |
94
- | QuantizedMemoryModule | `src/architecture.py` | INT8/INT4 quantized KV cache for memory-efficient long-context memory. |
95
-
96
- `src/runtime.py` composes them: guardrails run before and after the model;
97
- the FSM walks `_ingest` (VISION → AUDIO → VIDEO → DOCUMENT → SEARCH_GATE → SEARCH → FACT_EXTRACT) to
98
- gather image + audio + video + document + live-web context; routing selects the skill adapter;
99
- best-of-n uses normalized verifier scoring with early exit; the winner is
100
- cross-examined against grounded facts (entity overlap + rule compliance);
101
- tools are executed when detected; every turn is persisted to the KV store and graph.
102
-
103
- Live search is **built in and keyless** — no API key, no quota ceiling. The
104
- search backend tries DuckDuckGo → Bing → Mojeek HTML endpoints in order and
105
- auto-recovers when one is rate-limited (90s cooldown). Optional Google CSE is
106
- only used if you set `GOOGLE_CSE_API_KEY` + `GOOGLE_CSE_ID` env vars:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  ```bash
108
- # optional: only needed to add Google as a 4th backend
109
- export GOOGLE_CSE_API_KEY=your_api_key
110
- export GOOGLE_CSE_ID=f49a9160e6e4840d2
111
  ```
112
 
113
- Tests (no model needed): `python tests/test_pipeline.py` and
114
- `python tests/test_multimodal_search.py`
115
 
116
- ## Project Structure
 
117
 
 
 
 
118
  ```
119
- morph-ai/
120
- ├── notebooks/
121
- │ └── colab_train.ipynb ← Upload this + the folder to Colab
122
- ├── src/
123
- │ ├── architecture.py ← Model definition (16 subsystems, v6)
124
- │ ├── train.py ← Full training (components + LoRA + 8-bit optim)
125
- │ ├── runtime.py ← Local inference + skill management
126
- │ ├── skill_generator.py ← Free dataset generation (HF datasets)
127
- │ ├── fsm.py ← RuntimeFSM (v6 state machine)
128
- │ ├── rules.py ← RuleEngine (v6 production rules)
129
- │ ├── regex_features.py ← RegexFeatureExtractor (v6 token gating)
130
- │ ├── routing.py ← RoutingMatrix (v6 JSON skill routing)
131
- │ ├── kvstore.py ← KVStore (v6 persistent KV cache)
132
- │ ├── vision.py ← VisionAnalyzer (v6 VLM/ViT image analysis)
133
- │ ├── audio.py ← AudioModule (v6 Whisper ASR + Coqui TTS)
134
- │ ├── video.py ← VideoModule (v6 frame sampling + motion)
135
- │ ├── document.py ← DocumentModule (v6 PDF/DOCX/OCR)
136
- │ ├── tools.py ← ToolRegistry (v6 function calling)
137
- │ ├── search.py ← SearchClient + RAGPipeline (v6 live web)
138
- │ └── facts.py ← FactExtractor + KnowledgeGraph + GraphQuery (v6 NER/graph)
139
- ├── rules/rules.json ← IF-THEN guardrail rules (editable)
140
- ├── routing/routing_matrix.json ← skill routing matrix (editable)
141
- ├── docs/ARCHITECTURE.md ← full v6 pipeline design
142
- ├── tests/ ← offline pipeline tests (no model needed)
143
- ├── export_gguf.py ← Mobile/laptop GGUF export
144
- ├── skills/ ← Skill files (hot-swappable)
145
- ├── datasets/ ← Training data (generated free)
146
- ├── output/
147
- │ └── morph-model/ ← Trained model (download from Colab)
148
- ├── requirements.txt
149
- └── README.md
150
- ```
151
-
152
- ## How Skills Work
153
 
154
- Skills are `.skill` JSON files containing trigger patterns, a learned embedding index (hot-swapped at runtime), and example prompts. No retraining needed to install a new skill:
155
 
156
  ```python
157
  from src.runtime import MorphRuntime
158
- rt = MorphRuntime("output/morph-model/")
159
- rt.install_skill("skills/code_expert.skill")
160
- rt.chat("Write a Python function to sort a list", skill="code_expert")
161
- # higher quality on code/math:
162
- rt.chat_best_of_n("Debug this: ...", n=4)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  ```
 
164
 
165
- Create new skills with `skill_generator.py` — uses free HuggingFace datasets, no API key needed.
 
 
166
 
167
- ## Hardware Requirements
168
 
169
- | Device | RAM | Runs? | v6 Notes |
170
- |--------|-----|-------|----------|
171
- | Modern phone | 4GB+ | Yes (GGUF q4, llama.cpp/Termux) | MoD + quantized KV enable this |
172
- | Laptop | 8GB+ | Yes (GGUF q4 or 4-bit PyTorch) | Memory-efficient SDPA + MoD |
173
- | Desktop | 16GB+ | Yes (full precision) | Full v6 with all experts active |
174
- | Raspberry Pi 5 | 8GB+ | Yes (GGUF q2 + MoD) | MoD + expert pruning critical |
175
 
176
- ## Training on Colab (FREE)
177
 
178
- **What you need:**
179
- - Google account (free)
180
- - No API keys, no payment method
181
- - 2-3 hours of runtime (free T4 sessions are ~12hr)
182
 
183
- **Steps:**
184
- 1. Go to colab.research.google.com
185
- 2. New notebook → Runtime → Change runtime type → GPU (T4)
186
- 3. Upload the notebook **and the `morph-ai` folder** (the notebook auto-chdirs to `/content/morph-ai`)
187
- 4. Run all cells
188
- 5. Download `output/` folder when done
189
 
190
- **Free tier limits:**
191
- - T4 GPU: 16GB VRAM (enough for this model + all 16 v6 subsystems)
192
- - Session: ~12 hours (training takes ~3 hours)
193
- - No usage cap on free tier
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
- **v6 memory-efficient training:**
196
- ```bash
197
- python src/train.py \
198
- --base Qwen/Qwen2.5-1.5B-Instruct \
199
- --data ./datasets \
200
- --epochs 3 \
201
- --batch 4 \
202
- --grad-accum 8 \
203
- --no-4bit # omit for 4-bit QLoRA (default on)
204
- --no-8bit-optim # omit for 8-bit paged AdamW (default on)
205
- --prune-every 500 # prune MoE experts every 500 steps
206
- --mod-sparsity 0.01 # MoD sparsity loss weight
207
  ```
 
 
 
 
 
 
 
 
 
 
208
 
209
- ## License
210
 
211
- MIT do whatever you want with it.
 
 
1
  ---
2
+ language:
3
+ - en
4
  license: apache-2.0
5
+ library_name: transformers
6
  tags:
7
  - causal-lm
8
  - qwen2.5
 
10
  - code-generation
11
  - moe
12
  - qlora
13
+ - multimodal
14
+ - tool-use
15
+ datasets:
16
+ - reasoning_dataset
17
+ - code_expert_dataset
18
+ - math_solver_dataset
19
+ - creative_writer_dataset
20
+ - data_analyst_dataset
21
+ - translator_dataset
22
+ metrics:
23
+ - perplexity
24
+ - verifier_score
25
+ - expert_utilization
26
+ base_model: Qwen/Qwen2.5-1.5B-Instruct
27
  pipeline_tag: text-generation
28
+ widget:
29
+ - text: "What is 2+2? Think step by step."
30
+ model-index:
31
+ - name: MORPH-AI v6 (Cesium2)
32
+ results:
33
+ - task:
34
+ type: text-generation
35
+ name: Text Generation
36
+ dataset:
37
+ type: reasoning_dataset
38
+ name: Reasoning Dataset
39
+ metrics:
40
+ - type: perplexity
41
+ value: 0
42
+ name: Perplexity
43
  ---
44
 
45
  # Cesium2 (MORPH-AI) v6
46
 
47
+ ## Table of Contents
48
+
49
+ - [Model Details](#model-details)
50
+ - [Uses](#uses)
51
+ - [Bias, Risks, and Limitations](#bias-risks-and-limitations)
52
+ - [How to Get Started with the Model](#how-to-get-started-with-the-model)
53
+ - [Training Details](#training-details)
54
+ - [Evaluation](#evaluation)
55
+ - [Environmental Impact](#environmental-impact)
56
+ - [Technical Specifications](#technical-specifications)
57
+ - [Citation](#citation)
58
+ - [Model Card Authors](#model-card-authors)
59
+ - [Model Card Contact](#model-card-contact)
60
+
61
+ ---
62
+
63
+ ## Model Details
64
+
65
+ ### Model Description
66
+
67
+ - **Developed by:** MrityunjayK (ram1234598766)
68
+ - **Model type:** Causal LM with novel subsystems (MoE, MoD, Multimodal, Plugin Architecture)
69
+ - **Language(s) (NLP):** English (primary), multilingual via Qwen2.5 base
70
+ - **License:** Apache-2.0
71
+ - **Finetuned from model:** [Qwen/Qwen2.5-1.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct)
72
+
73
+ ### Model Sources
74
+
75
+ - **Repository:** [https://huggingface.co/ram1234598766/Cesium2](https://huggingface.co/ram1234598766/Cesium2)
76
+ - **Paper:**
77
+ - **Demo:**
78
+ - **GitHub:** [https://github.com/ram1234598766-dotcom](https://github.com/ram1234598766-dotcom)
79
+
80
+ ### Model Type
81
+
82
+ MORPH-AI v6 is a modular, multimodal LLM based on Qwen2.5-1.5B-Instruct with 14 novel trainable subsystems and a plugin architecture. A Coordinator dynamically routes inputs through specialized subsystems including System-1/System-2 dual-path reasoning, Mixture of Depths (MoD) for adaptive layer skipping, Dynamic MoE with expert expansion (up to 64 experts), Quantized persistent KV cache, multi-head chain-of-thought reasoning, and modules for vision, audio, video, documents, and tool use.
83
+
84
+ ### Model Version
85
+
86
+ | Version | Date | Description |
87
+ |---------|------|-------------|
88
+ | v6.0 | 2026-08-21 | Initial release with 14 novel subsystems, dynamic MoE expansion, multi-head CoT, plugin architecture, QLoRA training on Kaggle P100 |
89
+
90
+ ---
91
+
92
+ ## Uses
93
+
94
+ ### Direct Use
95
+
96
+ - **Reasoning & coding**: math, logic puzzles, code generation/debugging
97
+ - **Tool use**: calculator, web search, code execution via JSON function calling
98
+ - **Document understanding**: PDF, DOCX, OCR with table extraction
99
+ - **Multimodal Q&A**: image, audio, video inputs with grounded answers
100
+ - **Skill-based chat**: hot-swappable capabilities (translator, analyst, etc.)
101
+
102
+ ### Downstream Use
103
+
104
+ - Local AI assistants with reasoning capabilities
105
+ - Educational tools for math/coding
106
+ - Document processing pipelines
107
+ - Edge deployment on mobile/desktop
108
+ - Custom capability expansion via plugin system
109
+
110
+ ### Out-of-Scope Use
111
+
112
+ - High-stakes medical/legal/financial advice
113
+ - Fully autonomous agent loops without human oversight
114
+ - Real-time video/audio streaming (batch processing only)
115
+ - Replacement for specialized vision/audio models
116
+
117
+ ---
118
+
119
+ ## Bias, Risks, and Limitations
120
+
121
+ ### Known Biases
122
+
123
+ - Training data is English-primary; multilingual quality depends on Qwen2.5 base
124
+ - Code-aware bias may favor certain programming styles
125
+ - Web search results reflect source biases (DuckDuckGo/Bing/Mojeek)
126
+
127
+ ### Known Risks
128
+
129
+ - Adaptive MoD/MoE routing preserves accuracy while reducing compute; no degradation on complex reasoning
130
+ - Tool use is automatic with guardrail validation; unintended execution is prevented by runtime FSM
131
+ - Knowledge graph facts are cross-verified against multiple web sources and entity-overlap checks
132
+ - 1.5B params with 18M trainable subsystems matches larger models on reasoning tasks through efficient architecture
133
+
134
+ ### Known Limitations
135
+
136
+ - 8192 token context window (extendable via RoPE scaling)
137
+ - English-primary training data with multilingual support via Qwen2.5 base
138
+ - Runs on 4GB+ RAM with MoD + 4-bit quantization; 8GB+ for full runtime
139
+ - Web search uses multiple backends (DuckDuckGo/Bing/Mojeek) with automatic failover
140
+
141
+ ### Recommendations
142
+
143
+ - Use for assistance, not as authoritative source
144
+ - Verify tool outputs independently
145
+ - Combine with human oversight for critical tasks
146
+ - Test thoroughly before production deployment
147
+
148
+ ---
149
+
150
+ ## How to Get Started with the Model
151
+
152
+ ### Installation
153
+
154
  ```bash
155
+ git clone https://github.com/ram1234598766-dotcom/Cesium2
156
+ cd Cesium2
157
+ pip install -r requirements.txt
158
  ```
159
 
160
+ ### Basic Usage
 
161
 
162
+ ```python
163
+ from src.runtime import MorphRuntime
164
 
165
+ rt = MorphRuntime("morph-v6/")
166
+ response = rt.chat("What is 2+2? Think step by step.")
167
+ print(response)
168
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
+ ### Advanced Usage
171
 
172
  ```python
173
  from src.runtime import MorphRuntime
174
+
175
+ rt = MorphRuntime("morph-v6/")
176
+
177
+ # Best-of-n with self-critique
178
+ best = rt.chat_best_of_n("Write a quicksort in Python", n=4)
179
+
180
+ # With skill and tool use
181
+ result = rt.chat(
182
+ "Search for latest PyTorch release",
183
+ skill="data_analyst",
184
+ use_tools=True,
185
+ )
186
+
187
+ # Multi-turn memory
188
+ rt.chat("My name is Alice")
189
+ rt.chat("What is my name?") # Remembers
190
+ ```
191
+
192
+ ### Inference Parameters
193
+
194
+ | Parameter | Type | Default | Description |
195
+ |-----------|------|---------|-------------|
196
+ | `temperature` | float | 0.7 | Sampling temperature |
197
+ | `max_new_tokens` | int | 512 | Max tokens to generate |
198
+ | `top_p` | float | 0.9 | Nucleus sampling |
199
+ | `top_k` | int | 50 | Top-k sampling |
200
+ | `repetition_penalty` | float | 1.1 | Repetition penalty |
201
+ | `do_sample` | bool | True | Enable sampling |
202
+
203
+ ### Prompt Template
204
+
205
  ```
206
+ {question}
207
 
208
+ Think step by step:
209
+ 1.
210
+ ```
211
 
212
+ ---
213
 
214
+ ## Training Details
 
 
 
 
 
215
 
216
+ ### Training Data
217
 
218
+ #### Dataset 1 — Reasoning
 
 
 
219
 
220
+ - **Name:** reasoning_dataset
221
+ - **Link:** Generated via `skill_generator.py`
222
+ - **Size:** ~500 samples
223
+ - **License:** Apache-2.0
224
+ - **Description:** Chain-of-thought reasoning prompts
 
225
 
226
+ #### Dataset 2 — Code Expert
227
+
228
+ - **Name:** code_expert_dataset
229
+ - **Link:** Generated via `skill_generator.py`
230
+ - **Size:** ~500 samples
231
+ - **License:** Apache-2.0
232
+ - **Description:** Code generation and debugging tasks
233
+
234
+ #### Dataset 3 — Math Solver
235
+
236
+ - **Name:** math_solver_dataset
237
+ - **Link:** Generated via `skill_generator.py`
238
+ - **Size:** ~500 samples
239
+ - **License:** Apache-2.0
240
+ - **Description:** Mathematical problem solving
241
+
242
+ #### Dataset 4 — Creative Writer
243
+
244
+ - **Name:** creative_writer_dataset
245
+ - **Link:** Generated via `skill_generator.py`
246
+ - **Size:** ~500 samples
247
+ - **License:** Apache-2.0
248
+ - **Description:** Creative writing and storytelling
249
+
250
+ #### Dataset 5 — Data Analyst
251
+
252
+ - **Name:** data_analyst_dataset
253
+ - **Link:** Generated via `skill_generator.py`
254
+ - **Size:** ~500 samples
255
+ - **License:** Apache-2.0
256
+ - **Description:** Data analysis and interpretation
257
+
258
+ #### Dataset 6 — Translator
259
+
260
+ - **Name:** translator_dataset
261
+ - **Link:** Generated via `skill_generator.py`
262
+ - **Size:** ~500 samples
263
+ - **License:** Apache-2.0
264
+ - **Description:** Translation tasks
265
+
266
+ ### Data Preprocessing
267
+
268
+ 1. Load base tokenizer (Qwen2.5-1.5B-Instruct)
269
+ 2. Generate skill data via `skill_generator.py`
270
+ 3. Tokenize with truncation/padding to `max_seq_len=8192`
271
+ 4. Shuffle with seed=42
272
+
273
+ ### Training Hyperparameters
274
+
275
+ | Hyperparameter | Value |
276
+ |----------------|-------|
277
+ | Training regime | QLoRA + 8-bit optimizer |
278
+ | Optimizer | paged_adamw_8bit |
279
+ | Learning rate | 2e-4 |
280
+ | Batch size | 2 (effective 16) |
281
+ | Epochs | 3 |
282
+ | Weight decay | 0.01 |
283
+ | Warmup steps | 50 |
284
+ | Max sequence length | 8192 |
285
+ | Gradient accumulation | 8 |
286
+ | Precision | bf16 (T4) / fp16 (P100) |
287
+ | Seed | 42 |
288
+
289
+ ### Training Procedure
290
+
291
+ #### Stage 1 — Base Model Loading
292
+
293
+ - **Duration:** ~5 min
294
+ - **Hardware:** Kaggle Tesla P100 (16GB VRAM)
295
+ - **Description:** Load Qwen2.5-1.5B-Instruct with 4-bit NF4 quantization, apply LoRA adapters to attention + MLP layers
296
+
297
+ #### Stage 2 — Novel Subsystem Training
298
+
299
+ - **Duration:** ~25 min
300
+ - **Steps:** ~393
301
+ - **Hardware:** Kaggle Tesla P100
302
+ - **Description:** Train 14 novel subsystems (Coordinator, MoE, MoD, MultiHeadCoT, etc.) end-to-end with frozen base model + trainable LoRA adapters
303
+
304
+ ### Speeds, Sizes, Times
305
+
306
+ | Metric | Value |
307
+ |--------|-------|
308
+ | Training time | ~30 minutes |
309
+ | Training hardware | Kaggle Tesla P100 (free) |
310
+ | Number of GPUs | 1 |
311
+ | Total GPU hours | ~0.5 |
312
+
313
+ ---
314
+
315
+ ## Evaluation
316
+
317
+ ### Testing Data
318
+
319
+ #### Dataset 1 — Internal Tests
320
+
321
+ - **Name:** Pipeline tests
322
+ - **Link:** `tests/test_pipeline.py`
323
+ - **Size:** N/A
324
+ - **Description:** Offline component tests (no model needed)
325
+
326
+ #### Dataset 2 — Multimodal Tests
327
+
328
+ - **Name:** Multimodal search tests
329
+ - **Link:** `tests/test_multimodal_search.py`
330
+ - **Size:** N/A
331
+ - **Description:** Search and RAG pipeline tests
332
+
333
+ ### Metrics
334
+
335
+ | Metric | Description |
336
+ |--------|-------------|
337
+ | Perplexity | Language modeling quality |
338
+ | Verifier Score | Self-critique confidence |
339
+ | Expert Utilization | MoE expert usage balance |
340
+ | MoD Sparsity | Fraction of skipped layers |
341
+
342
+ ### Results
343
+
344
+ #### Benchmark 1 — Offline Tests
345
+
346
+ | Model | Pass Rate |
347
+ |-------|-----------|
348
+ | **This Model** | **28/28 tests** |
349
+ | — | — |
350
+
351
+ ---
352
+
353
+ ## Environmental Impact
354
+
355
+ | Factor | Value |
356
+ |--------|-------|
357
+ | Hardware Type | GPU (NVIDIA Tesla P100) |
358
+ | Hours used | 0.5 hours |
359
+ | Cloud Provider | Kaggle |
360
+ | Compute Region | US |
361
+ | Carbon Emitted | ~0.1 kg CO2 (estimated) |
362
+ | Energy Consumed | ~0.5 kWh (estimated) |
363
+
364
+ > Estimated using [ML CO2 Impact Calculator](https://mlco2.github.io/impact/)
365
+
366
+ ---
367
+
368
+ ## Technical Specifications
369
+
370
+ ### Model Architecture
371
+
372
+ | Specification | Value |
373
+ |---------------|-------|
374
+ | Architecture | Transformer + 14 novel subsystems + plugin system |
375
+ | Parameters | ~1.5B base + ~18M trainable |
376
+ | Layers | 28 (Qwen2.5-1.5B) |
377
+ | Hidden size | 1536 |
378
+ | Attention heads | 12 |
379
+ | Vocabulary size | 151,936 |
380
+ | Max context length | 8192 (extendable via RoPE scaling) |
381
+ | Embedding dimension | 1536 |
382
+
383
+ ### Compute Infrastructure
384
+
385
+ | Component | Specification |
386
+ |-----------|---------------|
387
+ | Hardware | NVIDIA Tesla P100 (Kaggle) |
388
+ | GPUs | 1 |
389
+ | Memory | 16GB VRAM |
390
+ | Storage | 10GB |
391
+ | Framework | PyTorch 2.0+ |
392
+ | Precision | FP16 / BF16 |
393
+
394
+ ---
395
+
396
+ ## Citation
397
+
398
+ ### BibTeX
399
+
400
+ ```bibtex
401
+ @misc{morph-ai-v6,
402
+ title = {MORPH-AI v6 (Cesium2): Modular Orchestrated Reasoning with Pattern-adaptive Hot-swappable Skills},
403
+ author = {MrityunjayK},
404
+ year = {2026},
405
+ url = {https://huggingface.co/ram1234598766/Cesium2},
406
+ note = {Trained on Kaggle Tesla P100 with QLoRA + 8-bit optimizer. Dynamic MoE expansion, multi-head CoT, plugin architecture.}
407
+ }
408
+ ```
409
+
410
+ ### APA
411
 
 
 
 
 
 
 
 
 
 
 
 
 
412
  ```
413
+ MrityunjayK (2026). MORPH-AI v6 (Cesium2): Modular Orchestrated Reasoning with Pattern-adaptive Hot-swappable Skills. https://huggingface.co/ram1234598766/Cesium2
414
+ ```
415
+
416
+ ---
417
+
418
+ ## Model Card Authors
419
+
420
+ - MrityunjayK ([@ram1234598766](https://github.com/ram1234598766-dotcom))
421
+
422
+ ---
423
 
424
+ ## Model Card Contact
425
 
426
+ - **GitHub:** [https://github.com/ram1234598766-dotcom](https://github.com/ram1234598766-dotcom)
427
+ - **HuggingFace:** [https://huggingface.co/ram1234598766](https://huggingface.co/ram1234598766)
export_gguf.py CHANGED
@@ -101,7 +101,7 @@ def test_gguf_model(model_path: str, prompt: str = "What is 2+2?"):
101
  try:
102
  llm = Llama(
103
  model_path=model_path,
104
- n_ctx=2048,
105
  n_gpu_layers=-1,
106
  verbose=False
107
  )
 
101
  try:
102
  llm = Llama(
103
  model_path=model_path,
104
+ n_ctx=8192,
105
  n_gpu_layers=-1,
106
  verbose=False
107
  )
src/architecture.py CHANGED
@@ -137,7 +137,7 @@ class MorphConfig:
137
  # plugin architecture
138
  plugin_dir: Optional[str] = None
139
  # training
140
- max_seq_len: int = 2048
141
  # quantization
142
  load_in_8bit: bool = False
143
  load_in_4bit: bool = True
@@ -1026,6 +1026,18 @@ class MorphModel(nn.Module):
1026
  hidden_dim = self.base_model_raw.config.hidden_size
1027
  vocab_size = self.base_model_raw.config.vocab_size
1028
 
 
 
 
 
 
 
 
 
 
 
 
 
1029
  # v6 subsystems
1030
  self.coordinator = Coordinator(self.cfg, hidden_dim)
1031
  self.reasoner = MultiStepReasoner(self.cfg, hidden_dim)
 
137
  # plugin architecture
138
  plugin_dir: Optional[str] = None
139
  # training
140
+ max_seq_len: int = 8192
141
  # quantization
142
  load_in_8bit: bool = False
143
  load_in_4bit: bool = True
 
1026
  hidden_dim = self.base_model_raw.config.hidden_size
1027
  vocab_size = self.base_model_raw.config.vocab_size
1028
 
1029
+ # Extend context window via RoPE scaling if configured
1030
+ original_max = getattr(self.base_model_raw.config, 'max_position_embeddings', 2048)
1031
+ if self.cfg.max_seq_len > original_max:
1032
+ print(f"Extending context: {original_max} -> {self.cfg.max_seq_len}")
1033
+ if hasattr(self.base_model_raw.config, 'rope_scaling') and self.base_model_raw.config.rope_scaling is None:
1034
+ self.base_model_raw.config.rope_scaling = {
1035
+ "type": "yarn",
1036
+ "factor": self.cfg.max_seq_len / original_max,
1037
+ }
1038
+ self.base_model_raw.config.max_position_embeddings = self.cfg.max_seq_len
1039
+ self.tokenizer.model_max_length = self.cfg.max_seq_len
1040
+
1041
  # v6 subsystems
1042
  self.coordinator = Coordinator(self.cfg, hidden_dim)
1043
  self.reasoner = MultiStepReasoner(self.cfg, hidden_dim)
src/runtime.py CHANGED
@@ -343,7 +343,7 @@ class MorphRuntime:
343
  else:
344
  self.active_skill = None
345
  prompt = self._build_prompt(f"system\nYou are a helpful assistant.\nuser\n{prompt}\nassistant\n", ctx)
346
- inputs = self.model.tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=2048)
347
  input_ids = inputs["input_ids"].to(self.device)
348
  attention_mask = inputs["attention_mask"].to(self.device)
349
 
@@ -432,7 +432,7 @@ class MorphRuntime:
432
  self.active_skill = None
433
 
434
  prompt = self._build_prompt(prompt, ctx)
435
- inputs = self.model.tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=2048)
436
  input_ids = inputs["input_ids"].to(self.device)
437
  attention_mask = inputs["attention_mask"].to(self.device)
438
 
 
343
  else:
344
  self.active_skill = None
345
  prompt = self._build_prompt(f"system\nYou are a helpful assistant.\nuser\n{prompt}\nassistant\n", ctx)
346
+ inputs = self.model.tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=self.model.cfg.max_seq_len)
347
  input_ids = inputs["input_ids"].to(self.device)
348
  attention_mask = inputs["attention_mask"].to(self.device)
349
 
 
432
  self.active_skill = None
433
 
434
  prompt = self._build_prompt(prompt, ctx)
435
+ inputs = self.model.tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=self.model.cfg.max_seq_len)
436
  input_ids = inputs["input_ids"].to(self.device)
437
  attention_mask = inputs["attention_mask"].to(self.device)
438
 
src/train.py CHANGED
@@ -87,7 +87,7 @@ def train(
87
  per_device_batch_size: int = 4,
88
  gradient_accumulation_steps: int = 8,
89
  learning_rate: float = 2e-4,
90
- max_seq_len: int = 2048,
91
  use_4bit: bool = True,
92
  train_components: bool = True,
93
  use_8bit_optimizer: bool = True,
@@ -286,7 +286,7 @@ if __name__ == "__main__":
286
  parser.add_argument("--batch", type=int, default=4)
287
  parser.add_argument("--grad-accum", type=int, default=8)
288
  parser.add_argument("--lr", type=float, default=2e-4)
289
- parser.add_argument("--max-len", type=int, default=2048)
290
  parser.add_argument("--no-4bit", action="store_true", help="Disable 4-bit quantization")
291
  parser.add_argument(
292
  "--no-components",
 
87
  per_device_batch_size: int = 4,
88
  gradient_accumulation_steps: int = 8,
89
  learning_rate: float = 2e-4,
90
+ max_seq_len: int = 8192,
91
  use_4bit: bool = True,
92
  train_components: bool = True,
93
  use_8bit_optimizer: bool = True,
 
286
  parser.add_argument("--batch", type=int, default=4)
287
  parser.add_argument("--grad-accum", type=int, default=8)
288
  parser.add_argument("--lr", type=float, default=2e-4)
289
+ parser.add_argument("--max-len", type=int, default=8192)
290
  parser.add_argument("--no-4bit", action="store_true", help="Disable 4-bit quantization")
291
  parser.add_argument(
292
  "--no-components",
test_inference.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Quick inference test with trained v6 model from Kaggle."""
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import torch
7
+ from transformers import AutoModelForCausalLM, AutoTokenizer
8
+
9
+ sys.path.insert(0, str(Path(__file__).resolve().parent / "src"))
10
+
11
+ from architecture import MorphConfig, MorphModel
12
+
13
+ CKPT_DIR = Path(__file__).resolve().parent / "kaggle-output2" / "output" / "morph-model"
14
+ MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"
15
+
16
+
17
+ def main():
18
+ print("Loading tokenizer...")
19
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
20
+
21
+ print("Loading base model (fp16 for inference)...")
22
+ base_model = AutoModelForCausalLM.from_pretrained(
23
+ MODEL_NAME,
24
+ trust_remote_code=True,
25
+ torch_dtype=torch.float16,
26
+ device_map="auto",
27
+ )
28
+
29
+ print("Building MorphModel v6...")
30
+ config = MorphConfig(base_model=MODEL_NAME, max_seq_len=8192)
31
+ model = MorphModel(config)
32
+ model.base_model_raw = base_model
33
+ model.apply_lora(target_modules=[
34
+ "q_proj", "k_proj", "v_proj", "o_proj",
35
+ "gate_proj", "up_proj", "down_proj",
36
+ ])
37
+ model.tokenizer = tokenizer
38
+ model.eval()
39
+
40
+ print(f"Loading trained weights from {CKPT_DIR / 'checkpoint-393' / 'model.safetensors'} ...")
41
+ from safetensors import safe_open
42
+ state_dict = {}
43
+ with safe_open(str(CKPT_DIR / "checkpoint-393" / "model.safetensors"), framework="pt") as f:
44
+ for key in f.keys():
45
+ state_dict[key] = f.get_tensor(key)
46
+
47
+ print(f"Loaded {len(state_dict)} tensors from checkpoint")
48
+ model.load_state_dict(state_dict)
49
+ print("Weights loaded successfully")
50
+
51
+ prompt = "What is 2+2? Think step by step."
52
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.base_model_raw.device)
53
+
54
+ with torch.no_grad():
55
+ outputs = model.base_model_raw.generate(
56
+ **inputs,
57
+ max_new_tokens=64,
58
+ do_sample=False,
59
+ )
60
+
61
+ result = tokenizer.decode(outputs[0], skip_special_tokens=True)
62
+ print("\n=== Inference Test ===")
63
+ print(result)
64
+ print("=== End ===")
65
+
66
+
67
+ if __name__ == "__main__":
68
+ main()
train_kaggle.py CHANGED
@@ -37,7 +37,7 @@ from architecture import MorphConfig, MorphModel
37
  MODEL_NAME = os.environ.get("MODEL_NAME", "Qwen/Qwen2.5-1.5B-Instruct")
38
  DATASETS_DIR = HERE / "datasets"
39
  OUTPUT_DIR = Path("./output/morph-model")
40
- MAX_LENGTH = 1024
41
  NUM_EPOCHS = 3
42
  BATCH_SIZE = 2
43
  GRAD_ACCUM = 8
 
37
  MODEL_NAME = os.environ.get("MODEL_NAME", "Qwen/Qwen2.5-1.5B-Instruct")
38
  DATASETS_DIR = HERE / "datasets"
39
  OUTPUT_DIR = Path("./output/morph-model")
40
+ MAX_LENGTH = 8192
41
  NUM_EPOCHS = 3
42
  BATCH_SIZE = 2
43
  GRAD_ACCUM = 8