from transformers import AutoModel, AutoTokenizer
from peft import PeftModel
import torch, torch.nn.functional as F
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-Embedding-8B", padding_side="right")
model = AutoModel.from_pretrained("Qwen/Qwen3-Embedding-8B", torch_dtype=torch.bfloat16).cuda()
model = PeftModel.from_pretrained(model, "anicka/qwen3-embedding-8b-tibetan-lora").eval()
INSTRUCT = ("Instruct: Given a term in any transliteration scheme "
"(Wylie, Tibetan script, Sanskrit, English), retrieve the "
"matching Tibetan dictionary headword\nQuery: ")
def embed(texts, prefix=""):
enc = tok([prefix + t for t in texts], padding=True, truncation=True,
max_length=256, return_tensors="pt").to("cuda")
h = model(**enc).last_hidden_state
idx = enc.attention_mask.sum(1) - 1
v = h[torch.arange(h.size(0)), idx]
return F.normalize(v.float(), dim=-1)
q = embed(["tongpa nyi"], prefix=INSTRUCT)
d = embed(["stong pa nyid", "སྟོང་པ་ཉིད་", "śūnyatā"])
print(q @ d.T)