SentenceTransformer based on microsoft/codebert-base

This is a sentence-transformers model finetuned from microsoft/codebert-base. It maps sentences & paragraphs to a 768-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, classification, clustering, and more.

Model Details

Model Description

  • Model Type: Sentence Transformer
  • Base model: microsoft/codebert-base
  • Maximum Sequence Length: 256 tokens
  • Output Dimensionality: 768 dimensions
  • Similarity Function: Cosine Similarity
  • Supported Modality: Text

Model Sources

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': 'RobertaModel'})
  (1): Pooling({'embedding_dimension': 768, 'pooling_mode': 'mean', 'include_prompt': True})
)

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("wraithklu/codesentinel-clone-detector")
# Run inference
sentences = [
    'protected void serveStaticContent(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException {\n        InputStream is = servletConfig.getServletContext().getResourceAsStream(pathInfo);\n        if (is == null) {\n            throw new ServletException("Static resource " + pathInfo + " is not available");\n        }\n        try {\n            int ind = pathInfo.lastIndexOf(".");\n            if (ind != -1 && ind < pathInfo.length()) {\n                String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1));\n                if (type != null) {\n                    response.setContentType(type);\n                }\n            }\n            ServletOutputStream os = response.getOutputStream();\n            IOUtils.copy(is, os);\n            os.flush();\n        } catch (IOException ex) {\n            throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream");\n        }\n    }',
    'private static String makeLoginRequest(String authenticationUrl, String accountEmail, String accountPassword) throws IOException {\n        URL url = new URL(authenticationUrl);\n        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();\n        urlConnection.setRequestMethod("POST");\n        urlConnection.setDoInput(true);\n        urlConnection.setDoOutput(true);\n        urlConnection.setUseCaches(false);\n        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");\n        StringBuffer content = new StringBuffer();\n        content.append("Email=").append(URLEncoder.encode(accountEmail, "UTF-8"));\n        content.append("&Passwd=").append(URLEncoder.encode(accountPassword, "UTF-8"));\n        content.append("&source=").append(URLEncoder.encode("Google Base data API for OFBiz", "UTF-8"));\n        content.append("&service=").append(URLEncoder.encode("gbase", "UTF-8"));\n        OutputStream outputStream = urlConnection.getOutputStream();\n        outputStream.write(content.toString().getBytes("UTF-8"));\n        outputStream.close();\n        int responseCode = urlConnection.getResponseCode();\n        InputStream inputStream;\n        if (responseCode == HttpURLConnection.HTTP_OK) {\n            inputStream = urlConnection.getInputStream();\n        } else {\n            inputStream = urlConnection.getErrorStream();\n        }\n        return toString(inputStream);\n    }',
    'public static void main(String[] args) throws Exception {\n        if (args.length != 2) {\n            System.out.println("arguments: sourcefile destfile");\n            System.exit(1);\n        }\n        FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel();\n        in.transferTo(0, in.size(), out);\n    }',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 768]

# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[ 1.0000, -0.0114,  0.9605],
#         [-0.0114,  1.0000,  0.0068],
#         [ 0.9605,  0.0068,  1.0000]])

Evaluation

Metrics

Semantic Similarity

Metric Value
pearson_cosine 0.905
spearman_cosine 0.8343

Training Details

Training Dataset

Unnamed Dataset

  • Size: 10,000 training samples
  • Columns: sentence_0, sentence_1, and label
  • Approximate statistics based on the first 100 samples:
    sentence_0 sentence_1 label
    type string string float
    modality text text
    details
    • min: 134 tokens
    • mean: 240.02 tokens
    • max: 256 tokens
    • min: 104 tokens
    • mean: 237.68 tokens
    • max: 256 tokens
    • min: 0.0
    • mean: 0.49
    • max: 1.0
  • Samples:
    sentence_0 sentence_1 label
    public InputLattice(String file, int type, boolean convertJoinMeet) throws FileNotFoundException, IOException {
    InputStream latStream = null;
    labels = new Vector();
    upperCoversVector = new Vector();
    Vector upperCovers = new Vector();
    edgeColors = new Hashtable();
    Vector upperCovering = new Vector();
    int level = 0;
    String str;
    String currentElt = null;
    String cover = null;
    boolean first = true;
    StreamTokenizer in;
    switch(type) {
    case FILE:
    latStream = new FileInputStream(file);
    break;
    case STRING:
    latStream = new StringBufferInputStream(file);
    break;
    case URL:
    URL url = new URL("http", Config.HOST, Config.PORT, "/" + Config.HASSE + "/" + Config.URL_STREAMER + file);
    System.out.println("url is " + url);
    URLConnection connection = url.openCo...
    private String calculateHash(String s) {
    if (s == null) {
    return null;
    }
    MessageDigest messageDigest;
    try {
    messageDigest = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
    logger.error("Could not find a message digest algorithm.");
    return null;
    }
    messageDigest.update(s.getBytes());
    byte[] hash = messageDigest.digest();
    StringBuilder sb = new StringBuilder();
    for (byte b : hash) {
    sb.append(String.format("%02x", b));
    }
    return sb.toString();
    }
    0.0
    void load(URL url) throws IOException {
    BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream()));
    Vector3f scale = new Vector3f(1, 1, 1);
    Group currentGroup = new Group();
    currentGroup.name = "default";
    groups.add(currentGroup);
    String line;
    while ((line = r.readLine()) != null) {
    String[] params = line.split(" +");
    if (params.length == 0) continue;
    String command = params[0];
    if (params[0].equals("v")) {
    Vector3f vertex = new Vector3f(Float.parseFloat(params[1]) * scale.x, Float.parseFloat(params[2]) * scale.y, Float.parseFloat(params[3]) * scale.z);
    verticies.add(vertex);
    radius = Math.max(radius, vertex.length());
    }
    if (command.equals("center")) {
    epicenter = new Vector3f(Float.parseFloat(params[1]), Float.parseFloat(params[2]), Float.parseFloat(params[3]));
    } ...
    public static boolean canWeConnectToInternet() {
    String s = "http://www.google.com/";
    URL url = null;
    boolean can = false;
    URLConnection conection = null;
    try {
    url = new URL(s);
    } catch (MalformedURLException e) {
    System.out.println("This should never happend. Error in URL name. URL specified was:" + s + ".");
    }
    try {
    conection = url.openConnection();
    conection.connect();
    can = true;
    } catch (IOException e) {
    can = false;
    }
    if (can) {
    }
    return can;
    }
    0.0
    public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) {
    java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream();
    try {
    InputStream input = _url.openStream();
    IOUtils.copy(input, buffer);
    IOUtils.closeQuietly(input);
    } catch (Exception err) {
    throw new RuntimeException(err);
    }
    return buffer;
    }
    public BufferedImage processUsingTemp(InputStream input, DjatokaDecodeParam params) throws DjatokaException {
    File in;
    try {
    in = File.createTempFile("tmp", ".jp2");
    FileOutputStream fos = new FileOutputStream(in);
    in.deleteOnExit();
    IOUtils.copyStream(input, fos);
    } catch (IOException e) {
    logger.error(e, e);
    throw new DjatokaException(e);
    }
    BufferedImage bi = process(in.getAbsolutePath(), params);
    if (in != null) in.delete();
    return bi;
    }
    1.0
  • Loss: CosineSimilarityLoss with these parameters:
    {
        "loss_fct": "torch.nn.modules.loss.MSELoss",
        "cos_score_transformation": "torch.nn.modules.linear.Identity"
    }
    

Training Hyperparameters

Non-Default Hyperparameters

  • per_device_train_batch_size: 32
  • num_train_epochs: 2
  • fp16: True
  • per_device_eval_batch_size: 32
  • multi_dataset_batch_sampler: round_robin

All Hyperparameters

Click to expand
  • per_device_train_batch_size: 32
  • num_train_epochs: 2
  • max_steps: -1
  • learning_rate: 5e-05
  • lr_scheduler_type: linear
  • lr_scheduler_kwargs: None
  • warmup_steps: 0
  • optim: adamw_torch_fused
  • optim_args: None
  • weight_decay: 0.0
  • adam_beta1: 0.9
  • adam_beta2: 0.999
  • adam_epsilon: 1e-08
  • optim_target_modules: None
  • gradient_accumulation_steps: 1
  • average_tokens_across_devices: True
  • max_grad_norm: 1
  • label_smoothing_factor: 0.0
  • bf16: False
  • fp16: True
  • bf16_full_eval: False
  • fp16_full_eval: False
  • tf32: None
  • gradient_checkpointing: False
  • gradient_checkpointing_kwargs: None
  • torch_compile: False
  • torch_compile_backend: None
  • torch_compile_mode: None
  • use_liger_kernel: False
  • liger_kernel_config: None
  • use_cache: False
  • neftune_noise_alpha: None
  • torch_empty_cache_steps: None
  • auto_find_batch_size: False
  • log_on_each_node: True
  • logging_nan_inf_filter: True
  • include_num_input_tokens_seen: no
  • log_level: passive
  • log_level_replica: warning
  • disable_tqdm: False
  • project: huggingface
  • trackio_space_id: None
  • trackio_bucket_id: None
  • trackio_static_space_id: None
  • per_device_eval_batch_size: 32
  • prediction_loss_only: True
  • eval_on_start: False
  • eval_do_concat_batches: True
  • eval_use_gather_object: False
  • eval_accumulation_steps: None
  • include_for_metrics: []
  • batch_eval_metrics: False
  • save_only_model: False
  • save_on_each_node: False
  • enable_jit_checkpoint: False
  • push_to_hub: False
  • hub_private_repo: None
  • hub_model_id: None
  • hub_strategy: every_save
  • hub_always_push: False
  • hub_revision: None
  • load_best_model_at_end: False
  • ignore_data_skip: False
  • restore_callback_states_from_checkpoint: False
  • full_determinism: False
  • seed: 42
  • data_seed: None
  • use_cpu: False
  • 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
  • dataloader_drop_last: False
  • dataloader_num_workers: 0
  • dataloader_pin_memory: True
  • dataloader_persistent_workers: False
  • dataloader_prefetch_factor: None
  • dataloader_multiprocessing_context: None
  • dataloader_in_order: True
  • remove_unused_columns: True
  • label_names: None
  • train_sampling_strategy: random
  • length_column_name: length
  • ddp_find_unused_parameters: None
  • ddp_bucket_cap_mb: None
  • ddp_broadcast_buffers: False
  • ddp_static_graph: None
  • ddp_backend: None
  • ddp_timeout: 1800
  • fsdp: None
  • fsdp_config: None
  • deepspeed: None
  • debug: []
  • skip_memory_metrics: True
  • do_predict: False
  • resume_from_checkpoint: None
  • local_rank: -1
  • prompts: None
  • batch_sampler: batch_sampler
  • multi_dataset_batch_sampler: round_robin
  • router_mapping: {}
  • learning_rate_mapping: {}
  • warmup_ratio: None

Training Logs

Epoch Step Training Loss bigclonebench-validation_spearman_cosine
0.4984 156 - 0.8142
0.9968 312 - 0.8325
1.0 313 - 0.8325
1.4952 468 - 0.8346
1.5974 500 0.0901 -
1.9936 624 - 0.8343
2.0 626 - 0.8343

Training Time

  • Training: 13.3 minutes

Framework Versions

  • Python: 3.13.16
  • Sentence Transformers: 5.7.0
  • Transformers: 5.22.1
  • PyTorch: 2.14.1+cu130
  • Accelerate: 1.15.0
  • Datasets: 4.8.5
  • Tokenizers: 0.23.3

Additional Resources

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

Model tree for wraithklu/codesentinel-clone-detector

Finetuned
(154)
this model

Paper for wraithklu/codesentinel-clone-detector

Evaluation results