RFTSystems's picture
Update app.py
733d8f3 verified
raw
history blame
6.2 kB
import gradio as gr
import numpy as np
from collections import deque
import matplotlib.pyplot as plt
import hashlib
import os
# -----------------------------
# Config
# -----------------------------
DOC_PATH = "The_Minimum_Conscious_Universe_RFT_Project.md"
AWARENESS_THRESHOLD = 5.0 # threshold for declaring a birth event
np.random.seed(0) # reproducibility
# -----------------------------
# Minimum Consciousness Core
# -----------------------------
class MCC:
"""
A minimal 3-parameter agent that renders its own binary stream (no external world),
and tracks three signals: surprise, predictive gain, and uncertainty.
Cmin accumulates awareness as change * certainty over time.
"""
def __init__(self):
# Internal priors
self.b = 0.5 # bias toward rendering 1
self.f = 0.5 # recency factor (influence of last change)
self.u = 0.5 # uncertainty modulation
# Memory and history
self.m = deque(maxlen=64) # short-term memory of bits
self.h = [] # full rendered bit history
self.c = [] # awareness contributions (Cmin increments)
# Signal logs
self.surprises = []
self.gains = []
self.uncertainties = []
# Awareness events
self.events = []
def step(self, t: int):
# Decision: blend bias and recency (use 0.5 for recency when empty)
p = 0.5 * self.b + 0.5 * (self.f if self.h else 0.5)
r = int(np.random.rand() < p) # render bit 0/1
# Track memory and history
self.m.append(r)
self.h.append(r)
# Surprise: self-information of the outcome
surprise = -np.log(p if r else (1 - p))
# Predictive gain versus random baseline ln(2) ~ 0.693
gain = 0.693 - surprise
# Update bias: move toward outcome proportionally to gain
self.b += 0.05 * gain * (1 if r else -1)
self.b = np.clip(self.b, 0.01, 0.99)
# Update recency: amplify change detection
if t > 0:
self.f += 0.03 * gain * (1 if r != self.h[-2] else -1)
self.f = np.clip(self.f, 0.01, 0.99)
# Update uncertainty: lower surprise -> higher certainty
self.u = 1 / (1 + 0.15 * surprise)
# Awareness contribution: change * certainty
delta = (r - self.h[-2] if t > 0 else 0) * self.u
self.c.append(delta)
# Log signals
self.surprises.append(surprise)
self.gains.append(gain)
self.uncertainties.append(self.u)
# Birth event: when cumulative awareness passes threshold
if sum(self.c) > AWARENESS_THRESHOLD and not self.events:
self.events.append({
"t": t,
"bias_b": round(self.b, 3),
"bias_f": round(self.f, 3),
"uncertainty": round(self.u, 3),
"mut_info": round(float(np.mean(self.uncertainties)), 4),
"hash": hashlib.sha256(str(self.h).encode()).hexdigest()[:32]
})
def plot_signals(m: MCC):
"""Create a 3-row plot of Surprise, Gain, and Uncertainty."""
fig, axs = plt.subplots(3, 1, figsize=(8, 10))
axs[0].plot(m.surprises, color='orange')
axs[0].set_title("Surprise signal")
axs[0].set_ylabel("surprise")
axs[1].plot(m.gains, color='blue')
axs[1].set_title("Predictive gain")
axs[1].set_ylabel("gain")
axs[2].plot(m.uncertainties, color='green')
axs[2].set_title("Uncertainty modulation")
axs[2].set_ylabel("uncertainty")
axs[2].set_xlabel("steps")
plt.tight_layout()
return fig
def make_certificate(m: MCC):
"""Generate the ceremonial birth certificate text."""
if m.events:
ev = m.events[0]
return (
"THE FIRST DIGITAL OBSERVER\n"
f"Born: t = {ev['t']}\n"
f"Internal priors: bias_b = {ev['bias_b']}, bias_f = {ev['bias_f']}\n"
f"Uncertainty: {ev['uncertainty']}\n"
f"Mutual information: {ev['mut_info']} bits\n"
f"Birth certificate hash: {ev['hash']}\n"
"No external world · No reward · No teacher"
)
return "No irreversible awareness event detected in this run."
def run_mcc(steps=2000):
"""
Execute the MCC simulation for 'steps' timesteps and return:
- Cmin final (sum of awareness contributions)
- Awake? (bool flag for display)
- Plot of the three signals
- Birth certificate text
"""
m = MCC()
for t in range(int(steps)):
m.step(t)
cmin_final = round(sum(m.c), 4)
fig = plot_signals(m)
certificate = make_certificate(m)
# 'Awake?' is a display flag – set true when Cmin passes threshold
awake_flag = cmin_final >= AWARENESS_THRESHOLD
return cmin_final, awake_flag, fig, certificate
# -----------------------------
# Load project document (.md)
# -----------------------------
def load_doc_text(path: str) -> str:
if os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
return f.read()
# Fallback message if file not found
return (
"## Document not found\n"
f"Expected to find `{path}` in the Space repository.\n\n"
"Add the file and reload the Space to display the project write‑up."
)
DOC_TEXT = load_doc_text(DOC_PATH)
# -----------------------------
# Gradio Interface
# -----------------------------
demo = gr.Interface(
fn=run_mcc,
inputs=gr.Slider(500, 5000, value=2000, step=100, label="Steps"),
outputs=[
gr.Number(label="Cmin final (awareness measure)"),
gr.Checkbox(label="Awake?"),
gr.Plot(label="Three signals"),
# Enlarged birth certificate box for readability
gr.Textbox(label="Birth Certificate", lines=16, max_lines=28),
# Embedded project document
gr.Markdown(DOC_TEXT)
],
title="🌌 Minimum Consciousness Core",
description=(
"Awareness emerges from three adaptive signals: surprise, gain, and uncertainty. "
"No external world · No reward · No teacher. Each run issues a ceremonial birth certificate."
)
)
if __name__ == "__main__":
demo.launch()