tahamajs/truthlyAI / HomeWorks /HW4 /code /notebook.ipynb
tahamajs's picture
download
raw
27.7 kB
{
"cells": [
{
"cell_type": "markdown",
"id": "50895022",
"metadata": {},
"source": [
"# HW4 Complete Notebook (Security, Privacy, Fairness)\n",
"\n",
"## Abstract\n",
"This notebook is the fully reproducible companion to the HW4 report. It includes complete theoretical foundations, executable methods for Q1/Q2/Q3, bonus fairness methods, artifact checks, and optional report rebuild commands. The default mode is optimized for fast verification by reusing generated report artifacts, while optional toggles allow full recomputation.\n"
]
},
{
"cell_type": "markdown",
"id": "3c8fb0f2",
"metadata": {},
"source": [
"## Coverage Map (Paper-Complete Structure)\n",
"- Introduction and objective\n",
"- Complete theory (security/privacy/fairness)\n",
"- Methods and implementation mapping\n",
"- Q1 results (Neural Cleanse + unlearning)\n",
"- Q2 results (Laplace scenarios + sweeps)\n",
"- Q3 results (baseline + assignment + bonus)\n",
"- Consolidated artifact/report checks\n",
"- Conclusion\n",
"- Appendix A-C (extended derivations)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7f114c5e",
"metadata": {},
"outputs": [],
"source": [
"# Setup: imports, paths, and deterministic seeds\n",
"from __future__ import annotations\n",
"\n",
"import json\n",
"import math\n",
"import os\n",
"import random\n",
"\n",
"# Runtime hygiene for reproducible/quiet local execution.\n",
"os.environ.setdefault('MPLCONFIGDIR', '/tmp/matplotlib')\n",
"os.environ.setdefault('LOKY_MAX_CPU_COUNT', '4')\n",
"import subprocess\n",
"import sys\n",
"from pathlib import Path\n",
"\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from IPython.display import Image, display, Markdown\n",
"\n",
"# Make local modules importable even if notebook is launched from a different CWD.\n",
"CODE_DIR = Path.cwd()\n",
"if not (CODE_DIR / 'generate_report_figs.py').exists():\n",
" candidates = [\n",
" Path('/Users/tahamajs/Documents/uni/truthlyAI/HomeWorks/HW4/code'),\n",
" Path.cwd(),\n",
" ]\n",
" for c in candidates:\n",
" if (c / 'generate_report_figs.py').exists():\n",
" CODE_DIR = c\n",
" break\n",
"ROOT_DIR = CODE_DIR.parent\n",
"REPORT_DIR = ROOT_DIR / 'report'\n",
"FIG_DIR = REPORT_DIR / 'figures'\n",
"RESULTS_DIR = REPORT_DIR / 'results'\n",
"\n",
"if str(CODE_DIR) not in sys.path:\n",
" sys.path.insert(0, str(CODE_DIR))\n",
"\n",
"SEED = 0\n",
"np.random.seed(SEED)\n",
"random.seed(SEED)\n",
"\n",
"print('CODE_DIR =', CODE_DIR)\n",
"print('REPORT_DIR =', REPORT_DIR)\n",
"print('SEED =', SEED)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d7242fa7",
"metadata": {},
"outputs": [],
"source": [
"# Runtime configuration (optimized defaults)\n",
"STUDENT_ID = '810101504'\n",
"MODEL_INDEX = None\n",
"SECURITY_PROFILE = 'balanced' # fast-smoke | balanced | high-fidelity\n",
"SWAP_K = 10\n",
"POPULATION_N = 500\n",
"UNBOUNDED_P = 0.01\n",
"\n",
"# Optimized by default: reuse existing artifacts unless explicitly recomputing.\n",
"RUN_FULL_PIPELINE = False\n",
"RUN_SECURITY_RECOMPUTE = False\n",
"RUN_BUILD_PDF = False\n",
"\n",
"EXPECTED_FIGURES = [\n",
" 'trigger_reconstructed.png',\n",
" 'trigger_all_labels_grid.png',\n",
" 'security_scale_profile.png',\n",
" 'security_before_after.png',\n",
" 'security_confusion_before_after.png',\n",
" 'security_unlearning_sweep.png',\n",
" 'privacy_scenarios.png',\n",
" 'privacy_tail_curves.png',\n",
" 'privacy_epsilon_sweep.png',\n",
" 'fairness_comparison.png',\n",
" 'fairness_group_rates.png',\n",
" 'fairness_tradeoff.png',\n",
" 'fairness_swapk_sweep.png',\n",
"]\n"
]
},
{
"cell_type": "markdown",
"id": "ec0d9bfc",
"metadata": {},
"source": [
"## Optional: Regenerate All Artifacts (Q1/Q2/Q3 + macros)\n",
"Set `RUN_FULL_PIPELINE = True` above if you want fresh artifacts. This runs the same orchestrator used by the report.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "76710b52",
"metadata": {},
"outputs": [],
"source": [
"if RUN_FULL_PIPELINE:\n",
" cmd = [\n",
" sys.executable,\n",
" str(CODE_DIR / 'generate_report_figs.py'),\n",
" '--student-id', STUDENT_ID,\n",
" '--security-profile', SECURITY_PROFILE,\n",
" '--swap-k', str(SWAP_K),\n",
" '--population-n', str(POPULATION_N),\n",
" '--unbounded-p', str(UNBOUNDED_P),\n",
" '--seed', str(SEED),\n",
" '--no-download-mnist',\n",
" ]\n",
" print('Running:', ' '.join(cmd))\n",
" subprocess.run(cmd, check=True, cwd=str(CODE_DIR))\n",
" print('Pipeline completed.')\n",
"else:\n",
" print('Skipped full regeneration (RUN_FULL_PIPELINE=False). Using cached artifacts/results.')\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d48c3869",
"metadata": {},
"outputs": [],
"source": [
"# Load generated metrics summary (single source of truth for report values)\n",
"metrics_path = RESULTS_DIR / 'metrics_summary.json'\n",
"if not metrics_path.exists():\n",
" raise FileNotFoundError(f'Missing metrics file: {metrics_path}. Run pipeline generation first.')\n",
"\n",
"metrics = json.loads(metrics_path.read_text(encoding='utf-8'))\n",
"print('Loaded metrics from:', metrics_path)\n",
"print('Top-level keys:', list(metrics.keys()))\n"
]
},
{
"cell_type": "markdown",
"id": "2ef4ca2c",
"metadata": {},
"source": [
"## Introduction\n",
"HW4 is a joint trustworthiness study with three objectives: security robustness against backdoors, privacy-preserving query release under DP, and fairness-aware decision behavior across sensitive groups. The notebook keeps those views synchronized in one reproducible pipeline.\n"
]
},
{
"cell_type": "markdown",
"id": "7735e858",
"metadata": {},
"source": [
"## Complete Theory (Quick Reference)\n",
"### Security (Backdoor + Neural Cleanse)\n",
"- Trigger injection: $\\mathcal{T}(x;m,p) = (1-m)\\odot x + m\\odot p$\n",
"- Per-label reconstruction:\n",
" $$\\min_{m,p}\\;\\mathbb{E}_{x}\\left[\\ell(f_\theta(\\mathcal{T}(x;m,p)),y)\n",
"ight] + \\lambda_1\\lVert m\n",
"Vert_1 + \\lambda_2\\lVert p\n",
"Vert_1$$\n",
"- Detection: lower-tail MAD outlier on reconstructed scales.\n",
"\n",
"### Privacy (Laplace DP)\n",
"- Mechanism: $\tilde{q}(D)=q(D)+\\eta,\\;\\eta\\sim\\mathrm{Lap}(0,b),\\;b=\\Delta f/\\epsilon$\n",
"- Threshold tail: $\\Pr(\tilde{q}>t)=1-F_{\\mathrm{Lap}}(t-q(D);0,b)$\n",
"- Sequential composition lock: $\\epsilon_i=\\epsilon/k,\\;\\delta_i=\\delta/k$\n",
"- Unbounded adjacency lock: $\\Delta f_{\text{unbounded}}=\\max(1,\\lceil pn\n",
"ceil)\\Delta f$\n",
"\n",
"### Fairness (Metrics + Mitigation)\n",
"- Accuracy: $\\Pr(\\hat{y}=y)$\n",
"- Disparate Impact: $\\mathrm{DI}=\\Pr(\\hat{y}=1|s=0)/\\Pr(\\hat{y}=1|s=1)$\n",
"- Reweighing: $w(s,y)=\f\n",
"rac{P(s)P(y)}{P(s,y)}$\n",
"- Group-threshold optimization minimizes fairness gap with bounded utility loss.\n"
]
},
{
"cell_type": "markdown",
"id": "907ab443",
"metadata": {},
"source": [
"## Q1 \u2014 Security: Neural Cleanse + Unlearning"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c6d4961e",
"metadata": {},
"outputs": [],
"source": [
"# Q1 summary table from generated results\n",
"sec = metrics.get('security', {})\n",
"if 'error' in sec:\n",
" raise RuntimeError(f\"Security pipeline error recorded in metrics_summary.json: {sec['error']}\")\n",
"\n",
"security_view = {\n",
" 'checkpoint_path': sec.get('checkpoint_path'),\n",
" 'detected_attacked_label': sec.get('detected_attacked_label'),\n",
" 'expected_attacked_label': sec.get('expected_attacked_label'),\n",
" 'clean_accuracy_before': sec.get('clean_accuracy_before'),\n",
" 'clean_accuracy_after': sec.get('clean_accuracy_after'),\n",
" 'asr_before': sec.get('asr_before'),\n",
" 'asr_after': sec.get('asr_after'),\n",
" 'smallest_scale': sec.get('smallest_scale'),\n",
" 'largest_scale': sec.get('largest_scale'),\n",
" 'best_fraction_by_asr': sec.get('fraction_sweep', {}).get('best_fraction_by_asr'),\n",
" 'best_fraction_asr': sec.get('fraction_sweep', {}).get('best_fraction_asr'),\n",
"}\n",
"\n",
"pd.DataFrame([security_view]).T.rename(columns={0: 'value'})\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "90c72769",
"metadata": {},
"outputs": [],
"source": [
"# Display all security figures used in the report\n",
"security_figs = [\n",
" 'trigger_reconstructed.png',\n",
" 'trigger_all_labels_grid.png',\n",
" 'security_scale_profile.png',\n",
" 'security_before_after.png',\n",
" 'security_confusion_before_after.png',\n",
" 'security_unlearning_sweep.png',\n",
"]\n",
"for name in security_figs:\n",
" p = FIG_DIR / name\n",
" if p.exists():\n",
" display(Markdown(f'**{name}**'))\n",
" display(Image(filename=str(p)))\n",
" else:\n",
" print('Missing figure:', p)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a82269ac",
"metadata": {},
"outputs": [],
"source": [
"# Optional focused recomputation for Q1 only (can be expensive depending on profile)\n",
"if RUN_SECURITY_RECOMPUTE:\n",
" from types import SimpleNamespace\n",
" from generate_report_figs import get_paths, configure_seed, run_security\n",
"\n",
" args = SimpleNamespace(\n",
" student_id=STUDENT_ID,\n",
" model_index=MODEL_INDEX,\n",
" checkpoint_path=None,\n",
" archive_path=None,\n",
" extract_dir=None,\n",
" mnist_root=None,\n",
" download_mnist=False,\n",
" security_profile=SECURITY_PROFILE,\n",
" swap_k=SWAP_K,\n",
" population_n=POPULATION_N,\n",
" unbounded_p=UNBOUNDED_P,\n",
" seed=SEED,\n",
" )\n",
" configure_seed(SEED)\n",
" sec_summary, sec_figs = run_security(args, get_paths())\n",
" print('Recomputed Q1 summary keys:', sorted(sec_summary.keys()))\n",
"else:\n",
" print('Skipped Q1 recomputation (RUN_SECURITY_RECOMPUTE=False).')\n"
]
},
{
"cell_type": "markdown",
"id": "944831f8",
"metadata": {},
"source": [
"## Q2 \u2014 Privacy: Assignment Scenarios + Sweeps"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fb136c61",
"metadata": {},
"outputs": [],
"source": [
"from privacy import income_query_results, counting_query_results, laplace_cdf_threshold\n",
"\n",
"income = income_query_results(\n",
" epsilon=0.1,\n",
" sensitivity_avg=5000.0,\n",
" sensitivity_total=50000.0,\n",
" true_avg=40000.0,\n",
" true_total=20_000_000.0,\n",
" sampled_noise_avg=2000.0,\n",
" sampled_noise_total=5000.0,\n",
" epsilon_avg_split=0.05,\n",
" epsilon_total_split=0.05,\n",
")\n",
"counting = counting_query_results(\n",
" epsilon=0.1,\n",
" delta=1e-5,\n",
" sensitivity=1.0,\n",
" true_value=500.0,\n",
" threshold=505.0,\n",
" k=92,\n",
" n=POPULATION_N,\n",
" p=UNBOUNDED_P,\n",
")\n",
"\n",
"print('Income query results:')\n",
"display(pd.DataFrame([income]).T.rename(columns={0: 'value'}))\n",
"print('Counting query results:')\n",
"display(pd.DataFrame([counting]).T.rename(columns={0: 'value'}))\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b6eea47a",
"metadata": {},
"outputs": [],
"source": [
"# Notebook-native privacy plots (in addition to report figures)\n",
"scenario_names = ['Base', 'Sequential', 'Unbounded']\n",
"b_values = [counting['b_base'], counting['b_sequential'], counting['b_unbounded']]\n",
"p_values = [\n",
" counting['prob_base_gt_threshold'],\n",
" counting['prob_sequential_gt_threshold'],\n",
" counting['prob_unbounded_gt_threshold'],\n",
"]\n",
"\n",
"fig, axes = plt.subplots(1, 2, figsize=(10, 3.6))\n",
"axes[0].bar(scenario_names, b_values)\n",
"axes[0].set_title('Laplace scale b')\n",
"axes[0].set_ylabel('b')\n",
"\n",
"axes[1].bar(scenario_names, p_values)\n",
"axes[1].set_title('P(noisy > 505)')\n",
"axes[1].set_ylim(0, 1)\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"eps = np.linspace(0.02, 1.0, 50)\n",
"b = [1.0 / e for e in eps]\n",
"p_tail = [laplace_cdf_threshold(505.0, 500.0, 1.0, float(e)) for e in eps]\n",
"\n",
"fig, ax = plt.subplots(1, 2, figsize=(10, 3.6))\n",
"ax[0].plot(eps, b)\n",
"ax[0].set_title('b vs epsilon')\n",
"ax[0].set_xlabel('epsilon')\n",
"ax[0].set_ylabel('b')\n",
"ax[0].grid(alpha=0.3)\n",
"\n",
"ax[1].plot(eps, p_tail)\n",
"ax[1].set_title('P(noisy > 505) vs epsilon')\n",
"ax[1].set_xlabel('epsilon')\n",
"ax[1].set_ylim(0, 1)\n",
"ax[1].grid(alpha=0.3)\n",
"plt.tight_layout()\n",
"plt.show()\n"
]
},
{
"cell_type": "markdown",
"id": "5f6ca928",
"metadata": {},
"source": [
"## Q3 \u2014 Fairness: Baseline, Assignment Method, and Bonus Methods"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6576820e",
"metadata": {},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"from fairness import (\n",
" load_data,\n",
" train_baseline_model,\n",
" apply_promotion_demotion,\n",
" retrain_with_swapped_labels,\n",
" train_reweighed_model,\n",
" optimize_group_thresholds,\n",
" apply_group_thresholds,\n",
" compute_fairness_metrics,\n",
")\n",
"\n",
"Xdf, y = load_data(str(CODE_DIR / 'data.csv'))\n",
"y_np = y.to_numpy()\n",
"sensitive = Xdf['gender'].to_numpy()\n",
"\n",
"Xnum = Xdf.select_dtypes(include=[np.number])\n",
"columns = list(Xnum.columns)\n",
"sens_col_idx = columns.index('gender')\n",
"X_with_gender = Xnum.to_numpy()\n",
"\n",
"idx_all = np.arange(X_with_gender.shape[0])\n",
"idx_train, idx_test = train_test_split(idx_all, test_size=0.3, random_state=0)\n",
"X_train = X_with_gender[idx_train]\n",
"X_test = X_with_gender[idx_test]\n",
"y_train = y_np[idx_train]\n",
"y_test = y_np[idx_test]\n",
"sens_train = sensitive[idx_train]\n",
"sens_test = sensitive[idx_test]\n",
"\n",
"# Baseline\n",
"clf_base = train_baseline_model(X_train, y_train)\n",
"Xs_train_base = clf_base._scaler.transform(X_train)\n",
"Xs_test_base = clf_base._scaler.transform(X_test)\n",
"proba_train_base = clf_base.predict_proba(Xs_train_base)[:, 1]\n",
"pred_train_base = (proba_train_base >= 0.5).astype(int)\n",
"proba_test_base = clf_base.predict_proba(Xs_test_base)[:, 1]\n",
"pred_test_base = (proba_test_base >= 0.5).astype(int)\n",
"\n",
"metrics_tbl = {}\n",
"metrics_tbl['baseline'] = compute_fairness_metrics(Xs_test_base, y_test, pred_test_base, sens_test)\n",
"\n",
"# Assignment method\n",
"swap_mask = apply_promotion_demotion(\n",
" y_proba=proba_train_base,\n",
" y_pred=pred_train_base,\n",
" sensitive=sens_train,\n",
" k=SWAP_K,\n",
")\n",
"clf_swap = retrain_with_swapped_labels(X_train, y_train, swap_mask)\n",
"Xs_test_swap = clf_swap._scaler.transform(X_test)\n",
"pred_test_swap = (clf_swap.predict_proba(Xs_test_swap)[:, 1] >= 0.5).astype(int)\n",
"metrics_tbl['promotion_demotion'] = compute_fairness_metrics(Xs_test_swap, y_test, pred_test_swap, sens_test)\n",
"\n",
"# No-gender variant\n",
"X_no_gender = np.delete(X_with_gender, sens_col_idx, axis=1)\n",
"Xng_train = X_no_gender[idx_train]\n",
"Xng_test = X_no_gender[idx_test]\n",
"clf_no_gender = train_baseline_model(Xng_train, y_train)\n",
"Xngs_test = clf_no_gender._scaler.transform(Xng_test)\n",
"pred_no_gender = (clf_no_gender.predict_proba(Xngs_test)[:, 1] >= 0.5).astype(int)\n",
"metrics_tbl['no_gender'] = compute_fairness_metrics(Xngs_test, y_test, pred_no_gender, sens_test)\n",
"\n",
"# Bonus 1: Reweighing\n",
"clf_rw = train_reweighed_model(X_train, y_train, sens_train)\n",
"Xs_test_rw = clf_rw._scaler.transform(X_test)\n",
"pred_rw = (clf_rw.predict_proba(Xs_test_rw)[:, 1] >= 0.5).astype(int)\n",
"metrics_tbl['reweighed'] = compute_fairness_metrics(Xs_test_rw, y_test, pred_rw, sens_test)\n",
"\n",
"# Bonus 2: Group thresholds\n",
"thr = optimize_group_thresholds(y_true=y_train, y_proba=proba_train_base, sensitive=sens_train)\n",
"pred_thr = apply_group_thresholds(proba_test_base, sens_test, thr)\n",
"metrics_tbl['group_thresholds'] = compute_fairness_metrics(Xs_test_base, y_test, pred_thr, sens_test)\n",
"metrics_tbl['group_thresholds']['threshold_group_0'] = float(thr[0])\n",
"metrics_tbl['group_thresholds']['threshold_group_1'] = float(thr[1])\n",
"\n",
"fair_df = pd.DataFrame(metrics_tbl).T\n",
"fair_df\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "360ebee7",
"metadata": {},
"outputs": [],
"source": [
"# Fairness ablation: swap budget sweep\n",
"k_grid = [0, 5, 10, 20, 50, 100, 200, 500, 1000]\n",
"k_grid = [k for k in k_grid if k <= len(y_train)]\n",
"\n",
"k_acc = []\n",
"k_gap = []\n",
"for k in k_grid:\n",
" if k == 0:\n",
" base_acc = float(metrics_tbl['baseline']['accuracy'])\n",
" base_di = float(metrics_tbl['baseline']['disparate_impact'])\n",
" k_acc.append(base_acc)\n",
" k_gap.append(abs(1.0 - base_di))\n",
" continue\n",
" swap_mask_k = apply_promotion_demotion(proba_train_base, pred_train_base, sens_train, k)\n",
" clf_k = retrain_with_swapped_labels(X_train, y_train, swap_mask_k)\n",
" pred_k = (clf_k.predict_proba(clf_k._scaler.transform(X_test))[:, 1] >= 0.5).astype(int)\n",
" m_k = compute_fairness_metrics(clf_k._scaler.transform(X_test), y_test, pred_k, sens_test)\n",
" k_acc.append(float(m_k['accuracy']))\n",
" k_gap.append(abs(1.0 - float(m_k['disparate_impact'])))\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 3.8))\n",
"ax.plot(k_grid, k_acc, marker='o', label='Accuracy')\n",
"ax.plot(k_grid, k_gap, marker='s', label='|1 - DI|')\n",
"ax.set_xlabel('Swap budget k')\n",
"ax.set_ylabel('Metric value')\n",
"ax.set_ylim(0, 1)\n",
"ax.grid(alpha=0.3)\n",
"ax.legend()\n",
"plt.tight_layout()\n",
"plt.show()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bea0c548",
"metadata": {},
"outputs": [],
"source": [
"# Consistency check against metrics_summary.json (for reproducibility confidence)\n",
"report_fair = metrics.get('fairness', {})\n",
"rows = []\n",
"for key in ['baseline', 'promotion_demotion', 'no_gender', 'reweighed', 'group_thresholds']:\n",
" if key not in metrics_tbl or key not in report_fair:\n",
" continue\n",
" rows.append({\n",
" 'model': key,\n",
" 'acc_notebook': float(metrics_tbl[key]['accuracy']),\n",
" 'acc_report': float(report_fair[key]['accuracy']),\n",
" 'di_notebook': float(metrics_tbl[key]['disparate_impact']),\n",
" 'di_report': float(report_fair[key]['disparate_impact']),\n",
" })\n",
"\n",
"cmp_df = pd.DataFrame(rows)\n",
"if len(cmp_df):\n",
" cmp_df['acc_abs_diff'] = (cmp_df['acc_notebook'] - cmp_df['acc_report']).abs()\n",
" cmp_df['di_abs_diff'] = (cmp_df['di_notebook'] - cmp_df['di_report']).abs()\n",
"cmp_df\n"
]
},
{
"cell_type": "markdown",
"id": "a2071cef",
"metadata": {},
"source": [
"## Artifact Completeness and Report Integration"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "057397a8",
"metadata": {},
"outputs": [],
"source": [
"# Verify all expected report artifacts exist\n",
"missing = [name for name in EXPECTED_FIGURES if not (FIG_DIR / name).exists()]\n",
"print('Expected figure count:', len(EXPECTED_FIGURES))\n",
"print('Missing figures:', missing)\n",
"\n",
"required_files = [\n",
" REPORT_DIR / 'assignment_template.tex',\n",
" REPORT_DIR / 'assignment_template.pdf',\n",
" RESULTS_DIR / 'metrics_summary.json',\n",
" RESULTS_DIR / 'results_macros.tex',\n",
"]\n",
"for p in required_files:\n",
" print(('OK ' if p.exists() else 'MISS '), p)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "148717cc",
"metadata": {},
"outputs": [],
"source": [
"# Optional: rebuild IEEE PDF from notebook workflow\n",
"if RUN_BUILD_PDF:\n",
" subprocess.run(['make', 'pdf'], check=True, cwd=str(REPORT_DIR))\n",
" print('Rebuilt:', REPORT_DIR / 'assignment_template.pdf')\n",
"else:\n",
" print('Skipped PDF rebuild (RUN_BUILD_PDF=False).')\n"
]
},
{
"cell_type": "markdown",
"id": "f8e50ad2",
"metadata": {},
"source": [
"## Conclusion\n",
"This notebook now contains all required assignment parts in one executable workflow and is aligned with the report artifacts. It supports both fast verification (cached artifacts) and full recomputation, while preserving deterministic settings and direct traceability from theory to results.\n"
]
},
{
"cell_type": "markdown",
"id": "ed0b0d6e",
"metadata": {},
"source": [
"## Appendix A \u2014 Extended Security Theory\n",
"Starting from\n",
"$$\\mathcal{L}_y(m,p)=\\mathbb{E}_{x}\\left[\\ell(f_\theta(\\mathcal{T}(x;m,p)),y)\n",
"ight]+\\lambda_1\\|m\\|_1+\\lambda_2\\|p\\|_1,$$\n",
"we get local trigger sensitivities\n",
"$$\f\n",
"rac{\\partial \\mathcal{T}}{\\partial m}=p-x,\\qquad \f\n",
"rac{\\partial \\mathcal{T}}{\\partial p}=m.$$ \n",
"The attacked label tends to minimize perturbation cost, so reconstructed scales $s_y$ are scored with modified z-score\n",
"$$z_y=0.6745\f\n",
"rac{s_y-\\mathrm{median}(s)}{\\mathrm{MAD}(s)}.$$ \n",
"Lower-tail outliers are theoretically correct because true backdoor labels need less perturbation budget.\n"
]
},
{
"cell_type": "markdown",
"id": "7afa8935",
"metadata": {},
"source": [
"## Appendix B \u2014 Extended Privacy Theory\n",
"For $\\eta\\sim\\mathrm{Lap}(0,b)$, the CDF is\n",
"$$F_{\\mathrm{Lap}}(x;0,b)=\begin{cases}\f\n",
"rac{1}{2}e^{x/b},&x<0\\1-\f\n",
"rac{1}{2}e^{-x/b},&x\\ge 0\\end{cases}$$\n",
"and threshold tail is\n",
"$$\\Pr(\tilde q>t)=1-F_{\\mathrm{Lap}}(t-q;0,b).$$\n",
"Sequential composition fixes per-query budget to $\\epsilon_i=\\epsilon/k$, so $b$ grows by factor $k$. Under unbounded adjacency, sensitivity scales by $\\max(1,\\lceil pn\n",
"ceil)$, further enlarging $b$ and flattening tail curves.\n"
]
},
{
"cell_type": "markdown",
"id": "c158d6f4",
"metadata": {},
"source": [
"## Appendix C \u2014 Extended Fairness Theory\n",
"Promotion/demotion uses prediction cohorts\n",
"$$\\mathcal{C}_P=\\{i:s_i=1,\\hat y_i=0\\},\\qquad \\mathcal{C}_D=\\{i:s_i=0,\\hat y_i=1\\}$$\n",
"with rank-based label swapping. Reweighing optimizes weighted empirical risk\n",
"$$\\hat R_w(\theta)=\f\n",
"rac{1}{n}\\sum_{i=1}^n w(s_i,y_i)\\,\\ell(f_\theta(x_i),y_i),\\qquad w(s,y)=\f\n",
"rac{P(s)P(y)}{P(s,y)}.$$ \n",
"Group-threshold post-processing solves\n",
"$$(\tau_0^\\*,\tau_1^\\*)=\u0007rg\\min_{\tau_0,\tau_1}\\left|1-\\mathrm{DI}(\tau_0,\tau_1)\n",
"ight|+\\lambda\\left(1-\\mathrm{Acc}(\tau_0,\tau_1)\n",
"ight).$$\n",
"This makes fairness-utility tradeoffs explicit and tunable.\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

Xet Storage Details

Size:
27.7 kB
·
Xet hash:
e4a9e3a55ba8c5cc8292fd7e43e282f287d6452d800bb18162ee27fdddfd79fd

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.