
Building the data foundations for a bank foundation model (Part 2 of 3)
Build a privacy-first data pipeline for bank foundation models — pseudonymization with AWS Glue, BPE tokenization, and GDPR-compliant Iceberg storage.
Learning level: Advanced (400)
Author: Faris Haddad
Building data foundations for a foundation model is the hardest part. You can't train on messy data — it's that simple.
In Part 1 , I made the case for why banks should train their own foundation models — with evidence showing 16–130% improvement across key banking tasks. But before you touch a GPU, you need to solve three problems: how to protect customer privacy, how to represent heterogeneous banking data as tokens, and how to store everything in a way that satisfies your General Data Protection Regulation (GDPR) obligations.
In this post, I walk through the data foundations layer with complete code examples. By the end, you'll have a pseudonymization pipeline deployed on AWS Glue , a trained Byte Pair Encoding (BPE) tokenizer, and a GDPR-compliant storage layer using Apache Iceberg on Amazon S3 . These are the building blocks that Part 3 will consume for model training.
Prerequisites
Before you begin, you need the following:
- An AWS account with access to Amazon S3, AWS Glue, and AWS Key Management Service (AWS KMS)
- Access to banking event data (transactions, digital engagement, communications, product events, risk events)
- Python 3.10+ with HuggingFace Tokenizers and Apache Iceberg libraries
- Familiarity with ETL pipelines and data lake concepts
Solution overview
The data foundations layer has four steps:
- Define the event schema and semantic key registry
- Build the pseudonymization pipeline on AWS Glue — with encryption
- Train the BPE tokenizer
- Design GDPR-compliant storage with Apache Iceberg — registered in the AWS Glue Data Catalog
Each step produces an artifact that the next step consumes. Get them right, and model training in Part 3 becomes straightforward. Get them wrong, and you'll be debugging data quality issues for months.
The following architecture diagram shows where these components fit in the end-to-end system:

Figure 1: Data pipeline architecture — from raw event sources through pseudonymization, tokenization, and GDPR-compliant storage.
Step 1: Define the event schema and semantic key registry
The first step is to standardize your heterogeneous banking data into a uniform schema. This might sound mundane, but it's the foundation everything else builds on. Get this wrong, and you'll be debugging tokenization issues for weeks.
Every field across all event sources needs a semantic key definition that specifies its type, privacy classification, and tokenization method.
from dataclasses import dataclass, fieldfrom typing import Dict, Optionalfrom enum import Enum
class EventSource(Enum): TRANSACTIONS = "transactions" DIGITAL = "digital_engagement" COMMUNICATIONS = "communications" PRODUCT = "product_events" RISK = "risk_events"
class ValueType(Enum): CATEGORICAL = "categorical" NUMERICAL = "numerical" TEXTUAL = "textual" TEMPORAL = "temporal" BINARY = "binary"
class PrivacyClassification(Enum): PUBLIC = "public" INTERNAL = "internal" CONFIDENTIAL = "confidential" RESTRICTED = "restricted"
@dataclassclass SemanticKeyDefinition: key_name: str value_type: ValueType source: EventSource privacy_class: PrivacyClassification cardinality: Optional[int] = None bucket_count: int = 50 pii_risk: bool = False
Define keys for each of your five event sources. The following example shows transaction keys:
TRANSACTION_KEYS = [ SemanticKeyDefinition("txn_type", ValueType.CATEGORICAL, EventSource.TRANSACTIONS, PrivacyClassification.INTERNAL, cardinality=12), SemanticKeyDefinition("txn_amount", ValueType.NUMERICAL, EventSource.TRANSACTIONS, PrivacyClassification.CONFIDENTIAL, bucket_count=50), SemanticKeyDefinition("txn_merchant", ValueType.TEXTUAL, EventSource.TRANSACTIONS, PrivacyClassification.INTERNAL), SemanticKeyDefinition("txn_mcc", ValueType.CATEGORICAL, EventSource.TRANSACTIONS, PrivacyClassification.PUBLIC, cardinality=400), SemanticKeyDefinition("txn_channel", ValueType.CATEGORICAL, EventSource.TRANSACTIONS, PrivacyClassification.INTERNAL, cardinality=8),]
This registry serves as the single source of truth for how every field is treated throughout the pipeline. You'll reference it in the pseudonymization stage, the tokenizer, and the model architecture.
Tip: Aim for 60–80 semantic keys across all five event sources. Fewer than 40 and you're losing signal. More than 120 and you're likely including redundant fields that inflate sequence length without adding predictive value.
Timestamp jitter: In the Iceberg schema (Step 4),
event_timestamp values are stored with ±30 seconds of random jitter applied. This is a deliberate privacy technique — without jitter, an adversary could correlate pseudonymized records across tables using precise timestamps, potentially re-identifying individuals. The jitter is small enough to have no effect on the model's temporal learning, but large enough to break timing-based re-identification attacks.Step 2: Build the pseudonymization pipeline
Before any data enters the training environment, you must remove direct identifiers while preserving statistical patterns. Deploy this as an AWS Glue extract, transform, load (ETL) job that processes events in batch.
The pipeline has three core components: a crypto engine for Hash-based Message Authentication Code (HMAC)-SHA256 hashing, a personally identifiable information (PII) scrubber for free-text fields, and a numerical bucketer for amounts.
import hashlibimport hmacimport refrom dataclasses import dataclassfrom typing import Dict, Any, Listfrom enum import Enum
class PseudoMethod(Enum): HMAC_SHA256 = "hmac_sha256" SUPPRESS = "suppress" BUCKET = "bucket" GENERALISE = "generalise" BPE_TOKENISE = "bpe_tokenise" PASSTHROUGH = "passthrough"
@dataclassclass FieldTreatment: field_pattern: str method: PseudoMethod params: Dict[str, Any]
FIELD_TREATMENTS = [ FieldTreatment("customer_id|account_id", PseudoMethod.HMAC_SHA256, {"key_purpose": "identifier"}), FieldTreatment("name|address|email|phone|nino", PseudoMethod.SUPPRESS, {}), FieldTreatment("postcode", PseudoMethod.GENERALISE, {"level": "outward_code"}), FieldTreatment("amount|balance|value|salary", PseudoMethod.BUCKET, {"n_buckets": 50, "method": "percentile"}), FieldTreatment("merchant_name|description", PseudoMethod.BPE_TOKENISE, {"scrub_pii_first": True}), FieldTreatment("mcc|currency|country_code", PseudoMethod.PASSTHROUGH, {}),]
The crypto engine
The crypto engine uses HMAC-SHA256 with AWS KMS -derived keys. Each identifier type gets its own purpose-specific key — so a customer_id hash can't be correlated with an account_id hash, even for the same person:
class CryptoEngine: """HMAC-SHA256 pseudonymization with KMS-derived keys."""
def __init__(self, kms_key_id: str): self.kms_key_id = kms_key_id self._purpose_keys: Dict[str, bytes] = {}
def _get_master_key(self) -> bytes: """Retrieve master key bytes from AWS KMS.""" import boto3 kms = boto3.client("kms") response = kms.generate_data_key( KeyId=self.kms_key_id, KeySpec="AES_256", ) return response["Plaintext"] # Use in-memory only; never log or store
def derive_purpose_key(self, purpose: str) -> bytes: """Derive purpose-specific key using PBKDF2 from KMS master.""" if purpose not in self._purpose_keys: master = self._get_master_key() self._purpose_keys[purpose] = hashlib.pbkdf2_hmac( 'sha256', master, purpose.encode(), 100000 ) return self._purpose_keys[purpose]
def pseudonymize(self, value: str, purpose: str) -> str: """Non-reversible HMAC-SHA256 hash.""" key = self.derive_purpose_key(purpose) return hmac.new( key, value.encode(), hashlib.sha256 ).hexdigest()[:32]
KMS key rotation: AWS KMS supports automatic annual key rotation (and on-demand rotation). When the master key rotates,generate_data_keyreturns bytes derived from the new key material — which means HMAC outputs for the same input values will differ from the previous night's run. If you rotate the key mid-training, re-pseudonymize your entire stored dataset before the next training run to avoid identity linkage breaks across shards. For most banks, the safest policy is to disable automatic rotation on this specific KMS key and perform rotation only at a scheduled model retraining boundary.
The PII scrubber
The PII scrubber detects and removes UK-specific patterns from free-text fields. This is critical for merchant descriptions and transaction narratives where customers' names, phone numbers, or postcodes can appear unexpectedly:
class PIIScrubber: """Detect and remove PII from free-text fields."""
UK_PATTERNS = { "nino": r"[A-Z]{2}\d{6}[A-Z]", "uk_phone": r"(?:0|\+44)\d{10,11}", "email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", "sort_code": r"\d{2}-\d{2}-\d{2}", "postcode": r"[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}", }
def scrub(self, text: str) -> str: cleaned = text for name, pattern in self.UK_PATTERNS.items(): cleaned = re.sub(pattern, f"[{name.upper()}]", cleaned) return cleaned
Deploy the Glue job with encryption
Create the Glue job with a
SecurityConfiguration that enables encryption at rest (S3 output) and in transit (CloudWatch logs). For a UK-regulated bank, this is a hard requirement under PRA and FCA guidance — unencrypted Glue job output or logs containing pseudonymized data would constitute a data handling breach.import boto3
glue_client = boto3.client("glue")
# Step 1: Create a security configuration (run once)glue_client.create_security_configuration( Name="bank-fm-glue-security", EncryptionConfiguration={ "S3Encryptions": [{ "S3EncryptionMode": "SSE-KMS", "KmsKeyArn": "arn:aws:kms:eu-west-2:111122223333:key/alias/bank-fm-kms", }], "CloudWatchEncryption": { "CloudWatchEncryptionMode": "SSE-KMS", "KmsKeyArn": "arn:aws:kms:eu-west-2:111122223333:key/alias/bank-fm-kms", }, "JobBookmarksEncryption": { "JobBookmarksEncryptionMode": "CSE-KMS", "KmsKeyArn": "arn:aws:kms:eu-west-2:111122223333:key/alias/bank-fm-kms", }, },)
# Step 2: Create the pseudonymization job with encryption and VPC isolationglue_client.create_job( Name="bank-fm-pseudonymization", Role="arn:aws:iam::111122223333:role/GluePseudonymizationRole", Command={ "Name": "glueetl", "ScriptLocation": "s3://bank-fm-scripts/pseudonymize.py", "PythonVersion": "3", }, DefaultArguments={ "--job-language": "python", "--enable-continuous-cloudwatch-log": "true", "--enable-metrics": "true", "--TempDir": "s3://bank-fm-temp/glue/", "--extra-py-files": "s3://bank-fm-scripts/deps.zip", "--KMS_KEY_ID": "alias/bank-fm-kms", "--INPUT_PATH": "s3://bank-fm-landing/raw-events/", "--OUTPUT_PATH": "s3://bank-fm-training/pseudonymized/", }, SecurityConfiguration="bank-fm-glue-security", # Encryption enabled GlueVersion="4.0", NumberOfWorkers=10, WorkerType="G.2X", # VPC isolation: Glue workers run in your private subnet Connections={ "Connections": ["bank-fm-glue-vpc-connection"] }, Tags={ "Project": "BankFoundationModel", "DataClassification": "Restricted", },)
IAM least-privilege: TheGluePseudonymizationRoleshould be scoped to the minimum required permissions:s3:GetObjecton the landing bucket,s3:PutObjecton the training bucket, andkms:GenerateDataKey+kms:Decryptonalias/bank-fm-kms. Do not uses3:*orkms:*wildcards. See the AWS Glue IAM guide for a reference policy.
A word of caution: Getting the pseudonymization pipeline right is harder than it looks. The biggest risk isn't the crypto — it's the edge cases. What happens when a customer's name appears in a merchant description ("John's Barber Shop")? What about joint accounts where one holder exercises their right to be forgotten? Build comprehensive test cases before you move to Step 3. I've seen teams discover PII leakage months into training because they didn't test free-text fields thoroughly.
Step 3: Train the BPE tokenizer
The tokenizer converts raw field values into token IDs. It combines special tokens, semantic keys, numerical buckets, categorical values, and BPE subwords into a unified vocabulary of approximately 34,000 tokens.
Why 34,000? It's a balance. Too small (under 10,000) and common merchant names fragment into unrecognizable subwords. Too large (over 100,000) and the embedding table dominates your model's parameter count without adding proportional value.
from dataclasses import dataclass, fieldfrom typing import Dict
@dataclassclass VocabularyConfig: """Vocabulary layout: ~34,000 tokens total."""
special_tokens: Dict[str, int] = field(default_factory=lambda: { "[PAD]": 0, "[MASK]": 1, "[UNK]": 2, "[USR]": 3, "[EVT]": 4, "[SEP]": 5, "[CLS]": 6, "[EOS]": 7, "[NUM_ZERO]": 8, "[EMPTY]": 9, })
bpe_vocab_size: int = 26000 min_frequency: int = 100
class BPETokenizerTrainer: """Train BPE on banking text corpus."""
def __init__(self, config: VocabularyConfig): self.config = config
def train(self, corpus: list) -> 'Tokenizer': from tokenizers import Tokenizer, models, trainers from tokenizers import pre_tokenizers, normalizers
tokenizer = Tokenizer(models.BPE(unk_token="[UNK]")) tokenizer.normalizer = normalizers.Sequence([ normalizers.NFKC(), normalizers.Lowercase(), ]) tokenizer.pre_tokenizer = pre_tokenizers.Sequence([ pre_tokenizers.Whitespace(), pre_tokenizers.Punctuation(), pre_tokenizers.Digits(individual_digits=True), ])
trainer = trainers.BpeTrainer( vocab_size=self.config.bpe_vocab_size, min_frequency=self.config.min_frequency, special_tokens=list(self.config.special_tokens.keys()), )
tokenizer.train_from_iterator(corpus, trainer=trainer) return tokenizer
Train this on your PII-scrubbed text corpus (merchant names, transaction descriptions, campaign names). Validate that the unknown token rate is below 3% and that common merchants tokenize to two or fewer subwords.
Validation checkpoint: Before proceeding, tokenize 10,000 random events and manually inspect 50. Are merchant names recognizable? Are amounts bucketed sensibly? Is the unknown rate acceptable? This 30-minute check can save you weeks of wasted GPU time in Part 3.
Step 4: Design GDPR-compliant storage with Apache Iceberg
Store your pre-tokenized training data in Apache Iceberg tables on Amazon S3. Iceberg provides row-level deletion for GDPR right-to-be-forgotten and time-travel for training reproducibility.
Why Iceberg specifically? Because it gives you three things no other table format offers simultaneously: row-level deletion (GDPR), time-travel (reproducibility for model validation), and schema evolution (you'll add new event sources over time). I've evaluated Delta Lake and Hudi for this use case — Iceberg's delete performance at scale is significantly better for the sparse deletion pattern that GDPR requests create.
Table definitions
-- User profiles: one row per user per evaluation pointCREATE TABLE bank_fm.user_profiles ( user_hash STRING COMMENT 'HMAC-SHA256 of customer_id', evaluation_point TIMESTAMP COMMENT 'Point-in-time snapshot', segment_token INT COMMENT 'Customer segment token ID', tenure_bucket INT COMMENT 'Relationship tenure bucket', product_count_bucket INT COMMENT 'Active products bucket', credit_band_token INT COMMENT 'Credit risk band token', total_event_count INT COMMENT 'Total events in history', tokenizer_version STRING COMMENT 'Tokenizer version used')USING icebergPARTITIONED BY (segment_token)TBLPROPERTIES ( 'write.format.default' = 'parquet', 'write.parquet.compression-codec' = 'zstd', 'write.delete.mode' = 'merge-on-read');
-- Event shards: pre-tokenized events-- event_timestamp has ±30s jitter applied during pseudonymization-- to prevent timing-based re-identification attacks (see Step 1 note).CREATE TABLE bank_fm.event_shards ( user_hash STRING COMMENT 'Links to user_profiles', event_timestamp TIMESTAMP COMMENT 'Event time (±30s jitter applied)', event_source STRING COMMENT 'transactions|digital|comms|product|risk', token_ids ARRAY<INT> COMMENT 'Complete tokenized event', hour_of_day INT COMMENT '0-23', day_of_week INT COMMENT '0-6 (Mon=0)', event_position INT COMMENT 'Chronological position')USING icebergPARTITIONED BY (event_source)TBLPROPERTIES ( 'write.format.default' = 'parquet', 'write.parquet.compression-codec' = 'zstd', 'write.delete.mode' = 'merge-on-read', 'write.sort-order' = 'user_hash ASC, event_position ASC');
Register tables in the AWS Glue Data Catalog
For these Iceberg tables to be accessible to Amazon SageMaker training jobs, Amazon Athena queries, and AWS Glue jobs in Part 3, they must be registered in the AWS Glue Data Catalog . Without this step, tools outside the Spark session that created the tables cannot discover them.
Register using the Boto3 Glue API immediately after table creation:
import boto3
glue_client = boto3.client("glue")
# Create the database namespace (run once)try: glue_client.create_database( DatabaseInput={ "Name": "bank_fm", "Description": "Bank foundation model training data", "Parameters": { "classification": "iceberg", }, } )except glue_client.exceptions.AlreadyExistsException: pass
# Register each Iceberg tablefor table_name, s3_location in [ ("user_profiles", "s3://bank-fm-training/iceberg/user_profiles/"), ("event_shards", "s3://bank-fm-training/iceberg/event_shards/"),]: try: glue_client.create_table( DatabaseName="bank_fm", TableInput={ "Name": table_name, "TableType": "EXTERNAL_TABLE", "Parameters": { "table_type": "ICEBERG", "metadata_location": f"{s3_location}metadata/", }, "StorageDescriptor": { "Location": s3_location, "InputFormat": "org.apache.iceberg.mr.hive.HiveIcebergInputFormat", "OutputFormat": "org.apache.iceberg.mr.hive.HiveIcebergOutputFormat", "SerdeInfo": { "SerializationLibrary": "org.apache.iceberg.mr.hive.HiveIcebergSerDe", }, }, }, ) print(f"✓ Registered bank_fm.{table_name} in Glue Data Catalog") except glue_client.exceptions.AlreadyExistsException: print(f" bank_fm.{table_name} already registered — skipping")
Once registered, SageMaker training jobs can read the tables via Amazon Athena or Spark, and Glue crawlers can keep the schema metadata up to date as you add new event types.
GDPR deletion operations
The
merge-on-read delete mode means GDPR deletions are fast (write a small delete file) without rewriting entire Parquet files:-- GDPR deletion: row-level delete without full rewriteDELETE FROM bank_fm.user_profiles WHERE user_hash = '{target_hash}';DELETE FROM bank_fm.event_shards WHERE user_hash = '{target_hash}';
-- Force physical removal during scheduled compactionALTER TABLE bank_fm.user_profiles EXECUTE rewrite_data_files;ALTER TABLE bank_fm.event_shards EXECUTE rewrite_data_files;
-- Reproducibility: query data at training timeSELECT * FROM bank_fm.event_shardsTIMESTAMP AS OF '2026-06-01 00:00:00'WHERE user_hash = '{target_hash}';
Schedule compaction weekly during off-peak hours using an Amazon EventBridge rule that triggers an AWS Glue job:
# Trigger compaction via Glue job on a weekly EventBridge scheduleevents_client = boto3.client("events")events_client.put_rule( Name="bank-fm-iceberg-compaction", ScheduleExpression="cron(0 2 ? * SUN *)", # 02:00 UTC every Sunday State="ENABLED", Description="Weekly Iceberg compaction — physically removes deleted records",)
Between compactions, deleted records are logically invisible but physically present — this is fine for GDPR compliance as long as S3 bucket policies prevent raw file access from outside the pipeline. Confirm this by checking that your S3 bucket has Block Public Access enabled and that IAM policies restrict
s3:GetObject on the training bucket to the GluePseudonymizationRole and SageMakerRole only.Compaction trigger on deletion volume: Weekly compaction is right for most cases, but if your bank processes a high volume of GDPR requests (for example, after a product closure), consider also triggering compaction when cumulative delete files across a partition exceed a threshold. An AWS Lambda function can monitor the Iceberg snapshot metadata and trigger the Glue compaction job whendelete_files_count > N.
Secure the S3 training bucket
All Iceberg tables and Glue outputs sit in S3. For a UK-regulated bank, apply these bucket-level controls before any data lands:
s3_client = boto3.client("s3")bucket_name = "bank-fm-training"
# 1. Block all public accesss3_client.put_public_access_block( Bucket=bucket_name, PublicAccessBlockConfiguration={ "BlockPublicAcls": True, "IgnorePublicAcls": True, "BlockPublicPolicy": True, "RestrictPublicBuckets": True, },)
# 2. Default encryption with KMSs3_client.put_bucket_encryption( Bucket=bucket_name, ServerSideEncryptionConfiguration={ "Rules": [{ "ApplyServerSideEncryptionByDefault": { "SSEAlgorithm": "aws:kms", "KMSMasterKeyID": "alias/bank-fm-kms", }, "BucketKeyEnabled": True, # Reduces KMS API call costs }] },)
# 3. Enable versioning (supports point-in-time recovery)s3_client.put_bucket_versioning( Bucket=bucket_name, VersioningConfiguration={"Status": "Enabled"},)
# 4. Enable server access logging (PRA audit trail)s3_client.put_bucket_logging( Bucket=bucket_name, BucketLoggingStatus={ "LoggingEnabled": { "TargetBucket": "bank-fm-access-logs", "TargetPrefix": "training-bucket/", } },)
print(f"✓ S3 bucket '{bucket_name}' secured: " "public access blocked, KMS encryption, versioning, access logging")
Validating your data foundations
Before moving to model training in Part 3, run these validation checks:
- Privacy audit — Sample 1,000 pseudonymized records and verify no PII leakage in any field
- Tokenizer coverage — Confirm unknown token rate is below 3% across all event sources
- Schema completeness — Verify all five event sources are represented in your Iceberg tables
- Deletion test — Execute a test GDPR deletion and confirm the record is invisible to queries
- Time-travel test — Query a historical snapshot and confirm reproducibility
- Glue catalog test — Run
aws glue get-table --database-name bank_fm --name event_shardsand confirm the table is discoverable
- Encryption test — Check a newly written S3 object and confirm
ServerSideEncryption: aws:kmsin its metadata
If all seven pass, your data foundations are solid. You're ready for model training.
Conclusion
In this post, I've shown you how to build the data foundations for a bank foundation model. The key insight is that data preparation isn't a preliminary step — it's a critical architectural decision that determines whether your model will be privacy-compliant, reproducible, and maintainable.
The four components work together as a system: the semantic key registry defines what data means, the pseudonymization pipeline protects it (with encryption enforced at the job level), the tokenizer converts it to model-ready format, and Iceberg stores it in a way that satisfies both your data scientists and your compliance team — and that's now discoverable to every downstream AWS service via the Glue Data Catalog.
In Part 3 , I'll show you how to consume these data foundations to train the three-encoder architecture, add graph integration for anti-money laundering (AML) via Amazon Neptune Analytics, implement LoRA fine-tuning, and deploy to production on Amazon SageMaker — with VPC isolation and Model Registry registration built in from the start.
Ready to start building? Try AWS Glue in the AWS Management Console to explore the ETL infrastructure for your pseudonymization pipeline.
Have questions about implementing the pseudonymization pipeline or tokenizer for your bank's data? Share your experience in the comments below — I'd love to hear what edge cases you've encountered.
References
- Ostroukhov, M., Mikhailov, R., Iashin, V., et al. (2026). "PRAGMA: Revolut Foundation Model." arXiv:2604.08649.
- Dwork, C. & Roth, A. (2014). "The Algorithmic Foundations of Differential Privacy." Foundations and Trends in Theoretical Computer Science.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article