File size: 18,115 Bytes
c9e8126 | 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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | import torch
import pickle
import json
import os
from typing import Dict, List, Tuple, Optional
import numpy as np
from text_processor import HierarchicalTextProcessor
from ae import ZRIA_Ultimate_PFAF, AdvancedTokenizer, EnhancedDataset
class PersistentZRIAModel:
"""
A persistent wrapper around the ZRIA model that allows saving/loading
and interactive prompting without retraining.
"""
def __init__(self, model_dir: str = "zria_model"):
self.model_dir = model_dir
self.model = None
self.tokenizer = None
self.knowledge_base = None
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Create model directory if it doesn't exist
os.makedirs(model_dir, exist_ok=True)
# Model file paths
self.model_path = os.path.join(model_dir, "zria_model.pth")
self.tokenizer_path = os.path.join(model_dir, "tokenizer.pkl")
self.knowledge_path = os.path.join(model_dir, "knowledge_base.pkl")
self.config_path = os.path.join(model_dir, "config.json")
# Load existing model if available
if self._check_model_exists():
self.load_model()
def _check_model_exists(self) -> bool:
"""Check if a trained model exists in the model directory."""
return (os.path.exists(self.model_path) and
os.path.exists(self.tokenizer_path) and
os.path.exists(self.config_path))
def train_and_save(self, training_data: List[Tuple],
model_config: Dict = None) -> None:
"""
Train the ZRIA model and save it for persistent use.
Args:
training_data: List of (prefix, text, label) tuples
model_config: Configuration dictionary for model parameters
"""
print("=== Training ZRIA Model ===")
# Default configuration
if model_config is None:
model_config = {
'dim': 128,
'max_seq_len': 64,
'action_dim': 1,
'batch_size': 16,
'epochs': 150,
'learning_rate': 3e-4,
'weight_decay': 0.01
}
# Create tokenizer from training data
corpus = [text for _, text, _ in training_data]
self.tokenizer = AdvancedTokenizer(corpus)
# Create dataset and dataloader
dataset = EnhancedDataset(training_data, self.tokenizer, max_len=model_config['max_seq_len'])
dataloader = torch.utils.data.DataLoader(
dataset,
batch_size=model_config['batch_size'],
shuffle=True
)
# Initialize model
self.model = ZRIA_Ultimate_PFAF(
dim=model_config['dim'],
vocab_size=self.tokenizer.vocab_size,
action_dim=model_config['action_dim'],
max_seq_len=model_config['max_seq_len']
)
# Training setup
optimizer = torch.optim.AdamW(
self.model.parameters(),
lr=model_config['learning_rate'],
weight_decay=model_config['weight_decay']
)
scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(
optimizer, T_0=30, T_mult=2, eta_min=1e-6
)
# Train the model
self._train_model(dataloader, optimizer, scheduler, model_config['epochs'])
# Save the trained model
self.save_model(model_config)
print("=== Training Complete ===")
def _train_model(self, dataloader, optimizer, scheduler, epochs: int):
"""Internal training loop."""
self.model.to(self.device)
self.model.train()
text_crit = torch.nn.CrossEntropyLoss()
action_crit = torch.nn.MSELoss()
route_crit = torch.nn.CrossEntropyLoss()
for epoch in range(epochs):
total_loss = 0
for batch in dataloader:
ids = batch['input_ids'].to(self.device)
labels = batch['label'].to(self.device)
mod_idx = batch['modality_idx'].to(self.device)
optimizer.zero_grad()
outputs = self.model(ids, mod_idx, mode='auto')
# Calculate loss
text_mask = torch.tensor([m == 'text' for m in batch['mode']], device=self.device)
action_mask = ~text_mask
loss = 0
if text_mask.any():
loss += text_crit(outputs['text_logits'][text_mask], labels[text_mask].long())
loss += 0.1 * route_crit(outputs['route_probs'][text_mask],
torch.zeros(text_mask.sum(), dtype=torch.long, device=self.device))
if action_mask.any():
loss += 0.1 * action_crit(outputs['action_output'][action_mask].squeeze(-1),
labels[action_mask])
loss += 0.1 * route_crit(outputs['route_probs'][action_mask],
torch.ones(action_mask.sum(), dtype=torch.long, device=self.device))
if isinstance(loss, torch.Tensor):
loss.backward()
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)
optimizer.step()
total_loss += loss.item()
scheduler.step()
if (epoch + 1) % 10 == 0 or epoch == epochs - 1:
print(f"Epoch {epoch+1}/{epochs} | Avg Loss: {total_loss/len(dataloader):.4f} | LR: {scheduler.get_last_lr()[0]:.6f}")
def save_model(self, config: Dict = None):
"""Save the trained model, tokenizer, and configuration."""
print("Saving model...")
# Save model weights
torch.save(self.model.state_dict(), self.model_path)
# Save tokenizer
with open(self.tokenizer_path, 'wb') as f:
pickle.dump(self.tokenizer, f)
# Save configuration
if config is None:
config = {
'dim': 128,
'max_seq_len': 64,
'action_dim': 1,
'vocab_size': self.tokenizer.vocab_size
}
with open(self.config_path, 'w') as f:
json.dump(config, f, indent=2)
# Save knowledge base if available
if self.knowledge_base is not None:
with open(self.knowledge_path, 'wb') as f:
pickle.dump(self.knowledge_base, f)
print(f"Model saved to {self.model_dir}")
def load_model(self):
"""Load the trained model, tokenizer, and configuration."""
print("Loading model...")
# Load configuration
with open(self.config_path, 'r') as f:
config = json.load(f)
# Load tokenizer
with open(self.tokenizer_path, 'rb') as f:
self.tokenizer = pickle.load(f)
# Initialize and load model
self.model = ZRIA_Ultimate_PFAF(
dim=config['dim'],
vocab_size=config['vocab_size'],
action_dim=config['action_dim'],
max_seq_len=config['max_seq_len']
)
# Load model weights
self.model.load_state_dict(torch.load(self.model_path, map_location=self.device))
self.model.to(self.device)
self.model.eval()
# Load knowledge base if available
if os.path.exists(self.knowledge_path):
with open(self.knowledge_path, 'rb') as f:
self.knowledge_base = pickle.load(f)
print("Model loaded successfully")
def prompt(self, text: str, task_type: str = 'auto') -> Dict:
"""
Interactive prompting interface for the trained model.
Args:
text: Input text to process
task_type: 'KNOW', 'DO', or 'auto' for automatic routing
Returns:
Dictionary with prediction results
"""
if self.model is None:
raise ValueError("No model loaded. Please train or load a model first.")
# Determine modality
if task_type == 'KNOW':
prefix = 'KNOW'
modality_idx = 0
elif task_type == 'DO':
prefix = 'DO'
modality_idx = 1
else: # auto
# Try both and let the model decide
return self._auto_route(text)
# Tokenize input
tokens = self.tokenizer.encode(text, prefix)
tokens += [self.tokenizer.pad_idx] * (64 - len(tokens))
ids = torch.tensor([tokens], dtype=torch.long).to(self.device)
mod_idx = torch.tensor([modality_idx], dtype=torch.long).to(self.device)
# Get prediction
with torch.no_grad():
outputs = self.model(ids, mod_idx, mode='auto')
# Format results
if prefix == 'KNOW':
pred_class = torch.argmax(outputs['text_logits'][0]).item()
sentiment = ['Negative', 'Neutral', 'Positive'][pred_class]
confidence = torch.softmax(outputs['text_logits'][0], dim=-1).max().item()
return {
'task_type': 'KNOW',
'input': text,
'prediction': sentiment,
'confidence': confidence,
'route_probability': outputs['route_probs'][0][0].item(),
'raw_outputs': outputs
}
else: # DO
action_value = outputs['action_output'][0].item()
route_prob = outputs['route_probs'][0][1].item()
return {
'task_type': 'DO',
'input': text,
'prediction': action_value,
'route_probability': route_prob,
'raw_outputs': outputs
}
def _auto_route(self, text: str) -> Dict:
"""Automatically determine task type and route accordingly."""
# Try both modalities and let the model decide
know_tokens = self.tokenizer.encode(text, 'KNOW')
know_tokens += [self.tokenizer.pad_idx] * (64 - len(know_tokens))
know_ids = torch.tensor([know_tokens], dtype=torch.long).to(self.device)
know_mod_idx = torch.tensor([0], dtype=torch.long).to(self.device)
do_tokens = self.tokenizer.encode(text, 'DO')
do_tokens += [self.tokenizer.pad_idx] * (64 - len(do_tokens))
do_ids = torch.tensor([do_tokens], dtype=torch.long).to(self.device)
do_mod_idx = torch.tensor([1], dtype=torch.long).to(self.device)
with torch.no_grad():
know_outputs = self.model(know_ids, know_mod_idx, mode='auto')
do_outputs = self.model(do_ids, do_mod_idx, mode='auto')
# Compare routing probabilities
know_route_prob = know_outputs['route_probs'][0][0].item()
do_route_prob = do_outputs['route_probs'][0][1].item()
if know_route_prob > do_route_prob:
# Route to KNOW
pred_class = torch.argmax(know_outputs['text_logits'][0]).item()
sentiment = ['Negative', 'Neutral', 'Positive'][pred_class]
confidence = torch.softmax(know_outputs['text_logits'][0], dim=-1).max().item()
return {
'task_type': 'KNOW',
'input': text,
'prediction': sentiment,
'confidence': confidence,
'route_probability': know_route_prob,
'auto_routed': True,
'raw_outputs': know_outputs
}
else:
# Route to DO
action_value = do_outputs['action_output'][0].item()
return {
'task_type': 'DO',
'input': text,
'prediction': action_value,
'route_probability': do_route_prob,
'auto_routed': True,
'raw_outputs': do_outputs
}
def batch_prompt(self, texts: List[str], task_type: str = 'auto') -> List[Dict]:
"""Process multiple texts in batch."""
results = []
for text in texts:
result = self.prompt(text, task_type)
results.append(result)
return results
def interactive_mode(self):
"""Start an interactive prompting session."""
print("\n=== ZRIA Interactive Mode ===")
print("Type 'quit' to exit, 'help' for commands")
print("Commands:")
print(" KNOW <text> - Process as knowledge/sentiment")
print(" DO <text> - Process as action/task")
print(" AUTO <text> - Let model decide task type")
print(" help - Show this help")
print(" quit - Exit")
print()
while True:
try:
user_input = input("ZRIA> ").strip()
if user_input.lower() == 'quit':
break
elif user_input.lower() == 'help':
print("Commands:")
print(" KNOW <text> - Process as knowledge/sentiment")
print(" DO <text> - Process as action/task")
print(" AUTO <text> - Let model decide task type")
print(" help - Show this help")
print(" quit - Exit")
continue
# Parse command
if user_input.startswith('KNOW '):
text = user_input[5:]
result = self.prompt(text, 'KNOW')
elif user_input.startswith('DO '):
text = user_input[3:]
result = self.prompt(text, 'DO')
elif user_input.startswith('AUTO '):
text = user_input[5:]
result = self.prompt(text, 'auto')
else:
# Default to auto
result = self.prompt(user_input, 'auto')
# Display result
self._display_result(result)
except KeyboardInterrupt:
print("\nExiting...")
break
except Exception as e:
print(f"Error: {e}")
def _display_result(self, result: Dict):
"""Display formatted result."""
print(f"\nInput: {result['input']}")
print(f"Task Type: {result['task_type']}")
if result['task_type'] == 'KNOW':
print(f"Sentiment: {result['prediction']}")
print(f"Confidence: {result['confidence']:.3f}")
else: # DO
print(f"Action Value: {result['prediction']:.2f}")
print(f"Route Probability: {result['route_probability']:.3f}")
if result.get('auto_routed'):
print("(Auto-routed by model)")
print()
# Example usage and integration
def create_and_train_model_from_text_file(text_file_path: str, model_dir: str = "zria_model"):
"""
Complete pipeline: process text file, train model, and save for persistent use.
"""
print("=== ZRIA Model Creation Pipeline ===")
# Step 1: Process text file
processor = HierarchicalTextProcessor()
print(f"Processing text file: {text_file_path}")
knowledge = processor.process_large_text_file(text_file_path)
# Step 2: Create training data
print("Creating training data...")
training_data = processor.create_training_data(knowledge)
print(f"Created {len(training_data)} training examples")
# Step 3: Train and save model
print("Training model...")
persistent_model = PersistentZRIAModel(model_dir)
persistent_model.knowledge_base = knowledge
persistent_model.train_and_save(training_data)
print("=== Pipeline Complete ===")
return persistent_model
def load_and_use_model(model_dir: str = "zria_model"):
"""Load a trained model and start interactive mode."""
persistent_model = PersistentZRIAModel(model_dir)
if persistent_model.model is None:
print("No trained model found. Please train a model first.")
return None
print("Model loaded successfully!")
return persistent_model
if __name__ == "__main__":
# Example usage
import sys
if len(sys.argv) > 1:
if sys.argv[1] == "train" and len(sys.argv) > 2:
# Train from text file
text_file = sys.argv[2]
model_dir = sys.argv[3] if len(sys.argv) > 3 else "zria_model"
model = create_and_train_model_from_text_file(text_file, model_dir)
model.interactive_mode()
elif sys.argv[1] == "load":
# Load existing model
model_dir = sys.argv[2] if len(sys.argv) > 2 else "zria_model"
model = load_and_use_model(model_dir)
if model:
model.interactive_mode()
else:
print("Usage:")
print(" python persistent_model.py train <text_file> [model_dir]")
print(" python persistent_model.py load [model_dir]")
else:
print("ZRIA Persistent Model System")
print("Usage:")
print(" python persistent_model.py train <text_file> [model_dir]")
print(" python persistent_model.py load [model_dir]") |