CoolFace
Modelpublic

faisalmumtaz/codecompass-embed

sourceHugging Faceapache-2.0updated 7mo agoView on Hugging Face
1likes111downloads
Model Card

CodeCompass-Embed

CodeCompass-Embed is a 494M-parameter embedding model for semantic code search and retrieval, trained on 86B tokens total. It produces 896-dimensional embeddings optimized for matching natural language queries to code across Python, Java, JavaScript, Go, Ruby, and PHP, achieving state-of-the-art results on the CoIR code retrieval benchmark.

Model Highlights

  • Code search from natural language — find relevant code snippets across Python, Java, JavaScript, Go, Ruby, PHP
  • Competitive with models 3× smaller and larger — 494M params, 896-dim embeddings
  • Bidirectional attention — all 24 layers converted from causal for better embedding quality
  • Lightweight — runs on consumer GPUs, trained at 512 tokens with RoPE extrapolation for longer inputs
  • Versatile — supports NL→Code, Code→Code, Q&A, and Text→SQL retrieval via instruction templates

Model Details

PropertyValue
Base ModelQwen2.5-Coder-0.5B
Parameters494M
Embedding Dimension896
Max Sequence Length512 (training) / 32K (inference)
PoolingMean
NormalizationL2
AttentionBidirectional (all 24 layers)

Benchmark Results (CoIR)

Evaluated on the CoIR Benchmark (ACL 2025). All scores are NDCG@10. Sorted by CSN-Python.

ModelParamsCSN-PyCodeTransText2SQLSO-QACodeFeedbackAppsAvg
CodeCompass-Embed (ours)494M0.9790.2860.7360.8340.8140.3490.666
SFR-Embedding-Code400M0.9510.2680.9950.9110.7260.2210.679
Jina-Code-v2161M0.9440.2740.5170.8870.6980.1540.579
CodeRankEmbed137M0.9380.2600.7690.8990.7170.1990.630
Snowflake-Arctic-Embed-L568M0.9150.1960.5400.8720.6500.1440.553
BGE-M3568M0.8980.2190.5730.8500.6440.1450.555
BGE-Base-en-v1.5109M0.8940.2130.5270.8580.6420.1420.546
CodeT5+-110M110M0.8700.1790.3280.8150.5800.1180.482

Multi-Language Code Search (CodeSearchNet)

LanguageNDCG@10MRR@10
Python0.9790.976
Go0.7970.767
Java0.6390.600
PHP0.6270.585
JavaScript0.6210.578
Ruby0.5790.535

Full Results (All 12 Tasks)

TaskNDCG@10MRR@10
codesearchnet-python0.9790.976
stackoverflow-qa0.8340.810
codefeedback-st0.8140.775
codesearchnet-go0.7970.767
synthetic-text2sql0.7360.662
codesearchnet-java0.6390.600
codesearchnet-php0.6270.585
codesearchnet-javascript0.6210.578
codesearchnet-ruby0.5790.535
apps0.3490.307
codetrans-dl0.2860.164
cosqa0.2090.165
Average (12 tasks)0.6230.577

Usage

With Transformers

python
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoTokenizer

# Load model
model = AutoModel.from_pretrained("faisalmumtaz/codecompass-embed", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained("faisalmumtaz/codecompass-embed")

# CRITICAL: Enable bidirectional attention for embeddings
for layer in model.model.layers:
    layer.self_attn.is_causal = False

model.eval()

def encode(texts, is_query=False):
    # Add instruction prefix for queries
    if is_query:
        texts = [f"Instruct: Find the most relevant code snippet given the following query:\nQuery: {{t}}" for t in texts]
    
    inputs = tokenizer(texts, padding=True, truncation=True, max_length=512, return_tensors="pt")
    
    with torch.no_grad():
        outputs = model(**inputs, output_hidden_states=True)
        hidden = outputs.hidden_states[-1]
        
        # Mean pooling
        mask = inputs["attention_mask"].unsqueeze(-1).float()
        embeddings = (hidden * mask).sum(1) / mask.sum(1).clamp(min=1e-9)
        
        # L2 normalize
        embeddings = F.normalize(embeddings, p=2, dim=-1)
    
    return embeddings

# Example: Code Search
query = "How to sort a list in Python"
code_snippets = [
    "def sort_list(lst):\n    return sorted(lst)",
    "def add_numbers(a, b):\n    return a + b",
    "def reverse_string(s):\n    return s[::-1]",
]

query_emb = encode([query], is_query=True)
code_embs = encode(code_snippets, is_query=False)

# Compute similarities
similarities = (query_emb @ code_embs.T).squeeze()
print(f"Query: {{query}}")
for i, (code, sim) in enumerate(zip(code_snippets, similarities)):
    print(f"  [{{sim:.4f}}] {{code[:50]}}...")

Instruction Templates

For optimal performance, use these instruction prefixes for queries:

TaskInstruction Template
NL → CodeInstruct: Find the most relevant code snippet given the following query:\nQuery: {{query}}
Code → CodeInstruct: Find an equivalent code snippet given the following code snippet:\nQuery: {{query}}
Tech Q&AInstruct: Find the most relevant answer given the following question:\nQuery: {{query}}
Text → SQLInstruct: Given a natural language question and schema, find the corresponding SQL query:\nQuery: {{query}}

Note: Document/corpus texts do NOT need instruction prefixes.

Training Details

Training followed a two-stage approach:

Stage 1 — Embedding Conversion (8.8M samples): Converted Qwen2.5-Coder-0.5B from a causal language model to a bidirectional embedding model. Trained on 8.8M samples spanning CoRNStack (Python, Java, JavaScript, Go, Ruby, PHP), CoderPile, StackOverflow, and synthetic data with mined hard negatives.

Stage 2 — Hard Negative Refinement (100K samples): Continued fine-tuning on a curated 100K-sample subset with hard negatives.

  • Base Model: Qwen2.5-Coder-0.5B
  • Architecture: Bidirectional attention across all 24 layers, mean pooling, L2 normalization
  • Loss: InfoNCE with temperature τ=0.05
  • Effective Batch Size: 1024 (via GradCache)
  • Hardware: NVIDIA H100 (95GB)

Limitations

  • Strongest on Python; other languages show lower but competitive performance
  • Weaker on competitive programming tasks (APPS) due to long solution lengths vs. 512 training context
  • May not generalize to low-resource programming languages not seen in training

Citation

bibtex
@misc{{codecompass2026,
  author = {{Faisal Mumtaz}},
  title = {{CodeCompass-Embed: A Code Embedding Model for Semantic Code Search}},
  year = {{2026}},
  publisher = {{Hugging Face}},
  url = {{https://huggingface.co/faisalmumtaz/codecompass-embed}}
}}

License

Apache 2.0