SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2402.12336 · ICML · 2024

Robust CLIP: Unsupervised Adversarial Fine-Tuning of Vision Embeddings for Robust Large Vision-Language Models

Matthias Hein, Francesco Croce, Naman Singh, Christian Schlarmann

arXiv · PDF · Open in the Atlas

Code that ran

7 of 9 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 1 has no contract verdict; 6 failures of our instrument; 2 no recorded run), measured 2026-11-22; 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/2402.12336.json · badge: /api/ran/2402.12336.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
chs20/robustvlm canonical (classifier label)
classifier basis: classifier_2025
7 ran · 2 no recorded run
FunctionStatusWhere it lives
ComputeLossWrapper Ran
ran on a synthesized input
chs20/robustvlm/train/adversarial_training_clip.py
code served (permissive licence) · get_code("5bfccc77a86a50fb")
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 0, dtype family float, shape () 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
import torch.nn.functional as F

def ce(out, targets, reduction='mean'):
    assert out.shape[0] == targets.shape[0], (out.shape, targets.shape)
    assert out.shape[0] > 1
    return F.cross_entropy(out, targets, reduction=reduction)

def compute_loss(loss_str, embedding, targets, embedding_orig, logit_scale, embedding_text_labels_norm=None, reduction='mean'):
    if loss_str == 'l2':
        loss = l2(out=embedding, targets=embedding_orig, reduction=reduction)
    elif loss_str == 'ce':
        loss = ce(out=embedding @ (logit_scale * embedding_text_labels_norm), targets=targets, reduction=reduction)
    else:
        raise ValueError(f'loss {loss_str} not supported')
    return loss

def l2(out, targets, reduction='none'):
    assert out.shape == targets.shape, f'{out.shape} != {targets.shape}'
    assert out.shape[0] > 1
    squared_error_batch = F.mse_loss(out, targets, reduction='none')
    if reduction == 'mean':
        squared_error_batch = torch.mean(squared_error_batch.sum(dim=1))
    else:
        squared_error_batch = squared_error_batch.sum(dim=1)
        assert squared_error_batch.shape == (out.shape[0],), f'{squared_error_batch.shape} != {(out.shape[0],)}'
    return squared_error_batch

class ComputeLossWrapper:

    def __init__(self, embedding_orig, embedding_text_labels_norm, reduction='mean', loss=None, logit_scale=100.0):
        self.embedding_orig = embedding_orig
        self.embedding_text_labels_norm = embedding_text_labels_norm
        self.reduction = reduction
        self.loss_str = loss
        self.logit_scale = logit_scale

    def __call__(self, embedding, targets):
        return compute_loss(loss_str=self.loss_str, embedding=embedding, targets=targets, embedding_orig=self.embedding_orig, logit_scale=self.logit_scale, embedding_text_labels_norm=self.embedding_text_labels_norm, reduction=self.reduction)


INIT_ARGS = {
    'embedding_orig': torch.randn(2, 4),
    'embedding_text_labels_norm': torch.randn(3, 4),
    'reduction': 'mean',
    'loss': 'l2',
    'logit_scale': 100.0,
}

ARGS = {
    'embedding': torch.randn(2, 4),
    'targets': torch.tensor([0, 1]),
}
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 0, dtype family float, shape () — shape () 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)
compute_acc Ran
ran; our contract draft was wrong, not the code
chs20/robustvlm/train/adversarial_training_clip.py
code served (permissive licence) · get_code("1f2be2216dc3f7cd")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned float, ndim 0, dtype family float, shape () 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

torch.manual_seed(0)

# Create logits tensor: shape (batch_size=2, num_classes=4)
# The function calls logits.max(dim=1)[1] to get predictions
logits = torch.randn(2, 4)

# Create targets tensor: shape (batch_size=2,)
# The function compares predictions with targets and computes accuracy
targets = torch.tensor([0, 2])

ARGS = {
    "logits": logits,
    "targets": targets,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float, ndim 0, dtype family float, shape () — shape () 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: none by the harness; any seed is in the setup block
compute_loss Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
chs20/robustvlm/train/adversarial_training_clip.py
code served (permissive licence) · get_code("75f68885e2ff2684")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 0, dtype family float, shape () 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
import torch.nn.functional as F

torch.manual_seed(0)

# Test case 1: l2 loss
embedding_l2 = torch.randn(2, 4)
embedding_orig_l2 = torch.randn(2, 4)
targets_l2 = torch.tensor([0, 1])
logit_scale_l2 = torch.tensor(1.0)
embedding_text_labels_norm_l2 = None

# Test case 2: ce loss
embedding_ce = torch.randn(2, 5)  # 5 classes
embedding_orig_ce = torch.randn(2, 4)
targets_ce = torch.tensor([0, 1])
logit_scale_ce = torch.tensor(0.1)
embedding_text_labels_norm_ce = torch.randn(5, 4)
embedding_text_labels_norm_ce = F.normalize(embedding_text_labels_norm_ce, dim=1)

ARGS = {
    'loss_str': 'l2',
    'embedding': embedding_l2,
    'targets': targets_l2,
    'embedding_orig': embedding_orig_l2,
    'logit_scale': logit_scale_l2,
    'embedding_text_labels_norm': embedding_text_labels_norm_l2,
    'reduction': 'mean'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
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 0, dtype family float, shape () — shape () 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: none by the harness; any seed is in the setup block
compute_loss Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
chs20/robustvlm/train/adversarial_training_clip.py
code served (permissive licence) · get_code("b03f0274dabbb8c0")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 0, dtype family float, shape () 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
import torch.nn as nn

torch.manual_seed(0)

# For loss_str == 'l2': embedding and embedding_orig must have same shape, batch size > 1
# For loss_str == 'ce': embedding @ (logit_scale * embedding_text_labels_norm) produces logits
#   - embedding shape: (batch, embedding_dim)
#   - embedding_text_labels_norm shape: (num_classes, embedding_dim)
#   - result shape: (batch, num_classes)
#   - targets shape: (batch,) with class indices

batch_size = 2
embedding_dim = 4
num_classes = 3

# Create tensors
embedding = torch.randn(batch_size, embedding_dim)
embedding_orig = torch.randn(batch_size, embedding_dim)
targets = torch.randint(0, num_classes, (batch_size,))
embedding_text_labels_norm = torch.randn(num_classes, embedding_dim)
logit_scale = torch.tensor(1.0)

ARGS = {
    'loss_str': 'l2',
    'embedding': embedding,
    'targets': targets,
    'embedding_orig': embedding_orig,
    'logit_scale': logit_scale,
    'embedding_text_labels_norm': embedding_text_labels_norm,
    'reduction': 'mean'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
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 0, dtype family float, shape () — shape () 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: none by the harness; any seed is in the setup block
get_query_set Ran
ran; our contract draft was wrong, not the code
chs20/robustvlm/vlm_eval/run_evaluation.py
code served (permissive licence) · get_code("68d0f41190a26308")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned list. 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 numpy as np
import torch

# Create a minimal stand-in dataset class
class SimpleDataset:
    def __init__(self, size=10):
        self.data = [(torch.randn(4), torch.randint(0, 2, (1,))) for _ in range(size)]
    
    def __len__(self):
        return len(self.data)
    
    def __getitem__(self, idx):
        return self.data[idx]

# Construct arguments
train_dataset = SimpleDataset(size=10)
query_set_size = 3
seed = 42

ARGS = {
    "train_dataset": train_dataset,
    "query_set_size": query_set_size,
    "seed": seed
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list — a list 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: none by the harness; any seed is in the setup block
get_random_indices Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
chs20/robustvlm/vlm_eval/run_evaluation.py
code served (permissive licence) · get_code("63ec736a72a6cb74")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned ndarray, ndim 1, dtype family int, shape (50,) 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 numpy as np

# Create a small dataset
full_dataset = list(range(100))

# Define arguments
ARGS = {
    'num_samples': 30,
    'query_set_size': 20,
    'full_dataset': full_dataset,
    'seed': 42
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 1, dtype family int, shape (50,) — shape (50,) 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: none by the harness; any seed is in the setup block
pgd Ran
ran; our contract draft was wrong, not the code
chs20/robustvlm/train/adversarial_training_clip.py
code served (permissive licence) · get_code("7062c33b2cc96026")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 2, dtype family float, shape (2, 4) 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
import torch.nn as nn
import torch.nn.functional as F

torch.manual_seed(0)

# Define a simple forward model
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 3)
    
    def forward(self, x, output_normalize=False):
        out = self.linear(x)
        if output_normalize:
            out = F.normalize(out, p=2, dim=1)
        return out

# Define a simple loss function
def loss_fn(output, targets):
    return F.cross_entropy(output, targets)

# Create model and loss function
model = SimpleModel()
forward_fn = model.forward

# Create clean data (batch_size=2, input_dim=4)
# Values in range [0, 1) as required by the function
data_clean = torch.rand(2, 4) * 0.99

# Create targets (batch_size=2, num_classes=3)
targets = torch.tensor([0, 1])

ARGS = {
    'forward': forward_fn,
    'loss_fn': loss_fn,
    'data_clean': data_clean,
    'targets': targets,
    'norm': 'inf',
    'eps': 0.1,
    'iterations': 2,
    'stepsize': 0.01,
    'output_normalize': False,
    'perturbation': None,
    'mode': 'min',
    'momentum': 0.9,
    'verbose': False,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
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 2, dtype family float, shape (2, 4) — shape (2, 4) 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: none by the harness; any seed is in the setup block
train_one_epoch Not yet run
unverified (harvested, no recorded run)
chs20/robustvlm/train/adversarial_training_clip.py
code served (permissive licence) · get_code("1707d13b9dc6cb32")
How it ran

no invocation recorded.

unwrap_model Not yet run
unverified (harvested, no recorded run)
chs20/robustvlm/train/adversarial_training_clip.py
code served (permissive licence) · get_code("04cf221e803c96d7")
How it ran

no invocation recorded.

Also present in other papers' code

Of 9 samples lifted from this paper's linked repositories, 9 carry a function identity and 0 do not. Of the 8 distinct functions with an identity, 4 are also present in other papers whose code we hold (4 with at least one paper dated earlier, 0 the same month, 1 later) and 4 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.

FunctionAlso present inEarliest-datedOthers named
compute_acc
brick of this paper's assembly: metric
2 other papers
1 dated earlier, 1 later
2308.10741 (2023-08)
On the Adversarial Robustness of Multi-Modal Foundation Models
2506.03355 (2025-06)
Robustness in Both Domains: CLIP Needs a Robust Text Encoder
compute_loss
brick of this paper's assembly: loss
1 other paper
1 dated earlier
2308.10741 (2023-08)
On the Adversarial Robustness of Multi-Modal Foundation Models
get_query_set 1 other paper
1 dated earlier
2308.10741 (2023-08)
On the Adversarial Robustness of Multi-Modal Foundation Models
get_random_indices 1 other paper
1 dated earlier
2308.10741 (2023-08)
On the Adversarial Robustness of Multi-Modal Foundation Models

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-22.

Repositories linked to this paper

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

Abstract

Multi-modal foundation models like Open-Flamingo, LLaVA, and GPT-4 are increasingly used for various real-world tasks. Prior work has shown that these models are highly vulnerable to adversarial attacks on the vision modality. These attacks can be leveraged to spread fake information or defraud users, and thus pose a significant risk, which makes the robustness of large multi-modal foundation models a pressing problem. The CLIP model, or one of its variants, is used as a frozen vision encoder in many large vision-language models (LVLMs), e.g. LLaVA and OpenFlamingo. We propose an unsupervised adversarial fine-tuning scheme to obtain a robust CLIP vision encoder, which yields robustness on all vision down-stream tasks (LVLMs, zero-shot classification) that rely on CLIP. In particular, we show that stealth-attacks on users of LVLMs by a malicious third party providing manipulated images are no longer possible once one replaces the original CLIP model with our robust one. No retraining or fine-tuning of the down-stream LVLMs is required. The code and robust models are available on GitHub.

For agents

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

get_harvested_code_for_paper("2402.12336")
get_code_for_paper("2402.12336")
have("2402.12336")

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

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

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

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

Connect an agent — have() is free.