key-data / models /tests /deep_dive_hold_async.py
tostido's picture
Upload folder using huggingface_hub
a80c9f6 verified
"""
Deep Dive: HOLD System with Async Override
Testing the full HOLD flow:
1. Brain yields a hold point (blocking)
2. Human/chat overrides before timeout
3. See how the override propagates through
This is how Twitch chat can control AI decisions in real-time!
"""
import numpy as np
import threading
import time
from cascade import Hold, HoldResolution
print("=" * 60)
print("⏸️ CASCADE HOLD - Async Override Demo")
print("=" * 60)
# Get the singleton
hold = Hold()
# Track what happened
events = []
def listener(hp):
"""Called when a hold point is created"""
events.append(f"[LISTENER] Hold point created: brain={hp.brain_id}")
print(f"\n🔴 HOLD POINT: {hp.brain_id}")
print(f" Action probs: {hp.action_probs}")
print(f" Labels: {hp.action_labels}")
print(f" Value estimate: {hp.value:.3f}")
# Show what AI wants to do
ai_choice = np.argmax(hp.action_probs)
print(f" AI wants: {ai_choice} ({hp.action_labels[ai_choice] if hp.action_labels else '?'})")
hold.register_listener(listener)
def brain_thread():
"""Simulates the AI brain yielding a hold point and waiting"""
events.append("[BRAIN] Starting inference...")
print("\n🧠 Brain: Starting inference...")
# Fake observations
observation = {
"health": 0.3, # Low health!
"enemies": 2,
"ammo": 5
}
# AI thinks: "Low health, should retreat!"
# But maybe human knows better...
action_probs = np.array([0.05, 0.85, 0.05, 0.05]) # RETREAT strongly preferred
value = -0.3 # AI thinks situation is bad
events.append("[BRAIN] Yielding hold point (blocking)...")
print("🧠 Brain: Yielding hold point, waiting for resolution...")
# This blocks until resolved!
resolution = hold.yield_point(
action_probs=action_probs,
value=value,
observation=observation,
brain_id="arcade_brain_007",
action_labels=["ATTACK", "RETREAT", "HEAL", "DODGE"],
blocking=True # BLOCKING - will wait
)
events.append(f"[BRAIN] Resolution received: action={resolution.action}")
print(f"\n🧠 Brain: Got resolution!")
print(f" Final action: {resolution.action} ({['ATTACK', 'RETREAT', 'HEAL', 'DODGE'][resolution.action]})")
print(f" Was override: {resolution.was_override}")
if resolution.was_override:
print(f" Override from: {resolution.override_source}")
print(f" Hold duration: {resolution.hold_duration:.3f}s")
print(f" Merkle: {resolution.merkle_root}")
return resolution
def human_thread():
"""Simulates human (Twitch chat) overriding the decision"""
time.sleep(0.5) # Wait for hold point to be created
events.append("[HUMAN] Deciding to override...")
print("\n👤 Human: AI wants to RETREAT but I see an opportunity!")
print("👤 Human: Overriding to ATTACK!")
# Human overrides: "No, attack! I see a power-up!"
hold.override(0, source="twitch_chat:xX_ProGamer_Xx")
events.append("[HUMAN] Override injected: ATTACK")
print("👤 Human: Override injected!")
print("\n=== Starting Async Hold Test ===")
print("Brain will want to RETREAT (low health)")
print("Human will override to ATTACK")
print("-" * 40)
# Start brain in a thread
brain = threading.Thread(target=brain_thread)
brain.start()
# Start human in another thread (with delay)
human = threading.Thread(target=human_thread)
human.start()
# Wait for both
brain.join()
human.join()
print("\n=== Event Log ===")
for i, event in enumerate(events, 1):
print(f" {i}. {event}")
print("\n=== Final Stats ===")
stats = hold.stats # Property not method!
print(f" Total holds: {stats['total_holds']}")
print(f" Overrides: {stats['overrides']}")
print(f" Override rate: {stats['override_rate']:.1%}")
print(f" Last merkle: {stats['last_merkle']}")