rahul27474's picture
v1.2 card + pip wheel
7e35eeb verified
|
Raw History Blame Contribute Delete
13.6 kB
---
license: mit
language:
- hi
- en
library_name: sentence-transformers
pipeline_tag: sentence-similarity
base_model: intfloat/multilingual-e5-small
datasets:
- rahul27474/hinglish-retrieval-train
- rahul27474/hinglish-retrieval-bench
tags:
- sentence-transformers
- sentence-similarity
- feature-extraction
- embeddings
- retrieval
- rag
- hinglish
- code-mixed
- romanized-hindi
- hindi
- onnx
- matryoshka
---
# hinglish-embed-small
A **37M-parameter** text embedding model for **Romanized Hinglish**, Hindi (Devanagari) and English. It is built for RAG, semantic search, FAQ bots and duplicate detection, and it is fast on a plain CPU.
Indian users write `bhai upi se paise kat gaye par receiver ko nhi mile` far more often than proper Hindi or English. General multilingual embedders handle this mixed, misspelled, SMS-style text poorly. This model is built for it, and it matches text in any of the three forms against any of the three.
- **384-dim** embeddings, cosine similarity. With **Matryoshka** training, you can cut them to 256 or 128 dims with little loss.
- **37M params**, 3.2× smaller than `multilingual-e5-small` and 15× smaller than `bge-m3`.
- ONNX **int8** weights are included (38 MB), at ~10 ms per query on a CPU.
- MIT license, so commercial use is OK.
- **[Try it in your browser →](https://huggingface.co/spaces/rahul27474/hinglish-embed-small-demo)**. It runs locally through transformers.js, with no server.
Fine-tuned and vocab-trimmed from [intfloat/multilingual-e5-small](https://huggingface.co/intfloat/multilingual-e5-small). It is not trained from scratch.
## Quickstart: the `hinglish-embed` package (no PyTorch)
```bash
pip install https://huggingface.co/rahul27474/hinglish-embed-small/resolve/main/python/hinglish_embed-0.1.0-py3-none-any.whl
```
```python
from hinglish_embed import HinglishEmbed
model = HinglishEmbed() # downloads the 38 MB int8 model once
# search
index = model.index(["UPI fail hone par paise 3-5 din me wapas aate hain.", "Order cancel: My Orders > Cancel."])
index.search("bhai upi se paise kat gaye", k=1)
# FAQ / support bot
faq = model.faq({"refund kab aayega": "5-7 din me account me aa jayega.", "order cancel kaise kare": "My Orders > Cancel"})
faq.ask("mera paisa wapas kab milega", default="Agent se baat karein")
# duplicate tickets, similarity, intent routing
model.find_duplicates(["app crash ho raha hai", "mera app crash ho rha h", "password reset kaise kare"])
model.similarity("mera refund kab aayega", "When will I get my money back?")
model.best_match("paise kat gaye", ["payment issue", "delivery issue", "login issue"])
```
The package also includes:
- **LangChain:** `from hinglish_embed.langchain import HinglishEmbeddings`
- **LlamaIndex:** `from hinglish_embed.llamaindex import HinglishEmbedding`
- **An API server:** `hinglish-embed serve` starts an OpenAI-compatible `/v1/embeddings` endpoint for n8n, Flowise, Dify or any programming language.
- **A CLI:** for example `hinglish-embed search docs.txt "query"` or `hinglish-embed dupes tickets.txt`.
The package adds the `query: ` / `passage: ` prefixes for you. The full guide is [python/README.md](https://huggingface.co/rahul27474/hinglish-embed-small/blob/main/python/README.md).
## Results (v1.2)
### Practical check: short Hinglish sentences
This is a small, hand-written set, not produced by the training-data generator. It has 46 sentence pairs (same meaning or different meaning) and 33 queries over 20 help-desk answers. The file is `training/practical_set.json`.
| | multilingual-e5-small | v1.1 | **v1.2** |
|---|---|---|---|
| separates same-meaning from different-meaning pairs (AUC) | 0.53 | 0.77 | **0.92** |
| best single-threshold accuracy on those pairs | 0.63 | 0.76 | **0.85** |
| average score, same meaning / different meaning | 0.86 / 0.86 | 0.81 / 0.74 | **0.81 / 0.62** |
| search: correct answer ranked #1 | 0.64 | 0.64 | **0.85** |
e5-small gives almost the same score to every pair of short Hinglish sentences. v1.2 separates them, which FAQ bots and duplicate detection depend on. The set is small, so treat it as a sanity check, not a benchmark.
### Independent public benchmarks (MTEB, nDCG@10)
These are public datasets that we did not create. They are the best guide to how the model behaves on data it has never seen.
| task | **v1.2** (37M) | v1.1 | multilingual-e5-small (118M) | bge-m3 (568M) |
|---|---|---|---|---|
| Belebele, Romanized Hindi (hin_Latn) | **0.587** | 0.574 | 0.538 | 0.617 |
| Belebele, hin_Latn query → English passage | **0.611** | 0.608 | 0.582 | 0.634 |
| Belebele, English query → hin_Latn passage | **0.453** | 0.406 | 0.407 | 0.491 |
| Belebele, Hindi (hin_Deva) | 0.842 | 0.862 | 0.861 | 0.893 |
| Belebele, hin_Deva query → English passage | 0.870 | 0.886 | 0.878 | |
| Belebele, English | 0.923 | 0.942 | 0.948 | 0.955 |
| IndicQA, Hindi | 0.612 | 0.639 | 0.658 | 0.669 |
| SciFact, English | 0.666 | 0.672 | 0.675 | 0.641 |
| NFCorpus, English | 0.296 | 0.304 | 0.310 | 0.317 |
| ArguAna, English | **0.421** | 0.396 | 0.389 | 0.540 |
| FiQA, English | 0.327 | 0.343 | 0.330 | 0.410 |
| **average of the 11 tasks** | **0.666** | 0.647 | 0.631 | |
v1.2 is the best version on Romanized Hindi and on mixed English↔Hinglish retrieval. The trade-off is that it is 1–3 points below e5-small on pure Devanagari Hindi and on pure English. If your data is only formal Hindi or only English, plain e5-small (or v1.1) may suit you better. bge-m3 is still stronger in general, but it is 15× the size and about 20× the CPU latency.
### Hinglish help-desk retrieval (our benchmark, nDCG@10)
The [hinglish-retrieval-bench](https://huggingface.co/datasets/rahul27474/hinglish-retrieval-bench) has 3,626 mixed-language passages. They cover 268 held-out topics in 40 Indian help-desk domains (UPI, IRCTC, Aadhaar/PAN, telecom, insurance, food delivery, …).
| model | Hinglish queries | Hindi queries | English queries |
|---|---|---|---|
| **hinglish-embed-small v1.2** | **0.769** | **0.773** | **0.807** |
| v1.2 at 256 dims | 0.766 | 0.772 | 0.805 |
| v1.2 at 128 dims | 0.758 | 0.764 | 0.800 |
| v1.2, ONNX int8 | 0.764 | | |
| v1.1 | 0.712 | 0.730 | 0.783 |
| BAAI/bge-m3 | 0.612 | 0.717 | 0.743 |
| intfloat/multilingual-e5-small | 0.482 | 0.570 | 0.704 |
> **Caveat:** this benchmark is synthetic and comes from the same LLM pipeline as the training data, although the topics are disjoint. Expect a smaller lead on your own data, and test on a sample of your real queries.
### Version history
- **v1.2 (current):** retrained with two new objectives:
- a paraphrase loss, so that different phrasings of the same question pull together;
- a "keep" loss, so that general English/Hindi text keeps its original e5 embedding.
It also adds Matryoshka dims. The weights are merged 0.5 × fine-tuned + 0.5 × original. That ratio was picked from a sweep over 0.3–1.0, scored on all three evaluations above.
- **v1.1:** a WiSE-FT merge of v1, 0.3 × fine-tuned + 0.7 × original. It is available as revision `079df9ac3d57db3c409d3c5df18aaa52843fe398`.
- **v1:** the pure fine-tune. It **overfit**: strong on our benchmark but well below e5-small on public tasks. It is available as revision `96c4bb389c01262d4538a72e1af11d3e718fcc05`.
To pin a version, pass `revision=...` (or `HinglishEmbed(revision=...)`).
## Score ranges (v1.2, int8)
| pair | p5 | median | p95 |
|---|---|---|---|
| query → its correct passage (300 bench queries) | 0.67 | 0.81 | 0.89 |
| query → random passage (5,000 pairs) | 0.27 | 0.38 | 0.51 |
| same-meaning sentence pairs (practical set) | 0.72 | 0.80 | 0.95 |
| different-meaning sentence pairs (practical set) | 0.50 | 0.62 | 0.79 |
Starting thresholds:
- **Search / RAG:** a passage below **0.60** is almost never relevant. 99% of random passages fall below it, but only ~1.5% of correct ones.
- **FAQ matching, or "is this related":** about **0.72**.
- **Duplicate questions:** about **0.80**.
Questions with different meanings on the *same* topic can still score high, for example `otp nahi aa raha` vs `otp kisi ko share mat karo`. Always check thresholds on a few dozen of your own examples.
## Usage with sentence-transformers
Prefix queries with `query: ` and documents with `passage: `, as in e5. The prefixes are saved as prompts, so `encode_query` / `encode_document` add them for you.
```python
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("rahul27474/hinglish-embed-small") # add truncate_dim=256 for smaller vectors
docs = ["UPI transaction fail hone par paisa 3-5 working days mein automatically refund ho jata hai.",
"ट्रेन टिकट कैंसिल करने पर चार्ज यात्रा से पहले के समय पर निर्भर करता है।",
"To port your mobile number, send an SMS 'PORT <number>' to 1900 to get a UPC code."]
q_emb = model.encode_query(["bhai upi se paise kat gaye par receiver ko nhi mile"]) # sentence-transformers >= 5
d_emb = model.encode_document(docs)
# older versions: model.encode(["query: " + q]) and model.encode(["passage: " + d for d in docs])
print(model.similarity(q_emb, d_emb))
```
To use the faster ONNX int8 weights, install `"sentence-transformers[onnx]"` and load with `SentenceTransformer("rahul27474/hinglish-embed-small", backend="onnx", model_kwargs={"file_name": "onnx/model_quint8_avx2.onnx"})`.
### JavaScript (browser or Node) with transformers.js
```js
import { pipeline } from '@huggingface/transformers';
const embed = await pipeline('feature-extraction', 'rahul27474/hinglish-embed-small', { dtype: 'q8' }); // 38 MB int8
const out = await embed(['query: refund kab aayega', 'passage: Refund 5-7 din mein account mein aa jayega.'],
{ pooling: 'mean', normalize: true });
```
### Plain transformers
Mean-pool `last_hidden_state` using the attention mask, then L2-normalise. Keep the `query: ` / `passage: ` prefixes.
## CPU speed
| | 1 query latency |
|---|---|
| hinglish-embed-small, ONNX int8 | **~10 ms** |
| hinglish-embed-small, PyTorch fp32 | ~26 ms |
| multilingual-e5-small, PyTorch fp32 | ~29 ms |
| bge-m3, PyTorch fp32 | ~248 ms |
All latencies were measured on a 4-vCPU Kaggle CPU box. On the same box, the `hinglish-embed` package took 7.6 ms per query. The int8 embeddings have cosine 0.991 to the fp32 embeddings, and their nDCG is within 0.005 of fp32.
## How it was built
1. **Vocab trim:** the 250k-token XLM-R vocabulary was cut to the 40k tokens used by English, Hindi and Hinglish (99.93% token coverage). This took the model from 118M to 37M params. Before any training, embeddings matched the original model at mean cosine 0.99994.
2. **Synthetic data:** `Qwen3-14B-AWQ` generated 18.9k help-desk passages across 40 domains. Each passage has 3 Hinglish queries, a Hindi query, an English query and a hard negative. `bge-m3` filtered out bad pairs. Details are in [hinglish-retrieval-train](https://huggingface.co/datasets/rahul27474/hinglish-retrieval-train).
3. **Training v1.2:** 1 epoch on one T4, ~50 min. Four objectives were mixed in proportion:
- **retrieval:** `CachedMultipleNegativesRankingLoss` (batch 256, hard negatives) inside `MatryoshkaLoss` (384/256/128/64), over 117k query→passage triplets. The queries are Hinglish, Hindi, English and auto-misspelled (`hai→h`, `nahi→nhi`, `kaise→kese`, …).
- **paraphrase:** the same loss over 115k pairs of different phrasings of the same question.
- **alignment:** `MSELoss` that maps 411k Hinglish/romanized texts onto the frozen original model's embedding of their English or Devanagari source.
- **keep:** `MSELoss` that holds 113k general English and Hindi texts at their original embedding, to limit forgetting.
4. **WiSE-FT merge:** 0.5 × fine-tuned + 0.5 × original weights.
The training, evaluation and export code is in `training/` (`10_train_v2.py`, `12_export_v2.py`).
## Limitations
- It does not beat e5-small everywhere: it is 1–3 points lower on pure Devanagari Hindi and on pure English (see the public table).
- Some unrelated short sentences still score high. In the practical set, `mera refund kab aayega` vs `aaj mausam bahut accha hai` scores 0.80. Combine a threshold with top-k ranking, and keep a fallback reply ("agent se baat karein").
- Our own benchmark is synthetic and in-distribution, so the public MTEB scores are the more trustworthy guide. On general retrieval the model is around e5-small level, not bge-m3 level.
- It is tuned for short help-desk questions and passages of 50–150 words. Chunk long documents.
- It covers Hindi and English only. Other Indic languages and their romanized forms were not trained.
- Like any embedder, it captures similarity, not truth. The training passages contain invented facts.
## Citation / credit
- Base model: [intfloat/multilingual-e5-small](https://huggingface.co/intfloat/multilingual-e5-small) (MIT). Wang et al., *Multilingual E5 Text Embeddings*, 2024.
- Data generator: [Qwen/Qwen3-14B-AWQ](https://huggingface.co/Qwen/Qwen3-14B-AWQ) (Apache-2.0). Filter and baseline: [BAAI/bge-m3](https://huggingface.co/BAAI/bge-m3) (MIT).
- Keep-loss texts: [GooAQ](https://github.com/allenai/gooaq) questions and answers (Apache-2.0), via sentence-transformers/gooaq.
- Alignment pairs: [findnitai/english-to-hinglish](https://huggingface.co/datasets/findnitai/english-to-hinglish) (Apache-2.0) and [sk-community/romanized_hindi](https://huggingface.co/datasets/sk-community/romanized_hindi) (MIT).