Spaces:
Sleeping
Sleeping
File size: 15,166 Bytes
b5f5071 9482977 b5f5071 b6978b7 b5f5071 8e48ffa b5f5071 8e48ffa b5f5071 8e48ffa b5f5071 8e48ffa b5f5071 8e48ffa b5f5071 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 |
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import json
from typing import Dict, List, Tuple
st.set_page_config(
page_title="LLM Healthcare Benchmarking Budgeting",
page_icon="🩺",
layout="wide"
)
blue_to_gray_palette = ["#0077b6", "#4a98c9", "#7ba7c5", "#a6b5c1", "#d0d7dc"]
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: bold;
margin-bottom: 1rem;
}
.section-header {
font-size: 1.5rem;
font-weight: bold;
margin-top: 2rem;
margin-bottom: 1rem;
}
.info-box {
background-color: #f0f2f6;
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
.cost-highlight {
font-size: 1.2rem;
font-weight: bold;
color: #ff4b4b;
}
</style>
""", unsafe_allow_html=True)
st.markdown('<div class="main-header">Budgeting for LLM Healthcare Benchmarking</div>', unsafe_allow_html=True)
default_models_json = """{
"OpenAI gpt-4.5-preview": {"input_cost": 75, "output_cost": 150},
"OpenAI gpt-4o": {"input_cost": 2.5, "output_cost": 10},
"OpenAI gpt-4o-mini": {"input_cost": 0.15, "output_cost": 0.6},
"OpenAI o1": {"input_cost": 15, "output_cost": 60},
"OpenAI o1-mini": {"input_cost": 1.1, "output_cost": 4.4},
"OpenAI o3-mini": {"input_cost": 1.1, "output_cost": 4.4},
"Anthropic Claude 3.7 Sonnet": {"input_cost": 3, "output_cost": 15},
"Anthropic Claude 3.5 Haiku": {"input_cost": 0.8, "output_cost": 4},
"Anthropic Claude 3 Opus": {"input_cost": 0.8, "output_cost": 4},
"Anthropic Claude 3.5 Sonnet": {"input_cost": 3, "output_cost": 15},
"Anthropic Claude 3 Haiku": {"input_cost": 0.25, "output_cost": 1.25},
"TogetherAI DeepSeek-R1": {"input_cost": 3, "output_cost": 7},
"Llama 3.2 3B Instruct Turbo": {"input_cost": 0.06, "output_cost": 0.06},
"Gemini 2.0 Flash": {"input_cost": 0.1, "output_cost": 0.4},
"Gemini 2.0 Flash-Lite": {"input_cost": 0.075, "output_cost": 0.3},
"Gemini 1.5 Pro": {"input_cost": 1.25, "output_cost": 5},
"Gemini Pro": {"input_cost": 0.5, "output_cost": 1.5},
"Mistral Small": {"input_cost": 0.1, "output_cost": 0.3},
"Mistral Large": {"input_cost": 2, "output_cost": 6}
}"""
# Add JSON editor to sidebar
st.sidebar.markdown('<div class="section-header">LLM Models Configuration</div>', unsafe_allow_html=True)
st.sidebar.markdown("Edit the JSON below to modify existing models or add new ones:")
# Display JSON in a text area for editing
models_json = st.sidebar.text_area("Models JSON", default_models_json, height=400)
# Parse the JSON input
try:
llm_models = json.loads(models_json)
except json.JSONDecodeError as e:
st.sidebar.error(f"Invalid JSON: {str(e)}")
# Use default models if JSON is invalid
llm_models = json.loads(default_models_json)
medmcqa_splits = {
"Single-Select Questions": {
"questions": 120765,
"avg_q_tokens": 12.77, # Using the train dataset average
"description": "Single-select questions from the MedMCQA train dataset"
}
}
col1, col2 = st.columns([2, 1])
with col1:
st.markdown('<div class="section-header">Select LLM Models</div>', unsafe_allow_html=True)
selected_models = st.multiselect(
"Choose one or more LLM models:",
options=list(llm_models.keys()),
default=list(llm_models.keys())[:2]
)
with st.expander("View Model Details"):
models_df = pd.DataFrame([
{
"Model": model,
"Input Cost (per 1M tokens)": f"${llm_models[model]['input_cost']:.2f}",
"Output Cost (per 1M tokens)": f"${llm_models[model]['output_cost']:.2f}"
}
for model in llm_models
])
st.dataframe(models_df, use_container_width=True)
with col2:
st.markdown('<div class="section-header">MedMCQA Dataset</div>', unsafe_allow_html=True)
st.markdown(f"""
**Single-Select Questions:** {medmcqa_splits['Single-Select Questions']['questions']:,}
**Average Question Tokens:** {medmcqa_splits['Single-Select Questions']['avg_q_tokens']}
**Description:** {medmcqa_splits['Single-Select Questions']['description']}
""")
st.markdown('<div class="section-header">Cost Simulation Parameters</div>', unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
prompt_tokens = st.number_input(
"Prompt Tokens per Question",
min_value=1,
max_value=1000,
value=200,
step=10,
help="Number of tokens in each prompt (including the question and any additional instructions)"
)
with col2:
output_tokens = st.number_input(
"Output Tokens per Question",
min_value=1,
max_value=1000,
value=100,
step=10,
help="Average number of tokens in the model's response"
)
col1, col2, col3 = st.columns(3)
with col1:
num_runs = st.number_input(
"Number of Evaluation Runs",
min_value=1,
max_value=1000,
value=1,
step=1,
help="How many times each dataset will be processed by each model"
)
with col2:
st.write("")
with col3:
sampling_percentage = st.slider(
"Dataset Sampling Percentage",
min_value=1,
max_value=100,
value=100,
step=1,
help="Percentage of questions to process from each split"
)
def calculate_costs(models, prompt_token_count, output_token_count, runs, sampling_pct):
results = []
total_questions = medmcqa_splits["Single-Select Questions"]["questions"]
num_questions = int(total_questions * (sampling_pct / 100))
for model in models:
model_input_cost = llm_models[model]["input_cost"]
model_output_cost = llm_models[model]["output_cost"]
total_input_tokens = num_questions * prompt_token_count * runs
total_output_tokens = num_questions * output_token_count * runs
input_cost = (total_input_tokens / 1000000) * model_input_cost
output_cost = (total_output_tokens / 1000000) * model_output_cost
total_cost = input_cost + output_cost
results.append({
"Model": model,
"Questions": num_questions, # Changed from Total Questions to Questions
"Number of Prompt Tokens per Question": prompt_token_count,
"Number of Output Tokens per Question": output_token_count,
"Total Input Tokens": total_input_tokens,
"Total Output Tokens": total_output_tokens,
"Input Cost": input_cost,
"Output Cost": output_cost,
"Total Cost": total_cost,
"Split": "Single-Select Questions"
})
cost_df = pd.DataFrame(results)
model_summary = cost_df.groupby("Model").agg({
"Input Cost": "sum",
"Output Cost": "sum",
"Total Cost": "sum"
}).reset_index()
# Fixed: Using columns that actually exist in the DataFrame
split_summary = cost_df.groupby("Split").agg({
"Questions": "sum", # Changed from "Total Questions"
"Total Input Tokens": "sum",
"Total Output Tokens": "sum",
"Total Cost": "sum"
}).reset_index()
return cost_df, model_summary, split_summary
if selected_models:
detailed_costs, model_summary, split_summary = calculate_costs(
selected_models,
prompt_tokens,
output_tokens,
num_runs,
sampling_percentage
)
total_cost = detailed_costs["Total Cost"].sum()
total_questions = detailed_costs["Questions"][0] # Changed from "Total Questions"
total_input_tokens = detailed_costs["Total Input Tokens"].sum()
total_output_tokens = detailed_costs["Total Output Tokens"].sum()
st.markdown('<div class="section-header">Cost Calculation Breakdown</div>', unsafe_allow_html=True)
with st.expander("View Detailed Cost Calculation Formula", expanded=False):
st.markdown("""
### Cost Calculation Formula
For each model, the cost is calculated as:
```
Input Cost = (Number of Questions × Prompt Tokens per Question × Number of Runs ÷ 1,000,000) × Input Cost per Million Tokens
Output Cost = (Number of Questions × Output Tokens per Question × Number of Runs ÷ 1,000,000) × Output Cost per Million Tokens
Total Cost = Input Cost + Output Cost
```
""")
for model in selected_models:
model_data = detailed_costs[detailed_costs["Model"] == model].iloc[0]
model_input_cost = llm_models[model]["input_cost"]
model_output_cost = llm_models[model]["output_cost"]
model_input_tokens = model_data["Total Input Tokens"]
model_output_tokens = model_data["Total Output Tokens"]
model_input_cost_total = model_data["Input Cost"]
model_output_cost_total = model_data["Output Cost"]
model_total_cost = model_data["Total Cost"]
st.markdown(f"""
#### {model}:
**Input Cost Calculation:**
({total_questions:,} questions × {prompt_tokens} tokens × {num_runs} runs ÷ 1,000,000) × ${model_input_cost:.2f} = ${model_input_cost_total:.2f}
**Output Cost Calculation:**
({total_questions:,} questions × {output_tokens} tokens × {num_runs} runs ÷ 1,000,000) × ${model_output_cost:.2f} = ${model_output_cost_total:.2f}
**Total Cost for {model}:** ${model_total_cost:.2f}
""")
st.markdown(f"""
<div class="info-box">
<div class="section-header">Total Estimated Cost</div>
<div class="cost-highlight">${total_cost:.2f}</div>
<p>For processing {total_questions:,} questions ({sampling_percentage}% of total)
with {len(selected_models)} models, {num_runs} time{'s' if num_runs > 1 else ''}.</p>
<p>Using {prompt_tokens} prompt tokens and {output_tokens} output tokens per question.</p>
<p>Total tokens processed: {total_input_tokens:,} input tokens + {total_output_tokens:,} output tokens = {total_input_tokens + total_output_tokens:,} total tokens</p>
</div>
""", unsafe_allow_html=True)
tab1, tab2 = st.tabs(["Cost Breakdown", "Detailed Costs"])
with tab1:
col1, col2 = st.columns(2)
with col1:
cost_types = ["Input Cost", "Output Cost"]
fig1 = px.bar(
model_summary,
x="Model",
y=cost_types,
title="Cost Breakdown by Model",
labels={"value": "Cost ($)", "variable": "Cost Type"},
color_discrete_sequence=blue_to_gray_palette,
)
fig1.update_layout(legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1))
st.plotly_chart(fig1, use_container_width=True)
with col2:
fig2 = go.Figure(data=[
go.Pie(
labels=model_summary["Model"],
values=model_summary["Total Cost"],
hole=.4,
textinfo="label+percent",
marker_colors=blue_to_gray_palette,
)
])
if "Split" in detailed_costs.columns and len(detailed_costs["Split"].unique()) > 1:
pivot_df = detailed_costs.pivot(index="Split", columns="Model", values="Total Cost")
fig4 = px.imshow(
pivot_df,
labels=dict(x="Model", y="Split", color="Cost ($)"),
x=pivot_df.columns,
y=pivot_df.index,
color_continuous_scale=["#0077b6", "#4a98c9", "#7ba7c5", "#a6b5c1", "#d0d7dc"],
title="Cost Heatmap (Model vs Split)",
text_auto='.2f',
)
fig4.update_layout(height=400)
st.plotly_chart(fig4, use_container_width=True)
with tab2:
# Fixed display columns to match the actual DataFrame columns
display_cols = [
"Model", "Questions", # Changed from "Total Questions"
"Number of Prompt Tokens per Question", "Number of Output Tokens per Question",
"Total Input Tokens", "Total Output Tokens",
"Input Cost", "Output Cost", "Total Cost"
]
formatted_df = detailed_costs[display_cols].copy()
# Format currency columns
for col in ["Input Cost", "Output Cost", "Total Cost"]:
if col in formatted_df.columns:
formatted_df[col] = formatted_df[col].map("${:.2f}".format)
# Format number columns
for col in ["Questions", "Total Input Tokens", "Total Output Tokens"]: # Changed from "Total Questions"
if col in formatted_df.columns:
formatted_df[col] = formatted_df[col].map("{:,}".format)
st.dataframe(formatted_df, use_container_width=True)
st.markdown('<div class="section-header">Export Results</div>', unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
# Round values to 2 decimal places before exporting
export_df = detailed_costs.copy()
for col in ["Input Cost", "Output Cost", "Total Cost"]:
export_df[col] = export_df[col].round(2)
csv = export_df.to_csv(index=False)
st.download_button(
label="Download Full Results (CSV)",
data=csv,
file_name="medmcqa_llm_cost_analysis.csv",
mime="text/csv",
)
with col2:
# Also round values in the JSON export
rounded_costs = detailed_costs.copy()
for col in ["Input Cost", "Output Cost", "Total Cost"]:
rounded_costs[col] = rounded_costs[col].round(2)
export_json = {
"parameters": {
"models": selected_models,
"dataset": "MedMCQA Single-Select Questions",
"total_questions": medmcqa_splits["Single-Select Questions"]["questions"],
"prompt_tokens": prompt_tokens,
"output_tokens": output_tokens,
"sampling_percentage": sampling_percentage,
"num_runs": num_runs
},
"results": {
"total_cost": round(float(total_cost), 2),
"detailed_costs": rounded_costs.to_dict(orient="records"),
"model_summary": model_summary.round(2).to_dict(orient="records")
}
}
st.download_button(
label="Download Full Results (JSON)",
data=json.dumps(export_json, indent=4),
file_name="medmcqa_llm_cost_analysis.json",
mime="application/json",
)
else:
st.info("Please select at least one model and one dataset split to calculate costs.") |