import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer model_id = "srpone/zoowork-instinct-reranker-0.8b"tok = AutoTokenizer.from_pretrained(model_id, padding_side="left")model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16).cuda().eval() SYSTEM = ('Judge whether the Document meets the requirements based on the Query and ' 'the Instruct provided. Note that the answer can only be "yes" or "no".')INSTRUCTION = "Given a web search query, retrieve relevant passages that answer the query"MAX_DOC_TOKENS = 2048 # the length the model was trained and evaluated at def token_ids(words): ids = set() for w in words: for s in (w, " " + w): enc = tok.encode(s, add_special_tokens=False) if len(enc) == 1: ids.add(enc[0]) return sorted(ids) YES, NO = token_ids(["yes", "Yes"]), token_ids(["no", "No"]) def prompt(query, doc, instruction=INSTRUCTION): doc = tok.decode(tok.encode(doc, add_special_tokens=False)[:MAX_DOC_TOKENS]) user = f"<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}" msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": user}] return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False) @torch.no_grad()def p_yes(query, docs, instruction=INSTRUCTION): enc = tok([prompt(query, d, instruction) for d in docs], return_tensors="pt", padding=True, add_special_tokens=False).to(model.device) logp = torch.log_softmax(model(**enc).logits[:, -1, :].float(), dim=-1) yes, no = logp[:, YES].logsumexp(-1), logp[:, NO].logsumexp(-1) return torch.sigmoid(yes - no).tolist() # P(yes | yes or no) query = "what causes the northern lights"docs = ["The northern lights (aurora borealis) are caused by charged particles from the Sun, carried by the solar " "wind, colliding with oxygen and nitrogen in Earth's upper atmosphere; the collisions emit the green and red " "light seen near the poles.", "The Northern Line is a London Underground line running from Edgware to Morden."]scores = p_yes(query, docs)print(scores) # rank by score ...print([d for d, s in zip(docs, scores) if s >= 0.5]) # ... or keep what passes the 0.5 threshold