Spaces:
Runtime error
Runtime error
File size: 17,731 Bytes
7498f2c | 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 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | """
Context Scaling System
Handles length scaling (millions of tokens) and multi-modal/structural scaling
Implements advanced attention methods and memory techniques from the article
"""
import logging
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
import numpy as np
from datetime import datetime
import heapq
logger = logging.getLogger(__name__)
@dataclass
class ScaledContext:
"""Context that can scale to millions of tokens"""
segments: List[str] # Segmented content
attention_map: np.ndarray # Attention weights for segments
token_count: int
compression_level: int # 0=none, 1=light, 2=medium, 3=heavy
modalities: Dict[str, Any] # Different context modalities
class AttentionOptimizer:
"""
Advanced attention methods for handling extremely long contexts
Implements sliding window, sparse attention, and hierarchical attention
"""
def __init__(self, window_size: int = 512, stride: int = 256):
self.window_size = window_size
self.stride = stride
def sliding_window_attention(
self,
context: str,
query: str,
max_windows: int = 10
) -> List[Tuple[str, float]]:
"""
Process context using sliding window attention
Returns relevant windows with attention scores
"""
tokens = context.split()
windows = []
# Create sliding windows
for i in range(0, len(tokens) - self.window_size + 1, self.stride):
window = ' '.join(tokens[i:i + self.window_size])
score = self._calculate_attention_score(window, query)
windows.append((window, score))
# Return top windows
windows.sort(key=lambda x: x[1], reverse=True)
return windows[:max_windows]
def hierarchical_attention(
self,
context: str,
query: str,
levels: int = 3
) -> Dict[int, List[str]]:
"""
Multi-level hierarchical attention
Higher levels = more compressed/abstract
"""
hierarchy = {}
current_text = context
for level in range(levels):
if level == 0:
# Finest level - full detail
hierarchy[level] = self._segment_text(current_text, 500)
elif level == 1:
# Middle level - paragraphs/sections
hierarchy[level] = self._extract_key_sentences(current_text)
else:
# Highest level - summary
hierarchy[level] = [self._generate_summary(current_text)]
# Compress for next level
current_text = ' '.join(hierarchy[level])
return hierarchy
def sparse_attention(
self,
context: str,
query: str,
sparsity: float = 0.1
) -> List[str]:
"""
Sparse attention - only attend to most relevant tokens
Reduces computation from O(n²) to O(n*k)
"""
tokens = context.split()
query_tokens = set(query.lower().split())
# Calculate relevance for each token
token_scores = []
for i, token in enumerate(tokens):
score = 1.0 if token.lower() in query_tokens else np.random.random() * 0.5
token_scores.append((i, token, score))
# Keep only top k% tokens
k = int(len(tokens) * sparsity)
top_tokens = heapq.nlargest(k, token_scores, key=lambda x: x[2])
# Sort by original position to maintain order
top_tokens.sort(key=lambda x: x[0])
# Reconstruct sparse context
sparse_context = []
last_idx = -1
for idx, token, score in top_tokens:
if idx > last_idx + 1:
sparse_context.append("...")
sparse_context.append(token)
last_idx = idx
return sparse_context
def _calculate_attention_score(self, window: str, query: str) -> float:
"""Calculate attention score between window and query"""
window_words = set(window.lower().split())
query_words = set(query.lower().split())
if not query_words:
return 0.0
overlap = len(window_words & query_words)
return overlap / len(query_words)
def _segment_text(self, text: str, segment_size: int) -> List[str]:
"""Segment text into chunks"""
words = text.split()
segments = []
for i in range(0, len(words), segment_size):
segments.append(' '.join(words[i:i + segment_size]))
return segments
def _extract_key_sentences(self, text: str) -> List[str]:
"""Extract key sentences (simplified)"""
sentences = text.split('.')
# Keep sentences with more than 10 words (likely more informative)
key_sentences = [s.strip() + '.' for s in sentences if len(s.split()) > 10]
return key_sentences[:10] # Top 10 sentences
def _generate_summary(self, text: str) -> str:
"""Generate summary (simplified - would use LLM in production)"""
sentences = text.split('.')[:3] # First 3 sentences as summary
return '. '.join(sentences) + '.'
class LengthScaler:
"""
Handle context scaling from thousands to millions of tokens
Maintains coherence across long documents
"""
def __init__(self, max_tokens: int = 1000000):
self.max_tokens = max_tokens
self.attention_optimizer = AttentionOptimizer()
def scale_context(
self,
context: str,
query: str,
target_tokens: int = 2000
) -> ScaledContext:
"""Scale context to target token count while maintaining relevance"""
tokens = context.split()
current_tokens = len(tokens)
# Determine compression level needed
compression_ratio = current_tokens / target_tokens
if compression_ratio <= 1:
# No compression needed
return ScaledContext(
segments=[context],
attention_map=np.array([1.0]),
token_count=current_tokens,
compression_level=0,
modalities={}
)
# Apply appropriate scaling strategy
if compression_ratio < 5:
# Light compression - sliding window
segments = self._light_compression(context, query, target_tokens)
compression_level = 1
elif compression_ratio < 20:
# Medium compression - hierarchical
segments = self._medium_compression(context, query, target_tokens)
compression_level = 2
else:
# Heavy compression - sparse attention
segments = self._heavy_compression(context, query, target_tokens)
compression_level = 3
# Calculate attention map
attention_map = self._calculate_attention_map(segments, query)
return ScaledContext(
segments=segments,
attention_map=attention_map,
token_count=sum(len(s.split()) for s in segments),
compression_level=compression_level,
modalities={}
)
def _light_compression(
self,
context: str,
query: str,
target_tokens: int
) -> List[str]:
"""Light compression using sliding windows"""
windows = self.attention_optimizer.sliding_window_attention(
context, query, max_windows=target_tokens // 100
)
return [w for w, _ in windows]
def _medium_compression(
self,
context: str,
query: str,
target_tokens: int
) -> List[str]:
"""Medium compression using hierarchical attention"""
hierarchy = self.attention_optimizer.hierarchical_attention(context, query)
segments = []
remaining_tokens = target_tokens
# Add from each level based on available tokens
for level in sorted(hierarchy.keys()):
level_segments = hierarchy[level]
for segment in level_segments:
segment_tokens = len(segment.split())
if segment_tokens <= remaining_tokens:
segments.append(segment)
remaining_tokens -= segment_tokens
if remaining_tokens <= 0:
break
return segments
def _heavy_compression(
self,
context: str,
query: str,
target_tokens: int
) -> List[str]:
"""Heavy compression using sparse attention"""
sparsity = target_tokens / len(context.split())
sparse_tokens = self.attention_optimizer.sparse_attention(
context, query, sparsity=min(sparsity, 0.3)
)
# Group sparse tokens into segments
segments = []
current_segment = []
for token in sparse_tokens:
if token == "...":
if current_segment:
segments.append(' '.join(current_segment))
current_segment = []
segments.append("...")
else:
current_segment.append(token)
if current_segment:
segments.append(' '.join(current_segment))
return segments
def _calculate_attention_map(
self,
segments: List[str],
query: str
) -> np.ndarray:
"""Calculate attention weights for each segment"""
query_words = set(query.lower().split())
attention_scores = []
for segment in segments:
if segment == "...":
attention_scores.append(0.0)
else:
segment_words = set(segment.lower().split())
overlap = len(query_words & segment_words)
score = overlap / max(len(query_words), 1)
attention_scores.append(score)
# Normalize
scores = np.array(attention_scores)
if scores.sum() > 0:
scores = scores / scores.sum()
return scores
class MultiModalScaler:
"""
Handle multi-modal and structural context scaling
Temporal, spatial, participant states, intentional, cultural
"""
def __init__(self):
self.modality_handlers = {
'temporal': self._scale_temporal,
'spatial': self._scale_spatial,
'participant': self._scale_participant,
'intentional': self._scale_intentional,
'cultural': self._scale_cultural
}
def scale_multimodal(
self,
modalities: Dict[str, Any],
importance_weights: Optional[Dict[str, float]] = None
) -> Dict[str, Any]:
"""Scale multiple modalities based on importance"""
if importance_weights is None:
importance_weights = {
'temporal': 0.3,
'spatial': 0.1,
'participant': 0.3,
'intentional': 0.2,
'cultural': 0.1
}
scaled = {}
for modality, data in modalities.items():
if modality in self.modality_handlers:
weight = importance_weights.get(modality, 0.1)
scaled[modality] = self.modality_handlers[modality](data, weight)
return scaled
def _scale_temporal(self, data: List[Dict], weight: float) -> List[Dict]:
"""Scale temporal context - keep most recent and important events"""
# Sort by timestamp
sorted_data = sorted(data, key=lambda x: x.get('timestamp', datetime.min), reverse=True)
# Keep based on weight (more weight = more events kept)
keep_count = max(1, int(len(sorted_data) * weight))
return sorted_data[:keep_count]
def _scale_spatial(self, data: Dict, weight: float) -> Dict:
"""Scale spatial context - simplify based on importance"""
if weight < 0.3:
# Low importance - just keep basic location
return {'location': data.get('primary_location', 'unknown')}
else:
# Higher importance - keep more detail
return data
def _scale_participant(self, data: Dict, weight: float) -> Dict:
"""Scale participant states - keep most active participants"""
if not data:
return {}
# Sort by activity level (approximated by state changes)
participants = []
for pid, pdata in data.items():
activity = len(pdata.get('history', []))
participants.append((pid, pdata, activity))
participants.sort(key=lambda x: x[2], reverse=True)
# Keep based on weight
keep_count = max(1, int(len(participants) * weight))
return {pid: pdata for pid, pdata, _ in participants[:keep_count]}
def _scale_intentional(self, data: Dict, weight: float) -> Dict:
"""Scale intentional context - keep high priority goals"""
if not data:
return {}
# Sort by priority
goals = [(k, v) for k, v in data.items()]
goals.sort(key=lambda x: x[1].get('priority', 0), reverse=True)
# Keep based on weight
keep_count = max(1, int(len(goals) * weight))
return {k: v for k, v in goals[:keep_count]}
def _scale_cultural(self, data: Dict, weight: float) -> Dict:
"""Scale cultural context - keep if important"""
if weight < 0.2:
return {} # Skip if low importance
return data
class ContextScalingOrchestrator:
"""
Main orchestrator for context scaling
Combines length and multi-modal scaling
"""
def __init__(self, max_context_tokens: int = 100000):
self.length_scaler = LengthScaler(max_context_tokens)
self.multimodal_scaler = MultiModalScaler()
def scale_complete_context(
self,
text_context: str,
multimodal_context: Dict[str, Any],
query: str,
target_tokens: int = 2000,
modality_weights: Optional[Dict[str, float]] = None
) -> Dict[str, Any]:
"""
Scale both text and multi-modal context
Returns optimally scaled context
"""
# Scale text context
scaled_text = self.length_scaler.scale_context(
text_context, query, target_tokens
)
# Scale multi-modal context
scaled_multimodal = self.multimodal_scaler.scale_multimodal(
multimodal_context, modality_weights
)
# Combine
result = {
'text': {
'segments': scaled_text.segments,
'attention_map': scaled_text.attention_map.tolist(),
'token_count': scaled_text.token_count,
'compression_level': scaled_text.compression_level
},
'multimodal': scaled_multimodal,
'metadata': {
'original_tokens': len(text_context.split()),
'scaled_tokens': scaled_text.token_count,
'compression_ratio': len(text_context.split()) / max(scaled_text.token_count, 1),
'modalities_preserved': list(scaled_multimodal.keys())
}
}
return result
# Demo usage
def demo_context_scaling():
"""Demonstrate context scaling capabilities"""
# Create a very long context
long_context = " ".join([
f"Sentence {i} about various topics including AI, engineering, and software development."
for i in range(10000)
]) # ~100k tokens
# Multi-modal context
multimodal = {
'temporal': [
{'event': f'Event {i}', 'timestamp': datetime.now()}
for i in range(50)
],
'participant': {
f'person_{i}': {'state': 'active', 'history': []}
for i in range(20)
},
'intentional': {
f'goal_{i}': {'priority': np.random.random()}
for i in range(10)
}
}
# Scale the context
orchestrator = ContextScalingOrchestrator()
scaled = orchestrator.scale_complete_context(
text_context=long_context,
multimodal_context=multimodal,
query="AI engineering position requirements",
target_tokens=2000
)
print(f"Scaling Results:")
print(f"Original tokens: {scaled['metadata']['original_tokens']}")
print(f"Scaled tokens: {scaled['metadata']['scaled_tokens']}")
print(f"Compression ratio: {scaled['metadata']['compression_ratio']:.2f}x")
print(f"Compression level: {scaled['text']['compression_level']}")
print(f"Modalities preserved: {scaled['metadata']['modalities_preserved']}")
print(f"Text segments: {len(scaled['text']['segments'])}")
print(f"Temporal events kept: {len(scaled['multimodal'].get('temporal', []))}")
if __name__ == "__main__":
demo_context_scaling() |