Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,93 +1,136 @@
|
|
1 |
import os
|
2 |
-
import
|
|
|
3 |
from threading import Thread
|
|
|
4 |
from logging.handlers import RotatingFileHandler
|
|
|
5 |
import torch
|
|
|
6 |
import gradio as gr
|
7 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig,
|
|
|
|
|
8 |
|
9 |
-
# Logging setup
|
10 |
log_file = '/tmp/app_debug.log'
|
11 |
logger = logging.getLogger(__name__)
|
12 |
logger.setLevel(logging.DEBUG)
|
13 |
file_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5)
|
14 |
-
file_handler.
|
|
|
|
|
15 |
logger.addHandler(file_handler)
|
16 |
|
17 |
logger.debug("Application started")
|
18 |
|
19 |
-
# Define model parameters
|
20 |
MODEL_ID = "Qwen/Qwen2.5-Coder-7B-Instruct"
|
|
|
|
|
21 |
CONTEXT_LENGTH = 16000
|
22 |
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
)
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
logger.debug("
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
model=model,
|
52 |
-
tokenizer=tokenizer,
|
53 |
-
max_length=CONTEXT_LENGTH,
|
54 |
-
temperature=0.7,
|
55 |
-
top_k=50,
|
56 |
-
top_p=0.9,
|
57 |
-
repetition_penalty=1.2,
|
58 |
-
)
|
59 |
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
69 |
try:
|
70 |
-
|
71 |
-
|
|
|
|
|
|
|
|
|
72 |
except Exception as e:
|
73 |
-
logger.exception(f"Error during prediction: {e}")
|
74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
gr.Slider(1, 80, 40, label="Top K sampling"),
|
84 |
gr.Slider(0, 2, 1.1, label="Repetition penalty"),
|
85 |
gr.Slider(0, 1, 0.95, label="Top P sampling"),
|
86 |
],
|
87 |
-
|
88 |
-
|
89 |
-
)
|
90 |
-
|
91 |
-
interface.launch()
|
92 |
|
93 |
-
logger.debug("Chat interface initialized and launched")
|
|
|
1 |
import os
|
2 |
+
import json
|
3 |
+
import subprocess
|
4 |
from threading import Thread
|
5 |
+
import logging
|
6 |
from logging.handlers import RotatingFileHandler
|
7 |
+
|
8 |
import torch
|
9 |
+
import spaces
|
10 |
import gradio as gr
|
11 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TextIteratorStreamer
|
12 |
+
|
13 |
+
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
14 |
|
|
|
15 |
log_file = '/tmp/app_debug.log'
|
16 |
logger = logging.getLogger(__name__)
|
17 |
logger.setLevel(logging.DEBUG)
|
18 |
file_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5)
|
19 |
+
file_handler.setLevel(logging.DEBUG)
|
20 |
+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
21 |
+
file_handler.setFormatter(formatter)
|
22 |
logger.addHandler(file_handler)
|
23 |
|
24 |
logger.debug("Application started")
|
25 |
|
|
|
26 |
MODEL_ID = "Qwen/Qwen2.5-Coder-7B-Instruct"
|
27 |
+
CHAT_TEMPLATE = "ChatML"
|
28 |
+
MODEL_NAME = MODEL_ID.split("/")[-1]
|
29 |
CONTEXT_LENGTH = 16000
|
30 |
|
31 |
+
COLOR = "blue"
|
32 |
+
EMOJI = "🤖"
|
33 |
+
DESCRIPTION = f"This is the {MODEL_NAME} model designed for coding assistance and general AI tasks."
|
|
|
34 |
|
35 |
+
@spaces.GPU()
|
36 |
+
def predict(message, history, system_prompt, temperature, max_new_tokens, top_k, repetition_penalty, top_p):
|
37 |
+
logger.debug(f"Received prediction request: message='{message}', system_prompt='{system_prompt}'")
|
38 |
+
if CHAT_TEMPLATE == "Auto":
|
39 |
+
stop_tokens = [tokenizer.eos_token_id]
|
40 |
+
instruction = system_prompt + "\n\n"
|
41 |
+
for user, assistant in history:
|
42 |
+
instruction += f"User: {user}\nAssistant: {assistant}\n"
|
43 |
+
instruction += f"User: {message}\nAssistant:"
|
44 |
+
elif CHAT_TEMPLATE == "ChatML":
|
45 |
+
stop_tokens = ["<|endoftext|>", "<|im_end|>"]
|
46 |
+
instruction = '<|im_start|>system\n' + system_prompt + '\n<|im_end|>\n'
|
47 |
+
for user, assistant in history:
|
48 |
+
instruction += f'<|im_start|>user\n{user}\n<|im_end|>\n<|im_start|>assistant\n{assistant}\n<|im_end|>\n'
|
49 |
+
instruction += f'<|im_start|>user\n{message}\n<|im_end|>\n<|im_start|>assistant\n'
|
50 |
+
elif CHAT_TEMPLATE == "Mistral Instruct":
|
51 |
+
stop_tokens = ["</s>", "[INST]", "[INST] ", "<s>", "[/INST]", "[/INST] "]
|
52 |
+
instruction = f'<s>[INST] {system_prompt}\n'
|
53 |
+
for user, assistant in history:
|
54 |
+
instruction += f'{user} [/INST] {assistant}</s>[INST]'
|
55 |
+
instruction += f' {message} [/INST]'
|
56 |
+
else:
|
57 |
+
raise Exception("Incorrect chat template, select 'Auto', 'ChatML' or 'Mistral Instruct'")
|
58 |
+
print(instruction)
|
59 |
+
|
60 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
61 |
+
enc = tokenizer(instruction, return_tensors="pt", padding=True, truncation=True)
|
62 |
+
input_ids, attention_mask = enc.input_ids, enc.attention_mask
|
63 |
|
64 |
+
if input_ids.shape[1] > CONTEXT_LENGTH:
|
65 |
+
input_ids = input_ids[:, -CONTEXT_LENGTH:]
|
66 |
+
attention_mask = attention_mask[:, -CONTEXT_LENGTH:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
generate_kwargs = dict(
|
69 |
+
input_ids=input_ids.to(device),
|
70 |
+
attention_mask=attention_mask.to(device),
|
71 |
+
streamer=streamer,
|
72 |
+
do_sample=True,
|
73 |
+
temperature=temperature,
|
74 |
+
max_new_tokens=max_new_tokens,
|
75 |
+
top_k=top_k,
|
76 |
+
repetition_penalty=repetition_penalty,
|
77 |
+
top_p=top_p
|
78 |
+
)
|
79 |
+
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
80 |
+
t.start()
|
81 |
+
outputs = []
|
82 |
try:
|
83 |
+
for new_token in streamer:
|
84 |
+
outputs.append(new_token)
|
85 |
+
if new_token in stop_tokens:
|
86 |
+
break
|
87 |
+
yield "".join(outputs)
|
88 |
+
logger.debug(f"Prediction completed successfully for message: '{message}'")
|
89 |
except Exception as e:
|
90 |
+
logger.exception(f"Error during prediction for message '{message}': {str(e)}")
|
91 |
+
yield "An error occurred during processing."
|
92 |
+
|
93 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
94 |
+
quantization_config = BitsAndBytesConfig(
|
95 |
+
load_in_4bit=True,
|
96 |
+
bnb_4bit_compute_dtype=torch.bfloat16
|
97 |
+
)
|
98 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
99 |
+
model = AutoModelForCausalLM.from_pretrained(
|
100 |
+
MODEL_ID,
|
101 |
+
device_map="auto",
|
102 |
+
quantization_config=quantization_config,
|
103 |
+
attn_implementation="flash_attention_2",
|
104 |
+
)
|
105 |
|
106 |
+
logger.debug("Model and tokenizer loaded successfully")
|
107 |
+
|
108 |
+
gr.ChatInterface(
|
109 |
+
predict,
|
110 |
+
title=EMOJI + " " + MODEL_NAME,
|
111 |
+
description=DESCRIPTION,
|
112 |
+
examples=[
|
113 |
+
["Can you solve the equation 2x + 3 = 11 for x in Python?"],
|
114 |
+
["Write a Java program that checks if a number is even or odd."],
|
115 |
+
["How can I reverse a string in JavaScript?"],
|
116 |
+
["Create a C++ function to find the factorial of a number."],
|
117 |
+
["Write a Python list comprehension to generate a list of squares of numbers from 1 to 10."],
|
118 |
+
["How do I implement a binary search algorithm in C?"],
|
119 |
+
["Write a Ruby script to read a file and count the number of lines in it."],
|
120 |
+
["Create a Swift class to represent a bank account with deposit and withdrawal methods."],
|
121 |
+
["How do I find the maximum element in an array using Kotlin?"],
|
122 |
+
["Write a Rust program to generate the Fibonacci sequence up to the 10th number."]
|
123 |
+
],
|
124 |
+
additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False),
|
125 |
+
additional_inputs=[
|
126 |
+
gr.Textbox("You are a code assistant.", label="System prompt"),
|
127 |
+
gr.Slider(0, 1, 0.3, label="Temperature"),
|
128 |
+
gr.Slider(128, 4096, 1024, label="Max new tokens"),
|
129 |
gr.Slider(1, 80, 40, label="Top K sampling"),
|
130 |
gr.Slider(0, 2, 1.1, label="Repetition penalty"),
|
131 |
gr.Slider(0, 1, 0.95, label="Top P sampling"),
|
132 |
],
|
133 |
+
theme=gr.themes.Soft(primary_hue=COLOR),
|
134 |
+
).queue().launch()
|
|
|
|
|
|
|
135 |
|
136 |
+
logger.debug("Chat interface initialized and launched")
|