File size: 14,342 Bytes
68f61ae c491f8e 68f61ae c491f8e 68f61ae c491f8e | 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 | """
Utility functions for LMCODE (Language Model with Memory CODE).
Includes memory visualization, analysis, and helper functions.
"""
import torch
import numpy as np
import matplotlib.pyplot as plt
from typing import Dict, List, Optional, Tuple
from collections import defaultdict
import json
def analyze_memory_capacity(model, test_sequences: List[torch.Tensor],
retrieval_threshold: float = 0.8) -> Dict:
"""
Analyze the memory capacity and retrieval accuracy of the model.
Args:
model: LMCODE model
test_sequences: List of test sequences
retrieval_threshold: Similarity threshold for successful retrieval
Returns:
Dictionary with analysis results
"""
results = {
'total_memories': 0,
'successful_retrievals': 0,
'average_similarity': 0,
'capacity_utilization': 0
}
similarities = []
for seq in test_sequences:
# Store sequence
model.store_experience(seq)
# Try to retrieve
retrieved, indices = model.query_memory(seq, top_k=5)
# Compute similarity
with torch.no_grad():
# Simplified similarity computation
seq_repr = seq.mean(dim=1) if seq.dim() > 2 else seq
retrieved_repr = retrieved.mean(dim=1) if retrieved.dim() > 2 else retrieved
if seq_repr.shape[-1] == retrieved_repr.shape[-1]:
# Cosine similarity
seq_norm = torch.nn.functional.normalize(seq_repr, dim=-1)
retrieved_norm = torch.nn.functional.normalize(retrieved_repr, dim=-1)
similarity = (seq_norm * retrieved_norm).sum(dim=-1).mean()
similarities.append(similarity.item())
if similarity > retrieval_threshold:
results['successful_retrievals'] += 1
results['total_memories'] += 1
if similarities:
results['average_similarity'] = np.mean(similarities)
results['similarity_std'] = np.std(similarities)
# Compute capacity utilization
total_slots = sum(
layer.long_term_memory.num_slots
for layer in model.layers
)
results['capacity_utilization'] = results['total_memories'] / total_slots
return results
def visualize_memory_attention(attention_weights: torch.Tensor,
save_path: Optional[str] = None) -> plt.Figure:
"""
Visualize memory attention patterns.
Args:
attention_weights: Attention weights tensor
save_path: Optional path to save figure
Returns:
Matplotlib figure
"""
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Short-term memory attention
if len(attention_weights.shape) == 4:
# Multi-head attention
attention_avg = attention_weights.mean(dim=1)
else:
attention_avg = attention_weights
im1 = axes[0].imshow(attention_avg[0].cpu().numpy(), cmap='hot', aspect='auto')
axes[0].set_title('Short-Term Memory Attention')
axes[0].set_xlabel('Memory Slots')
axes[0].set_ylabel('Sequence Position')
plt.colorbar(im1, ax=axes[0])
# Long-term memory retrieval weights
# (This would need actual retrieval weights from a forward pass)
axes[1].text(0.5, 0.5, 'Long-Term Memory\nRetrieval Weights',
ha='center', va='center', transform=axes[1].transAxes)
axes[1].set_title('Long-Term Memory Retrieval')
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=150, bbox_inches='tight')
return fig
def plot_training_history(history: Dict, save_path: Optional[str] = None) -> plt.Figure:
"""
Plot training history.
Args:
history: Training history dictionary
save_path: Optional path to save figure
Returns:
Matplotlib figure
"""
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
# Loss plot
axes[0].plot(history.get('train_loss', []), label='Train Loss', alpha=0.8)
if 'eval_loss' in history and history['eval_loss']:
axes[0].plot(history['eval_loss'], label='Eval Loss', alpha=0.8)
axes[0].set_xlabel('Epoch')
axes[0].set_ylabel('Loss')
axes[0].set_title('Training Loss')
axes[0].legend()
axes[0].grid(True, alpha=0.3)
# Memory statistics
if 'memory_stats' in history and history['memory_stats']:
memory_stats = history['memory_stats']
if isinstance(memory_stats, list) and len(memory_stats) > 0:
# Extract memory statistics
if isinstance(memory_stats[0], dict):
# Get first layer's memory stats
layer_0_stats = [s.get('layer_0_lt_active_count', 0)
for s in memory_stats if isinstance(s, dict)]
if layer_0_stats:
axes[1].plot(layer_0_stats, label='Active Memories (Layer 0)', alpha=0.8)
axes[1].set_xlabel('Step')
axes[1].set_ylabel('Active Memory Count')
axes[1].set_title('Memory Utilization')
axes[1].legend()
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=150, bbox_inches='tight')
return fig
def compute_memory_efficiency(model, baseline_model=None) -> Dict:
"""
Compute memory efficiency metrics.
Args:
model: LMCODE model
baseline_model: Optional baseline model for comparison
Returns:
Dictionary with efficiency metrics
"""
metrics = {}
# Count parameters
total_params = sum(p.numel() for p in model.parameters())
memory_params = sum(
p.numel() for name, p in model.named_parameters()
if 'memory' in name
)
metrics['total_parameters'] = total_params
metrics['memory_parameters'] = memory_params
metrics['memory_parameter_ratio'] = memory_params / total_params
# Memory capacity
total_memory_slots = sum(
layer.long_term_memory.num_slots
for layer in model.layers
)
metrics['total_memory_slots'] = total_memory_slots
# Compute parameter efficiency
params_per_slot = memory_params / total_memory_slots if total_memory_slots > 0 else 0
metrics['parameters_per_memory_slot'] = params_per_slot
if baseline_model:
baseline_params = sum(p.numel() for p in baseline_model.parameters())
metrics['parameter_savings'] = 1 - (total_params / baseline_params)
return metrics
def generate_memory_report(model, dataset, output_path: str = 'memory_report.json'):
"""
Generate a comprehensive memory report.
Args:
model: LMCODE model
dataset: Evaluation dataset (list of dicts or list of tensors)
output_path: Path to save report
"""
report = {
'model_config': model.config.to_dict() if hasattr(model.config, 'to_dict')
else vars(model.config),
'memory_analysis': {},
'efficiency_metrics': {}
}
# Analyze memory - handle different dataset formats
if isinstance(dataset, list):
if len(dataset) > 0:
if isinstance(dataset[0], dict):
test_sequences = [d['input_ids'] for d in dataset[:10]]
else:
test_sequences = dataset[:10]
else:
test_sequences = []
else:
test_sequences = []
memory_analysis = analyze_memory_capacity(model, test_sequences)
report['memory_analysis'] = memory_analysis
# Compute efficiency
efficiency = compute_memory_efficiency(model)
report['efficiency_metrics'] = efficiency
# Save report
with open(output_path, 'w') as f:
json.dump(report, f, indent=2, default=str)
print(f"Memory report saved to {output_path}")
return report
def visualize_memory_flow(model, input_sequence: torch.Tensor,
save_path: Optional[str] = None) -> plt.Figure:
"""
Visualize memory flow through the network.
Args:
model: LMCODE model
input_sequence: Input sequence
save_path: Optional path to save figure
Returns:
Matplotlib figure
"""
model.eval()
with torch.no_grad():
outputs = model(input_sequence.unsqueeze(0), use_long_term_memory=True)
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Plot 1: Hidden state evolution
hidden_states = outputs['hidden_states']
if hidden_states:
# Average across layers
avg_hidden = torch.stack([hs.mean(dim=0) for hs in hidden_states])
im1 = axes[0, 0].imshow(avg_hidden.cpu().numpy(), aspect='auto', cmap='viridis')
axes[0, 0].set_title('Hidden State Evolution Across Layers')
axes[0, 0].set_xlabel('Hidden Dimension')
axes[0, 0].set_ylabel('Layer')
plt.colorbar(im1, ax=axes[0, 0])
# Plot 2: Attention weights (first layer)
if outputs['attention_weights']:
attn = outputs['attention_weights'][0]
if attn.dim() == 4:
attn = attn.mean(dim=1) # Average heads
im2 = axes[0, 1].imshow(attn[0].cpu().numpy(), aspect='auto', cmap='plasma')
axes[0, 1].set_title('Self-Attention Weights (Layer 0)')
axes[0, 1].set_xlabel('Key Position')
axes[0, 1].set_ylabel('Query Position')
plt.colorbar(im2, ax=axes[0, 1])
# Plot 3: Memory retrieval weights
if outputs['long_term_outputs'] and outputs['long_term_outputs'][0]:
lt_output = outputs['long_term_outputs'][0]
if 'retrieval_weights' in lt_output:
weights = lt_output['retrieval_weights']
im3 = axes[1, 0].imshow(weights[0].cpu().numpy(), aspect='auto', cmap='coolwarm')
axes[1, 0].set_title('Long-Term Memory Retrieval Weights')
axes[1, 0].set_xlabel('Memory Slot')
axes[1, 0].set_ylabel('Sequence Position')
plt.colorbar(im3, ax=axes[1, 0])
# Plot 4: Short-term memory read weights
if outputs['short_term_outputs']:
st_output = outputs['short_term_outputs'][0]
if 'read_weights' in st_output:
weights = st_output['read_weights']
im4 = axes[1, 1].imshow(weights[0].cpu().numpy(), aspect='auto', cmap='YlOrRd')
axes[1, 1].set_title('Short-Term Memory Read Weights')
axes[1, 1].set_xlabel('Memory Slot')
axes[1, 1].set_ylabel('Sequence Position')
plt.colorbar(im4, ax=axes[1, 1])
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=150, bbox_inches='tight')
return fig
class MemoryMonitor:
"""
Monitor memory usage and performance during training.
"""
def __init__(self, model):
self.model = model
self.history = defaultdict(list)
def record_step(self, step: int, outputs: Dict):
"""
Record memory statistics for a training step.
Args:
step: Current training step
outputs: Model outputs
"""
# Record loss
if 'loss' in outputs and outputs['loss'] is not None:
self.history['loss'].append((step, outputs['loss'].item()))
# Record memory statistics
for i, lt_output in enumerate(outputs.get('long_term_outputs', [])):
if lt_output and 'retrieval_weights' in lt_output:
weights = lt_output['retrieval_weights']
avg_weight = weights.mean().item()
self.history[f'layer_{i}_retrieval_weight'].append((step, avg_weight))
for i, st_output in enumerate(outputs.get('short_term_outputs', [])):
if st_output and 'read_weights' in st_output:
weights = st_output['read_weights']
avg_weight = weights.mean().item()
self.history[f'layer_{i}_read_weight'].append((step, avg_weight))
def get_statistics(self) -> Dict:
"""
Get aggregated memory statistics.
Returns:
Dictionary with statistics
"""
stats = {}
for key, values in self.history.items():
if values:
vals = [v for _, v in values]
stats[key] = {
'mean': np.mean(vals),
'std': np.std(vals),
'min': np.min(vals),
'max': np.max(vals),
'latest': vals[-1]
}
return stats
def plot_history(self, save_path: Optional[str] = None) -> plt.Figure:
"""
Plot monitoring history.
Args:
save_path: Optional path to save figure
Returns:
Matplotlib figure
"""
n_metrics = len(self.history)
if n_metrics == 0:
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
ax.text(0.5, 0.5, 'No data recorded',
ha='center', va='center', transform=ax.transAxes)
return fig
n_cols = min(2, n_metrics)
n_rows = (n_metrics + n_cols - 1) // n_cols
fig, axes = plt.subplots(n_rows, n_cols, figsize=(6 * n_cols, 4 * n_rows))
if n_metrics == 1:
axes = [axes]
elif n_rows > 1 and n_cols > 1:
axes = axes.flatten()
for idx, (key, values) in enumerate(self.history.items()):
if idx >= len(axes):
break
steps, vals = zip(*values)
axes[idx].plot(steps, vals, alpha=0.7)
axes[idx].set_title(key.replace('_', ' ').title())
axes[idx].set_xlabel('Step')
axes[idx].set_ylabel('Value')
axes[idx].grid(True, alpha=0.3)
# Hide unused subplots
for idx in range(n_metrics, len(axes)):
axes[idx].axis('off')
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=150, bbox_inches='tight')
return fig |