Spaces:
Sleeping
Sleeping
EMMA commited on
Commit ·
3bcffd4
1
Parent(s): 490a29b
update code
Browse files- app.py +9 -0
- benchmark_token_efficiency.py +110 -0
app.py
CHANGED
|
@@ -17,6 +17,7 @@ import nltk
|
|
| 17 |
import torch
|
| 18 |
import torch.nn.functional as F
|
| 19 |
import tiktoken
|
|
|
|
| 20 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 21 |
|
| 22 |
# ==========================================
|
|
@@ -737,6 +738,13 @@ body:has(.progress-level)::before {
|
|
| 737 |
switch_user_btn = gr.Button("👥 Logout", elem_classes=["action-btn"])
|
| 738 |
system_msg = gr.Textbox(label="🔔 System Messages", interactive=False, max_lines=2)
|
| 739 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 740 |
# -------------------------------------------------------
|
| 741 |
# Internal Functions
|
| 742 |
# -------------------------------------------------------
|
|
@@ -1261,6 +1269,7 @@ def main():
|
|
| 1261 |
)
|
| 1262 |
|
| 1263 |
demo = create_gradio_interface(Settings, api_keys)
|
|
|
|
| 1264 |
demo.launch(
|
| 1265 |
server_name="0.0.0.0",
|
| 1266 |
server_port=7860,
|
|
|
|
| 17 |
import torch
|
| 18 |
import torch.nn.functional as F
|
| 19 |
import tiktoken
|
| 20 |
+
from benchmark_token_efficiency import run_benchmark
|
| 21 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 22 |
|
| 23 |
# ==========================================
|
|
|
|
| 738 |
switch_user_btn = gr.Button("👥 Logout", elem_classes=["action-btn"])
|
| 739 |
system_msg = gr.Textbox(label="🔔 System Messages", interactive=False, max_lines=2)
|
| 740 |
|
| 741 |
+
# === ابزار بنچمارک توکنها ===
|
| 742 |
+
with gr.Accordion("Developer / Benchmark Tools", open=False):
|
| 743 |
+
btn_run = gr.Button("Run Token Efficiency Benchmark")
|
| 744 |
+
output_text = gr.Markdown()
|
| 745 |
+
btn_run.click(fn=run_benchmark, outputs=output_text)
|
| 746 |
+
# ============================
|
| 747 |
+
|
| 748 |
# -------------------------------------------------------
|
| 749 |
# Internal Functions
|
| 750 |
# -------------------------------------------------------
|
|
|
|
| 1269 |
)
|
| 1270 |
|
| 1271 |
demo = create_gradio_interface(Settings, api_keys)
|
| 1272 |
+
|
| 1273 |
demo.launch(
|
| 1274 |
server_name="0.0.0.0",
|
| 1275 |
server_port=7860,
|
benchmark_token_efficiency.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import numpy as np
|
| 4 |
+
import tiktoken
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
from app import classify_query_local # یا classify_query_openai بسته به انتخابتان
|
| 7 |
+
|
| 8 |
+
# فرض میکنیم توابع بازیابی شما در ماژولهای زیر هستند (نامها را در صورت نیاز تطبیق دهید)
|
| 9 |
+
# from memory_utils import load_user_memory
|
| 10 |
+
# from build_memory_index import load_indices
|
| 11 |
+
|
| 12 |
+
def count_tokens(text: str, model_name: str = "gpt-4") -> int:
|
| 13 |
+
"""شمارش تعداد توکنهای یک متن با استفاده از توکنایزر"""
|
| 14 |
+
encoding = tiktoken.encoding_for_model(model_name)
|
| 15 |
+
return len(encoding.encode(text))
|
| 16 |
+
|
| 17 |
+
def simulate_retrieval(query, query_category, indices, semantic_text, top_k=3):
|
| 18 |
+
"""
|
| 19 |
+
شبیهسازی بازیابی بر اساس طبقهبندی (EMMA - Routed)
|
| 20 |
+
"""
|
| 21 |
+
retrieved_text = ""
|
| 22 |
+
|
| 23 |
+
if query_category == "semantic_memory":
|
| 24 |
+
retrieved_text = semantic_text
|
| 25 |
+
|
| 26 |
+
elif query_category == "episodic_memory":
|
| 27 |
+
if indices.get("episodic_memory"):
|
| 28 |
+
# بازیابی از ایندکس اپیزودیک
|
| 29 |
+
nodes = indices["episodic_memory"].as_retriever(similarity_top_k=top_k).retrieve(query)
|
| 30 |
+
retrieved_text = "\n".join([n.node.text for n in nodes])
|
| 31 |
+
|
| 32 |
+
elif query_category == "semantic-episodic":
|
| 33 |
+
retrieved_text = semantic_text + "\n"
|
| 34 |
+
if indices.get("episodic_memory"):
|
| 35 |
+
nodes = indices["episodic_memory"].as_retriever(similarity_top_k=top_k).retrieve(query)
|
| 36 |
+
retrieved_text += "\n".join([n.node.text for n in nodes])
|
| 37 |
+
|
| 38 |
+
# اگر unknown باشد، معمولاً فقط از کانتکست مکالمه (session) استفاده میشود
|
| 39 |
+
return retrieved_text
|
| 40 |
+
|
| 41 |
+
def simulate_full_retrieval(query, indices, semantic_text, top_k=3):
|
| 42 |
+
"""
|
| 43 |
+
شبیهسازی بازیابی از تمام حافظهها (EMMA-FULL)
|
| 44 |
+
"""
|
| 45 |
+
retrieved_text = semantic_text + "\n"
|
| 46 |
+
if indices.get("episodic_memory"):
|
| 47 |
+
nodes = indices["episodic_memory"].as_retriever(similarity_top_k=top_k).retrieve(query)
|
| 48 |
+
retrieved_text += "\n".join([n.node.text for n in nodes])
|
| 49 |
+
if indices.get("sessions_memory"):
|
| 50 |
+
nodes = indices["sessions_memory"].as_retriever(similarity_top_k=top_k).retrieve(query)
|
| 51 |
+
retrieved_text += "\n".join([n.node.text for n in nodes])
|
| 52 |
+
|
| 53 |
+
return retrieved_text
|
| 54 |
+
|
| 55 |
+
def run_benchmark(test_queries, username="test_user"):
|
| 56 |
+
# ۱. بارگذاری ایندکسهای کاربر (باید توابع واقعی پروژه خود را فراخوانی کنید)
|
| 57 |
+
# indices = {
|
| 58 |
+
# "episodic_memory": load_index(username, "episodic"),
|
| 59 |
+
# "sessions_memory": load_index(username, "sessions")
|
| 60 |
+
# }
|
| 61 |
+
# semantic_text = get_semantic_memory(username)
|
| 62 |
+
|
| 63 |
+
# مقادیر دامی برای جلوگیری از خطا در صورت عدم اتصال به دیتابیس در این مثال
|
| 64 |
+
indices = {}
|
| 65 |
+
semantic_text = "User values empathy and stability. Big Five: High Openness."
|
| 66 |
+
|
| 67 |
+
results = {
|
| 68 |
+
"EMMA": [], # توکنهای بازیابی شده با کلاسیفایر
|
| 69 |
+
"EMMA_FULL": [] # توکنهای بازیابی شده با جستجوی سراسری
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
for query in tqdm(test_queries, desc="Benchmarking Queries"):
|
| 73 |
+
# ۲. طبقهبندی کوئری
|
| 74 |
+
category = classify_query_local(query)
|
| 75 |
+
|
| 76 |
+
# ۳. بازیابی هدفمند (رویکرد پیشنهادی شما)
|
| 77 |
+
routed_context = simulate_retrieval(query, category, indices, semantic_text)
|
| 78 |
+
tokens_routed = count_tokens(routed_context)
|
| 79 |
+
|
| 80 |
+
# ۴. بازیابی کامل (بیسلاین)
|
| 81 |
+
full_context = simulate_full_retrieval(query, indices, semantic_text)
|
| 82 |
+
tokens_full = count_tokens(full_context)
|
| 83 |
+
|
| 84 |
+
results["EMMA"].append(tokens_routed)
|
| 85 |
+
results["EMMA_FULL"].append(tokens_full)
|
| 86 |
+
|
| 87 |
+
# ۵. محاسبه آمار و ارقام برای مقاله
|
| 88 |
+
avg_emma = np.mean(results["EMMA"])
|
| 89 |
+
avg_full = np.mean(results["EMMA_FULL"])
|
| 90 |
+
reduction_pct = ((avg_full - avg_emma) / avg_full) * 100 if avg_full > 0 else 0
|
| 91 |
+
|
| 92 |
+
print("\n" + "="*40)
|
| 93 |
+
print(" TOKEN EFFICIENCY ANALYSIS RESULTS ")
|
| 94 |
+
print("="*40)
|
| 95 |
+
print(f"Total Queries Evaluated: {len(test_queries)}")
|
| 96 |
+
print(f"Average Tokens Retrieved (EMMA-FULL): {avg_full:.2f}")
|
| 97 |
+
print(f"Average Tokens Retrieved (EMMA Routed): {avg_emma:.2f}")
|
| 98 |
+
print(f"Token Reduction (R_token): {reduction_pct:.2f}%")
|
| 99 |
+
print("="*40)
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
# مجموعهای از کوئریهای تستی برای ارزیابی
|
| 103 |
+
sample_queries = [
|
| 104 |
+
"What did we talk about regarding my job stress last week?", # Expected: episodic
|
| 105 |
+
"Can you remind me what my core values are?", # Expected: semantic
|
| 106 |
+
"I'm feeling very overwhelmed today, just like last time.", # Expected: semantic-episodic
|
| 107 |
+
"Hi, how are you?" # Expected: unknown
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
run_benchmark(sample_queries)
|