import streamlit as st import torch import torchvision import time import numpy as np from PIL import Image import matplotlib.pyplot as plt from model_utils import load_model, preprocess_image, get_class_names import os st.set_page_config( page_title="Resource Adaptive Inference", layout="wide", initial_sidebar_state="expanded" ) st.markdown(""" """, unsafe_allow_html=True) def entropy_bits(p): p = np.asarray(p) + 1e-12 return float(-np.sum(p * np.log2(p))) def gini_impurity(p): return float(1.0 - np.sum(np.asarray(p) ** 2)) def prediction_margin(p): s = np.sort(np.asarray(p))[::-1] return float(s[0] - s[1]) def top_k_classes(p, names, k=3): idx = np.argsort(p)[::-1][:k] return [(names[i], float(p[i])) for i in idx] def concentration_ratio(p, k=5): return float(np.sum(np.sort(np.asarray(p))[::-1][:k])) def effective_classes(p): return float(2 ** entropy_bits(p)) @st.cache_resource def load_demo_model(): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") path = os.path.join(os.path.dirname(__file__), 'cifar_100_early_exit.pth') return load_model(path, device), device @st.cache_resource def load_cifar_test(): tf = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)) ]) return torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=tf) model, device = load_demo_model() testset = load_cifar_test() class_names = get_class_names() _defaults = { "sample_idx": int(np.random.randint(0, len(testset))), "inference_cache": None, "last_inferred_idx": -1, "session_history": [], "batch_results": None, # stores last batch run summary } for k, v in _defaults.items(): if k not in st.session_state: st.session_state[k] = v with st.sidebar: st.markdown("#### Input") src = st.radio("", ["Random Sample", "Upload Image"], label_visibility="collapsed") if src == "Random Sample": if st.button("↻ Next Sample"): st.session_state.sample_idx = int(np.random.randint(0, len(testset))) raw_idx = st.number_input( "Sample Index", 0, len(testset) - 1, value=st.session_state.sample_idx, step=1, key="sample_idx_input" ) if int(raw_idx) != st.session_state.sample_idx: st.session_state.sample_idx = int(raw_idx) image_tensor, true_label = testset[st.session_state.sample_idx] image_display = torchvision.transforms.ToPILImage()( image_tensor * torch.tensor([0.2675, 0.2565, 0.2761]).view(3, 1, 1) + torch.tensor([0.5071, 0.4867, 0.4408]).view(3, 1, 1) ) image_tensor = image_tensor.unsqueeze(0).to(device) true_label_text = class_names[true_label] else: uploaded = st.file_uploader("Upload Image", type=['png', 'jpg', 'jpeg']) if uploaded: image_display = Image.open(uploaded).convert('RGB') image_tensor = preprocess_image(image_display).to(device) true_label_text = "Unknown" else: st.info("Upload an image to begin.") st.stop() st.image(image_display, use_container_width=True) if true_label_text != "Unknown": st.success(f"Ground Truth: **{true_label_text}**") st.divider() st.markdown("#### Inference Config") if "base_threshold_val" not in st.session_state: st.session_state.base_threshold_val = 0.80 st.markdown("**Base Confidence Threshold**") bt_col1, bt_col2 = st.columns([3, 1]) with bt_col1: bt_slider = st.slider("", 0.05, 0.95, st.session_state.base_threshold_val, 0.05, key="bt_slider", label_visibility="collapsed", help="Minimum confidence required to accept an early exit.") with bt_col2: bt_input = st.number_input("", 0.05, 0.95, value=st.session_state.base_threshold_val, step=0.05, format="%.2f", key="bt_input", label_visibility="collapsed") if bt_slider != st.session_state.base_threshold_val: st.session_state.base_threshold_val = bt_slider elif bt_input != st.session_state.base_threshold_val: st.session_state.base_threshold_val = bt_input base_threshold = st.session_state.base_threshold_val if "k_val" not in st.session_state: st.session_state.k_val = 5 st.markdown("**Slope Window (k)**") k_col1, k_col2 = st.columns([3, 1]) with k_col1: k_slider = st.slider("", 2, 100, st.session_state.k_val, 1, key="k_slider", label_visibility="collapsed", help="Top-k classes used in slope-based confidence. Max 100 for CIFAR-100.") with k_col2: k_input = st.number_input("", min_value=2, max_value=100, value=st.session_state.k_val, step=1, key="k_input", label_visibility="collapsed") if k_slider != st.session_state.k_val: st.session_state.k_val = k_slider elif k_input != st.session_state.k_val: st.session_state.k_val = int(k_input) k_value = st.session_state.k_val st.divider() st.markdown("#### Hardware Telemetry") st.caption("Simulated device state β€” drives dynamic threshold adjustment.") if "cpu_load_val" not in st.session_state: st.session_state.cpu_load_val = 30 st.markdown("**CPU Load (%)**") cpu_c1, cpu_c2 = st.columns([3, 1]) with cpu_c1: cpu_s = st.slider("", 0, 100, st.session_state.cpu_load_val, 5, key="cpu_slider", label_visibility="collapsed") with cpu_c2: cpu_n = st.number_input("", 0, 100, value=st.session_state.cpu_load_val, step=1, key="cpu_input", label_visibility="collapsed") if cpu_s != st.session_state.cpu_load_val: st.session_state.cpu_load_val = cpu_s elif cpu_n != st.session_state.cpu_load_val: st.session_state.cpu_load_val = int(cpu_n) cpu_load = st.session_state.cpu_load_val if "mem_val" not in st.session_state: st.session_state.mem_val = 512 st.markdown("**Available Memory (MB)**") mem_c1, mem_c2 = st.columns([3, 1]) with mem_c1: mem_s = st.slider("", 64, 1024, st.session_state.mem_val, 32, key="mem_slider", label_visibility="collapsed") with mem_c2: mem_n = st.number_input("", 64, 1024, value=st.session_state.mem_val, step=1, key="mem_input", label_visibility="collapsed") if mem_s != st.session_state.mem_val: st.session_state.mem_val = mem_s elif mem_n != st.session_state.mem_val: st.session_state.mem_val = int(mem_n) mem_available = st.session_state.mem_val power_state = st.radio("Power State", ["AC / Plugged In", "Battery", "Low Battery"]) thermal_ok = st.checkbox("Thermal Throttle Active", value=False) st.divider() if st.button("πŸ—‘ Reset Session Stats"): st.session_state.session_history = [] st.rerun() def compute_threshold(base, cpu, mem, pwr, therm): d = 0.0 if cpu > 70: d -= 0.10 elif cpu > 50: d -= 0.05 if mem < 128: d -= 0.12 elif mem < 256: d -= 0.06 if pwr == "Low Battery": d -= 0.15 elif pwr == "Battery": d -= 0.07 if therm: d -= 0.08 return float(np.clip(base + d, 0.30, 0.95)) eff_thresh = compute_threshold(base_threshold, cpu_load, mem_available, power_state, thermal_ok) pressure = base_threshold - eff_thresh st.markdown("## Resource Adaptive Neural Network Inference") st.caption("MobileNetV2 Β· CIFAR-100 Β· Early-exit with hardware-aware dynamic thresholding") st.divider() hc = st.columns(5) hc[0].metric("CPU Load", f"{cpu_load}%") hc[1].metric("Free Memory", f"{mem_available} MB") hc[2].metric("Power", power_state.split("/")[0].strip()) hc[3].metric("Thermal", "Throttling" if thermal_ok else "Normal") hc[4].metric("Eff. Threshold", f"{eff_thresh:.2f}", delta=f"-{pressure:.2f} relaxed" if pressure > 0.01 else "nominal", delta_color="inverse" if pressure > 0.01 else "off") if pressure > 0.01: st.warning( f"Hardware pressure active β€” threshold relaxed from **{base_threshold:.2f}** " f"β†’ **{eff_thresh:.2f}**. Model will exit earlier to conserve resources." ) else: st.info(f"Effective threshold: **{eff_thresh:.2f}** β€” no hardware pressure applied.") st.divider() current_idx = st.session_state.sample_idx if st.session_state.last_inferred_idx != current_idx or st.session_state.inference_cache is None: t0 = time.time() with torch.no_grad(): out_full = model(image_tensor) prob_full = torch.softmax(out_full, dim=1) pred_full = torch.argmax(prob_full, dim=1).item() conf_full = prob_full[0, pred_full].item() pnp_full = prob_full[0].cpu().numpy() time_full = (time.time() - t0) * 1000 configs = [ ("margin", None, "Margin (Baseline)"), ("slopev2", 5, "SlopeV2 k=5"), ("slopev2", k_value, f"SlopeV2 k={k_value} (Live)"), ] results = [] for metric, k, label in configs: kp = k if k is not None else 5 with torch.no_grad(): out_exit, exit_idx, layers_used, conf_score = model.forward_with_exits( image_tensor, eff_thresh, metric, kp ) pnp = torch.softmax(out_exit, dim=1)[0].cpu().numpy() pred_exit = int(np.argmax(pnp)) conf_exit = float(pnp[pred_exit]) cp = (layers_used / 19) * 100 results.append({ 'label': label, 'prediction': pred_exit, 'confidence': conf_exit, 'exit_idx': exit_idx, 'layers_used': layers_used, 'compute_pct': cp, 'speedup': 1.0 / (cp / 100), 'latency': time_full * (cp / 100), 'conf_score': conf_score, 'correct': pred_exit == pred_full, 'pnp': pnp, 'entropy': entropy_bits(pnp), 'gini': gini_impurity(pnp), 'margin': prediction_margin(pnp), 'top3': top_k_classes(pnp, class_names, 3), 'conc5': concentration_ratio(pnp, 5), 'eff_cls': effective_classes(pnp), }) st.session_state.session_history.append({ 'idx': current_idx, 'compute_pcts': [r['compute_pct'] for r in results], 'exit_idxs': [r['exit_idx'] for r in results], 'speedups': [r['speedup'] for r in results], 'correct': [r['correct'] for r in results], }) st.session_state.inference_cache = { 'pred_full': pred_full, 'conf_full': conf_full, 'time_full': time_full, 'pnp_full': pnp_full, 'results': results, } st.session_state.last_inferred_idx = current_idx else: c = st.session_state.inference_cache pred_full = c['pred_full'] conf_full = c['conf_full'] time_full = c['time_full'] pnp_full = c['pnp_full'] results = c['results'] def exit_label(r): if r['exit_idx'] == -1: return "Full depth" return f"Branch {r['exit_idx']+1} (block {model.exit_points[r['exit_idx']]})" # Column header labels β€” consistent across all sections cfg_labels = [ "Static Model", "Margin (Baseline)", f"SlopeV2 k=5", f"SlopeV2 k={k_value} (Live)", ] tab_inf, tab_analysis, tab_hw, tab_session = st.tabs([ "πŸ“Š Inference", "πŸ”¬ Distribution & Uncertainty", "βš™οΈ Hardware Impact", "πŸ“ˆ Session", ]) with tab_inf: # Uniform column headers β€” same style for all four h_static, h_m, h_s5, h_sk = st.columns(4) for hcol, lbl in zip([h_static, h_m, h_s5, h_sk], cfg_labels): hcol.markdown(f"**{lbl}**") st.divider() c_static, c_m, c_s5, c_sk = st.columns(4) # Static model with c_static: st.metric("Prediction", class_names[pred_full]) st.metric("Confidence", f"{conf_full:.1%}") st.metric("Latency", f"{time_full:.1f} ms") st.metric("Compute", "100%") st.progress(1.0, text="19 / 19 blocks β€” full depth") # Adaptive routing columns for col, r in zip([c_m, c_s5, c_sk], results): with col: # Prediction: delta only when branches disagree if not r['correct']: st.metric("Prediction", class_names[r['prediction']], delta="differs from static", delta_color="inverse") else: st.metric("Prediction", class_names[r['prediction']]) st.metric("Confidence", f"{r['confidence']:.1%}") # Latency: positive speedup = good (normal color = green) st.metric("Latency", f"{r['latency']:.1f} ms", delta=f"+{r['speedup']:.2f}Γ— faster", delta_color="normal") # Compute: negative savings string, inverse color β†’ green downward arrow saved = -(100 - r['compute_pct']) # e.g. -63.2 st.metric("Compute", f"{r['compute_pct']:.1f}%", delta=f"{saved:.1f}% vs static", delta_color="inverse") st.progress(r['layers_used'] / 19, text=exit_label(r)) st.divider() # Full routing log tucked in an expander β€” visible but not dominant with st.expander("Full Routing Log"): st.table({ "Config": cfg_labels, "Prediction": [class_names[pred_full]] + [class_names[r['prediction']] for r in results], "Confidence": [f"{conf_full:.1%}"] + [f"{r['confidence']:.1%}" for r in results], "Entropy (bits)": [f"{entropy_bits(pnp_full):.3f}"] + [f"{r['entropy']:.3f}" for r in results], "Gini": [f"{gini_impurity(pnp_full):.4f}"] + [f"{r['gini']:.4f}" for r in results], "Margin": [f"{prediction_margin(pnp_full):.4f}"] + [f"{r['margin']:.4f}" for r in results], "Top-5 Conc.": [f"{concentration_ratio(pnp_full):.1%}"] + [f"{r['conc5']:.1%}" for r in results], "Eff. Classes": [f"{effective_classes(pnp_full):.2f}"] + [f"{r['eff_cls']:.2f}" for r in results], "Compute (%)": ["100.0"] + [f"{r['compute_pct']:.1f}" for r in results], "Speedup": ["1.00Γ—"] + [f"{r['speedup']:.2f}Γ—" for r in results], "Exit Point": ["Full Network"] + [exit_label(r) for r in results], }) with tab_analysis: st.markdown("### Softmax Distributions") st.caption( "Top-15 class probabilities at each routing strategy's exit point. " "Steeper drop-off = higher slope confidence = more likely to trigger early exit." ) fig, axes = plt.subplots(1, 4, figsize=(14, 4)) all_pnp = [pnp_full] + [r['pnp'] for r in results] dist_clr = ['#5b8dd9', '#4CAF50', '#FF9800', '#E91E63'] for ax, pnp, lbl, color in zip(axes, all_pnp, cfg_labels, dist_clr): top_idx = np.argsort(pnp)[::-1][:15] top_vals = pnp[top_idx] top_lbls = [class_names[i][:12] for i in top_idx] ax.barh(range(15), top_vals[::-1], color=color, alpha=0.8) ax.set_yticks(range(15)) ax.set_yticklabels(top_lbls[::-1], fontsize=7) ax.set_xlabel("Probability", fontsize=8) ax.set_title(lbl, fontsize=9, fontweight='bold') ax.grid(axis='x', alpha=0.3) plt.tight_layout() st.pyplot(fig) st.divider() col_unc, col_top3 = st.columns(2) with col_unc: st.markdown("### Uncertainty Breakdown") unc_table = { "Metric": [ "Entropy (bits)", "Gini Impurity", "Margin (top-2 gap)", "Top-5 Concentration", "Effective Classes", ], cfg_labels[0]: [ f"{entropy_bits(pnp_full):.3f}", f"{gini_impurity(pnp_full):.4f}", f"{prediction_margin(pnp_full):.4f}", f"{concentration_ratio(pnp_full):.1%}", f"{effective_classes(pnp_full):.2f}", ], } for i, lbl in enumerate(cfg_labels[1:]): r = results[i] unc_table[lbl] = [ f"{r['entropy']:.3f}", f"{r['gini']:.4f}", f"{r['margin']:.4f}", f"{r['conc5']:.1%}", f"{r['eff_cls']:.2f}", ] st.table(unc_table) with st.expander("What do these mean?"): st.markdown(""" | Metric | Description | |---|---| | **Entropy (bits)** | Shannon entropy of the output distribution. Lower = more confident. Max β‰ˆ 6.64 bits for 100 uniform classes. | | **Gini Impurity** | 1 βˆ’ Ξ£pΒ². 0 = fully certain, β‰ˆ 0.99 = uniform. Cheaper to compute than entropy, similar signal. | | **Margin** | Probability gap between top-1 and top-2 class. Narrow margin = ambiguous prediction. | | **Top-5 Concentration** | Fraction of total probability mass held by top 5 classes. High = model has strong focus. | | **Effective Classes** | 2^H β€” perplexity of the distribution. Intuitive read: "the model is weighing ~N classes." | | **SlopeV2** | Steepness of probability decay across top-k classes. Generalises margin (k=2) to broader distribution shape. | """) with col_top3: st.markdown("### Top-3 Predictions") st.caption("What the model was considering at each exit point.") all_top3 = [top_k_classes(pnp_full, class_names)] + [r['top3'] for r in results] for lbl, top3 in zip(cfg_labels, all_top3): st.markdown(f"**{lbl}**") for rank, (cls, prob) in enumerate(top3, 1): rc1, rc2 = st.columns([2, 3]) rc1.markdown(f"`#{rank}` {cls}") rc2.progress(prob, text=f"{prob:.1%}") st.markdown("") with tab_hw: st.markdown("### Hardware Impact") st.caption("Per-sample compute, throughput gain, and decision uncertainty at each exit point.") chart_c, diag_c = st.columns([3, 1]) with chart_c: labels = [r['label'] for r in results] computes = [r['compute_pct'] for r in results] speedups = [r['speedup'] for r in results] entropies = [r['entropy'] for r in results] bar_clr = ['#4CAF50', '#FF9800', '#E91E63'] fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(13, 3.5)) b1 = ax1.barh(labels, computes, color=bar_clr, alpha=0.85, height=0.45) ax1.axvline(100, color='grey', linestyle='--', lw=1, label='Static baseline') ax1.set_xlabel('Compute (%)') ax1.set_title('Compute Footprint', fontsize=10, fontweight='bold') ax1.legend(fontsize=8) ax1.grid(axis='x', alpha=0.3) for bar, v in zip(b1, computes): ax1.text(v + 1, bar.get_y() + bar.get_height() / 2, f'{v:.1f}%', va='center', fontsize=8) b2 = ax2.barh(labels, speedups, color=bar_clr, alpha=0.85, height=0.45) ax2.set_xlabel('Speedup (Γ—)') ax2.set_title('Throughput Gain', fontsize=10, fontweight='bold') ax2.grid(axis='x', alpha=0.3) for bar, v in zip(b2, speedups): ax2.text(v + 0.03, bar.get_y() + bar.get_height() / 2, f'{v:.2f}Γ—', va='center', fontsize=8) b3 = ax3.barh(labels, entropies, color=bar_clr, alpha=0.85, height=0.45) ax3.axvline(entropy_bits(pnp_full), color='grey', linestyle='--', lw=1, label='Static') ax3.set_xlabel('Entropy (bits)') ax3.set_title('Decision Uncertainty at Exit', fontsize=10, fontweight='bold') ax3.legend(fontsize=8) ax3.grid(axis='x', alpha=0.3) for bar, v in zip(b3, entropies): ax3.text(v + 0.02, bar.get_y() + bar.get_height() / 2, f'{v:.3f}', va='center', fontsize=8) plt.tight_layout() st.pyplot(fig) with diag_c: st.markdown("#### Summary") best = min(results, key=lambda r: r['compute_pct']) most_certain = min(results, key=lambda r: r['entropy']) all_agree = all(r['correct'] for r in results) st.markdown(f""" **Most Efficient** {best['label']} `{best['compute_pct']:.1f}%` compute `{best['speedup']:.2f}Γ—` faster --- **Lowest Uncertainty at Exit** {most_certain['label']} `{most_certain['entropy']:.3f}` bits entropy `{most_certain['gini']:.4f}` Gini impurity --- **Branch Agreement** {"βœ… All routes agree" if all_agree else "⚠️ Drift β€” aggressive early exit changed prediction"} """) with tab_session: st.markdown("### Batch Evaluation") st.caption( "Run inference on N random samples using the current threshold, hardware " "telemetry, and k settings. Aggregates exit rates, compute savings, " "speedup, and accuracy drift across all configs." ) bcol1, bcol2, bcol3 = st.columns([1, 1, 2]) with bcol1: batch_n = st.number_input("Number of Samples (N)", min_value=5, max_value=10000, value=50, step=5) with bcol2: st.markdown("
", unsafe_allow_html=True) # vertical align with button run_batch = st.button("β–Ά Run Batch", type="primary") with bcol3: if st.session_state.batch_results is not None: br = st.session_state.batch_results st.caption( f"Last run: **{br['n']}** samples Β· " f"threshold `{br['threshold']:.2f}` Β· " f"k=`{br['k']}`" ) if run_batch: b_configs = [ ("margin", None, "Margin (Baseline)"), ("slopev2", 5, "SlopeV2 k=5"), ("slopev2", k_value, f"SlopeV2 k={k_value} (Live)"), ] # Accumulators: one list per config b_computes = [[] for _ in b_configs] # compute % b_speedups = [[] for _ in b_configs] b_exit_idxs = [[] for _ in b_configs] # -1 = full depth b_agree = [[] for _ in b_configs] # bool: matches static pred b_entropies = [[] for _ in b_configs] b_indices = np.random.choice(len(testset), size=batch_n, replace=False) prog = st.progress(0, text="Running batch…") stat_box = st.empty() for step, idx in enumerate(b_indices): img_t, gt = testset[int(idx)] img_t = img_t.unsqueeze(0).to(device) # Static reference for this sample with torch.no_grad(): out_s = model(img_t) prob_s = torch.softmax(out_s, dim=1) pred_s = torch.argmax(prob_s, dim=1).item() t_start = time.time() _ = model(img_t) # second pass for latency ref t_full = (time.time() - t_start) * 1000 for ci, (metric, k, _) in enumerate(b_configs): kp = k if k is not None else 5 with torch.no_grad(): out_e, e_idx, layers, _ = model.forward_with_exits( img_t, eff_thresh, metric, kp ) pnp_e = torch.softmax(out_e, dim=1)[0].cpu().numpy() pred_e = int(np.argmax(pnp_e)) cp = (layers / 19) * 100 b_computes[ci].append(cp) b_speedups[ci].append(1.0 / (cp / 100)) b_exit_idxs[ci].append(e_idx) b_agree[ci].append(pred_e == pred_s) b_entropies[ci].append(entropy_bits(pnp_e)) pct = (step + 1) / batch_n prog.progress(pct, text=f"Running batch… {step+1}/{batch_n}") prog.empty() # Store summary st.session_state.batch_results = { 'n': batch_n, 'threshold': eff_thresh, 'k': k_value, 'cfg_labels': [c[2] for c in b_configs], 'computes': [np.array(b_computes[i]) for i in range(3)], 'speedups': [np.array(b_speedups[i]) for i in range(3)], 'exit_idxs': [np.array(b_exit_idxs[i]) for i in range(3)], 'agree': [np.array(b_agree[i]) for i in range(3)], 'entropies': [np.array(b_entropies[i]) for i in range(3)], 'sample_indices': b_indices, } st.rerun() # ── Batch Results Display ───────────────────────────────────────────────── if st.session_state.batch_results is not None: br = st.session_state.batch_results n = br['n'] blabels = br['cfg_labels'] st.divider() st.markdown("#### Batch Summary") # Top-line metrics β€” one column per config b_header = st.columns(3) for ci, (col, lbl) in enumerate(zip(b_header, blabels)): col.markdown(f"**{lbl}**") st.markdown("") mc = st.columns(3) for ci, col in enumerate(mc): avg_cp = np.mean(br['computes'][ci]) avg_spd = np.mean(br['speedups'][ci]) exit_rate = np.mean(br['exit_idxs'][ci] != -1) * 100 agree_pct = np.mean(br['agree'][ci]) * 100 avg_ent = np.mean(br['entropies'][ci]) saved = -(100 - avg_cp) col.metric("Avg Compute", f"{avg_cp:.1f}%", delta=f"{saved:.1f}% vs static", delta_color="inverse") col.metric("Avg Speedup", f"{avg_spd:.2f}Γ—") col.metric("Early Exit Rate",f"{exit_rate:.1f}%") col.metric("Accuracy Match", f"{agree_pct:.1f}%", delta=f"{agree_pct-100:.1f}% drift" if agree_pct < 100 else "no drift", delta_color="inverse" if agree_pct < 100 else "off") col.metric("Avg Entropy", f"{avg_ent:.3f} bits") st.divider() # Charts fig_b, axes_b = plt.subplots(1, 3, figsize=(14, 3.5)) b_clr = ['#4CAF50', '#FF9800', '#E91E63'] # 1. Compute distribution β€” box-like violin or histogram overlay ax = axes_b[0] for ci, (lbl, clr) in enumerate(zip(blabels, b_clr)): ax.hist(br['computes'][ci], bins=15, alpha=0.55, color=clr, label=lbl, density=True) ax.axvline(100, color='grey', linestyle='--', lw=1, label='Static') ax.set_xlabel("Compute (%)") ax.set_ylabel("Density") ax.set_title("Compute Distribution", fontsize=10, fontweight='bold') ax.legend(fontsize=7) ax.grid(alpha=0.3) # 2. Exit branch breakdown β€” stacked bar per config ax = axes_b[1] bc = np.zeros((3, 3)) # (config, branch 0/1/full) for ci in range(3): for ei in br['exit_idxs'][ci]: bc[ci, 0 if ei == 0 else (1 if ei == 1 else 2)] += 1 bp = bc / n * 100 xa = np.arange(3) ax.bar(xa, bp[:, 0], 0.5, label="Branch 1 (Shallow)", color='#4CAF50', alpha=0.85) ax.bar(xa, bp[:, 1], 0.5, bottom=bp[:, 0], label="Branch 2 (Mid)", color='#FF9800', alpha=0.85) ax.bar(xa, bp[:, 2], 0.5, bottom=bp[:, 0]+bp[:, 1], label="Full Depth", color='#9E9E9E', alpha=0.85) ax.set_xticks(xa) ax.set_xticklabels([f"Cfg {i+1}" for i in range(3)], fontsize=8) ax.set_ylabel("% of samples") ax.set_title("Exit Branch Distribution", fontsize=10, fontweight='bold') ax.legend(fontsize=7) ax.grid(axis='y', alpha=0.3) # 3. Accuracy match rate bar ax = axes_b[2] agree_pcts = [np.mean(br['agree'][ci]) * 100 for ci in range(3)] drift_pcts = [100 - a for a in agree_pcts] bars_a = ax.bar(xa, agree_pcts, 0.5, label="Matches Static", color=b_clr, alpha=0.85) ax.bar(xa, drift_pcts, 0.5, bottom=agree_pcts, label="Drift", color='#9E9E9E', alpha=0.6) ax.set_xticks(xa) ax.set_xticklabels([f"Cfg {i+1}" for i in range(3)], fontsize=8) ax.set_ylabel("% of samples") ax.set_ylim(0, 110) ax.set_title("Prediction Agreement with Static", fontsize=10, fontweight='bold') ax.legend(fontsize=7) ax.grid(axis='y', alpha=0.3) for bar, v in zip(bars_a, agree_pcts): ax.text(bar.get_x() + bar.get_width()/2, v + 1, f'{v:.1f}%', ha='center', fontsize=8, fontweight='bold') plt.tight_layout() st.pyplot(fig_b) # Config legend below charts st.caption( " Β· ".join([f"Cfg {i+1} = {lbl}" for i, lbl in enumerate(blabels)]) ) st.divider() # ── Per-Sample Session History ──────────────────────────────────────────── history = st.session_state.session_history st.markdown("### Session History") st.caption(f"{len(history)} sample(s) browsed this session.") if len(history) >= 1: all_computes = np.array([h['compute_pcts'] for h in history]) all_speedups = np.array([h['speedups'] for h in history]) all_exits = np.array([h['exit_idxs'] for h in history]) s1, s2, s3, s4 = st.columns(4) s1.metric("Samples Browsed", len(history)) s2.metric("Avg Compute (live)", f"{np.mean(all_computes[:, -1]):.1f}%") s3.metric("Avg Speedup (live)", f"{np.mean(all_speedups[:, -1]):.2f}Γ—") s4.metric("Early Exit Rate", f"{np.mean(all_exits[:, -1] != -1) * 100:.1f}%") if len(history) >= 2: fig2, (sa1, sa2) = plt.subplots(1, 2, figsize=(12, 3.5)) x = np.arange(len(history)) s_clr = ['#4CAF50', '#FF9800', '#E91E63'] s_lbls = ["Margin", "SlopeV2 k=5", f"SlopeV2 k={k_value}"] for i, (lbl, clr) in enumerate(zip(s_lbls, s_clr)): sa1.plot(x, all_computes[:, i], label=lbl, color=clr, lw=1.5, marker='o', markersize=3, alpha=0.85) sa1.axhline(100, color='grey', linestyle='--', lw=1, label='Static baseline') sa1.set_xlabel("Sample #") sa1.set_ylabel("Compute (%)") sa1.set_title("Compute Usage Per Browse", fontsize=10, fontweight='bold') sa1.legend(fontsize=8) sa1.grid(alpha=0.3) bc = np.zeros((3, 3)) for h in history: for ci, ei in enumerate(h['exit_idxs']): bc[ci, 0 if ei == 0 else (1 if ei == 1 else 2)] += 1 bp = bc / max(len(history), 1) * 100 xa = np.arange(3) sa2.bar(xa, bp[:, 0], 0.5, label="Branch 1 (Shallow)", color='#4CAF50', alpha=0.85) sa2.bar(xa, bp[:, 1], 0.5, bottom=bp[:, 0], label="Branch 2 (Mid)", color='#FF9800', alpha=0.85) sa2.bar(xa, bp[:, 2], 0.5, bottom=bp[:, 0] + bp[:, 1], label="Full Depth", color='#9E9E9E', alpha=0.85) sa2.set_xticks(xa) sa2.set_xticklabels(s_lbls, fontsize=8) sa2.set_ylabel("% of samples") sa2.set_title("Exit Branch Distribution", fontsize=10, fontweight='bold') sa2.legend(fontsize=8) sa2.grid(axis='y', alpha=0.3) plt.tight_layout() st.pyplot(fig2) else: st.info("Browse at least 2 different samples to see trend charts.") else: st.info("Session history will appear as you browse samples.")