Views
No views yet
nomic-embed-code is a state-of-the-art code embedding model that excels at code retrieval tasks:| Model | Python | Java | Ruby | PHP | JavaScript | Go |
|---|---|---|---|---|---|---|
| Nomic Embed Code | 81.7 | 80.5 | 81.8 | 72.3 | 77.1 | 93.8 |
| Voyage Code 3 | 80.8 | 80.5 | 84.6 | 71.7 | 79.2 | 93.2 |
| OpenAI Embed 3 Large | 70.8 | 72.9 | 75.3 | 59.6 | 68.1 | 87.6 |
| Nomic CodeRankEmbed-137M | 78.4 | 76.9 | 79.3 | 68.8 | 71.4 | 92.7 |
| CodeSage Large v2 (1B) | 74.2 | 72.3 | 76.7 | 65.2 | 72.5 | 84.6 |
| CodeSage Large (1B) | 70.8 | 70.2 | 71.9 | 61.3 | 69.5 | 83.7 |
| Qodo Embed 1 7B | 59.9 | 61.6 | 68.4 | 48.5 | 57.0 | 81.4 |
pip install transformers sentence-transformers torch1import torch
2import torch.nn.functional as F
3from transformers import AutoTokenizer, AutoModel
4
5tokenizer = AutoTokenizer.from_pretrained("nomic-ai/nomic-embed-code")
6model = AutoModel.from_pretrained("nomic-ai/nomic-embed-code")
7
8def last_token_pooling(hidden_states, attention_mask):
9 sequence_lengths = attention_mask.sum(-1) - 1
10 return hidden_states[torch.arange(hidden_states.shape[0]), sequence_lengths]
11
12queries = ['Represent this query for searching relevant code: Calculate the n-th factorial']
13codes = ['def fact(n):\n if n < 0:\n raise ValueError\n return 1 if n == 0 else n * fact(n - 1)']
14code_snippets = queries + codes
15
16encoded_input = tokenizer(code_snippets, padding=True, truncation=True, return_tensors='pt')
17model.eval()
18with torch.no_grad():
19 model_output = model(**encoded_input)[0]
20
21embeddings = last_token_pooling(model_output, encoded_input['attention_mask'])
22embeddings = F.normalize(embeddings, p=2, dim=1)
23print(embeddings.shape)
24
25similarity = F.cosine_similarity(embeddings[0], embeddings[1], dim=0)
26print(similarity)1from sentence_transformers import SentenceTransformer
2
3queries = ['Calculate the n-th factorial']
4code_snippets = ['def fact(n):\n if n < 0:\n raise ValueError\n return 1 if n == 0 else n * fact(n - 1)']
5
6model = SentenceTransformer("nomic-ai/nomic-embed-code")
7query_emb = model.encode(queries, prompt_name="query")
8code_emb = model.encode(code_snippets)
9
10similarity = model.similarity(query_emb[0], code_emb[0])
11print(similarity)
1@misc{suresh2025cornstackhighqualitycontrastivedata,
2 title={CoRNStack: High-Quality Contrastive Data for Better Code Retrieval and Reranking},
3 author={Tarun Suresh and Revanth Gangi Reddy and Yifei Xu and Zach Nussbaum and Andriy Mulyar and Brandon Duderstadt and Heng Ji},
4 year={2025},
5 eprint={2412.01007},
6 archivePrefix={arXiv},
7 primaryClass={cs.CL},
8 url={https://arxiv.org/abs/2412.01007},
9}