Privacy by Design & by Default (GDPR Article 25) is the foundational principle that organizations must adopt when developing AI systems. It's not optional, not a post-hoc addition: it's integral to the design. Data minimization, pseudonymization, risk assessment (DPIA), retention limits, data subject rights: every step of the ML pipeline must embed privacy protections from the start. This article documents how to apply GDPR Article 25 + EU AI Act to real AI systems, with Ollama on-prem (privacy guaranteed) and practical compliance examples.
Introduction: Why Privacy by Design for AI (2026)?
In 2025-2026, European authorities (Italian Data Protection Authority, CNIL, BfDI) are conducting audits on AI systems across tech companies and startups. The focus: is GDPR Article 25 implemented, or just on paper?
Risks if neglected:
- GDPR Fine: up to 4% of global revenue (Article 83).
- EU AI Act High-Risk Classification: hiring, credit scoring, biometric, recommendation systems — require DPIA + documented data governance.
- Reputational Damage: data breach from training set is worse than traditional breach (algorithms memorize).
- Liability: GDPR Article 82 enables civil claims from data subjects if harm is proven.
The solution is not paralysis, but structural design: data minimization from ingestion onward, pseudonymization pre-training, DPIA risk-based, retention policies, Ollama on-prem (zero cloud API calls with sensitive data).
Article 25 GDPR: Privacy by Design & by Default
Article 25 GDPR imposes two parallel principles:
1. Privacy by Design (Article 25.1): From design phase and in all subsequent steps, the controller must implement technical and organizational measures to protect personal data.
2. Privacy by Default (Article 25.2): Default settings must provide the highest level of protection; users should not have to actively "choose" privacy; it must be the default.
Applied to AI systems, this means:
- Collect ONLY necessary data (data minimization).
- Pseudonymize immediately (before storage/training).
- Apply retention decay: delete data when no longer needed.
- Document DPIA before deployment.
- Implement data subject rights (access, rectification, erasure, portability).
- Use privacy-first providers (Ollama on-prem, NOT external cloud APIs).
Data Minimization in ML Pipeline
Data minimization means collecting and retaining only what's necessary for the declared purpose. In ML, many datasets contain unused columns: photos, biographies, IP addresses, granular timestamps — all attack surfaces.
Privacy-First Schema: Minimization at Ingestion Time
# config/data_minimization_policy.yaml
# Applied at ingestion time, BEFORE storage/training
data_ingestion:
# Case: Training set for credit scoring
# ALLOWED (necessary for the model)
allowed_columns:
- user_id: "hash anonymized" # UUID, never raw ID
- annual_income: "decimal" # Only annual, not transactions
- credit_history_years: "integer" # Only duration, not detail
- default_count_12m: "integer" # Last 12 months only
- employment_status: "categorical" # enum: employed|self-employed|retired
# FORBIDDEN (identifiable, not necessary)
forbidden_columns:
- email # No contact info
- phone_number # No contact info
- postal_address # Geo-locatable
- employment_history # Full history unnecessary
- credit_transaction_detail # Raw transaction leak
- ip_address # Device identifier
- device_fingerprint # Biometric-adjacent
- timestamp (granular) # Use epoch-only
# TRANSFORMATION (if present, clean before)
transformations:
- user_id: hash_sha256(salt=PEPPER) # Never store raw user ID
- annual_income: round_to_10k() # Reduce granularity
- timestamp: truncate_to_date() # Remove time precision
- employment_history: null # Drop, not needed
# RETENTION WINDOW
retention_policy:
training_set: "90 days, then delete"
validation_set: "30 days post-model-release"
production_inference: "zero storage — stream inference only"
# Audit trail
audit_trail:
log_access:
- user: "data-engineer-alice"
- action: "loaded credit_scoring_v2_train.parquet"
- timestamp: "2026-07-15T09:30:00Z"
- columns_accessed: ["user_id", "annual_income", "credit_history_years"]
- columns_forbidden: [] # OK, none violated
Code: Filter Out Non-Essential Columns
import pandas as pd
import hashlib
from typing import List
def minimize_dataset(
df: pd.DataFrame,
allowed_columns: List[str],
hash_columns: List[str] = None,
salt: str = "PEPPER_SECRET"
) -> pd.DataFrame:
"""
Minimize the dataset keeping only required columns.
- Drop columns not in the allow-list.
- Hash identifiable columns.
- Return cleaned dataset.
"""
if hash_columns is None:
hash_columns = []
# 1. Keep only allowed columns
if not all(col in df.columns for col in allowed_columns):
missing = set(allowed_columns) - set(df.columns)
raise ValueError(f"Missing columns: {missing}")
df_minimal = df[allowed_columns].copy()
# 2. Hash identifiable columns
for col in hash_columns:
if col in df_minimal.columns:
df_minimal[col] = df_minimal[col].apply(
lambda x: hashlib.sha256(
f"{x}{salt}".encode()
).hexdigest()
if pd.notna(x) else None
)
# 3. Verify no unexpected nulls
assert df_minimal.isnull().sum().sum() == 0, "Nulls detected after minimization"
return df_minimal
# Usage
if __name__ == "__main__":
raw_data = pd.read_csv("raw_credit_scores.csv")
print(f"Raw shape: {raw_data.shape}") # (100000, 35 columns)
minimized = minimize_dataset(
raw_data,
allowed_columns=["user_id", "annual_income", "default_count_12m"],
hash_columns=["user_id"],
salt="PEPPER_SECRET"
)
print(f"Minimized shape: {minimized.shape}") # (100000, 3 columns)
print(minimized.head())
Pseudonymization and Encryption
Pseudonymization is not anonymization. It means rendering data not attributable to an individual without supplementary information (the "key"). In ML, it's the first protection layer.
Pseudonymization Strategies
- Deterministic hash (e.g. SHA-256 + salt): Transform user_id into hash; the mapping is rigid (same input → same hash). Useful for table linkage; reverse brute-force is possible if inputs are known.
- Tokenization (random UUID): Generate random token per record; maintain mapping in separate vault. Zero reverse feasibility without vault.
- Differential Privacy (DP): Add statistical noise to data; query returns "DP-guaranteed" result without revealing single record.
- End-to-end Encryption: Encrypt data at rest and in transit; Ollama on-prem accesses plaintext only in runtime memory.
Code: Pseudonymization with Secure Tokenization
import uuid
import json
from datetime import datetime, timedelta
from cryptography.fernet import Fernet
import os
class PseudonymizationVault:
"""
Manages tokenization with separate vault.
- Generate random token for each PII.
- Maintain token ↔ PII mapping in encrypted vault.
- Support TTL (time-to-live) for automatic retention.
"""
def __init__(self, vault_path: str = "./.vault/pseudonym.db"):
self.vault_path = vault_path
self.cipher = Fernet(Fernet.generate_key())
self.mapping = {} # Production: use Redis or encrypted DB
def pseudonymize(self, pii_value: str, ttl_days: int = 90) -> str:
"""
Transform PII into random token.
TTL: auto-delete after N days.
"""
# Generate random token (UUID v4)
token = str(uuid.uuid4())
# Encrypt value and TTL
expiry = datetime.utcnow() + timedelta(days=ttl_days)
record = {
"pii": pii_value,
"created_at": datetime.utcnow().isoformat(),
"expires_at": expiry.isoformat()
}
encrypted = self.cipher.encrypt(
json.dumps(record).encode()
)
# Store mapping
self.mapping[token] = encrypted
return token
def depseudonymize(self, token: str) -> str:
"""Return original PII (only for data subject rights)."""
if token not in self.mapping:
raise ValueError(f"Token not found: {token}")
encrypted = self.mapping[token]
decrypted = self.cipher.decrypt(encrypted)
record = json.loads(decrypted.decode())
# Check TTL
expiry = datetime.fromisoformat(record["expires_at"])
if datetime.utcnow() > expiry:
del self.mapping[token]
raise ValueError(f"Token expired: {token}")
return record["pii"]
# Usage
vault = PseudonymizationVault()
# Ingestion: pseudonymize PII
user_id = "user_12345@company.com"
token = vault.pseudonymize(user_id, ttl_days=90)
print(f"Token: {token}") # 550e8400-e29b-41d4-a716-446655440000
# Training: use token only, never PII
training_data = {"user": token, "feature": 42}
print(training_data)
# Data Subject Request (ACCESS): return PII
retrieved = vault.depseudonymize(token)
assert retrieved == user_id
print(f"Access granted to data subject: {retrieved}")
DPIA for High-Risk AI
EU AI Act defines high-risk AI (Annex III): hiring, credit scoring, biometric, recidivism prediction, border control, etc. For these, GDPR Article 35 requires a Data Protection Impact Assessment (DPIA).
DPIA is not a compiled template: it's a structured analysis of:
- Nature of processing: What do you process? Sensitive data? Tracking? Automated decisions?
- Scope and context: Who is affected? Employees, customers, public?
- Necessity and proportionality: Is the purpose legitimate? Are there less invasive alternatives?
- Risks to rights and freedoms: Discrimination? Privacy breach? Unlawful profiling?
- Mitigation measures: Pseudonymization, encryption, access controls, audit trail, DPO involvement?
Minimal DPIA Template for AI
# dpia/credit_scoring_ai_v2.yaml
dpia:
ai_system: "Credit Scoring AI v2"
risk_category: "HIGH-RISK" # EU AI Act Annex III
date_created: "2026-07-15"
dpo_email: "dpo@company.com"
# 1. Description of processing
processing_description:
purpose: |
Automate credit approval decisions.
Enforce fair lending rules.
data_categories:
- employment_status
- annual_income
- credit_history_years
- default_count_12m
data_subjects: "Loan applicants"
retention: "90 days: training window. Then delete."
# 2. Identified risks
risks:
- risk_id: "DISC-001"
description: "Indirect discrimination via proxy for race/gender"
severity: "CRITICAL"
likelihood: "MEDIUM"
impact: "GDPR Article 5(1)(d) violation + EU AI Act Article 10"
- risk_id: "PRIVACY-002"
description: "Data memorization in model parameters (membership inference)"
severity: "HIGH"
likelihood: "HIGH"
impact: "Re-identification of individuals"
- risk_id: "TRANSPARENCY-003"
description: "Failure to communicate automated decision to subject"
severity: "HIGH"
likelihood: "LOW"
impact: "GDPR Article 22 violation (right to object)"
# 3. Mitigation measures
mitigations:
- for_risk: "DISC-001"
measures:
- "Quarterly fairness audit (demographic parity, disparate impact ratio)"
- "Exclude proxy features (ZIP code, education if correlated with protected attributes)"
- "Bias dataset detection via SHAP + explainability"
responsible: "Data Science Team"
deadline: "2026-08-15"
- for_risk: "PRIVACY-002"
measures:
- "Differential Privacy: epsilon=0.5, delta=1e-5 at training step"
- "Model watermarking (fingerprint v2) to detect membership attack"
- "Regular membership inference tests (shadow models)"
responsible: "ML Ops"
deadline: "2026-08-01"
- for_risk: "TRANSPARENCY-003"
measures:
- "Mandatory communication to customer within 3 days (Article 21 GDPR)"
- "Provide feature importance (LIME/SHAP) in denial motives"
- "Appeal process: human review post-denial"
responsible: "Legal + Product"
deadline: "2026-07-30"
# 4. Conclusion
recommendation: "PROCEED WITH MITIGATIONS. Monitor ongoing compliance via audit trail."
approver: "DPO"
approver_sign_date: "2026-07-15"
Legal Basis for Training and Fine-Tuning
Many organizations mistakenly assume that "collecting the data" automatically permits ML training. Wrong. GDPR Article 6 requires a legal basis for every processing:
- Consent (Article 6.1.a): User explicitly agrees to ML training. Problem: revocable, must be granular (training ≠ inference ≠ marketing).
- Contract (Article 6.1.b): Training is necessary to perform the promised service (e.g. recommendation engine for e-commerce). Strong, non-revocable.
- Legal Obligation (Article 6.1.c): Regulation (AML, sanctions, etc.).
- Legitimate Interest (Article 6.1.f): "Improve the product" is NOT; "prevent fraud" is. Requires balancing test: company interest vs. privacy risk.
- Public Task (Article 6.1.e): Public administrations.
For fine-tuning Ollama on-prem with proprietary data, the strongest base is contract (Article 6.1.b) + legitimate interest (Article 6.1.f) if a documented balancing test exists.
Data Retention and Deletion
GDPR Article 5(1)(e): "personal data kept for no longer than necessary." In ML, this is critical: the training set contains sensitive data that must be deleted after the purpose.
Retention Policy for AI Training
# config/retention_policy_ai.yaml
retention_windows:
# Training set: necessary only during development + validation
training_set:
retention_days: 90
purpose: "Model training and validation"
action_on_expiry: "DELETE" # Hard delete, non-recoverable
checksum_before_delete: "SHA256 final digest stored for audit"
# Production model (artifacts only): indefinite (necessary for inference)
production_model_artifacts:
retention_days: null # Indefinite, while model is active
purpose: "Active inference"
deletion_trigger: "Model decommissioned"
# Inference logs (PII minimized): for debugging + audit
inference_logs:
retention_days: 30
purpose: "Model monitoring and fairness audit"
data_minimization: "Log only token + prediction, never original features"
action_on_expiry: "DELETE"
# Audit trail (non-PII): for compliance
audit_trail:
retention_days: 2555 # 7 years (statute of limitations)
purpose: "Compliance documentation"
data_minimization: "Timestamp + action + user_id_hash, never PII"
action_on_expiry: "ARCHIVE offline"
# Cron automation (e.g. K8s CronJob)
automated_deletion:
schedule: "0 2 * * * (02:00 UTC daily)"
actions:
- scan_training_sets:
older_than: "90 days"
action: "hard_delete_with_verification"
- scan_inference_logs:
older_than: "30 days"
action: "hard_delete"
- verify_deletion:
query_db: "SELECT COUNT(*) FROM deleted_records WHERE created_at < '90 days ago'"
alert_if_nonzero: "DPO@company.com"
Data Subject Rights in ML Pipeline
GDPR Articles 15-22 define data subject rights in automated processing:
- Access (Article 15): The subject has the right to access data in your possession. For AI: provide features used by the model + prediction reasoning (SHAP).
- Rectification (Article 16): Correct inaccurate data. In ML, fix the source data and retrain (or mark record as rectified and re-infer).
- Erasure (Article 17 - "Right to Be Forgotten"): Delete all data. Critical problem in ML: the model has "memorized" the pattern. Solution: membership inference test + differential privacy.
- Object (Article 21): Refuse processing based on legitimate interest. For AI scoring: system must implement exception (human review fallback).
- Automated Decisions (Article 22): "Not be subject to decision based on automated processing with legal effects." Exception: explicit consent, contract necessary, legal obligation. Credit scoring is NOT an exception, so human in the loop is always required.
Implementation: Data Subject Access Request (DSAR) for ML
# ml_compliance/dsar_handler.py
import json
from datetime import datetime
from typing import Dict, List
import shap
class DSARHandler:
"""
Handle Data Subject Access Request for AI systems.
Provide to subject: data in possession + reasoning + prediction history.
"""
def __init__(self, db, model, feature_encoder):
self.db = db
self.model = model
self.feature_encoder = feature_encoder
def handle_access_request(self, user_token: str) -> Dict:
"""
Return a DSAR package:
- Data of subject in our possession (pseudonymized where possible)
- Prediction history (last 90 days)
- Explainability (SHAP feature importance)
- Audit trail
"""
# 1. Retrieve pseudonymization vault
from ml_compliance.pseudonym import vault
try:
user_id = vault.depseudonymize(user_token)
except ValueError:
return {"error": "Token expired. Contact DPO."}
# 2. Data in possession (access to records)
stored_data = self.db.query(f"SELECT * FROM user_features WHERE user_id_hash = %s", [user_token])
# 3. Prediction history (last 90 days)
predictions = self.db.query(f"""
SELECT prediction_date, prediction_score, prediction_decision
FROM inference_log
WHERE user_token = %s AND prediction_date > NOW() - INTERVAL 90 DAY
ORDER BY prediction_date DESC
""", [user_token])
# 4. Explainability (SHAP)
latest_features = stored_data[-1] if stored_data else {}
X = self.feature_encoder.transform([latest_features])
shap_explainer = shap.TreeExplainer(self.model)
shap_values = shap_explainer.shap_values(X)
# 5. Construct DSAR response
dsar_package = {
"dsar_request_date": datetime.utcnow().isoformat(),
"user_pseudonym": user_token,
"disclaimer": "This package contains pseudonymized data and AI reasoning. For full PII, contact DPO.",
"stored_data": stored_data,
"prediction_history": [
{
"date": pred["prediction_date"].isoformat(),
"score": float(pred["prediction_score"]),
"decision": pred["prediction_decision"]
}
for pred in predictions
],
"latest_prediction_explanation": {
"model_name": "credit_scoring_v2",
"features": {k: v for k, v in latest_features.items()},
"feature_importances": self._format_shap(shap_values)
}
}
return dsar_package
def _format_shap(self, shap_values):
"""Format SHAP values in readable way."""
return {
"top_positive": "Features that increased the score",
"top_negative": "Features that decreased the score",
"raw_values": shap_values.tolist()
}
# Usage
dsar = DSARHandler(db, credit_model, feature_encoder)
response = dsar.handle_access_request("550e8400-e29b-41d4-a716-446655440000")
print(json.dumps(response, indent=2))
EU AI Act: Privacy & Transparency Compliance
EU AI Act (effective March 2025) adds specific requirements for high-risk AI:
- Article 13 (Transparency): Disclose to subject that a decision is automated. Clear communication of logic.
- Article 14 (Human Oversight): Human involved in decision (not purely automated). Competence, authority, safeguards.
- Article 10 (Data Quality): Training set representative, bias auditing, quality governance.
- Conformity Assessment: Risk evaluation before deployment, audit trail, documented compliance.
The GDPR + EU AI Act overlap is: Privacy by Design (GDPR) is prerequisite for High-Risk AI compliance (EU AI Act).
Ollama On-Prem: Privacy by Design in Practice
Ollama is an open-source framework for running LLMs locally, without external cloud APIs. It is privacy by design because:
- Zero cloud call: Data never leaves the corporate network.
- Encryption at rest: Model weights stored locally (not cloud).
- Auditability: Inference logs are local, controllable.
- Data retention full control: You decide when to delete cache + prompt history.
Ollama Setup Privacy-First
#!/bin/bash
# ollama_privacy_setup.sh
# Setup Ollama on-prem with privacy policy
# 1. Installation (on Ubuntu/Debian)
curl https://ollama.ai/install.sh | sh
# 2. Download model (e.g. llama3.1:8b)
ollama pull llama3.1:8b
# 3. Start Ollama with local binding ONLY (no network exposure)
ollama serve \
--host 127.0.0.1:11434 \
--disable-mmap false \
--num-parallel 1 \
--num-gpu 1
# 4. Configure retention + cache cleanup
# Add to crontab: retention decay daily
echo "0 3 * * * /usr/local/bin/ollama_cache_cleanup.sh" | crontab -
# 5. Verify health + compliance
curl http://127.0.0.1:11434/api/tags | jq '.[]' # List models
curl http://127.0.0.1:11434/api/status # Health check
Code: Privacy-Preserving Inference via Ollama
import requests
import json
from datetime import datetime, timedelta
class PrivacyPreservingOllamaClient:
"""
Ollama client ensuring privacy:
- Local inference (zero cloud)
- Auto-purge prompt history after TTL
- Pseudonymization in logs
"""
def __init__(self, base_url: str = "http://127.0.0.1:11434"):
self.base_url = base_url
self.prompt_ttl_hours = 24 # Auto-delete prompt after 24h
def infer_on_prem(self, prompt: str, model: str = "llama3.1:8b") -> str:
"""
Run inference on-prem without cloud API call.
"""
response = requests.post(
f"{self.base_url}/api/generate",
json={
"model": model,
"prompt": prompt,
"stream": False,
"options": {
"temperature": 0.7,
"top_k": 40,
"top_p": 0.9,
}
},
timeout=60
)
if response.status_code != 200:
raise RuntimeError(f"Ollama error: {response.text}")
result = response.json()
return result.get("response", "")
def infer_with_data_minimization(
self,
user_token: str,
prompt_template: str,
features: dict
) -> str:
"""
Inference with pseudonymization:
- Accept user_token (no PII)
- Build prompt from features
- Return output (no PII storage)
"""
# 1. Minimize features (only necessary)
minimal_features = {
k: v for k, v in features.items()
if k in ["annual_income", "credit_years"] # Allow-list
}
# 2. Build anonymized prompt
prompt = prompt_template.format(
user_token=user_token,
**minimal_features
)
# 3. Infer on-prem
output = self.infer_on_prem(prompt)
# 4. Pseudonymized log (token, timestamp, no PII)
self._log_inference(
user_token=user_token,
timestamp=datetime.utcnow(),
output_length=len(output)
)
return output
def _log_inference(self, user_token: str, timestamp: datetime, output_length: int):
"""Write minimized log (token, timestamp, size)."""
log_entry = json.dumps({
"user_token": user_token,
"timestamp": timestamp.isoformat(),
"output_bytes": output_length,
"expires_at": (timestamp + timedelta(hours=self.prompt_ttl_hours)).isoformat()
})
# Production: write to local file / local DB
with open("/var/log/ollama_inference.log", "a") as f:
f.write(log_entry + "\n")
# Usage
client = PrivacyPreservingOllamaClient()
# Prompt template (anonymized)
template = """
Credit Scoring Decision Support
Applicant token: {user_token}
Annual income: ${annual_income}
Credit history years: {credit_years}
Based on above, provide a preliminary assessment:
"""
# Minimized features
features = {
"annual_income": 75000,
"credit_years": 5
}
# Infer on-prem
output = client.infer_with_data_minimization(
user_token="550e8400-e29b-41d4-a716-446655440000",
prompt_template=template,
features=features
)
print(f"Ollama output (on-prem): {output}")
Case Study: Private RAG with Local Embeddings
Retrieval-Augmented Generation (RAG) with sensitive corporate data requires Privacy by Design:
- Embedding model: local (e.g. `sentence-transformers` in Ollama).
- Vector store: PostgreSQL with pgvector (local), not Pinecone/Weaviate cloud.
- Retrieval: query → embedding local → similarity search local → LLM local.
Benefit: zero data leaves the corporate network.
Tools and Compliance Checks
To monitor Privacy by Design + EU AI Act compliance:
- DPIA Templates: Italian DPA, CNIL, BfDI (online, free).
- Fairness Audit Tools: AI Fairness 360 (IBM), Fairlearn (Microsoft).
- Differential Privacy: OpenDP, TensorFlow Privacy.
- Explainability: SHAP, LIME.
- Membership Inference Detection: PyMITorch.
FAQ
Q: Is pseudonymization mandatory?
A: GDPR Article 32 requires "appropriate" technical/organizational measures (pseudonymization is one). Not mandatory, but "expected by default" for high-risk systems. If NOT implemented, you must justify why (impracticable, disproportionate). EU AI Act pushes toward pseudonymization / differential privacy for high-risk.
Q: Is Ollama on-prem really more private than a cloud AI service?
A: Yes, structurally. Proprietary cloud AI services could theoretically log / retain input data (depends on contract). Ollama, running locally, has no API calls: zero possibility of leak to third parties. Trade-off: lower QoS (limited hardware, no fine-tuning on millions of parameters).
Q: What do I do if a user requests erasure (Article 17)?
A: If data is in past training set: (1) verify if production model contains it (membership inference test); (2) if yes, retrain without that data (or use differential privacy); (3) document right to erasure in DPIA and audit trail. For current dataset: delete immediately.
Q: Do I need consent for Ollama fine-tuning?
A: Depends on legal basis. If "necessary for contract" (e.g. customer pays for personalized model), basis is Article 6.1(b) — no consent. If "our legitimate interest" (e.g. improve product), use Article 6.1(f) + documented balancing test in DPIA.
Q: What is "high-risk" AI under EU AI Act?
A: Annex III EU AI Act lists: biometric ID + monitoring, employment, education, credit + loan scoring, hiring, law enforcement, migration + border control, asylum, critical infrastructure. If your system is in this list, it's presumed high-risk → DPIA mandatory + human oversight + transparency + data governance.
Conclusion
Privacy by Design for AI is not compliance theater. It's a structural engineering competency: pseudonymization, retention policy, DPIA risk assessment, human oversight, Ollama on-prem to avoid cloud leakage. GDPR Article 25 + EU AI Act together shift focus from "reaction to incidents" to "proactive design". Start with data minimization, pseudonymization, DPIA, and proceed through deployment monitoring.

Commenti
Caricamento commenti...
Sign in to comment