UniMod
Enhancing Multi-Modal Medical Diagnosis through Cross-Modality and Within-Modality Alignment
Zijian Gu, Weikai Lin, Shuang Zhou, Zihan Chen, Song Wang†
ACM Multimedia 2026 (MM '26), Rio de Janeiro, Brazil
📄 arXiv:2608.10316 · 📚 ACM Digital Library: 10.1145/3767308.3836116 (resolves once the proceedings are published, Nov 2026)
The problem: text is an easier modality than pixels
When a clinical note or radiology report already states the diagnosis, a model trained with a single fused classification loss has no reason to work hard on the image. It takes the shortcut: text carries the label, so the visual branch is never forced to learn anything. The failure is invisible in aggregate accuracy — the fused model looks fine — but the image encoder is close to useless on its own, and the model inherits whatever the report happens to omit.
UniMod’s answer is structural rather than regularisation-by-penalty: make every modality commit to a diagnosis on its own, so no branch can free-ride.
The design
Implementation note. The figure is schematic on one point: in code the multi-modal prediction is not read out at the final token position. It comes from a trainable concat-fusion MLP over the two pooled embeddings (losses/classification_loss.py:131,233). The wrapper does expose next-token answer_logits, but Trainer never uses them for classification.
One VLM, one forward pass, three supervised predictions:
| Component |
What it does |
Where it lives |
| Independent Feature Extraction (IFE) |
Image-only, text-only and multi-modal classification are supervised simultaneously. Three heads, three CE terms. |
losses/classification_loss.py |
| Modality-separated attention |
Text tokens are masked out of attending to image tokens, so the “text-only” embedding really is text-only rather than a fused representation in disguise. |
models/modality_separated_attention.py |
| Cross-modality alignment |
L2-normalised MSE between the projected image and text embeddings — knowledge transfer from the stronger to the weaker modality. |
losses/alignment_loss.py |
| Within-modality alignment |
Supervised contrastive loss over same-diagnosis patients, applied inside each modality separately. |
losses/supcon_loss.py |
| Dynamic loss weighting |
A GradNorm-style scheduler rebalances the three terms during training so none dominates. |
training/gradnorm.py |
$$\mathcal{L} = \lambda_1 \mathcal{L}\text{classify} + \lambda_2 \mathcal{L}\text{cross} + \lambda_3 \mathcal{L}_\text{within}$$
The backbone is InternVL2.5-8B adapted with LoRA (r=32, α=64) on the InternLM2 attention projections (wqkv, wo) — roughly 18.9M trainable adapter parameters, plus the projection heads and classifiers. The vision encoder and tokenizer stay frozen.
Results are reported in the paper (Table 1 for the binary benchmarks, Table 5 for 5-class multi-label). Short version: UniMod improves over OGM-GE and Gradient Blending on Harvard-Glaucoma and CheXpert Plus, and the gain is substantially larger in the multi-label setting than in the binary one. Please read Reproducibility before trying to match specific numbers.
Fundus images in the figures above are from the Harvard-Glaucoma dataset © Harvard Ophthalmology AI Lab, licensed CC BY-NC-ND 4.0, reproduced here for non-commercial research purposes.
Code structure
The library is unimod/; it is dataset-agnostic and serves both benchmarks. Entry points live in script_glaucoma/ and script_chexpert/, which differ only in their dataset wiring and prompt templates.
unimod/
├── models/
│ ├── vlm_wrapper.py InternVLWrapper — loads InternVL2.5-8B, builds chat prompts,
│ │ runs the forward pass, and locates the image/text token spans.
│ │ forward_chat_separated() is the training path.
│ ├── modality_separated_attention.py Builds the custom 4-D attention masks and monkey-patches
│ │ InternLM2's forward to accept them.
│ ├── feature_extractor.py ModalityFeatureExtractor — mean-pools the token spans and
│ │ projects each modality (4096 → 2048 → 512) with separate MLPs.
│ └── lora_config.py PEFT LoRA setup; InternLM2 target modules are wqkv/wo.
├── losses/
│ ├── combined_loss.py CombinedLossV2 — assembles L_total and owns the λ schedule.
│ ├── classification_loss.py The three heads (image / text / fusion); CE or BCE.
│ ├── alignment_loss.py Cross-modality: mse | cosine | contrastive | supervised_contrastive.
│ └── supcon_loss.py Within-modality supervised contrastive (per-class for multi-label).
├── training/
│ ├── trainer.py The training loop, evaluation, checkpointing, wandb.
│ ├── gradnorm.py Dynamic loss weighting (V2 / Cross / Within variants).
│ ├── metrics.py MetricsCalculator + MultilabelMetricsCalculator, incl. fairness.
│ ├── ogm_ge_v2.py OGM-GE baseline (Peng et al., CVPR 2022).
│ ├── gradient_blending.py Gradient Blending baseline (Wang et al., CVPR 2020).
│ └── cggm.py CGGM baseline (Guo et al., NeurIPS 2024).
├── data/
│ ├── glaucoma_dataset.py Harvard-Glaucoma; reads NPZ + data_summary.csv.
│ ├── chexpert_dataset.py CheXpert Plus binary and 5-class multi-label; deterministically
│ │ generates the 10k subsets on first run.
│ └── transforms.py Shared image transforms (448×448, ImageNet normalisation).
├── preprocessing/
│ ├── text_processor.py Text modes, incl. the leakage-control cleaner.
│ ├── prompt_template.py Glaucoma chat prompts.
│ └── chexpert_prompt_template.py CheXpert chat prompts (binary + multi-label).
└── utils/config.py YAML → dataclass config loading.
How a training step flows
train_v2.py
└─ builds dataloaders, InternVLWrapper, ModalityFeatureExtractor, CombinedLossV2
└─ Trainer.train()
└─ Trainer.train_epoch()
└─ Trainer._forward_step(batch)
├─ vlm.forward_chat_separated(pixel_values, prompts) ← modality-separated attention
│ → hidden_states, image_token_mask, text_token_mask
├─ feature_extractor(hidden_states, image_mask, text_mask)
│ → image_features [B,512], text_features [B,512]
└─ loss_fn(image_features, text_features, labels, dynamic_weights)
→ L_total, loss_dict, {logits_mm, logits_image, logits_text}
├─ loss.backward()
├─ (at the gradient-accumulation boundary) baseline modulators hook in here
├─ optimizer.step() / scheduler.step()
└─ gradnorm_scheduler.step(L_cls, L_cross, L_within) → weights for the next step
The batch contract
Every dataset’s collate_fn returns this dict; anything satisfying it will work with Trainer unchanged:
| Key |
Type |
Notes |
images |
Tensor [B,3,448,448] |
normalised |
labels |
Tensor [B] long, or [B,K] float |
long for binary/multi-class, float multi-hot for multi-label |
texts |
list[str] |
processed clinical text |
chat_prompts |
list[str] |
fully rendered prompt, <image> placeholder included |
metadata |
dict[str, list] |
dict-of-lists; race / gender drive the fairness breakdown |
indices |
Tensor [B] long |
dataset indices, for tracing predictions back to samples |
Extension points
Add a dataset. Mirror data/glaucoma_dataset.py: a Dataset returning the keys above, a collate_fn, and a get_*_dataloaders() returning (train_loader, val_loader, test_loader). Nothing in Trainer, the losses or the model needs to change.
Add or change a loss term. CombinedLossV2.forward in losses/combined_loss.py is the single place where terms are combined. Note that L_within is short-circuited when the static lambda3 is 0 — if you add a term that should be driven purely by GradNorm, mirror how L_cross is computed unconditionally instead.
Add a gradient-modulation baseline. Follow training/cggm.py or training/ogm_ge_v2.py: expose a modulate(...) that rescales .grad in place, then call it from Trainer.train_epoch after backward() and before optimizer.step(). Register the mode in EXPERIMENT_MODES in both train_v2.py files.
Add an experiment configuration. EXPERIMENT_MODES at the top of script_{glaucoma,chexpert}/train_v2.py maps a mode name to {lambda1, lambda2, lambda3, use_unimodal_cls, ...}. The two files are kept identical.
Swap the backbone. models/vlm_wrapper.py hard-codes InternLM2’s special-token IDs (92542–92546) and checks them against the tokenizer at load time, so a backbone that numbers them differently fails immediately rather than silently producing empty token masks. get_lora_target_modules() returns the InternLM2 attention module names. Both need updating for a different VLM, along with the token-span logic in _find_clinical_text_positions.
Change the masking scheme. models/modality_separated_attention.py has three mask builders — full separation, single-modality (used for the image-only / text-only baselines) and standard causal. --no_modality_separation disables the mechanism for ablation.
Experiment modes
| Mode |
λ₁ |
λ₂ |
λ₃ |
IFE |
Notes |
baseline |
1.0 |
0.0 |
0.0 |
✗ |
fusion head only |
plus_unimodal_cls |
1.0 |
0.0 |
0.0 |
✓ |
+ IFE |
plus_cross |
1.0 |
0.1 |
0.0 |
✓ |
+ cross-modality |
plus_within |
1.0 |
0.1 |
0.1 |
✓ |
default |
full |
1.0 |
0.1 |
0.1 |
✓ |
UniMod, static weights |
full_gradnorm |
1.0 |
1.0 |
1.0 |
✓ |
UniMod, dynamic weights |
no_cross |
1.0 |
0.0 |
0.1 |
✓ |
w/o cross ablation |
cross_only / cross_within |
1.0 |
0.1 |
0.0 / 0.1 |
✗ |
alignment without IFE |
ogm_ge / gradient_blending / cggm |
1.0 |
0.0 |
0.0 |
✓ |
baselines |
ogm_ge_alignment |
1.0 |
0.1 |
0.1 |
✗ |
OGM-GE + alignment, no IFE |
Two AUC conventions
The code reports two AUCs and they are not interchangeable:
auc_fused — mean of the image-head and text-head probabilities (late fusion). This is what the paper’s main table reports, and what model selection uses.
auc_mm — the multi-modal fusion classifier’s own AUC. Used for ablation comparisons, because configurations without IFE have no trained unimodal heads to average.
Mixing the two across rows of a table will produce misleading comparisons.
Setup
git clone https://github.com/futurespyhi/UniMod.git
cd UniMod
conda create -n unimod python=3.10
conda activate unimod
pip install -r requirements-loose.txt
requirements.txt / environment.yml are a frozen snapshot of the original training machine and pin nightly PyTorch wheels PyPI no longer serves. Use requirements-loose.txt unless you are specifically recreating that environment.
Run everything from the repository root — the configs use repo-relative paths.
Data
This repository distributes no data. Both datasets are access-controlled:
| Dataset |
How to obtain |
License |
| Harvard-Glaucoma (Harvard-FairVLMed) |
Request from the Harvard Ophthalmology AI Lab |
CC BY-NC-ND 4.0 |
| CheXpert Plus |
Sign the data use agreement with Stanford AIMI |
Stanford AIMI DUA |
Expected layout:
data/
├── glaucoma/data/
│ ├── ReadMe/data_summary.csv
│ ├── Training/ data_00001.npz ... (7,000)
│ ├── Validation/ data_07001.npz ... (1,000)
│ └── Test/ data_08001.npz ... (2,000)
└── cheXpert_Plus/
├── df_chexpert_plus_240401.csv
├── chexbert_labels/{report,findings,impression}_fixed.json
└── PNG/{train,valid}/patient*/study*/view*_frontal.png
The 10,000-sample subsets used in the paper are generated deterministically (seed 42) on first run and written to data/cheXpert_Plus/chexpert_pleural_effusion_10k.csv and chexpert_multilabel_5class_10k.csv. You do not need to build them by hand.
A note on text preprocessing: both datasets ship clinical text that frequently states the diagnosis outright, which is exactly the shortcut this work studies. The default text_mode: cleaned_clinical strips diagnostic sentences before they reach the model. This is leakage control, not de-identification — do not treat it as an anonymisation step.
Running
# Harvard-Glaucoma — full model with dynamic loss weighting
python script_glaucoma/train_v2.py --experiment_mode full_gradnorm --gpu 0 --epochs 3 --seed 42
# CheXpert Plus — binary (pleural effusion)
python script_chexpert/train_v2.py --experiment_mode full_gradnorm --gpu 0 --epochs 3 --seed 42
# CheXpert Plus — 5-class multi-label
python script_chexpert/train_v2.py --experiment_mode full --multilabel --gpu 0 --epochs 10 --seed 42
# Ablation: disable modality-separated attention
python script_glaucoma/train_v2.py --experiment_mode full_gradnorm --no_modality_separation --gpu 0 --epochs 3
# Smoke test (1 epoch, 32 samples)
python script_glaucoma/train_v2.py --experiment_mode full --debug --gpu 0
Add --wandb to log to Weights & Biases (off by default; run wandb login first). The wandb: block in the YAML is not read by train_v2.py — the project name is fixed to unimod_glaucoma / unimod_chexpert and no entity is passed, so runs land in your default entity. If initialisation fails, training continues without logging.
| Script |
Produces |
Usage |
script_{glaucoma,chexpert}/train_v2.py |
all trained models; every ablation row |
--experiment_mode <mode> (see the table above) |
script_{glaucoma,chexpert}/train_single_modality.py |
Table 1’s image-only and text-only rows |
--modality image | text |
script_{glaucoma,chexpert}/reeval_model.py |
Table 1’s optimal-threshold F1 / ACC |
--checkpoint <path> --experiment_mode <mode> |
script_glaucoma/eval_robustness.py |
Table 4 (missing-modality robustness) |
--checkpoint <path> |
script_{glaucoma,chexpert}/generate_case_study.py |
Figure 4 (case studies) |
--checkpoint <path> |
script_glaucoma/generate_tsne_viz.py, extract_features_single.py, plot_tsne_from_features.py |
the t-SNE embedding figures |
run in that order; pass --checkpoint explicitly |
script_{glaucoma,chexpert}/eval_zeroshot.py |
untuned-backbone reference numbers |
no checkpoint needed |
scripts/download_chexpert_chunks.sh, unzip_chexpert_chunks.sh |
fetches and unpacks the CheXpert Plus PNG archives |
SLURM array jobs; needs your signed-DUA download links in data/cheXpert_Plus/download_link.txt |
preprocessing/text_processor.py::analyze_dataset_leakage |
the leakage statistics quoted in the configs (e.g. “98.6% of gpt4_summary contains ‘glaucoma’”) |
import and call on a dataframe |
script_glaucoma/train.py is the superseded v1 loop (CombinedLoss, integer experiment_mode: 1-4). Despite its docstring it does not implement the paper’s $\mathcal{L}_\text{total}$, and script_chexpert/ has no counterpart. Always use train_v2.py.
Running on your own cluster
scripts/ holds SLURM job scripts written for UF HiPerGator. Before submitting, replace:
--account / --qos — removed from the scripts; pass your own via sbatch --account=... --qos=...
--partition (hpg-b200 / hpg-default / bigmem) and --gres=gpu:b200:1 — b200 is a site-local GRES type name and other schedulers will reject it
module load conda/25.7.0 — your site’s conda module
UNIMOD_ENV — set it if your environment is not named unimod
scripts/run_ogm_ge.sbatch runs with logging off; submit with --export=ALL,WANDB_FLAG=--wandb to enable it.
Reproducibility
Please read this before opening an issue about not matching the paper’s numbers.
The main-table results were produced in January 2026 on a 2×RTX 5090 workstation that is no longer accessible to us. Those checkpoints were not preserved and are not distributed here. The code here is the same method implementation, but we cannot guarantee bit-exact reproduction of that table.
The results we can back with archived artifacts are multi-seed runs from May 2026 on a single NVIDIA B200 under a shorter schedule (3 epochs, full_gradnorm):
|
Harvard-Glaucoma |
CheXpert Plus |
| AUC |
0.8412 ± 0.0044 |
0.9554 ± 0.0016 |
| ACC |
0.7557 ± 0.0091 |
0.8980 ± 0.0043 |
| F1 |
0.7279 ± 0.0192 |
0.8991 ± 0.0017 |
Different schedule and different hardware from the paper’s main table — reported here for transparency, not as a restatement of it.
Other things worth knowing before you run this:
- Seeds are fixed (
--seed, default 42) with cudnn.deterministic=True, but hardware, driver and PyTorch versions differ from the original runs. Small deviations are expected.
--batch_size defaults to 8, overriding the value in the YAML, with gradient accumulation to an effective batch of 32.
Trainer.load_checkpoint restores the projection heads and classifiers but not the LoRA adapter weights, so the reported test metrics use the best-epoch heads with the final-epoch backbone.
- The t-SNE and feature-extraction scripts under
script_glaucoma/ default to checkpoint paths from the original runs, which are not included. Pass --checkpoint explicitly.
This is a reference implementation of the method described in the paper, not a turnkey reproduction package.
Citation
@inproceedings{gu2026unimod,
author = {Gu, Zijian and Lin, Weikai and Zhou, Shuang and Chen, Zihan and Wang, Song},
title = {{UniMod}: Enhancing {Multi-Modal} Medical Diagnosis through {Cross-Modality} and {Within-Modality} Alignment},
booktitle = {Proceedings of the 34th ACM International Conference on Multimedia},
series = {MM '26},
year = {2026},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
location = {Rio de Janeiro, Brazil},
doi = {10.1145/3767308.3836116},
url = {https://doi.org/10.1145/3767308.3836116},
isbn = {979-8-4007-2213-4},
eprint = {2608.10316},
archivePrefix = {arXiv},
primaryClass = {cs.CV}
}
Page numbers are assigned when the proceedings are published (November 2026); the entry above will be updated with pages and numpages then. Once the paper is in the ACM Digital Library, its own export is authoritative.
License
Code in this repository is released under the MIT License (see LICENSE).
The paper is published open access under CC BY 4.0. The datasets are covered by neither — they remain under their own terms (Harvard-Glaucoma: CC BY-NC-ND 4.0; CheXpert Plus: Stanford AIMI DUA).
Acknowledgements
This research used data provided by the Stanford Center for Artificial Intelligence in Medicine and Imaging (AIMI). AIMI curated a publicly available imaging data repository containing clinical imaging and data from Stanford Health Care, the Stanford Children’s Hospital, the University Healthcare Alliance and Packard Children’s Health Alliance clinics provisioned for research use by the Stanford Medicine Research Data Repository (STARR).
Fundus images are from the Harvard-Glaucoma dataset © Harvard Ophthalmology AI Lab, licensed CC BY-NC-ND 4.0. All data is used for non-commercial research purposes only.
We build on InternVL and PEFT. Baseline implementations follow OGM-GE (Peng et al., CVPR 2022), Gradient Blending (Wang et al., CVPR 2020) and CGGM (Guo et al., NeurIPS 2024).
评论