import os import sys from pathlib import Path os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") # --------------------------------------------------------------------------- # `causilo` 1.5 is not on PyPI (PyPI stops at 1.0.3) and its source declares # `torch>=2.13`, which is outside the set of torch versions ZeroGPU supports. # The vendored `causilo/` package in this Space (Apache-2.0, from # https://github.com/nums-ai/causilo @ 84d1718) is therefore put on sys.path # directly — its real dependencies are pinned in requirements.txt and it runs # against the runtime's own torch. # --------------------------------------------------------------------------- sys.path.insert(0, str(Path(__file__).parent)) import spaces # noqa: E402 (must precede any CUDA-touching import) import torch # noqa: E402 import time # noqa: E402 import traceback # noqa: E402 import gradio as gr # noqa: E402 import numpy as np # noqa: E402 import pandas as pd # noqa: E402 from causilo import CausiloClassifier, CausiloRegressor # noqa: E402 from causilo.model_selection import select_checkpoint # noqa: E402 from causilo.v1_5.runtime import make_engine # noqa: E402 MODEL_ID = "nums-ai/causilo-1.5" # The checkpoint's prediction head has 10 output classes. MAX_CLASSES = 10 # Keep a single request comfortably inside the ZeroGPU window. MAX_TOTAL_ROWS = 5_000 MAX_QUERY_ROWS = 2_000 MAX_FEATURES = 100 MAX_ESTIMATORS = 8 PREVIEW_ROWS = 200 print(f"torch {torch.__version__} / causilo 1.5.0 (vendored)", flush=True) # --------------------------------------------------------------------------- # Model loading. Both checkpoints are ~1.1 GB, so they are loaded at module # scope and eagerly placed on CUDA for the ZeroGPU hijack; the fitted context # is built per request against these shared, read-only weights. # `initialize_model` only downloads/builds when a requested device is absent # from `engine._model_replicas`, so warming it once here means every request # reuses the resident replica. # --------------------------------------------------------------------------- ENGINES = {} for task_key in ("classification", "regression"): source = select_checkpoint("1.5", task_key) engine = make_engine(task_key, "cuda", source, memory_budgets={}) engine.initialize_model(1) ENGINES[task_key] = engine print("Causilo 1.5 classifier + regressor loaded.", flush=True) def _make_estimator(task: str, n_estimators: int, seed: int): """Build a scikit-learn estimator bound to the preloaded weights.""" factory = CausiloClassifier if task == "classification" else CausiloRegressor estimator = factory(n_estimators=int(n_estimators), random_state=int(seed), device="cuda") try: estimator._engine = ENGINES[task] estimator._checkpoint_request = ("1.5", None) except Exception as exc: # noqa: BLE001 - fall back to causilo's own lazy load print(f"Preloaded-weight injection unavailable ({exc!r}); loading in-worker.", flush=True) return estimator # --------------------------------------------------------------------------- # Data helpers # --------------------------------------------------------------------------- def _read_csv(path: str) -> pd.DataFrame: df = pd.read_csv(path, skipinitialspace=True) df.columns = [str(c) for c in df.columns] # Drop unnamed index columns pandas leaves behind on round-tripped CSVs. drop = [c for c in df.columns if c.startswith("Unnamed:") and df[c].isna().all()] if drop: df = df.drop(columns=drop) return df def _column_choices(path): """Populate the target-column dropdown from an uploaded CSV.""" if not path: return gr.update(choices=[], value=None) try: cols = list(_read_csv(path).columns) except Exception: # noqa: BLE001 return gr.update(choices=[], value=None) if not cols: return gr.update(choices=[], value=None) return gr.update(choices=cols, value=cols[-1]) def _preview(path): """Show the head of the uploaded CSV so users can see what they loaded.""" if not path: return pd.DataFrame() try: return _read_csv(path).head(8) except Exception: # noqa: BLE001 return pd.DataFrame() def _prepare_features(frame: pd.DataFrame): """Shape an arbitrary table into what Causilo's feature encoder accepts. Causilo handles mixed tables natively: numeric columns stay continuous, object/boolean columns become categorical, and NaNs are a first-class missing-value token. Only three things need fixing up here — datetimes (epoch-encoded), infinities (mapped to NaN), and free-text identifier columns (encodable but pure noise). """ prepared = {} categorical, dropped = [], [] n_rows = len(frame) for name in frame.columns: col = frame[name] if pd.api.types.is_bool_dtype(col): prepared[name] = col.astype(object).where(col.notna(), np.nan) categorical.append(name) continue if pd.api.types.is_datetime64_any_dtype(col): prepared[name] = col.astype("int64").astype("float64") / 1e9 continue if pd.api.types.is_timedelta64_dtype(col): prepared[name] = col.dt.total_seconds().astype("float64") continue if pd.api.types.is_numeric_dtype(col): values = pd.to_numeric(col, errors="coerce").astype("float64") prepared[name] = values.replace([np.inf, -np.inf], np.nan) continue # Mostly-numeric text columns are measurements written as strings. as_num = pd.to_numeric(col, errors="coerce") if as_num.notna().sum() >= 0.9 * max(1, col.notna().sum()): prepared[name] = as_num.astype("float64").replace([np.inf, -np.inf], np.nan) continue text = col.astype("string") n_unique = int(text.nunique(dropna=True)) if n_rows >= 20 and n_unique > 0.9 * n_rows: dropped.append(name) # identifier-like free text continue values = np.array( [np.nan if pd.isna(v) else str(v) for v in text], dtype=object ) prepared[name] = pd.Series(values, index=frame.index, dtype=object) categorical.append(name) if not prepared: raise ValueError("no usable feature columns remain") out = pd.DataFrame(prepared, index=frame.index) empty = [c for c in out.columns if out[c].isna().all()] if empty and len(empty) < out.shape[1]: out = out.drop(columns=empty) dropped.extend(empty) categorical = [c for c in categorical if c in out.columns] return out, categorical, dropped def _numeric_matrix(frame: pd.DataFrame) -> np.ndarray: """Ordinal-encoded float copy, used only for feature ranking and the baseline.""" columns = [] for name in frame.columns: col = frame[name] if pd.api.types.is_numeric_dtype(col): columns.append(pd.to_numeric(col, errors="coerce").astype("float64").to_numpy()) continue codes, _ = pd.factorize(col.astype("string"), use_na_sentinel=True) values = codes.astype("float64") values[codes < 0] = np.nan columns.append(values) return np.column_stack(columns) if columns else np.empty((len(frame), 0)) def _looks_categorical(values: pd.Series) -> bool: clean = values.dropna() if clean.empty: return False if not pd.api.types.is_numeric_dtype(clean): return True n_unique = int(clean.nunique()) if n_unique <= 2: return True integral = bool(np.all(np.equal(np.mod(clean.to_numpy(dtype="float64"), 1), 0))) return integral and n_unique <= MAX_CLASSES def _fmt(value) -> str: if value is None or not np.isfinite(value): return "—" if abs(value) >= 1000 or (abs(value) < 0.001 and value != 0): return f"{value:.4g}" return f"{value:.4f}" def _metrics_table(rows, headers): lines = [ "| " + " | ".join(headers) + " |", "|" + "|".join(["---"] * len(headers)) + "|", ] for row in rows: lines.append("| " + " | ".join(row) + " |") return "\n".join(lines) def _table_shape(path: str): """Cheap (rows, cols) probe so the GPU reservation matches the real workload.""" with open(path, "r", encoding="utf-8", errors="replace") as handle: header = handle.readline() if not header: return 0, 0 n_cols = header.count(",") + 1 n_rows = sum(1 for _ in handle) return n_rows, n_cols def _estimate_duration(csv_file=None, target_column="", task="Auto-detect", holdout_percent=25, n_estimators=MAX_ESTIMATORS, *args, **kwargs) -> int: """Size the ZeroGPU reservation from the table's shape. Measured on this Space (logged by ``run_prediction``): the whole handler -- CSV parse, encode, Causilo fit + predict, the sklearn baseline and table assembly -- takes ~5.7 s wall on a cold worker for the 150x4 iris table (including streaming the 2.42 GB of packed weights into VRAM) and ~5.9 s warm for the 5,000x100 maximum, i.e. roughly 0.25 s per ``unit`` beyond the cold-start floor. ZeroGPU charges a visitor's quota on the *requested* duration, not the actual, so this stays deliberately lean: a 15 s floor covering the cold start, +0.25 s per unit, 25 s hard cap. ``units`` is 1.0 for a 1,000-row x 25-column table at eight members. """ try: rows, cols = _table_shape(csv_file) except Exception: # noqa: BLE001 return 20 rows = min(max(rows, 0), MAX_TOTAL_ROWS) features = min(max(cols - 1, 1), MAX_FEATURES) try: members = max(1, min(int(n_estimators), MAX_ESTIMATORS)) except Exception: # noqa: BLE001 members = MAX_ESTIMATORS units = (rows / 1000.0) * (features / 25.0) * (members / 8.0) return int(min(25, max(15, 15 + 0.25 * units))) def _cap_features(features_df, numeric, y_train, train_mask, is_classification, limit): """Trim very wide tables with a univariate F-test before the model sees them.""" original = features_df.shape[1] if original <= limit: return features_df, None try: from sklearn.feature_selection import f_classif, f_regression train_numeric = numeric[train_mask] means = np.nanmean(train_numeric, axis=0) means = np.where(np.isfinite(means), means, 0.0) filled = np.where(np.isfinite(train_numeric), train_numeric, means) scorer = f_classif if is_classification else f_regression scores = np.asarray(scorer(filled, y_train)[0], dtype="float64") scores = np.where(np.isfinite(scores), scores, -np.inf) keep = np.sort(np.argsort(scores)[::-1][:limit]) except Exception: # noqa: BLE001 keep = np.arange(limit) return features_df.iloc[:, keep], original # --------------------------------------------------------------------------- # Inference # --------------------------------------------------------------------------- @spaces.GPU(duration=_estimate_duration) def run_prediction( csv_file: str, target_column: str = "", task: str = "Auto-detect", holdout_percent: int = 25, n_estimators: int = MAX_ESTIMATORS, seed: int = 42, run_baseline: bool = True, ) -> tuple: """Fit Causilo 1.5 in context on a CSV table and predict its unlabeled rows. Args: csv_file: path to a CSV file. One column is the target; the rest are features. target_column: name of the column to predict. Defaults to the last column. task: "Auto-detect", "Classification" or "Regression". holdout_percent: percentage of labeled rows held out as the query set when the target column has no blank values. n_estimators: number of Causilo ensemble members (1-8). seed: random seed for the holdout split and Causilo's permutations. run_baseline: also fit a gradient-boosting baseline for comparison. Returns: A markdown report and a table of per-row predictions. """ handler_started = time.perf_counter() empty = pd.DataFrame() if not csv_file: return "Upload a CSV file (or click one of the examples below) to start.", empty try: df = _read_csv(csv_file) except Exception as exc: # noqa: BLE001 return f"### Could not read the CSV\n\n```\n{exc}\n```", empty if df.shape[0] < 8 or df.shape[1] < 2: return ( "### Not enough data\n\nThe table needs at least 8 rows and 2 columns " f"(got {df.shape[0]} × {df.shape[1]}).", empty, ) if not target_column or target_column not in df.columns: target_column = df.columns[-1] seed = max(0, int(seed)) members = max(1, min(int(n_estimators), MAX_ESTIMATORS)) notes = [] if len(df) > MAX_TOTAL_ROWS: df = df.sample(n=MAX_TOTAL_ROWS, random_state=seed).sort_index() notes.append(f"Table subsampled to {MAX_TOTAL_ROWS:,} rows for this demo.") y_raw = df[target_column] try: features_df, categorical, dropped = _prepare_features(df.drop(columns=[target_column])) except Exception as exc: # noqa: BLE001 return f"### Could not prepare the features\n\n```\n{exc}\n```", empty # --- split: blank targets are the query set, otherwise hold out a slice --- missing = y_raw.isna().to_numpy() n_missing = int(missing.sum()) if n_missing == len(df): return ( f"### Every **{target_column}** cell is blank\n\nCausilo learns in " "context, so it needs some labeled rows to predict from.", empty, ) if 0 < n_missing < len(df): query_mask = missing has_truth = False split_note = ( f"{n_missing:,} rows have a blank **{target_column}** — those are the " "rows being predicted." ) else: rng = np.random.default_rng(seed) n_query = int(round(len(df) * float(holdout_percent) / 100.0)) n_query = max(1, min(n_query, len(df) - 4, MAX_QUERY_ROWS)) query_mask = np.zeros(len(df), dtype=bool) query_mask[rng.choice(len(df), size=n_query, replace=False)] = True has_truth = True split_note = ( f"No blank targets, so {int(holdout_percent)}% of the rows were held out " "as an unseen query set to score against." ) if int(query_mask.sum()) > MAX_QUERY_ROWS: keep = np.flatnonzero(query_mask)[:MAX_QUERY_ROWS] query_mask = np.zeros(len(df), dtype=bool) query_mask[keep] = True notes.append(f"Query set capped at {MAX_QUERY_ROWS:,} rows for this demo.") train_mask = ~query_mask & ~missing if int(train_mask.sum()) < 4 or int(query_mask.sum()) < 1: return "### Not enough labeled rows to fit and predict.", empty y_train_raw = y_raw[train_mask] # --- task selection ------------------------------------------------------- if task == "Classification": is_classification = True elif task == "Regression": is_classification = False else: is_classification = _looks_categorical(y_train_raw) classes_note = None try: if is_classification: y_train = np.array( [str(v) for v in y_train_raw.astype("string").fillna("")], dtype=object ) n_classes = int(pd.unique(y_train).size) if n_classes < 2: return ( "### Only one class present\n\nClassification needs at least two " f"distinct values in **{target_column}**.", empty, ) if n_classes > MAX_CLASSES: return ( f"### Too many classes ({n_classes})\n\nThe Causilo checkpoint's " f"prediction head supports at most {MAX_CLASSES} classes in its " "native ensemble. Try *Regression* if the target is a continuous " "quantity.", empty, ) classes_note = n_classes else: y_train = pd.to_numeric(y_train_raw, errors="coerce").to_numpy(dtype="float64") finite = np.isfinite(y_train) if not finite.all(): idx = np.flatnonzero(train_mask)[finite] train_mask = np.zeros(len(df), dtype=bool) train_mask[idx] = True y_train = y_train[finite] if y_train.size < 4: return "### Not enough finite numeric targets to fit.", empty except Exception as exc: # noqa: BLE001 return f"### Could not interpret the target column\n\n```\n{exc}\n```", empty numeric = _numeric_matrix(features_df) features_df, original_width = _cap_features( features_df, numeric, y_train, train_mask, is_classification, MAX_FEATURES ) if original_width is not None: numeric = _numeric_matrix(features_df) notes.append( f"Table narrowed from {original_width:,} to {MAX_FEATURES} feature " "columns (univariate F-test) to keep this demo inside its GPU budget." ) X_train = features_df[train_mask] X_query = features_df[query_mask] # --- run Causilo ---------------------------------------------------------- task_key = "classification" if is_classification else "regression" try: started = time.perf_counter() estimator = _make_estimator(task_key, members, seed) estimator.fit(X_train, y_train) fit_seconds = time.perf_counter() - started if is_classification: proba = np.asarray(estimator.predict_proba(X_query), dtype="float64") classes = estimator.classes_ preds = classes[np.argmax(proba, axis=1)] else: preds = np.asarray(estimator.predict(X_query), dtype="float64") proba, classes = None, None total_seconds = time.perf_counter() - started except torch.cuda.OutOfMemoryError: return ( "### Out of GPU memory\n\nTry a smaller table (fewer rows or columns), " "or lower the ensemble size in *Advanced settings*.", empty, ) except Exception as exc: # noqa: BLE001 return ( "### Inference failed\n\n```\n" + "".join(traceback.format_exception_only(type(exc), exc)).strip() + "\n```", empty, ) # --- ground truth + baseline --------------------------------------------- y_true = None if has_truth: truth = y_raw[query_mask] if is_classification: y_true = np.array( [str(v) for v in truth.astype("string").fillna("")], dtype=object ) else: y_true = pd.to_numeric(truth, errors="coerce").to_numpy(dtype="float64") baseline_preds = None baseline_seconds = None if run_baseline: try: b_started = time.perf_counter() if is_classification: from sklearn.ensemble import HistGradientBoostingClassifier base = HistGradientBoostingClassifier(random_state=seed) else: from sklearn.ensemble import HistGradientBoostingRegressor base = HistGradientBoostingRegressor(random_state=seed) base.fit(numeric[train_mask], y_train) baseline_preds = base.predict(numeric[query_mask]) baseline_seconds = time.perf_counter() - b_started except Exception: # noqa: BLE001 baseline_preds, baseline_seconds = None, None def score(true, pred): if is_classification: from sklearn.metrics import accuracy_score, balanced_accuracy_score return [ _fmt(float(accuracy_score(true, pred))), _fmt(float(balanced_accuracy_score(true, pred))), ] from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score return [ _fmt(float(r2_score(true, pred))), _fmt(float(np.sqrt(mean_squared_error(true, pred)))), _fmt(float(mean_absolute_error(true, pred))), ] metric_rows, headers = [], [] if has_truth and y_true is not None: valid = ( np.array([v not in ("", "nan") for v in y_true]) if is_classification else np.isfinite(y_true) ) if valid.any(): headers = ( ["Model", "Accuracy ↑", "Balanced acc. ↑", "Time (s)"] if is_classification else ["Model", "R² ↑", "RMSE ↓", "MAE ↓", "Time (s)"] ) metric_rows.append( ["**Causilo 1.5**"] + score(y_true[valid], np.asarray(preds)[valid]) + [_fmt(total_seconds)] ) if baseline_preds is not None: metric_rows.append( ["Gradient boosting (sklearn)"] + score(y_true[valid], np.asarray(baseline_preds)[valid]) + [_fmt(baseline_seconds)] ) # --- prediction table ----------------------------------------------------- query_index = np.flatnonzero(query_mask) table = {"row": query_index + 2} # +2 -> 1-based CSV line incl. header table[f"predicted_{target_column}"] = preds if is_classification and proba is not None: table["confidence"] = np.max(proba, axis=1).round(4) if has_truth and y_true is not None: table[f"actual_{target_column}"] = y_true if is_classification: table["correct"] = np.asarray(preds) == y_true else: table["error"] = np.round(np.asarray(preds) - y_true, 4) if baseline_preds is not None: table["baseline_prediction"] = baseline_preds if is_classification and proba is not None and classes is not None: for i, cls in enumerate(classes): table[f"p({cls})"] = proba[:, i].round(4) result_df = pd.DataFrame(table) for col in result_df.columns: if pd.api.types.is_float_dtype(result_df[col]): result_df[col] = result_df[col].round(4) shown = result_df.head(PREVIEW_ROWS) # --- report --------------------------------------------------------------- task_name = "Classification" if is_classification else "Regression" lines = [ f"### {task_name} — predicting `{target_column}`", "", f"- **Table**: {df.shape[0]:,} rows × {features_df.shape[1]:,} feature columns", f"- **In-context support set**: {int(train_mask.sum()):,} labeled rows", f"- **Predicted**: {len(query_index):,} rows", f"- **Fit + predict**: {total_seconds:.2f} s " f"(fit {fit_seconds:.2f} s, predict {total_seconds - fit_seconds:.2f} s) " f"with {members} ensemble member(s)", ] if is_classification and classes is not None: lines.append( f"- **Classes** ({classes_note}): " + ", ".join(f"`{c}`" for c in classes[:MAX_CLASSES]) ) lines.append(f"- {split_note}") if categorical: kept = [c for c in categorical if c in features_df.columns] if kept: lines.append( f"- **{len(kept)} categorical column(s)** passed to Causilo as " "categories (no manual encoding): " + ", ".join(f"`{c}`" for c in kept[:8]) + (" …" if len(kept) > 8 else "") ) if dropped: lines.append( f"- **Dropped {len(dropped)} column(s)** (identifier-like or all-missing): " + ", ".join(f"`{c}`" for c in dropped[:8]) + (" …" if len(dropped) > 8 else "") ) for note in notes: lines.append(f"- {note}") if metric_rows: lines += ["", "#### Held-out scores", "", _metrics_table(metric_rows, headers)] elif not has_truth: lines += ["", "_No ground truth for these rows — predictions only._"] if len(result_df) > PREVIEW_ROWS: lines += [ "", f"_Showing the first {PREVIEW_ROWS} of {len(result_df):,} predicted rows._", ] print( f"[causilo] {task_name.lower()} {df.shape[0]}x{features_df.shape[1]} " f"members={members} causilo={total_seconds:.2f}s " f"handler={time.perf_counter() - handler_started:.2f}s " f"reserved={_estimate_duration(csv_file, n_estimators=members)}s", flush=True, ) return "\n".join(lines), shown # --------------------------------------------------------------------------- # UI # --------------------------------------------------------------------------- CSS = """ #col-container { max-width: 1180px; margin: 0 auto; } .dark .gradio-container { color: var(--body-text-color); } """ INTRO = """# Causilo 1.5 — tabular foundation model Upload a CSV, pick the column to predict, and [**nums-ai/causilo-1.5**](https://huggingface.co/nums-ai/causilo-1.5) predicts it **in context** — no gradient training, no hyperparameter search. Causilo 1.5 is ranked **#1 on TabArena, BeyondArena, TALENT and six more tabular leaderboards**. Rows whose target cell is **blank** are the ones predicted. If nothing is blank, a slice of the table is held out so you can see how the model scores on rows it never saw. Text and boolean columns are handled as categories natively, and missing values are fine. """ with gr.Blocks(title="Causilo 1.5") as demo: with gr.Column(elem_id="col-container"): gr.Markdown(INTRO) with gr.Row(): with gr.Column(scale=2): csv_file = gr.File(label="CSV table", file_types=[".csv"], type="filepath") with gr.Column(scale=2): target_dd = gr.Dropdown( label="Target column (what to predict)", choices=[], value=None, allow_custom_value=True, info="Defaults to the last column of the CSV.", ) task_radio = gr.Radio( label="Task", choices=["Auto-detect", "Classification", "Regression"], value="Auto-detect", ) run_btn = gr.Button("Predict", variant="primary") with gr.Accordion("Uploaded table (first rows)", open=False): head_df = gr.Dataframe(interactive=False, wrap=True) summary = gr.Markdown("Upload a CSV or click an example below.") table_out = gr.Dataframe(label="Predictions", interactive=False, wrap=True) with gr.Accordion("Advanced settings", open=False): holdout = gr.Slider( label="Held-out query rows (%)", minimum=5, maximum=50, step=5, value=25, info="Used only when the target column has no blank cells.", ) estimators = gr.Slider( label="Ensemble members (n_estimators)", minimum=1, maximum=MAX_ESTIMATORS, step=1, value=MAX_ESTIMATORS, info="Causilo 1.5's default and benchmark setting is 8.", ) seed_box = gr.Number(label="Random seed", value=42, precision=0) baseline = gr.Checkbox( label="Compare against a gradient-boosting baseline", value=True ) gr.Examples( examples=[ ["examples/iris.csv"], ["examples/wine.csv"], ["examples/breast_cancer.csv"], ["examples/diabetes.csv"], ["examples/iris_unlabeled.csv"], ], inputs=[csv_file], outputs=[summary, table_out], fn=run_prediction, cache_examples=True, cache_mode="lazy", label="Examples — the datasets from Causilo's own example scripts", ) gr.Markdown( "The Causilo 1.5 **weights are licensed under the Nums AI Model License** " "(non-commercial research, testing and evaluation permitted; commercial, " "production and hosted/API/SaaS use require a separate license from " "Nums AI Inc.). Runtime code: " "[`causilo`](https://github.com/nums-ai/causilo) (Apache-2.0). " "Model card: [nums-ai/causilo-1.5](https://huggingface.co/nums-ai/causilo-1.5)." ) csv_file.change(_column_choices, inputs=csv_file, outputs=target_dd) csv_file.change(_preview, inputs=csv_file, outputs=head_df) run_btn.click( run_prediction, inputs=[csv_file, target_dd, task_radio, holdout, estimators, seed_box, baseline], outputs=[summary, table_out], api_name="predict", ) if __name__ == "__main__": # Gradio 6 moved `theme` / `css` from the Blocks constructor to launch(). demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)