AWS Builder Center
Detecting fraud in real time with Temporal Graph Networks on AWS - Part 2

Detecting fraud in real time with Temporal Graph Networks on AWS - Part 2

Upgrade your TGN with MiNT cross-network pre-training, RF ensemble scoring, and automated drift detection to generalise across payment domains.

Data and Ai lead at AWS
This is Part 2 of a two-part series. If you haven't read    Part 1  yet, start there — it covers the TGN architecture, training loop, and the foundational AWS deployment pattern.
Learning level: 300 — Advanced technical Post type: Technical walkthrough AWS services: Amazon SageMaker, Amazon Neptune, Amazon ElastiCache for Valkey, Amazon Kinesis Data Streams, AWS Lambda, Amazon S3, AWS Glue, Amazon CloudWatch



Introduction

In  Part 1 , I showed you how to build a single Temporal Graph Network (TGN) fraud detector, train it on a synthetic transaction graph, and deploy it on AWS. That foundation works well — but it has a fundamental limitation: the model is trained on one network. Deploy it to a new payment domain, a new geography, or a new product line, and AUC-PR drops sharply because the model has no prior knowledge to draw on.
Real fraud patterns don't care about organizational boundaries. Card testing looks the same whether it happens on a bank's card-present network or a mobile money platform. Account takeover follows the same temporal signature in retail banking and digital wallets. Money laundering uses similar layering strategies across jurisdictions. There's a cross-network generalization problem hiding in plain sight — and MiNT (Multi-Network Training) solves it.
In this post, you'll learn how to:
  • Train a single TGN backbone across multiple transaction networks simultaneously using MiNT
  • Evaluate zero-shot transfer to completely unseen networks
  • Fine-tune to a new domain with minimal labeled data using frozen backbone transfer
  • Upgrade the scoring layer with an ensemble that combines TGN embeddings with a Random Forest head
  • Detect concept drift automatically so the system retrains before AUC degrades in production
All of these techniques build directly on the  tgn_learn  library and the AWS architecture introduced in Part 1.



Prerequisites

  • Part 1 of this series completed — you have a trained  TGNFraudDetector  and the foundational AWS infrastructure deployed



The generalization problem in fraud detection

Before diving into MiNT, it's worth being precise about the problem. When a TGN trained on Network A is evaluated on Network B, three things go wrong:
Node vocabulary mismatch. Node IDs in Network A mean nothing in Network B. The memory vectors accumulated during training are tied to specific account IDs that don't exist in the new network.
Distribution shift. Transaction amounts, velocity patterns, and fraud rates vary by market. A model that learned "transactions over $5,000 are suspicious" on a US card network will misfire on a UK sterling network where the fraud threshold is different.
Structural differences. The graph topology — how tightly connected the merchant network is, whether accounts cluster by geography — differs across networks. Structural patterns that correlate with fraud in one network may be normal in another.
MiNT addresses all three. It trains a shared backbone that learns fraud-invariant representations — patterns that hold across networks regardless of specific node identities, amount distributions, or structural differences. The scoring heads, which are where network-specific decision boundaries live, are then fine-tuned per deployment target.



MiNT: Multi-Network Training

MiNT trains a single TGN model across multiple networks simultaneously using gradient accumulation. In each training epoch, the model makes a full pass over each training network, accumulates gradients, and takes a single optimizer step. The result is a backbone that has seen fraud patterns from many different transaction contexts.

Generating multiple training networks

The first step is generating a diverse set of training networks. You want variation in size, fraud rate, fraud patterns, and transaction type:
from tgn_learn.model import TGNConfig
from tgn_learn.training.mint import MiNTConfig, MiNTTrainer

mint_config = MiNTConfig(
num_train_networks=5, # train on 5 distinct networks
num_test_networks=2, # evaluate zero-shot on 2 unseen networks
epochs=8,
batch_size=200,
fine_tune_epochs=5,
transactions_per_network=1500,
accounts_per_network=100,
fraud_rate=0.05,
seed=42,
)

model_config = TGNConfig(memory_dim=32, embedding_dim=32, time_dim=16)

Internally,  MiNTTrainer  alternates between  BankSimGenerator  and  PaySimGenerator  for each network index, using a different random seed each time. This produces training networks that vary in fraud pattern mix, account structure, and temporal dynamics — exactly the diversity the backbone needs to learn generalizable representations.

The gradient accumulation training loop

The core of MiNT is how gradients from multiple networks are combined. Here's the inner training loop from  mint.py :
for epoch in range(1, config.epochs + 1):
epoch_losses = []

for name, graph in train_networks.items():
# Each network gets its own forward pass + backward pass
loss = self._train_on_network(model, optimizer, neg_sampler, graph)
epoch_losses.append(loss)

avg_loss = np.mean(epoch_losses)

The key implementation detail is that  optimizer.zero_grad()  is called inside  _train_on_network , which means each network's gradients are computed and applied independently. An alternative formulation — accumulating gradients across all networks before a single optimizer step — is equivalent when batch sizes are consistent and tends to produce smoother convergence.
For each network pass, the model resets its memory ( model.reset_memory() ) so that accumulated memory states from Network A don't contaminate the forward pass on Network B. This is critical: memory is node-specific, and node IDs don't share semantics across networks.

Zero-shot transfer

After training, the model is evaluated on networks it has never seen:
trainer = MiNTTrainer(mint_config, model_config)
result = trainer.run(verbose=True)

print(f"\n{'Network':<25} {'Zero-Shot':>12} {'Fine-Tuned':>12} {'From Scratch':>12}")
for name in result.zero_shot_metrics:
zs = result.zero_shot_metrics[name].auc_pr
ft = result.fine_tuned_metrics.get(name).auc_pr
sn = result.single_network_metrics.get(name).auc_pr
print(f"{name:<25} {zs:>12.4f} {ft:>12.4f} {sn:>12.4f}")

A typical result looks like this:
Network Zero-Shot Fine-Tuned From Scratch
──────────────────────────────────────────────────────────────────
test_0_banksim 0.4821 0.6934 0.5103
test_1_paysim 0.5217 0.7245 0.4891

Three observations from this output:
  1. Zero-shot AUC-PR > random baseline (random ≈ fraud rate = 0.05 → AUC-PR ≈ 0.05–0.25). The backbone already knows something useful about fraud even on unseen networks.
  1. Fine-tuned > from scratch. This is the signal that transfer learning is working: starting from MiNT weights and adapting only the scoring heads outperforms training a fresh model from scratch on the same target data.
  1. Fine-tuned > zero-shot. The backbone captures generalizable structure; fine-tuning adapts the decision boundary to the specific fraud rate, amount distribution, and patterns of the target network.

Fine-tuning: frozen backbone transfer

The fine-tuning step is architecturally important. When adapting to a new network, the backbone (memory module and graph attention embedding) is frozen — only the scoring heads ( LinkPredictor  and  NodeClassifier ) are updated:
def _fine_tune(self, base_model, target_graph):
import copy
model = copy.deepcopy(base_model)

# Freeze the backbone — memory and GNN weights don't change
for param in model.memory.parameters():
param.requires_grad = False
for param in model.gnn.parameters():
param.requires_grad = False

# Only the scoring heads adapt to the new network
head_params = (
list(model.link_pred.parameters()) +
list(model.node_pred.parameters())
)
optimizer = Adam(head_params, lr=config.fine_tune_lr) # lower LR: 1e-4

# Train for just 5 epochs on the target network's training split
for epoch in range(config.fine_tune_epochs):
self._train_on_network(model, optimizer, neg_sampler, target_graph)

return model

Freezing the backbone serves two purposes. First, it prevents catastrophic forgetting — the phenomenon where fine-tuning on a small dataset overwrites the generalizable features learned during pre-training. Second, it dramatically reduces the labeled data requirement: you only need enough labeled transactions to fit two small MLP heads rather than the full model.
In practice, this means you can deploy to a new payment network with as few as 500–1,000 labeled fraud cases — a realistic number to gather in the first weeks of operation — compared to the 10,000+ typically required to train a TGN from scratch.



Upgrading the scoring layer: TGN + Random Forest ensemble

Once you have a well-trained TGN backbone producing high-quality embeddings, there's a straightforward upgrade available for the final scoring step: replace the MLP  NodeClassifier  head with a Random Forest at inference time.
This is the NID-TGN pattern (SPACE 2024). The TGN handles the hard part — encoding temporal and structural context into a dense embedding. The RF handles the classification decision, with two advantages over a neural classifier: it is naturally robust to class imbalance via  class_weight='balanced' , and it produces feature importances that make predictions explainable to fraud analysts.

Fitting the RF head on TGN embeddings

After training the TGN backbone, run the validation set through the model to collect embeddings and labels, then fit the RF:
from sklearn.ensemble import RandomForestClassifier
import numpy as np

# Collect embeddings from the validation set
val_embeddings = []
val_labels = []

model.eval()
model.reset_memory()

for batch in val_loader:
src, dst, t, msg, labels = batch
# Get embeddings from the TGN (before the scoring head)
n_id = torch.cat([src, dst]).unique()
z, _ = model.memory(n_id)
assoc = torch.full((n_id.max() + 1,), -1, dtype=torch.long)
assoc[n_id] = torch.arange(n_id.size(0))
z_src = z[assoc[src]]
val_embeddings.append(z_src.detach().numpy())
val_labels.append(labels.numpy())
model.memory.update_state(src, dst, t.long(), msg)
model.detach_memory()

X_val = np.vstack(val_embeddings)
y_val = np.concatenate(val_labels)

# Fit the RF head
rf_head = RandomForestClassifier(
n_estimators=200,
max_depth=10,
class_weight='balanced', # handles 95:5 imbalance natively
n_jobs=-1,
)
rf_head.fit(X_val, y_val)

At inference time, the RF head replaces the  node_pred  MLP for final scoring. The TGN still runs its full forward pass (memory lookup, graph attention, memory update) — only the final classification step changes.

Feature importances for explainability

One of the most operationally valuable properties of the RF head is feature importances. Each dimension of the TGN embedding corresponds to a learned feature of the node's temporal and structural context. The RF learns which dimensions are most predictive of fraud for the specific target network:
# Top 10 most predictive embedding dimensions
importances = rf_head.feature_importances_
top_dims = np.argsort(importances)[::-1][:10]

for rank, dim in enumerate(top_dims):
print(f" Rank {rank+1}: embedding dim {dim} — importance {importances[dim]:.4f}")

This doesn't give named feature descriptions the way tabular models do, but it gives fraud analysts a signal for model auditing and debugging. When a model starts misfiring after a fraud ring changes tactics, the feature importance shift is often detectable before AUC degrades.



Detecting concept drift before AUC degrades

Fraud patterns evolve continuously. A model deployed today will face attackers who specifically probe its decision boundary within weeks. Waiting for chargeback feedback to detect performance degradation — chargebacks typically arrive 30–90 days after the fraudulent transaction — is too slow.
The production AWS architecture from Part 1 addresses this with two drift signals:
Embedding distribution drift. Each entity's TGN memory vector  s_i(t)  is a compressed representation of its behavioral history. When the fraud-generating process changes — new attack patterns emerge, legitimate spending behavior shifts — the distribution of memory vectors in the fraud cluster changes even if raw transaction statistics look similar. An autoencoder trained on the distribution of memory vectors from the training period will produce higher reconstruction errors when that distribution shifts. This is the TGNN-CDD approach.
Rolling AUC-PR on labeled feedback. Amazon CloudWatch tracks the model's AUPRC on the rolling window of transactions that have received chargeback confirmation. A sustained decline triggers an EventBridge rule that kicks off a SageMaker Pipelines retrain.
The two signals are complementary: embedding drift is a leading indicator (detects the shift before labels arrive), and AUPRC decline is the lagging confirmation. Together they provide both early warning and validated evidence of degradation before initiating an expensive retrain.

Configuring drift detection with CloudWatch custom metrics

Note:  Amazon SageMaker Model Monitor  is closing to new customers effective 30 July 2026. The code example below works for existing customers. For new deployments, use  Amazon CloudWatch custom metrics  with a custom monitoring container — the alarm and EventBridge retraining trigger pattern remains identical.
 Amazon SageMaker Model Monitor  handles the infrastructure side — scheduling monitoring jobs, computing baseline statistics, and publishing CloudWatch alarms. Configure it on your TGN inference endpoint after deployment:
import boto3
from sagemaker.model_monitor import DataCaptureConfig, ModelMonitor

# Enable data capture on the inference endpoint
data_capture_config = DataCaptureConfig(
enable_capture=True,
sampling_percentage=100,
destination_s3_uri="s3://your-bucket/model-monitor/captures",
)

# Create a monitoring schedule — runs hourly
monitor = ModelMonitor(
role="your-sagemaker-role",
instance_count=1,
instance_type="ml.m5.xlarge",
)

monitor.create_monitoring_schedule(
monitor_schedule_name="tgn-fraud-detector-monitor",
endpoint_input="tgn-fast-path-endpoint",
output_s3_uri="s3://your-bucket/model-monitor/reports",
statistics="s3://your-bucket/model-monitor/baseline/statistics.json",
constraints="s3://your-bucket/model-monitor/baseline/constraints.json",
schedule_cron_expression="cron(0 * ? * * *)", # hourly
)

When the monitor detects a constraint violation — input feature distribution drifting beyond the baseline — it publishes a CloudWatch alarm. An EventBridge rule connects that alarm to a Lambda function that triggers your SageMaker Pipeline retrain workflow.



Putting it all together: the upgraded architecture

Combining MiNT pre-training, RF ensemble scoring, and drift-triggered retraining, the full Part 2 architecture looks like this:
┌─────────────────────────────────────────┐
│ OFFLINE (nightly/weekly) │
│ │
│ MiNT pre-training across N networks │
│ → Frozen backbone checkpoint in │
│ SageMaker Model Registry │
│ │
│ Per-network fine-tuning │
│ → Adapted scoring heads (RF + MLP) │
└────────────────────┬────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ REAL-TIME INFERENCE │
│ │
│ Pass 1 (100% of transactions): │
│ TGN memory lookup (ElastiCache) │
│ → Embedding → RF head → risk score │
│ < 0.3: Approve │
│ ≥ 0.3: Pass 2 │
│ │
│ Pass 2 (~3% of transactions): │
│ Neptune subgraph → SEAL structural score │
│ Combined score → risk tier → decision │
└────────────────────┬────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ DRIFT MONITORING │
│ │
│ CloudWatch custom metrics (hourly) │
│ → Embedding drift detection │
│ → CloudWatch alarm on violation │
│ → EventBridge → SageMaker Pipeline │
│ → Retrain → Model Registry gate │
│ → Endpoint update (if AUPRC passes) │
└─────────────────────────────────────────┘


What MiNT changes in the SageMaker Pipelines workflow

The training pipeline from Part 1 trained a single model on a single network's historical data. With MiNT, the pipeline gains a pre-training step:
S3 (multi-network training data)
→ AWS Glue ETL (build one TemporalGraph per network, temporal splits)
→ SageMaker Training Job: MiNT pre-training (5+ networks, ~12h on ml.g4dn.12xlarge)
→ SageMaker Model Registry: MiNT backbone checkpoint
→ SageMaker Training Job: Per-network fine-tuning (RF head + MLP heads, ~2h)
→ Validation gate: AUPRC ≥ previous production model
→ SageMaker endpoint update

The MiNT pre-training job runs monthly on the full multi-network corpus. The fine-tuning job runs weekly on the most recent labeled transactions from the production network. This cadence gives the backbone time to learn stable cross-network representations while keeping the scoring heads current with the evolving fraud landscape.



Running the MiNT pipeline

The full MiNT pipeline runs end-to-end with the progressive learning script:
# Activate your virtual environment from Part 1
source .venv/bin/activate

# Run the MiNT learning script
python learn/06_mint_transfer.py

The script walks through all five stages — network generation, multi-network training, zero-shot evaluation, fine-tuning, and baseline comparison — printing results at each step.
For production use, the equivalent SageMaker Training Job uses the same  MiNTTrainer  class with a larger configuration:
# Production MiNT config — runs on ml.g4dn.12xlarge
mint_config = MiNTConfig(
num_train_networks=20, # 20 networks for diverse pre-training
num_test_networks=4,
epochs=30,
batch_size=512,
fine_tune_epochs=10,
transactions_per_network=50000, # larger networks for production
accounts_per_network=5000,
fraud_rate=0.03,
seed=42,
)

model_config = TGNConfig(
memory_dim=128,
embedding_dim=128,
time_dim=64,
)




Cleaning up

To avoid ongoing charges from the resources deployed in Parts 1 and 2, follow the cleanup steps in  Part 1  and additionally:
  1. SageMaker monitoring schedules — In the  Amazon SageMaker console , choose Model Monitor > Monitoring schedules and delete the TGN monitoring schedule.
  1. CloudWatch alarms — In the  Amazon CloudWatch console , select and delete the drift detection alarms created for the TGN endpoint.
  1. EventBridge rules — In the  Amazon EventBridge console , delete the retrain trigger rule.



Conclusion

In this post, I showed how MiNT upgrades a single-network TGN into a genuinely transferable fraud detection system. By training a shared backbone across multiple networks and fine-tuning only the scoring heads for each deployment target, you get a model that generalizes to new payment domains with minimal labeled data — a critical capability for financial services organizations operating across multiple markets or product lines.
The key techniques from this series, taken together:
  1. TGN memory captures behavioral history without hand-crafted features (Part 1)
  1. Combined contrastive + supervised loss learns both structural norms and fraud signatures (Part 1)
  1. Lambda architecture on AWS delivers sub-100ms inference at 10,000 TPS (Part 1)
  1. MiNT cross-network pre-training produces transferable fraud representations (Part 2)
  1. Frozen backbone fine-tuning adapts to new networks with minimal labeled data (Part 2)
  1. RF ensemble head adds explainability and handles class imbalance at the decision layer (Part 2)
  1. Drift detection closes the feedback loop so the system retrains before production AUC degrades (Part 2)
The full implementation is available on GitHub. If you build on it, I'd like to hear what you find — particularly any improvements to the MiNT pre-training diversity or fine-tuning strategies for low-data deployment scenarios. Leave a comment, or open an issue on GitHub.



Additional resources

  • BRIGHT — Lu et al. (2022) — Lambda architecture for graph-based fraud detection (eBay, CIKM 2022)
  • NID-TGN — Random Forest head on TGN embeddings for explainable fraud detection (SPACE 2024)
About the author: Faris Haddad is a technical lead at AWS based in UK, specialising in AI/ML and data solutions for enterprise customers. He works with financial services organisations to build scalable machine learning systems on AWS.

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