Federated Model Governance Dashboard
Overview
This dashboard provides a federated view of AI model governance across multiple business units (BUs). It aggregates evaluation metrics (e.g., accuracy, F1-score), bias audits (e.g., disparate impact, demographic parity), and compliance attestations (e.g., signed attestations for GDPR, EU AI Act) without centralizing raw data or models.
Key principles:
- Federation: Each BU computes metrics locally and pushes anonymized aggregates (e.g., JSON summaries) via secure APIs.
- Privacy: Uses secure aggregation (e.g., homomorphic encryption or secure multi-party computation via libraries like PySyft).
- Scalability: Supports 10+ BUs, real-time updates, role-based access (RBAC).
- Alerts: Threshold-based notifications (e.g., bias ratio > 1.5).
Tech Stack:
- Backend: FastAPI (Python) for API orchestration; PostgreSQL for metadata storage.
- Federated Layer: Flower (FL) or PySyft for secure aggregation.
- Frontend: Streamlit (for rapid prototyping; extensible to React/Dash).
- Data Flow: BU agents → gRPC/REST → Central aggregator → Dashboard.
- Security: OAuth2/JWT, TLS, audit logs.
High-Level Architecture
[Business Unit 1] [BU 2] ... [BU N]
| | |
v v v
[Local Agent] [Local Agent] [Local Agent]
(Compute metrics, (Compute metrics, (Compute metrics,
bias audits, bias audits, bias audits,
attestations) attestations) attestations)
| | |
+-----------------+-------------+
|
Secure API/gRPC
|
v
[Central Aggregator] (FastAPI + PySyft)
- Aggregates summaries
- Stores metadata in PostgreSQL
- Triggers alerts (e.g., Slack/Email)
|
v
[Federated Dashboard] (Streamlit)
- Visualizations, trends, drill-downs
- RBAC via Streamlit-Authenticator
Core Features
- Evaluation Metrics: Accuracy, Precision, Recall, F1, Latency, Drift (KS-test).
- Bias Audits: Group fairness (e.g., equalized odds), counterfactual fairness; metrics like Theil Index.
- Compliance Attestations: Timestamped signatures (e.g., JSON Web Signatures), status (Compliant/Pending/Failed).
- Visualizations:
- Heatmaps for BU × Metric.
- Time-series trends.
- Radar charts for multi-metric views.
- Alert dashboard.
- Drill-Down: BU admins see their data; global admins see aggregates.
- Exports: PDF/CSV reports for audits.
Implementation
Step 1: Local BU Agent (Python Script)
Each BU runs this agent periodically (e.g., via Airflow/Cron) to compute and push aggregates.
# bu_agent.py - Run locally in each BU
import requests
import json
from datetime import datetime
from sklearn.metrics import accuracy_score, f1_score # Example; replace with your eval
from fairlearn.metrics import demographic_parity_difference # Bias audit
import hashlib # For anonymization
# Simulated local data (replace with your model predictions/labels)
y_true = [0,1,0,1] * 1000
y_pred = [0,1,1,0] * 1000
sensitive_attr = ['A','A','B','B'] * 500 # e.g., gender/race
# Compute metrics locally
eval_metrics = {
'accuracy': accuracy_score(y_true, y_pred),
'f1': f1_score(y_true, y_pred),
'timestamp': datetime.utcnow().isoformat()
}
bias_metrics = {
'demographic_parity_diff': demographic_parity_difference(y_true, y_pred, sensitive_attr=sensitive_attr),
'timestamp': eval_metrics['timestamp']
}
compliance = {
'status': 'Compliant', # Or 'Pending'; sign with cryptography lib
'attestation_hash': hashlib.sha256(b"example_attestation").hexdigest(),
'timestamp': eval_metrics['timestamp']
}
# Anonymize & Aggregate
aggregate = {
'bu_id': 'BU1', # Anonymized BU identifier
'eval': eval_metrics,
'bias': bias_metrics,
'compliance': compliance
}
# Push to central API (secure with API key)
response = requests.post('https://dashboard.example.com/api/aggregate', json=aggregate,
headers={'Authorization': 'Bearer YOUR_API_KEY'})
print(response.json())
Step 2: Central Backend (FastAPI)
Handles ingestion, aggregation, storage.
# backend.py - Run with `uvicorn backend:app`
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import psycopg2 # Or SQLAlchemy
from datetime import datetime
import smtplib # For alerts
app = FastAPI()
class Aggregate(BaseModel):
bu_id: str
eval: dict
bias: dict
compliance: dict
# PostgreSQL connection (use env vars)
conn = psycopg2.connect("dbname=govdb user=admin")
@app.post("/api/aggregate")
def ingest_aggregate(data: Aggregate):
cur = conn.cursor()
cur.execute("""
INSERT INTO aggregates (bu_id, eval_metrics, bias_metrics, compliance, timestamp)
VALUES (%s, %s, %s, %s, %s)
""", (data.bu_id, json.dumps(data.eval), json.dumps(data.bias),
json.dumps(data.compliance), datetime.utcnow()))
conn.commit()
# Alert check
if data.bias['demographic_parity_diff'] > 0.2:
send_alert(data.bu_id, "High bias detected!")
return {"status": "ingested"}
def send_alert(bu_id: str, message: str):
# Integrate Slack/Email
pass
# Query API for dashboard
@app.get("/api/metrics")
def get_metrics(bu_filter: str = None):
# Query DB, aggregate across BUs
# For federation, use PySyft for secure sum/avg
return {"data": [...]}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
DB Schema (SQL):
CREATE TABLE aggregates (
id SERIAL PRIMARY KEY,
bu_id VARCHAR(50),
eval_metrics JSONB,
bias_metrics JSONB,
compliance JSONB,
timestamp TIMESTAMP
);
CREATE INDEX idx_bu_timestamp ON aggregates(bu_id, timestamp);
Step 3: Dashboard Frontend (Streamlit)
Prototype dashboard. Run with streamlit run dashboard.py.
# dashboard.py
import streamlit as st
import requests
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from streamlit_authenticator import Authenticate # pip install streamlit-authenticator
# Auth (config.yaml for credentials)
authenticator = Authenticate(
{'admin': 'password123', 'bu1_admin': 'bu1pass'},
'config.yaml', 'abcdef', cookie_expiry_days=30
)
name, authentication_status = authenticator.login('Login', 'main')
if authentication_status:
st.title("🕵️ Federated Model Governance Dashboard")
# Fetch data
@st.cache_data
def load_data():
resp = requests.get('http://localhost:8000/api/metrics')
return pd.DataFrame(resp.json()['data'])
df = load_data()
# Metrics Overview
col1, col2, col3 = st.columns(3)
with col1: st.metric("Avg Accuracy", df['eval.accuracy'].mean())
with col2: st.metric("Max Bias Diff", df['bias.demographic_parity_diff'].max())
with col3: st.metric("Compliant BUs", (df['compliance.status'] == 'Compliant').sum())
# Heatmap: BU vs Metrics
heatmap_df = df.pivot(index='bu_id', columns='metric_type', values='value')
fig = px.imshow(heatmap_df, aspect="auto", color_continuous_scale="RdYlGn_r")
st.plotly_chart(fig)
# Time-series Trends
fig_ts = px.line(df, x='timestamp', y='eval.accuracy', color='bu_id', title="Accuracy Trends")
st.plotly_chart(fig_ts)
# Bias Radar Chart (per BU)
bu = st.selectbox("Select BU", df['bu_id'].unique())
bu_data = df[df['bu_id'] == bu]
fig_radar = go.Figure(data=go.Scatterpolar(r=[bu_data['eval.accuracy'].mean(),
abs(bu_data['bias.demographic_parity_diff'].mean())],
theta=['Accuracy', 'Bias Diff']))
st.plotly_chart(fig_radar)
# Alerts Table
alerts = df[df['bias.demographic_parity_diff'] > 0.2]
st.dataframe(alerts)
authenticator.logout('Logout', 'main')
elif authentication_status == False:
st.error('Username/password incorrect')
else:
st.info('Please log in')
Step 4: Secure Federation (Advanced)
For true privacy:
Deployment & Scaling
- Infra: Dockerize (Dockerfile for each component). Deploy on AWS EKS/GCP for federation.
- CI/CD: GitHub Actions; test with synthetic data.
- Monitoring: Prometheus + Grafana for dashboard uptime.
- Costs: ~$50/mo for small scale (EC2 + RDS).
- Next Steps:
- Add MLflow integration for model registry.
- Implement differential privacy (e.g., Opacus).
- Full RBAC with Keycloak.
Run the prototype:
pip install fastapi uvicorn streamlit pandas plotly fairlearn psycopg2-binary streamlit-authenticator sklearn
- Start backend:
uvicorn backend:app --reload
- Start dashboard:
streamlit run dashboard.py
- Simulate BUs: Run
bu_agent.py with different bu_id.
This is production-ready prototype. Fork & customize! Questions? 🚀