Repository navigation
Expand file tree
/
Copy pathrun_lab.py
More file actions
executable file
·272 lines (235 loc) · 10.1 KB
/
Copy pathrun_lab.py
File metadata and controls
executable file
·272 lines (235 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/env choices
import os
import argparse
import json
import time
from datetime import datetime
import numpy as np
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
from app.engine import LatentEngine
from app.metrics import (
calculate_entropy,
extract_top_k,
calculate_cosine_similarity,
analyze_attention_distribution
)
from app.cognitive import compute_cognitive_profile
from app.projections import LatentProjector
# Colors for terminal styling
class Colors:
HEADER = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
CYAN = '\033[96m'
def make_progress_bar(val: float, max_val: float = 8.0, length: int = 10) -> str:
"""Generates a text-based progress bar representing a metric level (e.g. Entropy)."""
normalized = min(max(val / max_val, 0.0), 1.0)
filled_len = int(round(length * normalized))
bar = '█' * filled_len + '░' * (length - filled_len)
return bar
def main():
parser = argparse.ArgumentParser(description="LatentLab: LLM Observability Microscope")
parser.add_argument(
"--prompt",
type=str,
default=os.getenv("DEFAULT_PROMPT", "Explain the concept of Artificial Intelligence in a simple way."),
help="Prompt to send to the LLM"
)
parser.add_argument(
"--model",
type=str,
default=os.getenv("MODEL_NAME", "Qwen/Qwen2.5-0.5B-Instruct"),
help="HuggingFace model identifier"
)
parser.add_argument(
"--max_tokens",
type=int,
default=int(os.getenv("MAX_TOKENS", "60")),
help="Maximum tokens to generate"
)
parser.add_argument(
"--temp",
type=float,
default=float(os.getenv("TEMPERATURE", "0.7")),
help="Generation temperature"
)
parser.add_argument(
"--top_k",
type=int,
default=int(os.getenv("TOP_K", "50")),
help="Top-K token sampling filtering"
)
args = parser.parse_args()
# Title Banner
print("\n" + "="*80)
print(f"{Colors.HEADER}{Colors.BOLD}🔍 LATENTLAB: LLM COGNITIVE OBSERVABILITY SCOPE{Colors.ENDC}")
print("="*80)
print(f"{Colors.BOLD}Model:{Colors.ENDC} {args.model}")
print(f"{Colors.BOLD}Prompt:{Colors.ENDC} '{args.prompt}'")
print(f"{Colors.BOLD}Config:{Colors.ENDC} Max Tokens={args.max_tokens}, Temp={args.temp}, Top-K={args.top_k}")
print("="*80 + "\n")
# Ensure storage folder exists
os.makedirs("storage", exist_ok=True)
# Initialize Engine
engine = LatentEngine(model_name=args.model)
# Store token-by-token logs
steps_log = []
hidden_states_history = []
# Variables to calculate sliding cosine distance (surprise)
previous_hidden = None
previous_embedding = None
full_generated_text = ""
start_time = time.time()
try:
# Run autoregressive stream
generation_stream = engine.generate_with_observability(
prompt=args.prompt,
max_new_tokens=args.max_tokens,
temperature=args.temp,
top_k=args.top_k
)
print(f"\n{Colors.CYAN}{Colors.BOLD}--- GENERATION STEPS & COGNITIVE STATE PROFILE ---{Colors.ENDC}")
header_line = f"{'Step':<5} | {'Token':<12} | {'Entropy':<7} | {'Confid':<6} | {'Doubt':<5} | {'Surp':<5} | {'Curios':<6} | {'Top Alternative Candidates':<40}"
print(header_line)
print("-" * len(header_line))
for data in generation_stream:
step = data["step"]
token_str = data["token_str"]
probs = data["probabilities"]
hidden = data["last_hidden_state"]
embedding = data["embedding_state"]
hidden_states_history.append(hidden)
seq_len = data["sequence_len"]
prompt_len = data["prompt_len"]
raw_attns = data["raw_attentions"]
# Clean control character representation for display
clean_token_disp = token_str.replace("\n", "\\n").replace("\t", "\\t")
if len(clean_token_disp) > 10:
clean_token_disp = clean_token_disp[:9] + "…"
# 1. Calculate entropy (uncertainty)
ent_val = calculate_entropy(probs)
# 2. Calculate surprise (1.0 - Cosine Similarity of hidden state)
surprise_val = 0.0
if previous_hidden is not None:
sim = calculate_cosine_similarity(hidden, previous_hidden)
surprise_val = max(0.0, 1.0 - sim)
# 3. Calculate embedding drift (1.0 - Cosine Similarity of token embeddings)
emb_drift_val = 0.0
if previous_embedding is not None:
emb_sim = calculate_cosine_similarity(embedding, previous_embedding)
emb_drift_val = max(0.0, 1.0 - emb_sim)
# 4. Extract top 3 candidates
top_candidates = extract_top_k(probs, engine.tokenizer, k=3)
candidates_list = []
for c in top_candidates:
clean_cand = c['token_str'].replace('\n', '\\n').replace('\t', '\\t')
candidates_list.append(f"'{clean_cand}' ({c['probability']*100:.1f}%)")
candidates_str = ", ".join(candidates_list)
# 5. Process attention
attn_data = analyze_attention_distribution(raw_attns, seq_len, prompt_len)
# 6. Compute compound cognitive profile
cog_profile = compute_cognitive_profile(
entropy=ent_val,
surprise=surprise_val,
embedding_drift=emb_drift_val,
attention_entropy=attn_data["attention_entropy"],
sequence_len=seq_len,
top_candidates=top_candidates
)
# Save stats for the time-series JSON
step_stats = {
"step": step,
"token_id": data["token_id"],
"token_str": token_str,
"entropy": ent_val,
"surprise": surprise_val,
"embedding_drift": emb_drift_val,
"attention_entropy": attn_data["attention_entropy"],
"prompt_attention_sum": attn_data["prompt_attention_sum"],
"generation_attention_sum": attn_data["generation_attention_sum"],
"cognitive_state": {
"confidence": cog_profile["confidence"],
"doubt": cog_profile["doubt"],
"surprise": cog_profile["surprise"],
"curiosity": cog_profile["curiosity"]
},
"top_candidates": [
{"token_str": c["token_str"], "probability": c["probability"]}
for c in top_candidates
]
}
steps_log.append(step_stats)
# Color-coding based on cognitive indices
doubt_color = Colors.WARNING if cog_profile["doubt"] > 0.5 else Colors.GREEN
surprise_color = Colors.FAIL if cog_profile["surprise"] > 0.4 else Colors.BLUE
print(
f"{step:<5} | "
f"{Colors.BOLD}'{clean_token_disp}'{Colors.ENDC:<12} | "
f"{ent_val:7.2f} | "
f"{cog_profile['confidence']:6.2f} | "
f"{doubt_color}{cog_profile['doubt']:5.2f}{Colors.ENDC} | "
f"{surprise_color}{cog_profile['surprise']:5.2f}{Colors.ENDC} | "
f"{cog_profile['curiosity']:6.2f} | "
f"{candidates_str:<40}"
)
# Append token to accumulated generation string
full_generated_text += token_str
# Shift state references
previous_hidden = hidden
previous_embedding = embedding
except KeyboardInterrupt:
print(f"\n{Colors.WARNING}Generation interrupted by user.{Colors.ENDC}")
except Exception as e:
print(f"\n{Colors.FAIL}Error running inference: {e}{Colors.ENDC}")
raise e
elapsed_time = time.time() - start_time
tokens_generated = len(steps_log)
speed = tokens_generated / elapsed_time if elapsed_time > 0 else 0
# Apply dimensionality reduction to hidden states history
if len(hidden_states_history) > 0:
try:
projector = LatentProjector(hidden_states_history)
coords_2d = projector.project_2d()
coords_3d = projector.project_3d()
for i, step_stats in enumerate(steps_log):
step_stats["projection_2d"] = coords_2d[i].tolist()
step_stats["projection_3d"] = coords_3d[i].tolist()
except Exception as e:
print(f"\n{Colors.WARNING}Warning: Failed to calculate dimensional projections: {e}{Colors.ENDC}")
# Printing summary and full text generated
print("\n" + "="*80)
print(f"{Colors.GREEN}{Colors.BOLD}📄 FULL GENERATED TEXT:{Colors.ENDC}")
print(full_generated_text)
print("="*80)
print(f"\n{Colors.BOLD}Analysis Statistics:{Colors.ENDC}")
print(f"- Tokens generated: {tokens_generated}")
print(f"- Total time: {elapsed_time:.2f} seconds")
print(f"- Generation Speed: {speed:.1f} tokens/second")
# Save session data to JSON
session_data = {
"metadata": {
"model": args.model,
"prompt": args.prompt,
"max_tokens": args.max_tokens,
"temperature": args.temp,
"top_k": args.top_k,
"timestamp": datetime.now().isoformat(),
"elapsed_seconds": elapsed_time,
"tokens_generated": tokens_generated,
"speed_tps": speed
},
"full_text": full_generated_text,
"steps": steps_log
}
filename = f"storage/session_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(filename, "w", encoding="utf-8") as f:
json.dump(session_data, f, indent=2, ensure_ascii=False)
print(f"\n{Colors.GREEN}{Colors.BOLD}✅ Session results successfully saved to:{Colors.ENDC} {filename}\n")
if __name__ == "__main__":
main()