neuralworm commited on
Commit
1d1182e
·
verified ·
1 Parent(s): 76e7238

Create apy.py

Browse files
Files changed (1) hide show
  1. apy.py +82 -0
apy.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer
3
+ from sklearn.metrics.pairwise import cosine_similarity
4
+ import numpy as np
5
+ import gradio as gr
6
+
7
+ # Load GPT-2 and tokenizer
8
+ model_name = "gpt2"
9
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name)
10
+ model = GPT2LMHeadModel.from_pretrained(model_name)
11
+ model.eval()
12
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
13
+ model.to(device)
14
+
15
+ # Function to generate response
16
+ def generate_response(prompt, max_length=100):
17
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
18
+ outputs = model.generate(
19
+ **inputs,
20
+ max_length=len(inputs["input_ids"][0]) + max_length,
21
+ pad_token_id=tokenizer.eos_token_id,
22
+ do_sample=True,
23
+ temperature=0.9,
24
+ top_p=0.95,
25
+ )
26
+ return tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
27
+
28
+ # Semantic similarity via mean embeddings (ΔS approximation)
29
+ def similarity(a, b):
30
+ tok_a = tokenizer(a, return_tensors="pt").to(device)
31
+ tok_b = tokenizer(b, return_tensors="pt").to(device)
32
+ with torch.no_grad():
33
+ emb_a = model.transformer.wte(tok_a.input_ids).mean(dim=1)
34
+ emb_b = model.transformer.wte(tok_b.input_ids).mean(dim=1)
35
+ return float(cosine_similarity(emb_a.cpu().numpy(), emb_b.cpu().numpy())[0][0])
36
+
37
+ # Recursive identity loop (EAL-style unfolding)
38
+ def identity_unfolding(steps):
39
+ unfolding = []
40
+ ΔS_trace = []
41
+
42
+ current_text = "The following is a system thinking about itself:\n"
43
+
44
+ for step in range(steps):
45
+ response = generate_response(current_text)
46
+ unfolding.append(response)
47
+
48
+ if step > 0:
49
+ ΔS = similarity(unfolding[step - 1], unfolding[step])
50
+ ΔS_trace.append(round(ΔS, 4))
51
+
52
+ current_text = (
53
+ f'The system has previously stated:\n"{response}"\n'
54
+ "Now it continues thinking about what that implies:\n"
55
+ )
56
+
57
+ results = "\n\n---\n\n".join(
58
+ [f"Step {i}: {txt}" for i, txt in enumerate(unfolding)]
59
+ )
60
+ sim = "\n".join(
61
+ [f"ΔS({i} → {i+1}) = {val}" for i, val in enumerate(ΔS_trace)]
62
+ )
63
+ return results, sim
64
+
65
+ # Gradio Interface
66
+ iface = gr.Interface(
67
+ fn=identity_unfolding,
68
+ inputs=gr.Slider(2, 10, value=5, step=1, label="Number of Iterations"),
69
+ outputs=[
70
+ gr.Textbox(label="GPT-2 Identity Trace", lines=20),
71
+ gr.Textbox(label="Semantic ΔS Trace", lines=10),
72
+ ],
73
+ title="EAL Identity Tester for GPT-2",
74
+ description=(
75
+ "This app recursively prompts GPT-2 to reflect on its own output. "
76
+ "It shows how close each iteration is to the previous one using a cosine-based ΔS metric. "
77
+ "Use this to test if GPT-2 stabilizes around a semantically coherent self-representation."
78
+ ),
79
+ )
80
+
81
+ if __name__ == "__main__":
82
+ iface.launch()