Run this model with HF Jobs

Run mahiyama/Sazanami-ColBERT-310m on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/mahiyama/Sazanami-ColBERT-310m. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/mahiyama/Sazanami-ColBERT-310m on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Sazanami-ColBERT-310m

English | 日本語

A Japanese late-interaction retrieval model trained from sbintuitions/modernbert-ja-310m. It encodes queries and documents each into a sequence of token-level vectors, and computes similarity with MaxSim. Because it does not condense documents into a single vector, it can rank documents while preserving matches even when only part of a long document is relevant to the query.

Among four retrieval approaches trained on the same base model and the same training data, this corresponds to the configuration that does not compress documents. The two models with reduced document representations and the single-vector model were all trained separately under the same conditions.

1. Model Overview

Property Value
Base model sbintuitions/modernbert-ja-310m
Architecture Transformer → token-level linear projection (768 → 128, no bias) → exclusion of padding positions → token-level L2 normalization
Parameters About 315M (98,304 for the projection layer)
Vector dimensions 128
Number of vectors per document Equal to the number of non-padding tokens. Varies with document length, averaging 100.5 on JaGovFaqs-22k and 741.4 on Jaqket
Recommended input length 256 tokens for queries / 1,024 tokens for documents (defaults stored in the model; maximum is 8,192)
Scoring function MaxSim (sum over query tokens of the maximum similarity)
Prefix 検索クエリ: ("search query: ") for queries, 検索文書: ("search document: ") for documents
Tokenizer SentencePiece (uses the ModernBERT-Ja vocabulary as-is)
Main framework sentence-transformers 6.0.0 or later (MultiVectorEncoder)
Mixed precision during training bf16

Related Models

All four models were trained from sbintuitions/modernbert-ja-310m on the same training data. What differs is how many vectors represent a single document. Sazanami-Embed-310m is a single-vector model, trained under the same conditions for comparison.

Model Vectors per document When to choose
Sazanami-ColBERT-310m (this model) Same as the number of non-padding tokens in the text Highest accuracy when searching for long documents among many candidates
Sazanami-AGC-310m Up to 32 When you want to reduce storage size
Sazanami-MetaEmbed-310m Up to 64 (the number used can be reduced) When you want faster similarity computation
Sazanami-Embed-310m 1 (768 dimensions) Single-vector. When you want to minimize storage size and computational cost

2. Underlying Research

Late interaction is a retrieval method that encodes queries and documents separately and matches them token by token only during similarity computation. It was introduced in ColBERT (Khattab and Zaharia, 2020). Because document encoding can be done in advance, it is faster than cross-encoders that read queries and documents together, and it preserves finer-grained matches than bi-encoders that condense documents into a single vector.

The score is MaxSim. For each query token, the maximum similarity with any document token is computed, and these are summed across all query tokens. Even when only part of a document is relevant to the query, the match in that part is reflected in the score.

MaxSim(q,d)=∑imax⁡j  qi⋅dj \text{MaxSim}(q, d) = \sum_{i} \max_{j} \; q_i \cdot d_j

The idea of training using teacher model scores is similar to ColBERTv2 (Santhanam et al., 2022). On the other hand, this model differs from the implementation in the original ColBERT paper in the following ways.

  • It does not use query augmentation by padding with [MASK]. The original paper pads queries with [MASK] up to a fixed length to increase the targets for similarity computation, but this model uses only non-padding tokens.
  • It does not include processing to exclude punctuation. While the original paper's implementation excludes punctuation tokens from similarity computation, this model does not exclude them.

The base model is ModernBERT-Ja, a ModernBERT model pre-trained on Japanese. With a positional embedding limit of 8,192 tokens, it can process long documents as they are.

3. Usage

Load the model with MultiVectorEncoder in sentence-transformers 6.0.0 or later.

from sentence_transformers import MultiVectorEncoder

model = MultiVectorEncoder("mahiyama/Sazanami-ColBERT-310m")

# Queries: "Where can I get a certificate of residence?", "I want to know the enrollment procedure for National Health Insurance"
queries = [
    "住民票はどこで取れますか",
    "国民健康保険の加入手続きを知りたい",
]
# Documents: on obtaining a certificate of residence, National Health Insurance enrollment, and oversized garbage collection
documents = [
    "住民票の写しは、市区町村の窓口またはコンビニ交付サービスで取得できます。",
    "国民健康保険の加入手続きは、転入や退職から 14 日以内に市区町村の窓口で行ってください。",
    "粗大ごみの収集は、事前の申し込みが必要です。",
]

# Prefixes are stored in the model and do not need to be added to the text
query_vectors = model.encode_query(queries)
document_vectors = model.encode_document(documents)

# Scored with MaxSim according to the stored settings
scores = model.similarity(query_vectors, document_vectors)
print(scores)

4. Training

Base Model

The model is initialized with sbintuitions/modernbert-ja-310m. It has undergone only masked language modeling pre-training and has not been trained for retrieval. Upon loading, the pooling layer is removed, and a token-level linear projection (768 → 128), exclusion of padding positions, and token-level L2 normalization are attached. The projection layer is newly initialized.

Training Data

Two formats were used: n-tuples, pairing one query with one positive and five negatives, and pairs, pairing queries with only a positive.

Source Format Count
mahiyama/auto-wiki-qa n-tuples 100,000
mahiyama/mqa-ja n-tuples 100,000
mahiyama/mmarco-ja n-tuples 50,000
mahiyama/civicqa-ja (non-public) n-tuples 43,382
mahiyama/quiz-no-mori n-tuples 13,422
mahiyama/quiz-works n-tuples 12,502
mahiyama/amagasaki-qna n-tuples 11,069
mahiyama/miracl-retrieval n-tuples 4,603
mahiyama/mrtydi n-tuples 3,602
mahiyama/anlp-meeting-retrieval (title-abs) n-tuples 1,926
mahiyama/anlp-meeting-retrieval (title-intro) n-tuples 1,952
mahiyama/civicqa-ja (non-public) pairs 28,653
mahiyama/amagasaki-qna pairs 7,323
mahiyama/kosodate-faq-pairs-ja pairs 595
Total 379,029

mahiyama/civicqa-ja consists of questions and answers collected from FAQs published by Japanese government agencies and local governments. It is currently non-public.

Data used for evaluation was excluded from training. JaGovFaqs-22k was not used in training at all. Rows where the query after NFKC normalization and whitespace removal matched a query in the evaluation split of JaGovFaqs-22k, or where the positive after the same processing matched a document in that evaluation split, were excluded at each stage.

Training Procedure

For n-tuples, the sum of a contrastive loss and a distillation loss is used. Both are computed from a single score computation. Because using two built-in losses together would encode the same documents twice, they are combined into a single loss.

  • Contrastive loss — Cross-entropy with all documents in the batch (its own 6 candidates and documents from other rows in the same batch) as candidates.
  • Distillation loss — KL divergence between the probability distribution of MaxSim scores over its own 6 candidates and the probability distribution of teacher scores. The teacher temperature is 2.0 and the student temperature is 1.0.

For pairs, a contrastive loss is used with documents from other rows in the batch as negatives.

Setting Value
learning_rate (Transformer) 2e-5
learning_rate (projection layer) 1e-4
num_train_epochs 1
per_device_train_batch_size 64
lr_scheduler_type linear
warmup_steps 5% of total
weight_decay 0.01
Input length during training 128 tokens for queries / 512 tokens for documents
Mixed precision bf16
batch_sampler NO_DUPLICATES
Gradient checkpointing Enabled
Teacher temperature / student temperature 2.0 / 1.0
Random seed 42

Training took about 6 hours 18 minutes (5,923 steps) on a single NVIDIA A100 (40 GB) GPU, with peak GPU memory usage of 21.6 GB.

5. Training Code with Sentence Transformers

Load the initial model with MultiVectorEncoder, define a loss using MaxSim, and pass it to MultiVectorEncoderTrainer. The construction of train_dataset is not included.

import torch
import torch.nn.functional as F
from torch import nn
from sentence_transformers import (
    MultiVectorEncoder,
    MultiVectorEncoderTrainer,
    MultiVectorEncoderTrainingArguments,
)
from sentence_transformers.base.losses.merged_forward import embed_columns_padded
from sentence_transformers.base.sampler import BatchSamplers
from sentence_transformers.multi_vector_encoder.scoring import colbert_scores
from sentence_transformers.util import stack_padded_token_embeddings

QUERY_PREFIX = "検索クエリ: "
DOCUMENT_PREFIX = "検索文書: "


class ContrastiveDistillLoss(nn.Module):
    """Loss that computes the contrastive loss and the distillation of teacher scores from a single MaxSim computation.

    Input: Features of queries and candidate documents, teacher scores (batch size, number of candidates)
    Output: Sum of contrastive loss and distillation loss (scalar)
    """

    def __init__(self, model, teacher_temperature=2.0, student_temperature=1.0):
        super().__init__()
        self.model = model
        self.teacher_temperature = teacher_temperature
        self.student_temperature = student_temperature
        self.kl = nn.KLDivLoss(reduction="batchmean", log_target=True)

    def forward(self, sentence_features, labels):
        sentence_features = list(sentence_features)

        # Encode queries. Padding positions are excluded from the MaxSim sum.
        query_features = sentence_features[0]
        query_outputs = self.model(query_features, task="query")
        queries = query_outputs["token_embeddings"]
        query_mask = query_outputs["attention_mask"].bool()

        # Encode document columns together and stack into (batch size, number of candidates, number of tokens, dimensions).
        doc_embeddings, doc_masks = embed_columns_padded(
            self.model, sentence_features[1:], None, task_default="document"
        )
        docs, docs_mask = stack_padded_token_embeddings(doc_embeddings, doc_masks)

        # Create MaxSim score matrix against all documents in the batch, and compute contrastive loss.
        scores = colbert_scores(queries, docs, queries_mask=query_mask, documents_mask=docs_mask)
        batch_size = queries.size(0)
        n_ways = len(sentence_features) - 1
        targets = torch.arange(batch_size, device=scores.device) * n_ways
        contrastive = F.cross_entropy(scores, targets)

        # Extract own candidates and compute KL divergence against the teacher distribution.
        rows = torch.arange(batch_size)
        own = scores.view(batch_size, batch_size, n_ways)[rows, rows]
        student = F.log_softmax(own / self.student_temperature, dim=-1)
        teacher = F.log_softmax(labels.detach().float() / self.teacher_temperature, dim=-1)
        distill = self.kl(student, teacher) * (self.student_temperature**2)

        return contrastive + distill


# Load initial checkpoint. Pooling layer is removed, and projection and normalization layers are newly added.
model = MultiVectorEncoder(
    "sbintuitions/modernbert-ja-310m",
    prompts={"query": QUERY_PREFIX, "document": DOCUMENT_PREFIX},
    model_kwargs={"torch_dtype": torch.float32},
    similarity_fn_name="maxsim",
)

# Set here the input lengths to use for inference after saving.
model[0].query_length = 256
model[0].document_length = 1024

# Enable gradient checkpointing directly on the Transformer, not via training arguments.
model[0].auto_model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})

# Prefixes during training must be specified for each column name.
prompts = {"query": QUERY_PREFIX, "positive": DOCUMENT_PREFIX}
prompts.update({f"negative_{i}": DOCUMENT_PREFIX for i in range(1, 6)})

training_args = MultiVectorEncoderTrainingArguments(
    output_dir="runs/sazanami-colbert",
    num_train_epochs=1,
    per_device_train_batch_size=64,
    learning_rate=2e-5,
    learning_rate_mapping={r"\.1\.linear\.": 1e-4},   # Increase learning rate only for the projection layer
    warmup_steps=0.05,                               # Pass ratio as float
    lr_scheduler_type="linear",
    weight_decay=0.01,
    bf16=True,
    batch_sampler=BatchSamplers.NO_DUPLICATES,
    prompts=prompts,
    max_length={"query": 128, "document": 512},
    seed=42,
)

trainer = MultiVectorEncoderTrainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,                     # Dataset with query, positive, negative_1..5, label
    loss=ContrastiveDistillLoss(model),
)
trainer.train()
model.save_pretrained("runs/sazanami-colbert/final")

The following three points are behaviors observed with sentence-transformers 6.1.0 and transformers 5.16.1.

  • Prefixes during training are not added automatically. Because the prompts stored in the model are used only at inference, training will proceed without prefixes unless specified per column using MultiVectorEncoderTrainingArguments(prompts={column_name: prefix}).
  • Passing gradient_checkpointing=True to the training arguments fails. Because argument passing does not align properly, model[0].auto_model.gradient_checkpointing_enable(...) is called directly. Without this, memory will be insufficient for a batch of 64 × 6 documents × 512 tokens.
  • warmup_ratio cannot be used. Pass the ratio as a float to warmup_steps.

6. Evaluation Results

Among the 11 Retrieval tasks included in JMTEB(v2) in MTEB 2.21.8, three tasks differing in document length and candidate count were evaluated. The metric is NDCG@10. The setting uses 1,024 tokens for documents and 256 tokens for queries.

Benchmark Size

Number of documents, queries, and document lengths for the three tasks.

Task Documents Queries Avg. document tokens
Mintaka 1,592 2,312 10.0
JaGovFaqs 22,794 2,048 100.5
Jaqket 114,229 997 741.4

Average document tokens is the value calculated from the number of vectors actually generated by Sazanami-ColBERT-310m, which retains all tokens (1 vector = 1 token). It was measured with documents set to 1,024 tokens.

Retrieval Accuracy

Model Mintaka JaGovFaqs Jaqket
Sazanami-ColBERT-310m (this model) 0.18070 0.77986 0.77868
Sazanami-AGC-310m 0.17302 0.78513 0.72986
Sazanami-MetaEmbed-310m 0.22697 0.79316 0.72855
Sazanami-Embed-310m 0.21771 0.78883 0.69682

Storage Size and Similarity Computation Time

These are measured values on Jaqket with 114,229 documents. Documents were set to 1,024 tokens. Encoding is the process of converting document text into vectors, and is the total time to process all documents divided by 114,229 (as it is a batch process when building the index, it is averaged over GPU batch processing). Similarity computation time is the total time to process all 997 evaluation queries divided by 997.

Model Vectors per document Dimensions Storage ratio Encoding per document Similarity computation per query
Sazanami-ColBERT-310m (this model) 741.4 128 1 11.57 ms 43.03 ms
Sazanami-AGC-310m 32.0 128 About 1/23 12.22 ms 4.01 ms
Sazanami-MetaEmbed-310m 64.0 128 About 1/12 12.56 ms 0.70 ms
Sazanami-Embed-310m 1.0 768 About 1/124 12.83 ms 0.90 ms

7. Discussion of the Results

  • The longer the documents and the more candidates there are, the greater the advantage of this model. On Jaqket, with an average document length of 741 tokens and 114,229 documents, NDCG@10 is 0.049 higher than Sazanami-AGC-310m, 0.050 higher than Sazanami-MetaEmbed-310m, and 0.082 higher than Sazanami-Embed-310m. This can be interpreted as MaxSim, which preserves token-level matches, being advantageous when the parts relevant to the query are in only a portion of the document.
  • On tasks with short documents, the other approaches outperform it. On JaGovFaqs, where documents average 100 tokens, Sazanami-MetaEmbed-310m is 0.013 higher and Sazanami-Embed-310m is 0.009 higher. On Mintaka, where documents average 10 tokens, Sazanami-MetaEmbed-310m is 0.046 higher and Sazanami-Embed-310m is 0.037 higher. The results do not show that using multi-vector representations always leads to higher accuracy.

8. License and Training Data Restrictions

The model weights are released under the MIT License. The base model, sbintuitions/modernbert-ja-310m, is also released under the MIT License.

The training data includes a Japanese translation of MS MARCO (mahiyama/mmarco-ja). MS MARCO is released for non-commercial research purposes, and its license for commercial use is not clear. If you use this model commercially, please check the MS MARCO terms of use at your own responsibility.

Part of the training data includes questions and answers collected from FAQs published by Japanese government agencies and local governments. This data is subject to the terms of use of each source and is not redistributed in this model's repository. If you use this model, please determine the suitability for your application at your own responsibility.

Downloads last month
77
Safetensors
Model size
0.3B params
Tensor type
F32
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for mahiyama/Sazanami-ColBERT-310m

Finetuned
(28)
this model

Datasets used to train mahiyama/Sazanami-ColBERT-310m

Collection including mahiyama/Sazanami-ColBERT-310m

Papers for mahiyama/Sazanami-ColBERT-310m