1inkusFace commited on
Commit
6f6ea3e
·
verified ·
1 Parent(s): c7cd4fe

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -0
app.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ torch.backends.cuda.matmul.allow_tf32 = False
20
+ torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False
21
+ torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False
22
+ torch.backends.cudnn.allow_tf32 = False
23
+ torch.backends.cudnn.deterministic = False
24
+ torch.backends.cudnn.benchmark = True
25
+ torch.set_float32_matmul_precision("highest")
26
+
27
+ # --- Model and Tokenizer Configuration ---
28
+ model_name = "FelixChao/vicuna-33b-coder"
29
+
30
+ # --- Quantization Configuration (Example: 4-bit) ---
31
+ # This section is included based on our previous discussion.
32
+ # Remove or comment out if you are not using quantization.
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.bfloat16
39
+ )
40
+
41
+ print(f"Loading model: {model_name} with quantization")
42
+ model = AutoModelForCausalLM.from_pretrained(
43
+ model_name,
44
+ quantization_config=quantization_config_4bit, # Comment out if not using quantization
45
+ device_map="auto",
46
+ )
47
+
48
+ print(f"Loading tokenizer: {model_name}")
49
+ tokenizer = AutoTokenizer.from_pretrained(
50
+ model_name,
51
+ use_fast=True
52
+ )
53
+
54
+ # ** MODIFICATION: Define and set the Vicuna chat template **
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' %}" # Check if the first message is a system prompt
62
+ "{{ messages[0]['content'] + '\\n\\n' }}" # Add system prompt with two newlines
63
+ "{% set loop_messages = messages[1:] %}" # Slice to loop over remaining messages
64
+ "{% else %}"
65
+ "{% set loop_messages = messages %}" # No system prompt, loop over all messages
66
+ "{% endif %}"
67
+ "{% for message in loop_messages %}" # Loop through user and assistant 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 %}" # If we need to prompt the model for a response
75
+ "{% if messages[-1]['role'] != 'assistant' %}" # And the last message wasn't from the assistant
76
+ "{{ 'ASSISTANT:' }}" # Add the assistant prompt
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
+
93
+ @spaces.GPU(required=True)
94
+ def generate_code(prompt: str) -> str:
95
+ messages = [
96
+ {"role": "system", "content": "You are a helpful and proficient coding assistant."},
97
+ {"role": "user", "content": prompt}
98
+ ]
99
+ try:
100
+ # ** DOCUMENTATION: Applying Chat Template **
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 # Important to append "ASSISTANT:"
106
+ )
107
+ print(f"Formatted prompt using chat template:\n{text}") # For debugging
108
+ except Exception as e:
109
+ print(f"Error applying chat template: {e}")
110
+ # Provide a more informative error or fallback if needed
111
+ return f"Error: Could not apply chat template. Details: {e}. Ensure the tokenizer has a valid `chat_template` attribute."
112
+
113
+ # Determine device for inputs if model is on multiple devices
114
+ # For device_map="auto", input tensors should go to the device of the first model block.
115
+ input_device = model.hf_device_map.get("", next(iter(model.hf_device_map.values()))) if hasattr(model, "hf_device_map") else model.device
116
+
117
+ model_inputs = tokenizer([text], return_tensors="pt").to(input_device)
118
+
119
+ with torch.no_grad():
120
+ generated_ids = model.generate(
121
+ **model_inputs, # Pass tokenized inputs
122
+ max_new_tokens=1024,
123
+ min_new_tokens=256,
124
+ do_sample=True,
125
+ temperature=0.7,
126
+ top_p=0.9,
127
+ pad_token_id=tokenizer.eos_token_id # Use EOS token for padding
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 33B Coder") as demo:
136
+ with gr.Tab("Code Chat"):
137
+ gr.Markdown("# Vicuna 33B Coder\nProvide a prompt to generate code.")
138
+ with gr.Row():
139
+ prompt_input = gr.Textbox( # Renamed to avoid conflict with 'prompt' variable in function scope
140
+ label="Prompt",
141
+ show_label=True,
142
+ lines=3,
143
+ placeholder="Enter your coding prompt here...",
144
+ )
145
+ run_button = gr.Button("Generate Code", variant="primary")
146
+ with gr.Row():
147
+ result_output = gr.Code( # Renamed
148
+ label="Generated Code",
149
+ show_label=True,
150
+ language="python",
151
+ lines=20,
152
+ )
153
+ gr.on(
154
+ triggers=[
155
+ run_button.click,
156
+ prompt_input.submit
157
+ ],
158
+ fn=generate_code,
159
+ inputs=[prompt_input],
160
+ outputs=[result_output],
161
+ )
162
+
163
+ if __name__ == "__main__":
164
+ demo.launch(share=False, debug=True)