Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Paper • 1908.10084 • Published • 14
How to use hasinthakapiyumal/bge-code-v1-ai-pattern-tuned with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("hasinthakapiyumal/bge-code-v1-ai-pattern-tuned")
sentences = [
"This code implements a Reinforcement Learning (RL) agent, specifically a Deep Q-Network (DQN) or its Double DQN variant, designed for interaction with OpenAI Gym environments. It employs an experience replay buffer for efficient off-policy learning and manages exploration-exploitation through initial random actions and decaying noise. A key AI pattern is the use of a distributional RL approach, likely C51, evident from the visualization of predicted value distributions across a range of atoms during policy rendering.",
"The code exhibits an optimization-driven 3D bounding-box estimation pattern: BoxRegressor minimizes a reprojection residual of 8 keypoints plus size and distance regularizers, using a pseudo-inverse camera-initialization and a discrete RotY sweep evaluated with least_squares. It embodies a geometric projection pattern via get_keypoints that builds the 3D corners under rotation, projects them through the camera matrix to image coordinates, and uses those projections as the residual basis. Data handling follows a PyTorch-style pattern with multiple Dataset classes that load KITTI data, apply per-sample augmentations (random flips, crops, color normalization), and normalize/prepare size, keypoints, and distance tensors for learning.",
"This code showcases a PyTorch-based, object-oriented training framework with a BaseModel that unifies compilation, iterative training (train_step, train_epoch), evaluation, checkpointing, and early stopping driven by a Monitor. It implements a modular regularization strategy via get_regularizer, supporting float, L1/L2, and L1_L2 patterns and applying penalties selectively to embedding vs. non-embedding parameters. The MultiTaskModel demonstrates a true multi-task pattern: per-task outputs and losses organized in a ModuleList, task-wise activation mappings, and per-task metric evaluation with aggregated reporting and group-aware metrics guided by a feature_map.",
"This code implements a system for Large Language Model (LLM) inference, loading a pre-trained causal language model and tokenizer to process user queries. A central AI pattern is \"AutoThink,\" which enables controllable generation through activation steering. This involves applying steering vectors from a specified dataset to a target model layer, guided by explicit \"pattern strengths\" to direct the LLM's output towards desired cognitive attributes like depth, accuracy, and self-correction."
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from BAAI/bge-code-v1. It maps sentences & paragraphs to a 1536-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, text classification, clustering, and more.
SentenceTransformer(
(0): Transformer({'max_seq_length': 768, 'do_lower_case': False, 'architecture': 'Qwen2Model'})
(1): Pooling({'word_embedding_dimension': 1536, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': False, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': True, 'include_prompt': True})
(2): Normalize()
)
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("sentence_transformers_model_id")
# Run inference
sentences = [
'The module implements a parallel Monte Carlo Tree Search (MCTS) framework that partitions FactorioInstance objects into N groups and runs independent MCTS pipelines concurrently for scalable AI planning. It showcases a pluggable MCTS strategy via config.mcts_class and a per-group Evaluator with language-model guided rollouts, wired through dependency-injected components (DBClient, APIFactory) and prompts (system_prompt, initial_state) to shape value estimation (value_accrual_time, error_penalty). Asynchronous orchestration with asyncio.gather and per-group logging (GroupedFactorioLogger, evaluator.logger) enable fine-grained performance and error reporting across parallel search groups.',
'- The code demonstrates a data-driven testing pattern using pytest parametrization: parametrize_dir and parametrize_filebased generate per-scene test parameters, while the nuplan_test decorator orchestrates hardcoded vs. file-based tests and preserves metadata with wraps. This yields scalable, JSON-driven test coverage for AI components.\n\n- It encodes vectorized AI patterns for scene understanding: vector map feature builders (VectorMapFeatureBuilder, VectorSetMapFeatureBuilder) that pack map primitives (lanes, boundaries, stop lines, traffic lights) into TorchScript-friendly tensors, convert coordinates to local frames, and support multi-scale connections; aided by helpers like get_neighbor_vector_map and get_neighbor_vector_set_map to assemble neighborhood features.\n\n- It also showcases asynchronous and concurrent design patterns for performance: multi-threaded rendering paths in SimulationTile using ThreadPoolExecutor and concurrent futures to decouple map/data loading from visualization.',
'The code exemplifies a time-based scheduling pattern that differentiates one-off versus recurring jobs using end_time and repeat_interval, validated through tests that exercise sleep-time calculation and next-run updates with datetime arithmetic. It also presents a persistence-driven domain model (JobCatalog) mapped via ORM with fields for start/end times, active status, and next_scheduled_run, including an index to optimize retrieval and an as_dataclass converter for lightweight data transfer. Testing patterns include the use of mocks (MagicMock) and a helper factory to generate dummy catalog entries, enabling isolated, deterministic verification of the scheduler’s time-dependent logic.',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 1536]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[1.0000, 0.5391, 0.5195],
# [0.5391, 1.0000, 0.5352],
# [0.5195, 0.5352, 1.0000]], dtype=torch.bfloat16)
sentence_0, sentence_1, and label| sentence_0 | sentence_1 | label | |
|---|---|---|---|
| type | string | string | float |
| details |
|
|
|
| sentence_0 | sentence_1 | label |
|---|---|---|
This code implements a neural network-based recommender system, specifically utilizing a NeuMF (Neural Matrix Factorization) model. It follows a standard deep learning training pattern, employing mini-batch updates and gradient descent optimization. Model performance is periodically evaluated using ranking-specific metrics such as Hit Ratio and NDCG, which assess the quality of top-k recommendations. |
The code embodies a vectorized evaluation pipeline for strategy signals, using numpy to compute active returns, risk, and performance ratios (e.g., information ratio) from portfolio and benchmark series. It follows a modular, functional style with static methods and guard clauses for data validation, followed by a value-added decomposition into allocation and selection effects to support explainable AI-like attribution. A statistical-significance module computes a t-statistic and maps it to significance levels, mirroring hypothesis-testing patterns used in AI model evaluation and uncertainty quantification. |
0.0 |
The code exemplifies a prompt-driven action pattern where CodeVerification formats inputs into a structured prompt, queries an LLM, and parses the result into a typed output with a primary parser and a robust fallback that extracts triple-backtick code blocks when parsing fails. It also encodes a modular, end-to-end workflow pipeline (plan → build graph → instantiate agents → execute → verify/extract) with stepwise user confirmations and intermediate-state serialization. Additionally, it demonstrates pluggable parsing and code extraction patterns via a decorator-based parse registry, a dedicated extract_code_blocks utility for language-tagged blocks, and a multi-LLM setup using distinct config objects (OpenAI, Claude, Lite wrappers). |
The code centers on an AI-oriented knowledge-graph pattern, modeling entities, relationships, chunks, and their assembly into a TGraph with per-item TScore and a TContext for prompt construction and ranking. It follows a DTO/ORM style where domain models expose an internal Pydantic-like Model and a to_dataclass conversion, enabling strict ValidationError checks and deterministic normalization (e.g., uppercase transformations) for reliable comparisons. It also demonstrates AI-prompt generation patterns with CSV/markdown output (dump_to_csv and TContext.truncate) that partition data into Entities, Relationships, and Sources for structured LLM prompts and testable formatting. |
0.0 |
Cluster 34 showcases an event-driven, multi-agent AI integration where LarkAgent and WechatAgent act as adapters that translate external chats into a unified AI pipeline, using async request parsing and a callback-based responder flow. It employs a discriminated content-type pipeline (LarkContentType) to classify input as normal text, bot/mention text, or images, decide processing, and then construct AI-facing requests via builder/factory patterns, including image storage and per-message query IDs. The design relies on modular feature-store/cache lookups, token-based access control, and standardized error handling, all enhanced by thorough logging for observable, scalable AI orchestration. |
Cluster 19 showcases a modular AI orchestration pattern: a proxy routes chat requests through multiple configurable approaches (including a direct none path) and dynamic model composition using tags like optillm_approach and operators (AND/OR). It includes utilities to normalize and parse conversation formats (User/Assistant tagging, content lists) and convert tagged transcripts into standard message objects, enabling cross-LLM compatibility. The design emphasizes streaming responses (server-sent events), batch processing hooks, and thorough provider logging to enable observable, configurable multi-provider AI workflows. |
0.0 |
ContrastiveLoss with these parameters:{
"distance_metric": "SiameseDistanceMetric.COSINE_DISTANCE",
"margin": 0.5,
"size_average": true
}
per_device_train_batch_size: 128per_device_eval_batch_size: 128multi_dataset_batch_sampler: round_robinoverwrite_output_dir: Falsedo_predict: Falseeval_strategy: noprediction_loss_only: Trueper_device_train_batch_size: 128per_device_eval_batch_size: 128per_gpu_train_batch_size: Noneper_gpu_eval_batch_size: Nonegradient_accumulation_steps: 1eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 5e-05weight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1num_train_epochs: 3max_steps: -1lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_ratio: 0.0warmup_steps: 0log_level: passivelog_level_replica: warninglog_on_each_node: Truelogging_nan_inf_filter: Truesave_safetensors: Truesave_on_each_node: Falsesave_only_model: Falserestore_callback_states_from_checkpoint: Falseno_cuda: Falseuse_cpu: Falseuse_mps_device: Falseseed: 42data_seed: Nonejit_mode_eval: Falsebf16: Falsefp16: Falsefp16_opt_level: O1half_precision_backend: autobf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonelocal_rank: 0ddp_backend: Nonetpu_num_cores: Nonetpu_metrics_debug: Falsedebug: []dataloader_drop_last: Falsedataloader_num_workers: 0dataloader_prefetch_factor: Nonepast_index: -1disable_tqdm: Falseremove_unused_columns: Truelabel_names: Noneload_best_model_at_end: Falseignore_data_skip: Falsefsdp: []fsdp_min_num_params: 0fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}fsdp_transformer_layer_cls_to_wrap: Noneaccelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}parallelism_config: Nonedeepspeed: Nonelabel_smoothing_factor: 0.0optim: adamw_torch_fusedoptim_args: Noneadafactor: Falsegroup_by_length: Falselength_column_name: lengthproject: huggingfacetrackio_space_id: trackioddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falsedataloader_pin_memory: Truedataloader_persistent_workers: Falseskip_memory_metrics: Trueuse_legacy_prediction_loop: Falsepush_to_hub: Falseresume_from_checkpoint: Nonehub_model_id: Nonehub_strategy: every_savehub_private_repo: Nonehub_always_push: Falsehub_revision: Nonegradient_checkpointing: Falsegradient_checkpointing_kwargs: Noneinclude_inputs_for_metrics: Falseinclude_for_metrics: []eval_do_concat_batches: Truefp16_backend: autopush_to_hub_model_id: Nonepush_to_hub_organization: Nonemp_parameters: auto_find_batch_size: Falsefull_determinism: Falsetorchdynamo: Noneray_scope: lastddp_timeout: 1800torch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Noneinclude_tokens_per_second: Falseinclude_num_input_tokens_seen: noneftune_noise_alpha: Noneoptim_target_modules: Nonebatch_eval_metrics: Falseeval_on_start: Falseuse_liger_kernel: Falseliger_kernel_config: Noneeval_use_gather_object: Falseaverage_tokens_across_devices: Trueprompts: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: round_robinrouter_mapping: {}learning_rate_mapping: {}@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",
}
@inproceedings{hadsell2006dimensionality,
author={Hadsell, R. and Chopra, S. and LeCun, Y.},
booktitle={2006 IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'06)},
title={Dimensionality Reduction by Learning an Invariant Mapping},
year={2006},
volume={2},
number={},
pages={1735-1742},
doi={10.1109/CVPR.2006.100}
}
Base model
BAAI/bge-code-v1