Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,32 +1,49 @@
|
|
|
|
1 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
2 |
|
3 |
model_name = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
4 |
|
|
|
5 |
model = AutoModelForCausalLM.from_pretrained(
|
6 |
model_name,
|
7 |
torch_dtype="auto",
|
8 |
-
device_map="auto"
|
|
|
9 |
)
|
10 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
11 |
-
|
12 |
-
prompt = "write a quick sort algorithm."
|
13 |
-
messages = [
|
14 |
-
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
|
15 |
-
{"role": "user", "content": prompt}
|
16 |
-
]
|
17 |
-
text = tokenizer.apply_chat_template(
|
18 |
-
messages,
|
19 |
-
tokenize=False,
|
20 |
-
add_generation_prompt=True
|
21 |
-
)
|
22 |
-
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
23 |
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
)
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
import spaces
|
2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
import torch
|
4 |
|
5 |
model_name = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
6 |
|
7 |
+
# Load model and tokenizer (outside the function for efficiency)
|
8 |
model = AutoModelForCausalLM.from_pretrained(
|
9 |
model_name,
|
10 |
torch_dtype="auto",
|
11 |
+
device_map="auto",
|
12 |
+
trust_remote_code=True # Add this line for Qwen models
|
13 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) # Add this line for Qwen models
|
16 |
+
|
17 |
+
|
18 |
+
@spaces.GPU(required=True)
|
19 |
+
def generate_code(prompt):
|
20 |
+
messages = [
|
21 |
+
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
|
22 |
+
{"role": "user", "content": prompt}
|
23 |
+
]
|
24 |
+
|
25 |
+
text = tokenizer.apply_chat_template(
|
26 |
+
messages,
|
27 |
+
tokenize=False,
|
28 |
+
add_generation_prompt=True
|
29 |
+
)
|
30 |
+
|
31 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
32 |
+
|
33 |
+
generated_ids = model.generate(
|
34 |
+
**model_inputs,
|
35 |
+
max_new_tokens=512
|
36 |
+
)
|
37 |
+
|
38 |
+
generated_ids = [
|
39 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
40 |
+
]
|
41 |
+
|
42 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
43 |
+
return response
|
44 |
|
45 |
+
# Example usage (optional - remove for Spaces deployment)
|
46 |
+
if __name__ == "__main__":
|
47 |
+
prompt = "write a quick sort algorithm."
|
48 |
+
generated_code = generate_code(prompt)
|
49 |
+
print(generated_code)
|