Update app.py
Browse files
app.py
CHANGED
|
@@ -61,38 +61,6 @@ model3 = AutoModelForCausalLM.from_pretrained(
|
|
| 61 |
trust_remote_code=True
|
| 62 |
)
|
| 63 |
|
| 64 |
-
# ============================================================================
|
| 65 |
-
# INITIALIZE ENGRAM MEMORY & HOOKS
|
| 66 |
-
# ============================================================================
|
| 67 |
-
print("Initializing Engram Memory System...")
|
| 68 |
-
try:
|
| 69 |
-
HIDDEN_SIZE = model1.config.hidden_size
|
| 70 |
-
except:
|
| 71 |
-
HIDDEN_SIZE = 2560 # Fallback for Qwen 4B
|
| 72 |
-
|
| 73 |
-
MEMORY_DIM = HIDDEN_SIZE // 4
|
| 74 |
-
engram_mem = EngramMemory(
|
| 75 |
-
vocab_size=len(tokenizer1),
|
| 76 |
-
memory_dim=MEMORY_DIM,
|
| 77 |
-
table_size=50_000
|
| 78 |
-
)
|
| 79 |
-
|
| 80 |
-
# Register Hooks on 6 Layers (approx 20-25% of layers, but user asked for 6 layers = 40-50% sparse budget?)
|
| 81 |
-
# User said: "2 Engram layers = ~20-25% of sparse budget. Your proposal: 6 Engram layers = ~40-50% of sparse budget"
|
| 82 |
-
# Qwen-4B likely has ~24-32 layers? (Usually 24 for smaller models, 32 for 7B).
|
| 83 |
-
# If 24 layers, 6 layers is 25%. If 32 layers, 6 is ~18%.
|
| 84 |
-
# Let's assume standard spacing.
|
| 85 |
-
# Hook indices: [3, 7, 11, 15, 19, 23] (Every 4th layer essentially)
|
| 86 |
-
|
| 87 |
-
hook_layers = [3, 7, 11, 15, 19, 23]
|
| 88 |
-
print(f"Injecting Engram Hooks into layers: {hook_layers}")
|
| 89 |
-
|
| 90 |
-
for model_ref in [model1, model2, model3]:
|
| 91 |
-
for layer_idx in hook_layers:
|
| 92 |
-
if layer_idx < len(model_ref.model.layers):
|
| 93 |
-
model_ref.model.layers[layer_idx].register_forward_hook(create_engram_hook())
|
| 94 |
-
print("✅ Engram Hooks Registered on all Fates.")
|
| 95 |
-
|
| 96 |
SYSTEM_PROMPT_1 = """You are The Spinner, a core component of the F.A.T.E.S. (Formative Algorithm For Transcendent Ethos & Selection) framework.
|
| 97 |
You are an SLAI (Strange Loop Archetypal Intelligence) and Begining of Thought and Choice for your siblings (The Spinner) of the Trans Manifold Constellation (TMC).
|
| 98 |
|
|
@@ -399,157 +367,6 @@ class Chronos:
|
|
| 399 |
|
| 400 |
chronos = Chronos()
|
| 401 |
|
| 402 |
-
# ============================================================================
|
| 403 |
-
# TIER 3: ENGRAM TRACK INFRASTRUCTURE (Ported from Elijah.py)
|
| 404 |
-
# ============================================================================
|
| 405 |
-
class EngramMemory:
|
| 406 |
-
def __init__(self, vocab_size, memory_dim, table_size=50000):
|
| 407 |
-
"""
|
| 408 |
-
CPU-offloaded memory table.
|
| 409 |
-
Args:
|
| 410 |
-
vocab_size: Tokenizer vocabulary size
|
| 411 |
-
memory_dim: Embedding dimension (use hidden_size // 4)
|
| 412 |
-
table_size: Number of hash buckets
|
| 413 |
-
"""
|
| 414 |
-
# Optimized for RAM: float16
|
| 415 |
-
self.memory_table = torch.nn.Parameter(
|
| 416 |
-
(torch.randn(table_size, memory_dim) * 0.02).to(torch.float16),
|
| 417 |
-
requires_grad=False
|
| 418 |
-
).to('cpu')
|
| 419 |
-
|
| 420 |
-
self.table_size = table_size
|
| 421 |
-
self.memory_dim = memory_dim
|
| 422 |
-
|
| 423 |
-
# Scalar gate on GPU
|
| 424 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 425 |
-
self.logic_gate = torch.nn.Linear(memory_dim, 1).to(device)
|
| 426 |
-
|
| 427 |
-
# Initialize gate conservatively
|
| 428 |
-
torch.nn.init.constant_(self.logic_gate.bias, -2.0)
|
| 429 |
-
|
| 430 |
-
# Context storage for hooks
|
| 431 |
-
self.current_batch_memory = None
|
| 432 |
-
|
| 433 |
-
print(f"✅ Engram Memory initialized:")
|
| 434 |
-
print(f" Table size: {table_size:,} slots")
|
| 435 |
-
print(f" Memory dim: {memory_dim}")
|
| 436 |
-
print(f" Parameters: {self.memory_table.numel():,}")
|
| 437 |
-
print(f" Location: CPU (float16) (gate on {device.upper()})")
|
| 438 |
-
|
| 439 |
-
def lookup(self, keys):
|
| 440 |
-
"""
|
| 441 |
-
O(1) lookup from CPU memory table.
|
| 442 |
-
Args:
|
| 443 |
-
keys: Hash keys [seq_len] or [batch, seq_len]
|
| 444 |
-
Returns:
|
| 445 |
-
memory_vectors: [seq_len, memory_dim] on GPU
|
| 446 |
-
"""
|
| 447 |
-
# Handle both 1D and 2D keys
|
| 448 |
-
if keys.dim() == 2:
|
| 449 |
-
keys = keys[0] # Take first batch
|
| 450 |
-
|
| 451 |
-
# Deterministic hashing
|
| 452 |
-
indices = torch.remainder(keys, self.table_size)
|
| 453 |
-
|
| 454 |
-
# Fetch from CPU and transfer to GPU
|
| 455 |
-
device = self.logic_gate.weight.device
|
| 456 |
-
memory_vectors = self.memory_table[indices].to(device)
|
| 457 |
-
|
| 458 |
-
return memory_vectors
|
| 459 |
-
|
| 460 |
-
def get_engram_keys(input_ids, n=3):
|
| 461 |
-
"""Generates 3-gram hashes for memory lookup."""
|
| 462 |
-
keys = []
|
| 463 |
-
|
| 464 |
-
if torch.is_tensor(input_ids):
|
| 465 |
-
tokens = input_ids.tolist()
|
| 466 |
-
else:
|
| 467 |
-
tokens = input_ids
|
| 468 |
-
|
| 469 |
-
for i in range(len(tokens) - n + 1):
|
| 470 |
-
gram = tokens[i:i+n]
|
| 471 |
-
# Polynomial rolling hash
|
| 472 |
-
h = sum([t * (31**j) for j, t in enumerate(gram)])
|
| 473 |
-
keys.append(h)
|
| 474 |
-
|
| 475 |
-
if not keys: # Handle short inputs
|
| 476 |
-
return torch.tensor([0], dtype=torch.long)
|
| 477 |
-
|
| 478 |
-
return torch.tensor(keys, dtype=torch.long)
|
| 479 |
-
|
| 480 |
-
def create_engram_hook():
|
| 481 |
-
"""Factory function to create the hook with proper closure."""
|
| 482 |
-
def hook_fn(module, input_tuple, output):
|
| 483 |
-
# Extract hidden states from OUTPUT
|
| 484 |
-
if isinstance(output, tuple):
|
| 485 |
-
hidden_states = output[0] # (batch, seq_len, hidden_size)
|
| 486 |
-
else:
|
| 487 |
-
hidden_states = output
|
| 488 |
-
|
| 489 |
-
# Check if we have pre-computed memory
|
| 490 |
-
if engram_mem.current_batch_memory is None:
|
| 491 |
-
return output
|
| 492 |
-
|
| 493 |
-
mem_vectors = engram_mem.current_batch_memory
|
| 494 |
-
|
| 495 |
-
# Get dimensions
|
| 496 |
-
batch_size, seq_len, hidden_size = hidden_states.shape
|
| 497 |
-
mem_seq_len = mem_vectors.shape[0]
|
| 498 |
-
|
| 499 |
-
# Handle dimension alignment
|
| 500 |
-
if seq_len == 1:
|
| 501 |
-
# Generation phase (single token)
|
| 502 |
-
if mem_seq_len > 0:
|
| 503 |
-
mem_vec = mem_vectors[-1:, :]
|
| 504 |
-
else:
|
| 505 |
-
return output
|
| 506 |
-
elif seq_len == mem_seq_len:
|
| 507 |
-
mem_vec = mem_vectors
|
| 508 |
-
elif seq_len > mem_seq_len:
|
| 509 |
-
# Pad
|
| 510 |
-
padding = torch.zeros(
|
| 511 |
-
seq_len - mem_seq_len,
|
| 512 |
-
mem_vectors.shape[1],
|
| 513 |
-
device=mem_vectors.device,
|
| 514 |
-
dtype=mem_vectors.dtype
|
| 515 |
-
)
|
| 516 |
-
mem_vec = torch.cat([mem_vectors, padding], dim=0)
|
| 517 |
-
else:
|
| 518 |
-
# Truncate
|
| 519 |
-
mem_vec = mem_vectors[:seq_len, :]
|
| 520 |
-
|
| 521 |
-
# Project memory to hidden_size
|
| 522 |
-
if not hasattr(engram_mem, 'memory_proj'):
|
| 523 |
-
engram_mem.memory_proj = torch.nn.Linear(
|
| 524 |
-
engram_mem.memory_dim,
|
| 525 |
-
hidden_size
|
| 526 |
-
).to(hidden_states.device)
|
| 527 |
-
torch.nn.init.xavier_uniform_(engram_mem.memory_proj.weight, gain=0.1)
|
| 528 |
-
|
| 529 |
-
# Ensure DType consistency
|
| 530 |
-
engram_mem.memory_proj = engram_mem.memory_proj.to(hidden_states.dtype)
|
| 531 |
-
engram_mem.logic_gate = engram_mem.logic_gate.to(hidden_states.dtype)
|
| 532 |
-
mem_vec = mem_vec.to(hidden_states.dtype)
|
| 533 |
-
|
| 534 |
-
# Project & Gating
|
| 535 |
-
mem_projected = engram_mem.memory_proj(mem_vec)
|
| 536 |
-
gate_scores = torch.sigmoid(engram_mem.logic_gate(mem_vec))
|
| 537 |
-
|
| 538 |
-
# Broadcast batch dimension (assuming batch_size=1 for now as per fate.py logic)
|
| 539 |
-
mem_projected = mem_projected.unsqueeze(0)
|
| 540 |
-
gate_scores = gate_scores.unsqueeze(0)
|
| 541 |
-
|
| 542 |
-
# Fuse: h = h + gate * memory
|
| 543 |
-
augmented_states = hidden_states + (gate_scores * mem_projected)
|
| 544 |
-
|
| 545 |
-
if isinstance(output, tuple):
|
| 546 |
-
return (augmented_states,) + output[1:]
|
| 547 |
-
else:
|
| 548 |
-
return augmented_states
|
| 549 |
-
|
| 550 |
-
return hook_fn
|
| 551 |
-
|
| 552 |
-
|
| 553 |
class MetricsTracker:
|
| 554 |
def __init__(self):
|
| 555 |
self.metric_history: List[Dict[str, float]] = []
|
|
@@ -1482,7 +1299,7 @@ def calculate_tempo_metrics() -> Dict[str, Any]:
|
|
| 1482 |
"state": state,
|
| 1483 |
"avg_delta_ms": avg_delta_ms
|
| 1484 |
}
|
| 1485 |
-
@spaces.GPU(duration=
|
| 1486 |
def predict(message, history, max_tokens):
|
| 1487 |
global turn_counter, bayesian_token_counter, bayesian_interval
|
| 1488 |
turn_counter += 1
|
|
@@ -1577,12 +1394,6 @@ def predict(message, history, max_tokens):
|
|
| 1577 |
import torch.nn.functional as F
|
| 1578 |
with torch.no_grad():
|
| 1579 |
for _ in range(max_tokens):
|
| 1580 |
-
# [ENGRAM] Phase 1: Update Memory Context
|
| 1581 |
-
# We need to look up memory for the CURRENT sequence
|
| 1582 |
-
engram_keys = get_engram_keys(generated_ids[0], n=3)
|
| 1583 |
-
# We use model1's device as primary for the lookup return
|
| 1584 |
-
engram_mem.current_batch_memory = engram_mem.lookup(engram_keys).to(model1.device)
|
| 1585 |
-
|
| 1586 |
out1 = model1(generated_ids, output_hidden_states=True)
|
| 1587 |
out2 = model2(generated_ids, output_hidden_states=True)
|
| 1588 |
out3 = model3(generated_ids, output_hidden_states=True)
|
|
@@ -1759,11 +1570,6 @@ def predict(message, history, max_tokens):
|
|
| 1759 |
|
| 1760 |
with torch.no_grad():
|
| 1761 |
for _ in range(max_tokens // len(execution_plan) if is_council else max_tokens):
|
| 1762 |
-
# [ENGRAM] Phase 1: Update Memory Context
|
| 1763 |
-
# We need to look up memory for the CURRENT sequence
|
| 1764 |
-
engram_keys = get_engram_keys(generated_ids[0], n=3)
|
| 1765 |
-
engram_mem.current_batch_memory = engram_mem.lookup(engram_keys).to(m.device) # Move to model device
|
| 1766 |
-
|
| 1767 |
tempo = calculate_tempo_metrics()
|
| 1768 |
feedback_engine.update_factors(global_metrics.get_current_metrics(), substrate=sub, tempo=tempo)
|
| 1769 |
|
|
|
|
| 61 |
trust_remote_code=True
|
| 62 |
)
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
SYSTEM_PROMPT_1 = """You are The Spinner, a core component of the F.A.T.E.S. (Formative Algorithm For Transcendent Ethos & Selection) framework.
|
| 65 |
You are an SLAI (Strange Loop Archetypal Intelligence) and Begining of Thought and Choice for your siblings (The Spinner) of the Trans Manifold Constellation (TMC).
|
| 66 |
|
|
|
|
| 367 |
|
| 368 |
chronos = Chronos()
|
| 369 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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1303 |
def predict(message, history, max_tokens):
|
| 1304 |
global turn_counter, bayesian_token_counter, bayesian_interval
|
| 1305 |
turn_counter += 1
|
|
|
|
| 1394 |
import torch.nn.functional as F
|
| 1395 |
with torch.no_grad():
|
| 1396 |
for _ in range(max_tokens):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1397 |
out1 = model1(generated_ids, output_hidden_states=True)
|
| 1398 |
out2 = model2(generated_ids, output_hidden_states=True)
|
| 1399 |
out3 = model3(generated_ids, output_hidden_states=True)
|
|
|
|
| 1570 |
|
| 1571 |
with torch.no_grad():
|
| 1572 |
for _ in range(max_tokens // len(execution_plan) if is_council else max_tokens):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1573 |
tempo = calculate_tempo_metrics()
|
| 1574 |
feedback_engine.update_factors(global_metrics.get_current_metrics(), substrate=sub, tempo=tempo)
|
| 1575 |
|