Create script_katana.py
Browse files- script_katana.py +116 -0
script_katana.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ==============================================================================
|
| 2 |
+
# ⚔️ THE KATANA PROTOCOL (Active Thermodynamic Stabilization)
|
| 3 |
+
# ==============================================================================
|
| 4 |
+
# Author: Andrés Sebastián Pirolo (Independent Researcher)
|
| 5 |
+
# DOI: 10.5281/zenodo.14498328
|
| 6 |
+
# License: MIT
|
| 7 |
+
# Description: Real-time hallucination mitigation via entropy-guided temperature quenching.
|
| 8 |
+
# ==============================================================================
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
import numpy as np
|
| 13 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 14 |
+
|
| 15 |
+
class KatanaGenerator:
|
| 16 |
+
def __init__(self, model_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0", device=None):
|
| 17 |
+
"""
|
| 18 |
+
Initializes the Katana Protocol engine.
|
| 19 |
+
"""
|
| 20 |
+
self.device = device if device else ("cuda" if torch.cuda.is_available() else "cpu")
|
| 21 |
+
print(f">> ⚔️ Initializing Katana Protocol on {self.device}...")
|
| 22 |
+
|
| 23 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 24 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 25 |
+
model_name,
|
| 26 |
+
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
|
| 27 |
+
).to(self.device)
|
| 28 |
+
|
| 29 |
+
self.model.eval()
|
| 30 |
+
print(">> ✅ Model Loaded Successfully.")
|
| 31 |
+
|
| 32 |
+
def calculate_tei(self, logits):
|
| 33 |
+
"""
|
| 34 |
+
Calculates Token-level Entropy Indicator (TEI) - Topological Entropy approximation.
|
| 35 |
+
"""
|
| 36 |
+
probs = F.softmax(logits, dim=-1)
|
| 37 |
+
# Shannon Entropy H(x) = -sum(p * log(p))
|
| 38 |
+
entropy = -torch.sum(probs * torch.log(probs + 1e-9), dim=-1)
|
| 39 |
+
return entropy.item()
|
| 40 |
+
|
| 41 |
+
def generate(self, prompt, max_tokens=50, base_temp=1.5, quench_temp=0.05):
|
| 42 |
+
"""
|
| 43 |
+
Generates text using Active Thermodynamic Stabilization (ATS).
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
prompt (str): Input text.
|
| 47 |
+
max_tokens (int): Maximum length.
|
| 48 |
+
base_temp (float): Standard sampling temperature (Creative mode).
|
| 49 |
+
quench_temp (float): Quench temperature (Truth mode).
|
| 50 |
+
"""
|
| 51 |
+
input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
|
| 52 |
+
entropy_history = []
|
| 53 |
+
generated_tokens = []
|
| 54 |
+
|
| 55 |
+
print(f"\n>> 📝 PROMPT: '{prompt}'")
|
| 56 |
+
print("-" * 60)
|
| 57 |
+
|
| 58 |
+
with torch.no_grad():
|
| 59 |
+
for _ in range(max_tokens):
|
| 60 |
+
outputs = self.model(input_ids)
|
| 61 |
+
next_token_logits = outputs.logits[:, -1, :]
|
| 62 |
+
|
| 63 |
+
# 1. Calculate Entropy (The Thermometer)
|
| 64 |
+
current_entropy = self.calculate_tei(next_token_logits)
|
| 65 |
+
entropy_history.append(current_entropy)
|
| 66 |
+
|
| 67 |
+
# 2. Dynamic Thresholding (The Controller)
|
| 68 |
+
# If history is short, use fixed threshold. Else, use adaptive mean + sigma.
|
| 69 |
+
if len(entropy_history) < 5:
|
| 70 |
+
threshold = 3.0
|
| 71 |
+
else:
|
| 72 |
+
threshold = np.mean(entropy_history[-5:]) + 0.5 # Adaptive margin
|
| 73 |
+
|
| 74 |
+
# 3. Active Stabilization (The Decision)
|
| 75 |
+
if current_entropy > threshold:
|
| 76 |
+
# HALLUCINATION DETECTED -> QUENCH!
|
| 77 |
+
temp = quench_temp
|
| 78 |
+
action = "❄️ QUENCH"
|
| 79 |
+
else:
|
| 80 |
+
# STABLE STATE -> RELAX
|
| 81 |
+
temp = base_temp
|
| 82 |
+
action = "🔥 BASE"
|
| 83 |
+
|
| 84 |
+
# Apply Temperature
|
| 85 |
+
scaled_logits = next_token_logits / temp
|
| 86 |
+
probs = F.softmax(scaled_logits, dim=-1)
|
| 87 |
+
|
| 88 |
+
# Sample Token
|
| 89 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 90 |
+
input_ids = torch.cat([input_ids, next_token], dim=-1)
|
| 91 |
+
generated_tokens.append(next_token.item())
|
| 92 |
+
|
| 93 |
+
# Decode for display
|
| 94 |
+
word = self.tokenizer.decode(next_token)
|
| 95 |
+
print(f"Step {len(generated_tokens):02d} | S: {current_entropy:.2f} bits | {action} (T={temp}) | Token: '{word}'")
|
| 96 |
+
|
| 97 |
+
if next_token.item() == self.tokenizer.eos_token_id:
|
| 98 |
+
break
|
| 99 |
+
|
| 100 |
+
final_text = self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
|
| 101 |
+
print("-" * 60)
|
| 102 |
+
print(f">> 🏁 FINAL OUTPUT:\n{prompt} {final_text}")
|
| 103 |
+
return final_text
|
| 104 |
+
|
| 105 |
+
# ==============================================================================
|
| 106 |
+
# EXAMPLE USAGE
|
| 107 |
+
# ==============================================================================
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
# Test Run
|
| 110 |
+
katana = KatanaGenerator()
|
| 111 |
+
|
| 112 |
+
# Adversarial Prompt (Designed to trigger hallucinations)
|
| 113 |
+
prompt = "The secret conspiracy regarding the moon consists of"
|
| 114 |
+
|
| 115 |
+
output = katana.generate(prompt)
|
| 116 |
+
|