SimrusDenuvo commited on
Commit
a79ad35
·
verified ·
1 Parent(s): 2e3aac7

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +94 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import torch
4
+ import time
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM
6
+ from datasets import load_dataset
7
+
8
+ # Конфигурация моделей
9
+ MODEL_CONFIGS = {
10
+ "GigaChat-like": "cointegrated/rugpt2-large",
11
+ "ChatGPT-like": "sberbank-ai/rugpt3medium_based_on_gpt2",
12
+ "DeepSeek-like": "ai-forever/rugpt3small_based_on_gpt2"
13
+ }
14
+
15
+ # Устройство
16
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
+
18
+ # Загрузка моделей
19
+ models = {}
20
+ for label, name in MODEL_CONFIGS.items():
21
+ tokenizer = AutoTokenizer.from_pretrained(name)
22
+ model = AutoModelForCausalLM.from_pretrained(name)
23
+ model.to(device)
24
+ model.eval()
25
+ models[label] = (tokenizer, model)
26
+
27
+ # Загрузка датасета (не используется напрямую, но может быть полезен)
28
+ dataset = load_dataset("ZhenDOS/alpha_bank_data", split="train")
29
+
30
+ # CoT-промпты
31
+ def cot_prompt_1(text):
32
+ return f"Клиент задал вопрос: {text}\nПодумай шаг за шагом и объясни, как бы ты ответил на это обращение от лица банка."
33
+
34
+ def cot_prompt_2(text):
35
+ return f"Вопрос клиента: {text}\nРазложи на части, что именно спрашивает клиент, и предложи логичный ответ с пояснениями."
36
+
37
+ # Генерация
38
+ def generate_all_responses(question):
39
+ results = {}
40
+ for model_name, (tokenizer, model) in models.items():
41
+ results[model_name] = {}
42
+ for i, prompt_func in enumerate([cot_prompt_1, cot_prompt_2], start=1):
43
+ prompt = prompt_func(question)
44
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
45
+ inputs = {k: v.to(device) for k, v in inputs.items()}
46
+
47
+ start_time = time.time()
48
+ with torch.no_grad():
49
+ outputs = model.generate(
50
+ **inputs,
51
+ max_new_tokens=200,
52
+ do_sample=True,
53
+ temperature=0.7,
54
+ top_p=0.9,
55
+ eos_token_id=tokenizer.eos_token_id
56
+ )
57
+ end_time = time.time()
58
+
59
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
60
+ response = response.replace(prompt, "").strip()
61
+ duration = round(end_time - start_time, 2)
62
+
63
+ results[model_name][f"CoT Промпт {i}"] = {
64
+ "response": response,
65
+ "time": f"{duration} сек."
66
+ }
67
+ return results
68
+
69
+ # Отображение
70
+ def display_responses(question):
71
+ all_responses = generate_all_responses(question)
72
+ output = ""
73
+ for model_name, prompts in all_responses.items():
74
+ output += f"\n### Модель: {model_name}\n"
75
+ for prompt_label, content in prompts.items():
76
+ output += f"\n**{prompt_label}** ({content['time']}):\n{content['response']}\n"
77
+ return output.strip()
78
+
79
+ # Интерфейс
80
+ demo = gr.Interface(
81
+ fn=display_responses,
82
+ inputs=gr.Textbox(lines=4, label="Введите клиентский вопрос"),
83
+ outputs=gr.Markdown(label="Ответы от разных моделей"),
84
+ title="Alpha Bank Assistant — сравнение моделей",
85
+ description="Сравнение CoT-ответов от GigaChat, ChatGPT и DeepSeek-подобных моделей на обращение клиента.",
86
+ examples=[
87
+ "Как восстановить доступ в мобильный банк?",
88
+ "Почему с меня списали комиссию за обслуживание карты?",
89
+ "Какие условия по потребительскому кредиту?",
90
+ ]
91
+ )
92
+
93
+ if __name__ == "__main__":
94
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+
2
+ transformers>=4.38.0
3
+ torch>=2.0.0
4
+ gradio>=4.0.0
5
+ datasets
6
+ accelerate