Views
No views yet
pip install sentence_transformers1from sentence_transformers import CrossEncoder, util
2
3model_path = "ibm-granite/granite-embedding-reranker-english-r2"
4# Load the Sentence Transformer model
5model = CrossEncoder(model_path)
6
7passages = [
8 "Romeo and Juliet is a play by William Shakespeare.",
9 "Climate change refers to long-term shifts in temperatures.",
10 "Shakespeare also wrote Hamlet and Macbeth.",
11 "Water is an inorganic compound with the chemical formula H2O.",
12 "In liquid form, H2O is also called 'water' at standard temperature and pressure."
13 ]
14
15query = "what is the chemical formula of water?"
16
17# encodes query and passages jointly and computes relevance score.
18ranks = model.rank(query, passages, return_documents=True)
19
20# Print document rank and relevance score
21for rank in ranks:
22 print(f"- #{rank['corpus_id']} ({rank['score']:.2f}): {rank['text']}")pip install transformers torch1import torch
2from transformers import AutoModelForSequenceClassification, AutoTokenizer
3
4model_path = "ibm-granite/granite-embedding-reranker-english-r2"
5
6# Load the model and tokenizer
7model = AutoModelForSequenceClassification.from_pretrained(model_path).eval()
8tokenizer = AutoTokenizer.from_pretrained(model_path)
9
10pairs = [
11 ["what is the chemical formula of water?", "Water is an inorganic compound with the chemical formula H2O."],
12 ["what is the chemical formula of water?", "In liquid form, H2O is also called 'water' at standard temperature and pressure."],
13 ["how to implement quick sort in python?", "The weather is nice today"],
14]
15
16
17# tokenize inputs
18tokenized_pairs = tokenizer(pairs, padding=True, truncation=True, return_tensors='pt')
19
20# encode and compute scores
21with torch.no_grad():
22 scores = model(**tokenized_pairs, return_dict=True).logits.view(-1, ).float()
23 print(scores)
241import torch
2from transformers import AutoModel, AutoTokenizer, AutoModelForSequenceClassification
3
4# --------------------------
5# 1. Load retriever (149M)
6# --------------------------
7retriever_model_path = "ibm-granite/granite-embedding-english-r2"
8retriever = AutoModel.from_pretrained(retriever_model_path).eval()
9retriever_tokenizer = AutoTokenizer.from_pretrained(retriever_model_path)
10
11# Example query + candidate documents
12query = "what is the chemical formula of water?"
13documents = [
14 "Water is an inorganic compound with the chemical formula H2O.",
15 "In liquid form, H2O is also called 'water' at standard temperature and pressure.",
16 "The weather is nice today",
17 "Quick sort is a divide and conquer algorithm that sorts by partitioning."
18]
19
20# Encode query and documents
21with torch.no_grad():
22 query_emb = retriever(
23 **retriever_tokenizer(query, return_tensors="pt", truncation=True, padding=True)
24 ).last_hidden_state[:, 0, :] # CLS embedding
25
26 doc_embs = retriever(
27 **retriever_tokenizer(documents, return_tensors="pt", truncation=True, padding=True)
28 ).last_hidden_state[:, 0, :]
29
30# Compute cosine similarity
31query_emb = torch.nn.functional.normalize(query_emb, dim=-1)
32doc_embs = torch.nn.functional.normalize(doc_embs, dim=-1)
33similarities = torch.matmul(query_emb, doc_embs.T).squeeze(0)
34
35# Rank docs by retriever
36retriever_ranked = sorted(
37 zip(documents, similarities.tolist()),
38 key=lambda x: x[1],
39 reverse=True
40)
41print("Retriever ranking:")
42for doc, score in retriever_ranked:
43 print(f"{score:.4f} | {doc}")
44
45
46# --------------------------
47# 2. Load reranker (149M)
48# --------------------------
49reranker_model_path = "ibm-granite/granite-embedding-reranker-english-r2"
50reranker = AutoModelForSequenceClassification.from_pretrained(reranker_model_path).eval()
51reranker_tokenizer = AutoTokenizer.from_pretrained(reranker_model_path)
52
53# Prepare top-k candidates (say top 3 from retriever)
54top_k = 3
55candidate_pairs = [[query, doc] for doc, _ in retriever_ranked[:top_k]]
56
57# Tokenize and rerank
58with torch.no_grad():
59 tokenized_pairs = reranker_tokenizer(
60 candidate_pairs, padding=True, truncation=True, return_tensors="pt"
61 )
62 rerank_scores = reranker(**tokenized_pairs).logits.view(-1, ).float()
63
64# Rank docs by reranker
65reranker_ranked = sorted(
66 zip([doc for doc, _ in retriever_ranked[:top_k]], rerank_scores.tolist()),
67 key=lambda x: x[1],
68 reverse=True
69)
70
71print("\nReranker final ranking:")
72for doc, score in reranker_ranked:
73 print(f"{score:.4f} | {doc}")docker run -p 8080:80 -v hf_cache:/data --pull always ghcr.io/huggingface/text-embeddings-inference:cpu-latest --model-id ibm-granite/granite-embedding-reranker-english-r2docker run --gpus all -p 8080:80 -v hf_cache:/data --pull always ghcr.io/huggingface/text-embeddings-inference:cuda-latest --model-id ibm-granite/granite-embedding-reranker-english-r2/rerank route (see the Text Embeddings Inference OpenAPI Specification for more details):1curl http://0.0.0.0:8080/rerank \
2 -H "Content-Type: application/json" \
3 -d '{
4 "query": "what is the chemical formula of water?",
5 "texts": [
6 "Water is an inorganic compound with the chemical formula H2O.",
7 "In liquid form, H2O is also called '\''water'\'' at standard temperature and pressure.",
8 "The weather is nice today",
9 "Quick sort is a divide and conquer algorithm that sorts by partitioning."
10 ],
11 "raw_scores": false,
12 "return_text": false,
13 "truncate": true,
14 "truncation_direction": "Right"
15 }'| Model | Parameters (M) | Seq. Length | BEIR Avg. | MLDR (en) | Miracl (en) |
|---|---|---|---|---|---|
| Retriever: granite-embedding-small-english-r2 | 47 | 8192 | 50.9 | 40.1 | 42.4 |
| ms-marco-MiniLM-L12-v2 | 33 | 512 | 52.0 | 34.8 | 54.5 |
| bge-reranker-base | 278 | 512 | 51.6 | 36.7 | 40.7 |
| bge-reranker-large | 560 | 512 | 53.0 | 37.9 | 42.2 |
| gte-reranker-modernbert-base | 149 | 8192 | 54.8 | 50.4 | 54.3 |
| granite-embedding-reranker-english-r2 | 149 | 8192 | 55.0 | 44.9 | 54.2 |
| Retriever: granite-embedding-english-r2 | 149 | 8192 | 53.1 | 41.6 | 43.6 |
| ms-marco-MiniLM-L12-v2 | 33 | 512 | 53.2 | 34.5 | 55.4 |
| bge-reranker-base | 278 | 512 | 53.0 | 36.6 | 40.9 |
| bge-reranker-large | 560 | 512 | 54.3 | 38.0 | 42.3 |
| gte-reranker-modernbert-base | 149 | 8192 | 56.1 | 51.2 | 54.8 |
| granite-embedding-reranker-english-r2 | 149 | 8192 | 55.8 | 45.8 | 55.2 |
| Model | granite-embedding-reranker-english-r2 |
|---|---|
| Embedding size | 768 |
| Number of layers | 22 |
| Number of attention heads | 12 |
| Intermediate size | 1152 |
| Activation Function | GeGLU |
| Vocabulary Size | 50368 |
| Max. Sequence Length | 8192 |
| # Parameters | 149M |
@misc{awasthy2025graniteembeddingr2models,
title={Granite Embedding R2 Models},
author={Parul Awasthy and Aashka Trivedi and Yulong Li and Meet Doshi and Riyaz Bhat and Vignesh P and Vishwajeet Kumar and Yushu Yang and Bhavani Iyer and Abraham Daniels and Rudra Murthy and Ken Barker and Martin Franz and Madison Lee and Todd Ward and Salim Roukos and David Cox and Luis Lastras and Jaydeep Sen and Radu Florian},
year={2025},
eprint={2508.21085},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2508.21085},
}