Shuya Feng commited on
Commit ·
6640531
1
Parent(s): 17e9685
feat: Implement DP-SGD Explorer web application with Flask backend, interactive frontend, and easy deployment script
Browse filesFiles changed (20)
- README.md+77-1
- app/__init__.pyAdded+12
- app/__pycache__/__init__.cpython-38.pycAdded
- app/__pycache__/routes.cpython-38.pycAdded
- app/routes.pyAdded+43
- app/static/css/learning.cssAdded+202
- app/static/css/styles.cssAdded+457
- app/static/js/main.jsAdded+371
- app/templates/base.htmlAdded+42
- app/templates/index.htmlAdded+331
- app/templates/learning.htmlAdded+261
- app/training/__init__.pyAdded+4
- app/training/__pycache__/__init__.cpython-38.pycAdded
- app/training/__pycache__/mock_trainer.cpython-38.pycAdded
- app/training/__pycache__/privacy_calculator.cpython-38.pycAdded
- app/training/mock_trainer.pyAdded+152
- app/training/privacy_calculator.pyAdded+104
- requirements.txtAdded+5
- run.pyAdded+6
- start_server.shAdded+60
1# DPSGDTool1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677# DP-SGD ExplorerAn interactive web application for exploring and learning about Differentially Private Stochastic Gradient Descent (DP-SGD).## Features- Interactive playground for experimenting with DP-SGD parameters- Comprehensive learning hub with detailed explanations- Real-time privacy budget calculations- Training visualizations and metrics- Parameter recommendations## Requirements- Python 3.8 or higher- Modern web browser (Chrome, Firefox, Safari, or Edge)## Quick Start1. Clone this repository:```bashgit clone https://github.com/yourusername/dpsgd-explorer.gitcd dpsgd-explorer```2. Run the start script:```bash./start_server.sh```3. Open your web browser and navigate to:```http://127.0.0.1:5000```The start script will automatically:- Check for Python installation- Create a virtual environment- Install required dependencies- Start the Flask development server## Manual Setup (if the script doesn't work)1. Create a virtual environment:```bashpython3 -m venv .venvsource .venv/bin/activate # On Windows: .venv\Scripts\activate```2. Install dependencies:```bashpip install -r requirements.txt```3. Start the server:```bashPYTHONPATH=. python3 run.py```## Project Structure```dpsgd-explorer/├── app/│ ├── static/ # Static files (CSS, JS)│ ├── templates/ # HTML templates│ ├── training/ # Training simulation│ ├── routes.py # Flask routes│ └── __init__.py # App initialization├── requirements.txt # Python dependencies├── run.py # Application entry point└── start_server.sh # Start script```## LicenseMIT License - Feel free to use this project for learning and educational purposes.
123456789101112from flask import Flaskfrom flask_cors import CORS
def create_app(): app = Flask(__name__) CORS(app) # Register blueprints from app.routes import main app.register_blueprint(main) return app 12345678910111213141516171819202122232425262728293031323334353637383940414243from flask import Blueprint, render_template, jsonify, requestfrom app.training.mock_trainer import MockTrainerfrom app.training.privacy_calculator import PrivacyCalculator
main = Blueprint('main', __name__)mock_trainer = MockTrainer()privacy_calculator = PrivacyCalculator()
@main.route('/')def index(): return render_template('index.html')
@main.route('/learning')def learning(): return render_template('learning.html')
@main.route('/api/train', methods=['POST'])def train(): data = request.json params = { 'clipping_norm': float(data.get('clipping_norm', 1.0)), 'noise_multiplier': float(data.get('noise_multiplier', 1.0)), 'batch_size': int(data.get('batch_size', 64)), 'learning_rate': float(data.get('learning_rate', 0.01)), 'epochs': int(data.get('epochs', 5)) } # Get mock training results results = mock_trainer.train(params) return jsonify(results)
@main.route('/api/privacy-budget', methods=['POST'])def calculate_privacy_budget(): data = request.json params = { 'clipping_norm': float(data.get('clipping_norm', 1.0)), 'noise_multiplier': float(data.get('noise_multiplier', 1.0)), 'batch_size': int(data.get('batch_size', 64)), 'epochs': int(data.get('epochs', 5)) } epsilon = privacy_calculator.calculate_epsilon(params) return jsonify({'epsilon': epsilon}) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202/* Learning Hub Container */.learning-container { display: flex; gap: 2rem; padding: 2rem; max-width: 1400px; margin: 0 auto;}
/* Sidebar Styles */.learning-sidebar { flex: 0 0 300px; background: #f8f9fa; border-radius: 8px; padding: 1.5rem; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); height: fit-content; position: sticky; top: 2rem;}
.learning-steps { list-style: none; padding: 0; margin: 1rem 0;}
.learning-step { padding: 0.75rem 1rem; margin: 0.5rem 0; border-radius: 6px; cursor: pointer; transition: all 0.3s ease; font-size: 0.95rem; color: #495057;}
.learning-step:hover { background: #e9ecef; color: #212529;}
.learning-step.active { background: #007bff; color: white; font-weight: 500;}
/* Content Area Styles */.learning-content { flex: 1; min-width: 0;}
.step-content { display: none; animation: fadeIn 0.3s ease;}
.step-content.active { display: block;}
/* Typography */.section-title { font-size: 2.5rem; color: #212529; margin-bottom: 2rem; text-align: center;}
.panel-title { font-size: 1.25rem; color: #343a40; margin-bottom: 1rem;}
.step-content h2 { font-size: 2rem; color: #212529; margin-bottom: 1.5rem;}
.step-content h3 { font-size: 1.5rem; color: #343a40; margin: 2rem 0 1rem;}
.step-content p { font-size: 1rem; line-height: 1.6; color: #495057; margin-bottom: 1rem;}
/* Concept Box Styles */.concept-box { display: flex; gap: 1.5rem; margin: 2rem 0;}
.box1, .box2 { flex: 1; background: #f8f9fa; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);}
.concept-highlight { background: #e9ecef; padding: 1.5rem; border-radius: 8px; margin: 1.5rem 0; border-left: 4px solid #007bff;}
/* Formula Styles */.formula { background: #f8f9fa; padding: 1.5rem; border-radius: 8px; margin: 1rem 0; text-align: center; font-family: 'Times New Roman', serif; font-size: 1.2rem;}
/* List Styles */.step-content ul, .step-content ol { padding-left: 1.5rem; margin: 1rem 0;}
.step-content li { margin-bottom: 0.5rem; color: #495057; line-height: 1.5;}
/* Animation */@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); }}
/* Responsive Design */@media (max-width: 1024px) { .learning-container { flex-direction: column; } .learning-sidebar { flex: none; position: static; width: 100%; } .concept-box { flex-direction: column; }}
/* Code and Math Styles */code { background: #f8f9fa; padding: 0.2rem 0.4rem; border-radius: 4px; font-family: 'Courier New', monospace; font-size: 0.9rem;}
sub { font-size: 0.75em; vertical-align: sub;}
/* Links */.step-content a { color: #007bff; text-decoration: none; transition: color 0.2s ease;}
.step-content a:hover { color: #0056b3; text-decoration: underline;}
/* Strong Text */strong { color: #212529; font-weight: 600;} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457:root { --primary-color: #3f51b5; --primary-light: #757de8; --primary-dark: #002984; --secondary-color: #4caf50; --accent-color: #ff9800; --error-color: #f44336; --text-primary: #333; --text-secondary: #666; --background-light: #fff; --background-off: #f5f7fa; --border-color: #ddd; --font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif; --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);}
/* Base Styles */body { font-family: var(--font-family); margin: 0; padding: 0; background: var(--background-off); color: var(--text-primary);}
.app-container { min-height: 100vh; display: flex; flex-direction: column;}
/* Header */.main-header { background-color: var(--primary-color); color: white; padding: 1rem; box-shadow: var(--shadow-sm);}
.header-container { display: flex; justify-content: space-between; align-items: center; max-width: 1200px; margin: 0 auto;}
.logo { font-size: 1.5rem; font-weight: bold;}
.tagline { font-size: 0.8rem; opacity: 0.8;}
/* Navigation */.nav-list { list-style: none; display: flex; gap: 1rem; padding: 0; margin: 0;}
.nav-link { color: white; cursor: pointer; padding: 0.5rem 1rem; border-radius: 4px; text-decoration: none;}
.nav-link:hover { background-color: rgba(255, 255, 255, 0.1);}
.nav-link.active { background-color: rgba(255, 255, 255, 0.2);}
/* Main Content */.main-content { flex: 1; max-width: 1200px; margin: 0 auto; padding: 1rem;}
.section-title { font-size: 2rem; color: var(--primary-dark); margin-bottom: 1.5rem;}
/* Grid Layout */.lab-container { display: grid; grid-template-columns: 300px 1fr; gap: 1.5rem;}
@media (max-width: 900px) { .lab-container { grid-template-columns: 1fr; }}
/* Panels */.panel { background: white; border-radius: 8px; padding: 1rem; box-shadow: var(--shadow-sm);}
.panel-title { font-size: 1.2rem; margin-bottom: 1rem; color: var(--primary-dark);}
/* Parameter Controls */.parameter-control { margin-bottom: 1rem;}
.parameter-label { display: block; margin-bottom: 0.5rem; font-weight: 500;}
.parameter-slider { width: 100%; margin-bottom: 0.5rem;}
.slider-display { display: flex; justify-content: space-between; font-size: 0.9rem; color: var(--text-secondary);}
/* Privacy Budget Display */.budget-display { margin-top: 1.5rem; padding: 1rem; background: var(--background-off); border-radius: 4px;}
.budget-bar { height: 8px; background-color: #e0e0e0; border-radius: 4px; position: relative; margin: 0.5rem 0;}
.budget-fill { height: 100%; border-radius: 4px; background-color: var(--accent-color); transition: width 0.3s ease;}
.budget-fill.low { background-color: var(--secondary-color);}
.budget-fill.medium { background-color: var(--accent-color);}
.budget-fill.high { background-color: var(--error-color);}
/* Buttons */.control-button { width: 100%; padding: 0.8rem; border: none; border-radius: 4px; background-color: var(--primary-color); color: white; font-weight: bold; cursor: pointer; margin-top: 1rem; transition: background-color 0.3s ease;}
.control-button:hover { background-color: var(--primary-dark);}
.control-button.running { background-color: var(--error-color);}
/* Charts */.chart-container { height: 300px; margin-bottom: 1rem; position: relative;}
.chart { width: 100%; height: 100%; border: 1px solid var(--border-color); border-radius: 4px;}
/* Metrics */.metrics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1rem;}
.metric-card { background-color: var(--background-off); border-radius: 4px; padding: 1rem; text-align: center;}
.metric-value { font-size: 1.5rem; font-weight: bold; margin-bottom: 0.5rem;}
.metric-label { color: var(--text-secondary); font-weight: 500;}
/* Recommendations */.recommendation-list { list-style: none; padding: 0; margin: 0;}
.recommendation-item { display: flex; align-items: flex-start; padding: 0.8rem 0; border-bottom: 1px solid var(--border-color);}
.recommendation-icon { margin-right: 0.5rem; font-size: 1.2rem;}
/* Tabs */.tabs { display: flex; margin-bottom: 1rem;}
.tab { padding: 0.5rem 1rem; cursor: pointer; border-bottom: 2px solid transparent; transition: all 0.3s ease;}
.tab:hover { color: var(--primary-color);}
.tab.active { border-bottom: 2px solid var(--primary-color); color: var(--primary-color);}
.tab-content { display: none;}
.tab-content.active { display: block;}
/* Training Status */.status-badge { display: flex; align-items: center; margin-top: 1rem; padding: 0.5rem; background-color: var(--background-off); border-radius: 4px;}
.pulse { display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: var(--secondary-color); margin-right: 0.5rem; animation: pulse 1.5s infinite;}
@keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.7); } 70% { box-shadow: 0 0 0 10px rgba(76, 175, 80, 0); } 100% { box-shadow: 0 0 0 0 rgba(76, 175, 80, 0); }}
/* Footer */.footer { text-align: center; padding: 1rem; background-color: var(--primary-dark); color: white; margin-top: 2rem;}
/* Tooltips */.tooltip { position: relative; display: inline-block; margin-left: 0.5rem;}
.tooltip-icon { width: 16px; height: 16px; border-radius: 50%; background-color: var(--primary-light); color: white; font-size: 12px; display: flex; align-items: center; justify-content: center; cursor: help;}
.tooltip-text { visibility: hidden; width: 200px; background-color: #333; color: white; text-align: center; border-radius: 4px; padding: 0.5rem; position: absolute; z-index: 1; bottom: 125%; left: 50%; margin-left: -100px; opacity: 0; transition: opacity 0.3s; font-size: 0.8rem;}
.tooltip:hover .tooltip-text { visibility: visible; opacity: 1;}
/* Learning Hub Styles */.learning-container { display: grid; grid-template-columns: 250px 1fr; gap: 1.5rem;}
.learning-sidebar { background: white; border-radius: 8px; padding: 1rem; box-shadow: var(--shadow-sm);}
.learning-content { background: white; border-radius: 8px; padding: 1.5rem; box-shadow: var(--shadow-sm);}
.learning-steps { list-style: none; padding: 0; margin: 0;}
.learning-step { padding: 0.75rem 0.5rem; border-radius: 4px; cursor: pointer; margin-bottom: 0.5rem; transition: all 0.3s ease;}
.learning-step:hover { background-color: var(--background-off);}
.learning-step.active { background-color: var(--background-off); color: var(--primary-color); font-weight: 500;}
/* Concept Boxes */.concept-highlight { background-color: var(--background-off); border-radius: 4px; padding: 1rem; margin: 1rem 0;}
.formula { background-color: #f5f7fa; padding: 0.75rem; border-radius: 4px; font-family: monospace; margin: 1rem 0;}
.concept-box { display: flex; margin: 1rem 0; gap: 1rem;}
.concept-box > div { flex: 1; padding: 1rem; border-radius: 8px;}
.concept-box .box1 { background-color: #e3f2fd;}
.concept-box .box2 { background-color: #fff8e1;} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371class DPSGDExplorer { constructor() { this.trainingChart = null; this.privacyChart = null; this.isTraining = false; this.initializeUI(); }
initializeUI() { // Initialize parameter controls this.initializeSliders(); this.initializePresets(); this.initializeTabs(); this.initializeCharts(); // Add event listeners document.getElementById('train-button')?.addEventListener('click', () => this.toggleTraining()); }
initializeSliders() { // Parameter sliders const sliders = { 'clipping-norm': document.getElementById('clipping-norm'), 'noise-multiplier': document.getElementById('noise-multiplier'), 'batch-size': document.getElementById('batch-size'), 'learning-rate': document.getElementById('learning-rate'), 'epochs': document.getElementById('epochs') };
// Add event listeners to sliders for (const [id, slider] of Object.entries(sliders)) { if (slider) { slider.addEventListener('input', (e) => { document.getElementById(`${id}-value`).textContent = e.target.value; this.updatePrivacyBudget(); }); } } }
initializePresets() { const presets = { 'high-privacy': { clippingNorm: 1.0, noiseMultiplier: 1.5, batchSize: 256, learningRate: 0.005, epochs: 10 }, 'balanced': { clippingNorm: 1.0, noiseMultiplier: 1.0, batchSize: 128, learningRate: 0.01, epochs: 8 }, 'high-utility': { clippingNorm: 1.5, noiseMultiplier: 0.5, batchSize: 64, learningRate: 0.02, epochs: 5 } };
// Add event listeners to preset buttons for (const [preset, values] of Object.entries(presets)) { document.getElementById(`preset-${preset}`)?.addEventListener('click', () => { this.applyPreset(values); }); } }
initializeTabs() { const tabs = document.querySelectorAll('.tab'); tabs.forEach(tab => { tab.addEventListener('click', () => { const tabsContainer = tab.closest('.tabs'); tabsContainer.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); tab.classList.add('active');
const tabName = tab.getAttribute('data-tab'); const panel = tab.closest('.panel'); panel.querySelectorAll('.tab-content').forEach(content => { content.classList.remove('active'); }); panel.querySelector(`#${tabName}-tab`)?.classList.add('active'); }); }); }
initializeCharts() { const trainingCtx = document.getElementById('training-chart')?.getContext('2d'); const privacyCtx = document.getElementById('privacy-chart')?.getContext('2d');
if (trainingCtx) { this.trainingChart = new Chart(trainingCtx, { type: 'line', data: { labels: [], datasets: [ { label: 'Accuracy', borderColor: '#4caf50', data: [], yAxisID: 'y' }, { label: 'Loss', borderColor: '#f44336', data: [], yAxisID: 'y1' } ] }, options: { responsive: true, interaction: { mode: 'index', intersect: false, }, scales: { y: { type: 'linear', display: true, position: 'left', title: { display: true, text: 'Accuracy (%)' } }, y1: { type: 'linear', display: true, position: 'right', title: { display: true, text: 'Loss' }, grid: { drawOnChartArea: false, }, } } } }); }
if (privacyCtx) { this.privacyChart = new Chart(privacyCtx, { type: 'line', data: { labels: [], datasets: [{ label: 'Privacy Budget (ε)', borderColor: '#3f51b5', data: [] }] }, options: { responsive: true, scales: { y: { title: { display: true, text: 'Privacy Budget (ε)' } }, x: { title: { display: true, text: 'Epoch' } } } } }); } }
async updatePrivacyBudget() { const params = this.getParameters(); try { const response = await fetch('/api/privacy-budget', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(params) }); const data = await response.json(); // Update UI const budgetValue = document.getElementById('budget-value'); const budgetFill = document.getElementById('budget-fill'); if (budgetValue && budgetFill) { budgetValue.textContent = data.epsilon.toFixed(2); budgetFill.style.width = `${Math.min(data.epsilon / 10 * 100, 100)}%`; // Update class for coloring budgetFill.classList.remove('low', 'medium', 'high'); if (data.epsilon <= 1) { budgetFill.classList.add('low'); } else if (data.epsilon <= 5) { budgetFill.classList.add('medium'); } else { budgetFill.classList.add('high'); } } } catch (error) { console.error('Error calculating privacy budget:', error); } }
async toggleTraining() { if (this.isTraining) { this.stopTraining(); } else { await this.startTraining(); } }
async startTraining() { const trainButton = document.getElementById('train-button'); const trainingStatus = document.getElementById('training-status'); if (!trainButton || this.isTraining) return;
this.isTraining = true; trainButton.textContent = 'Stop Training'; trainButton.classList.add('running'); trainingStatus.style.display = 'flex';
// Reset charts this.resetCharts();
try { const response = await fetch('/api/train', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(this.getParameters()) });
const data = await response.json(); this.updateCharts(data.epochs_data); this.updateResults(data); } catch (error) { console.error('Training error:', error); } finally { this.stopTraining(); } }
stopTraining() { this.isTraining = false; const trainButton = document.getElementById('train-button'); if (trainButton) { trainButton.textContent = 'Run Training'; trainButton.classList.remove('running'); } document.getElementById('training-status').style.display = 'none'; }
resetCharts() { if (this.trainingChart) { this.trainingChart.data.labels = []; this.trainingChart.data.datasets[0].data = []; this.trainingChart.data.datasets[1].data = []; this.trainingChart.update(); }
if (this.privacyChart) { this.privacyChart.data.labels = []; this.privacyChart.data.datasets[0].data = []; this.privacyChart.update(); } }
updateCharts(epochsData) { if (!this.trainingChart || !epochsData) return;
const labels = epochsData.map(d => d.epoch); const accuracies = epochsData.map(d => d.accuracy); const losses = epochsData.map(d => d.loss);
this.trainingChart.data.labels = labels; this.trainingChart.data.datasets[0].data = accuracies; this.trainingChart.data.datasets[1].data = losses; this.trainingChart.update();
// Update privacy chart if (this.privacyChart) { this.privacyChart.data.labels = labels; this.privacyChart.data.datasets[0].data = epochsData.map((_, i) => this.calculateEpochPrivacy(i + 1) ); this.privacyChart.update(); } }
updateResults(data) { // Hide no-results message and show results content document.getElementById('no-results').style.display = 'none'; document.getElementById('results-content').style.display = 'block';
// Update metrics document.getElementById('accuracy-value').textContent = data.final_metrics.accuracy.toFixed(1) + '%'; document.getElementById('loss-value').textContent = data.final_metrics.loss.toFixed(3); document.getElementById('training-time-value').textContent = data.final_metrics.training_time.toFixed(1) + 's';
// Update recommendations const recommendationList = document.querySelector('.recommendation-list'); recommendationList.innerHTML = ''; data.recommendations.forEach(rec => { const item = document.createElement('li'); item.className = 'recommendation-item'; item.innerHTML = ` <span class="recommendation-icon">${rec.icon}</span> <span>${rec.text}</span> `; recommendationList.appendChild(item); }); }
getParameters() { return { clipping_norm: parseFloat(document.getElementById('clipping-norm').value), noise_multiplier: parseFloat(document.getElementById('noise-multiplier').value), batch_size: parseInt(document.getElementById('batch-size').value), learning_rate: parseFloat(document.getElementById('learning-rate').value), epochs: parseInt(document.getElementById('epochs').value) }; }
applyPreset(values) { document.getElementById('clipping-norm').value = values.clippingNorm; document.getElementById('noise-multiplier').value = values.noiseMultiplier; document.getElementById('batch-size').value = values.batchSize; document.getElementById('learning-rate').value = values.learningRate; document.getElementById('epochs').value = values.epochs;
// Update displayed values document.getElementById('clipping-norm-value').textContent = values.clippingNorm; document.getElementById('noise-multiplier-value').textContent = values.noiseMultiplier; document.getElementById('batch-size-value').textContent = values.batchSize; document.getElementById('learning-rate-value').textContent = values.learningRate; document.getElementById('epochs-value').textContent = values.epochs;
this.updatePrivacyBudget(); }
calculateEpochPrivacy(epoch) { const params = this.getParameters(); const samplingRate = params.batch_size / 60000; // Assuming MNIST size const steps = epoch * (1 / samplingRate); const delta = 1e-5; const c = Math.sqrt(2 * Math.log(1.25 / delta)); return Math.min((c * samplingRate * Math.sqrt(steps)) / params.noise_multiplier, 10); }}
// Initialize the application when the DOM is loadeddocument.addEventListener('DOMContentLoaded', () => { window.dpsgdExplorer = new DPSGDExplorer();}); 123456789101112131415161718192021222324252627282930313233343536373839404142<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}DP-SGD Explorer{% endblock %}</title> <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/learning.css') }}"> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> {% block extra_head %}{% endblock %}</head><body> <div class="app-container"> <header class="main-header"> <div class="header-container"> <div> <div class="logo">DP-SGD Explorer</div> <div class="tagline">Interactive Learning & Experimentation</div> </div> <nav> <ul class="nav-list"> <li><a href="{{ url_for('main.learning') }}" class="nav-link {% if request.endpoint == 'main.learning' %}active{% endif %}">Learning Hub</a></li> <li><a href="{{ url_for('main.index') }}" class="nav-link {% if request.endpoint == 'main.index' %}active{% endif %}">Playground</a></li> </ul> </nav> </div> </header>
<main class="main-content"> {% block content %}{% endblock %} </main>
<footer class="footer"> <p>DP-SGD Explorer - An Educational Tool for Differential Privacy in Machine Learning</p> <p>© 2024 - For educational purposes</p> </footer> </div>
<script src="{{ url_for('static', filename='js/main.js') }}"></script> {% block extra_scripts %}{% endblock %}</body></html> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331{% extends "base.html" %}
{% block title %}DP-SGD Explorer - Interactive Playground{% endblock %}
{% block content %}<h1 class="section-title">DP-SGD Interactive Playground</h1>
<div class="lab-container"> <!-- Sidebar - Configuration Panels --> <div class="lab-sidebar"> <!-- Model Configuration Panel --> <div class="panel"> <h2 class="panel-title">Model Configuration</h2> <div class="parameter-control"> <label for="dataset-select" class="parameter-label"> Dataset <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">The dataset used for training affects privacy budget calculations and model accuracy.</span> </span> </label> <select id="dataset-select" class="parameter-select"> <option value="mnist">MNIST Digits</option> <option value="fashion-mnist">Fashion MNIST</option> <option value="cifar10">CIFAR-10</option> </select> </div> <div class="parameter-control"> <label for="model-select" class="parameter-label"> Model Architecture <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">The model architecture affects training time, capacity to learn, and resilience to noise.</span> </span> </label> <select id="model-select" class="parameter-select"> <option value="simple-mlp">Simple MLP</option> <option value="simple-cnn">Simple CNN</option> <option value="advanced-cnn">Advanced CNN</option> </select> </div> <div style="margin-top: 1.5rem;"> <h3 style="margin-bottom: 0.5rem; font-size: 1rem;">Quick Presets</h3> <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.5rem;"> <button id="preset-high-privacy" style="padding: 0.5rem; text-align: center; background-color: #e3f2fd; border: none; border-radius: 4px; cursor: pointer;"> <div style="font-size: 1.2rem; margin-bottom: 0.2rem;">🔒</div> <div style="font-weight: 500; margin-bottom: 0.2rem;">High Privacy</div> <div style="font-size: 0.8rem; color: #666;">ε ≈ 1.2</div> </button> <button id="preset-balanced" style="padding: 0.5rem; text-align: center; background-color: #f1f8e9; border: none; border-radius: 4px; cursor: pointer;"> <div style="font-size: 1.2rem; margin-bottom: 0.2rem;">⚖️</div> <div style="font-weight: 500; margin-bottom: 0.2rem;">Balanced</div> <div style="font-size: 0.8rem; color: #666;">ε ≈ 3.0</div> </button> <button id="preset-high-utility" style="padding: 0.5rem; text-align: center; background-color: #fff8e1; border: none; border-radius: 4px; cursor: pointer;"> <div style="font-size: 1.2rem; margin-bottom: 0.2rem;">📈</div> <div style="font-weight: 500; margin-bottom: 0.2rem;">High Utility</div> <div style="font-size: 0.8rem; color: #666;">ε ≈ 8.0</div> </button> </div> </div> </div> <!-- DP-SGD Parameters Panel --> <div class="panel" style="margin-top: 1rem;"> <h2 class="panel-title">DP-SGD Parameters</h2> <div class="parameter-control"> <label for="clipping-norm" class="parameter-label"> Clipping Norm (C) <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Limits how much any single training example can affect the model update. Smaller values provide stronger privacy but can slow learning.</span> </span> </label> <input type="range" id="clipping-norm" class="parameter-slider" min="0.1" max="5.0" step="0.1" value="1.0"> <div class="slider-display"> <span>0.1</span> <span id="clipping-norm-value">1.0</span> <span>5.0</span> </div> </div> <div class="parameter-control"> <label for="noise-multiplier" class="parameter-label"> Noise Multiplier (σ) <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Controls how much noise is added to protect privacy. Higher values increase privacy but may reduce accuracy.</span> </span> </label> <input type="range" id="noise-multiplier" class="parameter-slider" min="0.1" max="5.0" step="0.1" value="1.0"> <div class="slider-display"> <span>0.1</span> <span id="noise-multiplier-value">1.0</span> <span>5.0</span> </div> </div> <div class="parameter-control"> <label for="batch-size" class="parameter-label"> Batch Size <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Number of examples processed in each training step. Affects both privacy accounting and training stability.</span> </span> </label> <input type="range" id="batch-size" class="parameter-slider" min="16" max="512" step="16" value="64"> <div class="slider-display"> <span>16</span> <span id="batch-size-value">64</span> <span>512</span> </div> </div> <div class="parameter-control"> <label for="learning-rate" class="parameter-label"> Learning Rate (η) <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Controls how quickly model parameters update. For DP-SGD, often needs to be smaller than standard SGD.</span> </span> </label> <input type="range" id="learning-rate" class="parameter-slider" min="0.001" max="0.1" step="0.001" value="0.01"> <div class="slider-display"> <span>0.001</span> <span id="learning-rate-value">0.01</span> <span>0.1</span> </div> </div> <div class="parameter-control"> <label for="epochs" class="parameter-label"> Epochs <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Number of complete passes through the dataset. More epochs improves learning but increases privacy budget consumption.</span> </span> </label> <input type="range" id="epochs" class="parameter-slider" min="1" max="20" step="1" value="5"> <div class="slider-display"> <span>1</span> <span id="epochs-value">5</span> <span>20</span> </div> </div> <div class="budget-display"> <h3 style="margin-top: 0; margin-bottom: 0.5rem;"> Estimated Privacy Budget (ε) <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">This is the estimated privacy loss from training with these parameters. Lower ε means stronger privacy guarantees.</span> </span> </h3> <div style="display: flex; align-items: center; gap: 1rem;"> <div id="budget-value" style="font-size: 1.5rem; font-weight: bold; min-width: 60px;">2.47</div> <div style="flex: 1;"> <div class="budget-bar"> <div id="budget-fill" class="budget-fill medium" style="width: 25%;"></div> </div> <div class="budget-scale"> <span>Stronger Privacy</span> <span>Weaker Privacy</span> </div> </div> </div> </div> <button id="train-button" class="control-button"> Run Training </button> </div> </div> <!-- Main Content - Visualizations and Results --> <div class="lab-main"> <!-- Training Visualizer --> <div class="panel"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;"> <h2 class="panel-title">Training Progress</h2> <div class="tabs"> <div class="tab active" data-tab="training">Training Metrics</div> <div class="tab" data-tab="gradients">Gradient Clipping</div> <div class="tab" data-tab="privacy">Privacy Budget</div> </div> </div> <div id="training-tab" class="tab-content active"> <div class="chart-container"> <canvas id="training-chart" class="chart"></canvas> </div> <div id="training-status" class="status-badge" style="display: none;"> <span class="pulse"></span> <span style="font-weight: 500; color: #4caf50;">Training in progress</span> <span style="margin-left: auto; font-weight: 500;">Epoch: <span id="current-epoch">1</span> / <span id="total-epochs">5</span></span> </div> </div> <div id="gradients-tab" class="tab-content"> <div style="margin-bottom: 1rem;"> <h3 style="font-size: 1rem; margin-bottom: 0.5rem;">Gradient Clipping Visualization</h3> <p style="font-size: 0.9rem; color: var(--text-secondary);"> The chart below shows a distribution of gradient norms before and after clipping. The vertical red line indicates the clipping threshold. <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Clipping ensures no single example has too much influence on model updates, which is essential for differential privacy.</span> </span> </p> </div> <div class="canvas-container"> <canvas id="gradient-canvas" width="600" height="300"></canvas> </div> </div> <div id="privacy-tab" class="tab-content"> <div style="margin-bottom: 1rem;"> <h3 style="font-size: 1rem; margin-bottom: 0.5rem;">Privacy Budget Consumption</h3> <p style="font-size: 0.9rem; color: var(--text-secondary);"> This chart shows how the privacy budget (ε) accumulates during training. <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">In differential privacy, we track the 'privacy budget' (ε) which represents the amount of privacy loss. Lower values mean stronger privacy guarantees.</span> </span> </p> </div> <div class="chart-container"> <canvas id="privacy-chart" class="chart"></canvas> </div> </div> </div> <!-- Results Panel --> <div class="panel" style="margin-top: 1rem;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;"> <h2 class="panel-title">Results</h2> <div class="tabs"> <div class="tab active" data-tab="metrics">Final Metrics</div> <div class="tab" data-tab="recommendations">Recommendations</div> </div> </div> <!-- Initial no-results state --> <div id="no-results" style="text-align: center; padding: 2rem 0;"> <p style="color: var(--text-secondary); margin-bottom: 1rem;">Run training to see results here</p> <div style="font-size: 3rem; opacity: 0.5;">📊</div> </div> <!-- Results content (hidden initially) --> <div id="results-content" style="display: none;"> <div id="metrics-tab" class="tab-content active"> <div class="metrics-grid"> <div class="metric-card"> <div id="accuracy-value" class="metric-value" style="color: var(--primary-color);">92.4%</div> <div class="metric-label"> Accuracy <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Model performance on test data. Higher values are better.</span> </span> </div> </div> <div class="metric-card"> <div id="loss-value" class="metric-value">0.283</div> <div class="metric-label"> Loss <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Final training loss. Lower values generally indicate better model fit.</span> </span> </div> </div> <div class="metric-card"> <div id="privacy-budget-value" class="metric-value" style="color: var(--accent-color);">ε = 2.1</div> <div class="metric-label"> Privacy Budget <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Final privacy loss (ε). Lower values mean stronger privacy guarantees.</span> </span> </div> </div> <div class="metric-card"> <div id="training-time-value" class="metric-value">3.7s</div> <div class="metric-label"> Training Time <span class="tooltip"> <span class="tooltip-icon">?</span> <span class="tooltip-text">Total time spent on training, including privacy mechanisms.</span> </span> </div> </div> </div> <div style="background-color: var(--background-off); border-radius: 4px; padding: 1rem; margin-top: 1rem;"> <h3 style="margin-top: 0; margin-bottom: 0.5rem; font-size: 1rem;">Privacy-Utility Trade-off</h3> <div style="position: relative; height: 8px; background-color: #e0e0e0; border-radius: 4px; margin: 1.5rem 0;"> <div style="position: absolute; top: -20px; left: 92%; transform: translateX(-50%);"> <span style="font-weight: 500; font-size: 0.8rem; color: var(--secondary-color);">Utility</span> </div> <div style="position: absolute; top: -20px; right: 79%; transform: translateX(50%);"> <span style="font-weight: 500; font-size: 0.8rem; color: var(--primary-color);">Privacy</span> </div> </div> <p id="tradeoff-explanation" style="font-size: 0.9rem; color: var(--text-secondary); margin-top: 1rem;"> This model achieved 92.4% accuracy with a privacy budget of ε=2.1. This is a good trade-off for most applications. </p> </div> </div> <div id="recommendations-tab" class="tab-content"> <h3 style="margin-top: 0; margin-bottom: 1rem; font-size: 1rem;">Recommendations</h3> <ul class="recommendation-list"> <!-- Recommendations will be dynamically added here --> </ul> </div> </div> </div> </div></div>{% endblock %} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261{% extends "base.html" %}
{% block title %}DP-SGD Explorer - Learning Hub{% endblock %}
{% block content %}<h1 class="section-title">Learning Hub</h1>
<div class="learning-container"> <div class="learning-sidebar"> <h2 class="panel-title">DP-SGD Concepts</h2> <ul class="learning-steps"> <li class="learning-step active" data-step="intro">Introduction to Differential Privacy</li> <li class="learning-step" data-step="dp-concepts">Core DP Concepts</li> <li class="learning-step" data-step="sgd-basics">SGD Refresher</li> <li class="learning-step" data-step="dpsgd-intro">DP-SGD: Core Modifications</li> <li class="learning-step" data-step="parameters">Hyperparameter Deep Dive</li> <li class="learning-step" data-step="privacy-accounting">Privacy Accounting</li> </ul> </div> <div class="learning-content"> <div id="intro-content" class="step-content active"> <h2>Introduction to Differential Privacy</h2> <p>Differential Privacy (DP) is a mathematical framework that provides strong privacy guarantees when performing analyses on sensitive data. It ensures that the presence or absence of any single individual's data has a minimal effect on the output of an analysis.</p> <h3>Why is Differential Privacy Important?</h3> <p>Traditional anonymization techniques often fail to protect privacy. With enough auxiliary information, it's possible to re-identify individuals in supposedly "anonymized" datasets. Differential privacy addresses this by adding carefully calibrated noise to the analysis process.</p> <div class="concept-highlight"> <h4>Key Insight</h4> <p>Differential privacy creates plausible deniability. By adding controlled noise, it becomes mathematically impossible to confidently determine whether any individual's data was used in the analysis.</p> </div> <h3>The Privacy-Utility Trade-off</h3> <p>There's an inherent trade-off between privacy and utility (accuracy) in DP. More privacy means more noise, which typically reduces accuracy. The challenge is finding the right balance for your specific application.</p> <div class="concept-box"> <div class="box1"> <h4>Strong Privacy (Low ε)</h4> <ul> <li>More noise added</li> <li>Lower accuracy</li> <li>Better protection for sensitive data</li> </ul> </div> <div class="box2"> <h4>Strong Utility (Higher ε)</h4> <ul> <li>Less noise added</li> <li>Higher accuracy</li> <li>Reduced privacy guarantees</li> </ul> </div> </div> </div> <div id="dp-concepts-content" class="step-content"> <h2>Core Differential Privacy Concepts</h2> <h3>The Formal Definition</h3> <p>A mechanism M is (ε,δ)-differentially private if for all neighboring datasets D and D' (differing in one record), and for all possible outputs S:</p> <div class="formula"> P(M(D) ∈ S) ≤ e^ε × P(M(D') ∈ S) + δ </div> <h3>Key Parameters</h3> <p><strong>ε (epsilon)</strong>: The privacy budget. Lower values mean stronger privacy but typically lower utility.</p> <p><strong>δ (delta)</strong>: The probability of the privacy guarantee being broken. Usually set very small (e.g., 10^-5).</p> <h3>Differential Privacy Mechanisms</h3> <p><strong>Laplace Mechanism</strong>: Adds noise from a Laplace distribution to numeric queries.</p> <p><strong>Gaussian Mechanism</strong>: Adds noise from a Gaussian (normal) distribution. This is used in DP-SGD.</p> <p><strong>Exponential Mechanism</strong>: Used for non-numeric outputs, selects an output based on a probability distribution.</p> <h3>Privacy Accounting</h3> <p>When you apply multiple differentially private operations, the privacy loss (ε) accumulates. This is known as composition.</p> <p>Advanced composition theorems and privacy accountants help track the total privacy spend.</p> </div> <div id="sgd-basics-content" class="step-content"> <h2>Stochastic Gradient Descent Refresher</h2> <h3>Standard SGD</h3> <p>Stochastic Gradient Descent (SGD) is an optimization algorithm used to train machine learning models by iteratively updating parameters based on gradients computed from mini-batches of data.</p> <h3>The Basic Update Rule</h3> <p>The standard SGD update for a batch B is:</p> <div class="formula"> θ ← θ - η∇L(θ; B) </div> <p>Where:</p> <ul> <li>θ represents the model parameters</li> <li>η is the learning rate</li> <li>∇L(θ; B) is the average gradient of the loss over the batch B</li> </ul> <h3>Privacy Concerns with Standard SGD</h3> <p>Standard SGD can leak information about individual training examples through the gradients. For example:</p> <ul> <li>Gradients might be larger for outliers or unusual examples</li> <li>Model memorization of sensitive data can be extracted through attacks</li> <li>Gradient values can be used in reconstruction attacks</li> </ul> <p>These privacy concerns motivate the need for differentially private training methods.</p> </div> <div id="dpsgd-intro-content" class="step-content"> <h2>DP-SGD: Core Modifications</h2> <h3>How DP-SGD Differs from Standard SGD</h3> <p>Differentially Private SGD modifies standard SGD in two key ways:</p> <div class="concept-box"> <div class="box1"> <h4>1. Per-Sample Gradient Clipping</h4> <p>Compute gradients for each example individually, then clip their L2 norm to a threshold C.</p> <p>This limits the influence of any single training example on the model update.</p> </div> <div class="box2"> <h4>2. Noise Addition</h4> <p>Add Gaussian noise to the sum of clipped gradients before applying the update.</p> <p>The noise scale is proportional to the clipping threshold and the noise multiplier.</p> </div> </div> <h3>The DP-SGD Update Rule</h3> <p>The DP-SGD update can be summarized as:</p> <ol> <li>Compute per-sample gradients: g<sub>i</sub> = ∇L(θ; x<sub>i</sub>)</li> <li>Clip each gradient: g̃<sub>i</sub> = g<sub>i</sub> × min(1, C/||g<sub>i</sub>||<sub>2</sub>)</li> <li>Add noise: ḡ = (1/|B|) × (∑g̃<sub>i</sub> + N(0, σ²C²I))</li> <li>Update parameters: θ ← θ - η × ḡ</li> </ol> <p>Where:</p> <ul> <li>C is the clipping norm</li> <li>σ is the noise multiplier</li> <li>B is the batch</li> </ul> </div> <div id="parameters-content" class="step-content"> <h2>Hyperparameter Deep Dive</h2> <p>DP-SGD introduces several new hyperparameters that need to be tuned carefully:</p> <h3>Clipping Norm (C)</h3> <p>The maximum allowed L2 norm for any individual gradient.</p> <ul> <li><strong>Too small:</strong> Gradients are over-clipped, limiting learning</li> <li><strong>Too large:</strong> Requires more noise to achieve the same privacy guarantee</li> <li><strong>Typical range:</strong> 0.1 to 10.0, depending on the dataset and model</li> </ul> <h3>Noise Multiplier (σ)</h3> <p>Controls the amount of noise added to the gradients.</p> <ul> <li><strong>Higher σ:</strong> Better privacy, worse utility</li> <li><strong>Lower σ:</strong> Better utility, worse privacy</li> <li><strong>Typical range:</strong> 0.5 to 2.0 for most practical applications</li> </ul> <h3>Batch Size</h3> <p>Affects both training dynamics and privacy accounting.</p> <ul> <li><strong>Larger batches:</strong> Reduce variance from noise, but change sampling probability</li> <li><strong>Smaller batches:</strong> More update steps, potentially consuming more privacy budget</li> <li><strong>Typical range:</strong> 64 to 1024, larger than standard SGD</li> </ul> <h3>Learning Rate (η)</h3> <p>May need adjustment compared to non-private training.</p> <ul> <li><strong>DP-SGD often requires:</strong> Lower learning rates or careful scheduling</li> <li><strong>Reason:</strong> Added noise can destabilize training with high learning rates</li> </ul> <h3>Number of Epochs</h3> <p>More epochs consume more privacy budget.</p> <ul> <li><strong>Trade-off:</strong> More training vs. privacy budget consumption</li> <li><strong>Early stopping:</strong> Often beneficial for balancing accuracy and privacy</li> </ul> </div> <div id="privacy-accounting-content" class="step-content"> <h2>Privacy Accounting</h2> <h3>Tracking Privacy Budget</h3> <p>Privacy accounting is the process of keeping track of the total privacy loss (ε) throughout training.</p> <h3>Common Methods</h3> <div style="display: flex; flex-direction: column; gap: 15px; margin: 15px 0;"> <div class="concept-highlight"> <h4>Moment Accountant</h4> <p>Used in the original DP-SGD paper, provides tight bounds on the privacy loss.</p> <p>Tracks the moments of the privacy loss random variable.</p> </div> <div class="concept-highlight"> <h4>Rényi Differential Privacy (RDP)</h4> <p>Alternative accounting method based on Rényi divergence.</p> <p>Often used in modern implementations like TensorFlow Privacy and Opacus.</p> </div> <div class="concept-highlight"> <h4>Analytical Gaussian Mechanism</h4> <p>Simpler method for specific mechanisms like the Gaussian Mechanism.</p> <p>Less tight bounds but easier to compute.</p> </div> </div> <h3>Privacy Budget Allocation</h3> <p>With a fixed privacy budget (ε), you must decide how to allocate it:</p> <ul> <li><strong>Fixed noise, variable epochs:</strong> Set noise level, train until budget is exhausted</li> <li><strong>Fixed epochs, variable noise:</strong> Set desired epochs, calculate required noise</li> <li><strong>Advanced techniques:</strong> Privacy filters, odometers, and adaptive mechanisms</li> </ul> <h3>Practical Implementation</h3> <p>In practice, privacy accounting is handled by libraries like:</p> <ul> <li>TensorFlow Privacy</li> <li>PyTorch Opacus</li> <li>Diffprivlib (IBM)</li> </ul> </div> </div></div>
{% endblock %}
{% block extra_scripts %}<script>document.addEventListener('DOMContentLoaded', () => { const steps = document.querySelectorAll('.learning-step'); steps.forEach(step => { step.addEventListener('click', () => { // Remove active class from all steps steps.forEach(s => s.classList.remove('active')); // Add active class to clicked step step.classList.add('active'); // Hide all content document.querySelectorAll('.step-content').forEach(content => { content.classList.remove('active'); }); // Show selected content const stepName = step.getAttribute('data-step'); document.getElementById(`${stepName}-content`).classList.add('active'); }); });});</script>{% endblock %} 1234"""Training module for DP-SGD Explorer.Contains mock trainer and privacy calculator implementations.""" 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152import numpy as npimport timefrom typing import Dict, List, Any
class MockTrainer: def __init__(self): self.base_accuracy = 0.95 # Base accuracy for non-private training self.base_loss = 0.15 # Base loss for non-private training def train(self, params: Dict[str, Any]) -> Dict[str, Any]: """ Simulate DP-SGD training with given parameters. Args: params: Dictionary containing training parameters: - clipping_norm: float - noise_multiplier: float - batch_size: int - learning_rate: float - epochs: int Returns: Dictionary containing training results and metrics """ # Extract parameters clipping_norm = params['clipping_norm'] noise_multiplier = params['noise_multiplier'] batch_size = params['batch_size'] learning_rate = params['learning_rate'] epochs = params['epochs'] # Calculate privacy impact on performance privacy_factor = self._calculate_privacy_factor(clipping_norm, noise_multiplier) # Generate epoch-wise data epochs_data = self._generate_epoch_data(epochs, privacy_factor) # Calculate final metrics final_metrics = self._calculate_final_metrics(epochs_data, privacy_factor) # Generate recommendations recommendations = self._generate_recommendations(params, final_metrics) return { 'epochs_data': epochs_data, 'final_metrics': final_metrics, 'recommendations': recommendations } def _calculate_privacy_factor(self, clipping_norm: float, noise_multiplier: float) -> float: """Calculate how much privacy mechanisms affect model performance.""" # Higher noise and stricter clipping reduce performance return 1.0 - (0.3 * noise_multiplier + 0.2 * (1.0 / clipping_norm)) def _generate_epoch_data(self, epochs: int, privacy_factor: float) -> List[Dict[str, float]]: """Generate realistic training metrics for each epoch.""" epochs_data = [] # Base learning curve parameters base_accuracy = self.base_accuracy * privacy_factor base_loss = self.base_loss / privacy_factor for epoch in range(1, epochs + 1): # Simulate learning curve with some randomness progress = epoch / epochs noise = np.random.normal(0, 0.02) # Small random fluctuations accuracy = base_accuracy * (0.7 + 0.3 * progress) + noise loss = base_loss * (1.2 - 0.2 * progress) + noise epochs_data.append({ 'epoch': epoch, 'accuracy': max(0, min(1, accuracy)) * 100, # Convert to percentage 'loss': max(0, loss) }) return epochs_data def _calculate_final_metrics(self, epochs_data: List[Dict[str, float]], privacy_factor: float) -> Dict[str, float]: """Calculate final training metrics.""" final_epoch = epochs_data[-1] # Add some randomness to training time based on batch size and epochs base_time = 0.5 # Base time in seconds time_factor = (1.0 / privacy_factor) * (1.0 + np.random.normal(0, 0.1)) return { 'accuracy': final_epoch['accuracy'], 'loss': final_epoch['loss'], 'training_time': base_time * time_factor } def _generate_recommendations(self, params: Dict[str, Any], metrics: Dict[str, float]) -> List[Dict[str, str]]: """Generate recommendations based on training results.""" recommendations = [] # Check clipping norm if params['clipping_norm'] < 0.5: recommendations.append({ 'icon': '⚠️', 'text': 'Clipping norm is very low. This might slow down learning.' }) elif params['clipping_norm'] > 2.0: recommendations.append({ 'icon': '🔒', 'text': 'Consider reducing clipping norm for stronger privacy guarantees.' }) # Check noise multiplier if params['noise_multiplier'] < 0.5: recommendations.append({ 'icon': '🔒', 'text': 'Noise multiplier is low. Consider increasing it for better privacy.' }) elif params['noise_multiplier'] > 2.0: recommendations.append({ 'icon': '⚠️', 'text': 'High noise multiplier might significantly impact model accuracy.' }) # Check batch size if params['batch_size'] < 64: recommendations.append({ 'icon': '⚡', 'text': 'Small batch size might lead to noisy updates. Consider increasing it.' }) elif params['batch_size'] > 256: recommendations.append({ 'icon': '🔍', 'text': 'Large batch size might reduce model generalization.' }) # Check learning rate if params['learning_rate'] > 0.05: recommendations.append({ 'icon': '⚠️', 'text': 'High learning rate might destabilize training with DP-SGD.' }) elif params['learning_rate'] < 0.001: recommendations.append({ 'icon': '⏳', 'text': 'Very low learning rate might slow down convergence.' }) # Check final metrics if metrics['accuracy'] < 80: recommendations.append({ 'icon': '📉', 'text': 'Model accuracy is low. Consider adjusting privacy parameters.' }) return recommendations 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import numpy as npfrom typing import Dict, Any
class PrivacyCalculator: def __init__(self): self.delta = 1e-5 # Standard delta value for DP guarantees def calculate_epsilon(self, params: Dict[str, Any]) -> float: """ Calculate the privacy budget (ε) using the moment accountant method. Args: params: Dictionary containing training parameters: - clipping_norm: float - noise_multiplier: float - batch_size: int - epochs: int Returns: The calculated privacy budget (ε) """ # Extract parameters clipping_norm = params['clipping_norm'] noise_multiplier = params['noise_multiplier'] batch_size = params['batch_size'] epochs = params['epochs'] # Calculate sampling rate (assuming MNIST dataset size of 60,000) sampling_rate = batch_size / 60000 # Calculate number of steps steps = epochs * (1 / sampling_rate) # Calculate moments for different orders orders = [1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0] moments = [self._calculate_moment(order, sampling_rate, noise_multiplier) for order in orders] # Find the minimum ε that satisfies all moment bounds epsilon = float('inf') for moment in moments: # Convert moment bound to (ε,δ)-DP bound moment_epsilon = moment + np.log(1/self.delta) / (orders[0] - 1) epsilon = min(epsilon, moment_epsilon) # Add some randomness to make it more realistic epsilon *= (1 + np.random.normal(0, 0.05)) return max(0.1, epsilon) # Ensure ε is at least 0.1 def _calculate_moment(self, order: float, sampling_rate: float, noise_multiplier: float) -> float: """ Calculate the moment bound for a given order. Args: order: The moment order sampling_rate: The probability of sampling each example noise_multiplier: The noise multiplier used in DP-SGD Returns: The calculated moment bound """ # Simplified moment calculation based on the moment accountant method # This is a simplified version that captures the key relationships c = np.sqrt(2 * np.log(1.25 / self.delta)) moment = (order * sampling_rate * c) / noise_multiplier # Add some non-linear effects moment *= (1 + 0.1 * np.sin(order)) return moment def calculate_optimal_noise(self, target_epsilon: float, params: Dict[str, Any]) -> float: """ Calculate the optimal noise multiplier for a target privacy budget. Args: target_epsilon: The desired privacy budget params: Dictionary containing training parameters: - clipping_norm: float - batch_size: int - epochs: int Returns: The calculated optimal noise multiplier """ # Extract parameters clipping_norm = params['clipping_norm'] batch_size = params['batch_size'] epochs = params['epochs'] # Calculate sampling rate sampling_rate = batch_size / 60000 # Calculate number of steps steps = epochs * (1 / sampling_rate) # Calculate optimal noise using the analytical Gaussian mechanism c = np.sqrt(2 * np.log(1.25 / self.delta)) optimal_noise = (c * sampling_rate * np.sqrt(steps)) / target_epsilon # Add some randomness to make it more realistic optimal_noise *= (1 + np.random.normal(0, 0.05)) return max(0.1, optimal_noise) # Ensure noise is at least 0.1 12345flask==3.0.0flask-cors==4.0.0python-dotenv==1.0.0gunicorn==21.2.0numpy==1.24.3 123456from app import create_app
app = create_app()
if __name__ == '__main__': app.run(debug=True) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960#!/bin/bash
# Colors for outputGREEN='\033[0;32m'YELLOW='\033[1;33m'RED='\033[0;31m'NC='\033[0m' # No Color
# Function to print colored messagesprint_message() { echo -e "${2}${1}${NC}"}
# Check if Python 3 is installedif ! command -v python3 &> /dev/null; then print_message "Python 3 is not installed. Please install Python 3 first." "$RED" exit 1fi
# Check Python versionPYTHON_VERSION=$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')print_message "Found Python version: $PYTHON_VERSION" "$GREEN"
# Create virtual environment if it doesn't existif [ ! -d ".venv" ]; then print_message "Creating virtual environment..." "$YELLOW" python3 -m venv .venv if [ $? -ne 0 ]; then print_message "Failed to create virtual environment. Please install python3-venv package." "$RED" exit 1 fifi
# Activate virtual environmentprint_message "Activating virtual environment..." "$GREEN"source .venv/bin/activateif [ $? -ne 0 ]; then print_message "Failed to activate virtual environment." "$RED" exit 1fi
# Install or upgrade pipprint_message "Upgrading pip..." "$YELLOW"python3 -m pip install --upgrade pip
# Install requirementsprint_message "Installing dependencies..." "$YELLOW"pip install -r requirements.txtif [ $? -ne 0 ]; then print_message "Failed to install dependencies." "$RED" exit 1fi
# Start the Flask applicationprint_message "\n=== DP-SGD Explorer Backend ===" "$GREEN"print_message "Starting server..." "$GREEN"print_message "The application will be available at http://127.0.0.1:5000\n" "$YELLOW"
# Set Python path and start serverPYTHONPATH=. python3 run.py README.md+77-1
app/__init__.pyAdded+12
app/__pycache__/__init__.cpython-38.pycAdded
app/__pycache__/routes.cpython-38.pycAdded
app/routes.pyAdded+43
app/static/css/learning.cssAdded+202
app/static/css/styles.cssAdded+457
app/static/js/main.jsAdded+371
app/templates/base.htmlAdded+42
app/templates/index.htmlAdded+331
app/templates/learning.htmlAdded+261
app/training/__init__.pyAdded+4
app/training/__pycache__/__init__.cpython-38.pycAdded
app/training/__pycache__/mock_trainer.cpython-38.pycAdded
app/training/__pycache__/privacy_calculator.cpython-38.pycAdded
app/training/mock_trainer.pyAdded+152
app/training/privacy_calculator.pyAdded+104
requirements.txtAdded+5
run.pyAdded+6
start_server.shAdded+60