Thorne core

Laptop displaying coding interface with neon-lit cityscape and Japanese signs in background
Python
#!/bin/bash
# =============================================================================
# PROGRAM NAME: Thorn Production Installer Builder (Ubuntu 26.04)
# GOAL / PURPOSE: Automates the generation of a production-ready, fully
# compiled standalone executable binary and a .deb package
# for the independent Thorn Core Engine. Enables single-click
# installation without third-party network API dependencies.
# OWNER / AUTHOR: Proprietary System / Veteran-Led Private Architecture
# TARGET RECIPIENT: Special Edition Build (Family Archive Distribution)
# DEPLOYMENT DATE: June 8, 2026
# =============================================================================
set -e # Immediate termination upon any internal statement failure
# Standard terminal escape sequence color modifiers for output tracking
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo -e "${GREEN}================================================================${NC}"
echo -e "${GREEN} Thorn Core LLM Engine - Production Installer Builder${NC}"
echo -e "${GREEN}================================================================${NC}"
# -------------------------------------------------------------------------
# 1. Directory Context Allocation
# -------------------------------------------------------------------------
PROJECT_DIR="$HOME/ThornEngine"
INSTALLER_DIR="$PROJECT_DIR/installer_output"
mkdir -p "$PROJECT_DIR"
mkdir -p "$INSTALLER_DIR"
cd "$PROJECT_DIR"
echo -e "${YELLOW}[1/8] Setting workspace root to: $PROJECT_DIR${NC}"
# -------------------------------------------------------------------------
# 2. Host System Build Tool Assessment and Installation
# -------------------------------------------------------------------------
echo -e "${YELLOW}[2/8] Synchronizing system package maps and building baseline compilers...${NC}"
sudo apt-get update -qq
sudo apt-get install -y -qq python3-full python3-pip python3-venv git build-essential binutils file
# -------------------------------------------------------------------------
# 3. Virtual Environment Separation
# -------------------------------------------------------------------------
echo -e "${YELLOW}[3/8] Allocating clean local python virtual environment sandbox...${NC}"
python3 -m venv venv
source venv/bin/activate
pip install --quiet --upgrade pip
pip install --quiet numpy pyinstaller
# -------------------------------------------------------------------------
# 4. Monolithic Source Tree Generation (Internal Module Code Writes)
# -------------------------------------------------------------------------
echo -e "${YELLOW}[4/8] Building isolated python package source components...${NC}"
mkdir -p thorn_engine
# ----- Component A: Initialization Manifest -----
cat > thorn_engine/__init__.py << 'EOF'
"""
Thorn Core LLM Engine - Edge AI Transformer
"""
__version__ = "1.0.0"
EOF
# ----- Component B: Mathematical Transformer Architecture Core -----
cat > thorn_engine/core.py << 'EOF'
import numpy as np
class AutonomousTransformerBlock:
"""
Core tensor matrix math calculation layer. Tracks multi-head attention scores
and applies custom backward propagation gradients to alter internal registers
locally, without communicating with external network hosts.
"""
def __init__(self, d_model, num_heads):
self.d_model = d_model
self.num_heads = num_heads
assert d_model % num_heads == 0, "Embedding dimensions must divide evenly by head count."
self.d_k = d_model // num_heads
# Initial allocation of internal weight arrays using standard normal scale
self.W_q = np.random.randn(d_model, d_model) * np.sqrt(2.0 / d_model)
self.W_k = np.random.randn(d_model, d_model) * np.sqrt(2.0 / d_model)
self.W_v = np.random.randn(d_model, d_model) * np.sqrt(2.0 / d_model)
self.W_o = np.random.randn(d_model, d_model) * np.sqrt(2.0 / d_model)
d_ff = 4 * d_model
self.W_ff1 = np.random.randn(d_model, d_ff) * np.sqrt(2.0 / d_model)
self.b_ff1 = np.zeros((1, d_ff))
self.W_ff2 = np.random.randn(d_ff, d_model) * np.sqrt(2.0 / d_ff)
self.b_ff2 = np.zeros((1, d_model))
def _stable_softmax(self, x):
exp_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
return exp_x / np.sum(exp_x, axis=-1, keepdims=True)
def _split_heads(self, tensor, batch, seq):
return tensor.reshape(batch, seq, self.num_heads, self.d_k).transpose(0, 2, 1, 3)
def _merge_heads(self, tensor, batch, seq):
return tensor.transpose(0, 2, 1, 3).reshape(batch, seq, self.d_model)
def forward(self, X):
""" Runs raw matrix calculations forward through the model graph array. """
self.X = X
batch, seq, _ = X.shape
self.Q_all = X @ self.W_q
self.K_all = X @ self.W_k
self.V_all = X @ self.W_v
self.Q = self._split_heads(self.Q_all, batch, seq)
self.K = self._split_heads(self.K_all, batch, seq)
self.V = self._split_heads(self.V_all, batch, seq)
self.scores = np.matmul(self.Q, self.K.transpose(0, 1, 3, 2)) / np.sqrt(self.d_k)
self.attention_weights = self._stable_softmax(self.scores)
self.head_out = np.matmul(self.attention_weights, self.V)
# CRITICAL BUG FIX: Cache concatenated state to the instance pool to align with backward pass
self.concatenated_heads = self._merge_heads(self.head_out, batch, seq)
self.attn_out = self.concatenated_heads @ self.W_o
self.x_residual_1 = self.attn_out + X
self.ffn1_in = self.x_residual_1 @ self.W_ff1 + self.b_ff1
self.ffn1_out = np.maximum(0, self.ffn1_in)
self.ffn2_out = self.ffn1_out @ self.W_ff2 + self.b_ff2
final_block_output = self.ffn2_out + self.x_residual_1
return final_block_output
def backward(self, d_out, learning_rate=0.01):
""" Computes raw derivative error gradients and runs weight modifications. """
batch, seq, d_model = d_out.shape
dW_ff2 = (self.ffn1_out.reshape(-1, 4 * d_model).T @ d_out.reshape(-1, d_model))
db_ff2 = np.sum(d_out, axis=(0, 1), keepdims=True)
d_ffn1_out = d_out @ self.W_ff2.T
d_ffn1_in = d_ffn1_out * (self.ffn1_in > 0)
dW_ff1 = (self.x_residual_1.reshape(-1, d_model).T @ d_ffn1_in.reshape(-1, 4 * d_model))
db_ff1 = np.sum(d_ffn1_in, axis=(0, 1), keepdims=True)
d_residual_1 = d_ffn1_in @ self.W_ff1.T + d_out
d_concat = d_residual_1 @ self.W_o.T
dW_o = (self.concatenated_heads.reshape(-1, d_model).T @ d_residual_1.reshape(-1, d_model))
d_head = d_concat.reshape(batch, seq, self.num_heads, self.d_k).transpose(0, 2, 1, 3)
dV = np.matmul(self.attention_weights.transpose(0, 1, 3, 2), d_head)
d_attn = np.matmul(d_head, self.V.transpose(0, 1, 3, 2))
d_scores = self.attention_weights * (d_attn - np.sum(d_attn * self.attention_weights, axis=-1, keepdims=True))
d_scores /= np.sqrt(self.d_k)
dQ = np.matmul(d_scores, self.K)
dK = np.matmul(d_scores.transpose(0, 1, 3, 2), self.Q)
dQ_all = dQ.transpose(0, 2, 1, 3).reshape(batch, seq, d_model)
dK_all = dK.transpose(0, 2, 1, 3).reshape(batch, seq, d_model)
dV_all = dV.transpose(0, 2, 1, 3).reshape(batch, seq, d_model)
dW_q = self.X.reshape(-1, d_model).T @ dQ_all.reshape(-1, d_model)
dW_k = self.X.reshape(-1, d_model).T @ dK_all.reshape(-1, d_model)
dW_v = self.X.reshape(-1, d_model).T @ dV_all.reshape(-1, d_model)
# Apply array weight transformations locally via Stochastic Gradient Descent
self.W_q -= learning_rate * dW_q
self.W_k -= learning_rate * dW_k
self.W_v -= learning_rate * dW_v
self.W_o -= learning_rate * dW_o
self.W_ff1 -= learning_rate * dW_ff1
self.W_ff2 -= learning_rate * dW_ff2
self.b_ff1 -= learning_rate * db_ff1.reshape(self.b_ff1.shape)
self.b_ff2 -= learning_rate * db_ff2.reshape(self.b_ff2.shape)
EOF
# ----- Component C: Isolated Local Text Tokenizer -----
cat > thorn_engine/tokenizer.py << 'EOF'
import json
from pathlib import Path
from typing import List, Dict
class IsolatedVocabularyTokenizer:
""" Manages string to matrix array transformations completely inside local memory. """
def __init__(self, vocab: Dict[str, int] = None, unknown_token="<UNK>"):
self.unknown_token = unknown_token
self.vocab = vocab or {unknown_token: 0}
self.inverse_vocab = {v: k for k, v in self.vocab.items()}
self.next_id = len(self.vocab)
def encode(self, text: str) -> List[int]:
words = text.lower().replace('.', ' .').replace(',', ' ,').split()
return [self.vocab.get(w, self.vocab[self.unknown_token]) for w in words]
def decode(self, ids: List[int]) -> str:
return " ".join(self.inverse_vocab.get(i, self.unknown_token) for i in ids)
def add_word(self, word: str) -> int:
if word not in self.vocab:
self.vocab[word] = self.next_id
self.inverse_vocab[self.next_id] = word
self.next_id += 1
return self.vocab[word]
def save(self, path: Path):
with open(path, "w") as f:
json.dump(self.vocab, f)
@classmethod
def load(cls, path: Path):
with open(path, "r") as f:
vocab = json.load(f)
return cls(vocab)
EOF
# ----- Component D: Storage & Binary Serialization Layer -----
cat > thorn_engine/persistence.py << 'EOF'
import numpy as np
import json
from pathlib import Path
from .core import AutonomousTransformerBlock
from .tokenizer import IsolatedVocabularyTokenizer
class LocalPersistenceManager:
""" Writes and reads model matrices directly to host disk blocks. """
def __init__(self, storage_dir: Path):
self.storage_dir = Path(storage_dir)
self.storage_dir.mkdir(parents=True, exist_ok=True)
def save_model(self, block: AutonomousTransformerBlock, embedding: np.ndarray, tokenizer: IsolatedVocabularyTokenizer):
np.save(self.storage_dir / "embedding.npy", embedding)
tokenizer.save(self.storage_dir / "vocabulary.json")
for name in ["W_q", "W_k", "W_v", "W_o", "W_ff1", "W_ff2", "b_ff1", "b_ff2"]:
np.save(self.storage_dir / f"{name}.npy", getattr(block, name))
def load_model(self, block: AutonomousTransformerBlock):
try:
for name in ["W_q", "W_k", "W_v", "W_o", "W_ff1", "W_ff2", "b_ff1", "b_ff2"]:
setattr(block, name, np.load(self.storage_dir / f"{name}.npy"))
embedding = np.load(self.storage_dir / "embedding.npy")
tokenizer = IsolatedVocabularyTokenizer.load(self.storage_dir / "vocabulary.json")
return embedding, tokenizer
except FileNotFoundError:
return None, None
EOF
# ----- Component E: Interactive Command Shell -----
cat > thorn_engine/shell.py << 'EOF'
import numpy as np
from .core import AutonomousTransformerBlock
from .tokenizer import IsolatedVocabularyTokenizer
class LocalInteractiveConsole:
""" Handles terminal loops for user text evaluation profiles. """
def __init__(self, model: AutonomousTransformerBlock, tokenizer: IsolatedVocabularyTokenizer, embedding: np.ndarray):
self.model = model
self.tokenizer = tokenizer
self.embeddings = embedding
def run_terminal_loop(self):
print("\n" + "="*70)
print("Thorn Core LLM Engine - Standalone Interactive Terminal Console")
print("Execute manual inputs live. Type 'exit' to cleanly close context.")
print("="*70 + "\n")
while True:
try:
user_input = input("🌿 thorn> ")
if user_input.strip().lower() == "exit":
break
if not user_input.strip():
continue
tokens = self.tokenizer.encode(user_input)
if not tokens:
print("(zero indexed terms found)")
continue
vec = self.embeddings[tokens]
X = vec.reshape(1, len(tokens), self.model.d_model)
out = self.model.forward(X)
print(f" Tokens Array Map: {tokens}")
print(f" Computed Output Shape Block: {out.shape}")
except KeyboardInterrupt:
print("\n[SYSTEM] Session terminated via hardware signal intercept.")
break
EOF
# ----- Component F: Local Gradient Backprop Trainer -----
cat > thorn_engine/trainer.py << 'EOF'
import numpy as np
import logging
from pathlib import Path
from .core import AutonomousTransformerBlock
from .tokenizer import IsolatedVocabularyTokenizer
from .persistence import LocalPersistenceManager
logger = logging.getLogger("thorn")
def train_on_text(block: AutonomousTransformerBlock, tokenizer: IsolatedVocabularyTokenizer,
embedding: np.ndarray, text_file: Path, epochs: int, lr: float,
storage: LocalPersistenceManager, seq_len: int = 32):
""" Reads flat input documents and executes gradient tuning loops locally. """
with open(text_file, "r", encoding="utf-8") as f:
raw_text = f.read()
words = raw_text.lower().replace('.', ' .').replace(',', ' ,').split()
ids = []
for w in words:
if w not in tokenizer.vocab:
tokenizer.add_word(w)
ids.append(tokenizer.vocab[w])
old_vocab = embedding.shape[0]
new_vocab = len(tokenizer.vocab)
if new_vocab > old_vocab:
new_embed = np.random.randn(new_vocab, block.d_model) * 0.01
new_embed[:old_vocab] = embedding
embedding = new_embed
logger.info(f"Initiating optimization pass on {len(ids)} tokens. Active internal dictionary count: {new_vocab}")
for epoch in range(epochs):
loss_sum = 0.0
steps = 0
for i in range(0, len(ids) - seq_len, seq_len):
inp = ids[i:i+seq_len]
tgt = ids[i+1:i+seq_len+1]
if len(inp) < seq_len or len(tgt) < seq_len:
continue
X = embedding[inp].reshape(1, seq_len, block.d_model)
Y = embedding[tgt].reshape(1, seq_len, block.d_model)
out = block.forward(X)
loss = np.mean((out - Y) ** 2)
loss_sum += loss
d_out = 2 * (out - Y)
block.backward(d_out, learning_rate=lr)
steps += 1
if steps > 0:
avg_loss = loss_sum / steps
logger.info(f"Epoch Step [{epoch+1}/{epochs}] -> Compiled Layer Error Loss = {avg_loss:.6f}")
storage.save_model(block, embedding, tokenizer)
EOF
# ----- Component G: Command Line Router Entry Point -----
cat > thorn_engine/cli.py << 'EOF'
import argparse
import logging
import sys
from pathlib import Path
import numpy as np
from .core import AutonomousTransformerBlock
from .tokenizer import IsolatedVocabularyTokenizer
from .persistence import LocalPersistenceManager
from .shell import LocalInteractiveConsole
from .trainer import train_on_text
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger("thorn")
def main():
parser = argparse.ArgumentParser(prog="thorn", description="Thorn Core LLM Engine CLI Router")
parser.add_argument("--model-dir", type=Path, default="./thorn_weights")
parser.add_argument("--d-model", type=int, default=64)
parser.add_argument("--num-heads", type=int, default=4)
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("shell", help="Run standalone terminal interface")
train = sub.add_parser("train", help="Optimize weights using local flat document files")
train.add_argument("text_file", type=Path)
train.add_argument("--epochs", type=int, default=5)
train.add_argument("--lr", type=float, default=0.01)
args = parser.parse_args()
block = AutonomousTransformerBlock(args.d_model, args.num_heads)
store = LocalPersistenceManager(args.model_dir)
embedding, tokenizer = store.load_model(block)
if embedding is None:
logger.info("Initializing baseline array structures (zero binary assets located on local disk)")
base_vocab = {"<UNK>":0, ".":1, ",":2, "the":3, "a":4, "to":5, "of":6, "and":7}
tokenizer = IsolatedVocabularyTokenizer(base_vocab)
embedding = np.random.randn(len(tokenizer.vocab), args.d_model) * 0.01
store.save_model(block, embedding, tokenizer)
if args.command == "shell":
shell = LocalInteractiveConsole(block, tokenizer, embedding)
shell.run_terminal_loop()
elif args.command == "train":
train_on_text(block, tokenizer, embedding, args.text_file, args.epochs, args.lr, store)
else:
sys.exit(1)
if __name__ == "__main__":
main()
EOF
# ----- Build Setup Configuration Script -----
cat > setup.py << 'EOF'
from setuptools import setup, find_packages
setup(
name="thorn-engine",
version="1.0.0",
packages=find_packages(),
install_requires=["numpy"],
entry_points={"console_scripts": ["thorn = thorn_engine.cli:main"]},
author="Thorn Architecture",
description="Edge AI Transformer Engine",
)
EOF
echo "numpy" > requirements.txt
# -------------------------------------------------------------------------
# 5. Compiled Executable Compression Processing via PyInstaller
# -------------------------------------------------------------------------
echo -e "${YELLOW}[5/8] Compiling system components into flat binary layout via PyInstaller...${NC}"
pyinstaller --onefile --name thorn --console thorn_engine/cli.py --distpath "$INSTALLER_DIR" --workpath /tmp/build --specpath /tmp/spec
# -------------------------------------------------------------------------
# 6. Debian Deployment Package Core Mapping (.deb Compilation)
# -------------------------------------------------------------------------
echo -e "${YELLOW}[6/8] Building native debian package file system architectures...${NC}"
DEB_ROOT="$PROJECT_DIR/deb_package"
mkdir -p "$DEB_ROOT/usr/local/bin"
mkdir -p "$DEB_ROOT/DEBIAN"
cp "$INSTALLER_DIR/thorn" "$DEB_ROOT/usr/local/bin/"
cat > "$DEB_ROOT/DEBIAN/control" << EOF
Package: thorn-engine
Version: 1.0.0
Section: utils
Priority: optional
Architecture: amd64
Maintainer: Thorn <build@local>
Description: Thorn Core LLM Engine - Edge AI Transformer
A standalone transformer engine with local training and inference loops.
EOF
cat > "$DEB_ROOT/DEBIAN/postinst" << 'EOF'
#!/bin/sh
set -e
chmod +x /usr/local/bin/thorn
echo "[SUCCESS] Thorn Engine initialized in local system space. Call 'thorn shell' to operate."
EOF
chmod 755 "$DEB_ROOT/DEBIAN/postinst"
dpkg-deb --build "$DEB_ROOT" "$INSTALLER_DIR/thorn-engine_1.0.0_amd64.deb"
# -------------------------------------------------------------------------
# 7. Multi-Platform Portable Distribution Build
# -------------------------------------------------------------------------
echo -e "${YELLOW}[7/8] Generating source code backup distributions for other platforms...${NC}"
tar -czf "$INSTALLER_DIR/thorn-engine-source.tar.gz" \
--exclude='venv' \
--exclude='__pycache__' \
--exclude='*.pyc' \
--exclude='deb_package' \
--exclude='installer_output' \
--exclude='build' \
. 2>/dev/null || true
cat > "$PROJECT_DIR/build_other_platforms.sh" << 'EOF'
#!/bin/bash
echo "Building local execution blocks for this platform hardware layers..."
python3 -m venv venv
source venv/bin/activate
pip install numpy pyinstaller
pyinstaller --onefile --name thorn thorn_engine/cli.py
echo "[COMPLETE] Native execution file built inside dist/thorn directory structure"
EOF
chmod +x "$PROJECT_DIR/build_other_platforms.sh"
tar -rf "$INSTALLER_DIR/thorn-engine-source.tar.gz" build_other_platforms.sh 2>/dev/null
gzip -f "$INSTALLER_DIR/thorn-engine-source.tar.gz" 2>/dev/null || true
mv "$INSTALLER_DIR/thorn-engine-source.tar.gz.gz" "$INSTALLER_DIR/thorn-engine-source.tar.gz" 2>/dev/null || true
# -------------------------------------------------------------------------
# 8. Execution Validation Logs
# -------------------------------------------------------------------------
echo -e "${GREEN}[8/8] Deployment binary compilation actions finalized successfully.${NC}"
echo -e "${GREEN}================================================================${NC}"
echo -e "Operational production files committed directly to target output folder: ${YELLOW}$INSTALLER_DIR${NC}"
echo -e ""
echo -e " ${GREEN}► Linux Standalone Executable Command Binary:${NC} $INSTALLER_DIR/thorn"
echo -e " ${GREEN}► Managed Debian Package Installer Block (.deb):${NC} $INSTALLER_DIR/thorn-engine_1.0.0_amd64.deb"
echo -e " ${GREEN}► Universal Cross-Platform Target Source Archive:${NC} $INSTALLER_DIR/thorn-engine-source.tar.gz"
echo -e ""
echo -e "To integrate directly into your local machine kernel runtime profile paths:"
echo -e " ${YELLOW}sudo dpkg -i $INSTALLER_DIR/thorn-engine_1.0.0_amd64.deb${NC}"
echo -e " Then access the console at any point via: ${YELLOW}thorn shell${NC}"
echo -e ""
echo -e "To evaluate execution vectors instantly without package layer registration:"
echo -e " ${YELLOW}$INSTALLER_DIR/thorn shell${NC}"
echo -e "================================================================${NC}"
deactivate 2>/dev/null || true
Python
#!/bin/bash
# =============================================================================
# PROGRAM NAME: Thorn Multimodal GUI Installer Builder (Ubuntu 26.04)
# GOAL / PURPOSE: Automates the compilation of an integrated Tkinter GUI
# and decentralized multimodal text, image, video, and audio
# synthesis framework. Packages the stack into portable,
# offline-executable binaries (.deb + standalone executable).
# AUTHOR / OWNER: Proprietary System / Veteran-Led Private Architecture
# TARGET RECIPIENT: Special Edition Build (Family Archive Distribution)
# DEVELOPMENT DATE: June 8, 2026
# =============================================================================
set -e # Immediate termination if any internal statement errors out
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo -e "${GREEN}================================================================${NC}"
echo -e "${GREEN} Thorn Core GUI + Multimodal Engine - Production Builder${NC}"
echo -e "${GREEN}================================================================${NC}"
# -------------------------------------------------------------------------
# 1. Workspace Allocation
# -------------------------------------------------------------------------
PROJECT_DIR="$HOME/ThornEngineGUI"
INSTALLER_DIR="$PROJECT_DIR/installer_output"
mkdir -p "$PROJECT_DIR" "$INSTALLER_DIR"
cd "$PROJECT_DIR"
echo -e "${YELLOW}[1/8] Setting workspace root directory to: $PROJECT_DIR${NC}"
# -------------------------------------------------------------------------
# 2. System Layer Assessment & Tkinter Tool Dependencies
# -------------------------------------------------------------------------
echo -e "${YELLOW}[2/8] Synchronizing package maps and building baseline compilers...${NC}"
sudo apt-get update -qq
sudo apt-get install -y -qq python3-full python3-pip python3-venv python3-tk git build-essential binutils file
# -------------------------------------------------------------------------
# 3. Environment Isolation
# -------------------------------------------------------------------------
echo -e "${YELLOW}[3/8] Allocating clean local Python virtual environment sandbox...${NC}"
python3 -m venv venv
source venv/bin/activate
pip install --quiet --upgrade pip
pip install --quiet numpy pyinstaller
# -------------------------------------------------------------------------
# 4. Monolithic Source Tree Generation (Internal Module Code Writes)
# -------------------------------------------------------------------------
echo -e "${YELLOW}[4/8] Packaging modular python files into secure system directory...${NC}"
mkdir -p thorn_engine
# ----- Component A: Manifest -----
cat > thorn_engine/__init__.py << 'EOF'
"""
Thorn Core LLM & Multimodal Synthesis Engine
"""
__version__ = "1.0.0"
EOF
# ----- Component B: Mathematical Neural Network Core Layer -----
cat > thorn_engine/core.py << 'EOF'
import numpy as np
class AutonomousTransformerBlock:
""" Tracks vector weights and backprop matrices locally inside core memory. """
def __init__(self, d_model, num_heads):
self.d_model = d_model
self.num_heads = num_heads
assert d_model % num_heads == 0, "Dimensions must scale cleanly into the head counts."
self.d_k = d_model // num_heads
self.W_q = np.random.randn(d_model, d_model) * np.sqrt(2.0 / d_model)
self.W_k = np.random.randn(d_model, d_model) * np.sqrt(2.0 / d_model)
self.W_v = np.random.randn(d_model, d_model) * np.sqrt(2.0 / d_model)
self.W_o = np.random.randn(d_model, d_model) * np.sqrt(2.0 / d_model)
d_ff = 4 * d_model
self.W_ff1 = np.random.randn(d_model, d_ff) * np.sqrt(2.0 / d_model)
self.b_ff1 = np.zeros((1, d_ff))
self.W_ff2 = np.random.randn(d_ff, d_model) * np.sqrt(2.0 / d_ff)
self.b_ff2 = np.zeros((1, d_model))
def _stable_softmax(self, x):
exp_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
return exp_x / np.sum(exp_x, axis=-1, keepdims=True)
def _split_heads(self, tensor, batch, seq):
return tensor.reshape(batch, seq, self.num_heads, self.d_k).transpose(0, 2, 1, 3)
def _merge_heads(self, tensor, batch, seq):
return tensor.transpose(0, 2, 1, 3).reshape(batch, seq, self.d_model)
def forward(self, X):
self.X = X
batch, seq, _ = X.shape
self.Q_all = X @ self.W_q
self.K_all = X @ self.W_k
self.V_all = X @ self.W_v
Q = self._split_heads(self.Q_all, batch, seq)
K = self._split_heads(self.K_all, batch, seq)
V = self._split_heads(self.V_all, batch, seq)
self.scores = np.matmul(Q, K.transpose(0, 1, 3, 2)) / np.sqrt(self.d_k)
self.attention_weights = self._stable_softmax(self.scores)
self.head_out = np.matmul(self.attention_weights, V)
self.concatenated_heads = self._merge_heads(self.head_out, batch, seq)
self.attn_out = self.concatenated_heads @ self.W_o
self.x_residual_1 = self.attn_out + X
self.ffn1_in = self.x_residual_1 @ self.W_ff1 + self.b_ff1
self.ffn1_out = np.maximum(0, self.ffn1_in)
self.ffn2_out = self.ffn1_out @ self.W_ff2 + self.b_ff2
return self.ffn2_out + self.x_residual_1
def backward(self, d_out, lr=0.01):
batch, seq, _ = d_out.shape
dW_ff2 = (self.ffn1_out.reshape(-1, 4 * self.d_model).T @ d_out.reshape(-1, self.d_model))
db_ff2 = np.sum(d_out, axis=(0, 1), keepdims=True)
d_ffn1_out = d_out @ self.W_ff2.T
d_ffn1_in = d_ffn1_out * (self.ffn1_in > 0)
dW_ff1 = (self.x_residual_1.reshape(-1, self.d_model).T @ d_ffn1_in.reshape(-1, 4 * self.d_model))
db_ff1 = np.sum(d_ffn1_in, axis=(0, 1), keepdims=True)
d_res = d_ffn1_in @ self.W_ff1.T + d_out
d_concat = d_res @ self.W_o.T
dW_o = (self.concatenated_heads.reshape(-1, self.d_model).T @ d_res.reshape(-1, self.d_model))
d_head = d_concat.reshape(batch, seq, self.num_heads, self.d_k).transpose(0, 2, 1, 3)
dV = np.matmul(self.attention_weights.transpose(0, 1, 3, 2), d_head)
d_attn = np.matmul(d_head, self.V.transpose(0, 1, 3, 2))
d_scores = self.attention_weights * (d_attn - np.sum(d_attn * self.attention_weights, axis=-1, keepdims=True))
d_scores /= np.sqrt(self.d_k)
dQ = np.matmul(d_scores, self.K)
dK = np.matmul(d_scores.transpose(0, 1, 3, 2), self.Q)
dQ_all = dQ.transpose(0, 2, 1, 3).reshape(batch, seq, self.d_model)
dK_all = dK.transpose(0, 2, 1, 3).reshape(batch, seq, self.d_model)
dV_all = dV.transpose(0, 2, 1, 3).reshape(batch, seq, self.d_model)
dW_q = self.X.reshape(-1, self.d_model).T @ dQ_all.reshape(-1, self.d_model)
dW_k = self.X.reshape(-1, self.d_model).T @ dK_all.reshape(-1, self.d_model)
dW_v = self.X.reshape(-1, self.d_model).T @ dV_all.reshape(-1, self.d_model)
self.W_q -= lr * dW_q
self.W_k -= lr * dW_k
self.W_v -= lr * dW_v
self.W_o -= lr * dW_o
self.W_ff1 -= lr * dW_ff1
self.W_ff2 -= lr * dW_ff2
self.b_ff1 -= lr * db_ff1.reshape(self.b_ff1.shape)
self.b_ff2 -= lr * db_ff2.reshape(self.b_ff2.shape)
EOF
# ----- Component C: Secure Offline String Tokenizer -----
cat > thorn_engine/tokenizer.py << 'EOF'
import json
from pathlib import Path
class IsolatedVocabularyTokenizer:
def __init__(self, vocab=None, unknown_token="<UNK>"):
self.unknown_token = unknown_token
self.vocab = vocab or {unknown_token: 0}
self.inverse_vocab = {v: k for k, v in self.vocab.items()}
self.next_id = len(self.vocab)
def encode(self, text):
words = text.lower().replace('.', ' .').replace(',', ' ,').split()
return [self.vocab.get(w, self.vocab[self.unknown_token]) for w in words]
def decode(self, ids):
return " ".join(self.inverse_vocab.get(i, self.unknown_token) for i in ids)
def add_word(self, word):
if word not in self.vocab:
self.vocab[word] = self.next_id
self.inverse_vocab[self.next_id] = word
self.next_id += 1
return self.vocab[word]
def save(self, path):
with open(path, "w") as f:
json.dump(self.vocab, f)
@classmethod
def load(cls, path):
with open(path, "r") as f:
return cls(json.load(f))
EOF
# ----- Component D: Multimodal Output Generation Modules -----
cat > thorn_engine/multimodal.py << 'EOF'
import numpy as np
class ImageGenerationModule:
def __init__(self, d_model):
self.d_model = d_model
self.render_matrix = np.random.randn(d_model, 256) * 0.01
def generate(self, latent_vectors, resolution=(16, 16, 3)):
flat_size = resolution[0] * resolution[1] * resolution[2]
projection = np.random.randn(latent_vectors.shape[1], flat_size) * 0.01
raw_signal = latent_vectors[0] @ projection
normalized = (raw_signal - np.min(raw_signal)) / (np.max(raw_signal) - np.min(raw_signal) + 1e-8)
pixel_array = (normalized * 255).astype(np.uint8)
return pixel_array.reshape(resolution)
class VideoGenerationModule:
def __init__(self, d_model):
self.d_model = d_model
self.image_mod = ImageGenerationModule(d_model)
def generate_frames(self, latent_vectors, num_frames=8, resolution=(16, 16, 3)):
video = []
for i in range(num_frames):
frame_latent = latent_vectors + (np.sin(i) * 0.05)
frame = self.image_mod.generate(frame_latent, resolution)
video.append(frame)
return np.stack(video, axis=0)
class AudioGenerationModule:
def __init__(self, d_model):
self.d_model = d_model
def generate_signal(self, latent_vectors, duration_samples=8000):
projection = np.random.randn(latent_vectors.shape[1], duration_samples) * 0.01
raw_audio = latent_vectors[0] @ projection
normalized = 2.0 * (raw_audio - np.min(raw_audio)) / (np.max(raw_audio) - np.min(raw_audio) + 1e-8) - 1.0
return normalized.flatten()
EOF
# ----- Component E: Native Window GUI Framework Application -----
cat > thorn_engine/gui.py << 'EOF'
import sys
import os
import numpy as np
from tkinter import Tk, Frame, Label, Button, Text, Entry, Scrollbar, StringVar, TOP, BOTTOM, LEFT, RIGHT, BOTH, X, Y, END, INSERT
from .core import AutonomousTransformerBlock
from .tokenizer import IsolatedVocabularyTokenizer
from .multimodal import ImageGenerationModule, VideoGenerationModule, AudioGenerationModule
class ThornMasterGUI:
def __init__(self, root):
self.root = root
self.root.title("Thorn Core GUI Engine")
self.root.geometry("900x600")
self.d_model = 64
self.num_heads = 4
self.vocab = {"<UNK>":0, ".":1, ",":2, "the":3, "system":4, "generate":5, "matrix":6}
self.tokenizer = IsolatedVocabularyTokenizer(self.vocab)
self.model = AutonomousTransformerBlock(self.d_model, self.num_heads)
self.embeddings = np.random.randn(len(self.vocab), self.d_model) * 0.01
self.image_module = ImageGenerationModule(self.d_model)
self.video_module = VideoGenerationModule(self.d_model)
self.audio_module = AudioGenerationModule(self.d_model)
self._init_interface()
def _init_interface(self):
top_frame = Frame(self.root)
top_frame.pack(side=TOP, fill=X, padx=10, pady=5)
Label(top_frame, text="Command Input String:").pack(side=LEFT, padx=5)
self.input_var = StringVar()
self.entry = Entry(top_frame, textvariable=self.input_var, width=50)
self.entry.pack(side=LEFT, fill=X, expand=True, padx=5)
Button(top_frame, text="Execute Base Inference", command=self.run_inference).pack(side=LEFT, padx=5)
ctrl_frame = Frame(self.root)
ctrl_frame.pack(side=TOP, fill=X, padx=10, pady=5)
Button(ctrl_frame, text="Trigger Image Module", command=self.trigger_image).pack(side=LEFT, padx=5, expand=True, fill=X)
Button(ctrl_frame, text="Trigger Video Module", command=self.trigger_video).pack(side=LEFT, padx=5, expand=True, fill=X)
Button(ctrl_frame, text="Trigger Audio Module", command=self.trigger_audio).pack(side=LEFT, padx=5, expand=True, fill=X)
display_frame = Frame(self.root)
display_frame.pack(side=BOTTOM, fill=BOTH, expand=True, padx=10, pady=10)
scrollbar = Scrollbar(display_frame)
scrollbar.pack(side=RIGHT, fill=Y)
self.console = Text(display_frame, yscrollcommand=scrollbar.set, bg="#111111", fg="#00FF00", font=("Courier", 10))
self.console.pack(side=LEFT, fill=BOTH, expand=True)
scrollbar.config(command=self.console.yview)
def log_message(self, message):
self.console.insert(END, message + "\n")
self.console.see(END)
def get_latent_array(self):
text = self.input_var.get().strip()
if not text:
text = "system matrix generation"
tokens = self.tokenizer.encode(text)
if not tokens:
tokens = [0]
vec = self.embeddings[tokens]
X = vec.reshape(1, len(tokens), self.d_model)
return self.model.forward(X)
def run_inference(self):
latent = self.get_latent_array()
self.log_message(f"[LLM CORE] Forward computation evaluated matrix shape: {latent.shape}")
def trigger_image(self):
latent = self.get_latent_array()
img = self.image_module.generate(latent)
self.log_message(f"[IMAGE MODULE] Frame synthesis completed. Shape: {img.shape}. RGB range: [{np.min(img)}, {np.max(img)}]")
def trigger_video(self):
latent = self.get_latent_array()
video = self.video_module.generate_frames(latent, num_frames=10)
self.log_message(f"[VIDEO MODULE] Sequential rendering complete. Batch shape: {video.shape}. Frames locked inside host memory maps.")
def trigger_audio(self):
latent = self.get_latent_array()
audio = self.audio_module.generate_signal(latent)
self.log_message(f"[AUDIO MODULE] Signal compilation active. Samples generated: {len(audio)}. Peak amplitude frequency value: {np.max(np.abs(audio)):.4f}")
def main():
root = Tk()
app = ThornMasterGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
EOF
# ----- Component F: Execution Hub Mapping -----
cat > thorn_engine/__main__.py << 'EOF'
from .gui import main
if __name__ == "__main__":
main()
EOF
# ----- Setuptools Build Mapping Block -----
cat > setup.py << 'EOF'
from setuptools import setup, find_packages
setup(
name="thorn-engine-gui",
version="1.0.0",
packages=find_packages(),
install_requires=["numpy"],
entry_points={"gui_scripts": ["thorn_gui = thorn_engine.gui:main"]},
)
EOF
echo "numpy" > requirements.txt
# -------------------------------------------------------------------------
# 5. Compiled Executable Compression Processing via PyInstaller
# -------------------------------------------------------------------------
echo -e "${YELLOW}[5/8] Packaging system scripts into compiled windowed binaries...${NC}"
pyinstaller --onefile --windowed --name thorn_gui --add-data "thorn_engine:thorn_engine" thorn_engine/__main__.py --distpath "$INSTALLER_DIR" --workpath /tmp/build --specpath /tmp/spec
# -------------------------------------------------------------------------
# 6. Debian Deployment Package Core Mapping (.deb Configuration)
# -------------------------------------------------------------------------
echo -e "${YELLOW}[6/8] Compiling native Debian package architectures...${NC}"
DEB_ROOT="$PROJECT_DIR/deb_package"
mkdir -p "$DEB_ROOT/usr/local/bin"
mkdir -p "$DEB_ROOT/DEBIAN"
cp "$INSTALLER_DIR/thorn_gui" "$DEB_ROOT/usr/local/bin/thorn_gui"
cat > "$DEB_ROOT/DEBIAN/control" << EOF
Package: thorn-engine-gui
Version: 1.0.0
Section: utils
Priority: optional
Architecture: amd64
Maintainer: Thorn <build@local>
Description: Thorn Core LLM Engine - GUI & Multimodal
A standalone transformer engine with a local Tkinter GUI, plus text, image, video, and audio synthesis pipelines.
Bypasses browser tracking entirely.
EOF
cat > "$DEB_ROOT/DEBIAN/postinst" << 'EOF'
#!/bin/sh
set -e
chmod +x /usr/local/bin/thorn_gui
echo "[SUCCESS] Thorn Engine GUI deployed to local system space. Execute 'thorn_gui' to operate window."
EOF
chmod 755 "$DEB_ROOT/DEBIAN/postinst"
dpkg-deb --build "$DEB_ROOT" "$INSTALLER_DIR/thorn-engine-gui_1.0.0_amd64.deb"
# -------------------------------------------------------------------------
# 7. Cross-Platform Source Distribution Packager
# -------------------------------------------------------------------------
echo -e "${YELLOW}[7/8] Generating source code target distribution tarball archives...${NC}"
tar -czf "$INSTALLER_DIR/thorn-engine-gui-source.tar.gz" \
--exclude='venv' --exclude='__pycache__' --exclude='*.pyc' \
--exclude='deb_package' --exclude='installer_output' --exclude='build' \
. 2>/dev/null || true
cat > "$PROJECT_DIR/build_other_platforms.sh" << 'EOF'
#!/bin/bash
echo "Building local execution blocks for this system's host window maps..."
python3 -m venv venv
source venv/bin/activate
pip install numpy pyinstaller
pyinstaller --onefile --windowed --name thorn_gui --add-data "thorn_engine:thorn_engine" thorn_engine/__main__.py
echo "[COMPLETE] Native standalone execution binary generated in folder: dist/thorn_gui"
EOF
chmod +x "$PROJECT_DIR/build_other_platforms.sh"
tar -rf "$INSTALLER_DIR/thorn-engine-gui-source.tar.gz" build_other_platforms.sh 2>/dev/null
gzip -f "$INSTALLER_DIR/thorn-engine-gui-source.tar.gz" 2>/dev/null || true
mv "$INSTALLER_DIR/thorn-engine-gui-source.tar.gz.gz" "$INSTALLER_DIR/thorn-engine-gui-source.tar.gz" 2>/dev/null || true
# -------------------------------------------------------------------------
# 8. Execution Validation Summaries
# -------------------------------------------------------------------------
echo -e "${GREEN}[8/8] Build actions finalized successfully.${NC}"
echo -e "${GREEN}================================================================${NC}"
echo -e "Production installation assets committed directly to output folder: ${YELLOW}$INSTALLER_DIR${NC}"
echo -e ""
echo -e " ${GREEN}► Linux Standalone GUI Window Binary:${NC} $INSTALLER_DIR/thorn_gui"
echo -e " ${GREEN}► Managed Debian Package Installer Block (.deb):${NC} $INSTALLER_DIR/thorn-engine-gui_1.0.0_amd64.deb"
echo -e " ${GREEN}► Cross-Platform Source Archive (.tar.gz):${NC} $INSTALLER_DIR/thorn-engine-gui-source.tar.gz"
echo -e ""
echo -e "To integrate directly into your local machine kernel runtime profile paths:"
echo -e " ${YELLOW}sudo dpkg -i $INSTALLER_DIR/thorn-engine-gui_1.0.0_amd64.deb${NC}"
echo -e " Then run inside any shell session: ${YELLOW}thorn_gui${NC}"
echo -e ""
echo -e "To evaluate execution vectors instantly without package layer registration:"
echo -e " ${YELLOW}$INSTALLER_DIR/thorn_gui${NC}"
echo -e "================================================================${NC}"
deactivate 2>/dev/null || true