Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from uei_core.models import ModelPortfolio
|
| 6 |
+
from uei_core.uncertainty import UncertaintyEstimator
|
| 7 |
+
from uei_core.energy import EnergyProfiler
|
| 8 |
+
from uei_core.policy import UEIPolicy
|
| 9 |
+
|
| 10 |
+
device = "cpu" # M1 CPU is optimized enough; GPU optional
|
| 11 |
+
|
| 12 |
+
models = ModelPortfolio(device=device)
|
| 13 |
+
unc = UncertaintyEstimator()
|
| 14 |
+
energy = EnergyProfiler()
|
| 15 |
+
policy = UEIPolicy()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def uei_infer(img):
|
| 19 |
+
|
| 20 |
+
x = models.preprocess(img)
|
| 21 |
+
|
| 22 |
+
# Step 1: Small model
|
| 23 |
+
logits_s, E_s = energy.measure(models.infer_small, x)
|
| 24 |
+
U_s = unc.estimate(logits_s)
|
| 25 |
+
|
| 26 |
+
# Step 2: Large model (to measure marginal utility)
|
| 27 |
+
logits_l, E_l = energy.measure(models.infer_large, x)
|
| 28 |
+
U_l = unc.estimate(logits_l)
|
| 29 |
+
|
| 30 |
+
decision = policy.decide(U_s, U_l, E_s, E_l)
|
| 31 |
+
|
| 32 |
+
if decision == "small":
|
| 33 |
+
final_logits = logits_s
|
| 34 |
+
energy_used = E_s
|
| 35 |
+
unc_used = U_s
|
| 36 |
+
model_name = "Low-Energy Small Model"
|
| 37 |
+
else:
|
| 38 |
+
final_logits = logits_l
|
| 39 |
+
energy_used = E_l
|
| 40 |
+
unc_used = U_l
|
| 41 |
+
model_name = "High-Energy Large Model"
|
| 42 |
+
|
| 43 |
+
probs = torch.softmax(final_logits, dim=1).squeeze()
|
| 44 |
+
top_idx = torch.argmax(probs).item()
|
| 45 |
+
confidence = float(probs[top_idx])
|
| 46 |
+
|
| 47 |
+
return {
|
| 48 |
+
"Predicted Class Index": top_idx,
|
| 49 |
+
"Confidence": confidence,
|
| 50 |
+
"Selected Model": model_name,
|
| 51 |
+
"Uncertainty": float(unc_used),
|
| 52 |
+
"Energy (proxy units)": energy_used
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
demo = gr.Interface(
|
| 57 |
+
fn=uei_infer,
|
| 58 |
+
inputs=gr.Image(type="pil"),
|
| 59 |
+
outputs=gr.JSON(),
|
| 60 |
+
title="Uncertainty-Elastic Inference (UEI)",
|
| 61 |
+
description="Energy-efficient inference by dynamically selecting models based on uncertainty-energy tradeoffs."
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
if __name__ == "__main__":
|
| 65 |
+
demo.launch()
|