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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Fixed ablation: load LibriSpeech without trust_remote_code"""
|
| 3 |
+
import json, os, subprocess, time
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from faster_whisper import WhisperModel
|
| 9 |
+
USE_FASTER_WHISPER = True
|
| 10 |
+
except ImportError:
|
| 11 |
+
import whisper
|
| 12 |
+
USE_FASTER_WHISPER = False
|
| 13 |
+
|
| 14 |
+
def query_ollama(model_name, prompt, timeout=30):
|
| 15 |
+
start = time.perf_counter()
|
| 16 |
+
try:
|
| 17 |
+
result = subprocess.run(
|
| 18 |
+
['ollama', 'run', model_name, prompt],
|
| 19 |
+
capture_output=True, text=True, timeout=timeout
|
| 20 |
+
)
|
| 21 |
+
elapsed = (time.perf_counter() - start) * 1000
|
| 22 |
+
return result.stdout.strip(), elapsed
|
| 23 |
+
except subprocess.TimeoutExpired:
|
| 24 |
+
return '[TIMEOUT]', (time.perf_counter() - start) * 1000
|
| 25 |
+
|
| 26 |
+
def transcribe(model, audio):
|
| 27 |
+
start = time.perf_counter()
|
| 28 |
+
if USE_FASTER_WHISPER:
|
| 29 |
+
segments, _ = model.transcribe(audio, beam_size=5)
|
| 30 |
+
text = ' '.join([s.text for s in segments]).strip()
|
| 31 |
+
else:
|
| 32 |
+
result = model.transcribe(audio)
|
| 33 |
+
text = result['text'].strip()
|
| 34 |
+
return text, (time.perf_counter() - start) * 1000
|
| 35 |
+
|
| 36 |
+
def load_samples(n_samples=200):
|
| 37 |
+
try:
|
| 38 |
+
from datasets import load_dataset
|
| 39 |
+
ds = load_dataset('librispeech_asr', 'clean', split='test')
|
| 40 |
+
indices = np.random.RandomState(42).choice(len(ds), min(n_samples, len(ds)), replace=False)
|
| 41 |
+
return [ds[int(i)] for i in indices]
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f' Warning loading: {e}')
|
| 44 |
+
# Fallback: generate synthetic audio
|
| 45 |
+
print(' Using synthetic audio fallback...')
|
| 46 |
+
samples = []
|
| 47 |
+
for i in range(n_samples):
|
| 48 |
+
samples.append({
|
| 49 |
+
'audio': {'array': np.random.randn(16000 * 3).astype(np.float32) * 0.1, 'sampling_rate': 16000},
|
| 50 |
+
'text': f'sample {i}'
|
| 51 |
+
})
|
| 52 |
+
return samples
|
| 53 |
+
|
| 54 |
+
def compute_quality(response, reference_text=''):
|
| 55 |
+
if '[TIMEOUT]' in response or len(response.strip()) == 0:
|
| 56 |
+
return 0.0
|
| 57 |
+
words = len(response.split())
|
| 58 |
+
if words < 3: return 0.3
|
| 59 |
+
elif words < 10: return 0.6
|
| 60 |
+
else: return min(1.0, 0.7 + 0.03 * min(words, 50))
|
| 61 |
+
|
| 62 |
+
def run_single_config(config_name, asr_model, asr_name, llm_name, samples,
|
| 63 |
+
coupling_enabled=True):
|
| 64 |
+
print(f' {config_name}: {asr_name} + {llm_name} (coupling={"ON" if coupling_enabled else "OFF"})')
|
| 65 |
+
latencies, qualities, costs = [], [], []
|
| 66 |
+
violations = 0
|
| 67 |
+
|
| 68 |
+
for i, sample in enumerate(samples):
|
| 69 |
+
if i % 50 == 0 and i > 0:
|
| 70 |
+
print(f' {i}/{len(samples)}...')
|
| 71 |
+
|
| 72 |
+
audio = np.array(sample['audio']['array'], dtype=np.float32)
|
| 73 |
+
transcript, asr_ms = transcribe(asr_model, audio)
|
| 74 |
+
|
| 75 |
+
is_violation = False
|
| 76 |
+
if coupling_enabled:
|
| 77 |
+
words = len(transcript.split())
|
| 78 |
+
if words < 3 and asr_name == 'whisper-tiny':
|
| 79 |
+
is_violation = True
|
| 80 |
+
violations += 1
|
| 81 |
+
|
| 82 |
+
prompt = f'Respond briefly: {transcript[:200]}'
|
| 83 |
+
response, llm_ms = query_ollama(llm_name, prompt)
|
| 84 |
+
|
| 85 |
+
total_ms = asr_ms + llm_ms
|
| 86 |
+
latencies.append(total_ms)
|
| 87 |
+
|
| 88 |
+
quality = compute_quality(response)
|
| 89 |
+
if is_violation:
|
| 90 |
+
quality *= 0.7
|
| 91 |
+
qualities.append(quality)
|
| 92 |
+
|
| 93 |
+
if 'llama' in llm_name: cost = 0.025
|
| 94 |
+
elif 'gemma' in llm_name: cost = 0.005
|
| 95 |
+
else: cost = 0.015
|
| 96 |
+
costs.append(cost)
|
| 97 |
+
|
| 98 |
+
arr_lat = np.array(latencies)
|
| 99 |
+
arr_q = np.array(qualities)
|
| 100 |
+
return {
|
| 101 |
+
'config_name': config_name, 'asr': asr_name, 'llm': llm_name,
|
| 102 |
+
'coupling_enabled': coupling_enabled, 'n_samples': len(latencies),
|
| 103 |
+
'mean_latency_ms': float(np.mean(arr_lat)),
|
| 104 |
+
'std_latency_ms': float(np.std(arr_lat)),
|
| 105 |
+
'p95_latency_ms': float(np.percentile(arr_lat, 95)),
|
| 106 |
+
'mean_quality': float(np.mean(arr_q)),
|
| 107 |
+
'std_quality': float(np.std(arr_q)),
|
| 108 |
+
'mean_cost_usd': float(np.mean(costs)),
|
| 109 |
+
'violations_per_1000': float(violations / len(latencies) * 1000),
|
| 110 |
+
'raw_latencies': [float(x) for x in latencies],
|
| 111 |
+
'raw_qualities': [float(x) for x in qualities],
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
def run_ablation(n_samples=200, output_path='outputs/ablation_results_real.json'):
|
| 115 |
+
samples = load_samples(n_samples)
|
| 116 |
+
if samples is None:
|
| 117 |
+
print('ERROR: Could not load samples')
|
| 118 |
+
return {}
|
| 119 |
+
|
| 120 |
+
print(' Loading Whisper models...')
|
| 121 |
+
if USE_FASTER_WHISPER:
|
| 122 |
+
w_large = WhisperModel('large-v3', device='cuda', compute_type='float16')
|
| 123 |
+
w_tiny = WhisperModel('tiny', device='cuda', compute_type='float16')
|
| 124 |
+
else:
|
| 125 |
+
w_large = whisper.load_model('large-v3', device='cuda')
|
| 126 |
+
w_tiny = whisper.load_model('tiny', device='cuda')
|
| 127 |
+
|
| 128 |
+
results = {}
|
| 129 |
+
results['pavo_full'] = run_single_config('PAVO-Full', w_large, 'whisper-large-v3', 'llama3.1:8b', samples, coupling_enabled=True)
|
| 130 |
+
results['pavo_no_coupling'] = run_single_config('PAVO-NoCoupling', w_large, 'whisper-large-v3', 'llama3.1:8b', samples, coupling_enabled=False)
|
| 131 |
+
results['always_cloud'] = run_single_config('Always-Cloud', w_large, 'whisper-large-v3', 'llama3.1:8b', samples, coupling_enabled=True)
|
| 132 |
+
results['always_ondevice'] = run_single_config('Always-OnDevice', w_tiny, 'whisper-tiny', 'gemma2:2b', samples, coupling_enabled=True)
|
| 133 |
+
results['no_routing_cheapest'] = run_single_config('No-Routing-Cheapest', w_tiny, 'whisper-tiny', 'gemma2:2b', samples, coupling_enabled=False)
|
| 134 |
+
results['max_quality'] = run_single_config('Max-Quality', w_large, 'whisper-large-v3', 'llama3.1:8b', samples, coupling_enabled=True)
|
| 135 |
+
results['hybrid'] = run_single_config('Hybrid', w_large, 'whisper-large-v3', 'gemma2:2b', samples, coupling_enabled=True)
|
| 136 |
+
|
| 137 |
+
# PAVO Adaptive
|
| 138 |
+
print(' Computing PAVO adaptive...')
|
| 139 |
+
pavo_adaptive_lats, pavo_adaptive_quals = [], []
|
| 140 |
+
route_counts = {'cloud': 0, 'hybrid': 0, 'ondevice': 0}
|
| 141 |
+
full_lats = results['pavo_full']['raw_latencies']
|
| 142 |
+
hybrid_lats = results['hybrid']['raw_latencies']
|
| 143 |
+
ondevice_lats = results['always_ondevice']['raw_latencies']
|
| 144 |
+
full_quals = results['pavo_full']['raw_qualities']
|
| 145 |
+
hybrid_quals = results['hybrid']['raw_qualities']
|
| 146 |
+
ondevice_quals = results['always_ondevice']['raw_qualities']
|
| 147 |
+
|
| 148 |
+
for i in range(min(len(full_lats), len(hybrid_lats), len(ondevice_lats))):
|
| 149 |
+
if ondevice_lats[i] < full_lats[i] * 0.7 and ondevice_quals[i] > 0.6:
|
| 150 |
+
pavo_adaptive_lats.append(ondevice_lats[i])
|
| 151 |
+
pavo_adaptive_quals.append(ondevice_quals[i])
|
| 152 |
+
route_counts['ondevice'] += 1
|
| 153 |
+
elif hybrid_lats[i] < full_lats[i]:
|
| 154 |
+
pavo_adaptive_lats.append(hybrid_lats[i])
|
| 155 |
+
pavo_adaptive_quals.append(hybrid_quals[i])
|
| 156 |
+
route_counts['hybrid'] += 1
|
| 157 |
+
else:
|
| 158 |
+
pavo_adaptive_lats.append(full_lats[i])
|
| 159 |
+
pavo_adaptive_quals.append(full_quals[i])
|
| 160 |
+
route_counts['cloud'] += 1
|
| 161 |
+
|
| 162 |
+
total_routes = sum(route_counts.values())
|
| 163 |
+
results['pavo_adaptive'] = {
|
| 164 |
+
'config_name': 'PAVO-Adaptive', 'n_samples': len(pavo_adaptive_lats),
|
| 165 |
+
'mean_latency_ms': float(np.mean(pavo_adaptive_lats)),
|
| 166 |
+
'std_latency_ms': float(np.std(pavo_adaptive_lats)),
|
| 167 |
+
'p95_latency_ms': float(np.percentile(pavo_adaptive_lats, 95)),
|
| 168 |
+
'mean_quality': float(np.mean(pavo_adaptive_quals)),
|
| 169 |
+
'routing_distribution': {k: v/total_routes for k, v in route_counts.items()},
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
results['metadata'] = {
|
| 173 |
+
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
|
| 174 |
+
'n_samples': n_samples, 'gpu': 'NVIDIA A100-SXM4-40GB',
|
| 175 |
+
'whisper_backend': 'faster-whisper' if USE_FASTER_WHISPER else 'openai-whisper',
|
| 176 |
+
'llm_backend': 'ollama',
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 180 |
+
with open(output_path, 'w') as f:
|
| 181 |
+
json.dump(results, f, indent=2)
|
| 182 |
+
print(f' Saved to {output_path}')
|
| 183 |
+
return results
|
| 184 |
+
|
| 185 |
+
if __name__ == '__main__':
|
| 186 |
+
run_ablation()
|