sagarleet commited on
Commit
7334bca
Β·
1 Parent(s): 2ae8489

Improve error handling and use Q2_K quantization for faster loading

Browse files
Files changed (1) hide show
  1. app.py +91 -22
app.py CHANGED
@@ -5,32 +5,66 @@ import gradio as gr
5
  from llama_cpp import Llama
6
  import logging
7
  from huggingface_hub import hf_hub_download
 
8
 
9
  logging.basicConfig(level=logging.INFO)
10
  logger = logging.getLogger(__name__)
11
 
12
  MODEL_REPO = "Jiunsong/supergemma4-26b-uncensored-gguf-v2"
13
- MODEL_FILE = "supergemma4-26b-uncensored-Q4_K_M.gguf"
 
14
 
15
  logger.info(f"Loading model: {MODEL_REPO}/{MODEL_FILE}")
 
 
 
16
 
17
  try:
18
- model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE, repo_type="model")
 
 
 
 
 
 
19
  logger.info(f"Model downloaded to: {model_path}")
20
- llm = Llama(model_path=model_path, n_ctx=4096, n_threads=8, n_gpu_layers=0, verbose=False)
21
- logger.info("Model loaded successfully on CPU")
 
 
 
 
 
 
 
 
 
 
 
22
  except Exception as e:
23
- logger.error(f"Error loading model: {str(e)}")
 
24
  llm = None
25
 
26
  def generate_text(prompt, max_tokens=500, temperature=0.7, top_p=0.9, top_k=40):
27
  if llm is None:
28
- return "Error: Model not loaded"
29
  try:
30
- response = llm(prompt, max_tokens=int(max_tokens), temperature=float(temperature),
31
- top_p=float(top_p), top_k=int(top_k), stop=["</s>"], echo=False)
32
- return response['choices'][0]['text'].strip()
 
 
 
 
 
 
 
 
 
 
33
  except Exception as e:
 
34
  return f"Error: {str(e)}"
35
 
36
  def generate_code(prompt, max_tokens=500, temperature=0.2, top_p=0.95):
@@ -39,24 +73,52 @@ def generate_code(prompt, max_tokens=500, temperature=0.2, top_p=0.95):
39
 
40
  def chat(message, history, max_tokens=500, temperature=0.7):
41
  if llm is None:
42
- return "Error: Model not loaded"
43
  conversation = ""
44
  for user_msg, assistant_msg in history:
45
- conversation += f"### User:\n{user_msg}\n\n### Assistant:\n{assistant_msg}\n\n"
46
- conversation += f"### User:\n{message}\n\n### Assistant:\n"
47
- response = llm(conversation, max_tokens=int(max_tokens), temperature=float(temperature),
48
- top_p=0.9, top_k=40, stop=["### User:"], echo=False)
 
 
 
 
 
 
 
49
  return response['choices'][0]['text'].strip()
50
 
 
51
  with gr.Blocks(title="SuperGemma4-26B Uncensored", theme=gr.themes.Soft()) as demo:
52
- gr.Markdown("# πŸš€ SuperGemma4-26B Uncensored (CPU)\n\n26B parameter uncensored model running on CPU")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  with gr.Tabs():
55
  with gr.Tab("πŸ’¬ Chat"):
56
  chatbot = gr.Chatbot(height=400)
57
- msg = gr.Textbox(label="Message")
58
  with gr.Row():
59
- chat_max_tokens = gr.Slider(100, 1000, value=500, label="Max Tokens")
60
  chat_temperature = gr.Slider(0.1, 2.0, value=0.7, label="Temperature")
61
  with gr.Row():
62
  submit = gr.Button("Send", variant="primary")
@@ -73,8 +135,8 @@ with gr.Blocks(title="SuperGemma4-26B Uncensored", theme=gr.themes.Soft()) as de
73
  with gr.Tab("πŸ’» Generate Code"):
74
  with gr.Row():
75
  with gr.Column():
76
- gen_prompt = gr.Textbox(label="Prompt", lines=5)
77
- gen_max_tokens = gr.Slider(100, 1000, value=500, label="Max Tokens")
78
  gen_temperature = gr.Slider(0.1, 1.0, value=0.2, label="Temperature")
79
  gen_top_p = gr.Slider(0.1, 1.0, value=0.95, label="Top P")
80
  gen_button = gr.Button("Generate", variant="primary")
@@ -85,8 +147,8 @@ with gr.Blocks(title="SuperGemma4-26B Uncensored", theme=gr.themes.Soft()) as de
85
  with gr.Tab("πŸ“ Generate Text"):
86
  with gr.Row():
87
  with gr.Column():
88
- text_prompt = gr.Textbox(label="Prompt", lines=5)
89
- text_max_tokens = gr.Slider(100, 1000, value=500, label="Max Tokens")
90
  text_temperature = gr.Slider(0.1, 2.0, value=0.7, label="Temperature")
91
  text_top_p = gr.Slider(0.1, 1.0, value=0.9, label="Top P")
92
  text_top_k = gr.Slider(1, 100, value=40, label="Top K")
@@ -94,6 +156,13 @@ with gr.Blocks(title="SuperGemma4-26B Uncensored", theme=gr.themes.Soft()) as de
94
  with gr.Column():
95
  text_output = gr.Textbox(label="Generated Text", lines=20)
96
  text_button.click(generate_text, [text_prompt, text_max_tokens, text_temperature, text_top_p, text_top_k], text_output)
 
 
 
 
 
 
 
97
 
98
  if __name__ == "__main__":
99
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
5
  from llama_cpp import Llama
6
  import logging
7
  from huggingface_hub import hf_hub_download
8
+ import os
9
 
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
  MODEL_REPO = "Jiunsong/supergemma4-26b-uncensored-gguf-v2"
14
+ # Try Q2_K for smaller size and faster loading
15
+ MODEL_FILE = "supergemma4-26b-uncensored-Q2_K.gguf"
16
 
17
  logger.info(f"Loading model: {MODEL_REPO}/{MODEL_FILE}")
18
+ logger.info(f"This may take 5-10 minutes for first load...")
19
+
20
+ llm = None
21
 
22
  try:
23
+ logger.info("Downloading model from HuggingFace...")
24
+ model_path = hf_hub_download(
25
+ repo_id=MODEL_REPO,
26
+ filename=MODEL_FILE,
27
+ repo_type="model",
28
+ resume_download=True
29
+ )
30
  logger.info(f"Model downloaded to: {model_path}")
31
+ logger.info(f"Model file size: {os.path.getsize(model_path) / (1024**3):.2f} GB")
32
+
33
+ logger.info("Loading model into memory...")
34
+ llm = Llama(
35
+ model_path=model_path,
36
+ n_ctx=2048, # Reduced context for faster inference
37
+ n_threads=4, # Reduced threads
38
+ n_gpu_layers=0, # CPU only
39
+ verbose=True,
40
+ n_batch=512
41
+ )
42
+ logger.info("βœ… Model loaded successfully on CPU!")
43
+
44
  except Exception as e:
45
+ logger.error(f"❌ Error loading model: {str(e)}")
46
+ logger.error(f"Full error: {repr(e)}")
47
  llm = None
48
 
49
  def generate_text(prompt, max_tokens=500, temperature=0.7, top_p=0.9, top_k=40):
50
  if llm is None:
51
+ return "❌ Error: Model not loaded. Check Space logs for details."
52
  try:
53
+ logger.info(f"Generating: {prompt[:50]}...")
54
+ response = llm(
55
+ prompt,
56
+ max_tokens=int(max_tokens),
57
+ temperature=float(temperature),
58
+ top_p=float(top_p),
59
+ top_k=int(top_k),
60
+ stop=["</s>", "\n\n\n"],
61
+ echo=False
62
+ )
63
+ result = response['choices'][0]['text'].strip()
64
+ logger.info(f"Generated {len(result)} characters")
65
+ return result
66
  except Exception as e:
67
+ logger.error(f"Generation error: {str(e)}")
68
  return f"Error: {str(e)}"
69
 
70
  def generate_code(prompt, max_tokens=500, temperature=0.2, top_p=0.95):
 
73
 
74
  def chat(message, history, max_tokens=500, temperature=0.7):
75
  if llm is None:
76
+ return "❌ Error: Model not loaded"
77
  conversation = ""
78
  for user_msg, assistant_msg in history:
79
+ conversation += f"User: {user_msg}\nAssistant: {assistant_msg}\n\n"
80
+ conversation += f"User: {message}\nAssistant: "
81
+ response = llm(
82
+ conversation,
83
+ max_tokens=int(max_tokens),
84
+ temperature=float(temperature),
85
+ top_p=0.9,
86
+ top_k=40,
87
+ stop=["User:", "</s>"],
88
+ echo=False
89
+ )
90
  return response['choices'][0]['text'].strip()
91
 
92
+ # Create UI
93
  with gr.Blocks(title="SuperGemma4-26B Uncensored", theme=gr.themes.Soft()) as demo:
94
+ gr.Markdown(f"""
95
+ # πŸš€ SuperGemma4-26B Uncensored (CPU)
96
+
97
+ **Status**: {'βœ… Model Loaded' if llm else '❌ Model Loading Failed'}
98
+
99
+ 26B parameter uncensored model running on CPU with Q2_K quantization
100
+
101
+ ⚠️ **Note**: First load takes 5-10 minutes. Please be patient!
102
+ """)
103
+
104
+ if llm is None:
105
+ gr.Markdown("""
106
+ ### ⚠️ Model Loading Error
107
+
108
+ The model failed to load. Possible reasons:
109
+ 1. Model file is still downloading (check Space logs)
110
+ 2. Insufficient memory
111
+ 3. Model file not found
112
+
113
+ **Check the Logs tab** in your Space for detailed error messages.
114
+ """)
115
 
116
  with gr.Tabs():
117
  with gr.Tab("πŸ’¬ Chat"):
118
  chatbot = gr.Chatbot(height=400)
119
+ msg = gr.Textbox(label="Message", placeholder="Ask anything...")
120
  with gr.Row():
121
+ chat_max_tokens = gr.Slider(100, 1000, value=300, label="Max Tokens")
122
  chat_temperature = gr.Slider(0.1, 2.0, value=0.7, label="Temperature")
123
  with gr.Row():
124
  submit = gr.Button("Send", variant="primary")
 
135
  with gr.Tab("πŸ’» Generate Code"):
136
  with gr.Row():
137
  with gr.Column():
138
+ gen_prompt = gr.Textbox(label="Prompt", lines=5, placeholder="Write a Python function to...")
139
+ gen_max_tokens = gr.Slider(100, 1000, value=400, label="Max Tokens")
140
  gen_temperature = gr.Slider(0.1, 1.0, value=0.2, label="Temperature")
141
  gen_top_p = gr.Slider(0.1, 1.0, value=0.95, label="Top P")
142
  gen_button = gr.Button("Generate", variant="primary")
 
147
  with gr.Tab("πŸ“ Generate Text"):
148
  with gr.Row():
149
  with gr.Column():
150
+ text_prompt = gr.Textbox(label="Prompt", lines=5, placeholder="Write about...")
151
+ text_max_tokens = gr.Slider(100, 1000, value=400, label="Max Tokens")
152
  text_temperature = gr.Slider(0.1, 2.0, value=0.7, label="Temperature")
153
  text_top_p = gr.Slider(0.1, 1.0, value=0.9, label="Top P")
154
  text_top_k = gr.Slider(1, 100, value=40, label="Top K")
 
156
  with gr.Column():
157
  text_output = gr.Textbox(label="Generated Text", lines=20)
158
  text_button.click(generate_text, [text_prompt, text_max_tokens, text_temperature, text_top_p, text_top_k], text_output)
159
+
160
+ gr.Markdown("""
161
+ ---
162
+ **Model**: SuperGemma4-26B-Uncensored (Q2_K) | **Hardware**: CPU | **Powered by**: llama.cpp
163
+
164
+ ⚠️ CPU inference is slower (~1-3 tokens/second). Be patient with responses.
165
+ """)
166
 
167
  if __name__ == "__main__":
168
+ demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)