Upload fsi_echo.py with huggingface_hub
Browse files- fsi_echo.py +68 -295
fsi_echo.py
CHANGED
|
@@ -1,34 +1,17 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
FSI_ECHO - Morphing Code Swarm
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
combined with nanobot swarm intelligence. Entirely my own design.
|
| 7 |
-
|
| 8 |
-
Core concepts:
|
| 9 |
-
1. MORPH EMBEDDING — Token embeddings transform/reconfigure based on context,
|
| 10 |
-
like a Transformer robot changing form for different situations.
|
| 11 |
-
2. NANOBOT SWARM — Hundreds of tiny processing units (nanobots) that each have
|
| 12 |
-
multiple operational modes (scout/combat/support). The router selects the
|
| 13 |
-
right mode per token, like nanobots reconfiguring for the task.
|
| 14 |
-
3. ASSEMBLY — Related nanobots combine into larger processing groups
|
| 15 |
-
(like Devastator forming from Constructicons) for deep reasoning.
|
| 16 |
-
4. DUAL PATH — Fast disguise mode (pattern matching) vs deep discovery mode
|
| 17 |
-
(analytical reasoning), with learned routing between them.
|
| 18 |
-
5. CLOSED-LOOP DEBUG — Generates, self-verifies, and iteratively refines code.
|
| 19 |
-
|
| 20 |
-
Size: ~3.1M params (fits in ~1.5MB at q4) — tiny enough for any device.
|
| 21 |
"""
|
| 22 |
-
import os, sys, json, time, math, random, re, struct
|
| 23 |
from typing import List, Dict, Optional, Tuple
|
| 24 |
-
from collections import defaultdict
|
| 25 |
import torch
|
| 26 |
import torch.nn as nn
|
| 27 |
import torch.nn.functional as F
|
| 28 |
-
import numpy as np
|
| 29 |
|
| 30 |
# =============================================================================
|
| 31 |
-
# 1.
|
| 32 |
# =============================================================================
|
| 33 |
class CodeTokenizer:
|
| 34 |
SPECIAL = {
|
|
@@ -78,20 +61,28 @@ class CodeTokenizer:
|
|
| 78 |
def encode(self, text: str, bos: bool = True, eos: bool = False) -> List[int]:
|
| 79 |
ids = []
|
| 80 |
if bos:
|
| 81 |
-
ids.append(
|
| 82 |
-
for token in re.findall(r'<[^>]+>|[A-Za-z_][A-Za-z0-9_]*|\.\.\.|==|!=|<=|>=|->|\*\*|//|\d+\.\d*|\d+|\S
|
| 83 |
-
if token.
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
if eos:
|
| 87 |
-
ids.append(
|
| 88 |
return ids[:2048]
|
| 89 |
-
def decode(self, ids: List[int], skip_special: bool =
|
| 90 |
tokens = []
|
| 91 |
for i in ids:
|
| 92 |
if i in self.inverse:
|
| 93 |
t = self.inverse[i]
|
| 94 |
-
if skip_special and t.startswith('<') and t.endswith('>'):
|
|
|
|
| 95 |
tokens.append(t)
|
| 96 |
else:
|
| 97 |
tokens.append(' ')
|
|
@@ -106,22 +97,17 @@ class CodeTokenizer:
|
|
| 106 |
def vocab_size_(self): return len(self.vocab)
|
| 107 |
|
| 108 |
# =============================================================================
|
| 109 |
-
# 2. MORPH EMBEDDING
|
| 110 |
# =============================================================================
|
| 111 |
class MorphEmbedding(nn.Module):
|
| 112 |
-
"""
|
| 113 |
-
Each token gets a base embedding PLUS a context-dependent morph vector.
|
| 114 |
-
The morph is computed from the token's neighbors — like a Transformer robot
|
| 115 |
-
changing its form based on the situation.
|
| 116 |
-
"""
|
| 117 |
def __init__(self, vocab_size: int, d_model: int, morph_width: int = 3):
|
| 118 |
super().__init__()
|
| 119 |
self.d_model = d_model
|
| 120 |
self.morph_width = morph_width
|
| 121 |
self.base_embed = nn.Embedding(vocab_size, d_model)
|
|
|
|
| 122 |
self.morph_net = nn.Sequential(
|
| 123 |
-
nn.Linear(d_model * morph_width, d_model),
|
| 124 |
-
nn.Tanh(),
|
| 125 |
nn.Linear(d_model, d_model),
|
| 126 |
)
|
| 127 |
self.gate = nn.Linear(d_model * 2, d_model)
|
|
@@ -129,7 +115,8 @@ class MorphEmbedding(nn.Module):
|
|
| 129 |
def forward(self, tokens: torch.Tensor) -> torch.Tensor:
|
| 130 |
B, T = tokens.shape
|
| 131 |
base = self.base_embed(tokens)
|
| 132 |
-
|
|
|
|
| 133 |
contexts = []
|
| 134 |
for i in range(self.morph_width):
|
| 135 |
contexts.append(padded[:, i:i+T, :])
|
|
@@ -139,36 +126,23 @@ class MorphEmbedding(nn.Module):
|
|
| 139 |
return base + gate * morph
|
| 140 |
|
| 141 |
# =============================================================================
|
| 142 |
-
# 3. NANOBOT SWARM
|
| 143 |
# =============================================================================
|
| 144 |
class NanobotSwarm(nn.Module):
|
| 145 |
-
"""
|
| 146 |
-
Inspired by nanobot swarms AND movie Transformers: each nanobot is a tiny
|
| 147 |
-
processor that can operate in different modes (scout/combat/support).
|
| 148 |
-
They communicate, combine, and their collective intelligence emerges.
|
| 149 |
-
|
| 150 |
-
- scout mode: lightweight pattern scanning (fast FFN, small dim)
|
| 151 |
-
- combat mode: deep analytical reasoning (full FFN, larger dim)
|
| 152 |
-
- support mode: coordination & information routing (gate network)
|
| 153 |
-
"""
|
| 154 |
def __init__(self, d_model: int, n_nanobots: int = 512, scout_dim: int = 64, combat_dim: int = 128):
|
| 155 |
super().__init__()
|
| 156 |
self.d_model = d_model
|
| 157 |
self.n_nanobots = n_nanobots
|
| 158 |
-
|
| 159 |
self.nano_keys = nn.Parameter(torch.randn(n_nanobots, d_model // 4))
|
| 160 |
self.nano_vals = nn.Parameter(torch.randn(n_nanobots, d_model))
|
| 161 |
-
|
| 162 |
self.scout_ffn = nn.Sequential(
|
| 163 |
nn.Linear(d_model, scout_dim), nn.GELU(), nn.Linear(scout_dim, d_model),
|
| 164 |
)
|
| 165 |
self.combat_ffn = nn.Sequential(
|
| 166 |
nn.Linear(d_model, combat_dim), nn.GELU(), nn.Linear(combat_dim, d_model),
|
| 167 |
)
|
| 168 |
-
|
| 169 |
self.mode_router = nn.Linear(d_model, 2)
|
| 170 |
self.assembly = nn.Linear(d_model, d_model)
|
| 171 |
-
|
| 172 |
self.norm = nn.LayerNorm(d_model)
|
| 173 |
self.dropout = nn.Dropout(0.1)
|
| 174 |
|
|
@@ -176,49 +150,33 @@ class NanobotSwarm(nn.Module):
|
|
| 176 |
B, T, D = x.shape
|
| 177 |
residual = x
|
| 178 |
x = self.norm(x)
|
| 179 |
-
|
| 180 |
router_query = x[..., :self.d_model // 4]
|
| 181 |
nano_scores = torch.matmul(router_query, self.nano_keys.T)
|
| 182 |
nano_weights = F.softmax(nano_scores / math.sqrt(self.d_model // 4), dim=-1)
|
| 183 |
-
|
| 184 |
mode_logits = self.mode_router(x)
|
| 185 |
mode_w = F.softmax(mode_logits, dim=-1)
|
| 186 |
-
|
| 187 |
scout_out = self.scout_ffn(x)
|
| 188 |
combat_out = self.combat_ffn(x)
|
| 189 |
mode_out = mode_w[:, :, 0:1] * scout_out + mode_w[:, :, 1:2] * combat_out
|
| 190 |
-
|
| 191 |
nano_out = torch.matmul(nano_weights, self.nano_vals)
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
out = residual + self.dropout(self.assembly(token_out))
|
| 195 |
return out
|
| 196 |
|
| 197 |
# =============================================================================
|
| 198 |
-
# 4. ASSEMBLY BLOCK
|
| 199 |
# =============================================================================
|
| 200 |
class AssemblyBlock(nn.Module):
|
| 201 |
-
"""
|
| 202 |
-
Larger processing block formed when nanobots combine forces.
|
| 203 |
-
Like Constructicons forming Devastator — individual units combine into
|
| 204 |
-
a more powerful entity for complex reasoning.
|
| 205 |
-
"""
|
| 206 |
def __init__(self, d_model: int, n_heads: int = 4, dropout: float = 0.1):
|
| 207 |
super().__init__()
|
| 208 |
self.d_model = d_model
|
| 209 |
self.n_heads = n_heads
|
| 210 |
self.head_dim = d_model // n_heads
|
| 211 |
-
|
| 212 |
self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
|
| 213 |
self.proj = nn.Linear(d_model, d_model, bias=False)
|
| 214 |
-
|
| 215 |
self.ffn = nn.Sequential(
|
| 216 |
-
nn.Linear(d_model, d_model * 2),
|
| 217 |
-
nn.
|
| 218 |
-
nn.Linear(d_model * 2, d_model),
|
| 219 |
-
nn.Dropout(dropout),
|
| 220 |
)
|
| 221 |
-
|
| 222 |
self.adapt_gate = nn.Linear(d_model, 1)
|
| 223 |
self.norm1 = nn.LayerNorm(d_model)
|
| 224 |
self.norm2 = nn.LayerNorm(d_model)
|
|
@@ -226,70 +184,45 @@ class AssemblyBlock(nn.Module):
|
|
| 226 |
|
| 227 |
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 228 |
B, T, D = x.shape
|
| 229 |
-
|
| 230 |
-
# Multi-head attention
|
| 231 |
qkv = self.qkv(self.norm1(x))
|
| 232 |
qkv = qkv.reshape(B, T, 3, self.n_heads, self.head_dim)
|
| 233 |
q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
|
| 234 |
-
q = q.transpose(1, 2)
|
| 235 |
-
k = k.transpose(1, 2)
|
| 236 |
-
v = v.transpose(1, 2)
|
| 237 |
scale = math.sqrt(self.head_dim)
|
| 238 |
attn = torch.matmul(q, k.transpose(-2, -1)) / scale
|
| 239 |
mask = torch.triu(torch.ones(T, T, device=x.device) * float('-inf'), diagonal=1)
|
| 240 |
attn = attn + mask.unsqueeze(0)
|
| 241 |
attn = F.softmax(attn, dim=-1)
|
| 242 |
-
out = torch.matmul(attn, v)
|
| 243 |
-
out = out.transpose(1, 2).reshape(B, T, D)
|
| 244 |
out = self.proj(out)
|
| 245 |
x = x + self.dropout(out)
|
| 246 |
-
|
| 247 |
-
# Adaptive FFN with gating
|
| 248 |
gate = torch.sigmoid(self.adapt_gate(self.norm2(x)))
|
| 249 |
-
|
| 250 |
-
x = x + gate * self.dropout(ffn_out)
|
| 251 |
-
|
| 252 |
return x
|
| 253 |
|
| 254 |
# =============================================================================
|
| 255 |
-
# 5. FSI_ECHO MODEL
|
| 256 |
# =============================================================================
|
| 257 |
class FSIEchoModel(nn.Module):
|
| 258 |
-
"""
|
| 259 |
-
FSI_ECHO: Morphing Code Swarm
|
| 260 |
-
- Morph Embedding: tokens transform based on context
|
| 261 |
-
- Nanobot Swarm: tiny specialists with multiple operational modes
|
| 262 |
-
- Assembly Blocks: combined processing for deep reasoning
|
| 263 |
-
- Dual Output: generation + self-verification
|
| 264 |
-
"""
|
| 265 |
def __init__(self, vocab_size: int = 4096, d_model: int = 192,
|
| 266 |
n_swarm_layers: int = 3, n_assembly_layers: int = 3,
|
| 267 |
n_nanobots: int = 512):
|
| 268 |
super().__init__()
|
| 269 |
self.vocab_size = vocab_size
|
| 270 |
self.d_model = d_model
|
| 271 |
-
|
| 272 |
self.morph_embed = MorphEmbedding(vocab_size, d_model)
|
| 273 |
-
|
| 274 |
self.swarm_layers = nn.ModuleList([
|
| 275 |
NanobotSwarm(d_model, n_nanobots) for _ in range(n_swarm_layers)
|
| 276 |
])
|
| 277 |
-
|
| 278 |
self.assembly_layers = nn.ModuleList([
|
| 279 |
AssemblyBlock(d_model) for _ in range(n_assembly_layers)
|
| 280 |
])
|
| 281 |
-
|
| 282 |
self.norm = nn.LayerNorm(d_model)
|
| 283 |
-
|
| 284 |
-
# Self-verification head — predicts confidence per token
|
| 285 |
self.verify = nn.Sequential(
|
| 286 |
-
nn.Linear(d_model, d_model // 2), nn.GELU(),
|
| 287 |
-
nn.Linear(d_model // 2, 1),
|
| 288 |
)
|
| 289 |
-
|
| 290 |
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
|
| 291 |
self.lm_head.weight = self.morph_embed.base_embed.weight
|
| 292 |
-
|
| 293 |
self._init_weights()
|
| 294 |
|
| 295 |
def _init_weights(self):
|
|
@@ -313,12 +246,12 @@ class FSIEchoModel(nn.Module):
|
|
| 313 |
confidence = torch.sigmoid(self.verify(x)).squeeze(-1)
|
| 314 |
loss = None
|
| 315 |
if targets is not None:
|
| 316 |
-
loss = F.cross_entropy(logits.view(-1, self.vocab_size), targets.view(-1))
|
| 317 |
return {'logits': logits, 'confidence': confidence, 'loss': loss}
|
| 318 |
|
| 319 |
@torch.no_grad()
|
| 320 |
def generate(self, tokenizer, prompt: str, max_tokens: int = 512,
|
| 321 |
-
temperature: float = 0.
|
| 322 |
self.eval()
|
| 323 |
device = next(self.parameters()).device
|
| 324 |
toks = torch.tensor([tokenizer.encode(prompt)], dtype=torch.long, device=device)
|
|
@@ -336,12 +269,14 @@ class FSIEchoModel(nn.Module):
|
|
| 336 |
rm = cum > top_p
|
| 337 |
rm[1:] = rm[:-1].clone()
|
| 338 |
rm[0] = False
|
| 339 |
-
logits[rm] = float('-inf')
|
| 340 |
logits = torch.nan_to_num(logits, nan=-100.0, posinf=100.0, neginf=-100.0)
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
|
|
|
|
|
|
| 345 |
confs.append(out['confidence'][0, -1].item())
|
| 346 |
if nxt.item() == tokenizer.eos_id:
|
| 347 |
break
|
|
@@ -355,54 +290,8 @@ class FSIEchoModel(nn.Module):
|
|
| 355 |
return sum(p.numel() for p in self.parameters())
|
| 356 |
|
| 357 |
# =============================================================================
|
| 358 |
-
# 6.
|
| 359 |
# =============================================================================
|
| 360 |
-
def make_training_data() -> List[str]:
|
| 361 |
-
texts = []
|
| 362 |
-
gold_path = '/tmp/fsi_felon/gold_standard_corpus.jsonl'
|
| 363 |
-
if os.path.exists(gold_path):
|
| 364 |
-
with open(gold_path) as f:
|
| 365 |
-
for line in f:
|
| 366 |
-
try:
|
| 367 |
-
d = json.loads(line)
|
| 368 |
-
for k in ['text', 'code', 'response', 'content', 'output']:
|
| 369 |
-
if d.get(k) and len(d[k]) > 30:
|
| 370 |
-
texts.append(d[k])
|
| 371 |
-
break
|
| 372 |
-
except: pass
|
| 373 |
-
# Synthetic code examples
|
| 374 |
-
examples = [
|
| 375 |
-
("sort", "def sort_list(lst):\n return sorted(lst)"),
|
| 376 |
-
("max", "def max_value(lst):\n return max(lst) if lst else None"),
|
| 377 |
-
("reverse string", "def reverse(s):\n return s[::-1]"),
|
| 378 |
-
("palindrome", "def is_palindrome(s):\n s = s.lower().replace(' ', '')\n return s == s[::-1]"),
|
| 379 |
-
("prime check", "def is_prime(n):\n if n < 2: return False\n for i in range(2, int(n**0.5)+1):\n if n % i == 0: return False\n return True"),
|
| 380 |
-
("fibonacci", "def fib(n):\n a, b = 0, 1\n for _ in range(n):\n yield a\n a, b = b, a + b"),
|
| 381 |
-
("binary search", "def binary_search(arr, target):\n l, r = 0, len(arr)-1\n while l <= r:\n m = (l+r)//2\n if arr[m] == target: return m\n elif arr[m] < target: l = m+1\n else: r = m-1\n return -1"),
|
| 382 |
-
("stack class", "class Stack:\n def __init__(self):\n self._items = []\n def push(self, item):\n self._items.append(item)\n def pop(self):\n return self._items.pop() if self._items else None\n def peek(self):\n return self._items[-1] if self._items else None\n @property\n def is_empty(self):\n return len(self._items) == 0"),
|
| 383 |
-
("cache decorator", "def cache(func):\n _cache = {}\n def wrapper(*args):\n if args not in _cache:\n _cache[args] = func(*args)\n return _cache[args]\n return wrapper"),
|
| 384 |
-
("flatten", "def flatten(lst):\n result = []\n for item in lst:\n if isinstance(item, list):\n result.extend(flatten(item))\n else:\n result.append(item)\n return result"),
|
| 385 |
-
("word count", "def word_count(text):\n from collections import Counter\n return Counter(text.lower().split())"),
|
| 386 |
-
("class decorator", "def singleton(cls):\n instances = {}\n def get(*args, **kwargs):\n if cls not in instances:\n instances[cls] = cls(*args, **kwargs)\n return instances[cls]\n return get"),
|
| 387 |
-
("validate email", "def is_valid_email(email):\n import re\n return bool(re.match(r'^[\\w.-]+@[\\w.-]+\\.\\w+$', email))"),
|
| 388 |
-
("merge dicts", "def merge(a, b):\n c = a.copy()\n c.update(b)\n return c"),
|
| 389 |
-
("chunk list", "def chunk(lst, n):\n return [lst[i:i+n] for i in range(0, len(lst), n)]"),
|
| 390 |
-
("factorial", "def factorial(n):\n return 1 if n <= 1 else n * factorial(n-1)"),
|
| 391 |
-
]
|
| 392 |
-
for desc, code in examples:
|
| 393 |
-
texts.append(f"Write a function to {desc}:\n```python\n{code}\n```")
|
| 394 |
-
# Bug-fix examples
|
| 395 |
-
bug_fixes = [
|
| 396 |
-
("use == not =", "if x = 5:", "if x == 5:"),
|
| 397 |
-
("missing return", "def add(a, b): a + b", "def add(a, b): return a + b"),
|
| 398 |
-
("off by one", "for i in range(len(lst)):", "for i in range(len(lst) - 1):"),
|
| 399 |
-
("bare except", "try: x = 1/y\nexcept: pass", "try: x = 1/y\nexcept ZeroDivisionError: pass"),
|
| 400 |
-
("mutable default", "def f(x=[]): x.append(1); return x", "def f(x=None): x = x or []; x.append(1); return x"),
|
| 401 |
-
]
|
| 402 |
-
for desc, buggy, fixed in bug_fixes:
|
| 403 |
-
texts.append(f"Fix this bug ({desc}):\n```python\n{buggy}\n```\nFixed:\n```python\n{fixed}\n```")
|
| 404 |
-
return texts
|
| 405 |
-
|
| 406 |
class Trainer:
|
| 407 |
def __init__(self, model: FSIEchoModel, tokenizer: CodeTokenizer, lr: float = 3e-4):
|
| 408 |
self.model = model
|
|
@@ -413,8 +302,8 @@ class Trainer:
|
|
| 413 |
def step(self, texts: List[str], batch_size: int = 2, device: str = 'cpu') -> float:
|
| 414 |
self.model.train()
|
| 415 |
batch = random.sample(texts, min(batch_size, len(texts)))
|
| 416 |
-
max_len = 0
|
| 417 |
encoded = []
|
|
|
|
| 418 |
for t in batch:
|
| 419 |
toks = self.tokenizer.encode(t)
|
| 420 |
if 5 < len(toks) <= 2048:
|
|
@@ -423,11 +312,11 @@ class Trainer:
|
|
| 423 |
if not encoded:
|
| 424 |
return 0.0
|
| 425 |
padded = torch.zeros(len(encoded), max_len, dtype=torch.long)
|
| 426 |
-
targets = torch.full((len(encoded), max_len),
|
| 427 |
for i, toks in enumerate(encoded):
|
| 428 |
padded[i, :len(toks)] = torch.tensor(toks)
|
| 429 |
targets[i, :len(toks)-1] = torch.tensor(toks[1:])
|
| 430 |
-
targets[i, len(toks)-1] =
|
| 431 |
padded, targets = padded.to(device), targets.to(device)
|
| 432 |
out = self.model(padded, targets)
|
| 433 |
self.optimizer.zero_grad()
|
|
@@ -446,7 +335,6 @@ class Trainer:
|
|
| 446 |
'n_swarm': len(self.model.swarm_layers), 'n_assembly': len(self.model.assembly_layers),
|
| 447 |
'n_nanobots': self.model.swarm_layers[0].n_nanobots if self.model.swarm_layers else 512},
|
| 448 |
}, path)
|
| 449 |
-
print(f"Saved {path}")
|
| 450 |
|
| 451 |
@classmethod
|
| 452 |
def load(cls, path: str, device: str = 'cpu') -> 'Trainer':
|
|
@@ -463,11 +351,10 @@ class Trainer:
|
|
| 463 |
if 'optimizer' in data:
|
| 464 |
t.optimizer.load_state_dict(data['optimizer'])
|
| 465 |
model.to(device)
|
| 466 |
-
print(f"Loaded {path} ({model.param_count():,} params)")
|
| 467 |
return t
|
| 468 |
|
| 469 |
# =============================================================================
|
| 470 |
-
# 7. CLOSED-LOOP DEBUG
|
| 471 |
# =============================================================================
|
| 472 |
class CodeVerifier:
|
| 473 |
@staticmethod
|
|
@@ -477,20 +364,14 @@ class CodeVerifier:
|
|
| 477 |
return True, ""
|
| 478 |
except SyntaxError as e:
|
| 479 |
return False, f"Line {e.lineno}: {e.msg}"
|
| 480 |
-
|
| 481 |
@staticmethod
|
| 482 |
def find_issues(code: str) -> List[str]:
|
| 483 |
issues = []
|
| 484 |
for i, line in enumerate(code.split('\n'), 1):
|
| 485 |
s = line.strip()
|
| 486 |
-
if '== True' in s or '== False' in s:
|
| 487 |
-
issues.append(f"L{i}: Use 'if x:' instead of 'if x == True/False'")
|
| 488 |
-
if s.startswith('if ') and ':' not in s:
|
| 489 |
-
issues.append(f"L{i}: Missing colon")
|
| 490 |
if s == 'except:':
|
| 491 |
issues.append(f"L{i}: Bare except — specify exception")
|
| 492 |
return issues
|
| 493 |
-
|
| 494 |
def verify(self, code: str) -> Dict:
|
| 495 |
ok, err = self.check_syntax(code)
|
| 496 |
issues = self.find_issues(code)
|
|
@@ -502,19 +383,16 @@ class ClosedLoopDebugger:
|
|
| 502 |
self.tokenizer = tokenizer
|
| 503 |
self.max_iters = max_iters
|
| 504 |
self.verifier = CodeVerifier()
|
| 505 |
-
|
| 506 |
-
|
| 507 |
result = self._extract_code(code)
|
| 508 |
if not result:
|
| 509 |
return {'code': code, 'error': 'Could not parse code', 'iterations': 0, 'confidence': 0.0}
|
| 510 |
buggy = result
|
| 511 |
-
prompt = f"Fix this code:\n```python\n{buggy}\n```\n"
|
| 512 |
-
if requirement:
|
| 513 |
-
prompt += f"Requirement: {requirement}\n"
|
| 514 |
-
prompt += "Fixed:\n```python\n"
|
| 515 |
best_code, best_v = buggy, self.verifier.verify(buggy)
|
| 516 |
-
for i in range(
|
| 517 |
-
gen = self.model.generate(self.tokenizer, prompt, max_tokens=
|
| 518 |
fixed = self._extract_code(gen['generated'])
|
| 519 |
if not fixed:
|
| 520 |
prompt += "\n```python\n"
|
|
@@ -525,13 +403,12 @@ class ClosedLoopDebugger:
|
|
| 525 |
if len(v['issues']) < len(best_v['issues']):
|
| 526 |
best_code, best_v = fixed, v
|
| 527 |
if v['issues']:
|
| 528 |
-
prompt += f"\
|
| 529 |
elif not v['syntax_ok']:
|
| 530 |
-
prompt += f"\n
|
| 531 |
else:
|
| 532 |
break
|
| 533 |
-
return {'code': best_code, 'verification': best_v, 'iterations':
|
| 534 |
-
|
| 535 |
def _extract_code(self, text: str) -> str:
|
| 536 |
m = re.search(r'```(?:python)?\n(.*?)```', text, re.DOTALL)
|
| 537 |
if m: return m.group(1).strip()
|
|
@@ -548,11 +425,10 @@ class ClosedLoopDebugger:
|
|
| 548 |
# =============================================================================
|
| 549 |
def export_gguf(model: FSIEchoModel, tokenizer: CodeTokenizer, path: str):
|
| 550 |
sd = model.state_dict()
|
| 551 |
-
magic, version = b'GGUF', 3
|
| 552 |
keys = sorted(sd.keys())
|
| 553 |
meta = {
|
| 554 |
'general.name': 'FSI_ECHO', 'general.architecture': 'fsi_echo',
|
| 555 |
-
'general.description': 'Morphing Code Swarm
|
| 556 |
'general.file_type': 0, 'general.vocab_size': model.vocab_size,
|
| 557 |
'general.context_length': 2048, 'general.parameter_count': model.param_count(),
|
| 558 |
'fsi_echo.block_count': len(model.swarm_layers) + len(model.assembly_layers),
|
|
@@ -562,7 +438,7 @@ def export_gguf(model: FSIEchoModel, tokenizer: CodeTokenizer, path: str):
|
|
| 562 |
'fsi_echo.nanobot_count': model.swarm_layers[0].n_nanobots if model.swarm_layers else 512,
|
| 563 |
}
|
| 564 |
with open(path, 'wb') as f:
|
| 565 |
-
f.write(
|
| 566 |
for k, v in meta.items():
|
| 567 |
f.write(struct.pack('<I', len(k)) + k.encode())
|
| 568 |
if isinstance(v, str):
|
|
@@ -581,133 +457,30 @@ def export_gguf(model: FSIEchoModel, tokenizer: CodeTokenizer, path: str):
|
|
| 581 |
offset += sd[name].numel() * 4
|
| 582 |
for name in keys:
|
| 583 |
f.write(sd[name].float().numpy().tobytes())
|
| 584 |
-
sz = os.path.getsize(path)
|
| 585 |
-
print(f"GGUF: {path} ({sz/1e6:.1f}MB)")
|
| 586 |
|
| 587 |
# =============================================================================
|
| 588 |
-
# 9.
|
| 589 |
-
# =============================================================================
|
| 590 |
-
def benchmark(model: FSIEchoModel, tokenizer: CodeTokenizer) -> Dict:
|
| 591 |
-
cases = {
|
| 592 |
-
'code_gen': [
|
| 593 |
-
("reverse string", "def reverse(s):"),
|
| 594 |
-
("find max", "def find_max(lst):"),
|
| 595 |
-
("prime check", "def is_prime(n):"),
|
| 596 |
-
("binary search", "def binary_search(arr, target):"),
|
| 597 |
-
("word count", "def word_count(text):"),
|
| 598 |
-
("fibonacci", "def fib(n):"),
|
| 599 |
-
("stack class", "class Stack:"),
|
| 600 |
-
("merge dicts", "def merge(a, b):"),
|
| 601 |
-
],
|
| 602 |
-
'bug_fix': [
|
| 603 |
-
("fix ==", "if x == 5:"),
|
| 604 |
-
("fix return", "return a + b"),
|
| 605 |
-
],
|
| 606 |
-
}
|
| 607 |
-
results = {}
|
| 608 |
-
model.eval()
|
| 609 |
-
for cat, items in cases.items():
|
| 610 |
-
passed = 0
|
| 611 |
-
for name, expected in items:
|
| 612 |
-
prompt = f"Write a function to {name}:\n```python\n"
|
| 613 |
-
r = model.generate(tokenizer, prompt, max_tokens=128, temperature=0.3, top_k=10)
|
| 614 |
-
ok = expected.lower() in r['generated'].lower()
|
| 615 |
-
if ok: passed += 1
|
| 616 |
-
results[f"{cat}/{name}"] = {'pass': ok, 'conf': r['confidence']}
|
| 617 |
-
results[f"{cat}_acc"] = passed / max(len(items), 1)
|
| 618 |
-
total_pass = sum(1 for k, v in results.items() if isinstance(v, dict) and v.get('pass'))
|
| 619 |
-
total = sum(1 for k, v in results.items() if isinstance(v, dict) and 'pass' in v)
|
| 620 |
-
results['overall_acc'] = total_pass / max(total, 1)
|
| 621 |
-
results['params'] = model.param_count()
|
| 622 |
-
results['model_mb_fp32'] = model.param_count() * 4 / 1e6
|
| 623 |
-
results['model_mb_q4'] = model.param_count() * 0.5 / 1e6
|
| 624 |
-
return results
|
| 625 |
-
|
| 626 |
-
# =============================================================================
|
| 627 |
-
# 10. MAIN
|
| 628 |
# =============================================================================
|
| 629 |
if __name__ == '__main__':
|
| 630 |
import argparse
|
| 631 |
-
p = argparse.ArgumentParser(description='FSI_ECHO
|
| 632 |
p.add_argument('--train', action='store_true')
|
| 633 |
-
p.add_argument('--
|
| 634 |
p.add_argument('--gguf', type=str, help='Export to GGUF')
|
| 635 |
p.add_argument('--load', type=str, help='Load checkpoint')
|
| 636 |
p.add_argument('--steps', type=int, default=5000)
|
| 637 |
-
p.add_argument('--interactive', action='store_true')
|
| 638 |
-
p.add_argument('--debug', type=str, help='Debug code string or file')
|
| 639 |
args = p.parse_args()
|
| 640 |
-
|
| 641 |
-
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 642 |
-
print(f"FSI_ECHO on {device}")
|
| 643 |
-
|
| 644 |
if args.load and os.path.exists(args.load):
|
| 645 |
trainer = Trainer.load(args.load, device)
|
| 646 |
else:
|
| 647 |
model = FSIEchoModel()
|
| 648 |
model.to(device)
|
| 649 |
-
|
| 650 |
print(f"New model: {model.param_count():,} params")
|
| 651 |
-
|
| 652 |
-
if args.
|
| 653 |
-
|
| 654 |
-
print(
|
| 655 |
-
os.makedirs('/tmp/fsi_echo/checkpoints', exist_ok=True)
|
| 656 |
-
start = time.time()
|
| 657 |
-
losses = []
|
| 658 |
-
for step in range(1, args.steps + 1):
|
| 659 |
-
loss = trainer.step(texts, batch_size=2, device=device)
|
| 660 |
-
losses.append(loss)
|
| 661 |
-
if step % 50 == 0:
|
| 662 |
-
avg = sum(losses[-50:]) / max(len(losses[-50:]), 1)
|
| 663 |
-
print(f"Step {step:>6}/{args.steps} | loss {avg:.4f} | {time.time()-start:.0f}s")
|
| 664 |
-
if step % 500 == 0:
|
| 665 |
-
trainer.save(f'/tmp/fsi_echo/checkpoints/step_{step}.pt')
|
| 666 |
-
print(json.dumps(benchmark(trainer.model, trainer.tokenizer), indent=2))
|
| 667 |
-
trainer.save('/tmp/fsi_echo/checkpoints/final.pt')
|
| 668 |
-
print(f"Done: {args.steps} steps in {time.time()-start:.0f}s")
|
| 669 |
-
|
| 670 |
-
if args.bench:
|
| 671 |
-
r = benchmark(trainer.model, trainer.tokenizer)
|
| 672 |
-
print("\n=== BENCHMARK ===")
|
| 673 |
-
for k, v in r.items():
|
| 674 |
-
if isinstance(v, dict):
|
| 675 |
-
print(f" {k}: {'PASS' if v.get('pass') else 'FAIL'} (conf={v.get('conf',0):.2f})")
|
| 676 |
-
else:
|
| 677 |
-
print(f" {k}: {v}")
|
| 678 |
-
with open('/tmp/fsi_echo/bench.json', 'w') as f:
|
| 679 |
-
json.dump(r, f, indent=2)
|
| 680 |
-
|
| 681 |
if args.gguf:
|
| 682 |
export_gguf(trainer.model, trainer.tokenizer, args.gguf)
|
| 683 |
-
|
| 684 |
-
if args.debug:
|
| 685 |
-
code = args.debug
|
| 686 |
-
if os.path.exists(code):
|
| 687 |
-
with open(code) as f:
|
| 688 |
-
code = f.read()
|
| 689 |
-
d = ClosedLoopDebugger(trainer.model, trainer.tokenizer)
|
| 690 |
-
r = d.debug(code)
|
| 691 |
-
print(f"\n{'='*40}\nResult ({r['iterations']} iters):\n{r['code']}")
|
| 692 |
-
if not r['verification']['valid']:
|
| 693 |
-
if r['verification']['error']: print(f"Syntax: {r['verification']['error']}")
|
| 694 |
-
for issue in r['verification']['issues']: print(f"Issue: {issue}")
|
| 695 |
-
else:
|
| 696 |
-
print("All checks passed!")
|
| 697 |
-
print(f"Confidence: {r['confidence']:.2f}")
|
| 698 |
-
|
| 699 |
-
if args.interactive:
|
| 700 |
-
d = ClosedLoopDebugger(trainer.model, trainer.tokenizer)
|
| 701 |
-
print("\nFSI_ECHO Interactive — commands: gen <prompt>, debug <code>, exit")
|
| 702 |
-
while True:
|
| 703 |
-
try:
|
| 704 |
-
cmd = input('\n> ').strip()
|
| 705 |
-
if cmd == 'exit': break
|
| 706 |
-
if cmd.startswith('debug '):
|
| 707 |
-
r = d.debug(cmd[6:])
|
| 708 |
-
print(f"\n{r['code']}\n[iters={r['iterations']}, conf={r['confidence']:.2f}]")
|
| 709 |
-
else:
|
| 710 |
-
r = trainer.model.generate(trainer.tokenizer, cmd, max_tokens=256)
|
| 711 |
-
print(f"\n{r['generated']}\n[conf={r['confidence']:.2f}]")
|
| 712 |
-
except (KeyboardInterrupt, EOFError):
|
| 713 |
-
break
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
FSI_ECHO - Morphing Code Swarm
|
| 4 |
+
Novel architecture: token morph embedding + nanobot swarm + assembly blocks + self-verification.
|
| 5 |
+
2.6M params — fits in 1.3MB at q4, runs on any phone.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
+
import os, sys, json, time, math, random, re, struct
|
| 8 |
from typing import List, Dict, Optional, Tuple
|
|
|
|
| 9 |
import torch
|
| 10 |
import torch.nn as nn
|
| 11 |
import torch.nn.functional as F
|
|
|
|
| 12 |
|
| 13 |
# =============================================================================
|
| 14 |
+
# 1. TOKENIZER
|
| 15 |
# =============================================================================
|
| 16 |
class CodeTokenizer:
|
| 17 |
SPECIAL = {
|
|
|
|
| 61 |
def encode(self, text: str, bos: bool = True, eos: bool = False) -> List[int]:
|
| 62 |
ids = []
|
| 63 |
if bos:
|
| 64 |
+
ids.append(2)
|
| 65 |
+
for token in re.findall(r'<[^>]+>|[A-Za-z_][A-Za-z0-9_]*|\.\.\.|==|!=|<=|>=|->|\*\*|//|::|=>|\d+\.\d*|\d+|\S', text):
|
| 66 |
+
if token in self.vocab:
|
| 67 |
+
ids.append(self.vocab[token])
|
| 68 |
+
elif token.lower() in self.vocab:
|
| 69 |
+
ids.append(self.vocab[token.lower()])
|
| 70 |
+
else:
|
| 71 |
+
for ch in token:
|
| 72 |
+
if ch in self.vocab:
|
| 73 |
+
ids.append(self.vocab[ch])
|
| 74 |
+
else:
|
| 75 |
+
ids.append(3)
|
| 76 |
if eos:
|
| 77 |
+
ids.append(1)
|
| 78 |
return ids[:2048]
|
| 79 |
+
def decode(self, ids: List[int], skip_special: bool = True) -> str:
|
| 80 |
tokens = []
|
| 81 |
for i in ids:
|
| 82 |
if i in self.inverse:
|
| 83 |
t = self.inverse[i]
|
| 84 |
+
if skip_special and t.startswith('<') and t.endswith('>'):
|
| 85 |
+
continue
|
| 86 |
tokens.append(t)
|
| 87 |
else:
|
| 88 |
tokens.append(' ')
|
|
|
|
| 97 |
def vocab_size_(self): return len(self.vocab)
|
| 98 |
|
| 99 |
# =============================================================================
|
| 100 |
+
# 2. MORPH EMBEDDING
|
| 101 |
# =============================================================================
|
| 102 |
class MorphEmbedding(nn.Module):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
def __init__(self, vocab_size: int, d_model: int, morph_width: int = 3):
|
| 104 |
super().__init__()
|
| 105 |
self.d_model = d_model
|
| 106 |
self.morph_width = morph_width
|
| 107 |
self.base_embed = nn.Embedding(vocab_size, d_model)
|
| 108 |
+
# Causal morph: only current + past (morph_width tokens, no future leakage)
|
| 109 |
self.morph_net = nn.Sequential(
|
| 110 |
+
nn.Linear(d_model * morph_width, d_model), nn.Tanh(),
|
|
|
|
| 111 |
nn.Linear(d_model, d_model),
|
| 112 |
)
|
| 113 |
self.gate = nn.Linear(d_model * 2, d_model)
|
|
|
|
| 115 |
def forward(self, tokens: torch.Tensor) -> torch.Tensor:
|
| 116 |
B, T = tokens.shape
|
| 117 |
base = self.base_embed(tokens)
|
| 118 |
+
# Causal sliding window: each position only sees itself and preceding tokens
|
| 119 |
+
padded = F.pad(base, (0, 0, self.morph_width - 1, 0), mode='replicate')
|
| 120 |
contexts = []
|
| 121 |
for i in range(self.morph_width):
|
| 122 |
contexts.append(padded[:, i:i+T, :])
|
|
|
|
| 126 |
return base + gate * morph
|
| 127 |
|
| 128 |
# =============================================================================
|
| 129 |
+
# 3. NANOBOT SWARM
|
| 130 |
# =============================================================================
|
| 131 |
class NanobotSwarm(nn.Module):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
def __init__(self, d_model: int, n_nanobots: int = 512, scout_dim: int = 64, combat_dim: int = 128):
|
| 133 |
super().__init__()
|
| 134 |
self.d_model = d_model
|
| 135 |
self.n_nanobots = n_nanobots
|
|
|
|
| 136 |
self.nano_keys = nn.Parameter(torch.randn(n_nanobots, d_model // 4))
|
| 137 |
self.nano_vals = nn.Parameter(torch.randn(n_nanobots, d_model))
|
|
|
|
| 138 |
self.scout_ffn = nn.Sequential(
|
| 139 |
nn.Linear(d_model, scout_dim), nn.GELU(), nn.Linear(scout_dim, d_model),
|
| 140 |
)
|
| 141 |
self.combat_ffn = nn.Sequential(
|
| 142 |
nn.Linear(d_model, combat_dim), nn.GELU(), nn.Linear(combat_dim, d_model),
|
| 143 |
)
|
|
|
|
| 144 |
self.mode_router = nn.Linear(d_model, 2)
|
| 145 |
self.assembly = nn.Linear(d_model, d_model)
|
|
|
|
| 146 |
self.norm = nn.LayerNorm(d_model)
|
| 147 |
self.dropout = nn.Dropout(0.1)
|
| 148 |
|
|
|
|
| 150 |
B, T, D = x.shape
|
| 151 |
residual = x
|
| 152 |
x = self.norm(x)
|
|
|
|
| 153 |
router_query = x[..., :self.d_model // 4]
|
| 154 |
nano_scores = torch.matmul(router_query, self.nano_keys.T)
|
| 155 |
nano_weights = F.softmax(nano_scores / math.sqrt(self.d_model // 4), dim=-1)
|
|
|
|
| 156 |
mode_logits = self.mode_router(x)
|
| 157 |
mode_w = F.softmax(mode_logits, dim=-1)
|
|
|
|
| 158 |
scout_out = self.scout_ffn(x)
|
| 159 |
combat_out = self.combat_ffn(x)
|
| 160 |
mode_out = mode_w[:, :, 0:1] * scout_out + mode_w[:, :, 1:2] * combat_out
|
|
|
|
| 161 |
nano_out = torch.matmul(nano_weights, self.nano_vals)
|
| 162 |
+
out = residual + self.dropout(self.assembly(mode_out + nano_out))
|
|
|
|
|
|
|
| 163 |
return out
|
| 164 |
|
| 165 |
# =============================================================================
|
| 166 |
+
# 4. ASSEMBLY BLOCK
|
| 167 |
# =============================================================================
|
| 168 |
class AssemblyBlock(nn.Module):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
def __init__(self, d_model: int, n_heads: int = 4, dropout: float = 0.1):
|
| 170 |
super().__init__()
|
| 171 |
self.d_model = d_model
|
| 172 |
self.n_heads = n_heads
|
| 173 |
self.head_dim = d_model // n_heads
|
|
|
|
| 174 |
self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
|
| 175 |
self.proj = nn.Linear(d_model, d_model, bias=False)
|
|
|
|
| 176 |
self.ffn = nn.Sequential(
|
| 177 |
+
nn.Linear(d_model, d_model * 2), nn.GELU(),
|
| 178 |
+
nn.Linear(d_model * 2, d_model), nn.Dropout(dropout),
|
|
|
|
|
|
|
| 179 |
)
|
|
|
|
| 180 |
self.adapt_gate = nn.Linear(d_model, 1)
|
| 181 |
self.norm1 = nn.LayerNorm(d_model)
|
| 182 |
self.norm2 = nn.LayerNorm(d_model)
|
|
|
|
| 184 |
|
| 185 |
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 186 |
B, T, D = x.shape
|
|
|
|
|
|
|
| 187 |
qkv = self.qkv(self.norm1(x))
|
| 188 |
qkv = qkv.reshape(B, T, 3, self.n_heads, self.head_dim)
|
| 189 |
q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
|
| 190 |
+
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
|
|
|
|
|
|
| 191 |
scale = math.sqrt(self.head_dim)
|
| 192 |
attn = torch.matmul(q, k.transpose(-2, -1)) / scale
|
| 193 |
mask = torch.triu(torch.ones(T, T, device=x.device) * float('-inf'), diagonal=1)
|
| 194 |
attn = attn + mask.unsqueeze(0)
|
| 195 |
attn = F.softmax(attn, dim=-1)
|
| 196 |
+
out = torch.matmul(attn, v).transpose(1, 2).reshape(B, T, D)
|
|
|
|
| 197 |
out = self.proj(out)
|
| 198 |
x = x + self.dropout(out)
|
|
|
|
|
|
|
| 199 |
gate = torch.sigmoid(self.adapt_gate(self.norm2(x)))
|
| 200 |
+
x = x + gate * self.dropout(self.ffn(self.norm2(x)))
|
|
|
|
|
|
|
| 201 |
return x
|
| 202 |
|
| 203 |
# =============================================================================
|
| 204 |
+
# 5. FSI_ECHO MODEL
|
| 205 |
# =============================================================================
|
| 206 |
class FSIEchoModel(nn.Module):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
def __init__(self, vocab_size: int = 4096, d_model: int = 192,
|
| 208 |
n_swarm_layers: int = 3, n_assembly_layers: int = 3,
|
| 209 |
n_nanobots: int = 512):
|
| 210 |
super().__init__()
|
| 211 |
self.vocab_size = vocab_size
|
| 212 |
self.d_model = d_model
|
|
|
|
| 213 |
self.morph_embed = MorphEmbedding(vocab_size, d_model)
|
|
|
|
| 214 |
self.swarm_layers = nn.ModuleList([
|
| 215 |
NanobotSwarm(d_model, n_nanobots) for _ in range(n_swarm_layers)
|
| 216 |
])
|
|
|
|
| 217 |
self.assembly_layers = nn.ModuleList([
|
| 218 |
AssemblyBlock(d_model) for _ in range(n_assembly_layers)
|
| 219 |
])
|
|
|
|
| 220 |
self.norm = nn.LayerNorm(d_model)
|
|
|
|
|
|
|
| 221 |
self.verify = nn.Sequential(
|
| 222 |
+
nn.Linear(d_model, d_model // 2), nn.GELU(), nn.Linear(d_model // 2, 1),
|
|
|
|
| 223 |
)
|
|
|
|
| 224 |
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
|
| 225 |
self.lm_head.weight = self.morph_embed.base_embed.weight
|
|
|
|
| 226 |
self._init_weights()
|
| 227 |
|
| 228 |
def _init_weights(self):
|
|
|
|
| 246 |
confidence = torch.sigmoid(self.verify(x)).squeeze(-1)
|
| 247 |
loss = None
|
| 248 |
if targets is not None:
|
| 249 |
+
loss = F.cross_entropy(logits.view(-1, self.vocab_size), targets.view(-1), ignore_index=0)
|
| 250 |
return {'logits': logits, 'confidence': confidence, 'loss': loss}
|
| 251 |
|
| 252 |
@torch.no_grad()
|
| 253 |
def generate(self, tokenizer, prompt: str, max_tokens: int = 512,
|
| 254 |
+
temperature: float = 0.3, top_k: int = 5, top_p: float = 0.9) -> Dict:
|
| 255 |
self.eval()
|
| 256 |
device = next(self.parameters()).device
|
| 257 |
toks = torch.tensor([tokenizer.encode(prompt)], dtype=torch.long, device=device)
|
|
|
|
| 269 |
rm = cum > top_p
|
| 270 |
rm[1:] = rm[:-1].clone()
|
| 271 |
rm[0] = False
|
| 272 |
+
logits[sorted_idx[rm]] = float('-inf')
|
| 273 |
logits = torch.nan_to_num(logits, nan=-100.0, posinf=100.0, neginf=-100.0)
|
| 274 |
+
logits[0] = float('-inf')
|
| 275 |
+
for rid in range(300, logits.size(-1)):
|
| 276 |
+
logits[rid] = float('-inf')
|
| 277 |
+
if (logits > float(-1e9)).sum() == 0:
|
| 278 |
+
logits[tokenizer.eos_id] = 0.0
|
| 279 |
+
nxt = logits.argmax().unsqueeze(0)
|
| 280 |
confs.append(out['confidence'][0, -1].item())
|
| 281 |
if nxt.item() == tokenizer.eos_id:
|
| 282 |
break
|
|
|
|
| 290 |
return sum(p.numel() for p in self.parameters())
|
| 291 |
|
| 292 |
# =============================================================================
|
| 293 |
+
# 6. TRAINER
|
| 294 |
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
class Trainer:
|
| 296 |
def __init__(self, model: FSIEchoModel, tokenizer: CodeTokenizer, lr: float = 3e-4):
|
| 297 |
self.model = model
|
|
|
|
| 302 |
def step(self, texts: List[str], batch_size: int = 2, device: str = 'cpu') -> float:
|
| 303 |
self.model.train()
|
| 304 |
batch = random.sample(texts, min(batch_size, len(texts)))
|
|
|
|
| 305 |
encoded = []
|
| 306 |
+
max_len = 0
|
| 307 |
for t in batch:
|
| 308 |
toks = self.tokenizer.encode(t)
|
| 309 |
if 5 < len(toks) <= 2048:
|
|
|
|
| 312 |
if not encoded:
|
| 313 |
return 0.0
|
| 314 |
padded = torch.zeros(len(encoded), max_len, dtype=torch.long)
|
| 315 |
+
targets = torch.full((len(encoded), max_len), 0, dtype=torch.long)
|
| 316 |
for i, toks in enumerate(encoded):
|
| 317 |
padded[i, :len(toks)] = torch.tensor(toks)
|
| 318 |
targets[i, :len(toks)-1] = torch.tensor(toks[1:])
|
| 319 |
+
targets[i, len(toks)-1] = 1
|
| 320 |
padded, targets = padded.to(device), targets.to(device)
|
| 321 |
out = self.model(padded, targets)
|
| 322 |
self.optimizer.zero_grad()
|
|
|
|
| 335 |
'n_swarm': len(self.model.swarm_layers), 'n_assembly': len(self.model.assembly_layers),
|
| 336 |
'n_nanobots': self.model.swarm_layers[0].n_nanobots if self.model.swarm_layers else 512},
|
| 337 |
}, path)
|
|
|
|
| 338 |
|
| 339 |
@classmethod
|
| 340 |
def load(cls, path: str, device: str = 'cpu') -> 'Trainer':
|
|
|
|
| 351 |
if 'optimizer' in data:
|
| 352 |
t.optimizer.load_state_dict(data['optimizer'])
|
| 353 |
model.to(device)
|
|
|
|
| 354 |
return t
|
| 355 |
|
| 356 |
# =============================================================================
|
| 357 |
+
# 7. CLOSED-LOOP DEBUG
|
| 358 |
# =============================================================================
|
| 359 |
class CodeVerifier:
|
| 360 |
@staticmethod
|
|
|
|
| 364 |
return True, ""
|
| 365 |
except SyntaxError as e:
|
| 366 |
return False, f"Line {e.lineno}: {e.msg}"
|
|
|
|
| 367 |
@staticmethod
|
| 368 |
def find_issues(code: str) -> List[str]:
|
| 369 |
issues = []
|
| 370 |
for i, line in enumerate(code.split('\n'), 1):
|
| 371 |
s = line.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
if s == 'except:':
|
| 373 |
issues.append(f"L{i}: Bare except — specify exception")
|
| 374 |
return issues
|
|
|
|
| 375 |
def verify(self, code: str) -> Dict:
|
| 376 |
ok, err = self.check_syntax(code)
|
| 377 |
issues = self.find_issues(code)
|
|
|
|
| 383 |
self.tokenizer = tokenizer
|
| 384 |
self.max_iters = max_iters
|
| 385 |
self.verifier = CodeVerifier()
|
| 386 |
+
def debug(self, code: str, requirement: str = "", max_iterations: int = None) -> Dict:
|
| 387 |
+
iters = max_iterations or self.max_iters
|
| 388 |
result = self._extract_code(code)
|
| 389 |
if not result:
|
| 390 |
return {'code': code, 'error': 'Could not parse code', 'iterations': 0, 'confidence': 0.0}
|
| 391 |
buggy = result
|
| 392 |
+
prompt = f"Fix this code:\n```python\n{buggy}\n```\nFixed:\n```python\n"
|
|
|
|
|
|
|
|
|
|
| 393 |
best_code, best_v = buggy, self.verifier.verify(buggy)
|
| 394 |
+
for i in range(iters):
|
| 395 |
+
gen = self.model.generate(self.tokenizer, prompt, max_tokens=256, temperature=0.3, top_k=5)
|
| 396 |
fixed = self._extract_code(gen['generated'])
|
| 397 |
if not fixed:
|
| 398 |
prompt += "\n```python\n"
|
|
|
|
| 403 |
if len(v['issues']) < len(best_v['issues']):
|
| 404 |
best_code, best_v = fixed, v
|
| 405 |
if v['issues']:
|
| 406 |
+
prompt += f"\nIssues: {'; '.join(v['issues'])}\nFixed:\n```python\n"
|
| 407 |
elif not v['syntax_ok']:
|
| 408 |
+
prompt += f"\n{v['error']}\nFixed:\n```python\n"
|
| 409 |
else:
|
| 410 |
break
|
| 411 |
+
return {'code': best_code, 'verification': best_v, 'iterations': iters, 'confidence': 0.0}
|
|
|
|
| 412 |
def _extract_code(self, text: str) -> str:
|
| 413 |
m = re.search(r'```(?:python)?\n(.*?)```', text, re.DOTALL)
|
| 414 |
if m: return m.group(1).strip()
|
|
|
|
| 425 |
# =============================================================================
|
| 426 |
def export_gguf(model: FSIEchoModel, tokenizer: CodeTokenizer, path: str):
|
| 427 |
sd = model.state_dict()
|
|
|
|
| 428 |
keys = sorted(sd.keys())
|
| 429 |
meta = {
|
| 430 |
'general.name': 'FSI_ECHO', 'general.architecture': 'fsi_echo',
|
| 431 |
+
'general.description': 'Morphing Code Swarm',
|
| 432 |
'general.file_type': 0, 'general.vocab_size': model.vocab_size,
|
| 433 |
'general.context_length': 2048, 'general.parameter_count': model.param_count(),
|
| 434 |
'fsi_echo.block_count': len(model.swarm_layers) + len(model.assembly_layers),
|
|
|
|
| 438 |
'fsi_echo.nanobot_count': model.swarm_layers[0].n_nanobots if model.swarm_layers else 512,
|
| 439 |
}
|
| 440 |
with open(path, 'wb') as f:
|
| 441 |
+
f.write(b'GGUF' + struct.pack('<I', 3) + struct.pack('<Q', len(keys)) + struct.pack('<Q', len(meta)))
|
| 442 |
for k, v in meta.items():
|
| 443 |
f.write(struct.pack('<I', len(k)) + k.encode())
|
| 444 |
if isinstance(v, str):
|
|
|
|
| 457 |
offset += sd[name].numel() * 4
|
| 458 |
for name in keys:
|
| 459 |
f.write(sd[name].float().numpy().tobytes())
|
|
|
|
|
|
|
| 460 |
|
| 461 |
# =============================================================================
|
| 462 |
+
# 9. MAIN
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
# =============================================================================
|
| 464 |
if __name__ == '__main__':
|
| 465 |
import argparse
|
| 466 |
+
p = argparse.ArgumentParser(description='FSI_ECHO')
|
| 467 |
p.add_argument('--train', action='store_true')
|
| 468 |
+
p.add_argument('--gen', type=str, help='Generate from prompt')
|
| 469 |
p.add_argument('--gguf', type=str, help='Export to GGUF')
|
| 470 |
p.add_argument('--load', type=str, help='Load checkpoint')
|
| 471 |
p.add_argument('--steps', type=int, default=5000)
|
|
|
|
|
|
|
| 472 |
args = p.parse_args()
|
| 473 |
+
device = 'cpu'
|
|
|
|
|
|
|
|
|
|
| 474 |
if args.load and os.path.exists(args.load):
|
| 475 |
trainer = Trainer.load(args.load, device)
|
| 476 |
else:
|
| 477 |
model = FSIEchoModel()
|
| 478 |
model.to(device)
|
| 479 |
+
tok = CodeTokenizer()
|
| 480 |
print(f"New model: {model.param_count():,} params")
|
| 481 |
+
trainer = Trainer(model, tok)
|
| 482 |
+
if args.gen:
|
| 483 |
+
r = trainer.model.generate(trainer.tokenizer, args.gen, max_tokens=256)
|
| 484 |
+
print(r['generated'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
if args.gguf:
|
| 486 |
export_gguf(trainer.model, trainer.tokenizer, args.gguf)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|