File size: 16,599 Bytes
b190b45 |
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 |
#!/usr/bin/env python3
"""
Direct Model Loader Service - NO PIPELINES
Loads Hugging Face models directly using AutoModel and AutoTokenizer
NO PIPELINE USAGE - Direct model inference only
"""
import logging
import os
from typing import Dict, Any, Optional, List
from datetime import datetime
import torch
import numpy as np
from pathlib import Path
logger = logging.getLogger(__name__)
# Try to import transformers
try:
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
AutoModelForCausalLM,
BertTokenizer,
BertForSequenceClassification
)
TRANSFORMERS_AVAILABLE = True
except ImportError:
TRANSFORMERS_AVAILABLE = False
logger.error("β Transformers library not available. Install with: pip install transformers torch")
class DirectModelLoader:
"""
Direct Model Loader - NO PIPELINES
Loads models directly and performs inference without using Hugging Face pipelines
"""
def __init__(self, cache_dir: Optional[str] = None):
"""
Initialize Direct Model Loader
Args:
cache_dir: Directory to cache models (default: ~/.cache/huggingface)
"""
if not TRANSFORMERS_AVAILABLE:
raise ImportError("Transformers library is required. Install with: pip install transformers torch")
self.cache_dir = cache_dir or os.path.expanduser("~/.cache/huggingface")
self.models = {}
self.tokenizers = {}
self.device = "cuda" if torch.cuda.is_available() else "cpu"
logger.info(f"π Direct Model Loader initialized")
logger.info(f" Device: {self.device}")
logger.info(f" Cache directory: {self.cache_dir}")
# Model configurations - DIRECT LOADING ONLY
# Ordered by preference (most reliable first)
self.model_configs = {
"cryptobert_kk08": {
"model_id": "kk08/CryptoBERT",
"model_class": "BertForSequenceClassification",
"task": "sentiment-analysis",
"description": "CryptoBERT by KK08 for crypto sentiment",
"loaded": False,
"requires_auth": False,
"priority": 1
},
"twitter_sentiment": {
"model_id": "cardiffnlp/twitter-roberta-base-sentiment-latest",
"model_class": "AutoModelForSequenceClassification",
"task": "sentiment-analysis",
"description": "Twitter RoBERTa for sentiment analysis",
"loaded": False,
"requires_auth": False,
"priority": 2
},
"finbert": {
"model_id": "ProsusAI/finbert",
"model_class": "AutoModelForSequenceClassification",
"task": "sentiment-analysis",
"description": "FinBERT for financial sentiment",
"loaded": False,
"requires_auth": False,
"priority": 3
},
"cryptobert_elkulako": {
"model_id": "ElKulako/cryptobert",
"model_class": "BertForSequenceClassification",
"task": "sentiment-analysis",
"description": "CryptoBERT by ElKulako for crypto sentiment",
"loaded": False,
"requires_auth": True,
"priority": 4
}
}
async def load_model(self, model_key: str) -> Dict[str, Any]:
"""
Load a specific model directly (NO PIPELINE)
Args:
model_key: Key of the model to load
Returns:
Status dict with model info
"""
if model_key not in self.model_configs:
raise ValueError(f"Unknown model: {model_key}")
config = self.model_configs[model_key]
# Check if already loaded
if model_key in self.models and model_key in self.tokenizers:
logger.info(f"β
Model {model_key} already loaded")
config["loaded"] = True
return {
"success": True,
"model_key": model_key,
"model_id": config["model_id"],
"status": "already_loaded",
"device": self.device
}
try:
logger.info(f"π₯ Loading model: {config['model_id']} (NO PIPELINE)")
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(
config["model_id"],
cache_dir=self.cache_dir
)
# Load model based on class
if config["model_class"] == "BertForSequenceClassification":
model = BertForSequenceClassification.from_pretrained(
config["model_id"],
cache_dir=self.cache_dir
)
elif config["model_class"] == "AutoModelForSequenceClassification":
model = AutoModelForSequenceClassification.from_pretrained(
config["model_id"],
cache_dir=self.cache_dir
)
elif config["model_class"] == "AutoModelForCausalLM":
model = AutoModelForCausalLM.from_pretrained(
config["model_id"],
cache_dir=self.cache_dir
)
else:
raise ValueError(f"Unknown model class: {config['model_class']}")
# Move model to device
model.to(self.device)
model.eval() # Set to evaluation mode
# Store model and tokenizer
self.models[model_key] = model
self.tokenizers[model_key] = tokenizer
config["loaded"] = True
logger.info(f"β
Model loaded successfully: {config['model_id']}")
return {
"success": True,
"model_key": model_key,
"model_id": config["model_id"],
"status": "loaded",
"device": self.device,
"task": config["task"]
}
except Exception as e:
logger.error(f"β Failed to load model {model_key}: {e}")
# Don't raise - allow fallback to other models
raise Exception(f"Failed to load model {model_key}: {str(e)}")
async def load_all_models(self) -> Dict[str, Any]:
"""
Load all configured models
Returns:
Status dict with all models
"""
results = []
success_count = 0
for model_key in self.model_configs.keys():
try:
result = await self.load_model(model_key)
results.append(result)
if result["success"]:
success_count += 1
except Exception as e:
logger.error(f"β Failed to load {model_key}: {e}")
results.append({
"success": False,
"model_key": model_key,
"error": str(e)
})
return {
"success": True,
"total_models": len(self.model_configs),
"loaded_models": success_count,
"failed_models": len(self.model_configs) - success_count,
"results": results,
"timestamp": datetime.utcnow().isoformat()
}
async def predict_sentiment(
self,
text: str,
model_key: str = "cryptobert_elkulako",
max_length: int = 512
) -> Dict[str, Any]:
"""
Predict sentiment directly (NO PIPELINE)
Args:
text: Input text
model_key: Model to use
max_length: Maximum sequence length
Returns:
Sentiment prediction
"""
# Ensure model is loaded
if model_key not in self.models:
await self.load_model(model_key)
try:
model = self.models[model_key]
tokenizer = self.tokenizers[model_key]
# Tokenize input - NO PIPELINE
inputs = tokenizer(
text,
return_tensors="pt",
truncation=True,
padding=True,
max_length=max_length
)
# Move inputs to device
inputs = {k: v.to(self.device) for k, v in inputs.items()}
# Forward pass - Direct inference
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
# Get predictions - Direct calculation
probs = torch.softmax(logits, dim=1)
predicted_class = torch.argmax(probs, dim=1).item()
confidence = probs[0][predicted_class].item()
# Map class to label (standard 3-class sentiment)
label_map = {0: "negative", 1: "neutral", 2: "positive"}
# Try to get actual labels from model config
if hasattr(model.config, "id2label"):
label = model.config.id2label.get(predicted_class, label_map.get(predicted_class, "unknown"))
else:
label = label_map.get(predicted_class, "unknown")
# Get all class probabilities
all_probs = {
label_map.get(i, f"class_{i}"): probs[0][i].item()
for i in range(probs.shape[1])
}
logger.info(f"β
Sentiment predicted: {label} (confidence: {confidence:.4f})")
return {
"success": True,
"text": text[:100] + "..." if len(text) > 100 else text,
"sentiment": label,
"label": label,
"score": confidence,
"confidence": confidence,
"all_scores": all_probs,
"model": model_key,
"model_id": self.model_configs[model_key]["model_id"],
"inference_type": "direct_no_pipeline",
"device": self.device,
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β Sentiment prediction failed: {e}")
raise Exception(f"Sentiment prediction failed: {str(e)}")
async def batch_predict_sentiment(
self,
texts: List[str],
model_key: str = "cryptobert_elkulako",
max_length: int = 512
) -> Dict[str, Any]:
"""
Batch sentiment prediction (NO PIPELINE)
Args:
texts: List of input texts
model_key: Model to use
max_length: Maximum sequence length
Returns:
Batch predictions
"""
# Ensure model is loaded
if model_key not in self.models:
await self.load_model(model_key)
try:
model = self.models[model_key]
tokenizer = self.tokenizers[model_key]
# Tokenize all inputs - NO PIPELINE
inputs = tokenizer(
texts,
return_tensors="pt",
truncation=True,
padding=True,
max_length=max_length
)
# Move inputs to device
inputs = {k: v.to(self.device) for k, v in inputs.items()}
# Forward pass - Direct inference
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
# Get predictions - Direct calculation
probs = torch.softmax(logits, dim=1)
predicted_classes = torch.argmax(probs, dim=1).cpu().numpy()
confidences = probs.max(dim=1).values.cpu().numpy()
# Map classes to labels
label_map = {0: "negative", 1: "neutral", 2: "positive"}
# Build results
results = []
for i, text in enumerate(texts):
predicted_class = predicted_classes[i]
confidence = confidences[i]
if hasattr(model.config, "id2label"):
label = model.config.id2label.get(predicted_class, label_map.get(predicted_class, "unknown"))
else:
label = label_map.get(predicted_class, "unknown")
results.append({
"text": text[:100] + "..." if len(text) > 100 else text,
"sentiment": label,
"label": label,
"score": float(confidence),
"confidence": float(confidence)
})
logger.info(f"β
Batch sentiment predicted for {len(texts)} texts")
return {
"success": True,
"count": len(results),
"results": results,
"model": model_key,
"model_id": self.model_configs[model_key]["model_id"],
"inference_type": "direct_batch_no_pipeline",
"device": self.device,
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β Batch sentiment prediction failed: {e}")
raise Exception(f"Batch sentiment prediction failed: {str(e)}")
def get_loaded_models(self) -> Dict[str, Any]:
"""
Get list of loaded models
Returns:
Dict with loaded models info
"""
models_info = []
for model_key, config in self.model_configs.items():
models_info.append({
"model_key": model_key,
"model_id": config["model_id"],
"task": config["task"],
"description": config["description"],
"loaded": model_key in self.models,
"device": self.device if model_key in self.models else None
})
return {
"success": True,
"total_configured": len(self.model_configs),
"total_loaded": len(self.models),
"device": self.device,
"models": models_info,
"timestamp": datetime.utcnow().isoformat()
}
def unload_model(self, model_key: str) -> Dict[str, Any]:
"""
Unload a specific model from memory
Args:
model_key: Key of the model to unload
Returns:
Status dict
"""
if model_key not in self.models:
return {
"success": False,
"model_key": model_key,
"message": "Model not loaded"
}
try:
# Remove model and tokenizer
del self.models[model_key]
del self.tokenizers[model_key]
# Update config
self.model_configs[model_key]["loaded"] = False
# Clear CUDA cache if using GPU
if self.device == "cuda":
torch.cuda.empty_cache()
logger.info(f"β
Model unloaded: {model_key}")
return {
"success": True,
"model_key": model_key,
"message": "Model unloaded successfully"
}
except Exception as e:
logger.error(f"β Failed to unload model {model_key}: {e}")
return {
"success": False,
"model_key": model_key,
"error": str(e)
}
# Global instance
direct_model_loader = DirectModelLoader()
# Export
__all__ = ["DirectModelLoader", "direct_model_loader"]
|