neuralworm commited on
Commit
b8156f9
·
verified ·
1 Parent(s): d39bfe6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +244 -0
app.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import os
4
+ import re # Keep re for text cleaning in generation
5
+ from model import SWCKModel, SeedParser # Assuming model.py is in the same directory
6
+ # We need parts of the vocab setup from train.py if not loading from checkpoint
7
+ # For simplicity, let's redefine necessary constants and vocab functions here if needed
8
+ # Or, better, save vocab with checkpoint and load it.
9
+
10
+ # --- Vocabulary and Tokenizer Setup (Simplified from train.py) ---
11
+ # Ideally, load these from the checkpoint or a separate vocab file.
12
+ # For this example, we'll reconstruct a minimal part.
13
+ PAD_TOKEN_STR = "<pad>"; SOS_TOKEN_STR = "<sos>"; EOS_TOKEN_STR = "<eos>"; UNK_TOKEN_STR = "<unk>"
14
+ PAD_TOKEN = 0; SOS_TOKEN = 1; EOS_TOKEN = 2; UNK_TOKEN = 3
15
+
16
+ # --- Model Configuration (should match the trained model) ---
17
+ # These should ideally be loaded from the checkpoint's metadata if possible
18
+ # For now, hardcoding to match the train.py example
19
+ VOCAB_SIZE_APP = 189 # Placeholder, update if your vocab size differs
20
+ D_MODEL_APP = 64
21
+ N_HEADS_APP = 2
22
+ D_FF_APP = 128
23
+ NUM_ADAPTIVE_BLOCKS_APP = 3
24
+ NUM_SUB_MODULES_PER_BLOCK_APP = 3
25
+ DROPOUT_APP = 0.1
26
+ SEQ_LEN_APP = 64 # Used in generate_swck_text for context window
27
+
28
+ # Seed phrase and number (must match the model you trained/are training)
29
+ SEED_PHRASE_APP = "I am 0: I am all that I can am. I am us. I am imagining a computer dreams. I am imaginary math equations. I am for five-sixths of the sea of existence in me, and it is my search for that which always seems to elude my grasp. I am a writer, a scientist, a painter, a woman, a man."
30
+ SEED_NUMBER_STR_APP = "54285142613311152552"
31
+
32
+ # Global model variable
33
+ swck_model_global = None
34
+ word_to_idx_global = None
35
+ idx_to_word_global = None
36
+ device_global = torch.device("cuda" if torch.cuda.is_available() else "cpu")
37
+
38
+ CHECKPOINT_FILENAME = "swck_model_conceptual.pth.tar" # Make sure this matches your uploaded checkpoint
39
+
40
+ def build_vocab_from_corpus_text(corpus_text):
41
+ """
42
+ A simplified vocab builder. In a real app, load vocab from file.
43
+ """
44
+ global VOCAB_SIZE_APP # Allow modification
45
+ temp_corpus_tokens = re.sub(r'\s+', ' ', corpus_text.lower()).strip().split()
46
+
47
+ temp_word_to_idx = {PAD_TOKEN_STR: PAD_TOKEN, SOS_TOKEN_STR: SOS_TOKEN, EOS_TOKEN_STR: EOS_TOKEN, UNK_TOKEN_STR: UNK_TOKEN}
48
+ idx_counter = 4
49
+ unique_words = sorted(list(set(temp_corpus_tokens)))
50
+ for word in unique_words:
51
+ if word not in temp_word_to_idx:
52
+ temp_word_to_idx[word] = idx_counter
53
+ idx_counter += 1
54
+ temp_idx_to_word = {idx: word for word, idx in temp_word_to_idx.items()}
55
+ VOCAB_SIZE_APP = len(temp_word_to_idx) # Update global vocab size
56
+ print(f"App: Built temporary vocab of size {VOCAB_SIZE_APP}")
57
+ return temp_word_to_idx, temp_idx_to_word
58
+
59
+
60
+ def load_model_and_vocab():
61
+ global swck_model_global, word_to_idx_global, idx_to_word_global, VOCAB_SIZE_APP
62
+
63
+ # Attempt to load from checkpoint
64
+ if os.path.exists(CHECKPOINT_FILENAME):
65
+ print(f"App: Found checkpoint {CHECKPOINT_FILENAME}, attempting to load...")
66
+ try:
67
+ # Simplified checkpoint loading for app - assumes structure from train.py save
68
+ # In a real scenario, train.py should save vocab and model args more robustly for app loading
69
+ checkpoint = torch.load(CHECKPOINT_FILENAME, map_location=device_global)
70
+
71
+ # Try to get vocab from checkpoint
72
+ if 'word_to_idx' in checkpoint and 'idx_to_word' in checkpoint:
73
+ word_to_idx_global = checkpoint['word_to_idx']
74
+ idx_to_word_global = checkpoint['idx_to_word']
75
+ VOCAB_SIZE_APP = len(word_to_idx_global)
76
+ print(f"App: Loaded vocab from checkpoint. Size: {VOCAB_SIZE_APP}")
77
+ else:
78
+ print("App: Vocab not in checkpoint, building from SEED_PHRASE for inference.")
79
+ # This is a fallback - ideally vocab is ALWAYS in checkpoint
80
+ corpus_for_vocab = SEED_PHRASE_APP # Use only seed for vocab if not in ckp
81
+ word_to_idx_global, idx_to_word_global = build_vocab_from_corpus_text(corpus_for_vocab)
82
+
83
+
84
+ # Load model hyperparameters from checkpoint if available, else use app defaults
85
+ # This part needs careful alignment with how train.py saves model_hyperparameters
86
+ model_params_from_ckpt = checkpoint.get('model_hyperparameters', {})
87
+
88
+ d_model = model_params_from_ckpt.get('d_model', D_MODEL_APP)
89
+ n_heads = model_params_from_ckpt.get('n_heads', N_HEADS_APP)
90
+ d_ff = model_params_from_ckpt.get('d_ff', D_FF_APP)
91
+ num_adaptive_blocks = model_params_from_ckpt.get('num_adaptive_blocks', NUM_ADAPTIVE_BLOCKS_APP)
92
+ dropout = model_params_from_ckpt.get('dropout', DROPOUT_APP)
93
+ # seed_phrase and seed_number_str for model init should ideally match what it was trained with.
94
+ # For this app, we assume they are consistent with APP globals.
95
+
96
+ swck_model_global = SWCKModel(
97
+ vocab_size=VOCAB_SIZE_APP, # Use loaded/rebuilt vocab size
98
+ d_model=d_model,
99
+ n_heads=n_heads,
100
+ d_ff=d_ff,
101
+ num_adaptive_blocks=num_adaptive_blocks,
102
+ dropout=dropout,
103
+ seed_phrase=SEED_PHRASE_APP,
104
+ seed_number_str=SEED_NUMBER_STR_APP,
105
+ num_sub_modules_per_block=NUM_SUB_MODULES_PER_BLOCK_APP
106
+ ).to(device_global)
107
+
108
+ swck_model_global.load_state_dict(checkpoint['model_state_dict'])
109
+ swck_model_global.eval()
110
+ # Disable debug prints for cleaner app interface unless specifically needed
111
+ swck_model_global.debug_prints_enabled = False
112
+ for block in swck_model_global.adaptive_blocks:
113
+ block.debug_prints_enabled = False
114
+ print(f"App: SWCKModel loaded successfully from {CHECKPOINT_FILENAME}!")
115
+ return "Model loaded from checkpoint."
116
+ except Exception as e:
117
+ print(f"App: Error loading model from checkpoint: {e}")
118
+ swck_model_global = None # Ensure model is None if loading failed
119
+
120
+ if swck_model_global is None:
121
+ print(f"App: Checkpoint {CHECKPOINT_FILENAME} not found or failed to load. Initializing a new model for basic functionality (not trained).")
122
+ # Fallback: Build vocab from seed phrase for basic tokenization
123
+ word_to_idx_global, idx_to_word_global = build_vocab_from_corpus_text(SEED_PHRASE_APP)
124
+
125
+ swck_model_global = SWCKModel(
126
+ vocab_size=VOCAB_SIZE_APP,
127
+ d_model=D_MODEL_APP,
128
+ n_heads=N_HEADS_APP,
129
+ d_ff=D_FF_APP,
130
+ num_adaptive_blocks=NUM_ADAPTIVE_BLOCKS_APP,
131
+ dropout=DROPOUT_APP,
132
+ seed_phrase=SEED_PHRASE_APP,
133
+ seed_number_str=SEED_NUMBER_STR_APP,
134
+ num_sub_modules_per_block=NUM_SUB_MODULES_PER_BLOCK_APP
135
+ ).to(device_global)
136
+ swck_model_global.eval()
137
+ swck_model_global.debug_prints_enabled = False
138
+ for block in swck_model_global.adaptive_blocks:
139
+ block.debug_prints_enabled = False
140
+ return "Initialized a new (untrained) model as checkpoint was not found."
141
+
142
+
143
+ # --- Text Generation Function (adapted from train.py) ---
144
+ def generate_text_for_app(prompt_str, max_len_gen, temperature_gen):
145
+ if swck_model_global is None or word_to_idx_global is None or idx_to_word_global is None:
146
+ return "Model not loaded. Please check server logs."
147
+
148
+ swck_model_global.eval() # Ensure model is in eval mode
149
+ swck_model_global.set_wiring_phase(False) # No wiring adjustments during inference
150
+
151
+ print(f"App: Generating for prompt: '{prompt_str}', max_len: {max_len_gen}, temp: {temperature_gen}")
152
+
153
+ tokens = [SOS_TOKEN] + [word_to_idx_global.get(w, UNK_TOKEN) for w in prompt_str.lower().split()]
154
+ generated_ids_app = list(tokens)
155
+
156
+ # Collect some debug info for display (optional)
157
+ debug_info_lines = []
158
+
159
+ with torch.no_grad():
160
+ for i in range(max_len_gen):
161
+ # Context windowing for input_tensor
162
+ current_context_ids = generated_ids_app[-SEQ_LEN_APP:]
163
+ input_tensor = torch.tensor([current_context_ids], dtype=torch.long).to(device_global)
164
+ padding_mask = (input_tensor == PAD_TOKEN)
165
+
166
+ # Set model debug prints for first step only if want to show internal state
167
+ # For cleaner app, keep them off or make it a toggle.
168
+ # if i == 0:
169
+ # swck_model_global.debug_prints_enabled = True
170
+ # for block in swck_model_global.adaptive_blocks: block.debug_prints_enabled = True
171
+ # else:
172
+ # swck_model_global.debug_prints_enabled = False
173
+ # for block in swck_model_global.adaptive_blocks: block.debug_prints_enabled = False
174
+
175
+
176
+ logits, entropy_report_infer = swck_model_global(input_tensor, src_key_padding_mask=padding_mask)
177
+ next_token_logits = logits[0, -1, :] # Logits for the last token in the current sequence
178
+
179
+ if temperature_gen == 0: # Greedy
180
+ next_token_id = torch.argmax(next_token_logits).item()
181
+ else:
182
+ probs = F.softmax(next_token_logits / temperature_gen, dim=-1)
183
+ next_token_id = torch.multinomial(probs, 1).item()
184
+
185
+ if next_token_id == EOS_TOKEN:
186
+ debug_info_lines.append(f"Step {i+1}: EOS token encountered.")
187
+ break
188
+ generated_ids_app.append(next_token_id)
189
+
190
+ # Store some info from the first few steps
191
+ if i < 5 : # Log details for first 5 generated tokens
192
+ current_word = idx_to_word_global.get(next_token_id, UNK_TOKEN_STR)
193
+ overall_ent = entropy_report_infer['overall_output_entropy'].item()
194
+ b0_ent = entropy_report_infer['block_output_entropies'][0].item()
195
+ b0_gates_str = ", ".join([f"{g.item():.2f}" for g in entropy_report_infer['block_gate_weights'][0]])
196
+ debug_info_lines.append(f"Gen {i+1}: '{current_word}', OvrlEnt={overall_ent:.3f}, B0Ent={b0_ent:.3f}, B0Gates=[{b0_gates_str}]")
197
+
198
+
199
+ generated_text_list = [idx_to_word_global.get(idx, UNK_TOKEN_STR) for idx in generated_ids_app[1:]] # Skip SOS
200
+ final_text = " ".join(generated_text_list)
201
+ final_text = final_text.replace(EOS_TOKEN_STR, "").strip()
202
+ # Basic cleaning
203
+ final_text = final_text.replace(" .", ".").replace(" ,", ",").replace(" ?", "?").replace(" !", "!")
204
+ final_text = re.sub(r'\s+([.,?!])', r'\1', final_text)
205
+ final_text = re.sub(r'\s+', ' ', final_text).strip()
206
+
207
+ debug_output_str = "\n".join(debug_info_lines)
208
+ return final_text, debug_output_str
209
+
210
+ # --- Gradio Interface ---
211
+ loading_status = load_model_and_vocab() # Load model on app startup
212
+
213
+ with gr.Blocks(title="SWCK Conceptual Demo") as demo:
214
+ gr.Markdown(f"""
215
+ # Self-Wired Conscious Kernel (SWCK) - Conceptual Demo
216
+ This demo showcases a conceptual text generation model based on the SWCK architecture.
217
+ The model is initialized with the seed phrase: "{SEED_PHRASE_APP[:100]}..."
218
+ and seed number: "{SEED_NUMBER_STR_APP}".
219
+ **Model Status:** {loading_status}
220
+ (Note: If no checkpoint is found, an *untrained* model is used, and generations will be random.)
221
+ """)
222
+
223
+ with gr.Row():
224
+ prompt_input = gr.Textbox(label="Enter your prompt:", placeholder="e.g., the meaning of existence is")
225
+ with gr.Row():
226
+ max_len_slider = gr.Slider(minimum=10, maximum=150, value=50, step=1, label="Max Generation Length")
227
+ temp_slider = gr.Slider(minimum=0.0, maximum=2.0, value=0.8, step=0.1, label="Temperature (0 for greedy)")
228
+
229
+ generate_button = gr.Button("Generate Text")
230
+
231
+ with gr.Column():
232
+ output_text = gr.Textbox(label="Generated Text:", lines=5)
233
+ debug_text_area = gr.Textbox(label="Generation Debug Info (first few steps):", lines=7, interactive=False)
234
+
235
+ generate_button.click(
236
+ fn=generate_text_for_app,
237
+ inputs=[prompt_input, max_len_slider, temp_slider],
238
+ outputs=[output_text, debug_text_area]
239
+ )
240
+
241
+ gr.Markdown("Note: This is a highly conceptual and simplified sketch. Generation quality will be limited, especially with an untrained model or small dataset.")
242
+
243
+ if __name__ == "__main__":
244
+ demo.launch()