-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_3.py
More file actions
568 lines (450 loc) Β· 17.5 KB
/
Copy pathscript_3.py
File metadata and controls
568 lines (450 loc) Β· 17.5 KB
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# Create comprehensive README.md
readme_content = '''# O3 (Ozone) - Ollama Open-Source Optimizer



**Hardware-focused performance optimization suite for Ollama models, designed for agentic workflows and maximum context utilization.**
## π― Purpose
O3 (Ozone) is a comprehensive testing suite that optimizes Ollama model configurations for:
- **Maximum stable context windows** for agentic workflows
- **Optimal throughput** (tokens/second) on your specific hardware
- **Minimal time-to-first-token** (TTFT) for responsive applications
- **Resource utilization** tracking and optimization
- **Reproducible benchmarking** with detailed logging
### Why O3?
- **Hardware-First Approach:** Optimizes for your specific GPU/CPU configuration
- **Agentic Workflow Ready:** Maximizes context length for tool traces and memory
- **Production Ready:** Provides stable, tested configurations
- **Team Friendly:** Generates shareable logs and reports
- **Extensible:** Easy to add new models and test scenarios
## π Quick Start
### Installation
```bash
# Clone or download the O3 suite files
# Install dependencies
pip install -r requirements.txt
# Verify Ollama is running
ollama list
```
### Basic Usage
```bash
# Test a single model
python o3_optimizer.py qwen3-coder:30b
# Test multiple models
python o3_optimizer.py qwen3-coder:30b gemma3:latest
# Test all your models
python o3_optimizer.py qwen3-coder:30b orieg/gemma3-tools:27b-it-qat liquid-rag:latest qwen2.5:3b-instruct gemma3:latest
# Generate comprehensive report
python o3_report_generator.py --csv
```
### VS Code Integration
Use Ctrl+Shift+P β "Tasks: Run Task" β Select O3 task:
- **O3: Test Single Model** - Interactive model selection
- **O3: Test All Coding Models** - Optimize coding-focused models
- **O3: Full Test Suite** - Test all supported models
- **O3: Generate Summary Report** - Create markdown report
## π What O3 Tests
### Optimization Parameters
| Parameter | Purpose | Tested Values |
|-----------|---------|---------------|
| `num_ctx` | Context window size | 4096, 8192, 12288, 16384, 24576, 32768 |
| `batch` | Batch size for processing | 8, 16, 32 |
| `f16_kv` | KV cache precision | true, false |
| `num_predict` | Output token limit | 256, 512 |
| `num_thread` | CPU threads | Physical core count |
### Measured Metrics
- **Time to First Token (TTFT)** - Response latency
- **Tokens per Second** - Throughput
- **VRAM Usage** - GPU memory consumption
- **RAM Usage** - System memory consumption
- **Stability** - Success rate across concurrent runs
- **Context Limits** - Maximum stable context window
## ποΈ Architecture
```
O3 (Ozone) Test Suite
βββ o3_optimizer.py # Main test runner
βββ o3_report_generator.py # Report and analysis generator
βββ requirements.txt # Python dependencies
βββ .vscode/
β βββ tasks.json # VS Code integration
β βββ launch.json # Debug configurations
βββ o3_results/ # Generated results
βββ logs/ # Detailed JSONL logs
βββ summaries/ # Per-model JSON summaries
βββ defaults/ # Recommended YAML configs
βββ env/ # System environment snapshots
```
## π Model-Specific Configurations
O3 includes optimized test grids for common models:
### Large Coding Models (27B-30B)
- **Models:** `qwen3-coder:30b`, `orieg/gemma3-tools:27b-it-qat`
- **Focus:** Maximum context for complex code generation
- **Batch Sizes:** 8, 16 (VRAM conscious)
- **Context Range:** 4096 β 32768 tokens
### RAG Models
- **Models:** `liquid-rag:latest`
- **Focus:** Fast retrieval and response generation
- **Batch Sizes:** 16, 32
- **Context Range:** 8192 β 32768 tokens
### Chat/Instruct Models (3B-8B)
- **Models:** `qwen2.5:3b-instruct`, `gemma3:latest`
- **Focus:** Balanced performance and context
- **Batch Sizes:** 16, 32
- **Context Range:** 4096 β 32768 tokens
## π§ Advanced Usage
### Custom Model Testing
```bash
# Test custom model with specific concurrency levels
python o3_optimizer.py my-custom-model:latest --concurrency 1 2 4
# Save to custom directory
python o3_optimizer.py model-name --output-dir custom_results
```
### Programmatic Usage
```python
from o3_optimizer import OllamaOptimizer
optimizer = OllamaOptimizer("results")
results = optimizer.test_model("qwen3-coder:30b")
optimizer.save_results("qwen3-coder:30b", results)
```
### Configuration Customization
Edit the `generate_test_configs()` method in `o3_optimizer.py` to:
- Add new models with custom parameter grids
- Modify context window ranges
- Adjust batch size options
- Change test repetition counts
## π Understanding Results
### Output Files
#### `defaults/model_name.yaml`
```yaml
model: qwen3-coder:30b
presets:
max_ctx:
num_ctx: 16384 # Maximum stable context
batch: 16
f16_kv: true
tokens_per_sec: 12.5
fast_ctx:
num_ctx: 8192 # Optimized for speed
batch: 16
f16_kv: true
tokens_per_sec: 18.3
```
#### `summaries/model_name.json`
```json
{
"model": "qwen3-coder:30b",
"total_tests": 48,
"successful_tests": 42,
"max_ctx_preset": { ... },
"fast_ctx_preset": { ... }
}
```
#### `logs/model_name.jsonl`
```json
{"timestamp": "...", "model": "...", "config": {...}, "ttft_ms": 850, "tokens_per_sec": 12.5, ...}
{"timestamp": "...", "model": "...", "config": {...}, "ttft_ms": 1200, "tokens_per_sec": 8.3, ...}
```
### Performance Interpretation
**Tokens/Second:**
- **>20 tok/s** - Excellent for real-time applications
- **10-20 tok/s** - Good for most interactive use cases
- **5-10 tok/s** - Acceptable for batch processing
- **<5 tok/s** - Consider reducing context or using smaller model
**Time to First Token:**
- **<500ms** - Excellent responsiveness
- **500-1000ms** - Good for interactive use
- **1-2s** - Acceptable for most applications
- **>2s** - Consider optimizing for faster preset
## π― Integration Examples
### Use with Ollama API
```python
import requests
# Use O3 optimized settings
response = requests.post('http://localhost:11434/api/generate', json={
"model": "qwen3-coder:30b",
"prompt": "Generate a Python class for...",
"options": {
"num_ctx": 16384, # From O3 max_ctx preset
"batch": 16,
"f16_kv": True,
"num_predict": 512,
"temperature": 0.2,
"top_p": 0.95
}
})
```
### Use in LangChain
```python
from langchain_community.llms import Ollama
# Initialize with O3 optimized parameters
llm = Ollama(
model="qwen3-coder:30b",
num_ctx=16384, # Max context from O3
batch_size=16,
f16_kv=True,
temperature=0.2
)
```
### Use in Agentic Frameworks
O3 settings are particularly valuable for:
- **AutoGPT/AgentGPT** - Long conversation history
- **LangGraph** - Multi-step tool usage
- **CrewAI** - Complex multi-agent interactions
- **Custom RAG** - Large document contexts
## π Troubleshooting
### Common Issues
**"CUDA out of memory" / "ROCm out of memory"**
```bash
# Use smaller batch sizes
python o3_optimizer.py model-name # Will test smaller batches first
```
**Slow performance**
```bash
# Check system resources
nvidia-smi # or rocm-smi
htop
```
**Model not found**
```bash
# Pull model first
ollama pull qwen3-coder:30b
ollama list
```
### Performance Tuning
1. **Thermal Throttling:** Monitor GPU temperature during extended tests
2. **Memory Pressure:** Close other applications before testing
3. **Driver Issues:** Update GPU drivers if experiencing crashes
4. **Concurrent Usage:** Avoid running other Ollama instances during tests
## π CI/CD Integration
### GitHub Actions Example
```yaml
name: O3 Model Optimization
on:
schedule:
- cron: '0 2 * * 0' # Weekly optimization runs
jobs:
optimize:
runs-on: self-hosted
steps:
- uses: actions/checkout@v3
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run O3 optimization
run: python o3_optimizer.py qwen3-coder:30b
- name: Generate report
run: python o3_report_generator.py --csv
- name: Upload results
uses: actions/upload-artifact@v3
with:
name: o3-results
path: o3_results/
```
## π€ Contributing
O3 is designed to be extended and customized:
1. **Add New Models:** Update `generate_test_configs()` with model-specific parameters
2. **Add Metrics:** Extend `TestResult` class and monitoring
3. **Add Test Types:** Create specialized test scenarios
4. **Improve Reporting:** Enhance markdown and CSV output formats
## π License
MIT License - Feel free to use in educational and commercial projects.
## π Support
- **Issues:** Hardware-specific optimization problems
- **Features:** New model support, additional metrics
- **Integration:** Help with agentic frameworks and production deployment
---
**Built for educators, developers, and AI practitioners who need reliable, optimized model performance.**
*Optimize once, deploy confidently.*
'''
with open("README.md", "w") as f:
f.write(readme_content)
print("Created README.md")
# Create quick start script
quickstart_code = '''#!/usr/bin/env python3
"""
O3 Quick Start - Automated setup and initial test
"""
import subprocess
import sys
import os
from pathlib import Path
def run_command(cmd, description):
"""Run a command and handle errors"""
print(f"\\nπ {description}...")
try:
result = subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
print(f"β
{description} completed successfully")
return True
except subprocess.CalledProcessError as e:
print(f"β {description} failed: {e}")
if e.stdout:
print(f"Output: {e.stdout}")
if e.stderr:
print(f"Error: {e.stderr}")
return False
def check_prerequisites():
"""Check if required tools are installed"""
print("π Checking prerequisites...")
# Check Python version
if sys.version_info < (3, 7):
print("β Python 3.7+ required")
return False
print(f"β
Python {sys.version}")
# Check if Ollama is installed and running
if not run_command("ollama --version", "Check Ollama installation"):
print("β Ollama not found. Please install from https://ollama.ai")
return False
if not run_command("ollama list", "Check Ollama service"):
print("β Ollama service not running. Please start with 'ollama serve'")
return False
return True
def install_dependencies():
"""Install Python dependencies"""
return run_command("pip install -r requirements.txt", "Install Python dependencies")
def detect_models():
"""Detect available models"""
try:
result = subprocess.run("ollama list", shell=True, capture_output=True, text=True, check=True)
lines = result.stdout.strip().split('\\n')[1:] # Skip header
models = []
target_models = [
"qwen3-coder:30b", "orieg/gemma3-tools:27b-it-qat",
"liquid-rag:latest", "qwen2.5:3b-instruct", "gemma3:latest"
]
for line in lines:
if line.strip():
model_name = line.split()[0]
if model_name in target_models:
models.append(model_name)
return models
except subprocess.CalledProcessError:
return []
def run_sample_test(models):
"""Run a sample optimization test"""
if not models:
print("β No supported models found")
return False
# Use smallest available model for quick test
test_model = models[0]
print(f"\\nπ§ͺ Running sample test with {test_model}...")
return run_command(f"python o3_optimizer.py {test_model} --concurrency 1",
f"Sample optimization test")
def generate_sample_report():
"""Generate a sample report"""
return run_command("python o3_report_generator.py --csv", "Generate sample report")
def main():
print("""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β O3 (Ozone) Quick Start β
β Ollama Open-Source Optimizer β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
""")
# Check prerequisites
if not check_prerequisites():
print("\\nβ Prerequisites check failed. Please resolve issues and try again.")
return 1
# Install dependencies
if not install_dependencies():
print("\\nβ Failed to install dependencies.")
return 1
# Detect models
print("\\nπ Detecting available models...")
available_models = detect_models()
if available_models:
print(f"β
Found {len(available_models)} supported models:")
for model in available_models:
print(f" - {model}")
else:
print("β οΈ No supported models found. You may need to pull models first:")
print(" ollama pull qwen2.5:3b-instruct")
print(" ollama pull gemma3:latest")
# Offer to run sample test
if available_models:
response = input(f"\\nβ Run sample optimization test with {available_models[0]}? (y/N): ").lower()
if response in ['y', 'yes']:
if run_sample_test(available_models):
print("\\nπ Sample test completed successfully!")
# Generate report
if generate_sample_report():
print("\\nπ Sample report generated!")
# Show next steps
print(f"""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Next Steps β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
β 1. Check results in 'o3_results/' directory β
β 2. View the generated report: O3_Report_*.md β
β 3. Check optimized settings: o3_results/defaults/ β
β 4. Run full test suite: β
β python o3_optimizer.py {' '.join(available_models[:3])} β
β β
β π VS Code users: Use Ctrl+Shift+P β "Tasks: Run Task" β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
""")
else:
print("β οΈ Report generation failed, but test data is available")
else:
print("β Sample test failed")
else:
print("\\nSetup complete! Run 'python o3_optimizer.py <model-name>' to start optimizing.")
print("\\nβ
O3 Quick Start completed!")
return 0
if __name__ == "__main__":
sys.exit(main())
'''
with open("quickstart.py", "w") as f:
f.write(quickstart_code)
print("Created quickstart.py")
# Create example configuration file
example_config = '''# Example O3 Configuration
# This file shows how to customize O3 for your specific needs
# Custom model configurations
CUSTOM_MODEL_CONFIGS = {
"my-model:7b": {
"num_ctx": [4096, 8192, 16384],
"batch": [16, 32],
"f16_kv": [True],
"num_predict": [256, 512]
},
"my-large-model:30b": {
"num_ctx": [4096, 8192, 12288], # Smaller range for large models
"batch": [8, 16], # Smaller batches for VRAM constraints
"f16_kv": [True, False], # Test both precisions
"num_predict": [256]
}
}
# Test settings
DEFAULT_CONCURRENCY_LEVELS = [1, 2]
DEFAULT_REPETITIONS = 3
DEFAULT_TIMEOUT = 90 # seconds
# Hardware-specific settings
AMD_GPU_SETTINGS = {
"monitor_command": "rocm-smi --showmemuse --csv"
}
NVIDIA_GPU_SETTINGS = {
"monitor_command": "nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits"
}
# Output settings
OUTPUT_FORMATS = ["jsonl", "yaml", "csv"]
GENERATE_PLOTS = False # Set to True if matplotlib available
# Safety settings
MAX_VRAM_USAGE_PERCENT = 90
MAX_RAM_USAGE_PERCENT = 85
TEMPERATURE_THRESHOLD = 85 # Celsius
'''
with open("o3_config.py", "w") as f:
f.write(example_config)
print("Created o3_config.py (example configuration)")
print("\\nπ O3 (Ozone) Test Suite - All Materials Created!")
print("\\nFiles created:")
print("- o3_optimizer.py (main test runner)")
print("- o3_report_generator.py (report generator)")
print("- requirements.txt (Python dependencies)")
print("- quickstart.py (automated setup)")
print("- README.md (comprehensive documentation)")
print("- o3_config.py (example configuration)")
print("- .vscode/tasks.json (VS Code integration)")
print("- .vscode/launch.json (debugging configuration)")
print("\\nTo get started:")
print("1. Run: python quickstart.py")
print("2. Or manually: pip install -r requirements.txt")
print("3. Then: python o3_optimizer.py <model-name>")