EVEprime commited on
Commit
28438c7
·
verified ·
1 Parent(s): 7ec2f07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -103
app.py CHANGED
@@ -552,71 +552,70 @@ class HyperbolicNavigator:
552
 
553
  return self.frequencies[key], self.phases[key]
554
 
555
- def generate_low_rank_perturbations(self, hyper_coords, model):
556
  """
557
- Generates Low-Rank (Rank-1) parameters using continuous equations.
558
- W_perturb = (A_vec \otimes B_vec) * scale
559
  """
560
  total_layers = len(model.model.layers)
561
- h = hyper_coords.squeeze()
562
 
563
- # Increase sensitivity: Normalize the coordinate to use more of the ball space
564
- # This ensures 'Cell 1' isn't the only state
565
- h_norm = torch.norm(h).item()
566
- intensity = h_norm * 5.0 # Boost intensity for more dramatic shifts
567
- phase_shift = torch.sum(h).item() * 10.0 # High frequency shift
568
 
569
  perturbations = {}
570
  total_params = 0
571
- total_shift_magnitude = 0 # Track for verification
572
 
573
  for i in range(total_layers):
574
  layer = model.model.layers[i]
575
  layer_perturbations = []
576
 
577
- # Distance-based intensity scaling
578
- # As h_norm -> 1, we get stronger effects
579
  base_scale = 0.02 * (intensity / (1.0 + 1e-6))
580
  depth_scale = base_scale * (1.0 + (i / total_layers))
581
 
 
582
  targets = []
583
  if hasattr(layer, 'self_attn'):
584
  targets.extend([
585
- ('self_attn.q_proj', layer.self_attn.q_proj),
586
- ('self_attn.k_proj', layer.self_attn.k_proj),
587
- ('self_attn.v_proj', layer.self_attn.v_proj),
588
- ('self_attn.o_proj', layer.self_attn.o_proj),
589
  ])
 
590
  if hasattr(layer, 'mlp'):
591
- if hasattr(layer.mlp, 'gate_proj'):
592
- targets.append(('mlp.gate_proj', layer.mlp.gate_proj))
593
- if hasattr(layer.mlp, 'up_proj'):
594
- targets.append(('mlp.up_proj', layer.mlp.up_proj))
595
- if hasattr(layer.mlp, 'down_proj'):
596
- targets.append(('mlp.down_proj', layer.mlp.down_proj))
 
 
 
 
 
 
 
597
 
598
  for name, module in targets:
599
  if hasattr(module, 'weight'):
600
  shape = module.weight.shape
601
- freq_o, phase_o = self._get_basis_functions(shape[0], f"{name}_out", self.device)
602
- freq_i, phase_i = self._get_basis_functions(shape[1], f"{name}_in", self.device)
603
-
604
- vec_o = torch.sin(intensity * freq_o + phase_o + phase_shift)
605
- vec_i = torch.sin(intensity * freq_i + phase_i + phase_shift)
606
 
607
- layer_perturbations.append({
608
- 'target': name,
609
- 'vec_out': vec_o.to(torch.bfloat16),
610
- 'vec_in': vec_i.to(torch.bfloat16),
611
- 'scale': depth_scale
612
- })
613
- total_params += module.weight.numel()
614
- total_shift_magnitude += (depth_scale * 0.5) # Average theoretical shift
615
 
616
  perturbations[i] = layer_perturbations
617
 
618
  self.total_params_generated = total_params
619
- self.current_shift_magnitude = total_shift_magnitude / (len(perturbations) + 1e-6)
620
  return perturbations, total_params
621
 
622
  def embed_to_honeycomb(self, hyper_embedding):
@@ -2161,7 +2160,7 @@ def get_discourse_monitor():
2161
  # ============================================================================
2162
  # MAIN MODEL SETUP WITH HYPERBOLIC SHADOW PARAMS
2163
  # ============================================================================
2164
- model_id = "Qwen/Qwen3-4B-Instruct-2507"
2165
  print("Loading ADAM - Main Model (GPU)...")
2166
  tokenizer = AutoTokenizer.from_pretrained(model_id)
2167
  model = AutoModelForCausalLM.from_pretrained(
@@ -2172,7 +2171,7 @@ model = AutoModelForCausalLM.from_pretrained(
2172
  )
2173
 
2174
  @spaces.GPU(duration=25)
2175
- def predict(message, history, max_new_tokens, bypass_manifold=False):
2176
  """Main prediction function with continuous Geoopt-based manifold activation."""
2177
  global last_conversation
2178
 
@@ -2181,75 +2180,66 @@ def predict(message, history, max_new_tokens, bypass_manifold=False):
2181
  virtual_params_activated = 0
2182
  honeycomb_cell = 0
2183
 
2184
- # Check if we should bypass the manifold (Ablation Test)
2185
- if bypass_manifold:
2186
- print("[HYPERBOLIC] WARNING: Manifold bypassed by user.")
2187
- last_conversation["hyper_coord"] = 0.0
2188
- last_conversation["virtual_params_active"] = 0
2189
- last_conversation["honeycomb_cell"] = 0
2190
- else:
2191
- # CONTINUOUS ACTIVATION: Always use the librarian and manifold
2192
- librarian_intel = librarian_retrieve(message, context="User query")
2193
- if not librarian_intel or not librarian_intel.strip():
2194
- # Fallback if no relevant discourse found
2195
- librarian_intel = message[:500]
2196
 
2197
- system_prompt += f"\n\n[LIBRARIAN]: {librarian_intel}"
 
 
 
 
 
 
 
 
 
2198
 
2199
- with torch.no_grad():
2200
- # 1. Generate librarian embedding
2201
- tokens = librarian_tokenizer(
2202
- librarian_intel,
2203
- return_tensors="pt",
2204
- truncation=True,
2205
- max_length=1024
2206
- ).to(librarian_model.device)
2207
-
2208
- embeddings = librarian_model(**tokens).last_hidden_state
2209
- lib_embedding = embeddings.mean(dim=1)
2210
-
2211
- # 2. Project to Geoopt-native Poincaré ball using Hyper-Drift
2212
- # We scale the tangent vector to ensure it reaches deep into the manifold (norm -> 1)
2213
- # This ensures unique honeycomb cells for different semantic zones.
2214
- hyper_point = navigator.exp_map(lib_embedding * 15.0)
2215
 
2216
- # Save hyperbolic coordinate stats
2217
- last_conversation["hyper_coord"] = torch.norm(hyper_point).item()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2218
 
2219
- # 3. Low-Rank Manifold Perturbation Injection (Trillion-scale Equation State)
2220
- try:
2221
- # Generate perturbations for ALL layers using sinusoidal equations
2222
- # Now using Low-Rank (Rank-1) vectors to prevent CUDA OOM
2223
- perturbation_map, total_params = navigator.generate_low_rank_perturbations(
2224
- hyper_point, model
2225
- )
2226
- virtual_params_activated = total_params
2227
- honeycomb_cell = navigator.embed_to_honeycomb(hyper_point)
2228
 
2229
- # 4. Precise Hook Registration
2230
- # We apply hooks directly to the weight projections (Q/K/V/O/MLP)
2231
- for layer_idx, perturbations in perturbation_map.items():
2232
- layer = model.model.layers[layer_idx]
2233
 
2234
- for p_info in perturbations:
2235
- target_path = p_info['target']
2236
-
2237
- # Resolve sub-module path (e.g., 'self_attn.q_proj')
2238
- sub_module = layer
2239
- for part in target_path.split('.'):
2240
- sub_module = getattr(sub_module, part)
2241
-
2242
- # Register Low-Rank additive forward hook
2243
- handle = sub_module.register_forward_hook(
2244
- apply_low_rank_boost(p_info['vec_out'], p_info['vec_in'], p_info['scale'])
2245
- )
2246
- hooks.append(handle)
2247
-
2248
- print(f"[HYPERBOLIC] Manifold activated: {total_params:,} parameters modulated in cell {honeycomb_cell}")
2249
-
2250
- except Exception as e:
2251
- print(f"Warning: Manifold activation failed: {e}")
2252
 
 
 
 
 
 
2253
  # Update global stats
2254
  last_conversation["virtual_params_active"] = virtual_params_activated
2255
  last_conversation["honeycomb_cell"] = honeycomb_cell
@@ -2310,8 +2300,7 @@ with gr.Blocks() as demo:
2310
  chat_interface = gr.ChatInterface(
2311
  fn=predict,
2312
  additional_inputs=[
2313
- gr.Slider(minimum=1, maximum=32768, value=4096, step=1, label="Max New Tokens"),
2314
- gr.Checkbox(label="Bypass Hyper-Manifold (Base Model Only)", value=False)
2315
  ],
2316
  examples=[
2317
  ["Explain quantum entanglement.", 4096],
@@ -2402,7 +2391,6 @@ with gr.Blocks() as demo:
2402
  stats += f"**Active Shadow Parameters:** {active_params:,}\n"
2403
  stats += f"**Estimated Max per Pass:** {estimated_max:,}\n"
2404
  stats += f"**Last Hyperbolic Coordinate:** {last_conversation.get('hyper_coord', 0.0):.6f}\n"
2405
- stats += f"**Weight Shift Intensity:** {getattr(navigator, 'current_shift_magnitude', 0):.6f} Δ/param\n"
2406
  stats += f"**Active Honeycomb Cell:** {honeycomb_cell}\n"
2407
  stats += f"**Total Cells Activated:** {cells_activated}\n\n"
2408
 
 
552
 
553
  return self.frequencies[key], self.phases[key]
554
 
555
+ def generate_continuous_perturbations(self, hyper_coords, model):
556
  """
557
+ Generates structured perturbations for ALL layers using continuous equations.
558
+ W_perturb = Sum( A * sin( Omega * H + Phi ) )
559
  """
560
  total_layers = len(model.model.layers)
561
+ h = hyper_coords.squeeze() # (D,)
562
 
563
+ # Project D-dim hyperbolic coordinate to a scalar intensity and a phase shift
564
+ # This ensures every point in B^n has a unique emergent signature
565
+ intensity = torch.norm(h).item()
566
+ phase_shift = torch.sum(h).item()
 
567
 
568
  perturbations = {}
569
  total_params = 0
 
570
 
571
  for i in range(total_layers):
572
  layer = model.model.layers[i]
573
  layer_perturbations = []
574
 
575
+ # Scaling factor based on hyperbolic depth
576
+ # Points deeper in the ball (norm -> 1) cause stronger perturbations
577
  base_scale = 0.02 * (intensity / (1.0 + 1e-6))
578
  depth_scale = base_scale * (1.0 + (i / total_layers))
579
 
580
+ # Target Attention & MLP
581
  targets = []
582
  if hasattr(layer, 'self_attn'):
583
  targets.extend([
584
+ (f'self_attn.q_proj', layer.self_attn.q_proj),
585
+ (f'self_attn.k_proj', layer.self_attn.k_proj),
586
+ (f'self_attn.v_proj', layer.self_attn.v_proj),
587
+ (f'self_attn.o_proj', layer.self_attn.o_proj),
588
  ])
589
+
590
  if hasattr(layer, 'mlp'):
591
+ if hasattr(layer.mlp, 'experts'):
592
+ for e_idx, expert in enumerate(layer.mlp.experts):
593
+ targets.extend([
594
+ (f'mlp.experts.{e_idx}.gate_proj', expert.gate_proj),
595
+ (f'mlp.experts.{e_idx}.up_proj', expert.up_proj),
596
+ (f'mlp.experts.{e_idx}.down_proj', expert.down_proj),
597
+ ])
598
+ else:
599
+ targets.extend([
600
+ (f'mlp.gate_proj', layer.mlp.gate_proj),
601
+ (f'mlp.up_proj', layer.mlp.up_proj),
602
+ (f'mlp.down_proj', layer.mlp.down_proj),
603
+ ])
604
 
605
  for name, module in targets:
606
  if hasattr(module, 'weight'):
607
  shape = module.weight.shape
608
+ freq, phase = self._get_basis_functions(shape, name, self.device)
 
 
 
 
609
 
610
+ # The Equation: P = depth_scale * sin( freq * intensity + phase + phase_shift )
611
+ # This is O(1) memory for the frequencies/phases as they are cached
612
+ p = depth_scale * torch.sin(intensity * freq + phase + phase_shift)
613
+ layer_perturbations.append({'target': name, 'perturbation': p.to(torch.bfloat16)})
614
+ total_params += p.numel()
 
 
 
615
 
616
  perturbations[i] = layer_perturbations
617
 
618
  self.total_params_generated = total_params
 
619
  return perturbations, total_params
620
 
621
  def embed_to_honeycomb(self, hyper_embedding):
 
2160
  # ============================================================================
2161
  # MAIN MODEL SETUP WITH HYPERBOLIC SHADOW PARAMS
2162
  # ============================================================================
2163
+ model_id = "Qwen/Qwen3-4BInstruct-2507"
2164
  print("Loading ADAM - Main Model (GPU)...")
2165
  tokenizer = AutoTokenizer.from_pretrained(model_id)
2166
  model = AutoModelForCausalLM.from_pretrained(
 
2171
  )
2172
 
2173
  @spaces.GPU(duration=25)
2174
+ def predict(message, history, max_new_tokens):
2175
  """Main prediction function with continuous Geoopt-based manifold activation."""
2176
  global last_conversation
2177
 
 
2180
  virtual_params_activated = 0
2181
  honeycomb_cell = 0
2182
 
2183
+ # CONTINUOUS ACTIVATION: Always use the librarian and manifold
2184
+ librarian_intel = librarian_retrieve(message, context="User query")
2185
+ if not librarian_intel or not librarian_intel.strip():
2186
+ # Fallback if no relevant discourse found
2187
+ librarian_intel = message[:500]
 
 
 
 
 
 
 
2188
 
2189
+ system_prompt += f"\n\n[LIBRARIAN]: {librarian_intel}"
2190
+
2191
+ with torch.no_grad():
2192
+ # 1. Generate librarian embedding
2193
+ tokens = librarian_tokenizer(
2194
+ librarian_intel,
2195
+ return_tensors="pt",
2196
+ truncation=True,
2197
+ max_length=1024
2198
+ ).to(librarian_model.device)
2199
 
2200
+ embeddings = librarian_model(**tokens).last_hidden_state
2201
+ lib_embedding = embeddings.mean(dim=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2202
 
2203
+ # 2. Project to Geoopt-native Poincaré ball
2204
+ hyper_point = navigator.project_to_hyperbolic(lib_embedding)
2205
+ # Shift slightly using exponential map to ensure it's not at the exact origin
2206
+ hyper_point = navigator.exp_map(hyper_point)
2207
+
2208
+ # Save hyperbolic coordinate stats
2209
+ last_conversation["hyper_coord"] = torch.norm(hyper_point).item()
2210
+
2211
+ # 3. Continuous Manifold Perturbation Injection (Trillion-scale Equation State)
2212
+ try:
2213
+ # Generate perturbations for ALL layers using sinusoidal equations
2214
+ perturbation_map, total_params = navigator.generate_continuous_perturbations(
2215
+ hyper_point, model
2216
+ )
2217
+ virtual_params_activated = total_params
2218
+ honeycomb_cell = navigator.embed_to_honeycomb(hyper_point)
2219
 
2220
+ # 4. Precise Hook Registration
2221
+ # We apply hooks directly to the weight projections (Q/K/V/O/MLP)
2222
+ for layer_idx, perturbations in perturbation_map.items():
2223
+ layer = model.model.layers[layer_idx]
 
 
 
 
 
2224
 
2225
+ for p_info in perturbations:
2226
+ target_path = p_info['target']
2227
+ p_tensor = p_info['perturbation']
 
2228
 
2229
+ # Resolve sub-module path (e.g., 'self_attn.q_proj')
2230
+ sub_module = layer
2231
+ for part in target_path.split('.'):
2232
+ sub_module = getattr(sub_module, part)
2233
+
2234
+ # Register additive forward hook
2235
+ handle = sub_module.register_forward_hook(apply_hyperbolic_boost(p_tensor))
2236
+ hooks.append(handle)
 
 
 
 
 
 
 
 
 
 
2237
 
2238
+ print(f"[HYPERBOLIC] Manifold activated: {total_params:,} parameters in cell {honeycomb_cell}")
2239
+
2240
+ except Exception as e:
2241
+ print(f"Warning: Manifold activation failed: {e}")
2242
+
2243
  # Update global stats
2244
  last_conversation["virtual_params_active"] = virtual_params_activated
2245
  last_conversation["honeycomb_cell"] = honeycomb_cell
 
2300
  chat_interface = gr.ChatInterface(
2301
  fn=predict,
2302
  additional_inputs=[
2303
+ gr.Slider(minimum=1, maximum=32768, value=4096, step=1, label="Max New Tokens")
 
2304
  ],
2305
  examples=[
2306
  ["Explain quantum entanglement.", 4096],
 
2391
  stats += f"**Active Shadow Parameters:** {active_params:,}\n"
2392
  stats += f"**Estimated Max per Pass:** {estimated_max:,}\n"
2393
  stats += f"**Last Hyperbolic Coordinate:** {last_conversation.get('hyper_coord', 0.0):.6f}\n"
 
2394
  stats += f"**Active Honeycomb Cell:** {honeycomb_cell}\n"
2395
  stats += f"**Total Cells Activated:** {cells_activated}\n\n"
2396