Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,92 +1,94 @@
|
|
1 |
import spaces # If using Hugging Face Spaces
|
2 |
-
|
3 |
import os
|
4 |
-
|
5 |
-
os.putenv('PYTORCH_NVML_BASED_CUDA_CHECK','1')
|
6 |
-
os.putenv('TORCH_LINALG_PREFER_CUSOLVER','1')
|
7 |
-
alloc_conf_parts = [
|
8 |
-
'expandable_segments:True',
|
9 |
-
'pinned_use_background_threads:True' # Specific to pinned memory.
|
10 |
-
]
|
11 |
-
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = ','.join(alloc_conf_parts)
|
12 |
-
os.environ["SAFETENSORS_FAST_GPU"] = "1"
|
13 |
-
os.putenv('HF_HUB_ENABLE_HF_TRANSFER','1')
|
14 |
-
|
15 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig # Import BitsAndBytesConfig
|
16 |
import torch
|
17 |
import gradio as gr
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
#
|
28 |
-
|
|
|
|
|
29 |
|
30 |
-
#
|
31 |
-
#
|
32 |
-
#
|
33 |
-
print("Setting up 4-bit quantization config...")
|
34 |
-
quantization_config_4bit = BitsAndBytesConfig(
|
35 |
-
load_in_4bit=True,
|
36 |
-
bnb_4bit_use_double_quant=True,
|
37 |
-
bnb_4bit_quant_type="nf4",
|
38 |
-
bnb_4bit_compute_dtype=torch.float16
|
39 |
-
)
|
40 |
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
model = AutoModelForCausalLM.from_pretrained(
|
43 |
-
|
44 |
-
|
45 |
-
|
|
|
|
|
46 |
)
|
|
|
47 |
|
48 |
-
|
|
|
|
|
|
|
49 |
tokenizer = AutoTokenizer.from_pretrained(
|
50 |
-
|
51 |
use_fast=True
|
52 |
)
|
53 |
|
54 |
-
# **
|
55 |
-
# ** DOCUMENTATION: Chat Template **
|
56 |
-
# Vicuna models expect a specific chat format. If the tokenizer doesn't have one
|
57 |
-
# built-in, we need to set it manually.
|
58 |
-
# This template handles a system prompt, user messages, and assistant responses.
|
59 |
-
# It will also add the "ASSISTANT:" prompt for generation if needed.
|
60 |
VICUNA_CHAT_TEMPLATE = (
|
61 |
-
"{% if messages[0]['role'] == 'system' %}"
|
62 |
-
"{{ messages[0]['content'] + '\\n\\n' }}"
|
63 |
-
"{% set loop_messages = messages[1:] %}"
|
64 |
"{% else %}"
|
65 |
-
"{% set loop_messages = messages %}"
|
66 |
"{% endif %}"
|
67 |
-
"{% for message in loop_messages %}"
|
68 |
"{% if message['role'] == 'user' %}"
|
69 |
"{{ 'USER: ' + message['content'].strip() + '\\n' }}"
|
70 |
"{% elif message['role'] == 'assistant' %}"
|
71 |
"{{ 'ASSISTANT: ' + message['content'].strip() + eos_token + '\\n' }}"
|
72 |
"{% endif %}"
|
73 |
"{% endfor %}"
|
74 |
-
"{% if add_generation_prompt %}"
|
75 |
-
"{% if messages[-1]['role'] != 'assistant' %}"
|
76 |
-
"{{ 'ASSISTANT:' }}"
|
77 |
"{% endif %}"
|
78 |
"{% endif %}"
|
79 |
)
|
80 |
tokenizer.chat_template = VICUNA_CHAT_TEMPLATE
|
81 |
print("Manually set Vicuna chat template on the tokenizer.")
|
82 |
|
83 |
-
|
84 |
if tokenizer.pad_token is None:
|
85 |
tokenizer.pad_token = tokenizer.eos_token
|
86 |
-
# Also update the model config's pad_token_id if you are setting tokenizer.pad_token
|
87 |
-
# This is crucial if the model's config doesn't get updated automatically.
|
88 |
-
if model.config.pad_token_id is None:
|
89 |
-
model.config.pad_token_id = tokenizer.pad_token_id
|
90 |
print(f"Tokenizer `pad_token` was None, set to `eos_token`: {tokenizer.eos_token}")
|
91 |
|
92 |
|
@@ -97,46 +99,45 @@ def generate_code(prompt: str) -> str:
|
|
97 |
{"role": "user", "content": prompt}
|
98 |
]
|
99 |
try:
|
100 |
-
#
|
101 |
-
# Now that tokenizer.chat_template is set, this should work.
|
102 |
text = tokenizer.apply_chat_template(
|
103 |
messages,
|
104 |
tokenize=False,
|
105 |
-
add_generation_prompt=True
|
106 |
)
|
107 |
-
print(f"Formatted prompt using chat template:\n{text}")
|
108 |
except Exception as e:
|
109 |
print(f"Error applying chat template: {e}")
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
#
|
114 |
-
#
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
|
|
|
|
129 |
|
130 |
-
response_ids = generated_ids[0][len(model_inputs.input_ids[0]):]
|
131 |
-
response = tokenizer.decode(response_ids, skip_special_tokens=True)
|
132 |
return response.strip()
|
133 |
|
134 |
-
# --- Gradio Interface ---
|
135 |
-
with gr.Blocks(title="Vicuna 32B Milkdrop") as demo:
|
136 |
with gr.Tab("Code Chat"):
|
137 |
-
gr.Markdown("# Vicuna 32B Milkdrop\nProvide a prompt to generate HLSL.")
|
138 |
with gr.Row():
|
139 |
-
prompt_input = gr.Textbox(
|
140 |
label="Prompt",
|
141 |
show_label=True,
|
142 |
lines=3,
|
@@ -144,10 +145,10 @@ with gr.Blocks(title="Vicuna 32B Milkdrop") as demo:
|
|
144 |
)
|
145 |
run_button = gr.Button("Generate Code", variant="primary")
|
146 |
with gr.Row():
|
147 |
-
result_output = gr.Code(
|
148 |
label="Generated Code",
|
149 |
show_label=True,
|
150 |
-
language="
|
151 |
lines=20,
|
152 |
)
|
153 |
gr.on(
|
|
|
1 |
import spaces # If using Hugging Face Spaces
|
|
|
2 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import torch
|
4 |
import gradio as gr
|
5 |
|
6 |
+
# ## GGUF MOD: Unused environment variables for PyTorch have been removed.
|
7 |
+
# ## GGUF MOD: ctransformers handles its own memory and GPU management.
|
8 |
+
# os.putenv('PYTORCH_NVML_BASED_CUDA_CHECK','1')
|
9 |
+
# os.putenv('TORCH_LINALG_PREFER_CUSOLVER','1')
|
10 |
+
# alloc_conf_parts = [
|
11 |
+
# 'expandable_segments:True',
|
12 |
+
# 'pinned_use_background_threads:True'
|
13 |
+
# ]
|
14 |
+
# os.environ['PYTORCH_CUDA_ALLOC_CONF'] = ','.join(alloc_conf_parts)
|
15 |
+
# os.environ["SAFETENSORS_FAST_GPU"] = "1"
|
16 |
+
os.putenv('HF_HUB_ENABLE_HF_TRANSFER','1')
|
17 |
|
18 |
+
# ## GGUF MOD: Import AutoModelForCausalLM from ctransformers instead of transformers.
|
19 |
+
# ## GGUF MOD: BitsAndBytesConfig is no longer needed.
|
20 |
+
from ctransformers import AutoModelForCausalLM
|
21 |
+
from transformers import AutoTokenizer
|
22 |
|
23 |
+
# ## GGUF MOD: PyTorch backend settings are not used by ctransformers.
|
24 |
+
# torch.backends.cuda.matmul.allow_tf32 = True
|
25 |
+
# ... (rest of torch settings removed for clarity)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
+
# --- Model and Tokenizer Configuration ---
|
28 |
+
# ## GGUF MOD: The model name now points to the GGUF repository.
|
29 |
+
model_repo_id = "Quant-Cartel/MilkDropLM-32b-v0.3-GGUF"
|
30 |
+
# ## GGUF MOD: Specify the exact GGUF file to download.
|
31 |
+
# It's good practice to pick a specific quantization level.
|
32 |
+
# q4_K_M is a good balance of quality and performance.
|
33 |
+
model_file = "milkdroplm-32b-v0.3.q4_K_M.gguf"
|
34 |
+
|
35 |
+
# ## GGUF MOD: The quantization is handled by ctransformers when loading the model.
|
36 |
+
# ## The BitsAndBytesConfig is removed.
|
37 |
+
print("Loading GGUF model...")
|
38 |
+
# Documentation: Loading GGUF Model with ctransformers
|
39 |
+
# We use AutoModelForCausalLM from the ctransformers library.
|
40 |
+
# - model_repo_id: The Hugging Face repository containing the GGUF files.
|
41 |
+
# - model_file: The specific .gguf file to download and load.
|
42 |
+
# - model_type: 'llama' is specified as it's a Llama-based model, which helps ctransformers optimize.
|
43 |
+
# - gpu_layers: This is the most important parameter for performance. It determines
|
44 |
+
# how many layers of the model are offloaded to the GPU. 50 is a high value
|
45 |
+
# that should fill most of the VRAM on modern GPUs for a 32B model,
|
46 |
+
# leading to much faster inference. Adjust this number based on your VRAM.
|
47 |
+
# - hf=True: This tells ctransformers to download from the Hugging Face Hub.
|
48 |
model = AutoModelForCausalLM.from_pretrained(
|
49 |
+
model_repo_id,
|
50 |
+
model_file=model_file,
|
51 |
+
model_type='llama',
|
52 |
+
gpu_layers=50, # Offload all possible layers to GPU
|
53 |
+
hf=True
|
54 |
)
|
55 |
+
print("GGUF Model loaded successfully.")
|
56 |
|
57 |
+
# The tokenizer can still be loaded from the original repository.
|
58 |
+
# GGUF files do not contain tokenizer data.
|
59 |
+
tokenizer_repo_id = "InferenceIllusionist/MilkDropLM-32b-v0.3"
|
60 |
+
print(f"Loading tokenizer from: {tokenizer_repo_id}")
|
61 |
tokenizer = AutoTokenizer.from_pretrained(
|
62 |
+
tokenizer_repo_id,
|
63 |
use_fast=True
|
64 |
)
|
65 |
|
66 |
+
# ** This part remains the same. The chat template is independent of the model format. **
|
|
|
|
|
|
|
|
|
|
|
67 |
VICUNA_CHAT_TEMPLATE = (
|
68 |
+
"{% if messages[0]['role'] == 'system' %}"
|
69 |
+
"{{ messages[0]['content'] + '\\n\\n' }}"
|
70 |
+
"{% set loop_messages = messages[1:] %}"
|
71 |
"{% else %}"
|
72 |
+
"{% set loop_messages = messages %}"
|
73 |
"{% endif %}"
|
74 |
+
"{% for message in loop_messages %}"
|
75 |
"{% if message['role'] == 'user' %}"
|
76 |
"{{ 'USER: ' + message['content'].strip() + '\\n' }}"
|
77 |
"{% elif message['role'] == 'assistant' %}"
|
78 |
"{{ 'ASSISTANT: ' + message['content'].strip() + eos_token + '\\n' }}"
|
79 |
"{% endif %}"
|
80 |
"{% endfor %}"
|
81 |
+
"{% if add_generation_prompt %}"
|
82 |
+
"{% if messages[-1]['role'] != 'assistant' %}"
|
83 |
+
"{{ 'ASSISTANT:' }}"
|
84 |
"{% endif %}"
|
85 |
"{% endif %}"
|
86 |
)
|
87 |
tokenizer.chat_template = VICUNA_CHAT_TEMPLATE
|
88 |
print("Manually set Vicuna chat template on the tokenizer.")
|
89 |
|
|
|
90 |
if tokenizer.pad_token is None:
|
91 |
tokenizer.pad_token = tokenizer.eos_token
|
|
|
|
|
|
|
|
|
92 |
print(f"Tokenizer `pad_token` was None, set to `eos_token`: {tokenizer.eos_token}")
|
93 |
|
94 |
|
|
|
99 |
{"role": "user", "content": prompt}
|
100 |
]
|
101 |
try:
|
102 |
+
# The chat template application is the same.
|
|
|
103 |
text = tokenizer.apply_chat_template(
|
104 |
messages,
|
105 |
tokenize=False,
|
106 |
+
add_generation_prompt=True
|
107 |
)
|
108 |
+
print(f"Formatted prompt using chat template:\n{text}")
|
109 |
except Exception as e:
|
110 |
print(f"Error applying chat template: {e}")
|
111 |
+
return f"Error: Could not apply chat template. Details: {e}."
|
112 |
+
|
113 |
+
# ## GGUF MOD: The generation call is now simpler.
|
114 |
+
# The `ctransformers` model object takes the prompt text directly.
|
115 |
+
# No need for tokenization or sending tensors to a device manually.
|
116 |
+
|
117 |
+
# Documentation: Generating Text with ctransformers
|
118 |
+
# The model object has a built-in generator that you call like a function.
|
119 |
+
# - prompt (text): The formatted string prompt for the model.
|
120 |
+
# - max_new_tokens, temperature, top_p: These parameters function identically
|
121 |
+
# to their Hugging Face counterparts.
|
122 |
+
# - stop: We can provide the EOS token to ensure the model stops generating
|
123 |
+
# cleanly once it thinks it's finished.
|
124 |
+
# The output is a simple string.
|
125 |
+
response = model(
|
126 |
+
text,
|
127 |
+
max_new_tokens=2048,
|
128 |
+
temperature=0.7,
|
129 |
+
top_p=0.9,
|
130 |
+
stop=[tokenizer.eos_token],
|
131 |
+
)
|
132 |
|
|
|
|
|
133 |
return response.strip()
|
134 |
|
135 |
+
# --- Gradio Interface (No changes needed here) ---
|
136 |
+
with gr.Blocks(title="Vicuna 32B Milkdrop GGUF") as demo:
|
137 |
with gr.Tab("Code Chat"):
|
138 |
+
gr.Markdown("# Vicuna 32B Milkdrop (GGUF)\nProvide a prompt to generate HLSL.")
|
139 |
with gr.Row():
|
140 |
+
prompt_input = gr.Textbox(
|
141 |
label="Prompt",
|
142 |
show_label=True,
|
143 |
lines=3,
|
|
|
145 |
)
|
146 |
run_button = gr.Button("Generate Code", variant="primary")
|
147 |
with gr.Row():
|
148 |
+
result_output = gr.Code(
|
149 |
label="Generated Code",
|
150 |
show_label=True,
|
151 |
+
language="hlsl", # Changed to hlsl for better syntax highlighting
|
152 |
lines=20,
|
153 |
)
|
154 |
gr.on(
|