Biswajeet Arukha commited on
Commit ·
a3e599f
1
Parent(s): dccc3ae
Deep Prediction Upgrade: Transformer, MLflow, and MiroFish Multi-Agent Simulation
Browse filesFiles changed (7)
3 unmodified lines4567891011121314151617181914 unmodified lines34353637383974 unmodified lines1141151161171181191201211221231241251261273 unmodified linesimport asyncioimport loggingimport redisfrom fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewarefrom typing import List, Dict, Optionalfrom backend.ml_engine.hybrid_model import RealTimePredictor# Environment ConfigREDIS_HOST = os.getenv("REDIS_HOST", "localhost")REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))REDIS_DB = int(os.getenv("REDIS_DB", 0))REDIS_PASSWORD = os.getenv("REDIS_PASSWORD", None)# Logging configurationlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')14 unmodified linesallow_headers=["*"],)# Global Predictor Instancepredictor: Optional[RealTimePredictor] = None74 unmodified linesraise HTTPException(status_code=503, detail="ML Engine not initialized")try:result = predictor.predict_live_match(match_id)if 'error' in result:raise HTTPException(status_code=404, detail=result['error'])return resultexcept Exception as e:logger.error(f"Prediction Error for {match_id}: {e}")raise HTTPException(status_code=500, detail="Internal inference error")@app.websocket("/ws/predictions/{match_id}")async def websocket_prediction(websocket: WebSocket, match_id: str):"""Real-time prediction stream via WebSocket"""3 unmodified lines456789101112131415161714 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818274 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981993 unmodified linesimport asyncioimport loggingimport redisimport randomimport numpy as npfrom fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewarefrom typing import List, Dict, Optionalfrom pydantic import BaseModelfrom backend.ml_engine.hybrid_model import RealTimePredictorfrom backend.ml_engine.agent_sim import MultiAgentSimulator# Logging configurationlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')14 unmodified linesallow_headers=["*"],)# Enrichment Layersagent_swarm = MultiAgentSimulator(num_agents=10)class SimulationRequest(BaseModel):num_simulations: int = 1000overs_to_project: int = 5captain_policy: str = "aggressive" # aggressive, balanced, defensiveclass MatchSimulator:"""Monte Carlo engine for match projection"""def project_future(self, current_state: Dict, num_sims: int, overs: int, policy: str):results = []for _ in range(num_sims):temp_runs = 0temp_wickets = 0for _ in range(overs * 6): # ball by ball# Simple probabilistic transition (can be improved with Transformer)if policy == "aggressive":outcome = random.choices([0,1,2,4,6,'W'], weights=[35,20,10,15,10,10])[0]else:outcome = random.choices([0,1,2,4,6,'W'], weights=[50,25,10,5,5,5])[0]if outcome == 'W':temp_wickets += 1if temp_wickets + current_state.get('total_wickets', 0) >= 10:breakelse:temp_runs += outcomeresults.append((temp_runs, temp_wickets))runs_dist = [r for r, w in results]return {"projected_runs_avg": float(np.mean(runs_dist)),"projected_wickets_avg": float(np.mean([w for r, w in results])),"confidence_interval": [float(np.percentile(runs_dist, 5)), float(np.percentile(runs_dist, 95))]}match_sim = MatchSimulator()# Environment ConfigREDIS_HOST = os.getenv("REDIS_HOST", "localhost")REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))REDIS_DB = int(os.getenv("REDIS_DB", 0))REDIS_PASSWORD = os.getenv("REDIS_PASSWORD", None)# Global Predictor Instancepredictor: Optional[RealTimePredictor] = None74 unmodified linesraise HTTPException(status_code=503, detail="ML Engine not initialized")try:prediction = predictor.predict_live_match(match_id)# Enrich with Multi-Agent Simulation features (MiroFish-style)# We use current match data as seed for the swarmagent_features = agent_swarm.simulate(prediction if "error" not in prediction else {})prediction.update(agent_features)if "error" in prediction:raise HTTPException(status_code=404, detail=prediction["error"])return predictionexcept Exception as e:logger.error(f"Prediction Error for {match_id}: {e}")raise HTTPException(status_code=500, detail="Internal inference error")@app.post("/simulate/{match_id}")async def run_what_if_simulation(match_id: str, request: SimulationRequest):"""Project future match outcomes using Monte Carlo simulations.Allows testing 'What If' tactical scenarios."""prediction = predictor.predict_live_match(match_id)if "error" in prediction:raise HTTPException(status_code=404, detail="No live data to simulate from")projection = match_sim.project_future(prediction,request.num_simulations,request.overs_to_project,request.captain_policy)return {"match_id": match_id,"current_state": prediction,"projection": projection}@app.websocket("/ws/predictions/{match_id}")async def websocket_prediction(websocket: WebSocket, match_id: str):"""Real-time prediction stream via WebSocket"""
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import osimport loggingimport numpy as npimport tweepyfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzerfrom typing import Dict, List, Optional
# Logging configurationlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)
class SentimentPipeline: """Real-time sentiment analyzer for social media match reports.""" def __init__(self, consumer_key: str = None, consumer_secret: str = None, access_token: str = None, access_token_secret: str = None): self.analyzer = SentimentIntensityAnalyzer() self.api = None # Initialize Twitter API if keys are provided consumer_key = consumer_key or os.getenv("TWITTER_CONSUMER_KEY") consumer_secret = consumer_secret or os.getenv("TWITTER_CONSUMER_SECRET") access_token = access_token or os.getenv("TWITTER_ACCESS_TOKEN") access_token_secret = access_token_secret or os.getenv("TWITTER_ACCESS_TOKEN_SECRET") if all([consumer_key, consumer_secret, access_token, access_token_secret]): try: auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) self.api = tweepy.API(auth) logger.info("✅ Twitter API connection established.") except Exception as e: logger.error(f"❌ Failed to connect to Twitter API: {e}") else: logger.warning("⚠️ Twitter API keys missing. Sentiment will use mock random data.")
def get_match_sentiment(self, hashtag: str = "#IPL2024") -> Dict[str, float]: """Scrape latest 100 tweets and return aggregate sentiment.""" if not self.api: # Mock data for demonstration when offline/unauthenticated return { 'sentiment_score': float(np.random.uniform(0.3, 0.8)), 'sentiment_volatility': float(np.random.uniform(0.05, 0.2)) } try: # Search tweets with the given hashtag tweets = self.api.search_tweets(q=hashtag, count=100, lang='en', result_type='recent') scores = [] for tweet in tweets: # VADER: compound score (-1.0 to 1.0) sentiment = self.analyzer.polarity_scores(tweet.text)['compound'] scores.append(sentiment) if not scores: return {'sentiment_score': 0.0, 'sentiment_volatility': 0.0} return { 'sentiment_score': float(np.mean(scores)), 'sentiment_volatility': float(np.std(scores)) } except Exception as e: logger.error(f"❌ Sentiment analysis failed: {e}") return {'sentiment_score': 0.0, 'sentiment_volatility': 0.0}
class MomentumMonitor: """Combines sentiment and simulation scores into a unified momentum feature.""" def __init__(self): # We integrate the MiroFish sentiment signal into our RealTimePredictor pass12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import osimport randomimport loggingimport numpy as npfrom openai import OpenAIfrom typing import Dict, List, Optional
# Logging configurationlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)
class CricketAnalystAgent: """An AI agent representing a specific cricket analyst archetype.""" def __init__(self, bias_type: str, client: Optional[OpenAI] = None): self.bias_type = bias_type # e.g., 'pitch_focused', 'form_focused', 'tactical' self.client = client
def analyze(self, match_state: Dict) -> float: """Return a sentiment/confidence score [0-1] based on the agent's bias.""" if self.client: try: # LLM-based analysis for high-fidelity qualitative signal prompt = self._build_prompt(match_state) response = self.client.completions.create( model="gpt-3.5-turbo-instruct", prompt=prompt, max_tokens=60, temperature=0.7 ) text = response.choices[0].text.strip().lower() # Simple sentiment heuristic if any(word in text for word in ["high", "confident", "easy", "dominant"]): return 0.85 elif any(word in text for word in ["low", "worried", "struggle", "collapse"]): return 0.25 else: return 0.5 except Exception as e: logger.warning(f"LLM Agent ({self.bias_type}) failed: {e}. Falling back to simulation.") # Fallback deterministic simulation based on match state return self._simulate_score(match_state)
def _build_prompt(self, match_state: Dict) -> str: return (f"As a cricket analyst specializing in {self.bias_type}, analyze this IPL match state: " f"{match_state}. Does the batting team look dominant or under pressure? " f"Give a short 1-sentence analysis and a confidence score.")
def _simulate_score(self, match_state: Dict) -> float: """Heuristic-based fallback logic to ensure speed when API is unavailable.""" if self.bias_type == 'pitch_focused': # Pitch focus: Confidence high if runs are being scored crr = match_state.get('crr', 6.0) return 0.8 if crr > 9.0 else 0.4 elif self.bias_type == 'form_focused': # Form focus: Confidence high if few wickets lost wickets = match_state.get('total_wickets', 0) return 0.9 if wickets < 2 else 0.4 elif self.bias_type == 'momentum_analyst': # Momentum focus: Recent runs recent_runs = match_state.get('runs_last_6', 6) return 0.85 if recent_runs > 12 else 0.35 return 0.5
class MultiAgentSimulator: """Manages a swarm of analysts to extract emergent confidence features.""" def __init__(self, num_agents: int = 10, api_key: Optional[str] = None): self.num_agents = num_agents self.api_key = api_key or os.getenv("OPENAI_API_KEY") self.client = OpenAI(api_key=self.api_key) if self.api_key else None self.biases = ['pitch_focused', 'form_focused', 'momentum_analyst', 'tactical_observer', 'collapse_historian'] self.agents = [CricketAnalystAgent(random.choice(self.biases), self.client) for _ in range(num_agents)]
def simulate(self, match_state: Dict) -> Dict[str, float]: """Aggregate analysis scores into aggregate ensemble features.""" scores = [agent.analyze(match_state) for agent in self.agents] # We extract two key metrics for the XGBoost model # 1. Agent Confidence: The average sentiment across the swarm # 2. Agent Disagreement (Entropy): The standard deviation (uncertainty) return { 'agent_confidence': float(np.mean(scores)), 'agent_disagreement': float(np.std(scores)) }40 unmodified lines414243444546393 unmodified lines44044144244344444519 unmodified lines465466467468469470103 unmodified lines57457557657757857940 unmodified lineslstm_num_layers: int = 2lstm_dropout: float = 0.3sequence_length: int = 18 # Last 18 balls# Training paramsbatch_size: int = 64393 unmodified lines# Initialize modelsself.xgb_model: Optional[xgb.XGBClassifier] = Noneself.lstm_model: Optional[MomentumLSTM] = None# Scalersself.static_scaler = StandardScaler()19 unmodified lines)return model.to(self.device)def train_xgb(self,X_train: np.ndarray,y_train: np.ndarray,103 unmodified linesself.lstm_model.load_state_dict(torch.load('best_lstm.pth'))logger.info("LSTM training complete")def _validate_lstm(self,val_sequences: np.ndarray,val_labels: np.ndarray,40 unmodified lines41424344454647484950515253393 unmodified lines44744844945045145245319 unmodified lines473474475476477478479480481482483484485486487488489490103 unmodified lines59459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265340 unmodified lineslstm_num_layers: int = 2lstm_dropout: float = 0.3sequence_length: int = 18 # Last 18 balls# Transformer params (New)use_transformer: bool = Truetransformer_d_model: int = 128transformer_nhead: int = 8transformer_num_layers: int = 3transformer_dim_feedforward: int = 256transformer_dropout: float = 0.1# Training paramsbatch_size: int = 64393 unmodified lines# Initialize modelsself.xgb_model: Optional[xgb.XGBClassifier] = Noneself.lstm_model: Optional[MomentumLSTM] = Noneself.transformer_model: Optional[TransformerModel] = None# Scalersself.static_scaler = StandardScaler()19 unmodified lines)return model.to(self.device)def build_transformer_model(self) -> TransformerModel:"""Build Transformer model for sequence features"""model = TransformerModel(input_dim=3,d_model=self.config.transformer_d_model,nhead=self.config.transformer_nhead,num_layers=self.config.transformer_num_layers,dim_feedforward=self.config.transformer_dim_feedforward,dropout=self.config.transformer_dropout)return model.to(self.device)def train_xgb(self,X_train: np.ndarray,y_train: np.ndarray,103 unmodified linesself.lstm_model.load_state_dict(torch.load('best_lstm.pth'))logger.info("LSTM training complete")def train_transformer(self,train_sequences: np.ndarray,train_labels: np.ndarray,val_sequences: Optional[np.ndarray] = None,val_labels: Optional[np.ndarray] = None):"""Train Transformer model"""logger.info("Training Transformer model...")self.transformer_model = self.build_transformer_model()train_dataset = SequenceDataset(train_sequences, train_labels)train_loader = DataLoader(train_dataset, batch_size=self.config.batch_size, shuffle=True)criterion = nn.BCEWithLogitsLoss()optimizer = torch.optim.Adam(self.transformer_model.parameters(), lr=self.config.learning_rate)best_val_loss = float('inf')for epoch in range(self.config.num_epochs):self.transformer_model.train()for batch_seq, batch_labels in train_loader:batch_seq = batch_seq.to(self.device)batch_labels = batch_labels.to(self.device)optimizer.zero_grad()features = self.transformer_model(batch_seq)predictions = features[:, 0]loss = criterion(predictions, batch_labels.float())loss.backward()optimizer.step()if val_sequences is not None:val_loss = self._validate_transformer(val_sequences, val_labels, criterion)if val_loss < best_val_loss:best_val_loss = val_losstorch.save(self.transformer_model.state_dict(), 'best_transformer.pth')self.transformer_model.load_state_dict(torch.load('best_transformer.pth'))logger.info("Transformer training complete")def _validate_transformer(self,val_sequences: np.ndarray,val_labels: np.ndarray,criterion) -> float:self.transformer_model.eval()val_loader = DataLoader(SequenceDataset(val_sequences, val_labels), batch_size=self.config.batch_size)total_loss = 0.0with torch.no_grad():for seq, labels in val_loader:seq, labels = seq.to(self.device), labels.to(self.device)features = self.transformer_model(seq)loss = criterion(features[:, 0], labels.float())total_loss += loss.item()return total_loss / len(val_loader)def _validate_lstm(self,val_sequences: np.ndarray,val_labels: np.ndarray,
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import networkx as nximport loggingimport pickleimport osfrom typing import Dict, List, Optional, Tuple
# Logging configurationlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)
class CricketKnowledgeGraph: """GraphRAG-style knowledge base for deep matchup historical memory.""" def __init__(self, storage_path: str = "models/matchup_graph.pkl"): self.graph = nx.MultiDiGraph() self.storage_path = storage_path # Load existing graph if available if os.path.exists(self.storage_path): try: with open(self.storage_path, 'rb') as f: self.graph = pickle.load(f) logger.info(f"✅ Loaded Knowledge Graph with {self.graph.number_of_nodes()} nodes.") except Exception as e: logger.warning(f"❌ Failed to load Knowledge Graph from {self.storage_path}: {e}. Creating new.")
def add_matchup_event(self, batsman: str, bowler: str, runs: int, wicket: bool, context: Dict): """Adds a single ball outcome between batsman and bowler as an edge.""" # Clean labels batsman, bowler = batsman.strip(), bowler.strip() # Add edge with attributes self.graph.add_edge( bowler, batsman, runs=runs, wicket=wicket, venue=context.get('venue', 'N/A'), match_id=context.get('match_id', 'N/A') )
def query_matchup_stats(self, batsman: str, bowler: str) -> Dict[str, float]: """Expressed as [Bowler -> Batsman] edges. Returns statistical summary.""" batsman, bowler = batsman.strip(), bowler.strip() if not self.graph.has_edge(bowler, batsman): return { 'matchup_count': 0, 'avg_runs_per_ball': 0.0, 'wicket_rate': 0.0, 'dominance_index': 0.5 # Neutral index } # Extract edge data edge_data = self.graph.get_edge_data(bowler, batsman) balls = len(edge_data) runs = sum(e['runs'] for e in edge_data.values()) wickets = sum(1 for e in edge_data.values() if e['wicket']) # Dominance Heuristic: High if batsman dominates bowler # (Average runs per ball vs Wicket frequency) avg_runs = runs / balls wicket_freq = wickets / balls # Dominance Index: 1.0 (Batsman dominates), 0.0 (Bowler dominates) dominance = (avg_runs / 2.0) - (wicket_freq * 10.0) dominance = max(0.0, min(1.0, 0.5 + dominance)) # Clamped between 0 and 1 return { 'matchup_count': balls, 'avg_runs_per_ball': avg_runs, 'wicket_rate': wicket_freq, 'dominance_index': dominance }
def save(self): """Persist the graph to disk.""" os.makedirs(os.path.dirname(self.storage_path), exist_ok=True) with open(self.storage_path, 'wb') as f: pickle.dump(self.graph, f) logger.info(f"✅ Knowledge Graph saved to {self.storage_path}.")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import osimport timeimport loggingfrom datetime import datetimefrom pathlib import Pathfrom backend.ml_engine.train_efficient import train_efficiently
# Logging configurationlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)
# ConfigurationDATA_DIR = os.getenv("DATA_DIR", "data")CHECK_INTERVAL = int(os.getenv("CHECK_INTERVAL", 3600)) # 1 hourLAST_CHECK_FILE = "backend/ml_engine/last_retrain.txt"
def get_last_retrain_time(): """Read the last successfull retrain timestamp""" if not os.path.exists(LAST_CHECK_FILE): return datetime.min try: with open(LAST_CHECK_FILE, 'r') as f: return datetime.fromisoformat(f.read().strip()) except Exception as e: logger.warning(f"Could not read last_retrain file: {e}") return datetime.min
def update_last_retrain_time(): """Save the current timestamp as the last retrain time""" with open(LAST_CHECK_FILE, 'w') as f: f.write(datetime.now().isoformat())
def check_for_new_data(last_time): """Scan the data directory for any files modified after last_time""" new_files = [] # Search for JSON match files for file in Path(DATA_DIR).glob("**/*.json"): mod_time = datetime.fromtimestamp(file.stat().st_mtime) if mod_time > last_time: new_files.append(file) return new_files
def main_loop(): logger.info(f"🚀 Starting Automated Retraining Service (Watching: {DATA_DIR})") while True: last_retrain = get_last_retrain_time() new_data = check_for_new_data(last_retrain) if new_data: logger.info(f"📈 Found {len(new_data)} new match files! Triggering retraining pipeline...") try: # Trigger the efficient training pipeline train_efficiently(data_dir=DATA_DIR) update_last_retrain_time() logger.info("✅ Retraining complete and model updated.") except Exception as e: logger.error(f"❌ Retraining failed: {e}") else: logger.info("😴 No new data found. Sleeping...") time.sleep(CHECK_INTERVAL)
if __name__ == "__main__": main_loop()8 unmodified lines9101112131450 unmodified lines65666768697053 unmodified lines12412512612712812931 unmodified lines1611621631641651661671681691701711721738 unmodified linesfrom torch.utils.data import IterableDataset, DataLoaderimport xgboost as xgbfrom sklearn.model_selection import train_test_splitfrom hybrid_model import HybridEnsemble, ModelConfig, CricsheetNormalizerlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')50 unmodified linesconfig = ModelConfig()ensemble = HybridEnsemble(config)# 1. Get all JSON files (matches)all_files = glob.glob(os.path.join(data_dir, '*.json'))if not all_files:53 unmodified lineselse:xgb_model = xgb.train(params, dtrain, num_boost_round=10, xgb_model=xgb_model)# Free memory!del chunk_dfs, combined_df, static_features, X_chunk, y_chunk, dtraingc.collect()31 unmodified linesbatch_count += 1if batch_count % 100 == 0:logger.info(f"LSTM Batch {batch_count}: Loss = {loss.item():.4f}")gc.collect() # Periodically clean garbage within epoch# Save the modelslogger.info("Training complete! Saving models...")os.makedirs('models', exist_ok=True)ensemble.save_models('models/hybrid_ensemble')if __name__ == "__main__":import argparseparser = argparse.ArgumentParser(description="Memory-Efficient Training Pipeline")8 unmodified lines9101112131415161750 unmodified lines686970717273747576777879808182838485868753 unmodified lines14114214314414514614714814931 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272288 unmodified linesfrom torch.utils.data import IterableDataset, DataLoaderimport xgboost as xgbfrom sklearn.model_selection import train_test_splitimport mlflowimport mlflow.pytorchimport mlflow.xgboostfrom hybrid_model import HybridEnsemble, ModelConfig, CricsheetNormalizerlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')50 unmodified linesconfig = ModelConfig()ensemble = HybridEnsemble(config)# Initialize MLflowmlflow.set_experiment("IPL_Prediction_Engine_V2")with mlflow.start_run(run_name=f"Hybrid_Train_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}"):# Log Hyperparametersmlflow.log_params({"xgb_max_depth": config.xgb_params['max_depth'],"xgb_lr": config.xgb_params['learning_rate'],"lstm_hidden": config.lstm_hidden_size,"transformer_layers": config.transformer_num_layers,"batch_size": config.batch_size,"learning_rate": config.learning_rate})# 1. Get all JSON files (matches)all_files = glob.glob(os.path.join(data_dir, '*.json'))if not all_files:53 unmodified lineselse:xgb_model = xgb.train(params, dtrain, num_boost_round=10, xgb_model=xgb_model)# Log XGBoost status to MLflowmlflow.log_metric("xgb_chunk_processed", i//chunk_size + 1)# Free memory!del chunk_dfs, combined_df, static_features, X_chunk, y_chunk, dtraingc.collect()31 unmodified linesbatch_count += 1if batch_count % 100 == 0:logger.info(f"LSTM Batch {batch_count}: Loss = {loss.item():.4f}")mlflow.log_metric("lstm_loss", loss.item(), step=batch_count)gc.collect() # Periodically clean garbage within epoch# ---------------------------------------------------------# PART C: Streaming Training for PyTorch Transformer# ---------------------------------------------------------logger.info("Starting Transformer Streaming Training...")ensemble.transformer_model = ensemble.build_transformer_model()t_optimizer = torch.optim.Adam(ensemble.transformer_model.parameters(), lr=config.learning_rate)ensemble.transformer_model.train()t_batch_count = 0t_loader = DataLoader(train_dataset, batch_size=config.batch_size)for seq, label in t_loader:seq, label = seq.to(ensemble.device), label.to(ensemble.device)t_optimizer.zero_grad()features = ensemble.transformer_model(seq)predictions = features[:, 0]loss = criterion(predictions, label.squeeze())loss.backward()t_optimizer.step()t_batch_count += 1if t_batch_count % 100 == 0:logger.info(f"Transformer Batch {t_batch_count}: Loss = {loss.item():.4f}")mlflow.log_metric("transformer_loss", loss.item(), step=t_batch_count)gc.collect()# Save the modelslogger.info("Training complete! Saving models...")os.makedirs('models', exist_ok=True)ensemble.save_models('models/hybrid_ensemble')# Log models to MLflowmlflow.xgboost.log_model(ensemble.xgb_model, "xgb_static")mlflow.pytorch.log_model(ensemble.lstm_model, "lstm_sequence")mlflow.pytorch.log_model(ensemble.transformer_model, "transformer_attention")if __name__ == "__main__":import argparseparser = argparse.ArgumentParser(description="Memory-Efficient Training Pipeline")
backend/api_server.py+82-10
backend/data_pipeline/sentiment_pipeline.pyAdded+74
backend/ml_engine/agent_sim.pyAdded+88
backend/ml_engine/hybrid_model.py+74
backend/ml_engine/knowledge_graph.pyAdded+80
backend/ml_engine/retrain_service.pyAdded+67
backend/ml_engine/train_efficient.py+55