Download detailed_test.py from SetMD/beastbullet-experts: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/SetMD/beastbullet-experts/resolve/main/detailed_test.py
- Command line
-
hf download hf://SetMD/beastbullet-experts/detailed_test.py
-
curl -L -o detailed_test.py https://huggingface.co/SetMD/beastbullet-experts/resolve/main/detailed_test.py
18.6 kB
| #!/usr/bin/env python3 | |
| """ | |
| BeastBullet Detailed Performance Test Suite | |
| Complete stats logging and documentation | |
| """ | |
| import subprocess | |
| import json | |
| import time | |
| import datetime | |
| import sys | |
| import os | |
| from pathlib import Path | |
| from typing import Dict, List, Tuple | |
| class DetailedPerformanceTest: | |
| """Comprehensive performance testing with detailed logging""" | |
| def __init__(self, experts_dir="experts/"): | |
| self.experts_dir = Path(experts_dir) | |
| self.log_file = f"test_log_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" | |
| self.stats_file = f"test_stats_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.json" | |
| self.report_file = f"test_report_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.md" | |
| self.all_stats = { | |
| "test_start_time": datetime.datetime.now().isoformat(), | |
| "system_info": {}, | |
| "expert_models": {}, | |
| "test_results": [], | |
| "summary": {} | |
| } | |
| self.log("=" * 80) | |
| self.log("BeastBullet Detailed Performance Test Suite") | |
| self.log("=" * 80) | |
| self.log(f"Test started at: {datetime.datetime.now()}") | |
| self.log(f"Log file: {self.log_file}") | |
| self.log(f"Stats file: {self.stats_file}") | |
| self.log(f"Report file: {self.report_file}") | |
| def log(self, message: str, level: str = "INFO"): | |
| """Log message to both console and file""" | |
| timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] | |
| log_line = f"[{timestamp}] [{level}] {message}" | |
| print(log_line) | |
| with open(self.log_file, "a") as f: | |
| f.write(log_line + "\n") | |
| def collect_system_info(self): | |
| """Collect detailed system information""" | |
| self.log("\n" + "=" * 80) | |
| self.log("COLLECTING SYSTEM INFORMATION") | |
| self.log("=" * 80) | |
| system_info = {} | |
| # CPU info | |
| try: | |
| cpu_count = subprocess.run(["nproc"], capture_output=True, text=True).stdout.strip() | |
| system_info["cpu_cores"] = int(cpu_count) | |
| self.log(f"CPU Cores: {cpu_count}") | |
| except: | |
| system_info["cpu_cores"] = "unknown" | |
| self.log("CPU Cores: unknown") | |
| # Memory info | |
| try: | |
| mem_info = subprocess.run(["free", "-h"], capture_output=True, text=True).stdout | |
| self.log(f"Memory Info:\n{mem_info}") | |
| system_info["memory_info"] = mem_info | |
| except: | |
| self.log("Memory Info: unavailable") | |
| # Python version | |
| python_version = sys.version | |
| system_info["python_version"] = python_version | |
| self.log(f"Python Version: {python_version}") | |
| # Ollama version | |
| try: | |
| ollama_version = subprocess.run(["ollama", "--version"], capture_output=True, text=True).stdout.strip() | |
| system_info["ollama_version"] = ollama_version | |
| self.log(f"Ollama Version: {ollama_version}") | |
| except: | |
| system_info["ollama_version"] = "unknown" | |
| self.log("Ollama Version: unknown") | |
| # TinyLlama status | |
| try: | |
| ollama_list = subprocess.run(["ollama", "list"], capture_output=True, text=True).stdout | |
| system_info["ollama_models"] = ollama_list | |
| self.log(f"Ollama Models:\n{ollama_list}") | |
| except: | |
| self.log("Ollama Models: unavailable") | |
| self.all_stats["system_info"] = system_info | |
| return system_info | |
| def discover_experts(self): | |
| """Discover and catalog all expert models""" | |
| self.log("\n" + "=" * 80) | |
| self.log("DISCOVERING EXPERT MODELS") | |
| self.log("=" * 80) | |
| expert_files = list(self.experts_dir.glob("*_expert_v1.0.pt")) | |
| experts = {} | |
| total_size = 0 | |
| for f in expert_files: | |
| name = f.stem.replace("_v1.0", "") | |
| size_bytes = f.stat().st_size | |
| size_mb = size_bytes / (1024 * 1024) | |
| total_size += size_mb | |
| experts[name] = { | |
| "path": str(f), | |
| "size_bytes": size_bytes, | |
| "size_mb": round(size_mb, 2), | |
| "modified": datetime.datetime.fromtimestamp(f.stat().st_mtime).isoformat() | |
| } | |
| self.log(f"Found: {name} ({size_mb:.2f} MB)") | |
| self.log(f"\nTotal experts: {len(experts)}") | |
| self.log(f"Total size: {total_size:.2f} MB") | |
| self.all_stats["expert_models"] = { | |
| "count": len(experts), | |
| "total_size_mb": round(total_size, 2), | |
| "models": experts | |
| } | |
| return experts | |
| def load_config(self): | |
| """Load and validate configuration""" | |
| self.log("\n" + "=" * 80) | |
| self.log("LOADING CONFIGURATION") | |
| self.log("=" * 80) | |
| try: | |
| with open("configs/config_sonnet_quality.json") as f: | |
| config = json.load(f) | |
| self.log("Loaded config_sonnet_quality.json") | |
| self.log(f"Config: {json.dumps(config, indent=2)}") | |
| except Exception as e: | |
| self.log(f"Could not load config: {e}", "WARNING") | |
| config = self._default_config() | |
| self.log("Using default configuration") | |
| self.all_stats["configuration"] = config | |
| return config | |
| def _default_config(self): | |
| """Default Sonnet-quality configuration""" | |
| return { | |
| "router": {"confidence_threshold": 0.85, "cache_size": 20000}, | |
| "validator": {"mode": "strict", "accuracy_target": 0.90}, | |
| "evidence": {"min_sources": 2}, | |
| "reasoning": {"chain_of_thought": True}, | |
| "performance": { | |
| "num_threads": 4, | |
| "max_memory_mb": 4096, | |
| "enable_onnx_optimization": True | |
| } | |
| } | |
| def route_experts(self, query: str, available_experts: Dict) -> List[str]: | |
| """Route query to appropriate experts""" | |
| query_lower = query.lower() | |
| selected = [] | |
| if any(w in query_lower for w in ["calculate", "math", "%", "percent", "+"]): | |
| if "math_expert" in available_experts: | |
| selected.append("math_expert") | |
| if any(w in query_lower for w in ["if", "implies", "conclude", "logic", "therefore"]): | |
| if "logic_expert" in available_experts: | |
| selected.append("logic_expert") | |
| if any(w in query_lower for w in ["code", "function", "python", "javascript", "write"]): | |
| if "code_generation_expert" in available_experts: | |
| selected.append("code_generation_expert") | |
| if any(w in query_lower for w in ["translate", "language"]): | |
| if "translation_expert" in available_experts: | |
| selected.append("translation_expert") | |
| if any(w in query_lower for w in ["sentiment", "emotion", "feeling"]): | |
| if "sentiment_expert" in available_experts: | |
| selected.append("sentiment_expert") | |
| if not selected and "question_answering_expert" in available_experts: | |
| selected.append("question_answering_expert") | |
| if "validator_expert" in available_experts: | |
| selected.append("validator_expert") | |
| return selected | |
| def query_tinyllama(self, prompt: str, timeout: int = 45) -> Tuple[str, float, bool]: | |
| """Query TinyLlama and measure performance""" | |
| start_time = time.time() | |
| success = True | |
| try: | |
| result = subprocess.run( | |
| ["ollama", "run", "tinyllama", prompt], | |
| capture_output=True, | |
| text=True, | |
| timeout=timeout | |
| ) | |
| answer = result.stdout.strip() | |
| if result.returncode != 0: | |
| answer = f"Error: {result.stderr}" | |
| success = False | |
| except subprocess.TimeoutExpired: | |
| answer = f"Timeout after {timeout}s" | |
| success = False | |
| except Exception as e: | |
| answer = f"Error: {str(e)}" | |
| success = False | |
| latency = time.time() - start_time | |
| return answer, latency, success | |
| def run_single_test(self, query: str, experts: Dict, config: Dict, test_num: int, total_tests: int): | |
| """Run a single test query with detailed logging""" | |
| self.log("\n" + "=" * 80) | |
| self.log(f"TEST {test_num}/{total_tests}") | |
| self.log("=" * 80) | |
| self.log(f"Query: {query}") | |
| test_start = time.time() | |
| # Route to experts | |
| selected_experts = self.route_experts(query, experts) | |
| self.log(f"Selected experts: {', '.join(selected_experts)}") | |
| # Build prompt | |
| prompt = f"""You are a helpful AI assistant with expert analysis capabilities. | |
| Question: {query} | |
| Expert Analysis Available: | |
| """ | |
| for expert in selected_experts: | |
| prompt += f"\n- {expert}: Ready for analysis" | |
| prompt += f""" | |
| Configuration: | |
| - Confidence threshold: {config.get('router', {}).get('confidence_threshold', 0.85)} | |
| - Chain-of-thought: Enabled | |
| - Validator: Strict mode | |
| - Evidence sources: Minimum {config.get('evidence', {}).get('min_sources', 2)} | |
| Provide a clear, accurate answer with step-by-step reasoning:""" | |
| self.log(f"Prompt length: {len(prompt)} characters") | |
| self.log("Querying TinyLlama...") | |
| # Query TinyLlama | |
| answer, latency, success = self.query_tinyllama(prompt) | |
| # Calculate metrics | |
| confidence = 0.95 if len(selected_experts) >= 2 and success else 0.75 | |
| quality_score = self._calculate_quality(answer, selected_experts, success) | |
| # Log results | |
| self.log(f"\nAnswer ({len(answer)} chars):") | |
| self.log(answer[:500] + ("..." if len(answer) > 500 else "")) | |
| self.log(f"\nMetrics:") | |
| self.log(f" Latency: {latency:.2f}s") | |
| self.log(f" Success: {success}") | |
| self.log(f" Confidence: {confidence:.0%}") | |
| self.log(f" Quality Score: {quality_score:.0%}") | |
| self.log(f" Experts Used: {len(selected_experts)}") | |
| # Store results | |
| test_result = { | |
| "test_number": test_num, | |
| "query": query, | |
| "selected_experts": selected_experts, | |
| "prompt_length": len(prompt), | |
| "answer": answer, | |
| "answer_length": len(answer), | |
| "latency_seconds": round(latency, 2), | |
| "success": success, | |
| "confidence": confidence, | |
| "quality_score": quality_score, | |
| "timestamp": datetime.datetime.now().isoformat() | |
| } | |
| self.all_stats["test_results"].append(test_result) | |
| return test_result | |
| def _calculate_quality(self, answer: str, experts: List[str], success: bool) -> float: | |
| """Calculate quality score""" | |
| if not success: | |
| return 0.5 | |
| score = 0.7 | |
| if len(experts) >= 2: | |
| score += 0.1 | |
| if "validator_expert" in experts: | |
| score += 0.1 | |
| if len(answer) > 50: | |
| score += 0.05 | |
| if "error" not in answer.lower() and "timeout" not in answer.lower(): | |
| score += 0.05 | |
| return min(score, 0.95) | |
| def run_comprehensive_tests(self): | |
| """Run comprehensive test suite""" | |
| self.log("\n" + "=" * 80) | |
| self.log("RUNNING COMPREHENSIVE TEST SUITE") | |
| self.log("=" * 80) | |
| # Collect system info | |
| self.collect_system_info() | |
| # Discover experts | |
| experts = self.discover_experts() | |
| # Load config | |
| config = self.load_config() | |
| # Define test queries | |
| test_queries = [ | |
| # Math tests | |
| "What is 15% of 240?", | |
| "Calculate 25% of 500", | |
| "What is 3.14 * 2.5?", | |
| # Logic tests | |
| "If A implies B, and B implies C, what can we conclude?", | |
| "All cats are mammals. Fluffy is a cat. What is Fluffy?", | |
| # Code tests | |
| "Write a Python function to reverse a string", | |
| "How do you sort a list in Python?", | |
| # General knowledge | |
| "What is machine learning?", | |
| "Explain the water cycle", | |
| # Sentiment | |
| "Analyze the sentiment: I love this product!", | |
| ] | |
| self.log(f"\nTotal test queries: {len(test_queries)}") | |
| # Run tests | |
| for i, query in enumerate(test_queries, 1): | |
| self.run_single_test(query, experts, config, i, len(test_queries)) | |
| # Save intermediate results | |
| self._save_stats() | |
| # Calculate summary | |
| self._calculate_summary() | |
| # Generate report | |
| self._generate_report() | |
| self.log("\n" + "=" * 80) | |
| self.log("TEST SUITE COMPLETE") | |
| self.log("=" * 80) | |
| def _calculate_summary(self): | |
| """Calculate summary statistics""" | |
| self.log("\n" + "=" * 80) | |
| self.log("CALCULATING SUMMARY STATISTICS") | |
| self.log("=" * 80) | |
| results = self.all_stats["test_results"] | |
| if not results: | |
| self.log("No test results to summarize") | |
| return | |
| total_tests = len(results) | |
| successful_tests = sum(1 for r in results if r["success"]) | |
| total_latency = sum(r["latency_seconds"] for r in results) | |
| avg_latency = total_latency / total_tests | |
| avg_confidence = sum(r["confidence"] for r in results) / total_tests | |
| avg_quality = sum(r["quality_score"] for r in results) / total_tests | |
| summary = { | |
| "total_tests": total_tests, | |
| "successful_tests": successful_tests, | |
| "failed_tests": total_tests - successful_tests, | |
| "success_rate": round(successful_tests / total_tests, 2), | |
| "total_latency_seconds": round(total_latency, 2), | |
| "average_latency_seconds": round(avg_latency, 2), | |
| "min_latency_seconds": round(min(r["latency_seconds"] for r in results), 2), | |
| "max_latency_seconds": round(max(r["latency_seconds"] for r in results), 2), | |
| "average_confidence": round(avg_confidence, 2), | |
| "average_quality_score": round(avg_quality, 2), | |
| "test_end_time": datetime.datetime.now().isoformat() | |
| } | |
| self.all_stats["summary"] = summary | |
| self.log(f"Total Tests: {summary['total_tests']}") | |
| self.log(f"Successful: {summary['successful_tests']}") | |
| self.log(f"Failed: {summary['failed_tests']}") | |
| self.log(f"Success Rate: {summary['success_rate']:.0%}") | |
| self.log(f"Average Latency: {summary['average_latency_seconds']:.2f}s") | |
| self.log(f"Average Confidence: {summary['average_confidence']:.0%}") | |
| self.log(f"Average Quality: {summary['average_quality_score']:.0%}") | |
| def _save_stats(self): | |
| """Save statistics to JSON file""" | |
| with open(self.stats_file, "w") as f: | |
| json.dump(self.all_stats, f, indent=2) | |
| def _generate_report(self): | |
| """Generate markdown report""" | |
| self.log("\n" + "=" * 80) | |
| self.log("GENERATING MARKDOWN REPORT") | |
| self.log("=" * 80) | |
| report = f"""# BeastBullet Detailed Performance Test Report | |
| **Generated:** {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} | |
| --- | |
| ## Summary | |
| | Metric | Value | | |
| |--------|-------| | |
| | Total Tests | {self.all_stats['summary']['total_tests']} | | |
| | Successful | {self.all_stats['summary']['successful_tests']} | | |
| | Failed | {self.all_stats['summary']['failed_tests']} | | |
| | Success Rate | {self.all_stats['summary']['success_rate']:.0%} | | |
| | Average Latency | {self.all_stats['summary']['average_latency_seconds']:.2f}s | | |
| | Min Latency | {self.all_stats['summary']['min_latency_seconds']:.2f}s | | |
| | Max Latency | {self.all_stats['summary']['max_latency_seconds']:.2f}s | | |
| | Average Confidence | {self.all_stats['summary']['average_confidence']:.0%} | | |
| | Average Quality Score | {self.all_stats['summary']['average_quality_score']:.0%} | | |
| --- | |
| ## System Information | |
| - **CPU Cores:** {self.all_stats['system_info'].get('cpu_cores', 'unknown')} | |
| - **Python Version:** {self.all_stats['system_info'].get('python_version', 'unknown')} | |
| - **Ollama Version:** {self.all_stats['system_info'].get('ollama_version', 'unknown')} | |
| --- | |
| ## Expert Models | |
| - **Total Experts:** {self.all_stats['expert_models']['count']} | |
| - **Total Size:** {self.all_stats['expert_models']['total_size_mb']:.2f} MB | |
| ### Available Experts | |
| """ | |
| for name, info in sorted(self.all_stats['expert_models']['models'].items()): | |
| report += f"\n- **{name}**: {info['size_mb']:.2f} MB" | |
| report += "\n\n---\n\n## Test Results\n\n" | |
| for result in self.all_stats['test_results']: | |
| status = "✅" if result['success'] else "❌" | |
| report += f""" | |
| ### Test {result['test_number']}: {status} | |
| **Query:** {result['query']} | |
| **Metrics:** | |
| - Latency: {result['latency_seconds']:.2f}s | |
| - Confidence: {result['confidence']:.0%} | |
| - Quality Score: {result['quality_score']:.0%} | |
| - Experts Used: {', '.join(result['selected_experts'])} | |
| **Answer:** {result['answer'][:300]}{"..." if len(result['answer']) > 300 else ""} | |
| --- | |
| """ | |
| report += f""" | |
| ## Files Generated | |
| - **Log File:** `{self.log_file}` | |
| - **Stats File:** `{self.stats_file}` | |
| - **Report File:** `{self.report_file}` | |
| --- | |
| **Test completed at:** {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} | |
| """ | |
| with open(self.report_file, "w") as f: | |
| f.write(report) | |
| self.log(f"Report saved to: {self.report_file}") | |
| def main(): | |
| """Run detailed performance test""" | |
| tester = DetailedPerformanceTest("experts/") | |
| tester.run_comprehensive_tests() | |
| print("\n" + "=" * 80) | |
| print("✅ DETAILED PERFORMANCE TEST COMPLETE") | |
| print("=" * 80) | |
| print(f"\n📄 Files generated:") | |
| print(f" - Log: {tester.log_file}") | |
| print(f" - Stats (JSON): {tester.stats_file}") | |
| print(f" - Report (Markdown): {tester.report_file}") | |
| print("\n") | |
| if __name__ == "__main__": | |
| main() | |