SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2502.20056 · CVPR · 2025

Enhanced Contrastive Learning with Multi-view Longitudinal Data for Chest X-ray Report Generation

Kang Liu, Kun Xie, Yunan Li, Qiguang Miao, Zhuoqi Ma, Zhicheng Jiao, Xiaolu Kang, -Ap C 1 -Pa C-Ind

arXiv · PDF · Open in the Atlas

Code that ran

3 of 7 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 3 have no contract verdict; 0 failures of our instrument; 4 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2502.20056.json · badge: /api/ran/2502.20056.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
mk-runner/MLRG marked official in Papers with Code
Papers with Code archive
3 ran · 4 no recorded run
FunctionStatusWhere it lives
PretrainDinov2CollateFn Ran
ran on a synthesized input
mk-runner/MLRG/models/model_pretrain_finetune_v0905_ablation.py
code served (permissive licence) · get_code("5ea82faa51c79aa8")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np
from unittest.mock import Mock, MagicMock
from PIL import Image
import io

# Create a mock processor that mimics a vision processor
class MockProcessor:
    def __call__(self, image, return_tensors=None):
        # Return a mock object with pixel_values attribute
        mock_output = Mock()
        mock_output.pixel_values = torch.randn(1, 3, 224, 224)
        return mock_output

# Create temporary image files
def create_mock_image():
    img = Image.new('RGB', (224, 224), color='red')
    return img

# Create a temporary directory structure with mock images
import tempfile
import os

temp_dir = tempfile.mkdtemp()

# Create directory structure
os.makedirs(os.path.join(temp_dir, 'patient_001', 'study_001'), exist_ok=True)
os.makedirs(os.path.join(temp_dir, 'patient_002', 'study_002'), exist_ok=True)

# Create mock images
img1_path = os.path.join(temp_dir, 'patient_001', 'study_001', 'image_001.jpg')
img2_path = os.path.join(temp_dir, 'patient_001', 'study_001', 'image_002.jpg')
img3_path = os.path.join(temp_dir, 'patient_002', 'study_002', 'image_003.jpg')
img4_path = os.path.join(temp_dir, 'patient_002', 'study_002', 'image_004.jpg')

for img_path in [img1_path, img2_path, img3_path, img4_path]:
    create_mock_image().save(img_path)

# Prepare data for collate function
data_batch = [
    (
        'image_id_1',
        {
            'image_path': ['patient_001/study_001/image_001.jpg'],
            'view_position': ['PA']
        },
        {
            'image_path': ['patient_001/study_001/image_002.jpg'],
            'view_position': ['LATERAL']
        },
        'Report text 1',
        {
            'latest_study': {
                'image_path': 'patient_001/study_001/image_002.jpg',
                'view_position': 'PA'
            }
        }
    ),
    (
        'image_id_2',
        {
            'image_path': ['patient_002/study_002/image_003.jpg'],
            'view_position': ['AP']
        },
        {
            'image_path': ['patient_002/study_002/image_004.jpg'],
            'view_position': ['LATERAL']
        },
        'Report text 2',
        {
            'latest_study': {
                'image_path': 'patient_002/study_002/image_004.jpg',
                'view_position': 'AP'
            }
        }
    )
]

INIT_ARGS = {
    'image_dir': temp_dir,
    'processor': MockProcessor(),
    'is_multiview_learning': True,
    'is_prior_scan': True
}

ARGS = {
    'data': data_batch
}

# Test execution
if __name__ == '__main__':
    from class_fixture import PretrainDinov2CollateFn
    
    collate_fn = PretrainDinov2CollateFn(**INIT_ARGS)
    result = collate_fn(**ARGS)
    print("Collate function executed successfully")
    print(f"Result types: {[type(r) for r in result]}")
    print(f"Images shape: {result[1].shape}")
    print(f"Patient IDs shape: {result[3].shape}")
    print(f"View positions shape: {result[4].shape}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
PIL, class_fixture, numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
ProjectionHead Ran
ran on a synthesized input
mk-runner/MLRG/models/model_pretrain_finetune_v0905_ablation.py
code served (permissive licence) · get_code("c674dc293660818d")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float, shape (2, 5, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from torch import nn

class ProjectionHead(nn.Module):

    def __init__(self, input_dim, hidden_dim, output_dim) -> None:
        super().__init__()
        self.head = nn.Sequential(nn.Conv1d(input_dim, hidden_dim, kernel_size=1, stride=1, padding=0), nn.BatchNorm1d(hidden_dim), nn.ReLU(inplace=True), nn.Conv1d(hidden_dim, output_dim, kernel_size=1, stride=1, padding=0))

    def forward(self, x):
        x = x.permute(0, 2, 1)
        x = self.head(x)
        return x.permute(0, 2, 1)


INIT_ARGS = {
    'input_dim': 4,
    'hidden_dim': 8,
    'output_dim': 3,
}

ARGS = {
    'x': torch.randn(2, 5, 4),
}

if __name__ == '__main__':
    model = ProjectionHead(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Expected shape: (2, 5, 3)")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (2, 5, 3) — shape (2, 5, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
ScaledDotProductAttention2D Ran
ran on a synthesized input
mk-runner/MLRG/models/model_pretrain_finetune_v0905_ablation.py
code served (permissive licence) · get_code("ba53182976dad2ee")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 2, dtype family float, shape (5, 8) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from torch import nn
import numpy as np

# Construct the class
class ScaledDotProductAttention2D(nn.Module):
    """
    Scaled dot-product attention
    """

    def __init__(self, d_model, d_k, d_v, h, dropout=0.1):
        """
        :param d_model: Output dimensionality of the model
        :param d_k: Dimensionality of queries and keys
        :param d_v: Dimensionality of values
        :param h: Number of heads
        """
        super(ScaledDotProductAttention2D, self).__init__()
        self.fc_q = nn.Linear(d_model, h * d_k)
        self.fc_k = nn.Linear(d_model, h * d_k)
        self.fc_v = nn.Linear(d_model, h * d_v)
        self.fc_o = nn.Linear(h * d_v, d_model)
        self.dropout = nn.Dropout(dropout)
        self.ln_1 = nn.LayerNorm(d_model)
        self.ln_2 = nn.LayerNorm(d_model)
        self.d_model = d_model
        self.d_k = d_k
        self.d_v = d_v
        self.h = h
        self.init_weights()

    def save_grad(self):

        def hook(grad):
            self.attn_grads = grad
        return hook

    def init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, std=0.001)
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)

    def forward(self, queries, keys, values, attention_mask=None, attention_weights=None):
        """
        Computes
        :param queries: Queries (b_s, nq, d_model)
        :param keys: Keys (b_s, nk, d_model)
        :param values: Values (b_s, nk, d_model)
        :param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
        :param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
        :return:
        """
        queries, keys, values = (queries.unsqueeze(0), keys.unsqueeze(0), values.unsqueeze(0))
        b_s, nq = queries.shape[:2]
        nk = keys.shape[1]
        queries, keys, values = (self.ln_1(queries), self.ln_2(keys), self.ln_2(values))
        q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2, 1, 3)
        k = self.fc_k(keys).view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
        v = self.fc_v(values).view(b_s, nk, self.h, self.d_v).permute(0, 2, 1, 3)
        att = torch.matmul(q, k) / np.sqrt(self.d_k)
        if attention_weights is not None:
            att = att * attention_weights
        if attention_mask is not None:
            att = att.masked_fill(attention_mask, -np.inf)
        att = torch.softmax(att, -1)
        att = self.dropout(att)
        out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s, nq, self.h * self.d_v)
        out = self.fc_o(out)
        return out.squeeze(0)


INIT_ARGS = {
    'd_model': 8,
    'd_k': 4,
    'd_v': 3,
    'h': 2,
    'dropout': 0.1
}

ARGS = {
    'queries': torch.randn(5, 8),
    'keys': torch.randn(6, 8),
    'values': torch.randn(6, 8),
    'attention_mask': None,
    'attention_weights': None
}

if __name__ == '__main__':
    model = ScaledDotProductAttention2D(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Output: {output}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family float, shape (5, 8) — shape (5, 8) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
MimiccxrPretrainDataset Not yet run
unverified (harvested, no recorded run)
mk-runner/MLRG/models/model_pretrain_finetune_v0905_ablation.py
code served (permissive licence) · get_code("899bb9b39202d07f")
How it ran

no invocation recorded.

Pretrain Not yet run
unverified (harvested, no recorded run)
mk-runner/MLRG/models/model_pretrain_finetune_v0905_ablation.py
code served (permissive licence) · get_code("c5313543ca101d11")
How it ran

no invocation recorded.

PretrainBaseDataset Not yet run
unverified (harvested, no recorded run)
mk-runner/MLRG/models/model_pretrain_finetune_v0905_ablation.py
code served (permissive licence) · get_code("26f30fa9dc73079b")
How it ran

no invocation recorded.

Transformer Not yet run
unverified (harvested, no recorded run)
mk-runner/MLRG/models/model_pretrain_finetune_v0905_ablation.py
code served (permissive licence) · get_code("64ac80b8f3195986")
How it ran

no invocation recorded.

Also present in other papers' code

Of 7 samples lifted from this paper's linked repositories, 7 carry a function identity and 0 do not. Of the 7 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 7 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Automated radiology report generation offers an effective solution to alleviate radiologists' workload. However, most existing methods focus primarily on single or fixed-view images to model current disease conditions, which limits diagnostic accuracy and overlooks disease progression. Although some approaches utilize longitudinal data to track disease progression, they still rely on single images to analyze current visits. To address these issues, we propose enhanced contrastive learning with Multi-view Longitudinal data to facilitate chest X-ray Report Generation, named MLRG. Specifically, we introduce a multi-view longitudinal contrastive learning method that integrates spatial information from current multi-view images and temporal information from longitudinal data. This method also utilizes the inherent spatiotemporal information of radiology reports to supervise the pre-training of visual and textual representations. Subsequently, we present a tokenized absence encoding technique to flexibly handle missing patient-specific prior knowledge, allowing the model to produce more accurate radiology reports based on available prior knowledge. Extensive experiments on MIMIC-CXR, MIMIC-ABN, and Two-view CXR datasets demonstrate that our MLRG outperforms recent state-of-the-art methods, achieving a 2.3% BLEU-4 improvement on MIMIC-CXR, a 5.5% F1 score improvement on MIMIC-ABN, and a 2.7% F1 RadGraph improvement on Two-view CXR.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2502.20056")
get_code_for_paper("2502.20056")
have("2502.20056")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2502.20056.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2502.20056.svg)](https://syntology.ai/paper/2502.20056)

Connect an agent — have() is free.