From Distillation to Hard Negative Sampling: Making Sparse Neural IR Models More Effective
Paper • 2205.04733 • Published • 3
How to use yjoonjang/reviewsearch-sparse with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("yjoonjang/reviewsearch-sparse")
sentences = [
"The weather is lovely today.",
"It's so sunny outside!",
"He drove to the stadium."
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [3, 3]This is a Asymmetric Inference-free SPLADE Sparse Encoder model finetuned from opensearch-project/opensearch-neural-sparse-encoding-doc-v3-gte using the sentence-transformers library. It maps sentences & paragraphs to a 30522-dimensional sparse vector space and can be used for semantic search and sparse retrieval.
SparseEncoder(
(0): Router(
default_route='document'
(sub_modules): ModuleDict(
(query): Sequential(
(0): SparseStaticEmbedding({'frozen': False}, dim=30522, tokenizer=DistilBertTokenizer)
)
(document): Sequential(
(0): Transformer({'transformer_task': 'fill-mask', 'modality_config': {'text': {'method': 'forward', 'method_output_name': 'logits'}}, 'module_output_name': 'token_embeddings', 'architecture': 'NewForMaskedLM'})
(1): SpladePooling({'pooling_strategy': 'max', 'activation_function': 'log1p_relu', 'embedding_dimension': 30522})
)
)
)
)
First install the Sentence Transformers library:
pip install -U sentence-transformers
Then you can load this model and run inference.
from sentence_transformers import SparseEncoder
# Download from the 🤗 Hub
model = SparseEncoder("sparse_encoder_model_id")
# Run inference
sentences = [
'video detector frequency bias',
'title: Seeing What Matters: Generalizable AI-generated Video Detection with Forensic-Oriented Augmentation\n\nsummary: Recently, with the rapid development of video generative models, forensic detectors have also emerged; however, many of them lack generalizability. To address this issue, the authors propose a method that first identifies discriminative features that are less biased toward forensic-irrelevant patterns and more robust for detecting generated videos. Based on frequency domain analysis and previous literature, the authors identify that mid-high frequency components are less susceptible to compression artifacts and are thus suitable for forensic detection. To utilize these cues, two novel augmentation strategies are introduced during training: (1) Injection of forensic cues, by reconstructing real videos using the same autoencoder that generated the fake videos, aligning both real and fake samples in the representation space, and (2) Wavelet-based augmentation, by mixing real and fake videos using wavelet decomposition to enhance the mid-high frequency learning and push the detector to focus on those features. In the experimental evaluation, the model was trained using videos generated by the Pyramid Flow model, and testing was performed on both the GenVideo dataset (publicly available) and a newly constructed dataset comprising 2,400 videos from recent generative models. Accuracy was used as the evaluation metric, and the proposed method outperformed recent forensic detection methods.\n\nweaknesses and questions: 1. Quality: \nThe submission is technically sound, presenting a relevant formulation and effective use of forensic feature extraction from videos. The claims are well-supported by experimental results. The methods employed are appropriate, and the work is presented as a complete and cohesive study. The authors are transparent about both the strengths and limitations of their approach.\n\n2. Clarity:\nThe submission is clearly written and easy to follow.\n\n3. Significance:\nThe results are impactful for the community. While the code and new dataset have not been released, if shared, this work has strong potential to be used by other researchers for further development and benchmarking.\n\n4. Originality:\nThe work integrates several ideas from previous methods, with appropriate citations. Although the application of these ideas to video forensics is a novel context, the core techniques themselves are adapted rather than newly proposed. Therefore, the method is not entirely novel in its formulation.\na. In lines 186–193, the authors state that replacing the low-frequency bands with those from the real counterpart forces the detector to focus on mid-high frequency features. However, how can we confidently claim that the detector will focus on mid-high frequencies? It is possible that the detector still learns from the low-frequency content provided by the real counterpart, potentially leading to misleading or incorrect detection. Do the authors have empirical evidence or observations supporting this assumption?\nb. The proposed method appears to heavily rely on the reconstruction quality of the Pyramid Flow model. While the paper mentions that this model generally reconstructs videos without visible artifacts, what happens if it fails in certain cases? Would such failure compromise the robustness or generalizability of the detector trained using this reconstruction-based augmentation?\nc. The paper makes valuable contributions, including a new dataset and a promising method. However, neither the code nor the dataset has been made available. The authors are strongly encouraged to release both the code and dataset to enable transparent evaluation, reproducibility, and faster progress in the rapidly evolving field of forensic video detection.',
'title: FlexEvent: Towards Flexible Event-Frame Object Detection at Varying Operational Frequencies\n\nsummary: This paper proposes a fusion-based object detection pipeline that attempts to promote event+RGB fused object detection at varying frequencies. More specifically, a FlexFuse module is deigned to align the rich semantic information from RGB frames with the high-frequency event data, a FlexTune strategy is proposed to generate frequency-adjusted labels for unlabelled event streams. Experiments on the DSEC datasets demonstrate a superior performance of the proposed method over previous fusion-based methods. Also, the model maintains a robust performance across events of varying frequencies (up to 180 Hz).\n\nweaknesses and questions: Pros:\n- Fusing the complementary advantages of events and RGB images for object detection is a promising direction that can power applications that are sensitive to operational latency, for example, autonomous driving, industrial anomaly detection. In this context, exploring the robust detection across varying event frequencies and pushing its speed upper bound is important.\n- The proposed FlexTune strategy extends the classic pseudo label strategy to the event-RGB fused object detection, where high-frequency events are treated as unlabeled images, and several strategies grounded on the characteristics of events are deaigned to generate pseudo labels to boost the performance across different frequencies. \n- Experiments on the DSEC datasets (Car and Pedestrian classes) demonstrate the significant performance improvements of the proposed method. Meanwhile, the proposed methods maintain robustness across varying frequencies.\n- This paper is overall well-structured and easy to follow.\n\nCons:\nAlthough the task and method sound compelling, I have some major concerns about the data configuration and experimental comparison:\n- The quality of “high-frequency events” and the resulting performance degradation seems to be dependent on the proposed way of generating event frames. Section 3.2 mentions that the event is divided into several sub-intervals and aggregated within each interval to simulate high-frequency scenarios, while this setting may make the definition of high-frequency events problematic. For example, we can simply aggregate information for a longer period for each event aggregation, while still maintaining a low temporal gap between two sampling points. It will be helpful to provide the results on this setting with both high-frequency events and richer semantic information.\n- In the experimental section, this paper didn’t compare with models with solely RGB input. Therefore, it is hard to see the advantages of Event+RGB fusion compared to only using events or RGB frames. Also, it is not clear why only one fusion-based method is compared on the DSEC-Det dataset while more are compared on other datasets. \n- Although three datasets have been used for experiments, results on only 3 classes (Car, Pedestrian L-Veh.) are provided across all these datasets. This makes it hard to verify the methods’ generalization ability across more classes and scenarios, especially considering that pretrained weights are used during experiments.\n- It is not explained why using two significantly different backbones for events (RVT) and RGB frames (ResNet-50). Moreover, both pretrained weights are used for RVT and ResNet50 while it is not clear what are the pretrained datasets and how much they would contribute to the final performance.\nMy major concern is about the configuration of high-frequency events and the fairness of experimental comparison, I could reassess my score if these weaknesses are properly addressed.',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 30522]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[16.0392, 9.8499, 6.5218],
# [ 9.8499, 55.4061, 15.9871],
# [ 6.5218, 15.9871, 58.2849]])
reviewsearchSparseInformationRetrievalEvaluator| Metric | Value |
|---|---|
| dot_accuracy@1 | 0.4016 |
| dot_accuracy@10 | 0.788 |
| dot_precision@10 | 0.216 |
| dot_precision@100 | 0.0602 |
| dot_recall@10 | 0.196 |
| dot_recall@100 | 0.4714 |
| dot_ndcg@10 | 0.285 |
| dot_mrr@10 | 0.5244 |
| dot_map@100 | 0.1886 |
| query_active_dims | 7.1516 |
| query_sparsity_ratio | 0.9998 |
| corpus_active_dims | 902.1273 |
| corpus_sparsity_ratio | 0.9704 |
| avg_flops | 1.6039 |
anchor, positive, negative_1, negative_2, and negative_3| anchor | positive | negative_1 | negative_2 | negative_3 | |
|---|---|---|---|---|---|
| type | string | string | string | string | string |
| modality | text | text | text | text | text |
| details |
|
|
|
|
|
| anchor | positive | negative_1 | negative_2 | negative_3 |
|---|---|---|---|---|
meta-learning unclear contribution |
title: Extending Contextual Self-Modulation: Meta-Learning Across Modalities, Task Dimensionalities, and Data Regimes |
title: Generalizing to Unseen Domains for Regression |
title: The Meta-Representation Hypothesis |
title: Metanetworks as Regulatory Operators: Learning to Edit for Requirement Compliance |
meta-learning scalability benchmarks |
title: Extending Contextual Self-Modulation: Meta-Learning Across Modalities, Task Dimensionalities, and Data Regimes |
title: OPTFM: A Scalable Multi-View Graph Transformer for Hierarchical Pre-Training in Combinatorial Optimization |
title: Large-Scale Pretraining Offers Modest Benefits for Tabular Transfer Learning |
title: Scaling Laws for Pre-training Agents and World Models |
anchor quality upper bounds training |
title: Tournament Style RL: Stabilizing Policy Optimization on Non Verifiable Problems |
title: On Proper Learnability between Average- and Worst-case Robustness |
title: Spectral Perturbation Bounds for Low-Rank Approximation with Applications to Privacy |
title: Utility Boundary of Dataset Distillation: Scaling and Configuration-Coverage Laws |
CachedSpladeLoss with these parameters:{
"loss": "SparseMultipleNegativesRankingLoss(scale=1.0, similarity_fct='dot_score', gather_across_devices=True, directions=('query_to_doc',), partition_mode='joint', hardness_mode=None, hardness_strength=0.0)",
"document_regularizer_weight": 0.003,
"mini_batch_size": 128
}
per_device_train_batch_size: 1024num_train_epochs: 1.0learning_rate: 2e-05warmup_steps: 0.1bf16: Trueeval_on_start: Truerouter_mapping: {'anchor': 'query', 'positive': 'document', 'negative_1': 'document', 'negative_2': 'document', 'negative_3': 'document'}learning_rate_mapping: {'0\.sub_modules\.query\.0\.weight': 0.001}per_device_train_batch_size: 1024num_train_epochs: 1.0max_steps: -1learning_rate: 2e-05lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_steps: 0.1optim: adamw_torch_fusedoptim_args: Noneweight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08optim_target_modules: Nonegradient_accumulation_steps: 1average_tokens_across_devices: Truemax_grad_norm: 1.0label_smoothing_factor: 0.0bf16: Truefp16: Falsebf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonegradient_checkpointing: Falsegradient_checkpointing_kwargs: Nonetorch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Noneuse_liger_kernel: Falseliger_kernel_config: Noneuse_cache: Falseneftune_noise_alpha: Nonetorch_empty_cache_steps: Noneauto_find_batch_size: Falselog_on_each_node: Truelogging_nan_inf_filter: Trueinclude_num_input_tokens_seen: nolog_level: passivelog_level_replica: warningdisable_tqdm: Falseproject: huggingfacetrackio_space_id: Nonetrackio_bucket_id: Nonetrackio_static_space_id: Noneper_device_eval_batch_size: 8prediction_loss_only: Trueeval_on_start: Trueeval_do_concat_batches: Trueeval_use_gather_object: Falseeval_accumulation_steps: Noneinclude_for_metrics: []batch_eval_metrics: Falsesave_only_model: Falsesave_on_each_node: Falseenable_jit_checkpoint: Falsepush_to_hub: Falsehub_private_repo: Nonehub_model_id: Nonehub_strategy: every_savehub_always_push: Falsehub_revision: Noneload_best_model_at_end: Falseignore_data_skip: Falserestore_callback_states_from_checkpoint: Falsefull_determinism: Falseseed: 42data_seed: Noneuse_cpu: Falseaccelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}parallelism_config: Nonedataloader_drop_last: Truedataloader_num_workers: 0dataloader_pin_memory: Truedataloader_persistent_workers: Falsedataloader_prefetch_factor: Noneremove_unused_columns: Truelabel_names: Nonetrain_sampling_strategy: randomlength_column_name: lengthddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falseddp_static_graph: Noneddp_backend: Noneddp_timeout: 1800fsdp: Nonefsdp_config: Nonedeepspeed: Nonedebug: []skip_memory_metrics: Truedo_predict: Falseresume_from_checkpoint: Nonewarmup_ratio: Nonelocal_rank: -1prompts: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: proportionalrouter_mapping: {'anchor': 'query', 'positive': 'document', 'negative_1': 'document', 'negative_2': 'document', 'negative_3': 'document'}learning_rate_mapping: {'0\.sub_modules\.query\.0\.weight': 0.001}| Epoch | Step | Training Loss | reviewsearch_dot_ndcg@10 |
|---|---|---|---|
| 0 | 0 | - | 0.2377 |
| 0.0909 | 2 | 1.7752 | - |
| 0.1818 | 4 | 1.6872 | - |
| 0.2727 | 6 | 1.4462 | 0.2689 |
| 0.3636 | 8 | 1.3025 | - |
| 0.4545 | 10 | 1.2209 | - |
| 0.5455 | 12 | 1.1711 | 0.2882 |
| 0.6364 | 14 | 1.1102 | - |
| 0.7273 | 16 | 1.1213 | - |
| 0.8182 | 18 | 1.0570 | 0.2865 |
| 0.9091 | 20 | 1.0478 | - |
| 1.0 | 22 | 1.0844 | 0.2850 |
@inproceedings{reimers-2019-sentence-bert,
title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
author = "Reimers, Nils and Gurevych, Iryna",
booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
month = "11",
year = "2019",
publisher = "Association for Computational Linguistics",
url = "https://arxiv.org/abs/1908.10084",
}
@misc{gao2021scaling,
title={Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup},
author={Luyu Gao and Yunyi Zhang and Jiawei Han and Jamie Callan},
year={2021},
eprint={2101.06983},
archivePrefix={arXiv},
primaryClass={cs.LG}
}
@misc{formal2022distillationhardnegativesampling,
title={From Distillation to Hard Negative Sampling: Making Sparse Neural IR Models More Effective},
author={Thibault Formal and Carlos Lassance and Benjamin Piwowarski and St\'ephane Clinchant},
year={2022},
eprint={2205.04733},
archivePrefix={arXiv},
primaryClass={cs.IR},
}
@misc{oord2019representationlearningcontrastivepredictive,
title={Representation Learning with Contrastive Predictive Coding},
author={Aaron van den Oord and Yazhe Li and Oriol Vinyals},
year={2019},
eprint={1807.03748},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/1807.03748},
}
@article{paria2020minimizing,
title={Minimizing flops to learn efficient sparse representations},
author={Paria, Biswajit and Yeh, Chih-Kuan and Yen, Ian EH and Xu, Ning and Ravikumar, Pradeep and P{'o}czos, Barnab{'a}s},
journal={arXiv preprint arXiv:2004.05665},
year={2020}
}