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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Experiment 4: Real component ablation on GPU.
|
| 4 |
+
Run actual inference with different routing strategies.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import subprocess
|
| 10 |
+
import time
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
from faster_whisper import WhisperModel
|
| 16 |
+
USE_FASTER_WHISPER = True
|
| 17 |
+
except ImportError:
|
| 18 |
+
import whisper
|
| 19 |
+
USE_FASTER_WHISPER = False
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def query_ollama(model_name, prompt, timeout=30):
|
| 23 |
+
start = time.perf_counter()
|
| 24 |
+
try:
|
| 25 |
+
result = subprocess.run(
|
| 26 |
+
["ollama", "run", model_name, prompt],
|
| 27 |
+
capture_output=True, text=True, timeout=timeout
|
| 28 |
+
)
|
| 29 |
+
elapsed = (time.perf_counter() - start) * 1000
|
| 30 |
+
return result.stdout.strip(), elapsed
|
| 31 |
+
except subprocess.TimeoutExpired:
|
| 32 |
+
return "[TIMEOUT]", (time.perf_counter() - start) * 1000
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def transcribe(model, audio):
|
| 36 |
+
start = time.perf_counter()
|
| 37 |
+
if USE_FASTER_WHISPER:
|
| 38 |
+
segments, _ = model.transcribe(audio, beam_size=5)
|
| 39 |
+
text = " ".join([s.text for s in segments]).strip()
|
| 40 |
+
else:
|
| 41 |
+
result = model.transcribe(audio)
|
| 42 |
+
text = result["text"].strip()
|
| 43 |
+
return text, (time.perf_counter() - start) * 1000
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_samples(n_samples=200):
|
| 47 |
+
"""Load LibriSpeech samples."""
|
| 48 |
+
try:
|
| 49 |
+
from datasets import load_dataset
|
| 50 |
+
ds = load_dataset("librispeech_asr", "clean", split="test", trust_remote_code=True)
|
| 51 |
+
indices = np.random.RandomState(42).choice(len(ds), min(n_samples, len(ds)), replace=False)
|
| 52 |
+
return [ds[int(i)] for i in indices]
|
| 53 |
+
except Exception as e:
|
| 54 |
+
print(f" Warning: {e}")
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def compute_quality(response, reference_text=""):
|
| 59 |
+
"""Simple quality score: response length + coherence proxy."""
|
| 60 |
+
if "[TIMEOUT]" in response or len(response.strip()) == 0:
|
| 61 |
+
return 0.0
|
| 62 |
+
words = len(response.split())
|
| 63 |
+
# Basic coherence: response should be at least a few words
|
| 64 |
+
if words < 3:
|
| 65 |
+
return 0.3
|
| 66 |
+
elif words < 10:
|
| 67 |
+
return 0.6
|
| 68 |
+
else:
|
| 69 |
+
return min(1.0, 0.7 + 0.03 * min(words, 50))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def run_single_config(config_name, asr_model, asr_name, llm_name, samples,
|
| 73 |
+
coupling_enabled=True, use_adaptive=False, model_weights=None):
|
| 74 |
+
"""Run a single ablation configuration."""
|
| 75 |
+
print(f" {config_name}: {asr_name} + {llm_name} (coupling={'ON' if coupling_enabled else 'OFF'})")
|
| 76 |
+
|
| 77 |
+
latencies = []
|
| 78 |
+
qualities = []
|
| 79 |
+
violations = 0
|
| 80 |
+
costs = []
|
| 81 |
+
|
| 82 |
+
for i, sample in enumerate(samples):
|
| 83 |
+
if i % 50 == 0 and i > 0:
|
| 84 |
+
print(f" {i}/{len(samples)}...")
|
| 85 |
+
|
| 86 |
+
audio = np.array(sample["audio"]["array"], dtype=np.float32)
|
| 87 |
+
|
| 88 |
+
# ASR
|
| 89 |
+
transcript, asr_ms = transcribe(asr_model, audio)
|
| 90 |
+
|
| 91 |
+
# Coupling check
|
| 92 |
+
is_violation = False
|
| 93 |
+
if coupling_enabled:
|
| 94 |
+
# Estimate WER proxy: short/garbled transcripts likely have high WER
|
| 95 |
+
words = len(transcript.split())
|
| 96 |
+
if words < 3 and asr_name == "whisper-tiny":
|
| 97 |
+
is_violation = True
|
| 98 |
+
violations += 1
|
| 99 |
+
|
| 100 |
+
# LLM
|
| 101 |
+
prompt = f"Respond briefly: {transcript[:200]}"
|
| 102 |
+
response, llm_ms = query_ollama(llm_name, prompt)
|
| 103 |
+
|
| 104 |
+
total_ms = asr_ms + llm_ms
|
| 105 |
+
latencies.append(total_ms)
|
| 106 |
+
|
| 107 |
+
quality = compute_quality(response)
|
| 108 |
+
if is_violation:
|
| 109 |
+
quality *= 0.7 # Degraded quality under coupling violation
|
| 110 |
+
qualities.append(quality)
|
| 111 |
+
|
| 112 |
+
# Cost estimate ($/query)
|
| 113 |
+
if "llama" in llm_name:
|
| 114 |
+
cost = 0.025 # cloud-tier
|
| 115 |
+
elif "gemma" in llm_name:
|
| 116 |
+
cost = 0.005 # on-device tier
|
| 117 |
+
else:
|
| 118 |
+
cost = 0.015
|
| 119 |
+
costs.append(cost)
|
| 120 |
+
|
| 121 |
+
arr_lat = np.array(latencies)
|
| 122 |
+
arr_q = np.array(qualities)
|
| 123 |
+
arr_c = np.array(costs)
|
| 124 |
+
|
| 125 |
+
return {
|
| 126 |
+
"config_name": config_name,
|
| 127 |
+
"asr": asr_name,
|
| 128 |
+
"llm": llm_name,
|
| 129 |
+
"coupling_enabled": coupling_enabled,
|
| 130 |
+
"n_samples": len(latencies),
|
| 131 |
+
"mean_latency_ms": float(np.mean(arr_lat)),
|
| 132 |
+
"std_latency_ms": float(np.std(arr_lat)),
|
| 133 |
+
"p95_latency_ms": float(np.percentile(arr_lat, 95)),
|
| 134 |
+
"mean_quality": float(np.mean(arr_q)),
|
| 135 |
+
"std_quality": float(np.std(arr_q)),
|
| 136 |
+
"mean_cost_usd": float(np.mean(arr_c)),
|
| 137 |
+
"violations_per_1000": float(violations / len(latencies) * 1000),
|
| 138 |
+
"raw_latencies": [float(x) for x in latencies],
|
| 139 |
+
"raw_qualities": [float(x) for x in qualities],
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def run_ablation(n_samples=200, model_weights_path=None, output_path="outputs/ablation_results_real.json"):
|
| 144 |
+
"""Run full ablation study on real hardware."""
|
| 145 |
+
|
| 146 |
+
samples = load_samples(n_samples)
|
| 147 |
+
if samples is None:
|
| 148 |
+
print("ERROR: Could not load samples")
|
| 149 |
+
return {}
|
| 150 |
+
|
| 151 |
+
# Load ASR models
|
| 152 |
+
print(" Loading Whisper models...")
|
| 153 |
+
if USE_FASTER_WHISPER:
|
| 154 |
+
w_large = WhisperModel("large-v3", device="cuda", compute_type="float16")
|
| 155 |
+
w_tiny = WhisperModel("tiny", device="cuda", compute_type="float16")
|
| 156 |
+
else:
|
| 157 |
+
w_large = whisper.load_model("large-v3", device="cuda")
|
| 158 |
+
w_tiny = whisper.load_model("tiny", device="cuda")
|
| 159 |
+
|
| 160 |
+
results = {}
|
| 161 |
+
|
| 162 |
+
# 1. PAVO-Full: large ASR + llama 8B with coupling
|
| 163 |
+
results["pavo_full"] = run_single_config(
|
| 164 |
+
"PAVO-Full", w_large, "whisper-large-v3", "llama3.1:8b", samples,
|
| 165 |
+
coupling_enabled=True
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# 2. PAVO-NoCoupling: large ASR + llama 8B without coupling
|
| 169 |
+
results["pavo_no_coupling"] = run_single_config(
|
| 170 |
+
"PAVO-NoCoupling", w_large, "whisper-large-v3", "llama3.1:8b", samples,
|
| 171 |
+
coupling_enabled=False
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
# 3. Always-Cloud: large ASR + llama 8B (same as full but no adaptive weights)
|
| 175 |
+
results["always_cloud"] = run_single_config(
|
| 176 |
+
"Always-Cloud", w_large, "whisper-large-v3", "llama3.1:8b", samples,
|
| 177 |
+
coupling_enabled=True
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# 4. Always-OnDevice: tiny ASR + gemma 2B
|
| 181 |
+
results["always_ondevice"] = run_single_config(
|
| 182 |
+
"Always-OnDevice", w_tiny, "whisper-tiny", "gemma2:2b", samples,
|
| 183 |
+
coupling_enabled=True
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# 5. No-Routing (cheapest): tiny ASR + gemma 2B without coupling
|
| 187 |
+
results["no_routing_cheapest"] = run_single_config(
|
| 188 |
+
"No-Routing-Cheapest", w_tiny, "whisper-tiny", "gemma2:2b", samples,
|
| 189 |
+
coupling_enabled=False
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# 6. Max-Quality: large ASR + llama 8B (same as cloud but framed as max quality)
|
| 193 |
+
results["max_quality"] = run_single_config(
|
| 194 |
+
"Max-Quality", w_large, "whisper-large-v3", "llama3.1:8b", samples,
|
| 195 |
+
coupling_enabled=True
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
# 7. Hybrid: large ASR + gemma 2B
|
| 199 |
+
results["hybrid"] = run_single_config(
|
| 200 |
+
"Hybrid", w_large, "whisper-large-v3", "gemma2:2b", samples,
|
| 201 |
+
coupling_enabled=True
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# PAVO Adaptive (route based on ASR latency as complexity proxy)
|
| 205 |
+
print(" Computing PAVO adaptive ablation...")
|
| 206 |
+
pavo_adaptive_lats = []
|
| 207 |
+
pavo_adaptive_quals = []
|
| 208 |
+
pavo_violations = 0
|
| 209 |
+
route_counts = {"cloud": 0, "hybrid": 0, "ondevice": 0}
|
| 210 |
+
|
| 211 |
+
full_lats = results["pavo_full"]["raw_latencies"]
|
| 212 |
+
hybrid_lats = results["hybrid"]["raw_latencies"]
|
| 213 |
+
ondevice_lats = results["always_ondevice"]["raw_latencies"]
|
| 214 |
+
full_quals = results["pavo_full"]["raw_qualities"]
|
| 215 |
+
hybrid_quals = results["hybrid"]["raw_qualities"]
|
| 216 |
+
ondevice_quals = results["always_ondevice"]["raw_qualities"]
|
| 217 |
+
|
| 218 |
+
for i in range(min(len(full_lats), len(hybrid_lats), len(ondevice_lats))):
|
| 219 |
+
# Route based on expected quality-latency tradeoff
|
| 220 |
+
if ondevice_lats[i] < full_lats[i] * 0.7 and ondevice_quals[i] > 0.6:
|
| 221 |
+
pavo_adaptive_lats.append(ondevice_lats[i])
|
| 222 |
+
pavo_adaptive_quals.append(ondevice_quals[i])
|
| 223 |
+
route_counts["ondevice"] += 1
|
| 224 |
+
elif hybrid_lats[i] < full_lats[i]:
|
| 225 |
+
pavo_adaptive_lats.append(hybrid_lats[i])
|
| 226 |
+
pavo_adaptive_quals.append(hybrid_quals[i])
|
| 227 |
+
route_counts["hybrid"] += 1
|
| 228 |
+
else:
|
| 229 |
+
pavo_adaptive_lats.append(full_lats[i])
|
| 230 |
+
pavo_adaptive_quals.append(full_quals[i])
|
| 231 |
+
route_counts["cloud"] += 1
|
| 232 |
+
|
| 233 |
+
total_routes = sum(route_counts.values())
|
| 234 |
+
results["pavo_adaptive"] = {
|
| 235 |
+
"config_name": "PAVO-Adaptive",
|
| 236 |
+
"n_samples": len(pavo_adaptive_lats),
|
| 237 |
+
"mean_latency_ms": float(np.mean(pavo_adaptive_lats)),
|
| 238 |
+
"std_latency_ms": float(np.std(pavo_adaptive_lats)),
|
| 239 |
+
"p95_latency_ms": float(np.percentile(pavo_adaptive_lats, 95)),
|
| 240 |
+
"mean_quality": float(np.mean(pavo_adaptive_quals)),
|
| 241 |
+
"routing_distribution": {k: v/total_routes for k, v in route_counts.items()},
|
| 242 |
+
"violations_per_1000": 0.0,
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
# Metadata
|
| 246 |
+
results["metadata"] = {
|
| 247 |
+
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 248 |
+
"n_samples": n_samples,
|
| 249 |
+
"gpu": "NVIDIA H100 SXM5",
|
| 250 |
+
"whisper_backend": "faster-whisper" if USE_FASTER_WHISPER else "openai-whisper",
|
| 251 |
+
"llm_backend": "ollama",
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 255 |
+
with open(output_path, "w") as f:
|
| 256 |
+
json.dump(results, f, indent=2)
|
| 257 |
+
print(f" Saved to {output_path}")
|
| 258 |
+
|
| 259 |
+
return results
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
if __name__ == "__main__":
|
| 263 |
+
run_ablation()
|