Spaces:
Sleeping
Sleeping
Update app.py
Browse files9 unmodified lines1011121314151617181920212223242526276 unmodified lines34353637383940414243444518 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111122 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871889 unmodified linesDEFAULT_INSTRUCTION = "Given a query, retrieve documents that answer the query."MAX_DOCS = 20MAX_DOC_CHARS = 4000DOC_SEPARATOR = "---"def parse_documents(text: str) -> List[str]:docs = [doc.strip() for doc in text.split(DOC_SEPARATOR) if doc.strip()]docs = docs[:MAX_DOCS]docs = [doc[:MAX_DOC_CHARS] for doc in docs]return docs@spaces.GPUdef rerank(query: str, documents: str, instruction: str, chunk_size: int):reranker = KaLMReranker(MODEL_ID,device=None,6 unmodified linesquery = query.strip()instruction = instruction.strip() or DEFAULT_INSTRUCTIONdocs = parse_documents(documents)if not query:return [], "Please input a query."if not docs:return [], "Please input at least one candidate document."try:rankings = reranker.rank(18 unmodified linesreturn [], f"Error during reranking: {repr(error)}"with gr.Blocks(title="KaLM-Reranker-V1 Demo") as demo:gr.Markdown(f"""# KaLM-Reranker-V1 Demo**KaLM-Reranker-V1** is a fast but not late-interaction reranker for compressed document reranking.Input a query and several candidate documents. The demo returns relevance scores and reranked results.**Document format:** separate candidate documents with `{DOC_SEPARATOR}` (three dashes on its own line).""")with gr.Row():with gr.Column(scale=1):query = gr.Textbox(label="Query",value="What is the capital of China?",lines=3,)instruction = gr.Textbox(label="Instruction",value=DEFAULT_INSTRUCTION,lines=2,)chunk_size = gr.Dropdown(label="Chunk Size",choices=[2, 4, 8, 16],value=4,interactive=True,)documents = gr.Textbox(label="Candidate Documents",value=("The capital of China is Beijing.\n""---\n""Gravity attracts bodies toward one another.\n""---\n""Shanghai is a major city in China.\n""---\n""Paris is the capital of France."),lines=14,)submit = gr.Button("Rerank", variant="primary")with gr.Column(scale=1):output_table = gr.Dataframe(headers=["Rank", "Corpus ID", "Score", "Document"],2 unmodified lines)output_summary = gr.Markdown()submit.click(fn=rerank,inputs=[query, documents, instruction, chunk_size],outputs=[output_table, output_summary],)gr.Examples(examples=[["What is the capital of China?",("The capital of China is Beijing.\n""---\n""Gravity attracts bodies toward one another.\n""---\n""Paris is the capital of France."),DEFAULT_INSTRUCTION,4,],["Which model is suitable for efficient reranking?",("KaLM-Reranker-V1-Nano is designed for efficient reranking.\n""---\n""Large language models are often expensive for reranking.\n""---\n""Image classifiers are used for visual recognition."),DEFAULT_INSTRUCTION,4,],["What is KaLM-Reranker-V1 designed for?",("KaLM-Reranker-V1 is a reranker for compressed document reranking.\n""---\n""KaLM-Embedding is a general-purpose embedding model.\n""---\n""Weather forecasting predicts future weather conditions."),DEFAULT_INSTRUCTION,4,],],inputs=[query, documents, instruction, chunk_size],)gr.Markdown("""## CitationIf you find this demo useful, please cite:```bibtex@misc{zhao2026kalmrerankerv1,title={KaLM-Reranker-V1: Fast but Not Late Interaction for Compressed Document Reranking},author={Xinping Zhao and Jiaxin Xu and Ziqi Dai and Xin Zhang and Shouzheng Huang and Danyu Tang and Xinshuo Hu and Meishan Zhang and Baotian Hu and Min Zhang},year={2026},eprint={2606.22807},archivePrefix={arXiv},primaryClass={cs.CL},url={https://arxiv.org/abs/2606.22807},}```""")if __name__ == "__main__":demo.launch()9 unmodified lines10111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788896 unmodified lines9697989910010118 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851862 unmodified lines1891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352369 unmodified linesDEFAULT_INSTRUCTION = "Given a query, retrieve documents that answer the query."MAX_DOCS = 20MAX_DOC_CHARS = 4000INIT_DOCS = 4EXAMPLES = [{"label": "Capital of China","query": "What is the capital of China?","docs": ["The capital of China is Beijing.","Gravity attracts bodies toward one another.","Paris is the capital of France.",],},{"label": "Efficient Reranking","query": "Which model is suitable for efficient reranking?","docs": ["KaLM-Reranker-V1-Nano is designed for efficient reranking.","Large language models are often expensive for reranking.","Image classifiers are used for visual recognition.",],},{"label": "KaLM-Reranker Design","query": "What is KaLM-Reranker-V1 designed for?","docs": ["KaLM-Reranker-V1 is a reranker for compressed document reranking.","KaLM-Embedding is a general-purpose embedding model.","Weather forecasting predicts future weather conditions.",],},]def _make_vis_updates(count: int):return [gr.update(visible=(i < count)) for i in range(MAX_DOCS)]def add_doc(count: int):count = min(count + 1, MAX_DOCS)return _make_vis_updates(count) + [count]def remove_doc(count: int):count = max(count - 1, 1)return _make_vis_updates(count) + [count]def load_example(example_idx):if example_idx is None:query_upd = gr.update(value="")doc_upds = [gr.update(value="") for _ in range(MAX_DOCS)]return [query_upd] + doc_upds + [INIT_DOCS]ex = EXAMPLES[example_idx]docs = ex["docs"]count = len(docs)query_upd = gr.update(value=ex["query"])doc_upds = [gr.update(value=docs[i] if i < count else "", visible=(i < count))for i in range(MAX_DOCS)]return [query_upd] + doc_upds + [count]@spaces.GPUdef rerank(query: str, instruction: str, chunk_size: int, *doc_texts: str):docs = [doc.strip() for doc in doc_texts if doc and doc.strip()]docs = docs[:MAX_DOCS]docs = [doc[:MAX_DOC_CHARS] for doc in docs]if not query.strip():return [], "Please input a query."if not docs:return [], "Please input at least one candidate document."reranker = KaLMReranker(MODEL_ID,device=None,6 unmodified linesquery = query.strip()instruction = instruction.strip() or DEFAULT_INSTRUCTIONtry:rankings = reranker.rank(18 unmodified linesreturn [], f"Error during reranking: {repr(error)}"# ββ UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Blocks(title="KaLM-Reranker-V1 Demo") as demo:gr.Markdown("""# KaLM-Reranker-V1 Demo**KaLM-Reranker-V1** is a fast but not late-interaction reranker for compressed document reranking.Input a query and several candidate documents. The demo returns relevance scores and reranked results.""")with gr.Row():# ββ Left column: inputs ββwith gr.Column(scale=1):query_input = gr.Textbox(label="Query",value="What is the capital of China?",lines=3,)instruction_input = gr.Textbox(label="Instruction",value=DEFAULT_INSTRUCTION,lines=2,)chunk_size_input = gr.Dropdown(label="Chunk Size",choices=[2, 4, 8, 16],value=4,interactive=True,)# Example selectorexample_selector = gr.Dropdown(label="Load Example",choices=[ex["label"] for ex in EXAMPLES],value=None,interactive=True,)gr.Markdown("### Candidate Documents")doc_count = gr.State(value=INIT_DOCS)doc_textboxes: List[gr.Textbox] = []with gr.Column() as doc_list:for i in range(MAX_DOCS):visible = i < INIT_DOCStb = gr.Textbox(label=f"Document {i + 1}",lines=2,placeholder=f"Enter document {i + 1}...",visible=visible,)doc_textboxes.append(tb)with gr.Row():add_btn = gr.Button("+ Add Document", size="sm")remove_btn = gr.Button("- Remove Last", size="sm")submit = gr.Button("Rerank", variant="primary")# ββ Right column: outputs ββwith gr.Column(scale=1):output_table = gr.Dataframe(headers=["Rank", "Corpus ID", "Score", "Document"],2 unmodified lines)output_summary = gr.Markdown()# ββ Events ββadd_btn.click(fn=add_doc,inputs=[doc_count],outputs=doc_textboxes + [doc_count],)remove_btn.click(fn=remove_doc,inputs=[doc_count],outputs=doc_textboxes + [doc_count],)example_selector.change(fn=load_example,inputs=[example_selector],outputs=[query_input] + doc_textboxes + [doc_count],)submit.click(fn=rerank,inputs=[query_input, instruction_input, chunk_size_input] + doc_textboxes,outputs=[output_table, output_summary],)gr.Markdown("""## CitationIf you find this demo useful, please cite:```bibtex@misc{zhao2026kalmrerankerv1,title={KaLM-Reranker-V1: Fast but Not Late Interaction for Compressed Document Reranking},author={Xinping Zhao and Jiaxin Xu and Ziqi Dai and Xin Zhang and Shouzheng Huang and Danyu Tang and Xinshuo Hu and Meishan Zhang and Baotian Hu and Min Zhang},year={2026},eprint={2606.22807},archivePrefix={arXiv},primaryClass={cs.CL},url={https://arxiv.org/abs/2606.22807},}```""")if __name__ == "__main__":demo.launch()
app.py+127-79