{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CYB009 Baseline Classifier — Inference Example\n", "\n", "End-to-end demo: load the trained XGBoost and PyTorch MLP models from the Hugging Face repo and predict the **vulnerability class** (8-class CWE-style family) for a vulnerability record.\n", "\n", "**Models predict one of 8 vulnerability classes:** `auth_access_control`, `cryptographic_failure`, `information_disclosure`, `injection_family`, `logic_flaw`, `memory_corruption`, `misconfiguration`, `supply_chain_weakness`.\n", "\n", "**Read `leakage_diagnostic.json` first.** This is the most extensive structural-leakage audit in the XpertSystems catalog. Eight oracle paths were found across CYB009's targets; vulnerability_class is the only README-suggested target that learns honestly on the sample, and it gives the catalog's weakest baseline (acc 0.24 vs majority 0.18). The primary artifact value of this repo is the diagnostic, not the classifier." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Install dependencies" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install --quiet xgboost torch safetensors pandas numpy huggingface_hub" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Download model artifacts from Hugging Face" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import hf_hub_download\n", "\n", "REPO_ID = \"xpertsystems/cyb009-baseline-classifier\"\n", "\n", "files = {}\n", "for name in [\"model_xgb.json\", \"model_mlp.safetensors\",\n", " \"feature_engineering.py\", \"feature_meta.json\",\n", " \"feature_scaler.json\"]:\n", " files[name] = hf_hub_download(repo_id=REPO_ID, filename=name)\n", " print(f\" downloaded: {name}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sys, os\n", "fe_dir = os.path.dirname(files[\"feature_engineering.py\"])\n", "if fe_dir not in sys.path:\n", " sys.path.insert(0, fe_dir)\n", "\n", "from feature_engineering import (\n", " transform_single, load_meta, build_asset_lookup, INT_TO_LABEL,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Load models and metadata" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import numpy as np\n", "import torch\n", "import torch.nn as nn\n", "import xgboost as xgb\n", "from safetensors.torch import load_file\n", "\n", "meta = load_meta(files[\"feature_meta.json\"])\n", "with open(files[\"feature_scaler.json\"]) as f:\n", " scaler = json.load(f)\n", "\n", "N_FEATURES = len(meta[\"feature_names\"])\n", "N_CLASSES = len(meta[\"int_to_label\"])\n", "print(f\"feature count: {N_FEATURES}\")\n", "print(f\"class count: {N_CLASSES}\")\n", "print(f\"label classes: {list(meta['int_to_label'].values())}\")\n", "print(f\"\\noutcome-leak columns excluded from features:\")\n", "for c in meta.get(\"outcome_leak_excluded\", []):\n", " print(f\" - {c}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xgb_model = xgb.XGBClassifier()\n", "xgb_model.load_model(files[\"model_xgb.json\"])\n", "\n", "# MLP architecture (must match training)\n", "class VulnClassMLP(nn.Module):\n", " def __init__(self, n_features, n_classes=8, hidden1=128, hidden2=64, dropout=0.3):\n", " super().__init__()\n", " self.net = nn.Sequential(\n", " nn.Linear(n_features, hidden1),\n", " nn.BatchNorm1d(hidden1),\n", " nn.ReLU(),\n", " nn.Dropout(dropout),\n", " nn.Linear(hidden1, hidden2),\n", " nn.BatchNorm1d(hidden2),\n", " nn.ReLU(),\n", " nn.Dropout(dropout),\n", " nn.Linear(hidden2, n_classes),\n", " )\n", " def forward(self, x):\n", " return self.net(x)\n", "\n", "mlp_model = VulnClassMLP(N_FEATURES, n_classes=N_CLASSES)\n", "mlp_model.load_state_dict(load_file(files[\"model_mlp.safetensors\"]))\n", "mlp_model.eval()\n", "print(\"models loaded\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Load asset inventory for asset-feature lookup\n", "\n", "The model uses asset context (asset_type, criticality, environment, OS, scanner_coverage, etc.) as features. To predict on a new vulnerability, we look up its asset features from the asset_inventory." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import snapshot_download\n", "\n", "ds_path = snapshot_download(repo_id=\"xpertsystems/cyb009-sample\", repo_type=\"dataset\")\n", "asset_lookup = build_asset_lookup(f\"{ds_path}/asset_inventory.csv\")\n", "print(f\"loaded {len(asset_lookup)} asset records\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Prediction helper" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "MU = np.array(scaler[\"mean\"], dtype=np.float32)\n", "SD = np.array(scaler[\"std\"], dtype=np.float32)\n", "\n", "def predict_vuln_class(record: dict) -> dict:\n", " \"\"\"Predict the vulnerability class for one record.\n", "\n", " Note: do NOT include exploit_maturity_final, cvss_temporal_score_final,\n", " time_to_exploit_days, time_to_remediate_days, patch_lag_days, or\n", " risk_score_composite in the record. These were outcome leaks in\n", " the training data and are excluded from the feature set.\n", "\n", " Asset features (asset_type, criticality, etc.) are looked up\n", " from asset_inventory by asset_id.\n", " \"\"\"\n", " X = transform_single(record, meta, asset_lookup=asset_lookup)\n", "\n", " xgb_proba = xgb_model.predict_proba(X)[0]\n", " xgb_label = INT_TO_LABEL[int(np.argmax(xgb_proba))]\n", "\n", " Xs = ((X - MU) / SD).astype(np.float32)\n", " with torch.no_grad():\n", " logits = mlp_model(torch.tensor(Xs))\n", " mlp_proba = torch.softmax(logits, dim=1).numpy()[0]\n", " mlp_label = INT_TO_LABEL[int(np.argmax(mlp_proba))]\n", "\n", " return {\n", " \"xgboost\": {\n", " \"label\": xgb_label,\n", " \"probabilities\": {INT_TO_LABEL[i]: float(p) for i, p in enumerate(xgb_proba)},\n", " },\n", " \"mlp\": {\n", " \"label\": mlp_label,\n", " \"probabilities\": {INT_TO_LABEL[i]: float(p) for i, p in enumerate(mlp_proba)},\n", " },\n", " }" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Run on an example record\n", "\n", "Real critical-severity vulnerability from the CYB009 sample. True class is `memory_corruption` (CVSS 9.9, exploitation hasn't yet occurred, compensating control in place). On this kind of high-CVSS critical vulnerability the model has its strongest signal." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Real vulnerability from the sample dataset (true class: memory_corruption)\n", "# Note: asset_id is supplied so asset features are auto-looked-up\n", "example_record = {\n", " \"asset_id\": \"ASSET000001\",\n", " \"severity_class\": \"critical\",\n", " \"cvss_base_score\": 9.9,\n", " \"epss_score_final\": 0.2397,\n", " \"sla_compliance_flag\": 1,\n", " \"exploitation_occurred_flag\": 0,\n", " \"zero_day_flag\": 0,\n", " \"remediation_success_flag\": 1,\n", " \"compensating_control_flag\": 1,\n", " \"supply_chain_propagation_flag\": 0,\n", " \"cisa_kev_flag\": 0,\n", " \"false_positive_flag\": 0,\n", "}\n", "\n", "result = predict_vuln_class(example_record)\n", "\n", "print(f\"XGBoost -> {result['xgboost']['label']}\")\n", "for lbl, p in sorted(result['xgboost']['probabilities'].items(), key=lambda x: -x[1]):\n", " print(f\" P({lbl:30s}) = {p:.4f}\")\n", "\n", "print(f\"\\nMLP -> {result['mlp']['label']}\")\n", "for lbl, p in sorted(result['mlp']['probabilities'].items(), key=lambda x: -x[1]):\n", " print(f\" P({lbl:30s}) = {p:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Modest, honest confidence\n", "\n", "The model's confidence on individual predictions is modest (top-1 typically 0.2-0.4) because vulnerability_class is a genuinely hard task on this sample. The per-class feature distributions overlap heavily — different vuln classes have similar CVSS, EPSS, and asset distributions.\n", "\n", "The model is a useful baseline (acc 0.24 vs majority 0.18, AUC 0.69) but not a production classifier. Read `leakage_diagnostic.json` for the structural reasons why every other CYB009 README-suggested target is either trivially solvable via oracle features or unlearnable after honest leak removal." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Batch prediction on the sample dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "vulns = pd.read_csv(f\"{ds_path}/vuln_summary.csv\")\n", "\n", "# Score the first 500 vulnerabilities\n", "sample = vulns.head(500).copy()\n", "preds = [predict_vuln_class(row.to_dict())[\"xgboost\"][\"label\"] for _, row in sample.iterrows()]\n", "sample[\"xgb_pred\"] = preds\n", "\n", "ct = pd.crosstab(sample[\"vulnerability_class\"], sample[\"xgb_pred\"],\n", " rownames=[\"true\"], colnames=[\"pred\"])\n", "print(\"Confusion on first 500 sample vulnerabilities (XGBoost):\")\n", "print(ct)\n", "acc = (sample[\"vulnerability_class\"] == sample[\"xgb_pred\"]).mean()\n", "print(f\"\\nbatch accuracy on first 500 vulns (in-distribution): {acc:.4f}\")\n", "print(\"\\nNote: this includes training-set vulnerabilities. See validation_results.json\\n\"\n", " \"for proper held-out test metrics.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Important reading: the leakage diagnostic\n", "\n", "Before using CYB009 sample data to train your own models, read **`leakage_diagnostic.json`** in this repo. It documents **8 oracle paths** across the sample's targets:\n", "\n", "1. **`cvss_temporal_score_final`** is a near-deterministic function of `exploit_maturity_final` (via CVSS v3.1 multipliers 0.91/0.94/0.97/1.00).\n", "2. **`time_to_exploit_days`** uses a -1 sentinel that perfectly identifies `exploitation_occurred_flag = 0`.\n", "3. **`time_to_remediate_days`** uses a 120 sentinel that perfectly identifies `remediation_success_flag = 0`.\n", "4. **`severity_class`** is a 100% mechanical function of `cvss_base_score` (CVSS v3.1 boundaries).\n", "5. **`lifecycle_phase`** has 5+ phases that deterministically pin `remediation_status` (e.g. `residual_risk_review` → 100% `remediated`).\n", "6. **`patch_status`** has 5 of 6 values that pin `remediation_status` (e.g. `deployed` → 100% `remediated`).\n", "7. **`risk_score_composite`** is computed from flag fields (indirect oracle).\n", "8. **`patch_lag_days`** is suspected to have similar sentinel structure (precaution).\n", "\n", "It also documents **6 README-suggested headline targets that are unlearnable on the sample** after honest leak removal: `exploitation_occurred_flag`, `zero_day_flag`, `cisa_kev_flag`, `supply_chain_propagation_flag`, `false_positive_flag`, and `exploit_maturity_final`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9. Next steps\n", "\n", "- See `validation_results.json` for held-out test metrics (396 vulnerabilities).\n", "- See `multi_seed_results.json` for the across-10-seeds picture (accuracy 0.244 ± 0.023, ROC-AUC 0.687 ± 0.014).\n", "- See `ablation_results.json` — every feature group contributes 1-3pp accuracy, indicating spread-out modest signal across the feature set.\n", "- See **`leakage_diagnostic.json`** for the comprehensive structural-leakage audit (8 oracle paths + 6 unlearnable targets).\n", "- For the full ~487k-row CYB009 dataset and commercial licensing, contact **pradeep@xpertsystems.ai**." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10" } }, "nbformat": 4, "nbformat_minor": 5 }