AWS Builder Center
Training and deploying a bank foundation model on AWS (Part 3 of 3)

Training and deploying a bank foundation model on AWS (Part 3 of 3)

Train a three-encoder foundation model on AWS — with graph-enhanced AML, LoRA fine-tuning, SageMaker deployment, and production monitoring.

Data and Ai lead at AWS
Learning level: Advanced (400)
Author: Faris Haddad
Your data is pseudonymized, tokenized, and stored in GDPR-compliant Iceberg tables. Now the real work begins.
In this final post, I walk through the model architecture, training, graph integration, downstream adaptation, and production deployment — with complete code examples at every stage.

Prerequisites

In addition to the data foundations from  Part 2 , you need:
  • GPU compute: ml.p4d.24xlarge or ml.p5.48xlarge instances on Amazon SageMaker
  • Python 3.10+ with PyTorch 2.x
  • Familiarity with Transformer architectures and distributed training
  • The trained BPE tokenizer and populated Iceberg tables from Part 2
  • An Amazon Neptune Analytics graph (covered in Step 2)
  • A VPC with private subnets and security groups for SageMaker and Neptune (required for production)

Solution overview

This post covers five steps:
  1. Implement the three-encoder architecture in PyTorch
  1. Add graph integration for AML via Amazon Neptune Analytics
  1. Implement Low-Rank Adaptation (LoRA) for downstream fine-tuning
  1. Deploy to production on Amazon SageMaker
  1. Implement production monitoring
The following architecture diagram shows the complete model and deployment topology:

Figure 1: Three-encoder architecture with graph-enhanced AML, LoRA adaptation, and production deployment on Amazon SageMaker.

Step 1: Implement the three-encoder architecture

This is the core of the foundation model. If you completed Part 2, the hard infrastructure work is done — now we get to the interesting part.
The architecture follows PRAGMA's design: a Profile State Encoder captures who the customer is, an Event Encoder captures what happened, and a History Encoder learns how those two things interact over time.

Model configuration

import torch
import torch.nn as nn
import math
from dataclasses import dataclass

@dataclass
class BankFMConfig:
vocab_size: int = 34000
profile_d_model: int = 256
event_d_model: int = 256
history_d_model: int = 512
profile_n_heads: int = 4
event_n_heads: int = 4
history_n_heads: int = 8
profile_n_layers: int = 4
event_n_layers: int = 4
history_n_layers: int = 8
max_events: int = 512
max_tokens_per_event: int = 64
n_profile_attributes: int = 23
n_lifelong_events: int = 10
dropout: float = 0.1


Profile State Encoder

The Profile State Encoder processes static customer attributes (23 tokens) and lifelong events (10 milestone timestamps), using RoPE to encode temporal distance:
Note on RoPE: This applies RoPE as an additive offset for clarity. Canonical RoPE (Su et al., 2021) applies rotation matrices to Q/K projections inside each attention layer — replace  nn.TransformerEncoderLayer  with a custom layer for production.
class RotaryPositionalEncoding(nn.Module):
"""RoPE for temporal encoding (log-seconds since reference)."""

def __init__(self, d_model: int, max_len: int = 8192):
super().__init__()
inv_freq = 1.0 / (10000 ** (
torch.arange(0, d_model, 2).float() / d_model
))
self.register_buffer('inv_freq', inv_freq)

def forward(self, positions: torch.Tensor) -> torch.Tensor:
"""positions: [batch, seq_len] of log-second values."""
sinusoid = torch.einsum('bi,j->bij', positions, self.inv_freq)
return torch.cat([sinusoid.sin(), sinusoid.cos()], dim=-1)

class ProfileStateEncoder(nn.Module):
"""Encodes static customer attributes + lifelong events."""

def __init__(self, config: BankFMConfig):
super().__init__()
self.attribute_embed = nn.Embedding(config.vocab_size,
config.profile_d_model)
self.lifelong_rope = RotaryPositionalEncoding(config.profile_d_model)
self.transformer = nn.TransformerEncoder(
nn.TransformerEncoderLayer(
d_model=config.profile_d_model,
nhead=config.profile_n_heads,
dim_feedforward=config.profile_d_model * 4,
dropout=config.dropout,
batch_first=True,
),
num_layers=config.profile_n_layers,
)
self.output_proj = nn.Linear(config.profile_d_model,
config.history_d_model)

def forward(self, attribute_tokens, lifelong_days):
x = self.attribute_embed(attribute_tokens)
rope = self.lifelong_rope(lifelong_days.float().log1p())
x = x + rope[:, :x.size(1), :]
x = self.transformer(x)
return self.output_proj(x.mean(dim=1))


Event Encoder

The Event Encoder processes individual events with within-event attention, learning that co-occurring fields like  merchant_category=grocery  and  amount=bucket_3  carry joint meaning:
class EventEncoder(nn.Module):
"""Encodes individual banking events (within-event attention)."""

def __init__(self, config: BankFMConfig):
super().__init__()
self.token_embed = nn.Embedding(config.vocab_size,
config.event_d_model)
self.calendar_mlp = nn.Sequential(
nn.Linear(4, 64),
nn.GELU(),
nn.Linear(64, config.event_d_model),
)
self.transformer = nn.TransformerEncoder(
nn.TransformerEncoderLayer(
d_model=config.event_d_model,
nhead=config.event_n_heads,
dim_feedforward=config.event_d_model * 4,
dropout=config.dropout,
batch_first=True,
),
num_layers=config.event_n_layers,
)
self.output_proj = nn.Linear(config.event_d_model,
config.history_d_model)

def forward(self, token_ids, calendar_features, token_mask):
x = self.token_embed(token_ids)
cal = self.calendar_mlp(calendar_features)
x[:, 0, :] = x[:, 0, :] + cal
x = self.transformer(x, src_key_padding_mask=~token_mask)
return self.output_proj(x[:, 0, :]) # CLS token


History Encoder

The History Encoder fuses profile and event embeddings into a single representation. Cross-sequence context is what gives the model its predictive power:
class HistoryEncoder(nn.Module):
"""Fuses profile + event sequence into unified representation."""

def __init__(self, config: BankFMConfig):
super().__init__()
self.inter_event_rope = RotaryPositionalEncoding(
config.history_d_model
)
self.transformer = nn.TransformerEncoder(
nn.TransformerEncoderLayer(
d_model=config.history_d_model,
nhead=config.history_n_heads,
dim_feedforward=config.history_d_model * 4,
dropout=config.dropout,
batch_first=True,
),
num_layers=config.history_n_layers,
)

def forward(self, profile_embedding, event_embeddings,
log_seconds, event_mask):
batch_size = event_embeddings.size(0)
profile_token = profile_embedding.unsqueeze(1)
sequence = torch.cat([profile_token, event_embeddings], dim=1)

# Apply inter-event temporal encoding
rope = self.inter_event_rope(log_seconds)
sequence[:, 1:, :] = sequence[:, 1:, :] + rope

full_mask = torch.cat([
torch.ones(batch_size, 1, device=event_mask.device,
dtype=torch.bool),
event_mask
], dim=1)

output = self.transformer(sequence,
src_key_padding_mask=~full_mask)
return output[:, 0, :] # Profile position = user embedding


Complete foundation model

Combine the three encoders with an MLM head for pre-training:
class BankFoundationModel(nn.Module):
"""Complete foundation model combining all three encoders."""

def __init__(self, config: BankFMConfig):
super().__init__()
self.config = config
self.profile_encoder = ProfileStateEncoder(config)
self.event_encoder = EventEncoder(config)
self.history_encoder = HistoryEncoder(config)

# MLM head for pre-training
self.mlm_head = nn.Sequential(
nn.Linear(config.history_d_model, config.history_d_model),
nn.GELU(),
nn.LayerNorm(config.history_d_model),
nn.Linear(config.history_d_model, config.vocab_size),
)

def forward(self, attribute_tokens, lifelong_days,
event_token_ids, calendar_features,
token_mask, log_seconds, event_mask):
profile_emb = self.profile_encoder(attribute_tokens,
lifelong_days)

batch_size, n_events, seq_len = event_token_ids.shape
flat_tokens = event_token_ids.view(-1, seq_len)
flat_cal = calendar_features.view(-1, 4)
flat_mask = token_mask.view(-1, seq_len)

event_embs = self.event_encoder(flat_tokens, flat_cal,
flat_mask)
event_embs = event_embs.view(batch_size, n_events, -1)

user_embedding = self.history_encoder(
profile_emb, event_embs, log_seconds, event_mask
)
return user_embedding

Train with distributed data parallelism across multiple ml.p4d.24xlarge instances on SageMaker.
Training tip: Validate at the 10M parameter scale first — tokenizer bugs surface quickly at small scale.
Cost: Enable  SageMaker Managed Spot Training  ( use_spot_instances=True ,  max_wait=172800 ) for 60–70% compute savings. Checkpoint every 30 minutes to limit re-work on interruption.

Step 2: Add graph integration for AML

Your foundation model handles seven downstream tasks well. AML is the exception — fraud is about one person's behaviour, but money laundering is about a network: layering, structuring, cycling funds across accounts. A single-record encoder can't see that.
 Amazon Neptune Analytics  solves it. Pre-compute graph embeddings nightly and inject them via a gated fusion layer — the gate suppresses graph context for sparse networks and amplifies it for suspicious clusters.
class GraphContextInjector(nn.Module):
"""Inject Neptune graph embeddings into the foundation model."""

def __init__(self, graph_dim: int = 256, model_dim: int = 512):
super().__init__()
self.structural_proj = nn.Linear(graph_dim, model_dim)
self.temporal_flow_proj = nn.Linear(graph_dim, model_dim)
self.community_proj = nn.Linear(graph_dim, model_dim)
self.risk_prop_proj = nn.Linear(graph_dim, model_dim)

# Gated fusion
self.gate = nn.Sequential(
nn.Linear(model_dim * 2, model_dim),
nn.Sigmoid(),
)
self.layer_norm = nn.LayerNorm(model_dim)

def forward(self, user_embedding, graph_features):
"""
user_embedding: [batch, model_dim] from History Encoder
graph_features: dict with structural, temporal, community,
risk keys, each [batch, graph_dim]
"""
structural = self.structural_proj(graph_features['structural'])
temporal = self.temporal_flow_proj(graph_features['temporal'])
community = self.community_proj(graph_features['community'])
risk = self.risk_prop_proj(graph_features['risk'])

graph_combined = structural + temporal + community + risk

gate_input = torch.cat([user_embedding, graph_combined], dim=-1)
gate_value = self.gate(gate_input)

fused = user_embedding + gate_value * graph_combined
return self.layer_norm(fused)

Design decision: Gated fusion outperforms simple concatenation by 8–12% F1 on AML tasks because the gate suppresses noisy signals for sparsely-connected customers.
The  GraphContextInjector  expects four 256-d vectors per customer:  structural ,  temporal ,  community ,  risk . The following steps produce them.

Building the AML graph in Amazon Neptune Analytics

The overall flow runs nightly:
  1. Export transaction edges from your Iceberg table to S3
  1. Load into Neptune Analytics and run four graph algorithms
  1. Push scalar features to SageMaker Feature Store (InMemory tier)
  1. Retrieve at inference time (<5ms) and project to 256-d inside the model
Step 2a: Export the transaction graph to S3
Three edge types —  TRANSFERRED_TO ,  SHARES_DEVICE , and  SHARES_IP . The device/IP sharing edges surface accounts that look unrelated in the transaction graph but share physical infrastructure — a classic fraud ring indicator.
import boto3
import datetime
import pandas as pd
from pyiceberg.catalog import load_catalog
from pyiceberg.expressions import And, EqualTo, GreaterThanOrEqual

catalog = load_catalog("glue", **{"type": "glue"})
table = catalog.load_table("bank_fm.event_shards")

cutoff_ts = int(
(datetime.datetime.utcnow() - datetime.timedelta(days=90)).timestamp()
)

scan = table.scan(
row_filter=And(
EqualTo("event_source", "transactions"),
GreaterThanOrEqual("event_timestamp", cutoff_ts),
),
selected_fields=("user_hash", "txn_counterparty_hash",
"amount_bucket", "event_timestamp",
"device_hash", "ip_prefix"),
)
edges_df = scan.to_pandas()

# Transaction edges (directed: sender → receiver)
txn_edges = edges_df[["user_hash", "txn_counterparty_hash",
"amount_bucket", "event_timestamp"]].rename(
columns={"user_hash": "~from",
"txn_counterparty_hash": "~to",
"amount_bucket": "amount_bucket",
"event_timestamp": "timestamp"}
)
txn_edges["~label"] = "TRANSFERRED_TO"

# Device-sharing edges — cross-join on shared device_hash
device_edges = (
edges_df[["user_hash", "device_hash"]].dropna()
.merge(edges_df[["user_hash", "device_hash"]].dropna(),
on="device_hash", suffixes=("_a", "_b"))
.query("user_hash_a != user_hash_b")
.rename(columns={"user_hash_a": "~from", "user_hash_b": "~to"})
.drop_duplicates()
)
device_edges["~label"] = "SHARES_DEVICE"

bucket = "bank-fm-neptune-staging"
s3 = boto3.client("s3")
txn_edges.to_csv("/tmp/txn_edges.csv", index=False)
device_edges.to_csv("/tmp/device_edges.csv", index=False)
s3.upload_file("/tmp/txn_edges.csv", bucket, "aml-graph/txn_edges.csv")
s3.upload_file("/tmp/device_edges.csv", bucket, "aml-graph/device_edges.csv")

print(f"Exported {len(txn_edges):,} transaction edges, "
f"{len(device_edges):,} device-sharing edges")

Step 2b: Load into Neptune Analytics and run graph algorithms
Neptune Analytics manages compute automatically — no instance sizing, no cluster maintenance. You load data from S3, run algorithms, and tear down the in-memory graph when done (see the cost note at the end of this section).
neptune_analytics = boto3.client("neptune-graph")

graph = neptune_analytics.create_graph(
graphName="bank-aml-graph",
provisionedMemory=16,
publicConnectivity=False, # VPC-only
replicaCount=1,
tags={"Purpose": "AML-embeddings", "Environment": "production"},
)
graph_id = graph["id"]

import time
while neptune_analytics.get_graph(graphIdentifier=graph_id)["status"] != "AVAILABLE":
time.sleep(30)

# Load from S3
neptune_analytics.start_import_task(
graphIdentifier=graph_id,
source=f"s3://{bucket}/aml-graph/",
format="CSV",
roleArn="arn:aws:iam::111122223333:role/NeptuneAnalyticsS3Role",
)

Neptune Analytics exposes its algorithms as openCypher stored procedures. Run four to produce the signals that feed the  GraphContextInjector :
Algorithm
Neptune procedure
AML signal captured
Degree centrality
neptune.algo.degree
Raw connectivity: high in+out degree = potential layering node
PageRank
neptune.algo.pageRank
Influence: receiving from high-rank nodes is a strong prior
Louvain community detection
neptune.algo.louvain
Dense clusters containing SAR-flagged accounts
Strongly Connected Components
neptune.algo.scc
Directed cycles: A→B→C→A is classic structuring
def run_neptune_query(graph_id: str, query: str) -> list:
import json
resp = neptune_analytics.execute_query(
graphIdentifier=graph_id,
queryString=query,
language="OPEN_CYPHER",
)
return json.loads(resp["payload"].read())["results"]

degree_results = run_neptune_query(graph_id, """
CALL neptune.algo.degree({
nodeLabels: ['Customer'],
relationshipTypes: ['TRANSFERRED_TO'],
orientation: 'UNDIRECTED',
writeProperty: 'degree_centrality'
})
YIELD node, score
RETURN node.user_hash AS user_hash, score AS degree_centrality
""")

pagerank_results = run_neptune_query(graph_id, """
CALL neptune.algo.pageRank({
nodeLabels: ['Customer'],
relationshipTypes: ['TRANSFERRED_TO'],
dampingFactor: 0.85,
maxIterations: 20,
writeProperty: 'pagerank'
})
YIELD node, score
RETURN node.user_hash AS user_hash, score AS pagerank
""")

# Louvain: preferred over Label Propagation for AML because it produces
# stable community assignments across runs — important for audit trails.
louvain_results = run_neptune_query(graph_id, """
CALL neptune.algo.louvain({
nodeLabels: ['Customer'],
relationshipTypes: ['TRANSFERRED_TO', 'SHARES_DEVICE'],
maxLevels: 10,
maxIterations: 10,
writeProperty: 'community_id'
})
YIELD node, communityId
RETURN node.user_hash AS user_hash, communityId AS community_id
""")

scc_results = run_neptune_query(graph_id, """
CALL neptune.algo.scc({
nodeLabels: ['Customer'],
relationshipTypes: ['TRANSFERRED_TO'],
writeProperty: 'scc_component'
})
YIELD node, componentId, componentSize
RETURN node.user_hash AS user_hash,
componentId AS scc_component,
componentSize AS scc_size
""")

Step 2c: Build features and push to SageMaker Feature Store
Merge the algorithm outputs, normalise via percentile ranking (robust to the extreme outlier values you see with money mules), compute a community SAR contamination rate, and push to the Feature Store InMemory tier.
import numpy as np
from sklearn.preprocessing import QuantileTransformer
from datetime import datetime, timezone

# Merge
graph_features = (
pd.DataFrame(degree_results)
.merge(pd.DataFrame(pagerank_results), on="user_hash", how="outer")
.merge(pd.DataFrame(louvain_results), on="user_hash", how="outer")
.merge(pd.DataFrame(scc_results), on="user_hash", how="outer")
.fillna(0)
)

# Percentile-normalise continuous features
qt = QuantileTransformer(n_quantiles=1000, output_distribution="normal")
graph_features[["degree_centrality", "pagerank"]] = qt.fit_transform(
graph_features[["degree_centrality", "pagerank"]]
)

# Community SAR contamination: fraction of community members with SAR flags
sar_scan = catalog.load_table("bank_fm.event_shards").scan(
row_filter=EqualTo("event_source", "risk_events"),
selected_fields=("user_hash", "risk_flag"),
)
sar_hashes = set(
sar_scan.to_pandas()
.query("risk_flag == 'SAR'")["user_hash"]
)
community_sar = (
graph_features
.assign(is_sar=graph_features["user_hash"].isin(sar_hashes).astype(int))
.groupby("community_id")["is_sar"].mean()
.rename("community_sar_rate").reset_index()
)
graph_features = graph_features.merge(community_sar, on="community_id", how="left")
graph_features["cycle_risk"] = np.where(
graph_features["scc_size"] > 3,
np.log1p(graph_features["scc_size"]), 0.0
)

# Push to Feature Store (InMemory tier — sub-millisecond reads for fraud SLAs)
import boto3
from concurrent.futures import ThreadPoolExecutor, as_completed

sm_client = boto3.client("sagemaker")
featurestore_rt = boto3.client("sagemaker-featurestore-runtime")
FEATURE_GROUP_NAME = "bank-fm-aml-graph-features"

# Create feature group once (idempotent guard below)
try:
sm_client.create_feature_group(
FeatureGroupName=FEATURE_GROUP_NAME,
RecordIdentifierFeatureName="user_hash",
EventTimeFeatureName="feature_timestamp",
FeatureDefinitions=[
{"FeatureName": "user_hash", "FeatureType": "String"},
{"FeatureName": "feature_timestamp", "FeatureType": "String"},
{"FeatureName": "degree_centrality", "FeatureType": "Fractional"},
{"FeatureName": "pagerank", "FeatureType": "Fractional"},
{"FeatureName": "community_id", "FeatureType": "Integral"},
{"FeatureName": "community_sar_rate", "FeatureType": "Fractional"},
{"FeatureName": "scc_component", "FeatureType": "Integral"},
{"FeatureName": "scc_size", "FeatureType": "Integral"},
{"FeatureName": "cycle_risk", "FeatureType": "Fractional"},
],
OnlineStoreConfig={
"EnableOnlineStore": True,
"StorageType": "InMemory",
"SecurityConfig": {"KmsKeyId": "alias/bank-fm-kms"},
},
OfflineStoreConfig={
"S3StorageConfig": {
"S3Uri": "s3://bank-fm-features/aml-graph/",
"KmsKeyId": "alias/bank-fm-kms",
},
"DisableGlueTableCreation": False,
"TableFormat": "Iceberg",
},
RoleArn="arn:aws:iam::111122223333:role/SageMakerFeatureStoreRole",
)
except sm_client.exceptions.ResourceInUse:
pass

event_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
BATCH_SIZE = 500

def push_batch(batch_df):
for _, row in batch_df.iterrows():
featurestore_rt.put_record(
FeatureGroupName=FEATURE_GROUP_NAME,
Record=[
{"FeatureName": "user_hash", "ValueAsString": str(row["user_hash"])},
{"FeatureName": "feature_timestamp", "ValueAsString": event_time},
{"FeatureName": "degree_centrality", "ValueAsString": str(row["degree_centrality"])},
{"FeatureName": "pagerank", "ValueAsString": str(row["pagerank"])},
{"FeatureName": "community_id", "ValueAsString": str(int(row["community_id"]))},
{"FeatureName": "community_sar_rate", "ValueAsString": str(row["community_sar_rate"])},
{"FeatureName": "scc_component", "ValueAsString": str(int(row["scc_component"]))},
{"FeatureName": "scc_size", "ValueAsString": str(int(row["scc_size"]))},
{"FeatureName": "cycle_risk", "ValueAsString": str(row["cycle_risk"])},
],
TargetStores=["OnlineStore"],
)

batches = [graph_features.iloc[i:i+BATCH_SIZE]
for i in range(0, len(graph_features), BATCH_SIZE)]
with ThreadPoolExecutor(max_workers=16) as ex:
list(as_completed([ex.submit(push_batch, b) for b in batches]))
print(f"✓ Pushed {len(graph_features):,} AML graph records to Feature Store")

Step 2d: Retrieve graph features at inference time
Add this to your  inference.py . New or inactive customers receive zero vectors — the gate in  GraphContextInjector  suppresses the signal naturally.
import torch
import torch.nn as nn
import boto3
from typing import List

featurestore_rt = boto3.client("sagemaker-featurestore-runtime",
region_name="eu-west-2")
FEATURE_GROUP_NAME = "bank-fm-aml-graph-features"
GRAPH_FEATURE_NAMES = ["degree_centrality", "pagerank", "community_id",
"community_sar_rate", "scc_component", "scc_size",
"cycle_risk"]

class GraphFeatureProjector(nn.Module):
"""Projects raw Neptune scalar features into 256-d embedding vectors."""

def __init__(self, graph_dim: int = 256):
super().__init__()
self.structural_proj = nn.Sequential(
nn.Linear(2, 64), nn.GELU(), nn.Linear(64, graph_dim))
self.temporal_proj = nn.Sequential(
nn.Linear(1, 64), nn.GELU(), nn.Linear(64, graph_dim))
self.community_proj = nn.Sequential(
nn.Linear(2, 64), nn.GELU(), nn.Linear(64, graph_dim))
self.risk_proj = nn.Sequential(
nn.Linear(2, 64), nn.GELU(), nn.Linear(64, graph_dim))
self.community_embed = nn.Embedding(100_000, 2)
self.scc_embed = nn.Embedding(100_000, 2)

def forward(self, raw: dict) -> dict:
structural = self.structural_proj(
torch.stack([raw["degree_centrality"], raw["pagerank"]], dim=-1))
temporal = self.temporal_proj(raw["cycle_risk"].unsqueeze(-1))
community = self.community_proj(
self.community_embed(raw["community_id"].long().clamp(0, 99_999)))
risk = self.risk_proj(torch.cat([
self.scc_embed(raw["scc_component"].long().clamp(0, 99_999)),
raw["scc_size"].unsqueeze(-1).float().log1p(),
], dim=-1))
return {"structural": structural, "temporal": temporal,
"community": community, "risk": risk}

def fetch_graph_features(user_hashes: List[str],
device: str = "cpu") -> dict:
"""Retrieve graph features; zero-vector fallback for new/inactive users."""
defaults = {k: 0.0 for k in GRAPH_FEATURE_NAMES}
raw = {k: [] for k in GRAPH_FEATURE_NAMES}
for user_hash in user_hashes:
try:
resp = featurestore_rt.get_record(
FeatureGroupName=FEATURE_GROUP_NAME,
RecordIdentifierValueAsString=user_hash,
FeatureNames=GRAPH_FEATURE_NAMES,
)
record = {r["FeatureName"]: float(r["ValueAsString"])
for r in resp.get("Record", [])}
for k in GRAPH_FEATURE_NAMES:
raw[k].append(record.get(k, defaults[k]))
except featurestore_rt.exceptions.ResourceNotFound:
for k in GRAPH_FEATURE_NAMES:
raw[k].append(defaults[k])
return {k: torch.tensor(v, dtype=torch.float32, device=device)
for k, v in raw.items()}

Step 2e: Schedule the nightly graph refresh
Schedule via  Amazon EventBridge  at 01:00 UTC:
events_client = boto3.client("events")
events_client.put_rule(
Name="bank-fm-aml-graph-refresh",
ScheduleExpression="cron(0 1 * * ? *)",
State="ENABLED",
Description="Nightly AML graph embedding refresh via Neptune Analytics",
)
events_client.put_targets(
Rule="bank-fm-aml-graph-refresh",
Targets=[{
"Id": "GlueAMLGraphJob",
"Arn": "arn:aws:glue:eu-west-2:111122223333:job/bank-fm-aml-graph-refresh",
"RoleArn": "arn:aws:iam::111122223333:role/EventBridgeGlueRole",
}],
)

Cost: Delete the in-memory graph after each nightly run — edge data persists in S3. The full pipeline completes in 20–40 minutes for graphs up to 50M nodes.

Step 3: Implement LoRA for downstream fine-tuning

Freeze the backbone and train LoRA adapter layers for each task — 2–4% of parameters, equivalent performance, one backbone to govern.
class LoRALayer(nn.Module):
"""Low-rank adaptation: y = Wx + (BA)x * scaling."""

def __init__(self, in_features: int, out_features: int,
rank: int = 8, alpha: float = 16.0):
super().__init__()
self.scaling = alpha / rank
self.lora_a = nn.Linear(in_features, rank, bias=False)
self.lora_b = nn.Linear(rank, out_features, bias=False)

nn.init.kaiming_uniform_(self.lora_a.weight, a=5**0.5)
nn.init.zeros_(self.lora_b.weight)

def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.lora_b(self.lora_a(x)) * self.scaling

class LoRAWrapper(nn.Module):
"""Wrap a frozen linear layer with trainable LoRA."""

def __init__(self, original: nn.Linear, rank: int = 8,
alpha: float = 16.0):
super().__init__()
self.original = original
self.lora = LoRALayer(original.in_features,
original.out_features, rank, alpha)
for p in self.original.parameters():
p.requires_grad = False

def forward(self, x):
return self.original(x) + self.lora(x)

def apply_lora_to_model(model: BankFoundationModel,
rank: int = 8) -> BankFoundationModel:
"""Inject LoRA into all attention Q, K, V projections."""
for name, module in model.named_modules():
if isinstance(module, nn.Linear) and any(
t in name for t in ['q_proj', 'k_proj', 'v_proj']
):
parent_name, child_name = name.rsplit('.', 1)
parent = dict(model.named_modules())[parent_name]
setattr(parent, child_name,
LoRAWrapper(module, rank=rank))
return model

Each task converges in 1–3 days on ml.g5.xlarge versus 14 days for full backbone retraining.

Step 4: Deploy to production on Amazon SageMaker

4a: Register the model in SageMaker Model Registry

Mandatory for PRA SS1/23 Tier 1 models — every version needs auditable metadata and a human approval gate.
import boto3

sm_client = boto3.client("sagemaker")

# Create model package group once
try:
sm_client.create_model_package_group(
ModelPackageGroupName="bank-fm-fraud",
ModelPackageGroupDescription="Bank foundation model — fraud detection task",
Tags=[{"Key": "RegulatoryTier", "Value": "SS1-23-Tier1"}],
)
except sm_client.exceptions.ResourceInUse:
pass

# Register model version with full metadata
response = sm_client.create_model_package(
ModelPackageGroupName="bank-fm-fraud",
ModelPackageDescription="LoRA fine-tuned fraud adapter, training run 2026-07-13",
InferenceSpecification={
"Containers": [{
"Image": "763104351884.dkr.ecr.eu-west-2.amazonaws.com/"
"pytorch-inference:2.1.0-gpu-py310-cu118-ubuntu20.04-sagemaker",
"ModelDataUrl": "s3://bank-fm-models/fraud/model.tar.gz",
}],
"SupportedContentTypes": ["application/json"],
"SupportedResponseMIMETypes": ["application/json"],
},
ModelMetrics={
"ModelQuality": {
"Statistics": {
"ContentType": "application/json",
"S3Uri": "s3://bank-fm-models/fraud/eval-metrics.json",
}
}
},
CustomerMetadataProperties={
"TrainingDataVersion": "2026-07-13",
"BaseModelVersion": "bank-fm-backbone-v1.2",
"LoRArank": "8",
"DPEpsilon": "4.0",
},
ModelApprovalStatus="PendingManualApproval", # Requires human sign-off
)
model_package_arn = response["ModelPackageArn"]
print(f"Registered: {model_package_arn}")

Once approved ( ModelApprovalStatus: Approved ), deploy to a SageMaker endpoint.

4b: Deploy with VPC isolation

Endpoints must run inside a VPC with private subnets for a regulated bank — specify  VpcConfig  on every  deploy()  call:
import sagemaker

# Pinned URI — more reproducible than framework_version strings.
# Current DLCs: https://github.com/aws/deep-learning-containers/blob/master/available_images.md
INFERENCE_IMAGE = (
"763104351884.dkr.ecr.eu-west-2.amazonaws.com/"
"pytorch-inference:2.1.0-gpu-py310-cu118-ubuntu20.04-sagemaker"
)

from sagemaker.pytorch import PyTorchModel

fraud_model = PyTorchModel(
model_data="s3://bank-fm-models/fraud/model.tar.gz",
role="arn:aws:iam::111122223333:role/SageMakerRole",
image_uri=INFERENCE_IMAGE,
entry_point="inference.py",
)

fraud_predictor = fraud_model.deploy(
initial_instance_count=3,
instance_type="ml.g5.xlarge",
endpoint_name="bank-fm-fraud-realtime",
vpc_config={
"Subnets": ["subnet-aaa111", "subnet-bbb222"],
"SecurityGroupIds": ["sg-ccc333"],
},
# INT8 quantisation via torch.quantization.quantize_dynamic() in inference.py
)

# Batch transform for portfolio credit scoring (no real-time SLA)
transformer = fraud_model.transformer(
instance_count=8,
instance_type="ml.g5.12xlarge",
output_path="s3://bank-fm-outputs/credit-scoring/",
max_payload=100,
)
transformer.transform(
data="s3://bank-fm-inputs/credit-scoring/",
content_type="application/json",
)

Configure auto-scaling for payday and holiday traffic spikes:
client = boto3.client("application-autoscaling")

client.register_scalable_target(
ServiceNamespace="sagemaker",
ResourceId="endpoint/bank-fm-fraud-realtime/variant/AllTraffic",
ScalableDimension="sagemaker:variant:DesiredInstanceCount",
MinCapacity=3,
MaxCapacity=12,
)

client.put_scaling_policy(
PolicyName="FraudEndpointScaling",
ServiceNamespace="sagemaker",
ResourceId="endpoint/bank-fm-fraud-realtime/variant/AllTraffic",
ScalableDimension="sagemaker:variant:DesiredInstanceCount",
PolicyType="TargetTrackingScaling",
TargetTrackingScalingPolicyConfiguration={
"TargetValue": 1000,
"PredefinedMetricSpecification": {
"PredefinedMetricType":
"SageMakerVariantInvocationsPerInstance"
},
"ScaleInCooldown": 300,
"ScaleOutCooldown": 60,
},
)


4c: Wire the full pipeline with SageMaker Pipelines

For a Tier 1 model under PRA SS1/23, an auditable, replayable pipeline is mandatory.  SageMaker Pipelines  provides a DAG that logs every step and integrates with the Model Registry approval gate:
ProcessingStep (data validation)
→ TrainingStep (pre-training on p4d/p5)
→ ProcessingStep (evaluation)
→ RegisterModel (Model Registry — pending approval)
→ [Manual approval gate]
→ DeployStep (SageMaker endpoint)

See the  SageMaker Pipelines developer guide  for the full implementation.

Step 5: Implement production monitoring

Monitor for data drift, performance degradation, and fairness violations using  Amazon SageMaker Model Monitor .
import numpy as np

class DriftDetector:
"""Population Stability Index (PSI) for data drift detection."""

@staticmethod
def compute_psi(expected: np.ndarray, current: np.ndarray,
bins: int = 10) -> float:
"""
PSI < 0.1: No meaningful drift
PSI 0.1–0.25: Minor drift — investigate
PSI > 0.25: Significant drift — alert and consider retraining
"""
bin_edges = np.linspace(
min(expected.min(), current.min()),
max(expected.max(), current.max()),
bins + 1
)
exp_pct = np.histogram(expected, bin_edges)[0] / len(expected)
cur_pct = np.histogram(current, bin_edges)[0] / len(current)

exp_pct = np.where(exp_pct == 0, 1e-10, exp_pct)
cur_pct = np.where(cur_pct == 0, 1e-10, cur_pct)

return float(np.sum(
(cur_pct - exp_pct) * np.log(cur_pct / exp_pct)
))

class FairnessMonitor:
"""Monitor fairness across protected characteristics."""

@staticmethod
def demographic_parity(y_pred: np.ndarray,
protected: np.ndarray,
threshold: float = 0.5) -> float:
"""Returns |P(Y=1|A=0) - P(Y=1|A=1)|. Target: < 0.05."""
pred_binary = (y_pred >= threshold).astype(int)
rate_0 = pred_binary[protected == 0].mean()
rate_1 = pred_binary[protected == 1].mean()
return abs(rate_0 - rate_1)

Alert when PSI > 0.25 or fairness metrics breach. Build holiday seasonality into your baseline — it's the most common drift trigger.

Cleanup

To avoid ongoing charges, delete the following resources when you're done experimenting:
  1. Delete SageMaker endpoints:  fraud_predictor.delete_endpoint() 
  1. Delete Neptune Analytics graph:  neptune_analytics.delete_graph(graphIdentifier=graph_id, skipSnapshot=True) 
  1. Delete S3 training data:  aws s3 rm s3://bank-fm-training/ --recursive 
  1. Delete Iceberg tables:  DROP TABLE bank_fm.user_profiles; DROP TABLE bank_fm.event_shards; 
  1. Delete Glue jobs and crawlers
  1. Deregister SageMaker scalable targets

Conclusion

Across all three posts: a complete blueprint for a bank foundation model on AWS.
  • Tokenize heterogeneous banking data with a key-value-time scheme (Part 2)
  • Pseudonymize with HMAC-SHA256, KMS-derived keys, and Glue SSE-KMS encryption (Part 2)
  • Store in Apache Iceberg for GDPR row-level deletion and training reproducibility (Part 2)
  • Train a three-encoder architecture with masked language modeling on SageMaker (Part 3)
  • Extend with Neptune Analytics graph embeddings for network-level AML detection (Part 3)
  • Fine-tune with LoRA — 8+ tasks, 2–4% parameters, one governed backbone (Part 3)
  • Register every version in SageMaker Model Registry before deployment — PRA SS1/23 (Part 3)
  • Deploy inside a VPC with private subnets — mandatory for regulated banks (Part 3)
  • Orchestrate with SageMaker Pipelines for an auditable, replayable MLOps workflow (Part 3)
  • Monitor continuously for drift and fairness with SageMaker Model Monitor (Part 3)
Start small: one downstream task, measure the lift, then scale.
Share your experience in the comments.



References

  1. Ostroukhov et al. (2026). "PRAGMA: Revolut Foundation Model." arXiv:2604.08849.
  1. Hu et al. (2022). "LoRA: Low-Rank Adaptation of Large Language Models." ICLR.
  1. Vaswani et al. (2017). "Attention Is All You Need." NeurIPS.
  1. Devlin et al. (2019). "BERT." NAACL-HLT.
  1. Su et al. (2021). "RoFormer: Enhanced Transformer with Rotary Position Embedding." arXiv:2104.09864.
  1. Dwork & Roth (2014). "The Algorithmic Foundations of Differential Privacy." FnTTCS.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article