Spaces:
Sleeping
Sleeping
Update app.py
Browse files9 unmodified lines10111213131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585916176061626364656667686970717273747576777879802081828384858623248788896 unmodified lines9697983738394041429910010118 unmodified lines120121122123124125126691271281291307313113213313413513679137138139140141841421431441451468914714814915015115295969798991001011021031041051061531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851862 unmodified lines1891901911921931941951961971981992002012022032042052062072082091202102112122131241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641652142152161692172181712192202211742222232242252262271801812282292302312321851862332342352369 unmodified linesDEFAULT_INSTRUCTION = "Given a query, retrieve documents that answer the query."MAX_DOCS = 20MAX_DOC_CHARS = 4000DOC_SEPARATOR = "---"INIT_DOCS = 4
EXAMPLES = [ { "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 parse_documents(text: str) -> List[str]: docs = [doc.strip() for doc in text.split(DOC_SEPARATOR) if doc.strip()]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] return docs
if not query.strip(): return [], "Please input a query." if not docs: return [], "Please input at least one candidate document."
@spaces.GPUdef rerank(query: str, documents: str, instruction: str, chunk_size: int): reranker = KaLMReranker( MODEL_ID, device=None,6 unmodified lines
query = query.strip() instruction = instruction.strip() or DEFAULT_INSTRUCTION docs = 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 lines return [], f"Error during reranking: {repr(error)}"
# ββ UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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(): # ββ Left column: inputs ββ with gr.Column(scale=1): query = gr.Textbox( query_input = gr.Textbox( label="Query", value="What is the capital of China?", lines=3, ) instruction = gr.Textbox( instruction_input = gr.Textbox( label="Instruction", value=DEFAULT_INSTRUCTION, lines=2, ) chunk_size = gr.Dropdown( chunk_size_input = 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,
# Example selector example_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_DOCS tb = 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, documents, instruction, chunk_size], inputs=[query_input, instruction_input, chunk_size_input] + doc_textboxes, 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( """## Citation
If you find this demo useful, please cite:
```bibtex@misc{zhao2026kalmrerankerv1, title={KaLM-Reranker-V1: Fast but Not Late Interaction for Compressed Document Reranking}, 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}, } url={https://arxiv.org/abs/2606.22807},}``` """ )
if __name__ == "__main__": demo.launch()app.py+127-79