Spaces:
Running
Running
remove locally saved tokenizer
Browse files
main.py
CHANGED
|
@@ -10,7 +10,7 @@ app = FastAPI(title="EmCoder API & UI")
|
|
| 10 |
|
| 11 |
repo_id = "yezdata/EmCoder"
|
| 12 |
|
| 13 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 14 |
model = AutoModel.from_pretrained(repo_id, trust_remote_code=True)
|
| 15 |
|
| 16 |
model.eval()
|
|
@@ -35,20 +35,19 @@ def compute_uncertainty(probs_samples: torch.Tensor, mean_probs: torch.Tensor) -
|
|
| 35 |
return {"total": total_unc, "aleatoric": aleatoric_unc, "epistemic": epistemic_unc}
|
| 36 |
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
class PredictRequest(BaseModel):
|
| 41 |
text: str
|
| 42 |
monte_carlo: bool = False
|
| 43 |
n_samples: int = 10
|
| 44 |
|
|
|
|
| 45 |
@app.post("/predict")
|
| 46 |
def predict_api(request: PredictRequest):
|
| 47 |
encoded = tokenizer(request.text, return_tensors="pt")
|
| 48 |
-
|
| 49 |
input_ids = encoded["input_ids"]
|
| 50 |
attention_mask = encoded["attention_mask"]
|
| 51 |
-
|
| 52 |
id2label = model.config.id2label
|
| 53 |
|
| 54 |
if request.monte_carlo:
|
|
@@ -56,17 +55,19 @@ def predict_api(request: PredictRequest):
|
|
| 56 |
outputs = model.mc_forward(
|
| 57 |
input_ids=input_ids,
|
| 58 |
attention_mask=attention_mask,
|
| 59 |
-
n_samples=request.n_samples
|
| 60 |
)
|
| 61 |
|
| 62 |
mc_logits = outputs.logits
|
| 63 |
logits_samples = mc_logits.squeeze(1)
|
| 64 |
-
|
| 65 |
probs_samples = torch.sigmoid(logits_samples) # (n_samples, num_labels)
|
| 66 |
-
|
| 67 |
mean_probs = probs_samples.mean(dim=0) # (num_labels,)
|
| 68 |
|
| 69 |
-
unc_dict = compute_uncertainty(
|
|
|
|
|
|
|
| 70 |
|
| 71 |
predictions = {}
|
| 72 |
for i in range(model.config.num_labels):
|
|
@@ -77,82 +78,79 @@ def predict_api(request: PredictRequest):
|
|
| 77 |
"total_entropy": float(unc_dict["total"][i]),
|
| 78 |
"epistemic": float(unc_dict["epistemic"][i]),
|
| 79 |
"aleatoric": float(unc_dict["aleatoric"][i]),
|
| 80 |
-
}
|
| 81 |
}
|
| 82 |
-
|
| 83 |
return {
|
| 84 |
"mode": "monte_carlo",
|
| 85 |
"n_samples": request.n_samples,
|
| 86 |
-
"predictions": predictions
|
| 87 |
}
|
| 88 |
|
| 89 |
-
|
| 90 |
else:
|
| 91 |
with torch.no_grad():
|
| 92 |
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
|
| 93 |
-
|
| 94 |
logits = outputs.logits.squeeze(0)
|
| 95 |
probs = torch.sigmoid(logits)
|
| 96 |
-
|
| 97 |
predictions = {}
|
| 98 |
for i in range(model.config.num_labels):
|
| 99 |
label_name = id2label[i]
|
| 100 |
-
predictions[label_name] = {
|
| 101 |
-
"probability": float(probs[i])
|
| 102 |
-
}
|
| 103 |
-
|
| 104 |
-
return {
|
| 105 |
-
"mode": "standard",
|
| 106 |
-
"predictions": predictions
|
| 107 |
-
}
|
| 108 |
|
|
|
|
| 109 |
|
| 110 |
|
| 111 |
@app.get("/health")
|
| 112 |
def health_check():
|
| 113 |
return {"status": "healthy"}
|
| 114 |
|
|
|
|
| 115 |
def gradio_predict(text, monte_carlo, n_samples):
|
| 116 |
-
request_data = PredictRequest(
|
|
|
|
|
|
|
| 117 |
response = predict_api(request_data)
|
| 118 |
|
| 119 |
sorted_preds = sorted(
|
| 120 |
response["predictions"].items(),
|
| 121 |
-
key=lambda item:
|
| 122 |
-
|
|
|
|
|
|
|
| 123 |
)
|
| 124 |
|
| 125 |
standard_rows = []
|
| 126 |
mc_rows = []
|
| 127 |
-
|
| 128 |
for label_name, metrics in sorted_preds:
|
| 129 |
if monte_carlo:
|
| 130 |
prob = metrics["mean_probability"]
|
| 131 |
-
mc_rows.append(
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
| 138 |
else:
|
| 139 |
prob = metrics["probability"]
|
| 140 |
-
standard_rows.append([
|
| 141 |
-
label_name,
|
| 142 |
-
f"{prob * 100:.2f}%"
|
| 143 |
-
])
|
| 144 |
|
| 145 |
if monte_carlo:
|
| 146 |
return (
|
| 147 |
gr.update(value=[], visible=False),
|
| 148 |
-
gr.update(value=mc_rows, visible=True)
|
| 149 |
)
|
| 150 |
else:
|
| 151 |
return (
|
| 152 |
gr.update(value=standard_rows, visible=True),
|
| 153 |
-
gr.update(value=[], visible=False)
|
| 154 |
)
|
| 155 |
-
|
| 156 |
|
| 157 |
with gr.Blocks(title="EmCoder - Probabilistic Emotion Recognition") as ui:
|
| 158 |
gr.Markdown("# EmCoder - Probabilistic Emotion Recognition")
|
|
@@ -163,55 +161,51 @@ with gr.Blocks(title="EmCoder - Probabilistic Emotion Recognition") as ui:
|
|
| 163 |
"Live API service and graphical interface demonstrating **EmCoder's** epistemic and aleatoric "
|
| 164 |
"uncertainty decomposition via Monte Carlo Dropout across **28 multi-label emotion classes**."
|
| 165 |
)
|
| 166 |
-
|
| 167 |
with gr.Row():
|
| 168 |
with gr.Column(scale=1):
|
| 169 |
input_text = gr.Textbox(
|
| 170 |
-
label="Input text",
|
| 171 |
-
placeholder="Input text for classification...",
|
| 172 |
-
lines=3
|
|
|
|
|
|
|
|
|
|
| 173 |
)
|
| 174 |
-
use_mc = gr.Checkbox(label="Use Monte Carlo Dropout (Uncertainty Estimation)", value=False)
|
| 175 |
mc_samples_slider = gr.Slider(
|
| 176 |
-
minimum=5,
|
| 177 |
-
maximum=50,
|
| 178 |
-
value=10,
|
| 179 |
-
step=1,
|
| 180 |
-
label="MC samples"
|
| 181 |
)
|
| 182 |
submit_btn = gr.Button("Analyze Emotions", variant="primary")
|
| 183 |
-
|
| 184 |
with gr.Column(scale=2):
|
| 185 |
output_table_standard = gr.DataFrame(
|
| 186 |
headers=["Emotion", "Probability"],
|
| 187 |
datatype=["str", "str"],
|
| 188 |
label="Prediction Report",
|
| 189 |
-
visible=True
|
| 190 |
)
|
| 191 |
-
|
| 192 |
output_table_mc = gr.DataFrame(
|
| 193 |
headers=[
|
| 194 |
-
"Emotion",
|
| 195 |
-
"Probability (Mean)",
|
| 196 |
-
"Total Uncertainty (Entropy)",
|
| 197 |
"Epistemic (Model Knowledge)",
|
| 198 |
-
"Aleatoric (Data Noise)"
|
| 199 |
],
|
| 200 |
datatype=["str", "str", "str", "str", "str"],
|
| 201 |
label="Prediction & Bayesian Uncertainty Report",
|
| 202 |
-
visible=False
|
| 203 |
)
|
| 204 |
|
| 205 |
submit_btn.click(
|
| 206 |
fn=gradio_predict,
|
| 207 |
inputs=[input_text, use_mc, mc_samples_slider],
|
| 208 |
-
outputs=[output_table_standard, output_table_mc]
|
| 209 |
)
|
| 210 |
|
| 211 |
app = gr.mount_gradio_app(app, ui, path="/")
|
| 212 |
|
| 213 |
|
| 214 |
-
|
| 215 |
if __name__ == "__main__":
|
| 216 |
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
| 217 |
-
|
|
|
|
| 10 |
|
| 11 |
repo_id = "yezdata/EmCoder"
|
| 12 |
|
| 13 |
+
tokenizer = AutoTokenizer.from_pretrained("answerdotai/ModernBERT-base")
|
| 14 |
model = AutoModel.from_pretrained(repo_id, trust_remote_code=True)
|
| 15 |
|
| 16 |
model.eval()
|
|
|
|
| 35 |
return {"total": total_unc, "aleatoric": aleatoric_unc, "epistemic": epistemic_unc}
|
| 36 |
|
| 37 |
|
|
|
|
|
|
|
| 38 |
class PredictRequest(BaseModel):
|
| 39 |
text: str
|
| 40 |
monte_carlo: bool = False
|
| 41 |
n_samples: int = 10
|
| 42 |
|
| 43 |
+
|
| 44 |
@app.post("/predict")
|
| 45 |
def predict_api(request: PredictRequest):
|
| 46 |
encoded = tokenizer(request.text, return_tensors="pt")
|
| 47 |
+
|
| 48 |
input_ids = encoded["input_ids"]
|
| 49 |
attention_mask = encoded["attention_mask"]
|
| 50 |
+
|
| 51 |
id2label = model.config.id2label
|
| 52 |
|
| 53 |
if request.monte_carlo:
|
|
|
|
| 55 |
outputs = model.mc_forward(
|
| 56 |
input_ids=input_ids,
|
| 57 |
attention_mask=attention_mask,
|
| 58 |
+
n_samples=request.n_samples,
|
| 59 |
)
|
| 60 |
|
| 61 |
mc_logits = outputs.logits
|
| 62 |
logits_samples = mc_logits.squeeze(1)
|
| 63 |
+
|
| 64 |
probs_samples = torch.sigmoid(logits_samples) # (n_samples, num_labels)
|
| 65 |
+
|
| 66 |
mean_probs = probs_samples.mean(dim=0) # (num_labels,)
|
| 67 |
|
| 68 |
+
unc_dict = compute_uncertainty(
|
| 69 |
+
probs_samples=probs_samples, mean_probs=mean_probs
|
| 70 |
+
)
|
| 71 |
|
| 72 |
predictions = {}
|
| 73 |
for i in range(model.config.num_labels):
|
|
|
|
| 78 |
"total_entropy": float(unc_dict["total"][i]),
|
| 79 |
"epistemic": float(unc_dict["epistemic"][i]),
|
| 80 |
"aleatoric": float(unc_dict["aleatoric"][i]),
|
| 81 |
+
},
|
| 82 |
}
|
| 83 |
+
|
| 84 |
return {
|
| 85 |
"mode": "monte_carlo",
|
| 86 |
"n_samples": request.n_samples,
|
| 87 |
+
"predictions": predictions,
|
| 88 |
}
|
| 89 |
|
|
|
|
| 90 |
else:
|
| 91 |
with torch.no_grad():
|
| 92 |
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
|
| 93 |
+
|
| 94 |
logits = outputs.logits.squeeze(0)
|
| 95 |
probs = torch.sigmoid(logits)
|
| 96 |
+
|
| 97 |
predictions = {}
|
| 98 |
for i in range(model.config.num_labels):
|
| 99 |
label_name = id2label[i]
|
| 100 |
+
predictions[label_name] = {"probability": float(probs[i])}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
return {"mode": "standard", "predictions": predictions}
|
| 103 |
|
| 104 |
|
| 105 |
@app.get("/health")
|
| 106 |
def health_check():
|
| 107 |
return {"status": "healthy"}
|
| 108 |
|
| 109 |
+
|
| 110 |
def gradio_predict(text, monte_carlo, n_samples):
|
| 111 |
+
request_data = PredictRequest(
|
| 112 |
+
text=text, monte_carlo=bool(monte_carlo), n_samples=int(n_samples)
|
| 113 |
+
)
|
| 114 |
response = predict_api(request_data)
|
| 115 |
|
| 116 |
sorted_preds = sorted(
|
| 117 |
response["predictions"].items(),
|
| 118 |
+
key=lambda item: (
|
| 119 |
+
item[1]["mean_probability"] if monte_carlo else item[1]["probability"]
|
| 120 |
+
),
|
| 121 |
+
reverse=True,
|
| 122 |
)
|
| 123 |
|
| 124 |
standard_rows = []
|
| 125 |
mc_rows = []
|
| 126 |
+
|
| 127 |
for label_name, metrics in sorted_preds:
|
| 128 |
if monte_carlo:
|
| 129 |
prob = metrics["mean_probability"]
|
| 130 |
+
mc_rows.append(
|
| 131 |
+
[
|
| 132 |
+
label_name,
|
| 133 |
+
f"{prob * 100:.2f}%",
|
| 134 |
+
f"{metrics['uncertainty']['total_entropy']:.4f}",
|
| 135 |
+
f"{metrics['uncertainty']['epistemic']:.4f}",
|
| 136 |
+
f"{metrics['uncertainty']['aleatoric']:.4f}",
|
| 137 |
+
]
|
| 138 |
+
)
|
| 139 |
else:
|
| 140 |
prob = metrics["probability"]
|
| 141 |
+
standard_rows.append([label_name, f"{prob * 100:.2f}%"])
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
if monte_carlo:
|
| 144 |
return (
|
| 145 |
gr.update(value=[], visible=False),
|
| 146 |
+
gr.update(value=mc_rows, visible=True),
|
| 147 |
)
|
| 148 |
else:
|
| 149 |
return (
|
| 150 |
gr.update(value=standard_rows, visible=True),
|
| 151 |
+
gr.update(value=[], visible=False),
|
| 152 |
)
|
| 153 |
+
|
| 154 |
|
| 155 |
with gr.Blocks(title="EmCoder - Probabilistic Emotion Recognition") as ui:
|
| 156 |
gr.Markdown("# EmCoder - Probabilistic Emotion Recognition")
|
|
|
|
| 161 |
"Live API service and graphical interface demonstrating **EmCoder's** epistemic and aleatoric "
|
| 162 |
"uncertainty decomposition via Monte Carlo Dropout across **28 multi-label emotion classes**."
|
| 163 |
)
|
| 164 |
+
|
| 165 |
with gr.Row():
|
| 166 |
with gr.Column(scale=1):
|
| 167 |
input_text = gr.Textbox(
|
| 168 |
+
label="Input text",
|
| 169 |
+
placeholder="Input text for classification...",
|
| 170 |
+
lines=3,
|
| 171 |
+
)
|
| 172 |
+
use_mc = gr.Checkbox(
|
| 173 |
+
label="Use Monte Carlo Dropout (Uncertainty Estimation)", value=False
|
| 174 |
)
|
|
|
|
| 175 |
mc_samples_slider = gr.Slider(
|
| 176 |
+
minimum=5, maximum=50, value=10, step=1, label="MC samples"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
)
|
| 178 |
submit_btn = gr.Button("Analyze Emotions", variant="primary")
|
| 179 |
+
|
| 180 |
with gr.Column(scale=2):
|
| 181 |
output_table_standard = gr.DataFrame(
|
| 182 |
headers=["Emotion", "Probability"],
|
| 183 |
datatype=["str", "str"],
|
| 184 |
label="Prediction Report",
|
| 185 |
+
visible=True,
|
| 186 |
)
|
| 187 |
+
|
| 188 |
output_table_mc = gr.DataFrame(
|
| 189 |
headers=[
|
| 190 |
+
"Emotion",
|
| 191 |
+
"Probability (Mean)",
|
| 192 |
+
"Total Uncertainty (Entropy)",
|
| 193 |
"Epistemic (Model Knowledge)",
|
| 194 |
+
"Aleatoric (Data Noise)",
|
| 195 |
],
|
| 196 |
datatype=["str", "str", "str", "str", "str"],
|
| 197 |
label="Prediction & Bayesian Uncertainty Report",
|
| 198 |
+
visible=False,
|
| 199 |
)
|
| 200 |
|
| 201 |
submit_btn.click(
|
| 202 |
fn=gradio_predict,
|
| 203 |
inputs=[input_text, use_mc, mc_samples_slider],
|
| 204 |
+
outputs=[output_table_standard, output_table_mc],
|
| 205 |
)
|
| 206 |
|
| 207 |
app = gr.mount_gradio_app(app, ui, path="/")
|
| 208 |
|
| 209 |
|
|
|
|
| 210 |
if __name__ == "__main__":
|
| 211 |
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
|
|