SentenceTransformer based on BAAI/bge-code-v1

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.

Model Details

Model Description

  • Model Type: Sentence Transformer
  • Base model: BAAI/bge-code-v1
  • Maximum Sequence Length: 768 tokens
  • Output Dimensionality: 1536 dimensions
  • Similarity Function: Cosine Similarity

Model Sources

Full Model Architecture

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()
)

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("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)

Training Details

Training Dataset

Unnamed Dataset

  • Size: 9,359 training samples
  • Columns: sentence_0, sentence_1, and label
  • Approximate statistics based on the first 1000 samples:
    sentence_0 sentence_1 label
    type string string float
    details
    • min: 54 tokens
    • mean: 105.76 tokens
    • max: 196 tokens
    • min: 54 tokens
    • mean: 109.96 tokens
    • max: 196 tokens
    • min: 0.0
    • mean: 0.06
    • max: 1.0
  • Samples:
    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
  • Loss: ContrastiveLoss with these parameters:
    {
        "distance_metric": "SiameseDistanceMetric.COSINE_DISTANCE",
        "margin": 0.5,
        "size_average": true
    }
    

Training Hyperparameters

Non-Default Hyperparameters

  • per_device_train_batch_size: 128
  • per_device_eval_batch_size: 128
  • multi_dataset_batch_sampler: round_robin

All Hyperparameters

Click to expand
  • overwrite_output_dir: False
  • do_predict: False
  • eval_strategy: no
  • prediction_loss_only: True
  • per_device_train_batch_size: 128
  • per_device_eval_batch_size: 128
  • per_gpu_train_batch_size: None
  • per_gpu_eval_batch_size: None
  • gradient_accumulation_steps: 1
  • eval_accumulation_steps: None
  • torch_empty_cache_steps: None
  • learning_rate: 5e-05
  • weight_decay: 0.0
  • adam_beta1: 0.9
  • adam_beta2: 0.999
  • adam_epsilon: 1e-08
  • max_grad_norm: 1
  • num_train_epochs: 3
  • max_steps: -1
  • lr_scheduler_type: linear
  • lr_scheduler_kwargs: None
  • warmup_ratio: 0.0
  • warmup_steps: 0
  • log_level: passive
  • log_level_replica: warning
  • log_on_each_node: True
  • logging_nan_inf_filter: True
  • save_safetensors: True
  • save_on_each_node: False
  • save_only_model: False
  • restore_callback_states_from_checkpoint: False
  • no_cuda: False
  • use_cpu: False
  • use_mps_device: False
  • seed: 42
  • data_seed: None
  • jit_mode_eval: False
  • bf16: False
  • fp16: False
  • fp16_opt_level: O1
  • half_precision_backend: auto
  • bf16_full_eval: False
  • fp16_full_eval: False
  • tf32: None
  • local_rank: 0
  • ddp_backend: None
  • tpu_num_cores: None
  • tpu_metrics_debug: False
  • debug: []
  • dataloader_drop_last: False
  • dataloader_num_workers: 0
  • dataloader_prefetch_factor: None
  • past_index: -1
  • disable_tqdm: False
  • remove_unused_columns: True
  • label_names: None
  • load_best_model_at_end: False
  • ignore_data_skip: False
  • fsdp: []
  • fsdp_min_num_params: 0
  • fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}
  • fsdp_transformer_layer_cls_to_wrap: None
  • accelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}
  • parallelism_config: None
  • deepspeed: None
  • label_smoothing_factor: 0.0
  • optim: adamw_torch_fused
  • optim_args: None
  • adafactor: False
  • group_by_length: False
  • length_column_name: length
  • project: huggingface
  • trackio_space_id: trackio
  • ddp_find_unused_parameters: None
  • ddp_bucket_cap_mb: None
  • ddp_broadcast_buffers: False
  • dataloader_pin_memory: True
  • dataloader_persistent_workers: False
  • skip_memory_metrics: True
  • use_legacy_prediction_loop: False
  • push_to_hub: False
  • resume_from_checkpoint: None
  • hub_model_id: None
  • hub_strategy: every_save
  • hub_private_repo: None
  • hub_always_push: False
  • hub_revision: None
  • gradient_checkpointing: False
  • gradient_checkpointing_kwargs: None
  • include_inputs_for_metrics: False
  • include_for_metrics: []
  • eval_do_concat_batches: True
  • fp16_backend: auto
  • push_to_hub_model_id: None
  • push_to_hub_organization: None
  • mp_parameters:
  • auto_find_batch_size: False
  • full_determinism: False
  • torchdynamo: None
  • ray_scope: last
  • ddp_timeout: 1800
  • torch_compile: False
  • torch_compile_backend: None
  • torch_compile_mode: None
  • include_tokens_per_second: False
  • include_num_input_tokens_seen: no
  • neftune_noise_alpha: None
  • optim_target_modules: None
  • batch_eval_metrics: False
  • eval_on_start: False
  • use_liger_kernel: False
  • liger_kernel_config: None
  • eval_use_gather_object: False
  • average_tokens_across_devices: True
  • prompts: None
  • batch_sampler: batch_sampler
  • multi_dataset_batch_sampler: round_robin
  • router_mapping: {}
  • learning_rate_mapping: {}

Framework Versions

  • Python: 3.11.14
  • Sentence Transformers: 5.2.2
  • Transformers: 4.57.6
  • PyTorch: 2.10.0+cu128
  • Accelerate: 1.12.0
  • Datasets: 4.5.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",
}

ContrastiveLoss

@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}
}
Downloads last month
1
Safetensors
Model size
2B params
Tensor type
BF16
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for hasinthakapiyumal/bge-code-v1-ai-pattern-tuned

Base model

BAAI/bge-code-v1
Finetuned
(3)
this model

Paper for hasinthakapiyumal/bge-code-v1-ai-pattern-tuned