{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CYB004 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 **phishing campaign phase** of a new per-timestep telemetry record.\n", "\n", "**Models predict one of 7 phases:** `target_reconnaissance`, `infrastructure_setup`, `lure_crafting`, `email_delivery`, `victim_engagement`, `credential_harvesting`, `post_compromise_escalation`.\n", "\n", "**This is a baseline reference model**, not a production email-security platform. See the model card for full metrics and limitations." ] }, { "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/cyb004-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, INT_TO_LABEL, build_department_lookup\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())}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# XGBoost\n", "xgb_model = xgb.XGBClassifier()\n", "xgb_model.load_model(files[\"model_xgb.json\"])\n", "\n", "# MLP architecture (must match training)\n", "class PhaseMLP(nn.Module):\n", " def __init__(self, n_features, n_classes=7, 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 = PhaseMLP(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. Build the department lookup\n", "\n", "Per-department topology features (employee_count, MFA enrollment, gateway architecture, DMARC level, etc.) are pulled from `victim_topology.csv` and merged into each timestep record by `target_department_id`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import snapshot_download\n", "\n", "ds_path = snapshot_download(repo_id=\"xpertsystems/cyb004-sample\", repo_type=\"dataset\")\n", "\n", "dept_lookup = build_department_lookup(\n", " os.path.join(ds_path, \"victim_topology.csv\")\n", ")\n", "print(f\"loaded {len(dept_lookup)} department profiles\")" ] }, { "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_phase(record: dict) -> dict:\n", " \"\"\"Predict the campaign phase for one per-timestep telemetry record.\n", "\n", " Per-department topology features are pulled automatically via\n", " `target_department_id` from the dept_lookup loaded above.\n", " \"\"\"\n", " dept_id = int(record.get(\"target_department_id\", -1))\n", " dept_aggs = dept_lookup.get(dept_id, {})\n", " X = transform_single(record, meta, victim_aggregates=dept_aggs)\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 `email_delivery` event lifted from the sample dataset: a nation-state APT campaign at timestep 13, with homoglyph substitution evasion active and 58 emails sent. Both models should predict `email_delivery`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Real timestep record from the sample dataset (true phase: email_delivery)\n", "example_record = {\n", " \"timestep\": 13,\n", " \"emails_sent_cumulative\": 58,\n", " \"click_through_rate\": 0.1158,\n", " \"credential_submission_rate\": 0.0713,\n", " \"gateway_detection_score\": 0.7327,\n", " \"lure_personalisation_score\": 0.7507,\n", " \"evasion_technique_active\": \"homoglyph_substitution\",\n", " \"target_department_id\": 10,\n", " \"actor_capability_tier\": \"nation_state_apt\",\n", "}\n", "\n", "result = predict_phase(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])[:5]:\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])[:5]:\n", " print(f\" P({lbl:30s}) = {p:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Note: when the two models disagree\n", "\n", "XGBoost and the MLP can disagree on mid-pipeline phases (`victim_engagement`, `credential_harvesting`) where timestep windows overlap. The per-class F1 in the model card identifies which phases are robustly predicted vs. which are not. In a SOC workflow, conflicting predictions are worth surfacing for human review." ] }, { "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", "traj = pd.read_csv(f\"{ds_path}/campaign_trajectories.csv\")\n", "\n", "# Drop the leaky column the model was never trained on\n", "traj = traj.drop(columns=[\"delivery_outcome\"], errors=\"ignore\")\n", "\n", "# Score the first 200 timesteps\n", "sample = traj.head(200).copy()\n", "preds = [predict_phase(row.to_dict())[\"xgboost\"][\"label\"] for _, row in sample.iterrows()]\n", "sample[\"xgb_pred\"] = preds\n", "\n", "ct = pd.crosstab(sample[\"campaign_phase\"], sample[\"xgb_pred\"],\n", " rownames=[\"true\"], colnames=[\"pred\"])\n", "print(\"Confusion on first 200 sample rows (XGBoost):\")\n", "print(ct)\n", "acc = (sample[\"campaign_phase\"] == sample[\"xgb_pred\"]).mean()\n", "print(f\"\\nbatch accuracy on first 200 rows (in-distribution): {acc:.4f}\")\n", "print(\"\\nNote: these rows include training-set campaigns. See validation_results.json\\n\"\n", " \"for proper held-out test metrics from disjoint campaigns.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Next steps\n", "\n", "- See `validation_results.json` for held-out test metrics (15 disjoint campaigns, ~580 timesteps).\n", "- See `multi_seed_results.json` for the across-10-seeds robustness picture (accuracy 0.649 ± 0.038, ROC-AUC 0.937 ± 0.010).\n", "- See `ablation_results.json` for per-feature-group contribution. `timestep` carries the dominant signal.\n", "- The model card explains why `actor_capability_tier` was *not* used as the target despite being the README's headline use case.\n", "- For the full 335k-row CYB004 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 }