"""Score passages for citation share with a trained student (Qwen3-Reranker + LoRA adapter from train_student.py).
Input: a JSONL file, one object per line with at least "query" and "text" (any other fields are
copied to the output). Output: the same objects with a "score" field (log-odds of "yes" against
"no"; higher means a larger expected share of citation). Scores are meant for ranking passages
of the same query; they are not probabilities and are not comparable across queries.
python code/score_passages.py --adapter runs/student_4b/adapter --input passages.jsonl --output scored.jsonl
python code/score_passages.py --base Qwen/Qwen3-Reranker-0.6B --adapter runs/student_06b/adapter \
--input passages.jsonl --output scored.jsonl
Requirements: torch>=2.5, transformers>=5, peft>=0.15. A CUDA GPU is recommended (4B: about 10 GB
in bf16); CPU works for the 0.6B adapter. Passages are truncated to 864 tokens, as in training (max length 1024 minus the template).
"""
import argparse
import json
import torch
PREFIX = ("<|im_start|>system\nJudge whether the Document meets the requirements based on the Query "
"and the Instruct provided. Note that the answer can only be \"yes\" or \"no\".<|im_end|>\n"
"<|im_start|>user\n")
SUFFIX = "<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
INSTRUCT = ("Given a user query, judge whether this passage would be cited by a generative answer "
"engine (Perplexity, ChatGPT Search, Gemini) writing an answer to the query")
MAX_DOC_TOKENS = 864
def build(tok, query, text):
ids = tok(text, add_special_tokens=False).input_ids
if len(ids) > MAX_DOC_TOKENS:
text = tok.decode(ids[:MAX_DOC_TOKENS])
return PREFIX + f": {INSTRUCT}\n: {query}\n: {text}" + SUFFIX
def load(base, adapter, device):
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
tok = AutoTokenizer.from_pretrained(base, padding_side="left")
dtype = torch.bfloat16 if device != "cpu" else torch.float32
model = AutoModelForCausalLM.from_pretrained(base, dtype=dtype).to(device)
model = PeftModel.from_pretrained(model, adapter).eval()
return tok, model
@torch.no_grad()
def score(tok, model, pairs, device, batch_size=8):
yes, no = tok.convert_tokens_to_ids("yes"), tok.convert_tokens_to_ids("no")
out = []
for i in range(0, len(pairs), batch_size):
texts = [build(tok, q, t) for q, t in pairs[i:i + batch_size]]
enc = tok(texts, padding=True, return_tensors="pt").to(device)
last = model(**enc, logits_to_keep=1).logits[:, -1, :].float()
out += (last[:, yes] - last[:, no]).cpu().tolist()
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base", default="Qwen/Qwen3-Reranker-4B")
ap.add_argument("--adapter", required=True)
ap.add_argument("--input", required=True)
ap.add_argument("--output", required=True)
ap.add_argument("--batch-size", type=int, default=8)
ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
args = ap.parse_args()
rows = [json.loads(l) for l in open(args.input) if l.strip()]
tok, model = load(args.base, args.adapter, args.device)
scores = score(tok, model, [(r["query"], r["text"]) for r in rows], args.device, args.batch_size)
with open(args.output, "w") as f:
for r, s in zip(rows, scores):
f.write(json.dumps({**r, "score": s}, ensure_ascii=False) + "\n")
print(f"{len(rows)} passages scored -> {args.output}")
if __name__ == "__main__":
main()