Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,136 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
from datasets import load_dataset
|
| 5 |
from sklearn.ensemble import RandomForestRegressor
|
| 6 |
-
from sklearn.metrics import r2_score
|
| 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 |
model.fit(X_train, y_train)
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
ax1.scatter(y_test,
|
| 66 |
-
|
|
|
|
|
|
|
| 67 |
ax1.set_xlabel("True value")
|
| 68 |
-
ax1.set_ylabel("Predicted")
|
| 69 |
-
ax1.set_title(f"Predictions vs
|
| 70 |
|
| 71 |
-
# Важность признаков
|
| 72 |
importances = model.feature_importances_
|
| 73 |
-
|
| 74 |
-
ax2.barh(range(len(
|
| 75 |
-
ax2.set_yticks(range(len(
|
| 76 |
-
ax2.set_yticklabels([
|
| 77 |
ax2.set_xlabel("Feature importance")
|
| 78 |
-
ax2.set_title("Top 10
|
| 79 |
|
| 80 |
plt.tight_layout()
|
| 81 |
-
explanation = f"""
|
| 82 |
-
**R² score:** {r2:.4f}
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
- 0.0 = model predicts the mean (no better than guessing)
|
| 88 |
-
- Negative values = model performs worse than guessing the mean.
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
|
| 93 |
-
👉 **Our full datasets** contain up to 200,000 circuits, additional noise models, and more features – perfect for serious Quantum Machine Learning research.
|
| 94 |
-
"""
|
| 95 |
return fig, explanation
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
import gradio as gr
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
from datasets import load_dataset
|
| 9 |
from sklearn.ensemble import RandomForestRegressor
|
| 10 |
+
from sklearn.metrics import mean_absolute_error, r2_score
|
| 11 |
+
from sklearn.model_selection import train_test_split
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# =========================================================
|
| 15 |
+
# CONFIG
|
| 16 |
+
# =========================================================
|
| 17 |
+
HF_DATASET_NAME = "QSBench/QSBench-Core-v1.0.0-demo"
|
| 18 |
+
LOCAL_BENCHMARK_CSV = "noise_benchmark_results.csv"
|
| 19 |
+
|
| 20 |
+
TARGET_COL = "ideal_expval_Z_global"
|
| 21 |
+
|
| 22 |
+
EXCLUDE_COLS = {
|
| 23 |
+
"sample_id",
|
| 24 |
+
"sample_seed",
|
| 25 |
+
"ideal_expval_Z_global",
|
| 26 |
+
"ideal_expval_X_global",
|
| 27 |
+
"ideal_expval_Y_global",
|
| 28 |
+
"noisy_expval_Z_global",
|
| 29 |
+
"noisy_expval_X_global",
|
| 30 |
+
"noisy_expval_Y_global",
|
| 31 |
+
"error_Z_global",
|
| 32 |
+
"error_X_global",
|
| 33 |
+
"error_Y_global",
|
| 34 |
+
"sign_ideal_Z_global",
|
| 35 |
+
"sign_noisy_Z_global",
|
| 36 |
+
"sign_ideal_X_global",
|
| 37 |
+
"sign_noisy_X_global",
|
| 38 |
+
"sign_ideal_Y_global",
|
| 39 |
+
"sign_noisy_Y_global",
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
MODEL_PARAMS = dict(
|
| 43 |
+
n_estimators=80,
|
| 44 |
+
max_depth=10,
|
| 45 |
+
min_samples_leaf=2,
|
| 46 |
+
random_state=42,
|
| 47 |
+
n_jobs=-1,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# =========================================================
|
| 52 |
+
# DATA LOADING
|
| 53 |
+
# =========================================================
|
| 54 |
+
def load_demo_dataset() -> pd.DataFrame:
|
| 55 |
+
ds_all = load_dataset(HF_DATASET_NAME)
|
| 56 |
+
df_all = pd.DataFrame(ds_all["train"])
|
| 57 |
+
return df_all
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def split_by_split_column(df: pd.DataFrame) -> dict:
|
| 61 |
+
if "split" not in df.columns:
|
| 62 |
+
return {"all": df.reset_index(drop=True)}
|
| 63 |
+
|
| 64 |
+
splits = {}
|
| 65 |
+
for split_name in df["split"].dropna().astype(str).unique():
|
| 66 |
+
splits[split_name] = df[df["split"].astype(str) == split_name].reset_index(drop=True)
|
| 67 |
+
return splits
|
| 68 |
+
|
| 69 |
|
| 70 |
+
def get_numeric_feature_cols(df: pd.DataFrame) -> list[str]:
|
| 71 |
+
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
|
| 72 |
+
feature_cols = [c for c in numeric_cols if c not in EXCLUDE_COLS and not c.startswith("error_")]
|
| 73 |
+
return feature_cols
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def load_benchmark_results() -> pd.DataFrame:
|
| 77 |
+
path = Path(LOCAL_BENCHMARK_CSV)
|
| 78 |
+
if not path.exists():
|
| 79 |
+
return pd.DataFrame(
|
| 80 |
+
[
|
| 81 |
+
{
|
| 82 |
+
"dataset": "noise_benchmark_results.csv not found",
|
| 83 |
+
"split_used": "",
|
| 84 |
+
"n_samples": 0,
|
| 85 |
+
"r2": np.nan,
|
| 86 |
+
"mae": np.nan,
|
| 87 |
+
"avg_noise_prob": np.nan,
|
| 88 |
+
"status": "missing_file",
|
| 89 |
+
}
|
| 90 |
+
]
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
df = pd.read_csv(path)
|
| 94 |
+
return df
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# =========================================================
|
| 98 |
+
# DATA EXPLORER TAB
|
| 99 |
+
# =========================================================
|
| 100 |
+
def show_data(split_name, splits_cache):
|
| 101 |
+
if not splits_cache:
|
| 102 |
+
return pd.DataFrame([{"message": "Dataset not loaded"}])
|
| 103 |
+
|
| 104 |
+
if split_name in splits_cache:
|
| 105 |
+
return splits_cache[split_name].head(10)
|
| 106 |
+
|
| 107 |
+
first_key = next(iter(splits_cache.keys()))
|
| 108 |
+
return splits_cache[first_key].head(10)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# =========================================================
|
| 112 |
+
# MODEL DEMO TAB
|
| 113 |
+
# =========================================================
|
| 114 |
+
def train_model_demo(df: pd.DataFrame):
|
| 115 |
+
if TARGET_COL not in df.columns:
|
| 116 |
+
return None, "Target column not found."
|
| 117 |
+
|
| 118 |
+
feature_cols = get_numeric_feature_cols(df)
|
| 119 |
+
if not feature_cols:
|
| 120 |
+
return None, "No numeric feature columns found."
|
| 121 |
+
|
| 122 |
+
work_df = df.dropna(subset=feature_cols + [TARGET_COL]).reset_index(drop=True)
|
| 123 |
+
|
| 124 |
+
X = work_df[feature_cols]
|
| 125 |
+
y = work_df[TARGET_COL]
|
| 126 |
+
|
| 127 |
+
if len(work_df) < 20:
|
| 128 |
+
return None, "Not enough rows for a stable demo."
|
| 129 |
+
|
| 130 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 131 |
+
X, y, test_size=0.2, random_state=42
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
model = RandomForestRegressor(**MODEL_PARAMS)
|
| 135 |
model.fit(X_train, y_train)
|
| 136 |
+
preds = model.predict(X_test)
|
| 137 |
+
|
| 138 |
+
r2 = r2_score(y_test, preds)
|
| 139 |
+
mae = mean_absolute_error(y_test, preds)
|
| 140 |
|
| 141 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13, 5))
|
| 142 |
+
|
| 143 |
+
ax1.scatter(y_test, preds, alpha=0.6)
|
| 144 |
+
min_v = min(float(y_test.min()), float(np.min(preds)))
|
| 145 |
+
max_v = max(float(y_test.max()), float(np.max(preds)))
|
| 146 |
+
ax1.plot([min_v, max_v], [min_v, max_v], linestyle="--")
|
| 147 |
ax1.set_xlabel("True value")
|
| 148 |
+
ax1.set_ylabel("Predicted value")
|
| 149 |
+
ax1.set_title(f"Predictions vs Truth\nR² = {r2:.4f}, MAE = {mae:.4f}")
|
| 150 |
|
|
|
|
| 151 |
importances = model.feature_importances_
|
| 152 |
+
top_idx = np.argsort(importances)[-10:]
|
| 153 |
+
ax2.barh(range(len(top_idx)), importances[top_idx])
|
| 154 |
+
ax2.set_yticks(range(len(top_idx)))
|
| 155 |
+
ax2.set_yticklabels([feature_cols[i] for i in top_idx])
|
| 156 |
ax2.set_xlabel("Feature importance")
|
| 157 |
+
ax2.set_title("Top 10 features")
|
| 158 |
|
| 159 |
plt.tight_layout()
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
explanation = f"""
|
| 162 |
+
**R² score:** {r2:.4f}
|
| 163 |
+
**MAE:** {mae:.4f}
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
This is a lightweight baseline on the demo dataset. The point is not to get a perfect score, but to show that the dataset contains real structure and can support quantum ML experiments.
|
| 166 |
+
"""
|
| 167 |
|
|
|
|
|
|
|
| 168 |
return fig, explanation
|
| 169 |
|
| 170 |
+
|
| 171 |
+
# =========================================================
|
| 172 |
+
# BENCHMARK TAB
|
| 173 |
+
# =========================================================
|
| 174 |
+
def make_bar_plot(df: pd.DataFrame, value_col: str, title: str, ylabel: str):
|
| 175 |
+
fig, ax = plt.subplots(figsize=(9, 4.8))
|
| 176 |
+
if df.empty or value_col not in df.columns or "dataset" not in df.columns:
|
| 177 |
+
ax.text(0.5, 0.5, "No benchmark data available", ha="center", va="center")
|
| 178 |
+
ax.axis("off")
|
| 179 |
+
return fig
|
| 180 |
+
|
| 181 |
+
plot_df = df.copy()
|
| 182 |
+
plot_df = plot_df.dropna(subset=[value_col])
|
| 183 |
+
|
| 184 |
+
ax.bar(plot_df["dataset"].astype(str), plot_df[value_col].astype(float))
|
| 185 |
+
ax.set_title(title)
|
| 186 |
+
ax.set_xlabel("Dataset")
|
| 187 |
+
ax.set_ylabel(ylabel)
|
| 188 |
+
ax.tick_params(axis="x", rotation=20)
|
| 189 |
+
ax.axhline(0, linewidth=1)
|
| 190 |
+
plt.tight_layout()
|
| 191 |
+
return fig
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def build_benchmark_dashboard():
|
| 195 |
+
df = load_benchmark_results()
|
| 196 |
+
|
| 197 |
+
explanation = """
|
| 198 |
+
### Noise robustness benchmark
|
| 199 |
+
|
| 200 |
+
This dashboard shows how a model trained on clean circuits behaves on:
|
| 201 |
+
- **core_clean**
|
| 202 |
+
- **depolarizing**
|
| 203 |
+
- **amplitude_damping**
|
| 204 |
+
- **transpilation**
|
| 205 |
+
|
| 206 |
+
A sharp drop in R² indicates strong distribution shift. That is exactly the value of the larger QSBench packs.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
r2_fig = make_bar_plot(df, "r2", "Noise Robustness Benchmark — R²", "R²")
|
| 210 |
+
mae_fig = make_bar_plot(df, "mae", "Noise Robustness Benchmark — MAE", "MAE")
|
| 211 |
+
|
| 212 |
+
return df, r2_fig, mae_fig, explanation
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# =========================================================
|
| 216 |
+
# APP
|
| 217 |
+
# =========================================================
|
| 218 |
+
def main():
|
| 219 |
+
print("Loading demo dataset...")
|
| 220 |
+
df_all = load_demo_dataset()
|
| 221 |
+
splits_cache = split_by_split_column(df_all)
|
| 222 |
+
split_choices = list(splits_cache.keys())
|
| 223 |
+
|
| 224 |
+
default_split = split_choices[0] if split_choices else None
|
| 225 |
+
|
| 226 |
+
with gr.Blocks(title="QSBench Demo Explorer") as demo:
|
| 227 |
+
gr.Markdown(
|
| 228 |
+
"""
|
| 229 |
+
# QSBench Demo Explorer
|
| 230 |
+
|
| 231 |
+
Interactive demo for the QSBench Core demo dataset and precomputed noise robustness benchmark.
|
| 232 |
+
"""
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
with gr.Tabs():
|
| 236 |
+
with gr.TabItem("Data Explorer"):
|
| 237 |
+
gr.Markdown("Inspect the demo dataset split by split.")
|
| 238 |
+
split_selector = gr.Dropdown(
|
| 239 |
+
choices=split_choices,
|
| 240 |
+
value=default_split,
|
| 241 |
+
label="Choose a split",
|
| 242 |
+
)
|
| 243 |
+
data_table = gr.Dataframe(label="First 10 rows", interactive=False)
|
| 244 |
+
|
| 245 |
+
split_selector.change(
|
| 246 |
+
fn=lambda s: show_data(s, splits_cache),
|
| 247 |
+
inputs=split_selector,
|
| 248 |
+
outputs=data_table,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
demo.load(
|
| 252 |
+
fn=lambda: show_data(default_split, splits_cache),
|
| 253 |
+
inputs=[],
|
| 254 |
+
outputs=data_table,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
with gr.TabItem("Model Demo"):
|
| 258 |
+
gr.Markdown(
|
| 259 |
+
"""
|
| 260 |
+
Train a lightweight Random Forest baseline on the demo data and inspect predictions.
|
| 261 |
+
"""
|
| 262 |
+
)
|
| 263 |
+
train_button = gr.Button("Train model")
|
| 264 |
+
plot_output = gr.Plot()
|
| 265 |
+
text_output = gr.Markdown()
|
| 266 |
+
|
| 267 |
+
train_button.click(
|
| 268 |
+
fn=lambda: train_model_demo(df_all),
|
| 269 |
+
inputs=[],
|
| 270 |
+
outputs=[plot_output, text_output],
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
with gr.TabItem("Noise Robustness Benchmark"):
|
| 274 |
+
gr.Markdown(
|
| 275 |
+
"""
|
| 276 |
+
This tab loads the precomputed local benchmark results from `noise_benchmark_results.csv`.
|
| 277 |
+
"""
|
| 278 |
+
)
|
| 279 |
+
refresh_button = gr.Button("Load benchmark results")
|
| 280 |
+
benchmark_table = gr.Dataframe(label="Benchmark results", interactive=False)
|
| 281 |
+
r2_plot = gr.Plot(label="R² plot")
|
| 282 |
+
mae_plot = gr.Plot(label="MAE plot")
|
| 283 |
+
benchmark_text = gr.Markdown()
|
| 284 |
+
|
| 285 |
+
refresh_button.click(
|
| 286 |
+
fn=build_benchmark_dashboard,
|
| 287 |
+
inputs=[],
|
| 288 |
+
outputs=[benchmark_table, r2_plot, mae_plot, benchmark_text],
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
demo.load(
|
| 292 |
+
fn=build_benchmark_dashboard,
|
| 293 |
+
inputs=[],
|
| 294 |
+
outputs=[benchmark_table, r2_plot, mae_plot, benchmark_text],
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
gr.Markdown("---")
|
| 298 |
+
gr.Markdown(
|
| 299 |
+
"""
|
| 300 |
+
### What this demo shows
|
| 301 |
+
|
| 302 |
+
- Data Explorer: inspect the dataset splits
|
| 303 |
+
- Model Demo: quick baseline on the demo data
|
| 304 |
+
- Noise Robustness Benchmark: precomputed results that show how performance changes across clean, noisy, and transpiled datasets
|
| 305 |
+
"""
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
demo.launch()
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
if __name__ == "__main__":
|
| 312 |
+
main()
|