Text Ranking
sentence-transformers
ONNX
Safetensors
Transformers.js
modernbert
text-classification
reranker
cross-encoder
rerank
rag
retrieval
chinese
japanese
korean
langchain
llamaindex
haystack
text-embeddings-inference
Instructions to use CheezOne/reranker-cjk-small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use CheezOne/reranker-cjk-small with sentence-transformers:
from sentence_transformers import CrossEncoder model = CrossEncoder("CheezOne/reranker-cjk-small") query = "Which planet is known as the Red Planet?" passages = [ "Venus is often called Earth's twin because of its similar size and proximity.", "Mars, known for its reddish appearance, is often referred to as the Red Planet.", "Jupiter, the largest planet in our solar system, has a prominent red spot.", "Saturn, famous for its rings, is sometimes mistaken for the Red Planet." ] scores = model.predict([(query, passage) for passage in passages]) print(scores) - Transformers.js
How to use CheezOne/reranker-cjk-small with Transformers.js:
// npm i @huggingface/transformers import { AutoTokenizer, AutoModelForSequenceClassification } from '@huggingface/transformers'; const tokenizer = await AutoTokenizer.from_pretrained('CheezOne/reranker-cjk-small'); const model = await AutoModelForSequenceClassification.from_pretrained('CheezOne/reranker-cjk-small'); const query = 'Which planet is known as the Red Planet?'; const documents = [ 'Mars, known for its reddish appearance, is often referred to as the Red Planet.', 'Venus is often called the twin of Earth because of its similar size and proximity.', ]; const inputs = tokenizer(new Array(documents.length).fill(query), { text_pair: documents, padding: true, truncation: true }); const { logits } = await model(inputs); console.log(logits.sigmoid().tolist()); // one relevance score per document - Notebooks
- Google Colab
- Kaggle
Download scripts/make_rr_card.py from CheezOne/reranker-cjk-small: direct link, hf CLI and curl.
- Browser
- Download file 8.25 kB
-
https://huggingface.co/CheezOne/reranker-cjk-small/resolve/main/scripts/make_rr_card.py
- Command line
-
hf download hf://CheezOne/reranker-cjk-small/scripts/make_rr_card.py
-
curl -L -o make_rr_card.py https://huggingface.co/CheezOne/reranker-cjk-small/resolve/main/scripts/make_rr_card.py
8.25 kB
| """Build the model card (README.md) for the CJK reranker from the evaluation JSONs (no hand-copied numbers).""" | |
| import json, os, sys | |
| REPO = "CheezOne/reranker-chinese-japanese-korean-multilingual-small" | |
| run = sys.argv[1] if len(sys.argv) > 1 else "runs/rr_v1/student" | |
| stu = json.load(open("eval/rr_student_miracl.json")); comp = json.load(open("eval/rr_competitors_miracl.json")) | |
| onnx = json.load(open(os.path.join(run, "onnx_report.json"))) if os.path.exists(os.path.join(run, "onnx_report.json")) else None | |
| L = ["zh", "ja", "ko", "th", "id", "en"] | |
| rows = [("**this model** (mmBERT-small, ~140M)", stu["student"]), | |
| ("BAAI/bge-reranker-v2-m3 (568M, teacher)", stu["models/BAAI/bge-reranker-v2-m3"]), | |
| ("hotchpotch/japanese-reranker-cross-encoder-small-v1 (118M)", comp["models/hotchpotch/japanese-reranker-cross-encoder-small-v1"]), | |
| ("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1 (118M)", comp["models/cross-encoder/mmarco-mMiniLMv2-L12-H384-v1"]), | |
| ("BAAI/bge-reranker-base (278M)", comp["models/BAAI/bge-reranker-base"])] | |
| def table(): | |
| out = ["| model | " + " | ".join(L) + " | avg | pairs/s (L40, bf16) |", "|---" * (len(L) + 3) + "|"] | |
| best = {l: max(r[l]["ndcg@10"] for n, r in rows if "teacher" not in n) for l in L} | |
| for n, r in rows: | |
| v = [r[l]["ndcg@10"] for l in L] | |
| cells = [(f"**{x:.3f}**" if x == best[l] and "teacher" not in n else f"{x:.3f}") for x, l in zip(v, L)] | |
| out.append(f"| {n} | " + " | ".join(cells) + f" | {sum(v) / len(v):.3f} | {r['zh']['pairs_per_s_gpu']:.0f} |") | |
| return "\n".join(out) | |
| nq = {l: stu["student"][l]["queries"] for l in L} | |
| s_avg = sum(stu["student"][l]["ndcg@10"] for l in L) / len(L); t_avg = sum(stu["models/BAAI/bge-reranker-v2-m3"][l]["ndcg@10"] for l in L) / len(L) | |
| speed = stu["student"]["zh"]["pairs_per_s_gpu"] / stu["models/BAAI/bge-reranker-v2-m3"]["zh"]["pairs_per_s_gpu"] | |
| onnx_md = "" | |
| if onnx: | |
| langs = [k for k in onnx if k != "size_mb"] | |
| onnx_md = "\n| runtime | size | " + " | ".join(f"nDCG@10 {l}" for l in langs) + " |\n|---|---|" + "---|" * len(langs) + "\n" | |
| onnx_md += "| PyTorch fp32 | 563 MB (bf16 safetensors: 281 MB) | " + " | ".join(f"{onnx[l]['torch_fp32']['ndcg@10']:.3f}" for l in langs) + " |\n" | |
| onnx_md += f"| ONNX fp32 `onnx/model.onnx` | {onnx['size_mb']['fp32']:.0f} MB | " + " | ".join(f"{onnx[l]['onnx_fp32']['ndcg@10']:.3f}" for l in langs) + " |\n" | |
| onnx_md += f"| ONNX int8 `onnx/model_quantized.onnx` | {onnx['size_mb']['int8']:.0f} MB | " + " | ".join(f"{onnx[l]['onnx_int8']['ndcg@10']:.3f}" for l in langs) + " |\n" | |
| onnx_md += f"\n(ONNX check on the first {onnx[langs[0]]['torch_fp32']['queries']} MIRACL queries per language, CPU.)\n" | |
| card = f"""--- | |
| license: apache-2.0 | |
| language: [zh, ja, ko, th, id, en, multilingual] | |
| library_name: sentence-transformers | |
| pipeline_tag: text-ranking | |
| base_model: jhu-clsp/mmBERT-small | |
| datasets: | |
| - CheezOne/reranker-train-chinese-japanese-korean | |
| tags: [reranker, cross-encoder, rerank, rag, retrieval, chinese, japanese, korean, multilingual, onnx, transformers.js, distillation, modernbert] | |
| --- | |
| # Small multilingual reranker for Chinese, Japanese and Korean (and more) | |
| A **140M-parameter cross-encoder reranker** distilled from `BAAI/bge-reranker-v2-m3` into `jhu-clsp/mmBERT-small` (ModernBERT). | |
| Use it as the second stage of RAG / search: give it a query and candidate passages, it returns relevance scores. | |
| - **{s_avg:.3f} avg nDCG@10 on MIRACL reranking** (zh/ja/ko/th/id/en), vs {t_avg:.3f} for the 568M teacher: **{100 * (t_avg - s_avg):.1f} points lower, {speed:.1f}× faster**. | |
| - **Beats every small open reranker we tested on all 6 languages**, including Chinese, where small models are weakest. | |
| - Context up to 8k tokens (ModernBERT), trained at 384 tokens per query+passage. | |
| - ONNX fp32 + int8 included → runs on CPU and in the browser (transformers.js). | |
| 中文简介:一个约 1.4 亿参数的小型重排序(rerank)模型,面向中文、日文、韩文 RAG / 检索。从 bge-reranker-v2-m3 蒸馏而来, | |
| MIRACL 上平均只比老师低 {100 * (t_avg - s_avg):.1f} 分,速度快 {speed:.1f} 倍;在 6 种语言上全部超过我们测过的同级别小模型。附 ONNX(可 CPU / 浏览器运行)。 | |
| ## Results: MIRACL reranking, nDCG@10 | |
| Candidate lists from `mteb/MIRACLReranking` (dev). Queries per language: {", ".join(f"{l} {nq[l]}" for l in L)} | |
| (zh/ja/ko: all queries in our bundled subset; th/id/en: first 200). Same data, same code and same GPU for every model | |
| (`scripts/rr_gpu.py eval`). Bold = best non-teacher model. | |
| {table()} | |
| Notes, so you can judge the numbers yourself: | |
| - **Indonesian (id) was never in our training data**, so that column is zero-shot transfer. | |
| - MIRACL queries were removed from the training data (see the dataset card), but MIRACL and Mr. TyDi share Wikipedia, so passages can overlap. | |
| - hotchpotch's model is Japanese-focused, and the teacher is much larger. We include them as reference points, not as straw men. | |
| - Throughput was measured with batch 128 and max length 512. Expect different numbers on your hardware. | |
| ## Usage | |
| ### sentence-transformers | |
| ```python | |
| from sentence_transformers import CrossEncoder | |
| model = CrossEncoder("{REPO}") | |
| query = "如何办理护照?" | |
| passages = ["办理护照需要携带身份证和户口本到出入境管理局申请。", "护照是一种旅行证件。", "今天北京天气晴朗。"] | |
| print(model.rank(query, passages)) | |
| ``` | |
| ### transformers | |
| ```python | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification | |
| tok = AutoTokenizer.from_pretrained("{REPO}") | |
| model = AutoModelForSequenceClassification.from_pretrained("{REPO}").eval() | |
| pairs = [["東京タワーの高さは?", "東京タワーの高さは333メートルです。"], ["東京タワーの高さは?", "大阪城は豊臣秀吉が築いた城です。"]] | |
| enc = tok(pairs, padding=True, truncation=True, max_length=512, return_tensors="pt") | |
| with torch.no_grad(): | |
| print(model(**enc).logits.view(-1)) # higher = more relevant | |
| ``` | |
| Scores are raw logits; apply `sigmoid` if you want values in 0–1. | |
| ### transformers.js (browser / Node) | |
| ```js | |
| import {{ AutoTokenizer, AutoModelForSequenceClassification }} from "@huggingface/transformers"; | |
| const tok = await AutoTokenizer.from_pretrained("{REPO}"); | |
| const model = await AutoModelForSequenceClassification.from_pretrained("{REPO}", {{ dtype: "q8" }}); | |
| const inputs = tok(["빨간 물약", "빨간 물약"], {{ text_pair: ["체력을 회복하는 빨간 물약입니다.", "서울은 한국의 수도입니다."], padding: true, truncation: true }}); | |
| console.log((await model(inputs)).logits.data); | |
| ``` | |
| ## ONNX | |
| {onnx_md} | |
| The int8 model quantizes embeddings and attention only. ModernBERT's GeGLU MLP activations have outliers, so the MLPs and head stay fp32. | |
| ## Training | |
| - **Teacher**: `BAAI/bge-reranker-v2-m3` scored 551,213 query–passage pairs in 27 minutes on one L40. | |
| - **Data**: [`CheezOne/reranker-train-chinese-japanese-korean`](https://huggingface.co/datasets/CheezOne/reranker-train-chinese-japanese-korean), 51,858 query groups. | |
| - zh: 40k groups from T2Ranking. | |
| - ja/ko/th/en: from Mr. TyDi. | |
| - All Apache-2.0. | |
| - **Loss**: listwise KL between student and teacher score distributions within each group, plus 0.05 × MSE on raw scores. | |
| - **Hyperparameters**: 2 epochs, 16 groups per step, lr 5e-5, max length 384, bf16. 6,484 steps in 55 minutes on one L40. | |
| - **Reproduce**: `scripts/rr_prep.py` → `scripts/rr_gpu.py teacher|train|eval` → `scripts/rr_export_onnx.py`. | |
| ## Limitations | |
| - Trained mostly on Chinese (77% of groups), so ja/ko/th/en saw only 1.3k–3.7k groups each. Domain-specific text (legal, medical, code) is not evaluated. | |
| - It is a reranker, not a retriever: use it on top of BM25 or an embedding model. | |
| - No safety or bias evaluation was done. | |
| ## Citation / credits | |
| Base model: [jhu-clsp/mmBERT-small](https://huggingface.co/jhu-clsp/mmBERT-small) (MIT). Teacher: [BAAI/bge-reranker-v2-m3](https://huggingface.co/BAAI/bge-reranker-v2-m3) (Apache-2.0). | |
| Data: T2Ranking, Mr. TyDi; evaluation: MIRACL (via MTEB). | |
| """ | |
| open(os.path.join(run, "README.md"), "w").write(card); print("wrote", os.path.join(run, "README.md")); print(table()) | |