Gaston895 commited on
Commit
d675739
·
verified ·
1 Parent(s): 56f868c

Deploy: Enhanced AEGIS with 8-bit quantization 20260111_192048

Browse files
Files changed (1) hide show
  1. app.py +213 -48
app.py CHANGED
@@ -1,12 +1,14 @@
1
  from flask import Flask, render_template, request, jsonify
2
  import torch
3
- from transformers import AutoTokenizer, AutoModelForCausalLM
4
  import re
5
  import gc
6
  import json
7
  import threading
8
  import time
9
  from datetime import datetime
 
 
10
  import logging
11
 
12
  # Configure logging
@@ -24,47 +26,83 @@ loading_status = "Initializing AEGIS BIO LAB 10 CONDUCTOR Multi-Domain Expert Sy
24
  # AEGIS BIO LAB 10 CONDUCTOR Configuration
25
  MODEL_REPO = "Gaston895/aegisconduct"
26
  AEGIS_VERSION = "10.0"
 
 
 
 
 
 
 
 
 
 
27
 
28
  def load_model():
29
- """Load the AEGIS Conduct model optimized for CPU"""
30
  global model, tokenizer, model_loaded, loading_status
31
 
32
  try:
 
 
 
33
  loading_status = "Loading AEGIS BIO LAB 10 CONDUCTOR tokenizer..."
34
- print("Loading AEGIS BIO LAB 10 CONDUCTOR Multi-Domain Expert for CPU...")
35
 
36
  # Load tokenizer first
37
  tokenizer = AutoTokenizer.from_pretrained(
38
  MODEL_REPO,
39
- trust_remote_code=True
 
40
  )
41
 
42
- # Add pad token if missing
43
  if tokenizer.pad_token is None:
44
  tokenizer.pad_token = tokenizer.eos_token
45
 
46
- loading_status = "Loading AEGIS BIO LAB 10 CONDUCTOR model (this may take a few minutes)..."
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- # Load model optimized for CPU
49
  model = AutoModelForCausalLM.from_pretrained(
50
  MODEL_REPO,
51
- torch_dtype=torch.float16,
52
- device_map="cpu",
53
  trust_remote_code=True,
54
- low_cpu_mem_usage=True
 
 
55
  )
56
 
57
- # Force garbage collection
58
- gc.collect()
 
 
 
 
 
 
 
59
 
60
  loading_status = "AEGIS BIO LAB 10 CONDUCTOR Multi-Domain Expert loaded successfully!"
61
- print("AEGIS BIO LAB 10 CONDUCTOR Multi-Domain Expert loaded successfully on CPU!")
62
  model_loaded = True
63
  return True
64
 
65
  except Exception as e:
66
  loading_status = f"Error loading AEGIS BIO LAB 10 CONDUCTOR model: {str(e)}"
67
- print(f"Error loading model: {e}")
 
68
  model_loaded = False
69
  return False
70
 
@@ -79,37 +117,64 @@ def format_response(text):
79
 
80
  return text
81
 
82
- def generate_response(message, history=None, temperature=0.7, max_tokens=128):
83
- """Generate response from the model optimized for CPU"""
84
  global model, tokenizer, model_loaded
85
 
86
  if not model_loaded or model is None or tokenizer is None:
87
  return "AEGIS BIO LAB 10 CONDUCTOR is still loading... Please wait a moment and try again."
88
 
89
- try:
90
- # Build conversation context
91
- conversation = ""
92
- if history:
93
- # Only use last 2 exchanges to save memory
94
- recent_history = history[-2:] if len(history) > 2 else history
95
- for exchange in recent_history:
96
- conversation += f"User: {exchange['user']}\nAssistant: {exchange['assistant']}\n\n"
97
-
98
- # Add current message with AEGIS prompt
99
- aegis_prompt = f"""You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR - an advanced multi-domain analysis system. You can provide expert analysis on ANY topic including economics, technology, science, politics, health, environment, security, and more. Provide comprehensive, well-reasoned responses.
 
 
 
 
 
 
 
100
 
101
- User: {message}
102
- Assistant:"""
103
-
104
- # Tokenize input with strict length limit for CPU
105
- inputs = tokenizer(aegis_prompt, return_tensors="pt", truncation=True, max_length=512)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
- # Generate response with CPU-optimized settings
108
  with torch.no_grad():
109
  outputs = model.generate(
110
  **inputs,
111
- max_new_tokens=max_tokens,
112
- temperature=temperature,
113
  do_sample=True,
114
  top_p=0.9,
115
  top_k=50,
@@ -124,18 +189,92 @@ Assistant:"""
124
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
125
 
126
  # Extract only the new response
127
- response = response[len(aegis_prompt):].strip()
128
 
129
  # Format and clean response
130
  response = format_response(response)
131
 
132
  # Clean up memory after generation
133
- gc.collect()
134
 
135
- return response if response else "I apologize, but I couldn't generate a proper response. Please try rephrasing your question."
136
 
137
  except Exception as e:
138
- return f"Error generating response: {str(e)}. Please try a shorter question."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  @app.route('/')
141
  def index():
@@ -144,40 +283,66 @@ def index():
144
 
145
  @app.route('/status')
146
  def status():
147
- """Get model loading status"""
148
  return jsonify({
149
  'loaded': model_loaded,
150
  'status': loading_status,
151
  'model': MODEL_REPO,
152
- 'version': AEGIS_VERSION
 
 
153
  })
154
 
155
  @app.route('/chat', methods=['POST'])
156
  def chat():
157
- """Handle chat messages"""
158
  data = request.json
159
  message = data.get('message', '').strip()
160
  history = data.get('history', [])
161
  temperature = float(data.get('temperature', 0.7))
162
- max_tokens = int(data.get('max_tokens', 128))
 
163
 
164
  if not message:
165
  return jsonify({'error': 'No message provided'}), 400
166
 
167
- # Generate response
168
- response = generate_response(message, history, temperature, max_tokens)
169
 
170
  return jsonify({
171
  'response': response,
172
  'timestamp': time.time(),
173
- 'model': f"AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR"
 
174
  })
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  @app.route('/clear', methods=['POST'])
177
  def clear_chat():
178
  """Clear chat history and free memory"""
179
- gc.collect()
180
- return jsonify({'status': 'cleared'})
181
 
182
  # Start model loading in background thread
183
  def start_model_loading():
 
1
  from flask import Flask, render_template, request, jsonify
2
  import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
4
  import re
5
  import gc
6
  import json
7
  import threading
8
  import time
9
  from datetime import datetime
10
+ from typing import Dict, List, Optional
11
+ from pydantic import BaseModel
12
  import logging
13
 
14
  # Configure logging
 
26
  # AEGIS BIO LAB 10 CONDUCTOR Configuration
27
  MODEL_REPO = "Gaston895/aegisconduct"
28
  AEGIS_VERSION = "10.0"
29
+ GLOBAL_REGIONS = [
30
+ "North America", "Europe", "Asia", "Africa",
31
+ "South America", "Middle East", "Oceania", "Arctic Region"
32
+ ]
33
+
34
+ def clear_memory():
35
+ """Clear memory aggressively"""
36
+ gc.collect()
37
+ if torch.cuda.is_available():
38
+ torch.cuda.empty_cache()
39
 
40
  def load_model():
41
+ """Load the AEGIS Conduct model with 8-bit quantization"""
42
  global model, tokenizer, model_loaded, loading_status
43
 
44
  try:
45
+ # Initial memory cleanup
46
+ clear_memory()
47
+
48
  loading_status = "Loading AEGIS BIO LAB 10 CONDUCTOR tokenizer..."
49
+ print("🔄 Loading AEGIS BIO LAB 10 CONDUCTOR tokenizer...")
50
 
51
  # Load tokenizer first
52
  tokenizer = AutoTokenizer.from_pretrained(
53
  MODEL_REPO,
54
+ trust_remote_code=True,
55
+ use_fast=True
56
  )
57
 
58
+ # Set padding token if not set
59
  if tokenizer.pad_token is None:
60
  tokenizer.pad_token = tokenizer.eos_token
61
 
62
+ loading_status = "Configuring 8-bit quantization (16GB 8GB)..."
63
+ print("⚙️ Configuring 8-bit quantization (reduces 16GB model to ~8GB)...")
64
+
65
+ # Configure 8-bit quantization for CPU
66
+ quantization_config = BitsAndBytesConfig(
67
+ load_in_8bit=True,
68
+ llm_int8_threshold=6.0,
69
+ llm_int8_has_fp16_weight=False,
70
+ bnb_8bit_compute_dtype=torch.float32, # CPU compatible
71
+ bnb_8bit_use_double_quant=False,
72
+ )
73
+
74
+ loading_status = "Loading 16GB model with 8-bit quantization..."
75
+ print("📥 Loading 16GB model with 8-bit quantization...")
76
 
77
+ # Load model with 8-bit quantization
78
  model = AutoModelForCausalLM.from_pretrained(
79
  MODEL_REPO,
80
+ quantization_config=quantization_config,
81
+ device_map="auto",
82
  trust_remote_code=True,
83
+ low_cpu_mem_usage=True,
84
+ torch_dtype=torch.float32,
85
+ max_memory={"cpu": "12GB"},
86
  )
87
 
88
+ # Set model to evaluation mode
89
+ model.eval()
90
+
91
+ # Final memory cleanup
92
+ clear_memory()
93
+
94
+ print(f"✅ AEGIS BIO LAB 10 CONDUCTOR loaded successfully!")
95
+ print(f"⚡ 8-bit quantization: 16GB → ~8GB memory usage")
96
+ print(f"🚀 Ready for fast CPU inference")
97
 
98
  loading_status = "AEGIS BIO LAB 10 CONDUCTOR Multi-Domain Expert loaded successfully!"
 
99
  model_loaded = True
100
  return True
101
 
102
  except Exception as e:
103
  loading_status = f"Error loading AEGIS BIO LAB 10 CONDUCTOR model: {str(e)}"
104
+ print(f"Error loading model: {e}")
105
+ print(f"💡 Tip: Ensure bitsandbytes>=0.41.0 is installed")
106
  model_loaded = False
107
  return False
108
 
 
117
 
118
  return text
119
 
120
+ def analyze_with_aegis_conductor(prompt: str, analysis_type: str = "general") -> str:
121
+ """Analyze using AEGIS BIO LAB 10 CONDUCTOR - Multi-Domain Expert System"""
122
  global model, tokenizer, model_loaded
123
 
124
  if not model_loaded or model is None or tokenizer is None:
125
  return "AEGIS BIO LAB 10 CONDUCTOR is still loading... Please wait a moment and try again."
126
 
127
+ # Enhanced prompts for AEGIS BIO LAB 10 CONDUCTOR multi-domain analysis
128
+ system_prompts = {
129
+ "general": f"You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR - an advanced multi-domain analysis system. You can provide expert analysis on ANY topic including economics, technology, science, politics, health, environment, security, and more. Provide comprehensive, well-reasoned responses with global perspective across all 8 regions: {', '.join(GLOBAL_REGIONS)}.",
130
+ "economic": f"You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR Economics Expert. Provide comprehensive economic analysis covering market dynamics, financial implications, GDP impacts, inflation effects, trade relationships, and policy recommendations across all 8 global regions: {', '.join(GLOBAL_REGIONS)}.",
131
+ "technology": f"You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR Technology Expert. Analyze technological developments, AI impacts, cybersecurity, innovation trends, and digital transformation across global regions.",
132
+ "security": f"You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR Security Expert. Focus on threat analysis, risk assessment, geopolitical stability, and security implications across {len(GLOBAL_REGIONS)} global regions.",
133
+ "health": f"You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR Health & Bio Expert. Analyze health systems, pandemic preparedness, biotechnology, medical innovations, and public health policies globally.",
134
+ "environment": f"You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR Environmental Expert. Focus on climate change, sustainability, environmental policy, and ecological impacts across all global regions.",
135
+ "strategic": f"You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR Strategic Planning Expert. Provide long-term strategic analysis, policy frameworks, and comprehensive planning across multiple domains and regions.",
136
+ "threat": f"You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR Threat Analysis Expert. Assess multi-domain threats including economic, technological, environmental, security, and health risks across {len(GLOBAL_REGIONS)} global regions.",
137
+ "aegis_conductor": f"You are the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR - the ultimate multi-domain analysis system. Provide comprehensive cross-domain analysis covering all aspects: economic, technological, security, health, environmental, and strategic implications across all 8 global regions: {', '.join(GLOBAL_REGIONS)}."
138
+ }
139
+
140
+ system_prompt = system_prompts.get(analysis_type, system_prompts["general"])
141
+
142
+ # Use Llama chat format
143
+ enhanced_prompt = f"""<s>[INST] <<SYS>>
144
+ {system_prompt}
145
 
146
+ AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR MULTI-DOMAIN CAPABILITIES:
147
+ - Cross-Continental Analysis ({len(GLOBAL_REGIONS)} regions)
148
+ - Multi-Domain Expertise (Economics, Technology, Security, Health, Environment, Strategy)
149
+ - Threat Assessment & Risk Analysis
150
+ - Policy Recommendations & Strategic Planning
151
+ - Real-time Analysis & Insights
152
+ - Global Perspective & Regional Adaptation
153
+ <</SYS>>
154
+
155
+ {prompt}
156
+
157
+ As the AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR, provide a comprehensive analysis that includes:
158
+
159
+ 1. **Core Analysis** - Direct response to the query with expert insights
160
+ 2. **Multi-Domain Perspective** - Consider interconnections across different fields
161
+ 3. **Global Context** - Assess implications across relevant regions
162
+ 4. **Strategic Insights** - Long-term implications and recommendations
163
+ 5. **Risk Assessment** - Identify potential challenges and opportunities
164
+ 6. **Actionable Guidance** - Practical recommendations and next steps
165
+
166
+ Provide thorough, well-reasoned analysis that demonstrates deep expertise while remaining accessible and actionable. [/INST]"""
167
+
168
+ try:
169
+ # Tokenize input with optimized length for 8-bit model
170
+ inputs = tokenizer(enhanced_prompt, return_tensors="pt", truncation=True, max_length=2048)
171
 
172
+ # Generate response with 8-bit quantized model (faster inference)
173
  with torch.no_grad():
174
  outputs = model.generate(
175
  **inputs,
176
+ max_new_tokens=512,
177
+ temperature=0.7,
178
  do_sample=True,
179
  top_p=0.9,
180
  top_k=50,
 
189
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
190
 
191
  # Extract only the new response
192
+ response = response[len(enhanced_prompt):].strip()
193
 
194
  # Format and clean response
195
  response = format_response(response)
196
 
197
  # Clean up memory after generation
198
+ clear_memory()
199
 
200
+ return response if response else "I apologize, but I couldn't generate a proper AEGIS BIO LAB 10 CONDUCTOR analysis. Please try rephrasing your question."
201
 
202
  except Exception as e:
203
+ return f"AEGIS BIO LAB 10 CONDUCTOR analysis error: {str(e)}. Please try a shorter question."
204
+
205
+ def conduct_aegis_threat_analysis(tech_scores: Dict[str, float], year: str = None) -> Dict:
206
+ """Conduct comprehensive AEGIS BIO LAB 10 CONDUCTOR threat analysis"""
207
+ if year is None:
208
+ year = str(datetime.now().year)
209
+
210
+ # Filter critical threats (scores > 6.0)
211
+ critical_threats = {k: v for k, v in tech_scores.items() if v > 6.0}
212
+
213
+ # Enhanced threat analysis prompt
214
+ analysis_prompt = f"""AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR - COMPREHENSIVE THREAT ANALYSIS - Year {year}
215
+
216
+ TECHNOLOGY THREAT ASSESSMENT:
217
+ Critical Threats: {len(critical_threats)} detected from {len(tech_scores)} total threat categories
218
+ High-Impact Threat Categories: {list(critical_threats.keys())}
219
+ Technology Threat Scores: {dict(list(tech_scores.items()))}
220
+
221
+ REQUIRED CALCULATIONS:
222
+ 1. Market Shock Index (0-1 scale): Calculate based on threat interaction effects
223
+ 2. Impact Classification: Determine impact level (Limited/Moderate/Major/Crisis)
224
+ 3. Threat Level: Assess overall threat (Low/Medium/High/Extreme Risk)
225
+
226
+ REGIONAL VULNERABILITIES (0-10 scale for each region):
227
+ 4. North America: Technology and financial sector resilience
228
+ 5. Europe: Manufacturing and energy security
229
+ 6. Asia: Trade diversification and supply chain adaptation
230
+ 7. Africa: Agricultural and resource sector protection
231
+ 8. South America: Climate adaptation and economic diversification
232
+ 9. Middle East: Energy transition and modernization
233
+ 10. Oceania: Resource security and climate resilience
234
+ 11. Arctic Region: Sustainable development
235
+
236
+ Provide comprehensive analysis with specific numerical values for all calculated metrics."""
237
+
238
+ # Get analysis from the AEGIS model
239
+ full_analysis = analyze_with_aegis_conductor(analysis_prompt, "aegis_conductor")
240
+
241
+ # Parse metrics from the response
242
+ result = {
243
+ "reasoning_analysis": full_analysis,
244
+ "market_shock_index": 0.0,
245
+ "impact_classification": "Analysis in Progress",
246
+ "threat_level": "Assessment Pending",
247
+ "regional_vulnerabilities": {},
248
+ "contagion_metrics": {},
249
+ "tech_scores": tech_scores,
250
+ "year": year,
251
+ "analysis_timestamp": datetime.now().isoformat()
252
+ }
253
+
254
+ # Extract metrics from model response
255
+ lines = full_analysis.split('\n')
256
+ for line in lines:
257
+ line = line.strip()
258
+ if 'Market Shock Index:' in line or 'market shock index' in line.lower():
259
+ try:
260
+ import re
261
+ numbers = re.findall(r'(\d+\.?\d*)', line)
262
+ if numbers:
263
+ value = float(numbers[0])
264
+ if value <= 1.0:
265
+ result["market_shock_index"] = value
266
+ except:
267
+ pass
268
+ elif 'Impact Classification:' in line or 'impact classification' in line.lower():
269
+ parts = line.split(':')
270
+ if len(parts) > 1:
271
+ result["impact_classification"] = parts[1].strip()
272
+ elif 'Threat Level:' in line or 'threat level' in line.lower():
273
+ parts = line.split(':')
274
+ if len(parts) > 1:
275
+ result["threat_level"] = parts[1].strip()
276
+
277
+ return result
278
 
279
  @app.route('/')
280
  def index():
 
283
 
284
  @app.route('/status')
285
  def status():
286
+ """Get AEGIS model loading status"""
287
  return jsonify({
288
  'loaded': model_loaded,
289
  'status': loading_status,
290
  'model': MODEL_REPO,
291
+ 'version': AEGIS_VERSION,
292
+ 'regions': len(GLOBAL_REGIONS),
293
+ 'quantization': '8-bit' if model_loaded else 'Loading'
294
  })
295
 
296
  @app.route('/chat', methods=['POST'])
297
  def chat():
298
+ """Handle AEGIS multi-domain chat messages"""
299
  data = request.json
300
  message = data.get('message', '').strip()
301
  history = data.get('history', [])
302
  temperature = float(data.get('temperature', 0.7))
303
+ max_tokens = int(data.get('max_tokens', 256))
304
+ analysis_type = data.get('analysis_type', 'general')
305
 
306
  if not message:
307
  return jsonify({'error': 'No message provided'}), 400
308
 
309
+ # Generate response using AEGIS Multi-Domain System
310
+ response = analyze_with_aegis_conductor(message, analysis_type)
311
 
312
  return jsonify({
313
  'response': response,
314
  'timestamp': time.time(),
315
+ 'model': f"AEGIS BIO LAB {AEGIS_VERSION} CONDUCTOR (8-bit)",
316
+ 'analysis_type': analysis_type
317
  })
318
 
319
+ @app.route('/aegis_analysis', methods=['POST'])
320
+ def aegis_analysis():
321
+ """Handle comprehensive AEGIS BIO LAB 10 CONDUCTOR threat analysis"""
322
+ data = request.json
323
+
324
+ # Get technology threat scores
325
+ tech_scores = {
326
+ 'AI': float(data.get('ai_score', 7.0)),
327
+ 'Cyber': float(data.get('cyber_score', 6.5)),
328
+ 'Bio': float(data.get('bio_score', 8.0)),
329
+ 'Nuclear': float(data.get('nuclear_score', 4.0)),
330
+ 'Climate': float(data.get('climate_score', 7.5)),
331
+ 'Space': float(data.get('space_score', 5.0))
332
+ }
333
+
334
+ year = data.get('year', str(datetime.now().year))
335
+
336
+ # Conduct comprehensive AEGIS analysis
337
+ analysis_result = conduct_aegis_threat_analysis(tech_scores, year)
338
+
339
+ return jsonify(analysis_result)
340
+
341
  @app.route('/clear', methods=['POST'])
342
  def clear_chat():
343
  """Clear chat history and free memory"""
344
+ clear_memory()
345
+ return jsonify({'status': 'AEGIS BIO LAB 10 CONDUCTOR memory cleared'})
346
 
347
  # Start model loading in background thread
348
  def start_model_loading():