Sentence Similarity
sentence-transformers
ONNX
Safetensors
Hindi
English
bert
feature-extraction
embeddings
retrieval
rag
hinglish
code-mixed
romanized-hindi
hindi
matryoshka
text-embeddings-inference
Instructions to use rahul27474/hinglish-embed-small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use rahul27474/hinglish-embed-small with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("rahul27474/hinglish-embed-small") sentences = [ "The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium." ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [3, 3] - Notebooks
- Google Colab
- Kaggle
v1.2: training code
Browse files- training/10_train_v2.py +208 -0
- training/12_export_v2.py +48 -0
- training/practical_set.json +95 -0
training/10_train_v2.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Stage 10 (GPU): v1.2 training. Same data as stage 4, plus:
|
| 2 |
+
# (1) Matryoshka loss on retrieval (384/256/128/64 dims), so users can store smaller vectors;
|
| 3 |
+
# (2) "keep" self-distillation: general English/Hindi text must keep its ORIGINAL e5 embedding
|
| 4 |
+
# (fights the forgetting that hurt v1 on public benchmarks).
|
| 5 |
+
# Then WiSE-FT sweep vs the trimmed original, evaluated on our bench + public MTEB, with v1.1 (hub) as the reference.
|
| 6 |
+
import subprocess, sys, os
|
| 7 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "sentence-transformers>=4.1,<5", "transformers>=4.45,<4.58",
|
| 8 |
+
"mteb>=1.20,<2", "datasets"], check=False)
|
| 9 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "0"; os.environ["WANDB_DISABLED"] = "true"
|
| 10 |
+
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
| 11 |
+
import glob, json, random, re, time, math, shutil, traceback, gc
|
| 12 |
+
import numpy as np, torch, mteb
|
| 13 |
+
from datasets import Dataset, load_dataset
|
| 14 |
+
from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer, SentenceTransformerTrainingArguments, losses, models
|
| 15 |
+
from sentence_transformers.training_args import BatchSamplers, MultiDatasetBatchSamplers
|
| 16 |
+
from transformers import AutoModel
|
| 17 |
+
|
| 18 |
+
W = "/kaggle/working"; random.seed(7); np.random.seed(7)
|
| 19 |
+
t0 = time.time()
|
| 20 |
+
def log(*a): print(f"[{(time.time()-t0)/60:6.1f}m]", *a, flush=True)
|
| 21 |
+
def find(name):
|
| 22 |
+
h = glob.glob(f"/kaggle/input/**/{name}", recursive=True); assert h, name; return h[0]
|
| 23 |
+
TRIM = os.path.dirname(find("he-trimmed/config.json"))
|
| 24 |
+
SAMPLES = find("samples.jsonl")
|
| 25 |
+
BENCH = os.path.dirname(find("hinglish-retrieval-bench/corpus.jsonl"))
|
| 26 |
+
Q, P = "query: ", "passage: "
|
| 27 |
+
PRACT = json.loads(r'''__PRACTICAL__''')
|
| 28 |
+
def load_trim(): # he-trimmed was saved by ST 5.x; rebuild the e5 stack (mean pooling + normalize) so ST 4.x can load it
|
| 29 |
+
t = models.Transformer(TRIM, max_seq_length=256)
|
| 30 |
+
return SentenceTransformer(modules=[t, models.Pooling(t.get_word_embedding_dimension(), "mean"), models.Normalize()], device="cuda")
|
| 31 |
+
|
| 32 |
+
# ------------------------------------------------------------------ data (identical split logic to stage 4)
|
| 33 |
+
rows = [json.loads(l) for l in open(SAMPLES, encoding="utf-8")]
|
| 34 |
+
seen, uniq = set(), []
|
| 35 |
+
for r in rows:
|
| 36 |
+
k = r["passage"].strip()[:200]
|
| 37 |
+
if k in seen: continue
|
| 38 |
+
seen.add(k); uniq.append(r)
|
| 39 |
+
train = [r for r in uniq if r["split"] == "train"] # bench topics never touched
|
| 40 |
+
log("train rows", len(train))
|
| 41 |
+
|
| 42 |
+
SUBS = [(r"\bhai\b", ["h", "he", "hai"]), (r"\bnahi\b", ["nhi", "nai", "nahin"]), (r"\bnahin\b", ["nhi", "nahi"]),
|
| 43 |
+
(r"\bkaise\b", ["kese", "kaisay", "kaise"]), (r"\bkya\b", ["kia", "kyaa"]), (r"\bkar\b", ["kr"]), (r"\bkarna\b", ["krna"]),
|
| 44 |
+
(r"\bkaro\b", ["kro"]), (r"\bkare\b", ["kre", "karein"]), (r"\bmein\b", ["me", "mai", "main"]), (r"\bme\b", ["mein", "mai"]),
|
| 45 |
+
(r"\bhoon\b", ["hu", "hun"]), (r"\bhu\b", ["hoon"]), (r"\bplease\b", ["plz", "pls"]), (r"\byou\b", ["u"]), (r"\bkyun\b", ["kyu", "kyon"]),
|
| 46 |
+
(r"\bthik\b", ["theek", "thk"]), (r"\btheek\b", ["thik"]), (r"\baap\b", ["ap"]), (r"\bmujhe\b", ["muje", "mjhe"]),
|
| 47 |
+
(r"\bpaise\b", ["pese", "paisa"]), (r"\bkab\b", ["kb"]), (r"\bab\b", ["abb"]), (r"\bsab\b", ["sb"]), (r"\bkuch\b", ["kuchh", "kch"]),
|
| 48 |
+
(r"\bhota\b", ["hotaa"]), (r"\braha\b", ["rha"]), (r"\brahi\b", ["rhi"]), (r"\bgaya\b", ["gya"]), (r"\bkyunki\b", ["kyuki", "qki"])]
|
| 49 |
+
def misspell(s):
|
| 50 |
+
out = s.lower() if random.random() < 0.7 else s
|
| 51 |
+
hit = False
|
| 52 |
+
for pat, reps in SUBS:
|
| 53 |
+
if re.search(pat, out) and random.random() < 0.6:
|
| 54 |
+
out = re.sub(pat, lambda m: random.choice(reps), out); hit = True
|
| 55 |
+
if random.random() < 0.3:
|
| 56 |
+
ws = out.split()
|
| 57 |
+
if ws: i = random.randrange(len(ws)); ws[i] = ws[i].replace("aa", "a").replace("ee", "i").replace("oo", "u"); out = " ".join(ws)
|
| 58 |
+
return out if (hit or out != s) else None
|
| 59 |
+
|
| 60 |
+
# BGE-M3 cleaning (same thresholds as stage 4)
|
| 61 |
+
bge = SentenceTransformer("BAAI/bge-m3", device="cuda"); bge.max_seq_length = 320; bge.half()
|
| 62 |
+
enc = lambda t: bge.encode(t, batch_size=64, normalize_embeddings=True, convert_to_numpy=True, show_progress_bar=False)
|
| 63 |
+
eq, ep, en = enc([r["query_english"] for r in train]), enc([r["passage"] for r in train]), enc([r["hard_negative"] for r in train])
|
| 64 |
+
s_pos, s_neg = (eq * ep).sum(1), (eq * en).sum(1)
|
| 65 |
+
train = [dict(r, _neg_ok=bool(n)) for r, k, n in zip(train, s_pos > 0.45, s_neg < s_pos - 0.02) if k]
|
| 66 |
+
log("after bge cleaning", len(train)); del bge; gc.collect(); torch.cuda.empty_cache()
|
| 67 |
+
|
| 68 |
+
teacher = load_trim(); teacher.half()
|
| 69 |
+
tenc = lambda t: teacher.encode(t, batch_size=256, normalize_embeddings=True, convert_to_numpy=True, show_progress_bar=False).astype(np.float32).tolist()
|
| 70 |
+
|
| 71 |
+
# (a) alignment: Hinglish/romanized/misspelled -> teacher(English / Devanagari)
|
| 72 |
+
src, tgt = [], []
|
| 73 |
+
for r in train:
|
| 74 |
+
for q in r["queries_hinglish"]:
|
| 75 |
+
src.append(r["query_english"]); tgt.append(q)
|
| 76 |
+
m = misspell(q)
|
| 77 |
+
if m: src.append(r["query_english"]); tgt.append(m)
|
| 78 |
+
src.append(r["query_hindi"]); tgt.append(r["query_english"])
|
| 79 |
+
eh = load_dataset("findnitai/english-to-hinglish", split="train").shuffle(seed=1)
|
| 80 |
+
for x in eh.select(range(min(len(eh), 150000)))["translation"]:
|
| 81 |
+
if x and x.get("en") and x.get("hi_ng") and 3 < len(x["hi_ng"]) < 300:
|
| 82 |
+
src.append(x["en"]); tgt.append(x["hi_ng"])
|
| 83 |
+
m = misspell(x["hi_ng"])
|
| 84 |
+
if m and random.random() < 0.5: src.append(x["en"]); tgt.append(m)
|
| 85 |
+
rh = load_dataset("sk-community/romanized_hindi", split="train").shuffle(seed=1)
|
| 86 |
+
for a, b in zip(*[rh.select(range(120000))[c] for c in ("Hindi", "Transliterated Hindi")]):
|
| 87 |
+
if a and b and 3 < len(b) < 300: src.append(a); tgt.append(b)
|
| 88 |
+
pairs = [(s, t) for s, t in zip(src, tgt) if len(s) <= 200 and len(t) <= 200]
|
| 89 |
+
align_ds = Dataset.from_dict({"source": [Q + s for s, _ in pairs], "target": [Q + t for _, t in pairs], "label": tenc([Q + s for s, _ in pairs])})
|
| 90 |
+
log("align pairs", len(align_ds))
|
| 91 |
+
|
| 92 |
+
# (b) keep: general English + Devanagari text (queries and passages) keeps its original embedding
|
| 93 |
+
keep = []
|
| 94 |
+
gq = load_dataset("sentence-transformers/gooaq", split="train").shuffle(seed=2).select(range(60000))
|
| 95 |
+
keep += [Q + x for x in gq["question"][:30000]] + [P + x[:600] for x in gq["answer"][30000:60000]]
|
| 96 |
+
keep += [P + x for x in rh.select(range(120000, 160000))["Hindi"] if x and 10 < len(x) < 400]
|
| 97 |
+
keep += [Q + x["en"] for x in eh.select(range(150000, min(len(eh), 170000)))["translation"] if x and x.get("en") and len(x["en"]) < 300]
|
| 98 |
+
random.shuffle(keep)
|
| 99 |
+
keep_ds = Dataset.from_dict({"text": keep, "label": tenc(keep)})
|
| 100 |
+
log("keep texts", len(keep_ds)); del teacher; gc.collect(); torch.cuda.empty_cache()
|
| 101 |
+
|
| 102 |
+
# (c) retrieval triplets
|
| 103 |
+
by_dom = {}
|
| 104 |
+
for r in train: by_dom.setdefault(r["domain"], []).append(r)
|
| 105 |
+
A, Pp, N = [], [], []
|
| 106 |
+
for r in train:
|
| 107 |
+
neg = r["hard_negative"] if r["_neg_ok"] else random.choice(by_dom[r["domain"]])["passage"]
|
| 108 |
+
if neg == r["passage"]: continue
|
| 109 |
+
qs = list(r["queries_hinglish"]) + [r["query_hindi"], r["query_english"]]
|
| 110 |
+
qs += [m for m in (misspell(q) for q in r["queries_hinglish"]) if m]
|
| 111 |
+
for q in qs: A.append(Q + q); Pp.append(P + r["passage"]); N.append(P + neg)
|
| 112 |
+
retr_ds = Dataset.from_dict({"anchor": A, "positive": Pp, "negative": N}).shuffle(seed=3)
|
| 113 |
+
log("retrieval triplets", len(retr_ds))
|
| 114 |
+
# (d) paraphrase: different phrasings of the SAME question (Hinglish / misspelled / Hindi / English) pull together,
|
| 115 |
+
# other questions in the batch push apart -> fixes "all short Hinglish sentences look alike"
|
| 116 |
+
PA, PB = [], []
|
| 117 |
+
for r in train:
|
| 118 |
+
g = list(dict.fromkeys(list(r["queries_hinglish"]) + [r["query_hindi"], r["query_english"]] + [m for m in (misspell(q) for q in r["queries_hinglish"]) if m]))
|
| 119 |
+
for i, a in enumerate(g):
|
| 120 |
+
b = random.choice([x for x in g if x != a]) if len(g) > 1 else None
|
| 121 |
+
if b: PA.append(Q + a); PB.append(Q + b)
|
| 122 |
+
para_ds = Dataset.from_dict({"anchor": PA, "positive": PB}).shuffle(seed=4)
|
| 123 |
+
log("paraphrase pairs", len(para_ds))
|
| 124 |
+
|
| 125 |
+
# ------------------------------------------------------------------ train
|
| 126 |
+
student = load_trim()
|
| 127 |
+
DIMS = [384, 256, 128, 64]
|
| 128 |
+
retr_loss = losses.MatryoshkaLoss(student, losses.CachedMultipleNegativesRankingLoss(student, scale=20.0, mini_batch_size=64), DIMS)
|
| 129 |
+
para_loss = losses.MatryoshkaLoss(student, losses.CachedMultipleNegativesRankingLoss(student, scale=20.0, mini_batch_size=128), DIMS)
|
| 130 |
+
args = SentenceTransformerTrainingArguments(
|
| 131 |
+
output_dir=f"{W}/ckpt", num_train_epochs=1, per_device_train_batch_size=256, learning_rate=5e-5, warmup_ratio=0.06,
|
| 132 |
+
fp16=True, gradient_checkpointing=True, batch_sampler=BatchSamplers.NO_DUPLICATES,
|
| 133 |
+
multi_dataset_batch_sampler=MultiDatasetBatchSamplers.PROPORTIONAL, save_strategy="no", logging_steps=100, report_to="none", seed=7)
|
| 134 |
+
SentenceTransformerTrainer(model=student, args=args, train_dataset={"retrieval": retr_ds, "para": para_ds, "align": align_ds, "keep": keep_ds},
|
| 135 |
+
loss={"retrieval": retr_loss, "para": para_loss, "align": losses.MSELoss(student), "keep": losses.MSELoss(student)}).train()
|
| 136 |
+
FT = f"{W}/v2_ft"; student.save(FT); shutil.rmtree(f"{W}/ckpt", ignore_errors=True)
|
| 137 |
+
log("trained"); del student; gc.collect(); torch.cuda.empty_cache()
|
| 138 |
+
|
| 139 |
+
# ------------------------------------------------------------------ evaluation
|
| 140 |
+
rd = lambda f: [json.loads(l) for l in open(f"{BENCH}/{f}", encoding="utf-8")]
|
| 141 |
+
corpus = {d["_id"]: d["text"] for d in rd("corpus.jsonl")}; ids = list(corpus)
|
| 142 |
+
Qs, R = {}, {}
|
| 143 |
+
for typ in ["hinglish", "hindi", "english"]:
|
| 144 |
+
Qs[typ] = {d["_id"]: d["text"] for d in rd(f"queries_{typ}.jsonl")}; R[typ] = {}
|
| 145 |
+
for i, line in enumerate(open(f"{BENCH}/qrels_{typ}.tsv")):
|
| 146 |
+
if i: q, d, g = line.split("\t"); R[typ].setdefault(q, {})[d] = int(g)
|
| 147 |
+
def own_bench(m, dim=None):
|
| 148 |
+
cut = lambda x: x[:, :dim] / np.linalg.norm(x[:, :dim], axis=1, keepdims=True) if dim else x
|
| 149 |
+
D = cut(m.encode([P + corpus[i] for i in ids], batch_size=128, normalize_embeddings=True)); out = {}
|
| 150 |
+
for typ in Qs:
|
| 151 |
+
qids = list(Qs[typ]); Qv = cut(m.encode([Q + Qs[typ][q] for q in qids], batch_size=128, normalize_embeddings=True))
|
| 152 |
+
top = np.argsort(-(Qv @ D.T), axis=1)[:, :10]; nd = []
|
| 153 |
+
for qi, q in enumerate(qids):
|
| 154 |
+
rel = R[typ][q]; got = [ids[j] for j in top[qi]]
|
| 155 |
+
dcg = sum((2 ** rel.get(d, 0) - 1) / np.log2(r + 2) for r, d in enumerate(got))
|
| 156 |
+
idcg = sum((2 ** g - 1) / np.log2(r + 2) for r, g in enumerate(sorted(rel.values(), reverse=True)[:10]))
|
| 157 |
+
nd.append(dcg / idcg if idcg else 0)
|
| 158 |
+
out[f"own/{typ}" + (f"@{dim}" if dim else "")] = round(float(np.mean(nd)), 4)
|
| 159 |
+
return out
|
| 160 |
+
class Enc:
|
| 161 |
+
def __init__(self, m): self.m = m
|
| 162 |
+
def encode(self, sentences, task_name=None, prompt_type=None, **kw):
|
| 163 |
+
s = [((x.get("title") or "") + " " + (x.get("text") or "")).strip() if isinstance(x, dict) else x for x in sentences]
|
| 164 |
+
p = Q if prompt_type is not None and "query" in str(prompt_type).lower() else P
|
| 165 |
+
return self.m.encode([p + x for x in s], batch_size=128, normalize_embeddings=True, convert_to_numpy=True)
|
| 166 |
+
SPEC = {"BelebeleRetrieval": ["hin_Latn-hin_Latn", "hin_Deva-hin_Deva", "hin_Latn-eng_Latn", "eng_Latn-hin_Latn", "hin_Deva-eng_Latn", "eng_Latn-eng_Latn"],
|
| 167 |
+
"IndicQARetrieval": ["hi"], "SciFact": None, "NFCorpus": None, "ArguAna": None, "FiQA2018": None}
|
| 168 |
+
def public(m, tag):
|
| 169 |
+
out = {}
|
| 170 |
+
for tname, subsets in SPEC.items():
|
| 171 |
+
try:
|
| 172 |
+
task = mteb.get_tasks(tasks=[tname])[0]
|
| 173 |
+
if subsets: task.hf_subsets = [s for s in subsets if s in list(task.hf_subsets)]
|
| 174 |
+
for r in mteb.MTEB(tasks=[task]).run(Enc(m), output_folder=f"{W}/mteb/{tag}", eval_splits=["test"], overwrite_results=True, verbosity=0):
|
| 175 |
+
for rows_ in r.scores.values():
|
| 176 |
+
for row in rows_: out[f"{tname}/{row.get('hf_subset', 'default')}"] = round(float(row.get("ndcg_at_10", row["main_score"])), 4)
|
| 177 |
+
except Exception as e: traceback.print_exc(); log("FAILED", tag, tname, e)
|
| 178 |
+
return out
|
| 179 |
+
def practical(m):
|
| 180 |
+
pr = PRACT["pairs"]; ea = m.encode([Q + a for a, _, _ in pr], normalize_embeddings=True); eb = m.encode([Q + b for _, b, _ in pr], normalize_embeddings=True)
|
| 181 |
+
s = (ea * eb).sum(1); y = np.array([l for _, _, l in pr]); pos, neg = s[y == 1], s[y == 0]
|
| 182 |
+
auc = float(np.mean([(p > n) + 0.5 * (p == n) for p in pos for n in neg]))
|
| 183 |
+
acc = max(float(np.mean((s >= t) == (y == 1))) for t in s)
|
| 184 |
+
D = m.encode([P + d for d in PRACT["docs"]], normalize_embeddings=True); Qv = m.encode([Q + q for q, _ in PRACT["search"]], normalize_embeddings=True)
|
| 185 |
+
top1 = float(np.mean([int(np.argmax(Qv[i] @ D.T)) == g for i, (_, g) in enumerate(PRACT["search"])]))
|
| 186 |
+
return {"prac/pair_auc": round(auc, 4), "prac/pair_best_acc": round(acc, 4), "prac/pos_mean": round(float(pos.mean()), 3),
|
| 187 |
+
"prac/neg_mean": round(float(neg.mean()), 3), "prac/search_acc1": round(top1, 4)}
|
| 188 |
+
def evaluate(m, tag):
|
| 189 |
+
m = m.to("cuda"); m.max_seq_length = 512; m.half()
|
| 190 |
+
r = {**practical(m), **own_bench(m), **own_bench(m, 256), **own_bench(m, 128), **public(m, tag)}
|
| 191 |
+
pub = [v for k, v in r.items() if not k.startswith("own")]; r["public_avg"] = round(float(np.mean(pub)), 4) if pub else None
|
| 192 |
+
r["own_avg"] = round(float(np.mean([r["own/hinglish"], r["own/hindi"], r["own/english"]])), 4)
|
| 193 |
+
log(tag, r); return r
|
| 194 |
+
|
| 195 |
+
res = {}
|
| 196 |
+
res["e5-small"] = evaluate(SentenceTransformer("intfloat/multilingual-e5-small", device="cpu"), "e5")
|
| 197 |
+
res["v1.1 (hub)"] = evaluate(SentenceTransformer("rahul27474/hinglish-embed-small", device="cpu"), "v11")
|
| 198 |
+
json.dump(res, open(f"{W}/v2_eval.json", "w"), indent=2)
|
| 199 |
+
orig_sd = AutoModel.from_pretrained(TRIM).state_dict()
|
| 200 |
+
ft_sd = SentenceTransformer(FT, device="cpu")[0].auto_model.state_dict()
|
| 201 |
+
for a in [1.0, 0.8, 0.6, 0.5, 0.4, 0.3]:
|
| 202 |
+
m = SentenceTransformer(FT, device="cpu")
|
| 203 |
+
m[0].auto_model.load_state_dict({k: (a * ft_sd[k].float() + (1 - a) * orig_sd[k].float()).to(ft_sd[k].dtype) if ft_sd[k].is_floating_point() else ft_sd[k] for k in ft_sd})
|
| 204 |
+
if a < 1: m.save(f"{W}/v2_a{a}")
|
| 205 |
+
res[f"v2 a{a}"] = evaluate(m, f"v2a{a}"); json.dump(res, open(f"{W}/v2_eval.json", "w"), indent=2)
|
| 206 |
+
del m; gc.collect(); torch.cuda.empty_cache()
|
| 207 |
+
shutil.rmtree(f"{W}/mteb", ignore_errors=True)
|
| 208 |
+
log("minutes", round((time.time() - t0) / 60)); print(json.dumps(res, indent=2))
|
training/12_export_v2.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Stage 12 (CPU): export the chosen v1.2 WiSE-FT merge (alpha=0.5) to ONNX fp32 + int8, verify parity and int8 bench score.
|
| 2 |
+
import os, sys, json, glob, shutil, subprocess, time
|
| 3 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "sentence-transformers[onnx]>=3.3,<5", "transformers>=4.45,<4.58"], check=False)
|
| 4 |
+
subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", "-q", "diffusers"], check=False)
|
| 5 |
+
import numpy as np, torch
|
| 6 |
+
from sentence_transformers import SentenceTransformer, export_dynamic_quantized_onnx_model
|
| 7 |
+
def find(name):
|
| 8 |
+
h = glob.glob(f"/kaggle/input/**/{name}", recursive=True); assert h, name; return os.path.dirname(h[0])
|
| 9 |
+
SRC = find("v2_a0.5/config.json"); BENCH = find("hinglish-retrieval-bench/corpus.jsonl")
|
| 10 |
+
OUT = "/kaggle/working/hinglish-embed-small"; shutil.copytree(SRC, OUT)
|
| 11 |
+
m = SentenceTransformer(OUT, device="cpu")
|
| 12 |
+
o = SentenceTransformer(OUT, backend="onnx", device="cpu"); o.save_pretrained(OUT)
|
| 13 |
+
export_dynamic_quantized_onnx_model(o, "avx2", OUT)
|
| 14 |
+
shutil.copy(f"{OUT}/onnx/model_quint8_avx2.onnx", f"{OUT}/onnx/model_quantized.onnx")
|
| 15 |
+
print("files", sorted(os.listdir(OUT)), sorted(os.listdir(f"{OUT}/onnx")))
|
| 16 |
+
q8 = SentenceTransformer(OUT, backend="onnx", device="cpu", model_kwargs={"file_name": "onnx/model_quint8_avx2.onnx"})
|
| 17 |
+
rd = lambda f: [json.loads(l) for l in open(f"{BENCH}/{f}", encoding="utf-8")]
|
| 18 |
+
corpus = {d["_id"]: d["text"] for d in rd("corpus.jsonl")}; ids = list(corpus)
|
| 19 |
+
sample = [corpus[i] for i in ids[:50]]
|
| 20 |
+
a = m.encode(sample, normalize_embeddings=True); b = q8.encode(sample, normalize_embeddings=True)
|
| 21 |
+
rep = {"int8_cos_vs_fp32": float(np.mean(np.sum(a * b, 1)))}
|
| 22 |
+
Q = {d["_id"]: d["text"] for d in rd("queries_hinglish.jsonl")}; R = {}
|
| 23 |
+
for i, line in enumerate(open(f"{BENCH}/qrels_hinglish.tsv")):
|
| 24 |
+
if i: q, d, g = line.split("\t"); R.setdefault(q, {})[d] = int(g)
|
| 25 |
+
torch.set_num_threads(os.cpu_count())
|
| 26 |
+
D = q8.encode(["passage: " + corpus[i] for i in ids], batch_size=64, normalize_embeddings=True)
|
| 27 |
+
qids = list(Q); QE = q8.encode(["query: " + Q[q] for q in qids], batch_size=64, normalize_embeddings=True)
|
| 28 |
+
top = np.argsort(-(QE @ D.T), axis=1)[:, :10]; nd = []
|
| 29 |
+
for qi, q in enumerate(qids):
|
| 30 |
+
rel = R[q]; got = [ids[j] for j in top[qi]]
|
| 31 |
+
dcg = sum((2 ** rel.get(d, 0) - 1) / np.log2(r + 2) for r, d in enumerate(got))
|
| 32 |
+
idcg = sum((2 ** g - 1) / np.log2(r + 2) for r, g in enumerate(sorted(rel.values(), reverse=True)[:10]))
|
| 33 |
+
nd.append(dcg / idcg)
|
| 34 |
+
rep["int8_own_hinglish_ndcg10"] = round(float(np.mean(nd)), 4)
|
| 35 |
+
qt = ["query: " + Q[q] for q in qids[:256]]; speed = {}
|
| 36 |
+
for tag, mm in [("pytorch fp32", m), ("onnx int8", q8)]:
|
| 37 |
+
mm.encode(qt[:16]); t = time.time(); [mm.encode([x]) for x in qt[:100]]
|
| 38 |
+
speed[tag] = round((time.time() - t) * 10, 1)
|
| 39 |
+
rep["single_query_ms"] = speed
|
| 40 |
+
PR = json.loads(r'''__PRACTICAL__''')
|
| 41 |
+
pe = lambda t: q8.encode(t, normalize_embeddings=True)
|
| 42 |
+
ps = np.array([float(pe(["query: " + a])[0] @ pe(["query: " + b])[0]) for a, b, _ in PR["pairs"]]); py = np.array([l for *_, l in PR["pairs"]])
|
| 43 |
+
POS = np.array([float(QE[qi] @ D[ids.index(max(R[q], key=R[q].get))]) for qi, q in enumerate(qids)])
|
| 44 |
+
rng = np.random.default_rng(0); RAND = np.array([float(QE[i] @ D[j]) for i, j in zip(rng.integers(0, len(qids), 5000), rng.integers(0, len(ids), 5000))])
|
| 45 |
+
pc = lambda x: {p: round(float(np.percentile(x, p)), 3) for p in (1, 5, 10, 50, 90, 95, 99)}
|
| 46 |
+
rep["score_dist"] = {"query_vs_own_passage": pc(POS), "query_vs_random_passage": pc(RAND), "practical_pairs_same": pc(ps[py == 1]), "practical_pairs_different": pc(ps[py == 0])}
|
| 47 |
+
json.dump(rep, open("/kaggle/working/export_report.json", "w"), indent=2); print(json.dumps(rep, indent=2))
|
| 48 |
+
for f in ["config_sentence_transformers.json", "modules.json", "sentence_bert_config.json"]: print(f, open(f"{OUT}/{f}").read())
|
training/practical_set.json
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"note": "Hand-written sanity set (not from the synthetic generator). pairs: 1 = same meaning, 0 = different meaning. search: each query's gold doc index.",
|
| 3 |
+
"pairs": [
|
| 4 |
+
["mera refund kab aayega", "When will I get my money back?", 1],
|
| 5 |
+
["mera refund kab aayega", "refund kitne din me milta h", 1],
|
| 6 |
+
["mera refund kab aayega", "aaj mausam bahut accha hai", 0],
|
| 7 |
+
["mera refund kab aayega", "order cancel kaise karu", 0],
|
| 8 |
+
["app crash ho raha hai", "App baar baar band ho jata hai", 1],
|
| 9 |
+
["app crash ho raha hai", "mera app crash ho rha h", 1],
|
| 10 |
+
["app crash ho raha hai", "password reset kaise kare", 0],
|
| 11 |
+
["app crash ho raha hai", "delivery late kyun hai", 0],
|
| 12 |
+
["password bhool gaya", "I forgot my password", 1],
|
| 13 |
+
["password bhool gaya", "पासवर्ड भूल गया हूं", 1],
|
| 14 |
+
["password bhool gaya", "account delete kaise kare", 0],
|
| 15 |
+
["password bhool gaya", "kal match kitne baje hai", 0],
|
| 16 |
+
["upi se paise kat gaye par payment fail dikha raha", "UPI debited but transaction failed", 1],
|
| 17 |
+
["upi se paise kat gaye par payment fail dikha raha", "upi pin kaise change kare", 0],
|
| 18 |
+
["upi se paise kat gaye par payment fail dikha raha", "मेरी ट्रेन लेट है", 0],
|
| 19 |
+
["delivery late kyun hai", "mera order abhi tak nahi aaya", 1],
|
| 20 |
+
["delivery late kyun hai", "why is my order delayed", 1],
|
| 21 |
+
["delivery late kyun hai", "order ka bill kaise download kare", 0],
|
| 22 |
+
["bijli ka bill bahut zyada aaya", "electricity bill is too high this month", 1],
|
| 23 |
+
["bijli ka bill bahut zyada aaya", "बिजली का बिल ज्यादा क्यों आया", 1],
|
| 24 |
+
["bijli ka bill bahut zyada aaya", "gas cylinder book kaise kare", 0],
|
| 25 |
+
["bijli ka bill bahut zyada aaya", "phone ka bill kaise bhare", 0],
|
| 26 |
+
["sim card detect nahi ho raha", "phone me sim nahi dikh rahi", 1],
|
| 27 |
+
["sim card detect nahi ho raha", "my phone is not detecting the SIM", 1],
|
| 28 |
+
["sim card detect nahi ho raha", "naya sim kaise activate kare", 0],
|
| 29 |
+
["emi band karni hai", "how to stop my EMI", 1],
|
| 30 |
+
["emi band karni hai", "loan ka interest rate kya hai", 0],
|
| 31 |
+
["emi band karni hai", "bhai party kab hai", 0],
|
| 32 |
+
["pan aadhar link kaise kare", "how to link PAN with Aadhaar", 1],
|
| 33 |
+
["pan aadhar link kaise kare", "पैन को आधार से कैसे लिंक करें", 1],
|
| 34 |
+
["pan aadhar link kaise kare", "aadhar card me address change", 0],
|
| 35 |
+
["pan aadhar link kaise kare", "income tax return kab tak bharna hai", 0],
|
| 36 |
+
["train ticket cancel karna hai", "how to cancel my train ticket", 1],
|
| 37 |
+
["train ticket cancel karna hai", "tatkal ticket kaise book kare", 0],
|
| 38 |
+
["train ticket cancel karna hai", "flight ka refund status", 0],
|
| 39 |
+
["khana thanda aaya", "food was delivered cold", 1],
|
| 40 |
+
["khana thanda aaya", "restaurant kitne baje khulta hai", 0],
|
| 41 |
+
["wifi bahut slow chal raha hai", "internet speed bahut kam hai", 1],
|
| 42 |
+
["wifi bahut slow chal raha hai", "router ka password kaise badle", 0],
|
| 43 |
+
["wifi bahut slow chal raha hai", "mujhe bhook lagi hai", 0],
|
| 44 |
+
["kya main order ka address change kar sakta hu", "can I change the delivery address", 1],
|
| 45 |
+
["kya main order ka address change kar sakta hu", "kya main order cancel kar sakta hu", 0],
|
| 46 |
+
["otp nahi aa raha", "I am not receiving the OTP", 1],
|
| 47 |
+
["otp nahi aa raha", "otp kisi ko share mat karo", 0],
|
| 48 |
+
["salary account kaise khole", "how to open a salary account", 1],
|
| 49 |
+
["salary account kaise khole", "salary kab credit hogi", 0]
|
| 50 |
+
],
|
| 51 |
+
"docs": [
|
| 52 |
+
"Refund 5-7 working days me aapke original payment method me aa jata hai.",
|
| 53 |
+
"Order cancel karne ke liye My Orders me jaakar Cancel button dabayein.",
|
| 54 |
+
"App crash ho to app update karein, cache clear karein aur phone restart karein.",
|
| 55 |
+
"Password reset karne ke liye login page par Forgot Password dabayein, OTP aayega.",
|
| 56 |
+
"UPI se paise kat gaye aur payment fail hua to amount 3-5 din me auto-reverse ho jata hai.",
|
| 57 |
+
"UPI PIN badalne ke liye app me Bank Account > Change UPI PIN chunein.",
|
| 58 |
+
"Delivery late hone par order tracking dekhein; 48 ghante me na aaye to support se baat karein.",
|
| 59 |
+
"बिजली का बिल ज्यादा आने पर मीटर रीडिंग की फोटो लेकर बिजली विभाग में शिकायत करें।",
|
| 60 |
+
"Gas cylinder book karne ke liye 1906 par call karein ya app use karein.",
|
| 61 |
+
"If your phone does not detect the SIM, clean the SIM tray, reinsert the card and restart the phone.",
|
| 62 |
+
"New SIM activation takes up to 4 hours after e-KYC verification.",
|
| 63 |
+
"EMI band karne ke liye bank ko NACH mandate cancel karne ki request dein.",
|
| 64 |
+
"PAN ko Aadhaar se link karne ke liye income tax e-filing portal par Link Aadhaar option use karein.",
|
| 65 |
+
"Aadhaar me address badalne ke liye myAadhaar portal par documents upload karein.",
|
| 66 |
+
"Train ticket cancel karne ke liye IRCTC app me My Bookings > Cancel Ticket chunein; charges class par depend karte hain.",
|
| 67 |
+
"Tatkal booking subah 10 baje AC aur 11 baje non-AC ke liye khulti hai.",
|
| 68 |
+
"Khana thanda ya kharab aaye to order help me photo ke saath complaint karein, refund mil sakta hai.",
|
| 69 |
+
"Slow WiFi ke liye router restart karein aur dekhein kitne devices connected hain.",
|
| 70 |
+
"OTP na aaye to network check karein, DND band karein aur 60 second baad Resend dabayein.",
|
| 71 |
+
"Delivery address order ship hone se pehle hi badla ja sakta hai, My Orders me Edit Address dabayein."
|
| 72 |
+
],
|
| 73 |
+
"search": [
|
| 74 |
+
["paise kab wapas milenge", 0], ["mujhe mera paisa wapas chahiye kab tak", 0], ["refund status kya hai", 0],
|
| 75 |
+
["order cancel krna h", 1], ["how do I cancel my order", 1],
|
| 76 |
+
["app khulte hi band ho jata hai", 2], ["application keeps crashing", 2],
|
| 77 |
+
["password bhool gaya kya kru", 3], ["पासवर्ड रीसेट कैसे करें", 3],
|
| 78 |
+
["bhai upi se paise kat gaye par receiver ko nhi mile", 4], ["upi payment failed but money debited", 4],
|
| 79 |
+
["upi pin change karna hai", 5],
|
| 80 |
+
["order abhi tak nahi aaya", 6], ["parcel kab tak aayega bahut late ho gaya", 6],
|
| 81 |
+
["light ka bill bahut zyada aaya", 7], ["bijli bill galat aaya hai", 7],
|
| 82 |
+
["cylinder kaise book kare", 8],
|
| 83 |
+
["sim card nahi detect karta hai", 9], ["phone me sim nahi dikh rhi", 9],
|
| 84 |
+
["naya sim kab chalu hoga", 10],
|
| 85 |
+
["emi rokni hai", 11], ["auto debit band kaise kare loan ka", 11],
|
| 86 |
+
["pan aadhar link kaise kare", 12],
|
| 87 |
+
["aadhar me pata badalna hai", 13],
|
| 88 |
+
["train ticket cancel karne pe kitna paisa katega", 14], ["irctc ticket cancel", 14],
|
| 89 |
+
["tatkal kitne baje khulta hai", 15],
|
| 90 |
+
["khana thanda aaya refund milega kya", 16],
|
| 91 |
+
["wifi bahut slow hai", 17], ["net nahi chal raha theek se", 17],
|
| 92 |
+
["otp nahi aa raha", 18], ["OTP not received", 18],
|
| 93 |
+
["address change karna hai order ka", 19]
|
| 94 |
+
]
|
| 95 |
+
}
|