Leri777 commited on
Commit
569b33f
1 Parent(s): bea7c1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -44
app.py CHANGED
@@ -2,7 +2,6 @@ import os
2
  import logging
3
  from logging.handlers import RotatingFileHandler
4
 
5
- import torch
6
  import gradio as gr
7
  from transformers import AutoTokenizer, BitsAndBytesConfig
8
  from langchain_huggingface import ChatHuggingFace
@@ -14,45 +13,23 @@ log_file = '/tmp/app_debug.log'
14
  logger = logging.getLogger(__name__)
15
  logger.setLevel(logging.DEBUG)
16
  file_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5)
17
- file_handler.setLevel(logging.DEBUG)
18
- formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
19
- file_handler.setFormatter(formatter)
20
  logger.addHandler(file_handler)
21
 
22
  logger.debug("Application started")
23
 
24
  MODEL_ID = "Qwen/Qwen2.5-Coder-7B-Instruct"
25
- CHAT_TEMPLATE = "ChatML"
26
  MODEL_NAME = MODEL_ID.split("/")[-1]
27
- CONTEXT_LENGTH = 16000
28
 
29
- COLOR = "blue"
30
- EMOJI = "🤖"
31
- DESCRIPTION = f"This is the {MODEL_NAME} model designed for coding assistance and general AI tasks."
32
-
33
- # Prompt template for conversation
34
- template = """<|im_start|>system
35
- {system_prompt}
36
- <|im_end|>
37
- {history}
38
- <|im_start|>user
39
- {human_input}
40
- <|im_end|>
41
- <|im_start|>assistant
42
- """
43
  prompt = PromptTemplate(template=template, input_variables=["system_prompt", "history", "human_input"])
44
 
45
  def format_history(history):
46
- formatted = ""
47
- for human, ai in history:
48
- formatted += f"<|im_start|>user\n{human}\n<|im_end|>\n<|im_start|>assistant\n{ai}\n<|im_end|>\n"
49
- return formatted
50
 
51
  def predict(message, history, system_prompt, temperature, max_new_tokens, top_k, repetition_penalty, top_p):
52
  logger.debug(f"Received prediction request: message='{message}', system_prompt='{system_prompt}'")
53
 
54
- formatted_history = format_history(history)
55
-
56
  chat_model.temperature = temperature
57
  chat_model.max_new_tokens = max_new_tokens
58
  chat_model.top_k = top_k
@@ -62,41 +39,36 @@ def predict(message, history, system_prompt, temperature, max_new_tokens, top_k,
62
  chain = LLMChain(llm=chat_model, prompt=prompt)
63
 
64
  try:
 
65
  for chunk in chain.stream({"system_prompt": system_prompt, "history": formatted_history, "human_input": message}):
66
  yield chunk["text"]
67
  logger.debug(f"Prediction completed successfully for message: '{message}'")
68
  except Exception as e:
69
- logger.exception(f"Error during prediction for message '{message}': {str(e)}")
70
  yield "An error occurred during processing."
71
 
72
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
73
- quantization_config = BitsAndBytesConfig(
74
- load_in_4bit=True,
75
- bnb_4bit_compute_dtype=torch.bfloat16
76
- )
77
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
78
-
79
  chat_model = ChatHuggingFace(
80
  model_name=MODEL_ID,
 
81
  model_kwargs={
82
  "device_map": "auto",
83
- "quantization_config": quantization_config,
84
- },
85
- tokenizer=tokenizer
86
  )
87
 
88
  logger.debug("Model and tokenizer loaded successfully")
89
 
90
  gr.ChatInterface(
91
  predict,
92
- title=EMOJI + " " + MODEL_NAME,
93
- description=DESCRIPTION,
94
  examples=[
95
- ["Can you solve the equation 2x + 3 = 11 for x in Python?"],
96
- ["Write a Java program that checks if a number is even or odd."],
97
- ["How can I reverse a string in JavaScript?"],
98
- ["Create a C++ function to find the factorial of a number."],
99
- ["Write a Python list comprehension to generate a list of squares of numbers from 1 to 10."],
100
  ],
101
  additional_inputs=[
102
  gr.Textbox("You are a code assistant.", label="System prompt"),
@@ -106,7 +78,7 @@ gr.ChatInterface(
106
  gr.Slider(0, 2, 1.1, label="Repetition penalty"),
107
  gr.Slider(0, 1, 0.95, label="Top P sampling"),
108
  ],
109
- theme=gr.themes.Soft(primary_hue=COLOR),
110
  ).queue().launch()
111
 
112
  logger.debug("Chat interface initialized and launched")
 
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
 
13
  logger = logging.getLogger(__name__)
14
  logger.setLevel(logging.DEBUG)
15
  file_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5)
16
+ file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
 
 
17
  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
 
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"),
 
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")