1inkusFace commited on
Commit
64ca47b
·
verified ·
1 Parent(s): c9a47f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -88
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
- torch.backends.cuda.matmul.allow_tf32 = True
20
- torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = True
21
- torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = True
22
- torch.backends.cudnn.allow_tf32 = True
23
- torch.backends.cudnn.deterministic = True
24
- torch.backends.cudnn.benchmark = True
25
- torch.set_float32_matmul_precision("high")
 
 
 
 
26
 
27
- # --- Model and Tokenizer Configuration ---
28
- model_name = "InferenceIllusionist/MilkDropLM-32b-v0.3"
 
 
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.float16
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
 
@@ -97,46 +99,45 @@ def generate_code(prompt: str) -> str:
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=2048,
123
- min_new_tokens=768,
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 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( # Renamed to avoid conflict with 'prompt' variable in function scope
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( # Renamed
148
  label="Generated Code",
149
  show_label=True,
150
- language="python",
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(