Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Paper • 1908.10084 • Published • 19
How to use wraithklu/codesentinel-clone-detector with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("wraithklu/codesentinel-clone-detector")
sentences = [
"private void createTree(DefaultMutableTreeNode top) throws MalformedURLException, ParserConfigurationException, SAXException, IOException {\n InputStream stream;\n URL url = new URL(SHIPS_URL + view.getBaseurl());\n try {\n stream = url.openStream();\n } catch (Exception e) {\n stream = getClass().getResourceAsStream(\"ships.xml\");\n }\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n DocumentBuilder parser = factory.newDocumentBuilder();\n Document doc = parser.parse(stream);\n NodeList races = doc.getElementsByTagName(\"race\");\n for (int i = 0; i < races.getLength(); i++) {\n Element race = (Element) races.item(i);\n top.add(buildRaceTree(race));\n }\n top.setUserObject(\"Ships\");\n view.getShipTree().repaint();\n view.getShipTree().expandRow(0);\n }",
"private GenomicSequence fetch(Chromosome k, int start, int end) throws IOException {\n try {\n String chr = k.toString();\n if (chr.toLowerCase().startsWith(\"chr\")) chr = chr.substring(3);\n SAXParserFactory f = SAXParserFactory.newInstance();\n f.setNamespaceAware(false);\n f.setValidating(false);\n SAXParser parser = f.newSAXParser();\n URL url = new URL(\"http://genome.ucsc.edu/cgi-bin/das/\" + genomeVersion + \"/dna?segment=\" + URLEncoder.encode(chr, \"UTF-8\") + \":\" + (start + 1) + \",\" + (end));\n DASHandler handler = new DASHandler();\n InputStream in = url.openStream();\n parser.parse(in, handler);\n in.close();\n GenomicSequence seq = new GenomicSequence();\n seq.sequence = handler.bytes.toByteArray();\n seq.start = start;\n seq.end = end;\n if (seq.sequence.length != seq.length()) throw new IOException(\"bad bound \" + seq + \" \" + seq.sequence.length + \" \" + seq.length());\n return seq;\n } catch (IOException err) {\n throw err;\n } catch (Exception e) {\n throw new IOException(e);\n }\n }",
"public static void main(String[] args) throws Exception {\n FileChannel fc = new FileOutputStream(\"data.txt\").getChannel();\n fc.write(ByteBuffer.wrap(\"some text \".getBytes()));\n fc.close();\n fc = new RandomAccessFile(\"data.txt\", \"rw\").getChannel();\n fc.position(fc.size());\n fc.write(ByteBuffer.wrap(\"some more\".getBytes()));\n fc.close();\n fc = new FileInputStream(\"data.txt\").getChannel();\n ByteBuffer buff = ByteBuffer.allocate(BSIZE);\n fc.read(buff);\n buff.flip();\n while (buff.hasRemaining()) {\n PrintUtil.prt((char) buff.get());\n }\n }",
"private FileLog(LOG_LEVEL displayLogLevel, LOG_LEVEL logLevel, String logPath) {\n this.logLevel = logLevel;\n this.displayLogLevel = displayLogLevel;\n if (null != logPath) {\n logFile = new File(logPath, \"current.log\");\n log(LOG_LEVEL.DEBUG, \"FileLog\", \"Initialising logfile \" + logFile.getAbsolutePath() + \" .\");\n try {\n if (logFile.exists()) {\n if (!logFile.renameTo(new File(logPath, System.currentTimeMillis() + \".log\"))) {\n File newFile = new File(logPath, System.currentTimeMillis() + \".log\");\n if (newFile.exists()) {\n log(LOG_LEVEL.WARN, \"FileLog\", \"The file (\" + newFile.getAbsolutePath() + newFile.getName() + \") already exists, will overwrite it.\");\n newFile.delete();\n }\n newFile.createNewFile();\n FileInputStream inStream = new FileInputStream(logFile);\n FileOutputStream outStream = new FileOutputStream(newFile);\n byte buffer[] = null;\n int offSet = 0;\n while (inStream.read(buffer, offSet, 2048) != -1) {\n outStream.write(buffer);\n offSet += 2048;\n }\n inStream.close();\n outStream.close();\n logFile.delete();\n logFile = new File(logPath, \"current.log\");\n }\n }\n logFile.createNewFile();\n } catch (IOException e) {\n logFile = null;\n }\n } else {\n logFile = null;\n }\n }"
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]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.
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})
)
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]])
bigclonebench-validationEmbeddingSimilarityEvaluator| Metric | Value |
|---|---|
| pearson_cosine | 0.905 |
| spearman_cosine | 0.8343 |
sentence_0, sentence_1, and label| sentence_0 | sentence_1 | label | |
|---|---|---|---|
| type | string | string | float |
| modality | text | text | |
| details |
|
|
|
| sentence_0 | sentence_1 | label |
|---|---|---|
public InputLattice(String file, int type, boolean convertJoinMeet) throws FileNotFoundException, IOException { |
private String calculateHash(String s) { |
0.0 |
void load(URL url) throws IOException { |
public static boolean canWeConnectToInternet() { |
0.0 |
public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { |
public BufferedImage processUsingTemp(InputStream input, DjatokaDecodeParam params) throws DjatokaException { |
1.0 |
CosineSimilarityLoss with these parameters:{
"loss_fct": "torch.nn.modules.loss.MSELoss",
"cos_score_transformation": "torch.nn.modules.linear.Identity"
}
per_device_train_batch_size: 32num_train_epochs: 2fp16: Trueper_device_eval_batch_size: 32multi_dataset_batch_sampler: round_robinper_device_train_batch_size: 32num_train_epochs: 2max_steps: -1learning_rate: 5e-05lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_steps: 0optim: 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: 1label_smoothing_factor: 0.0bf16: Falsefp16: Truebf16_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: 32prediction_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: Falsedataloader_num_workers: 0dataloader_pin_memory: Truedataloader_persistent_workers: Falsedataloader_prefetch_factor: Nonedataloader_multiprocessing_context: Nonedataloader_in_order: Trueremove_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: Nonelocal_rank: -1prompts: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: round_robinrouter_mapping: {}learning_rate_mapping: {}warmup_ratio: None| 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 |
@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",
}
Base model
microsoft/codebert-base