Privacy-Aware Hospital Readmission Analysis and Prediction with Safe Synthesizer¶
What you'll learn¶
In this notebook, we'll build a privacy-aware hospital readmissions workflow with NeMo Safe Synthesizer. You'll learn how NeMo Safe Synthesizer finds and replaces columns that commonly contain sensitive healthcare data, generate synthetic admissions, interpret built-in quality and privacy evaluations, inspect healthcare-specific relationships, and test whether the generated data supports downstream readmission modeling.
We will answer three questions:
- Does the Synthetic data preserve the utilization, payer, and clinical patterns found in the Original data?
- What do the built-in quality and privacy evaluations tell us about the generated data?
- Can a model trained on Synthetic data transfer to a held-out Original cohort?
Runtime: Running the complete notebook took about an hour on an NVIDIA A100. A first run may take longer while model files are downloaded.
Important terminology: the Original dataset provided with this notebook was generated with NVIDIA NeMo Data Designer, is entirely simulated, and contains no real patient data. This public, non-sensitive dataset lets anyone run the tutorial. In a Safe Synthesizer deployment, Original would instead mean your private, internal dataset; NeMo Data Designer is not required. Throughout this tutorial and its plots, Original means the input dataset, while Synthetic means the new dataset generated from it by Safe Synthesizer.
1. Environment¶
Run the cell below to install NeMo Safe Synthesizer with the engine and CUDA 12.9 extras. If it is already installed in your notebook environment, you can skip this cell. The cell after it installs xgboost, which section 6 uses to train a readmission model. A GPU that supports CUDA 12.9 is required for training and generation. The cell requires uv.
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import sys
# The override resolves a flashinfer-python pin conflict between vLLM and NeMo Safe Synthesizer.
!echo "flashinfer-python==0.7.0.post1" | uv pip install --python "{sys.executable}" \
"nemo-safe-synthesizer[engine,cu129]==0.2.0" \
-c https://raw.githubusercontent.com/NVIDIA-NeMo/Safe-Synthesizer/v0.2.0/constraints.txt \
--overrides - \
--find-links https://flashinfer.ai/whl/cu129/flashinfer-jit-cache/ \
--find-links https://flashinfer.ai/whl/flashinfer-cubin/ \
--find-links https://wheels.vllm.ai/0.32.0/cu129/vllm/ \
--find-links https://download.pytorch.org/whl/cu129/torch/ \
--find-links https://download.pytorch.org/whl/cu129/torchaudio/ \
--find-links https://download.pytorch.org/whl/cu129/torchvision/ \
--find-links https://download.pytorch.org/whl/cu129/torchcodec/ \
--find-links https://download.pytorch.org/whl/cu129/torchao/ \
--find-links https://download.pytorch.org/whl/cu129/triton/
import sys
# Packages this tutorial uses besides NeMo Safe Synthesizer.
!uv pip install --python "{sys.executable}" xgboost
import html
import matplotlib.pyplot as plt
import pandas as pd
from IPython.display import Markdown, display
NVIDIA_GREEN = "#76B900"
NVIDIA_DARK = "#1A1A1A"
plt.rcParams.update({"figure.figsize": (10, 5), "axes.spines.top": False, "axes.spines.right": False})
2. Load the admissions data¶
The Original dataset is provided with this tutorial. Pandas infers quoted numeric CSV fields as integers, so the explicit string dtype below preserves leading zeros in postal codes.
source_df = pd.read_csv(
"datasets/hospital_readmissions_synthetic_2026_08_18.csv",
dtype={"postal_code": "string"},
)
print(f"Loaded {len(source_df):,} Original admissions with {source_df.shape[1]} fields.")
PREVIEW_COLUMNS = [
"age", "sex", "insurance_type", "encounter_type",
"primary_diagnosis", "icd10_code", "primary_lab_name",
"primary_lab_value", "primary_lab_unit", "primary_lab_flag",
"length_of_stay_days", "discharge_disposition",
"total_charge_usd", "readmitted_within_30_days",
]
source_df[PREVIEW_COLUMNS].head()
3. Sensitive-data replacement¶
Healthcare records may contain personally identifiable information (PII), and identifiable information about a person's health or care may be protected health information (PHI). Although this tutorial uses simulated data, its columns resemble fields that would require careful handling in a real healthcare workflow.
Before training, NeMo Safe Synthesizer replaces PII. An LLM first reviews each column and drafts a replacement plan: which columns hold PII and of what kind, and which replacements should stay consistent with each other, such as a patient's email following their replaced name. Free-text columns such as discharge_summary are scanned for names, dates, and identifiers by a named-entity recognition (NER) model running in the notebook environment, and each original value gets the same replacement wherever it appears in a record. Replacement runs on the training records before fine-tuning, so the model never sees the original identifiers.
By default, the planning LLM runs in a temporary vLLM server on this machine's GPU, so no API key is needed and the data stays on this machine. The local model needs an 80 GB GPU and downloads about 66 GB the first time it runs. To use a hosted service instead, such as the NVIDIA API at https://integrate.api.nvidia.com/v1, set NSS_INFERENCE_ENDPOINT, NSS_INFERENCE_MODEL, and NSS_INFERENCE_KEY in the next cell. You can obtain an API key from build.nvidia.com. Column samples are then sent to that service. See Where planning requests go for details.
Important: The plan is drafted by an LLM, so it can miss a sensitive column or replace one you need. Before using your own data, review the plan as shown in Review the PII Replacement Plan.
import os
# Keep the data split and generated replacements reproducible across tutorial runs.
SPLIT_SEED = 318
# Optional: plan with a hosted service instead of a local vLLM server.
# import getpass
# os.environ["NSS_INFERENCE_ENDPOINT"] = "https://integrate.api.nvidia.com/v1"
# os.environ["NSS_INFERENCE_MODEL"] = "nvidia/nemotron-3-ultra-550b-a55b"
# os.environ["NSS_INFERENCE_KEY"] = getpass.getpass("Paste inference API key: ")
if os.environ.get("NSS_INFERENCE_ENDPOINT"):
print(f"PII planning sends requests to {os.environ['NSS_INFERENCE_ENDPOINT']}")
else:
print("PII planning runs a local vLLM server on this machine's GPU")
4. Train, generate, and evaluate¶
The next cell runs the complete Safe Synthesizer pipeline. It sets aside 499 Original records for evaluation, drafts the PII replacement plan and applies it to the remaining 9,498 records before fine-tuning the default SmolLM3 model, generates 5,000 Synthetic records, and evaluates the result. The generated data, trained model adapter (the learned model update), metrics, and HTML report are saved automatically under ARTIFACT_ROOT. The adapter can be reused for later generation without repeating fine-tuning.
from nemo_safe_synthesizer.sdk.library_builder import SafeSynthesizer
ARTIFACT_ROOT = "safe-synthesizer-artifacts/healthcare-hospital-readmissions"
builder = (
SafeSynthesizer(save_path=ARTIFACT_ROOT)
.with_data_source(source_df)
.with_replace_pii(seed=SPLIT_SEED)
.with_data(random_state=SPLIT_SEED)
.with_generate(num_records=5_000)
)
builder.run()
results = builder.results
synthetic_df = results.synthetic_data.copy()
assert len(synthetic_df) == 5_000, f"Expected 5,000 generated records, found {len(synthetic_df):,}."
print(f"Generated {len(synthetic_df):,} synthetic admissions.")
display(synthetic_df[PREVIEW_COLUMNS].head())
Built-in SQS, DPS, and HTML report¶
The Synthetic Data Quality Score (SQS) summarizes statistical similarity, while the Data Privacy Score (DPS) summarizes the built-in privacy evaluation. Both use a 0–10 scale, where higher is better. Open the HTML report to inspect the component scores and identify distributions, relationships, or privacy risks that need attention. These results support review; they do not certify compliance or automatically approve the data for sharing.
report_html = results.evaluation_report_html
if report_html:
# srcdoc, not a data: URL: Chrome blanks data: URLs over 2 MB, and the base keeps the report's #section links in the frame.
report_doc = report_html.replace("<head>", '<head><base href="about:srcdoc">', 1)
frame = (
f'<iframe srcdoc="{html.escape(report_doc)}" sandbox="allow-scripts allow-popups" '
'width="100%" height="850"></iframe>'
)
# Raw display: HTML() warns about a bare <iframe>, and IFrame() cannot take srcdoc.
display({"text/html": frame}, raw=True)
else:
display(Markdown("The run did not return an HTML evaluation report."))