SentenceTransformer based on sentence-transformers/all-MiniLM-L6-v2
This is a sentence-transformers model finetuned from sentence-transformers/all-MiniLM-L6-v2. It maps sentences & paragraphs to a 384-dimensional dense vector space and can be used for retrieval.
Model Details
Model Description
- Model Type: Sentence Transformer
- Base model: sentence-transformers/all-MiniLM-L6-v2
- Maximum Sequence Length: 256 tokens
- Output Dimensionality: 384 dimensions
- Similarity Function: Cosine Similarity
- Supported Modality: Text
Model Sources
- Documentation: Sentence Transformers Documentation
- Repository: Sentence Transformers on GitHub
- Hugging Face: Sentence Transformers on Hugging Face
Full Model Architecture
SentenceTransformer(
(0): Transformer({'transformer_task': 'feature-extraction', 'modality_config': {'text': {'method': 'forward', 'method_output_name': 'last_hidden_state'}}, 'module_output_name': 'token_embeddings', 'architecture': 'BertModel'})
(1): Pooling({'embedding_dimension': 384, 'pooling_mode': 'mean', 'include_prompt': True})
(2): Normalize({})
)
Usage
Direct Usage (Sentence Transformers)
First install the Sentence Transformers library:
pip install -U sentence-transformers
Then you can load this model and run inference.
from sentence_transformers import SentenceTransformer
# Download from the 🤗 Hub
model = SentenceTransformer("opnsrcntrbtrian/csne-minilm-retrieval-full-1ep")
# Run inference
queries = [
'A shortcut to render a ``script`` tag for the packaged jQuery',
]
documents = [
"jquery_js def jquery_js(version=None, migrate=False): pass version = version or settings.JQUERY_VERSION suffix = '.min' if not settings.DEBUG else '' libs = [js_lib('jquery-%s%s.js' % (version, suffix))] if _boolean(migrate): libs.append(js_lib('jquery-migrate-%s%s.js' % (JQUERY_MIGRATE_VERSION, suffix))) return '\\n'.join(libs)",
"api_call def api_call(method, end_point, params=None, client_id=None, access_token=None): pass if bool(client_id) == bool(access_token): raise ValueError('Either client_id or access_token') url = 'https://api.quizlet.com/2.0/{}'.format(end_point) if not params: params = {} if client_id: params['client_id'] = client_id headers = {'Authorization': 'Bearer {}'.format(access_token)} if access_token else None response = requests.request(method, url, params=params, headers=headers) if int(response.status_code / 100) != 2: error_title = '' try: error_title += ', ' + response.json()['error_title'] except ValueError: pass except KeyError: pass raise ValueError('{} returned {}{}'.format(url, response.status_code, error_title)) try: return response.json() except json.decoder.JSONDecodeError: pass",
'_transaction_func def _transaction_func(entering, exiting, using): pass if callable(using): return Transaction(entering, exiting, None)(using) return Transaction(entering, exiting, using)',
]
query_embeddings = model.encode_query(queries)
document_embeddings = model.encode_document(documents)
print(query_embeddings.shape, document_embeddings.shape)
# [1, 384] [3, 384]
# Get the similarity scores for the embeddings
similarities = model.similarity(query_embeddings, document_embeddings)
print(similarities)
# tensor([[ 0.5674, -0.0050, -0.0192]])
Training Details
Training Dataset
Unnamed Dataset
- Size: 393,427 training samples
- Columns: query and code
- Approximate statistics based on the first 100 samples:
query code type string string modality text text details min: 5 tokensmean: 42.38 tokensmax: 256 tokens min: 39 tokensmean: 142.72 tokensmax: 256 tokens - Samples:
query code Estimate discontinuity in basis of low resolution image segmentation. ImageGraphCut.__msgc_step3_discontinuity_localization def __msgc_step3_discontinuity_localization(self): pass import scipy start = self._start_time seg = 1 - self.segmentation.astype(np.int8) self.stats['low level object voxels'] = np.sum(seg) self.stats['low level image voxels'] = np.prod(seg.shape) seg_border = scipy.ndimage.filters.laplace(seg, mode='constant') logger.debug('seg_border: %s', scipy.stats.describe(seg_border, axis=None)) seg_border[seg_border != 0] = 1 logger.debug('seg_border: %s', scipy.stats.describe(seg_border, axis=None)) boundary_dilatation_distance = self.segparams['boundary_dilatation_distance'] seg = scipy.ndimage.morphology.binary_dilation(seg_border, np.ones([boundary_dilatation_distance * 2 + 1, boundary_dilatation_distance * 2 + 1, boundary_dilatation_distance * 2 + 1])) if self.keep_temp_properties: self.temp_msgc_lowres_discontinuity = seg else: self.temp_msgc_lowres_discontinuity = None if self.debug_images: import sed3 pd = sed3.sed3(seg_border) pd.sh... Run Graph-Cut segmentation with refinement of low resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without use_boundary_penaltiesImageGraphCut.__multiscale_gc_lo2hi_run def __multiscale_gc_lo2hi_run(self): pass self._msgc_lo2hi_resize_init() self.__msgc_step0_init() hard_constraints = self.__msgc_step12_low_resolution_segmentation() seg = self.__msgc_step3_discontinuity_localization() self.stats['t3.1'] = time.time() - self._start_time graph = Graph(seg, voxelsize=self.voxelsize, nsplit=self.segparams['block_size'], edge_weight_table=self._msgc_npenalty_table, compute_low_nodes_index=True) graph.generate_base_grid() self.stats['t3.2'] = time.time() - self._start_time graph.split_voxels() self.stats['t3.3'] = time.time() - self._start_time self.stats.update(graph.stats) self.stats['t4'] = time.time() - self._start_time mul_mask, mul_val = self.__msgc_tlinks_area_weight_from_low_segmentation(seg) area_weight = 1 unariesalt = self.__create_tlinks(self.img, self.voxelsize, self.seeds, area_weight=area_weight, hard_constraints=hard_constraints, mul_mask=None, mul_val=None) self.stats['t5'] = time.time() - self._start... Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without use_boundary_penaltiesImageGraphCut.__multiscale_gc_hi2lo_run def __multiscale_gc_hi2lo_run(self): pass self.__msgc_step0_init() hard_constraints = self.__msgc_step12_low_resolution_segmentation() seg = self.__msgc_step3_discontinuity_localization() nlinks, unariesalt2, msinds = self.__msgc_step45678_hi2lo_construct_graph(hard_constraints, seg) self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds) - Loss: MultipleNegativesRankingLoss with these parameters:
{ "scale": 20.0, "similarity_fct": "cos_sim", "gather_across_devices": false, "directions": [ "query_to_doc" ], "partition_mode": "joint", "hardness_mode": null, "hardness_strength": 0.0 }
Training Hyperparameters
Non-Default Hyperparameters
per_device_train_batch_size: 64num_train_epochs: 1learning_rate: 2e-05warmup_steps: 0.1dataloader_drop_last: True
All Hyperparameters
per_device_train_batch_size: 64num_train_epochs: 1max_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: Falsefp16: 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: Falseeval_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: {}learning_rate_mapping: {}
Training Logs
| Epoch | Step | Training Loss |
|---|---|---|
| 0.0813 | 500 | 0.2719 |
| 0.1627 | 1000 | 0.1987 |
| 0.2440 | 1500 | 0.1820 |
| 0.3254 | 2000 | 0.1787 |
| 0.4067 | 2500 | 0.1655 |
| 0.4880 | 3000 | 0.1667 |
| 0.5694 | 3500 | 0.1570 |
| 0.6507 | 4000 | 0.1484 |
| 0.7321 | 4500 | 0.1511 |
| 0.8134 | 5000 | 0.1462 |
| 0.8947 | 5500 | 0.1418 |
| 0.9761 | 6000 | 0.1470 |
Training Time
- Training: 1.5 hours
Framework Versions
- Python: 3.12.13
- Sentence Transformers: 5.6.0
- Transformers: 5.13.1
- PyTorch: 2.11.0+cu128
- Accelerate: 1.14.0
- Datasets: 4.0.0
- Tokenizers: 0.22.2
Citation
BibTeX
Sentence Transformers
@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",
}
MultipleNegativesRankingLoss
@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},
}