Leri777 commited on
Commit
16013c5
·
verified ·
1 Parent(s): 3c19b27

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -51
app.py CHANGED
@@ -1,14 +1,15 @@
1
  import os
2
  import logging
 
3
  from logging.handlers import RotatingFileHandler
4
-
5
  import gradio as gr
6
  from transformers import AutoTokenizer, BitsAndBytesConfig
7
  from langchain_huggingface import ChatHuggingFace
8
  from langchain.prompts import PromptTemplate
9
  from langchain.chains import LLMChain
10
 
11
- # Настройка логирования
12
  log_file = '/tmp/app_debug.log'
13
  logger = logging.getLogger(__name__)
14
  logger.setLevel(logging.DEBUG)
@@ -18,67 +19,75 @@ logger.addHandler(file_handler)
18
 
19
  logger.debug("Application started")
20
 
 
21
  MODEL_ID = "Qwen/Qwen2.5-Coder-7B-Instruct"
22
- MODEL_NAME = MODEL_ID.split("/")[-1]
23
-
24
- template = """<|im_start|>system\n{system_prompt}\n<|im_end|>\n{history}<|im_start|>user\n{human_input}\n<|im_end|>\n<|im_start|>assistant\n"""
25
- prompt = PromptTemplate(template=template, input_variables=["system_prompt", "history", "human_input"])
26
-
27
- def format_history(history):
28
- return "".join([f"<|im_start|>user\n{h[0]}\n<|im_end|>\n<|im_start|>assistant\n{h[1]}\n<|im_end|>\n" for h in history])
29
-
30
- def predict(message, history, system_prompt, temperature, max_new_tokens, top_k, repetition_penalty, top_p):
31
- logger.debug(f"Received prediction request: message='{message}', system_prompt='{system_prompt}'")
32
-
33
- chat_model.temperature = temperature
34
- chat_model.max_new_tokens = max_new_tokens
35
- chat_model.top_k = top_k
36
- chat_model.repetition_penalty = repetition_penalty
37
- chat_model.top_p = top_p
38
 
39
- chain = LLMChain(llm=chat_model, prompt=prompt)
40
-
41
- try:
42
- formatted_history = format_history(history)
43
- for chunk in chain.stream({"system_prompt": system_prompt, "history": formatted_history, "human_input": message}):
44
- yield chunk["text"]
45
- logger.debug(f"Prediction completed successfully for message: '{message}'")
46
- except Exception as e:
47
- logger.exception(f"Error during prediction: {str(e)}")
48
- yield "An error occurred during processing."
49
 
 
50
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
 
 
51
  chat_model = ChatHuggingFace(
52
  model_name=MODEL_ID,
53
- tokenizer=tokenizer,
54
  model_kwargs={
55
  "device_map": "auto",
56
- "quantization_config": BitsAndBytesConfig(load_in_4bit=True),
57
- }
 
 
58
  )
59
 
60
  logger.debug("Model and tokenizer loaded successfully")
61
 
62
- gr.ChatInterface(
63
- predict,
64
- title=f"🤖 {MODEL_NAME}",
65
- description=f"This is the {MODEL_NAME} model designed for coding assistance and general AI tasks.",
66
- examples=[
67
- ["Can you solve the equation 2x + 3 = 11 for x in Python?"],
68
- ["Write a Java program that checks if a number is even or odd."],
69
- ["How can I reverse a string in JavaScript?"],
70
- ["Create a C++ function to find the factorial of a number."],
71
- ["Write a Python list comprehension to generate a list of squares of numbers from 1 to 10."],
72
- ],
73
- additional_inputs=[
74
- gr.Textbox("You are a code assistant.", label="System prompt"),
75
- gr.Slider(0, 1, 0.3, label="Temperature"),
76
- gr.Slider(128, 4096, 1024, label="Max new tokens"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  gr.Slider(1, 80, 40, label="Top K sampling"),
78
  gr.Slider(0, 2, 1.1, label="Repetition penalty"),
79
- gr.Slider(0, 1, 0.95, label="Top P sampling"),
80
  ],
81
- theme=gr.themes.Soft(primary_hue="blue"),
82
- ).queue().launch()
83
-
84
- logger.debug("Chat interface initialized and launched")
 
1
  import os
2
  import logging
3
+ from threading import Thread
4
  from logging.handlers import RotatingFileHandler
5
+ import torch
6
  import gradio as gr
7
  from transformers import AutoTokenizer, BitsAndBytesConfig
8
  from langchain_huggingface import ChatHuggingFace
9
  from langchain.prompts import PromptTemplate
10
  from langchain.chains import LLMChain
11
 
12
+ # Logging setup
13
  log_file = '/tmp/app_debug.log'
14
  logger = logging.getLogger(__name__)
15
  logger.setLevel(logging.DEBUG)
 
19
 
20
  logger.debug("Application started")
21
 
22
+ # Define model parameters
23
  MODEL_ID = "Qwen/Qwen2.5-Coder-7B-Instruct"
24
+ CONTEXT_LENGTH = 16000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ # Configuration for 4-bit quantization
27
+ quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
 
 
 
 
 
 
 
 
28
 
29
+ # Load tokenizer
30
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
31
+
32
+ # Initialize HuggingFace Chat model with LangChain
33
  chat_model = ChatHuggingFace(
34
  model_name=MODEL_ID,
 
35
  model_kwargs={
36
  "device_map": "auto",
37
+ "quantization_config": quantization_config,
38
+ "attn_implementation": "flash_attention_2",
39
+ },
40
+ tokenizer=tokenizer
41
  )
42
 
43
  logger.debug("Model and tokenizer loaded successfully")
44
 
45
+ # Define the conversation template for LangChain
46
+ template = """<|im_start|>system
47
+ {system_prompt}
48
+ <|im_end|>
49
+ {history}
50
+ <|im_start|>user
51
+ {human_input}
52
+ <|im_end|>
53
+ <|im_start|>assistant"""
54
+
55
+ # Create LangChain prompt and chain
56
+ prompt = PromptTemplate(template=template, input_variables=["system_prompt", "history", "human_input"])
57
+ chain = LLMChain(llm=chat_model, prompt=prompt)
58
+
59
+ # Format the conversation history
60
+ def format_history(history):
61
+ formatted = ""
62
+ for human, ai in history:
63
+ formatted += f"<|im_start|>user\n{human}\n<|im_end|>\n<|im_start|>assistant\n{ai}\n<|im_end|>\n"
64
+ return formatted
65
+
66
+ # Prediction function using LangChain and model
67
+ def predict(message, history, system_prompt, temperature, max_new_tokens, top_k, repetition_penalty, top_p):
68
+ formatted_history = format_history(history)
69
+
70
+ try:
71
+ result = chain.run({"system_prompt": system_prompt, "history": formatted_history, "human_input": message})
72
+ return result
73
+ except Exception as e:
74
+ logger.exception(f"Error during prediction: {e}")
75
+ return "An error occurred."
76
+
77
+ # Gradio UI
78
+ gr.Interface(
79
+ fn=predict,
80
+ inputs=[
81
+ gr.Textbox(label="User input"),
82
+ gr.State(),
83
+ gr.Textbox("You are a helpful coding assistant", label="System prompt"),
84
+ gr.Slider(0, 1, 0.7, label="Temperature"),
85
+ gr.Slider(128, 2048, 1024, label="Max new tokens"),
86
  gr.Slider(1, 80, 40, label="Top K sampling"),
87
  gr.Slider(0, 2, 1.1, label="Repetition penalty"),
88
+ gr.Slider(0, 1, 0.95, label="Top P sampling")
89
  ],
90
+ outputs="text",
91
+ title="Qwen2.5-Coder-7B-Instruct with LangChain",
92
+ live=True,
93
+ ).launch()