import asyncio
import os
from typing import Optional, Dict, List, Any
from dataclasses import dataclass
import time
import torch
from torch import amp
import torch.nn as nn
import numpy as np
from collections import deque
from solana_logger import log_debug, log_info, log_error, SolanaLogger
def forward(self, x):
features = self.feature_extractor(x)
return self.projection_head(features)
@dataclass
class VectorConfig:
batch_size: int = int(os.getenv("VECTOR_BATCH_SIZE", "64"))
vector_dim: int = int(os.getenv("VECTOR_DIMENSION", "512"))
similarity_threshold: float = float(os.getenv("SIMILARITY_THRESHOLD", "0.85"))
cache_size: int = int(os.getenv("VECTOR_CACHE_SIZE", "1000"))
@dataclass
class VectorMetrics:
patterns_stored: int = 0
patterns_retrieved: int = 0
last_cleanup: float = time.time()
class EnhancedVectorStore:
def init(self):
self.config = VectorConfig()
self.metrics = VectorMetrics()
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self._setup_model()
self._init_storage()
code
Assistant
User
do i even need logging in the vector that much yeah?
Assistant
User
oh okay good
Assistant
I'm glad you found the information helpful! If you have any more questions or need further assistance, whether it's regarding logging practices, optimizing your code, or anything else, feel free to ask. Happy coding!
def _setup_model(self):
self.feature_extractor = FeatureExtractor().to(self.device)
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.backends.cudnn.benchmark = True
self.scaler = amp.GradScaler()
def _init_storage(self):
self.patterns = {}
self.cache = {}
self.recent_patterns = deque(maxlen=self.config.cache_size)
async def __aenter__(self):
await self.initialize()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.cleanup()
async def initialize(self):
"""Initialize resources"""
try:
log_info("Initializing vector store")
if torch.cuda.is_available():
torch.cuda.empty_cache()
return True
except Exception as e:
log_error(f"Initialization failed: {e}")
return False
def _calculate_similarity(self, vec1: torch.Tensor, vec2: torch.Tensor) -> torch.Tensor:
with torch.no_grad():
vec1_norm = torch.nn.functional.normalize(vec1, p=2, dim=1)
vec2_norm = torch.nn.functional.normalize(vec2, p=2, dim=1)
return torch.mm(vec1_norm, vec2_norm.t())
async def store_pattern(self, pool_id: str, pattern_vector: torch.Tensor, metadata: Dict):
try:
pattern_vector = pattern_vector.to(device=self.device, dtype=torch.float16)
with amp.autocast(device_type='cuda' if torch.cuda.is_available() else 'cpu'):
features = self.feature_extractor(pattern_vector)
self.patterns[pool_id] = {
'vector': features,
'timestamp': time.time(),
'metadata': metadata
}
self.cache[pool_id] = features
self.recent_patterns.append(pool_id)
self.metrics.patterns_stored += 1
if len(self.patterns) > self.config.cache_size:
await self._cleanup_old_patterns()
except Exception as e:
log_error(f"Pattern storage failed: {e}")
async def search_similar_patterns(self, query_vector: torch.Tensor, k: int = 5) -> List[Dict]:
try:
if not self.patterns:
return []
query_vector = query_vector.to(device=self.device, dtype=torch.float16)
with amp.autocast(device_type='cuda' if torch.cuda.is_available() else 'cpu'):
query_features = self.feature_extractor(query_vector)
pattern_vectors = torch.stack([p['vector'] for p in self.patterns.values()], dim=0)
similarities = self._calculate_similarity(query_features.unsqueeze(0), pattern_vectors)
results = []
for pool_id, sim in zip(self.patterns.keys(), similarities[0]):
if sim >= self.config.similarity_threshold:
results.append({
'pool_id': pool_id,
'similarity': float(sim),
'metadata': self.patterns[pool_id]['metadata']
})
results.sort(key=lambda x: x['similarity'], reverse=True)
self.metrics.patterns_retrieved += 1
return results[:k]
except Exception as e:
log_error(f"Pattern search failed: {e}")
return []
async def _cleanup_old_patterns(self):
try:
if time.time() - self.metrics.last_cleanup < 3600:
return
sorted_patterns = sorted(
self.patterns.items(),
key=lambda x: x[1]['timestamp']
)
patterns_to_remove = len(sorted_patterns) - self.config.cache_size
for pool_id, _ in sorted_patterns[:patterns_to_remove]:
del self.patterns[pool_id]
del self.cache[pool_id]
self.metrics.last_cleanup = time.time()
if torch.cuda.is_available():
torch.cuda.empty_cache()
except Exception as e:
log_error(f"Pattern cleanup failed: {e}")
async def cleanup(self):
"""Cleanup resources"""
try:
self.patterns.clear()
self.cache.clear()
self.recent_patterns.clear()
if torch.cuda.is_available():
torch.cuda.empty_cache()
except Exception as e:
log_error(f"Cleanup failed: {e}")
if name == "main":
async def test():
async with EnhancedVectorStore() as store:
test_vector = torch.randn(512)
await store.store_pattern("test_pool", test_vector, {"test": True})
results = await store.search_similar_patterns(test_vector)
print(results)
code
asyncio.run(test()) is this script able to be condensed?
Yes, the script can be condensed to improve readability and maintainability. This can be achieved by reducing redundancy, grouping related functionalities, and enhancing the structure. Below is a condensed version of your script with some comments on what was changed:
python
import asyncio
import os
import time
import torch
import torch.nn as nn
from collections import deque
from dataclasses import dataclass
from typing import Dict, List, Any
from torch import amp
from solana_logger import log_info, log_error, SolanaLogger
logger = SolanaLogger()
class FeatureExtractor(nn.Module):
def __init__(self, input_dim=512, hidden_dims=[256, 128]):
super().__init__()
layers = []
prev_dim = input_dim
for hidden_dim in hidden_dims:
layers.extend([
nn.Linear(prev_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.LeakyReLU(0.01),
nn.Dropout(0.1)
])
prev_dim = hidden_dim
self.feature_extractor = nn.Sequential(*layers)
self.projection_head = nn.Linear(prev_dim, 64)
def forward(self, x):
return self.projection_head(self.feature_extractor(x))
@dataclass
class VectorConfig:
batch_size: int = int(os.getenv("VECTOR_BATCH_SIZE", "64"))
vector_dim: int = int(os.getenv("VECTOR_DIMENSION", "512"))
similarity_threshold: float = float(os.getenv("SIMILARITY_THRESHOLD", "0.85"))
cache_size: int = int(os.getenv("VECTOR_CACHE_SIZE", "1000"))
@dataclass
class VectorMetrics:
patterns_stored: int = 0
patterns_retrieved: int = 0
last_cleanup: float = time.time()
class EnhancedVectorStore:
def __init__(self):
self.config = VectorConfig()
self.metrics = VectorMetrics()
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.feature_extractor = FeatureExtractor().to(self.device)
self._reset_storage()
def _reset_storage(self):
"""Set up necessary storage."""
self.patterns = {}
self.cache = {}
self.recent_patterns = deque(maxlen=self.config.cache_size)
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.backends.cudnn.benchmark = True
async def __aenter__(self):
await self.initialize()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.cleanup()
async def initialize(self):
"""Initialize resources"""
log_info("Initializing vector store")
def _calculate_similarity(self, vec1: torch.Tensor, vec2: torch.Tensor) -> torch.Tensor:
"""Calculate cosine similarity."""
vec1_norm = torch.nn.functional.normalize(vec1, p=2, dim=1)
vec2_norm = torch.nn.functional.normalize(vec2, p=2, dim=1)
return torch.mm(vec1_norm, vec2_norm.t())
async def store_pattern(self, pool_id: str, pattern_vector: torch.Tensor, metadata: Dict):
"""Store a pattern and its associated metadata."""
try:
pattern_vector = pattern_vector.to(self.device, dtype=torch.float16)
with amp.autocast():
features = self.feature_extractor(pattern_vector)
self.patterns[pool_id] = {'vector': features, 'timestamp': time.time(), 'metadata': metadata}
self.cache[pool_id] = features
self.recent_patterns.append(pool_id)
self.metrics.patterns_stored += 1
if len(self.patterns) > self.config.cache_size:
await self._cleanup_old_patterns()
except Exception as e:
log_error(f"Pattern storage failed: {e}")
async def search_similar_patterns(self, query_vector: torch.Tensor, k: int = 5) -> List[Dict]:
"""Search for patterns similar to the query vector."""
try:
if not self.patterns:
return []
query_vector = query_vector.to(self.device, dtype=torch.float16)
with amp.autocast():
query_features = self.feature_extractor(query_vector)
pattern_vectors = torch.stack([p['vector'] for p in self.patterns.values()], dim=0)
similarities = self._calculate_similarity(query_features.unsqueeze(0), pattern_vectors)
results = sorted(
[{'pool_id': pool_id, 'similarity': float(sim), 'metadata': self.patterns[pool_id]['metadata']}
for pool_id, sim in zip(self.patterns.keys(), similarities[0])
if sim >= self.config.similarity_threshold],
key=lambda x: x['similarity'],
reverse=True
)
self.metrics.patterns_retrieved += 1
return results[:k]
except Exception as e:
log_error(f"Pattern search failed: {e}")
return []
async def _cleanup_old_patterns(self):
"""Remove old patterns beyond the cache size."""
if time.time() - self.metrics.last_cleanup < 3600:
return
patterns_to_remove = len(self.patterns) - self.config.cache_size
if patterns_to_remove > 0:
sorted_patterns = sorted(self.patterns.items(), key=lambda x: x[1]['timestamp'])
for pool_id, _ in sorted_patterns[:patterns_to_remove]:
del self.patterns[pool_id]
del self.cache[pool_id]
self.metrics.last_cleanup = time.time()
torch.cuda.empty_cache()
async def cleanup(self):
"""Cleanup resources."""
try:
self.patterns.clear()
self.cache.clear()
self.recent_patterns.clear()
if torch.cuda.is_available():
torch.cuda.empty_cache()
except Exception as e:
log_error(f"Cleanup failed: {e}")
async def test():
async with EnhancedVectorStore() as store:
test_vector = torch.randn(512)
await store.store_pattern("test_pool", test_vector, {"test": True})
results = await store.search_similar_patterns(test_vector)
print(results)
if __name__ == "__main__":
asyncio.run(test())
Changes made:
Reduced Redundant Code: The feature extraction and normalization routines were combined into more streamlined methods.
Code Structure: Grouping the setup functions for clarity and reusability.
Error Handling: Simplified error logging directly within try blocks without repeating patterns.
Additional Comments: Added comments to clarify function purposes.
Removed Unused Variables: Such as self.scaler, which was not being utilized within the provided code.
These adjustments help to ensure the script remains functional while improving its readability and organization.
The necessity and frequency of logging in your application depends on several factors, including:
Debugging Needs: If you're actively developing or debugging the vector storage system, logging can help you trace the flow of execution, monitor variable states, and catch errors. In such cases, detailed logging is beneficial.
Operational Monitoring: In a production environment, logging can provide insights into usage patterns, performance metrics, and system health. It can alert you to potential issues before they become critical.
Performance Impact: Logging can introduce overhead, especially if logging happens frequently or with high verbosity. If performance is an issue, you might want to reduce logging frequency or detail.
Severity Levels: Not every action needs 'info' or 'debug' level logging. You can categorize messages as 'info', 'warning', 'error', etc. This way, you can focus on significant issues while optionally logging lower-priority messages.
Recommendations on Logging
Here are some recommendations for handling logging in your vector storage application:
Log on Exceptions Only: If you're concerned about performance, consider only logging errors and critical issues. This reduces clutter in your logs and focuses attention on significant problems.
python
try:
# Some operation
except Exception as e:
log_error(f"An error occurred: {e}")
Use Conditional Logging: Implement a debug mode or environment variable that controls logging verbosity. For example, only log detailed information if running in a debug environment.
python
if os.getenv("DEBUG_MODE") == "1":
log_info("Detailed debug info...")
Aggregate Logs: If the logging data is too verbose, consider aggregating results (e.g., log counts of certain operations) rather than logging every single action.
Performance Monitoring: Instead of frequent logging, consider using performance monitoring tools that provide insights without logging every operation (like APM tools).
Periodic Summary Logs: Instead of logging every action, you could log summary statistics or metrics at regular intervals.
Conclusion
While logging is an essential aspect of software applications, its frequency and level of detail should be balanced with performance considerations and the operational context. If logging feels excessive, consider refining it based on the recommendations above to better suit your needs. If you find that some logging statements can be removed or reduced without losing important information, that can lead to cleaner and more efficient code.