FlameF0X commited on
Commit
f82987b
·
verified ·
1 Parent(s): 3fbdedd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -81
app.py CHANGED
@@ -2,11 +2,10 @@ import os
2
  import torch
3
  import gradio as gr
4
  from transformers import AutoTokenizer, AutoModelForCausalLM, TextGenerationPipeline
5
- from safetensors.torch import load_file # Import safetensors for loading .safetensors models
6
  import datetime
7
 
8
  # Model Constants
9
- MODEL_ID = "FlameF0X/Snowflake-G0-Release" # HF repo when published
10
  MAX_LENGTH = 384
11
  TEMPERATURE_MIN = 0.1
12
  TEMPERATURE_MAX = 2.0
@@ -70,32 +69,23 @@ css = """
70
  }
71
  """
72
 
73
- # Helper functions to load model
74
  def load_model_and_tokenizer():
75
- global model, tokenizer, pipeline # Add this line
76
 
77
- # Load the tokenizer
78
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
79
 
80
- # Check if the pad_token is None, set it to eos_token if needed
 
81
  if tokenizer.pad_token is None:
82
  tokenizer.pad_token = tokenizer.eos_token
83
 
84
- # Check if the model uses safetensors or pytorch .bin model file
85
- model_file_path = os.path.join(MODEL_ID, "model.safetensors") # or model.bin if that's the case
 
 
 
86
 
87
- if os.path.exists(model_file_path):
88
- # Check if safetensors file exists
89
- print("Loading model from safetensors file...")
90
- model = load_file(model_file_path) # Safetensors loading
91
- else:
92
- # Load from standard .bin file
93
- print("Loading model from .bin file...")
94
- model = AutoModelForCausalLM.from_pretrained(MODEL_ID,
95
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
96
- device_map="auto")
97
-
98
- # Initialize the generation pipeline
99
  pipeline = TextGenerationPipeline(
100
  model=model,
101
  tokenizer=tokenizer,
@@ -103,6 +93,7 @@ def load_model_and_tokenizer():
103
  max_length=MAX_LENGTH
104
  )
105
 
 
106
  return model, tokenizer, pipeline
107
 
108
  # Helper functions for generation
@@ -117,11 +108,9 @@ def generate_text(
117
  if history is None:
118
  history = []
119
 
120
- # Add current prompt to history
121
  history.append({"role": "user", "content": prompt})
122
-
123
  try:
124
- # Generate response
125
  outputs = pipeline(
126
  prompt,
127
  do_sample=temperature > 0,
@@ -132,20 +121,17 @@ def generate_text(
132
  pad_token_id=tokenizer.pad_token_id,
133
  num_return_sequences=1
134
  )
135
-
136
  response = outputs[0]["generated_text"]
137
-
138
- # Add model response to history
139
  history.append({"role": "assistant", "content": response})
140
-
141
- # Format chat history for display
142
  formatted_history = []
143
  for entry in history:
144
  role_prefix = "👤 User: " if entry["role"] == "user" else "❄️ Snowflake: "
145
  formatted_history.append(f"{role_prefix}{entry['content']}")
146
-
147
  return response, history, "\n\n".join(formatted_history)
148
-
149
  except Exception as e:
150
  error_msg = f"Error generating response: {str(e)}"
151
  history.append({"role": "assistant", "content": f"[ERROR] {error_msg}"})
@@ -166,7 +152,7 @@ examples = [
166
  "Create a dialogue between two AI researchers discussing the future of language models."
167
  ]
168
 
169
- # Main function
170
  def create_demo():
171
  with gr.Blocks(css=css) as demo:
172
  # Header
@@ -177,29 +163,29 @@ def create_demo():
177
  </div>
178
  """)
179
 
180
- # Model info
181
  with gr.Accordion("About Snowflake-G0-Release", open=False):
182
  gr.Markdown("""
183
  ## Snowflake-G0-Release
184
 
185
- This is the initial release of the Snowflake series language models, trained on the DialogMLM-50K dataset with optimized memory usage.
186
 
187
- ### Model details
188
  - Architecture: SnowflakeCore
189
  - Hidden size: 384
190
- - Number of attention heads: 6
191
- - Number of layers: 4
192
- - Feed-forward dimension: 768
193
- - Maximum sequence length: 384
194
  - Vocabulary size: 30522 (BERT tokenizer)
195
 
196
- ### Key Features
197
- - Efficient memory usage
198
- - Fused QKV projection for faster inference
199
- - Pre-norm architecture for stable training
200
- - Compatible with HuggingFace Transformers
201
  """)
202
-
203
  # Chat interface
204
  with gr.Column():
205
  chat_history_display = gr.Textbox(
@@ -209,11 +195,8 @@ def create_demo():
209
  max_lines=30,
210
  interactive=False
211
  )
212
-
213
- # Invisible state variables
214
  history_state = gr.State([])
215
-
216
- # Input and output
217
  with gr.Row():
218
  with gr.Column(scale=4):
219
  prompt = gr.Textbox(
@@ -224,7 +207,7 @@ def create_demo():
224
  with gr.Column(scale=1):
225
  submit_btn = gr.Button("Send", variant="primary")
226
  clear_btn = gr.Button("Clear Conversation")
227
-
228
  response_output = gr.Textbox(
229
  value="",
230
  label="Model Response",
@@ -232,8 +215,8 @@ def create_demo():
232
  max_lines=10,
233
  interactive=False
234
  )
235
-
236
- # Advanced parameters
237
  with gr.Accordion("Generation Parameters", open=False):
238
  with gr.Column(elem_classes="parameter-section"):
239
  with gr.Row():
@@ -243,95 +226,84 @@ def create_demo():
243
  maximum=TEMPERATURE_MAX,
244
  value=TEMPERATURE_DEFAULT,
245
  step=0.05,
246
- label="Temperature",
247
- info="Higher = more creative, Lower = more deterministic"
248
  )
249
-
250
  top_p = gr.Slider(
251
  minimum=TOP_P_MIN,
252
  maximum=TOP_P_MAX,
253
  value=TOP_P_DEFAULT,
254
  step=0.05,
255
- label="Top-p (nucleus sampling)",
256
- info="Controls diversity via cumulative probability"
257
  )
258
-
259
  with gr.Column():
260
  top_k = gr.Slider(
261
  minimum=TOP_K_MIN,
262
  maximum=TOP_K_MAX,
263
  value=TOP_K_DEFAULT,
264
  step=1,
265
- label="Top-k",
266
- info="Limits word choice to top k options"
267
  )
268
-
269
  max_new_tokens = gr.Slider(
270
  minimum=MAX_NEW_TOKENS_MIN,
271
  maximum=MAX_NEW_TOKENS_MAX,
272
  value=MAX_NEW_TOKENS_DEFAULT,
273
  step=8,
274
- label="Maximum New Tokens",
275
- info="Controls the length of generated response"
276
  )
277
-
278
- # Examples
279
  with gr.Accordion("Example Prompts", open=True):
280
  with gr.Column(elem_classes="example-section"):
281
- example_btn = gr.Examples(
282
  examples=examples,
283
  inputs=prompt,
284
- label="Click on an example to try it",
285
  examples_per_page=5
286
  )
287
-
288
  # Footer
289
  gr.HTML(f"""
290
  <div class="footer">
291
  <p>Snowflake-G0-Release Demo • Created with Gradio • {datetime.datetime.now().year}</p>
292
  </div>
293
  """)
294
-
295
- # Set up interactions
296
  submit_btn.click(
297
  fn=generate_text,
298
  inputs=[prompt, temperature, top_p, top_k, max_new_tokens, history_state],
299
  outputs=[response_output, history_state, chat_history_display]
300
  )
301
-
302
  prompt.submit(
303
  fn=generate_text,
304
  inputs=[prompt, temperature, top_p, top_k, max_new_tokens, history_state],
305
  outputs=[response_output, history_state, chat_history_display]
306
  )
307
-
308
  clear_btn.click(
309
  fn=clear_conversation,
310
  inputs=[],
311
  outputs=[prompt, history_state, chat_history_display]
312
  )
313
-
314
  return demo
315
 
316
- # Load model and tokenizer
317
- print("Loading Snowflake-G0-Release model and tokenizer...")
318
  try:
319
  model, tokenizer, pipeline = load_model_and_tokenizer()
320
- print("Model loaded successfully!")
321
  except Exception as e:
322
  print(f"Error loading model: {str(e)}")
323
- # Create a simple error demo if model fails to load
324
  with gr.Blocks(css=css) as error_demo:
325
  gr.HTML(f"""
326
  <div class="header" style="background-color: #ffebee;">
327
  <h1><span class="snowflake-icon">⚠️</span> Error Loading Model</h1>
328
- <p>There was a problem loading the Snowflake-G0-Release model: {str(e)}</p>
329
  </div>
330
  """)
331
  demo = error_demo
332
-
333
- # Create and launch the demo
334
- demo = create_demo()
335
 
336
  # Launch the app
337
  if __name__ == "__main__":
 
2
  import torch
3
  import gradio as gr
4
  from transformers import AutoTokenizer, AutoModelForCausalLM, TextGenerationPipeline
 
5
  import datetime
6
 
7
  # Model Constants
8
+ MODEL_ID = "./model" # Local folder containing model files
9
  MAX_LENGTH = 384
10
  TEMPERATURE_MIN = 0.1
11
  TEMPERATURE_MAX = 2.0
 
69
  }
70
  """
71
 
72
+ # Helper function to load model and tokenizer
73
  def load_model_and_tokenizer():
74
+ global model, tokenizer, pipeline
75
 
76
+ print("Loading Snowflake-G0-Release model and tokenizer...")
 
77
 
78
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
79
+
80
  if tokenizer.pad_token is None:
81
  tokenizer.pad_token = tokenizer.eos_token
82
 
83
+ model = AutoModelForCausalLM.from_pretrained(
84
+ MODEL_ID,
85
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
86
+ device_map="auto"
87
+ )
88
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  pipeline = TextGenerationPipeline(
90
  model=model,
91
  tokenizer=tokenizer,
 
93
  max_length=MAX_LENGTH
94
  )
95
 
96
+ print("Model loaded successfully!")
97
  return model, tokenizer, pipeline
98
 
99
  # Helper functions for generation
 
108
  if history is None:
109
  history = []
110
 
 
111
  history.append({"role": "user", "content": prompt})
112
+
113
  try:
 
114
  outputs = pipeline(
115
  prompt,
116
  do_sample=temperature > 0,
 
121
  pad_token_id=tokenizer.pad_token_id,
122
  num_return_sequences=1
123
  )
124
+
125
  response = outputs[0]["generated_text"]
 
 
126
  history.append({"role": "assistant", "content": response})
127
+
 
128
  formatted_history = []
129
  for entry in history:
130
  role_prefix = "👤 User: " if entry["role"] == "user" else "❄️ Snowflake: "
131
  formatted_history.append(f"{role_prefix}{entry['content']}")
132
+
133
  return response, history, "\n\n".join(formatted_history)
134
+
135
  except Exception as e:
136
  error_msg = f"Error generating response: {str(e)}"
137
  history.append({"role": "assistant", "content": f"[ERROR] {error_msg}"})
 
152
  "Create a dialogue between two AI researchers discussing the future of language models."
153
  ]
154
 
155
+ # Main app creation
156
  def create_demo():
157
  with gr.Blocks(css=css) as demo:
158
  # Header
 
163
  </div>
164
  """)
165
 
166
+ # About accordion
167
  with gr.Accordion("About Snowflake-G0-Release", open=False):
168
  gr.Markdown("""
169
  ## Snowflake-G0-Release
170
 
171
+ Initial release of the Snowflake series trained on DialogMLM-50K.
172
 
173
+ ### Model Details
174
  - Architecture: SnowflakeCore
175
  - Hidden size: 384
176
+ - Attention heads: 6
177
+ - Layers: 4
178
+ - Feed-forward dim: 768
179
+ - Max seq length: 384
180
  - Vocabulary size: 30522 (BERT tokenizer)
181
 
182
+ ### Features
183
+ - Memory-efficient
184
+ - Fused QKV for faster inference
185
+ - Pre-norm for stability
186
+ - Hugging Face compatible
187
  """)
188
+
189
  # Chat interface
190
  with gr.Column():
191
  chat_history_display = gr.Textbox(
 
195
  max_lines=30,
196
  interactive=False
197
  )
 
 
198
  history_state = gr.State([])
199
+
 
200
  with gr.Row():
201
  with gr.Column(scale=4):
202
  prompt = gr.Textbox(
 
207
  with gr.Column(scale=1):
208
  submit_btn = gr.Button("Send", variant="primary")
209
  clear_btn = gr.Button("Clear Conversation")
210
+
211
  response_output = gr.Textbox(
212
  value="",
213
  label="Model Response",
 
215
  max_lines=10,
216
  interactive=False
217
  )
218
+
219
+ # Generation Parameters
220
  with gr.Accordion("Generation Parameters", open=False):
221
  with gr.Column(elem_classes="parameter-section"):
222
  with gr.Row():
 
226
  maximum=TEMPERATURE_MAX,
227
  value=TEMPERATURE_DEFAULT,
228
  step=0.05,
229
+ label="Temperature"
 
230
  )
 
231
  top_p = gr.Slider(
232
  minimum=TOP_P_MIN,
233
  maximum=TOP_P_MAX,
234
  value=TOP_P_DEFAULT,
235
  step=0.05,
236
+ label="Top-p (nucleus sampling)"
 
237
  )
 
238
  with gr.Column():
239
  top_k = gr.Slider(
240
  minimum=TOP_K_MIN,
241
  maximum=TOP_K_MAX,
242
  value=TOP_K_DEFAULT,
243
  step=1,
244
+ label="Top-k"
 
245
  )
 
246
  max_new_tokens = gr.Slider(
247
  minimum=MAX_NEW_TOKENS_MIN,
248
  maximum=MAX_NEW_TOKENS_MAX,
249
  value=MAX_NEW_TOKENS_DEFAULT,
250
  step=8,
251
+ label="Maximum New Tokens"
 
252
  )
253
+
254
+ # Example Prompts
255
  with gr.Accordion("Example Prompts", open=True):
256
  with gr.Column(elem_classes="example-section"):
257
+ gr.Examples(
258
  examples=examples,
259
  inputs=prompt,
260
+ label="Click an example to try",
261
  examples_per_page=5
262
  )
263
+
264
  # Footer
265
  gr.HTML(f"""
266
  <div class="footer">
267
  <p>Snowflake-G0-Release Demo • Created with Gradio • {datetime.datetime.now().year}</p>
268
  </div>
269
  """)
270
+
271
+ # Interactions
272
  submit_btn.click(
273
  fn=generate_text,
274
  inputs=[prompt, temperature, top_p, top_k, max_new_tokens, history_state],
275
  outputs=[response_output, history_state, chat_history_display]
276
  )
277
+
278
  prompt.submit(
279
  fn=generate_text,
280
  inputs=[prompt, temperature, top_p, top_k, max_new_tokens, history_state],
281
  outputs=[response_output, history_state, chat_history_display]
282
  )
283
+
284
  clear_btn.click(
285
  fn=clear_conversation,
286
  inputs=[],
287
  outputs=[prompt, history_state, chat_history_display]
288
  )
289
+
290
  return demo
291
 
292
+ # Initialize model
 
293
  try:
294
  model, tokenizer, pipeline = load_model_and_tokenizer()
 
295
  except Exception as e:
296
  print(f"Error loading model: {str(e)}")
 
297
  with gr.Blocks(css=css) as error_demo:
298
  gr.HTML(f"""
299
  <div class="header" style="background-color: #ffebee;">
300
  <h1><span class="snowflake-icon">⚠️</span> Error Loading Model</h1>
301
+ <p>There was a problem loading the model: {str(e)}</p>
302
  </div>
303
  """)
304
  demo = error_demo
305
+ else:
306
+ demo = create_demo()
 
307
 
308
  # Launch the app
309
  if __name__ == "__main__":