|
| 1 | +"""Optional TabPFN-3 GPU comparison using the forest demo's exact synthetic split. |
| 2 | +
|
| 3 | +Requires a separately downloaded, hash-verified checkpoint. Does not serve a model. |
| 4 | +""" |
| 5 | + |
| 6 | +import argparse |
| 7 | +from hashlib import file_digest |
| 8 | +from importlib.metadata import version |
| 9 | +import json |
| 10 | +from pathlib import Path |
| 11 | +import platform |
| 12 | +from time import perf_counter |
| 13 | + |
| 14 | +from .forest_demo import SETTLED, feature_matrix, generate_rows, run_demo, temporal_split |
| 15 | + |
| 16 | + |
| 17 | +MODEL_REPO = "Prior-Labs/tabpfn_3" |
| 18 | +MODEL_REVISION = "24a16a89d245878b846555110985634aa2e656d7" |
| 19 | +MODEL_FILENAME = "tabpfn-v3-classifier-v3_default.ckpt" |
| 20 | +MODEL_SHA256 = "d0d865d54dfbc524f5703104be90620182dca7e5fb2c16de72e9959ea18f3988" |
| 21 | +MODEL_LICENCE = "https://huggingface.co/Prior-Labs/tabpfn_3/blob/" + MODEL_REVISION + "/LICENSE" |
| 22 | + |
| 23 | + |
| 24 | +def verify_checkpoint(path, expected_sha256): |
| 25 | + if len(expected_sha256) != 64 or any(c not in "0123456789abcdef" for c in expected_sha256): |
| 26 | + raise ValueError("checkpoint SHA-256 must be 64 lowercase hexadecimal characters") |
| 27 | + with Path(path).open("rb") as stream: |
| 28 | + actual = file_digest(stream, "sha256").hexdigest() |
| 29 | + if actual != expected_sha256: |
| 30 | + raise ValueError("checkpoint hash mismatch; refusing to load model") |
| 31 | + return actual |
| 32 | + |
| 33 | + |
| 34 | +def predict_independently(estimator, rows): |
| 35 | + """A future test row must not enter an earlier row's preprocessing/context.""" |
| 36 | + import numpy as np |
| 37 | + |
| 38 | + classes = list(estimator.classes_) |
| 39 | + if set(classes) != {0, 1}: |
| 40 | + raise ValueError("expected classes 0=not_met and 1=met") |
| 41 | + positive_column = classes.index(1) |
| 42 | + predictions = [] |
| 43 | + for row in rows: |
| 44 | + output = np.asarray(estimator.predict_proba(np.asarray([row], dtype=float))) |
| 45 | + if output.shape != (1, 2) or not np.isfinite(output).all(): |
| 46 | + raise ValueError("invalid probability response") |
| 47 | + if (output < 0).any() or (output > 1).any() or not np.allclose(output.sum(axis=1), 1): |
| 48 | + raise ValueError("invalid probability distribution") |
| 49 | + predictions.append(float(output[0, positive_column])) |
| 50 | + return np.asarray(predictions) |
| 51 | + |
| 52 | + |
| 53 | +def comparison(checkpoint, expected_sha256, samples=300, seed=42, gpu_memory_gib=4): |
| 54 | + checkpoint = Path(checkpoint).resolve() |
| 55 | + if expected_sha256 != MODEL_SHA256: |
| 56 | + raise ValueError("this adapter pins one checkpoint; update its provenance before changing weights") |
| 57 | + checkpoint_hash = verify_checkpoint(checkpoint, expected_sha256) |
| 58 | + if checkpoint.name != MODEL_FILENAME: |
| 59 | + raise ValueError("use the explicitly documented TabPFN-3 checkpoint filename") |
| 60 | + if not 0 < gpu_memory_gib <= 8: |
| 61 | + raise ValueError("GPU allocation budget must be greater than 0 and at most 8 GiB") |
| 62 | + |
| 63 | + import torch |
| 64 | + from sklearn.metrics import accuracy_score, brier_score_loss, log_loss |
| 65 | + from tabpfn import TabPFNClassifier |
| 66 | + |
| 67 | + if not torch.cuda.is_available(): |
| 68 | + raise ValueError("this experiment requires a working CUDA GPU; no silent CPU fallback") |
| 69 | + properties = torch.cuda.get_device_properties(0) |
| 70 | + budget_bytes = int(gpu_memory_gib * 1024**3) |
| 71 | + torch.cuda.set_per_process_memory_fraction(min(1.0, budget_bytes / properties.total_memory), 0) |
| 72 | + torch.set_num_threads(2) |
| 73 | + torch.manual_seed(seed) |
| 74 | + torch.cuda.reset_peak_memory_stats(0) |
| 75 | + |
| 76 | + baseline_start = perf_counter() |
| 77 | + report = run_demo(samples, seed) |
| 78 | + baseline_seconds = perf_counter() - baseline_start |
| 79 | + rows = generate_rows(samples, seed) |
| 80 | + train, test, excluded = temporal_split(rows, report["training_cutoff"], report["test_start"], report["evaluation_as_of"]) |
| 81 | + if [r["initiative_id"] for r in train] != report["training_initiatives"]: |
| 82 | + raise ValueError("training split differs from baseline") |
| 83 | + if [r["initiative_id"] for r in test] != [r["initiative_id"] for r in report["test_predictions"]]: |
| 84 | + raise ValueError("test split differs from baseline") |
| 85 | + if excluded != report["counts"]["excluded"]: |
| 86 | + raise ValueError("exclusion policy differs from baseline") |
| 87 | + |
| 88 | + import numpy as np |
| 89 | + |
| 90 | + x_train, x_test = feature_matrix(train), feature_matrix(test) |
| 91 | + y_train = np.asarray([SETTLED[r["label_status"]] for r in train]) |
| 92 | + y_test = np.asarray([SETTLED[r["label_status"]] for r in test]) |
| 93 | + estimator = TabPFNClassifier( |
| 94 | + model_path=checkpoint, device="cuda", random_state=seed, |
| 95 | + n_estimators=4, auto_scale_n_estimators=False, n_preprocessing_jobs=1, |
| 96 | + fit_mode="fit_preprocessors", softmax_temperature=0.9, |
| 97 | + ) |
| 98 | + torch.cuda.synchronize() |
| 99 | + start = perf_counter() |
| 100 | + estimator.fit(np.asarray(x_train, dtype=float), y_train) |
| 101 | + torch.cuda.synchronize() |
| 102 | + fit_seconds = perf_counter() - start |
| 103 | + start = perf_counter() |
| 104 | + predicted = predict_independently(estimator, x_test) |
| 105 | + torch.cuda.synchronize() |
| 106 | + predict_seconds = perf_counter() - start |
| 107 | + report["metrics"]["tabpfn_3"] = { |
| 108 | + "brier_score": float(brier_score_loss(y_test, predicted)), |
| 109 | + "log_loss": float(log_loss(y_test, predicted, labels=[0, 1])), |
| 110 | + "accuracy_at_0_5": float(accuracy_score(y_test, predicted >= 0.5)), |
| 111 | + } |
| 112 | + for row, probability in zip(report["test_predictions"], predicted): |
| 113 | + row["tabpfn_3"] = float(probability) |
| 114 | + report["environment"].update({p: version(p) for p in ("tabpfn", "torch", "huggingface-hub")}) |
| 115 | + report["environment"].update({"python": platform.python_version(), "architecture": platform.machine(), |
| 116 | + "gpu": properties.name, "cuda_runtime": torch.version.cuda}) |
| 117 | + report["candidate"] = { |
| 118 | + "name": "TabPFN-3", "repository": MODEL_REPO, "revision": MODEL_REVISION, |
| 119 | + "filename": checkpoint.name, "sha256": checkpoint_hash, "licence": MODEL_LICENCE, |
| 120 | + "n_estimators": 4, "random_state": seed, "device": "cuda", "n_preprocessing_jobs": 1, |
| 121 | + "auto_scale_n_estimators": False, "fit_mode": "fit_preprocessors", "softmax_temperature": 0.9, |
| 122 | + "prediction_protocol": "one_test_row_per_call_with_fixed_training_context", |
| 123 | + "gpu_allocator_budget_gib": gpu_memory_gib, |
| 124 | + "peak_torch_allocated_bytes": torch.cuda.max_memory_allocated(0), |
| 125 | + "peak_torch_reserved_bytes": torch.cuda.max_memory_reserved(0), |
| 126 | + } |
| 127 | + report["timing_seconds"] = { |
| 128 | + "complete_baseline_demo": baseline_seconds, |
| 129 | + "tabpfn_fit_including_model_loading": fit_seconds, |
| 130 | + "tabpfn_predict_all_test_rows_individually": predict_seconds, |
| 131 | + } |
| 132 | + report["implementation_sha256"] = {} |
| 133 | + for name in ("forest_demo.py", "tabpfn_demo.py"): |
| 134 | + with Path(__file__).with_name(name).open("rb") as stream: |
| 135 | + report["implementation_sha256"][name] = file_digest(stream, "sha256").hexdigest() |
| 136 | + report["limitations"].extend([ |
| 137 | + "One pretrained checkpoint, one synthetic generator and seed; no claim of model superiority or organisational validity.", |
| 138 | + "TabPFN has external pretraining; this comparison does not isolate architecture from pretraining.", |
| 139 | + "GPU timing is from a shared machine and single-row prediction; not a controlled hardware speed benchmark.", |
| 140 | + "CUDA seeds do not guarantee bitwise reproducibility across platforms or library versions.", |
| 141 | + "Allocator budget is not a hard bound on all process or unified-memory use.", |
| 142 | + "TabPFN-3 weights and outputs have their own non-commercial licence; the repository MIT licence does not replace it.", |
| 143 | + ]) |
| 144 | + return report |
| 145 | + |
| 146 | + |
| 147 | +def main(): |
| 148 | + parser = argparse.ArgumentParser(description=__doc__) |
| 149 | + parser.add_argument("--checkpoint", type=Path, required=True) |
| 150 | + parser.add_argument("--checkpoint-sha256", default=MODEL_SHA256) |
| 151 | + parser.add_argument("--samples", type=int, default=300) |
| 152 | + parser.add_argument("--seed", type=int, default=42) |
| 153 | + parser.add_argument("--gpu-memory-gib", type=float, default=4) |
| 154 | + parser.add_argument("--output", type=Path, required=True) |
| 155 | + args = parser.parse_args() |
| 156 | + try: |
| 157 | + if args.output.exists(): |
| 158 | + raise ValueError("output already exists; choose a new report filename") |
| 159 | + report = comparison(args.checkpoint, args.checkpoint_sha256, args.samples, args.seed, args.gpu_memory_gib) |
| 160 | + args.output.parent.mkdir(parents=True, exist_ok=True) |
| 161 | + with args.output.open("x") as stream: |
| 162 | + json.dump(report, stream, indent=2, allow_nan=False) |
| 163 | + stream.write("\n") |
| 164 | + except ModuleNotFoundError as error: |
| 165 | + parser.exit(1, f"Missing optional dependency: {error.name}. See docs/tabpfn-comparison.md.\n") |
| 166 | + except (ValueError, OSError) as error: |
| 167 | + parser.exit(1, f"error: {error}\n") |
| 168 | + print("SYNTHETIC GPU COMPARISON — not evidence of organisational prediction quality") |
| 169 | + print(f"Train: {report['counts']['train']}; test: {report['counts']['test']}; generator seed: {report['seed']}") |
| 170 | + print("Model Brier (lower) Log loss (lower) Accuracy @ 0.5") |
| 171 | + for name, metrics in report["metrics"].items(): |
| 172 | + print(f"{name:25} {metrics['brier_score']:.4f} {metrics['log_loss']:.4f} {metrics['accuracy_at_0_5']:.4f}") |
| 173 | + print(f"TabPFN-3: checkpoint {report['candidate']['sha256']}") |
| 174 | + print(f"Report: {args.output}") |
| 175 | + |
| 176 | + |
| 177 | +if __name__ == "__main__": |
| 178 | + main() |
0 commit comments