Publish ModernBERT-CNN with concise usage, training details and own evaluation metrics
Browse filesFiles changed (14)
- README.mdAdded+94
- config.jsonAdded+107
- evaluation/human_metrics.jsonAdded+21
- evaluation/modernbert.bertscore.jsonAdded+17
- evaluation/modernbert.coco_metrics.jsonAdded+17
- evaluation/test_scores.metrics.jsonAdded+20
- inference.pyAdded+44
- model.safetensorsAdded+3
- modeling.pyAdded+122
- provenance.jsonAdded+7
- requirements.txtAdded+4
- tokenizer/tokenizer.jsonAdded
- tokenizer/tokenizer_config.jsonAdded+16
- training_config.jsonAdded+27
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394---language: enlibrary_name: pytorchbase_model: answerdotai/ModernBERT-basetags:- modernbert- image-captioning- visual-relatedness- text-classification- custom-code---# ModernBERT-CNN Visual Caption Relatedness
ModernBERT-base with a CNN head that scores the relatedness between **image-contextwords and a candidate caption**. The output is a probability from 0 to 1. Use itto rank candidate captions or assign soft pseudo-labels to context/caption pairs.The model does not read images or generate captions.
## Usage
Install the dependencies from `requirements.txt`, then run:
```pythonfrom huggingface_hub import snapshot_downloadimport sys
path = snapshot_download("AhmedSSabir/modernbert-cnn-visual-relatedness-public")sys.path.insert(0, path)from inference import RelatednessScorer
scorer = RelatednessScorer(path, device="cpu") # use "cuda" for a GPUscores = scorer.score("dog, ball, grass", [ "A dog plays with a ball on the grass.", "A person cooks in a kitchen.",])print(scores)```
This is a custom CNN architecture. Use the included inference helper; thestandard `AutoModel` loader is not configured for this head. Context wordsshould come from the image's detected objects or scene labels.
## Model and training
- Base: `answerdotai/ModernBERT-base`; all 22 encoder layers fine-tuned, embedding parameters frozen.- Sequence length: 64 tokens for the combined context/caption input.- Head: 32 convolution filters, kernel width 3, ReLU, local max pooling, time-major flattening, sigmoid score.- Training: 330,790 pairs; validation: 41,275 pairs. Adam, learning rate 1e-5, batch size 16, seed 42; BF16/TF32 and compilation used during training.- Early stopping after three epochs; **best validation checkpoint: epoch 1**, validation loss 0.256281. Base revision and full settings are in `training_config.json`.
## Evaluation
Caption reranking: **45,000 candidates, nine per image, over 5,000 images**.Select the highest model score per image, with the earliest candidate winningties. No reference-based tuning was performed.
| Metric | Score || --- | ---: || BLEU-4 | 0.329180 || METEOR | 0.271592 || ROUGE-L | 0.552392 || CIDEr | 1.096723 || SPICE | 0.205827 || BERTScore F1 | 0.939820 |
COCO metrics use Stanford PTB tokenization and pycocoevalcap 1.2. BERTScoreuses RoBERTa-large layer 17, slow tokenization, no IDF or baseline rescaling,and all available raw reference captions. Exact metric configurations, packageversions and evaluated-input hashes are included in `evaluation/`.
Additional tests:
- **41,849 held-out pseudo-labeled pairs:** accuracy 0.890893, F1 0.904035, ROC-AUC 0.961563.- **5,822 Flickr8K expert-rated pairs / 1,000 images:** Spearman 0.293677, Kendall tau-b 0.212962 using fixed combined image-derived textual context.
## Limitations
Training labels derive from semantic similarity scores thresholded at 0.3;they are not human judgments. Output probabilities are not calibrated humanquality ratings, and human-rating agreement is modest. Object extractionerrors, truncated inputs and domain shift affect results. Evaluation is fromone training seed, and the derived training split and visual extractionpipeline differ from the historical experiment in the associated[dataset paper](https://arxiv.org/abs/2301.08784).
The repository includes inference-only weights, tokenizer, model/inferencecode, training settings, and this model's aggregate evaluation results.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107{ "architectures": [ "VisualRelatednessModel" ], "model_type": "modernbert-cnn-relatedness", "bert_config": { "pad_token_id": 50283, "bos_token_id": 50281, "eos_token_id": 50282, "cls_token_id": 50281, "sep_token_id": 50282, "tie_word_embeddings": true, "vocab_size": 50368, "max_position_embeddings": 8192, "hidden_size": 768, "intermediate_size": 1152, "num_hidden_layers": 22, "num_attention_heads": 12, "initializer_range": 0.02, "initializer_cutoff_factor": 2.0, "norm_eps": 1e-05, "norm_bias": false, "attention_bias": false, "attention_dropout": 0.0, "hidden_activation": "gelu", "local_attention": 128, "embedding_dropout": 0.0, "mlp_bias": false, "mlp_dropout": 0.0, "decoder_bias": true, "classifier_pooling": "mean", "classifier_dropout": 0.0, "classifier_bias": false, "classifier_activation": "gelu", "deterministic_flash_attn": false, "sparse_prediction": false, "sparse_pred_ignore_index": -100, "layer_types": [ "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention" ], "global_attn_every_n_layers": 3, "rope_parameters": { "sliding_attention": { "rope_type": "default", "rope_theta": 10000.0 }, "full_attention": { "rope_type": "default", "rope_theta": 160000.0 } }, "return_dict": true, "output_hidden_states": false, "dtype": "float32", "chunk_size_feed_forward": 0, "is_encoder_decoder": false, "architectures": [ "ModernBertForMaskedLM" ], "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "problem_type": null, "_name_or_path": "answerdotai/ModernBERT-base", "transformers_version": "5.3.0", "gradient_checkpointing": false, "layer_norm_eps": 1e-05, "model_type": "modernbert", "position_embedding_type": "absolute", "output_attentions": false }, "model_options": { "architecture": "modernbert-cnn", "seq_len": 64, "cnn_filters": 32, "cnn_kernel_size": 3, "num_bert_layers": 22, "tune_embeddings": false }, "best_validation_loss": 0.2562806813490731}123456789101112131415161718192021{ "dataset": "Original Flickr8K ExpertAnnotations.txt", "pairs": 5822, "images": 1000, "checkpoint_sha256": "13502ce4a3578a94effd914525935a2978facd1c7cb243526c3161cbd12db5c2", "metrics": { "examples": 5822, "spearman": 0.2936773447142244, "kendall_tau_b": 0.21296227698549494, "kendall_tau_c": 0.2081649490635248, "pearson": 0.37538085539793303, "normalized_human_mae": 0.22123509002405464, "empty_image_contexts": 0 }, "protocol": "Original mean human ratings; three fixed image-only context policies; no tuning on human ratings", "limitations": [ "Visual extractors differ from training-data extraction; not original-paper replication", "Normalized-human MAE is descriptive; binary-trained outputs are not calibrated human ratings", "Image-context ablations share test data and are not independent validation sets" ]}1234567891011121314151617{ "predictions_sha256": "8add6269339d94f5abb0542bb64c304feb4584b01708ae8a945e14a1606ac234", "references_sha256": "14ebad0ef1a546782a6a77d533c413e8a46ae179d7476872da91edb03c67d38d", "bertscore_hash": "roberta-large_L17_no-idf_version=0.3.12(hug_trans=5.3.0)", "images": 5000, "metrics": { "precision": 0.9421024364829064, "recall": 0.9399086234927178, "f1": 0.9398203430771828 }, "protocol": "Raw captions, all available references (at least five), max over references, RoBERTa-large layer 17, no IDF, no rescaling, slow tokenizer", "packages": { "bert-score": "0.3.13", "transformers": "5.3.0", "torch": "2.6.0" }}1234567891011121314151617{ "images": 5000, "metrics": { "BLEU_1": 0.7475716038854183, "BLEU_2": 0.581953053117491, "BLEU_3": 0.43965763874399744, "BLEU_4": 0.3291800364936827, "METEOR": 0.2715918036531294, "ROUGE_L": 0.5523921179429304, "CIDEr": 1.0967225482924987, "SPICE": 0.20582728578589596 }, "predictions_sha256": "8add6269339d94f5abb0542bb64c304feb4584b01708ae8a945e14a1606ac234", "references_sha256": "14ebad0ef1a546782a6a77d533c413e8a46ae179d7476872da91edb03c67d38d", "tokenizer": "COCO Stanford PTBTokenizer", "prediction_file": "captions.json"}1234567891011121314151617181920{ "examples": 41849, "accuracy": 0.890893450261655, "precision": 0.9029725417751281, "recall": 0.9051005807591953, "f1": 0.9040353089533417, "roc_auc": 0.9615626055488327, "binary_cross_entropy": 0.2513202982970983, "threshold": 0.5, "confusion_matrix": [ [ 15776, 2311 ], [ 2255, 21507 ] ]}1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Inference for exported BERT-CNN and ModernBERT-CNN relatedness models."""import jsonfrom pathlib import Path
import torchfrom safetensors.torch import load_filefrom transformers import AutoTokenizer
from modeling import VisualRelatednessModel, backbone_config_from_dict
class RelatednessScorer: def __init__(self, model_path, device="cpu"): path = Path(model_path) if not path.is_dir(): from huggingface_hub import snapshot_download path = Path(snapshot_download(str(model_path), allow_patterns=["config.json", "model.safetensors", "tokenizer/*"])) config = json.loads((path / "config.json").read_text()) self.device = torch.device(device) self.model = VisualRelatednessModel(backbone_config_from_dict(config["bert_config"]), **config["model_options"]) self.model.load_state_dict(load_file(str(path / "model.safetensors"))) self.model.to(self.device).eval() self.tokenizer = AutoTokenizer.from_pretrained(path / "tokenizer", local_files_only=True, use_fast=True) self.tokenizer.padding_side = "right" self.seq_len = config["model_options"]["seq_len"]
@torch.inference_mode() def score(self, visual_context, captions, batch_size=16): if not isinstance(visual_context, str) or not visual_context.strip(): raise ValueError("Provide image-context words, such as dog, ball, grass") if not captions or any(not isinstance(c, str) or not c.strip() for c in captions): raise ValueError("Provide at least one nonempty caption") if batch_size < 1: raise ValueError("batch_size must be positive") scores = [] for start in range(0, len(captions), batch_size): selected = captions[start:start + batch_size] batch = self.tokenizer([visual_context] * len(selected), selected, padding="max_length", truncation="longest_first", max_length=self.seq_len, return_tensors="pt").to(self.device) scores.extend(self.model.probabilities(self.model(**batch)).float().cpu().tolist()) if not all(0 <= score <= 1 for score in scores): raise RuntimeError("Model produced invalid scores") return scores123version https://git-lfs.github.com/spec/v1oid sha256:8911f0618f9b9a3f66ae5630343c49b4ba2dd5df0e4f4317ec7bd110b6603c76size 596370156123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""Original BERT heads/masking and explicit ModernBERT comparison variants."""
import torchfrom torch import nnfrom transformers import BertConfig, BertModel, ModernBertConfig, ModernBertModel, ModernBertForSequenceClassification
def backbone_config_from_dict(values): kind = values.get("model_type", "bert") classes = {"bert": BertConfig, "modernbert": ModernBertConfig} if kind not in classes: raise ValueError(f"Unsupported checkpoint backbone: {kind}") return classes[kind].from_dict(values)
class VisualRelatednessModel(nn.Module): def __init__(self, bert_config, architecture="bert-cnn", seq_len=64, cnn_filters=32, cnn_kernel_size=3, num_bert_layers=None, tune_embeddings=None, backbone=None): super().__init__() if architecture not in {"bert", "bert-cnn", "modernbert", "modernbert-cnn"}: raise ValueError("Unsupported model architecture") modern = architecture.startswith("modernbert") if modern != (bert_config.model_type == "modernbert"): raise ValueError("Architecture and pretrained backbone type do not match") if not 3 <= seq_len <= bert_config.max_position_embeddings: raise ValueError("seq_len must be between 3 and BERT's positional embedding limit") layers = bert_config.num_hidden_layers if num_bert_layers is None else num_bert_layers if not 0 <= layers <= bert_config.num_hidden_layers: raise ValueError("num_bert_layers is outside this BERT model's layer range") if cnn_filters < 1 or cnn_kernel_size < 1: raise ValueError("CNN filter count and kernel size must be positive") self.options = dict(architecture=architecture, seq_len=seq_len, cnn_filters=cnn_filters, cnn_kernel_size=cnn_kernel_size, num_bert_layers=layers, tune_embeddings=architecture in {"bert", "modernbert"} if tune_embeddings is None else tune_embeddings) if modern: # Let the outer training loop control compilation explicitly. bert_config.reference_compile = False bert_config._attn_implementation = "sdpa" model_class = ModernBertForSequenceClassification if architecture == "modernbert" else ModernBertModel self.bert = backbone if backbone is not None else model_class(bert_config) else: self.bert = backbone if backbone is not None else BertModel( bert_config, add_pooling_layer=architecture == "bert") hidden = bert_config.hidden_size if architecture == "bert": self.dropout = nn.Dropout(.1) self.classifier = nn.Linear(hidden, 2) nn.init.normal_(self.classifier.weight, std=.02) nn.init.zeros_(self.classifier.bias) elif architecture != "modernbert": pooled_length = (seq_len - cnn_kernel_size + 1) // 2 if pooled_length < 1: raise ValueError("seq_len must be at least cnn_kernel_size + 1") self.conv = nn.Conv1d(hidden, cnn_filters, cnn_kernel_size) self.pool = nn.MaxPool1d(2, stride=2) self.classifier = nn.Linear(pooled_length * cnn_filters, 1) # Keras Glorot initialization for the original CNN and dense head. nn.init.xavier_uniform_(self.conv.weight) nn.init.zeros_(self.conv.bias) nn.init.xavier_uniform_(self.classifier.weight) nn.init.zeros_(self.classifier.bias) self.configure_finetuning()
@classmethod def from_pretrained(cls, source, revision=None, **options): architecture = options.get("architecture", "bert-cnn") if architecture.startswith("modernbert"): model_class = ModernBertForSequenceClassification if architecture == "modernbert" else ModernBertModel extra = {"num_labels": 2} if architecture == "modernbert" else {} bert = model_class.from_pretrained(source, revision=revision, reference_compile=False, attn_implementation="sdpa", **extra) else: bert = BertModel.from_pretrained(source, revision=revision, add_pooling_layer=architecture == "bert") return cls(bert.config, backbone=bert, **options)
def configure_finetuning(self): self.bert.requires_grad_(False) modern = self.options["architecture"].startswith("modernbert") encoder = self.bert.model if self.options["architecture"] == "modernbert" else self.bert if self.options["tune_embeddings"]: encoder.embeddings.requires_grad_(True) count = self.options["num_bert_layers"] if count: layers = encoder.layers if modern else encoder.encoder.layer for layer in layers[-count:]: layer.requires_grad_(True) if modern: encoder.final_norm.requires_grad_(True) if self.options["architecture"] == "modernbert": self.bert.head.requires_grad_(True) self.bert.classifier.requires_grad_(True) if self.options["architecture"] == "bert" and self.bert.pooler is not None: self.bert.pooler.requires_grad_(True)
def forward(self, input_ids, attention_mask, token_type_ids=None): if self.options["architecture"].startswith("modernbert"): output = self.bert(input_ids=input_ids, attention_mask=attention_mask, return_dict=True) if self.options["architecture"] == "modernbert": return output.logits else: output = self.bert(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, return_dict=True) if self.options["architecture"] == "bert": return self.classifier(self.dropout(output.pooler_output)) if input_ids.shape[1] != self.options["seq_len"]: raise ValueError("BERT-CNN requires fixed padding to the checkpoint's seq_len") # The old BertLayer zeroed padded token vectors BEFORE the convolution. sequence = output.last_hidden_state * attention_mask.unsqueeze(-1).to(output.last_hidden_state.dtype) pooled = self.pool(torch.relu(self.conv(sequence.transpose(1, 2)))) # Keras Flatten traverses time then filters, rather than filters then time. flat = pooled.transpose(1, 2).contiguous().flatten(1) return self.classifier(flat).squeeze(-1)
def probabilities(self, logits): return logits.softmax(-1)[:, 1] if self.options["architecture"] in {"bert", "modernbert"} else logits.sigmoid()
def loss(self, logits, labels): if self.options["architecture"] in {"bert", "modernbert"}: return nn.functional.cross_entropy(logits, labels.long()) return nn.functional.binary_cross_entropy_with_logits(logits, labels.float())1234567{ "source_checkpoint_sha256": "13502ce4a3578a94effd914525935a2978facd1c7cb243526c3161cbd12db5c2", "model_safetensors_sha256": "8911f0618f9b9a3f66ae5630343c49b4ba2dd5df0e4f4317ec7bd110b6603c76", "architecture": "modernbert-cnn", "best_epoch": 1, "weights_format": "Inference-only safetensors"}1234torch>=2.6,<3transformers==5.3.0safetensors>=0.4huggingface_hub>=1,<212345678910111213141516{ "backend": "tokenizers", "clean_up_tokenization_spaces": true, "cls_token": "[CLS]", "is_local": true, "mask_token": "[MASK]", "model_input_names": [ "input_ids", "attention_mask" ], "model_max_length": 8192, "pad_token": "[PAD]", "sep_token": "[SEP]", "tokenizer_class": "TokenizersBackend", "unk_token": "[UNK]"}123456789101112131415161718192021222324252627{ "base_model": "answerdotai/ModernBERT-base", "base_revision": "8949b909ec900327062f0ebf497f51aef5e6f0c8", "architecture": "modernbert-cnn", "sequence_length": 64, "encoder_layers_tuned": 22, "embeddings_frozen": true, "cnn_filters": 32, "cnn_kernel": 3, "training_pairs": 330790, "validation_pairs": 41275, "test_pairs": 41849, "optimizer": "Adam", "learning_rate": 1e-05, "batch_size": 16, "seed": 42, "warmup_ratio": 0.1, "max_epochs": 5, "completed_epochs": 3, "early_stopping_patience": 2, "exported_best_epoch": 1, "best_validation_loss": 0.2562806813490731, "precision": "bf16", "tf32": true, "torch_compile": true, "split": "Connected components of image IDs and normalized unordered pairs"}README.mdAdded+94
config.jsonAdded+107
evaluation/human_metrics.jsonAdded+21
evaluation/modernbert.bertscore.jsonAdded+17
evaluation/modernbert.coco_metrics.jsonAdded+17
evaluation/test_scores.metrics.jsonAdded+20
inference.pyAdded+44
model.safetensorsAdded+3
modeling.pyAdded+122
provenance.jsonAdded+7
requirements.txtAdded+4
tokenizer/tokenizer.jsonAdded
tokenizer/tokenizer_config.jsonAdded+16
training_config.jsonAdded+27