sagarleet commited on
Commit
92c977f
·
1 Parent(s): 93112a6

Deploy Gemma-4-31B-it-abliterated uncensored model

Browse files
Files changed (3) hide show
  1. README.md +51 -5
  2. app.py +364 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,12 +1,58 @@
1
  ---
2
- title: Test
3
- emoji: 🌍
4
  colorFrom: purple
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 6.12.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Gemma-4-31B Uncensored
3
+ emoji: 🚀
4
  colorFrom: purple
5
+ colorTo: pink
6
  sdk: gradio
7
+ sdk_version: 4.19.0
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
  ---
12
 
13
+ # Gemma-4-31B-it-abliterated (Uncensored)
14
+
15
+ Powerful 31B parameter uncensored AI model for code generation, chat, and text generation.
16
+
17
+ ## Features
18
+
19
+ - 💬 Interactive chat without restrictions
20
+ - 💻 Code generation (Python, JavaScript, Java, C++, etc.)
21
+ - ✨ Code completion
22
+ - 📝 Uncensored text generation
23
+ - 🔥 31B parameters with 4-bit quantization
24
+
25
+ ## Model
26
+
27
+ - **Base**: paperscarecrow/Gemma-4-31B-it-abliterated
28
+ - **Parameters**: 31 billion
29
+ - **Quantization**: 4-bit (NF4)
30
+ - **Type**: Uncensored/Abliterated
31
+
32
+ ## Usage
33
+
34
+ ### Web Interface
35
+
36
+ Use the tabs above to:
37
+ 1. Chat with the model
38
+ 2. Generate code
39
+ 3. Complete code
40
+ 4. Generate text
41
+
42
+ ### API
43
+
44
+ ```python
45
+ from gradio_client import Client
46
+
47
+ client = Client("sagarleet/test")
48
+ result = client.predict("Write a Python function", 500, 0.7, 0.9, 50, api_name="/predict")
49
+ print(result)
50
+ ```
51
+
52
+ ## Hardware
53
+
54
+ This Space requires GPU hardware (T4 or better) due to the model size.
55
+
56
+ ## Disclaimer
57
+
58
+ This is an uncensored AI model. Use responsibly and ethically.
app.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gemma-4-31B-it-abliterated API for HuggingFace Spaces
3
+ Uncensored model optimized for both Gradio UI and REST API access
4
+ """
5
+ import gradio as gr
6
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
7
+ import torch
8
+ import logging
9
+
10
+ # Configure logging
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Model configuration - Uncensored Gemma 31B
15
+ MODEL_NAME = "paperscarecrow/Gemma-4-31B-it-abliterated"
16
+
17
+ logger.info(f"Loading model: {MODEL_NAME}")
18
+
19
+ # Load tokenizer
20
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
21
+
22
+ # Configure 4-bit quantization for memory efficiency
23
+ quantization_config = BitsAndBytesConfig(
24
+ load_in_4bit=True,
25
+ bnb_4bit_compute_dtype=torch.float16,
26
+ bnb_4bit_use_double_quant=True,
27
+ bnb_4bit_quant_type="nf4"
28
+ )
29
+
30
+ # Load model with quantization - requires GPU
31
+ logger.info("Loading model with 4-bit quantization (requires GPU)...")
32
+ model = AutoModelForCausalLM.from_pretrained(
33
+ MODEL_NAME,
34
+ trust_remote_code=True,
35
+ quantization_config=quantization_config,
36
+ device_map="auto",
37
+ torch_dtype=torch.float16
38
+ )
39
+
40
+ if tokenizer.pad_token is None:
41
+ tokenizer.pad_token = tokenizer.eos_token
42
+
43
+ logger.info(f"Model loaded successfully on device: {model.device}")
44
+
45
+ def generate_text(prompt, max_tokens=500, temperature=0.7, top_p=0.9, top_k=50):
46
+ """Generate text from prompt"""
47
+ try:
48
+ logger.info(f"Generating text for prompt: {prompt[:50]}...")
49
+
50
+ # Format prompt for Gemma
51
+ formatted_prompt = f"<start_of_turn>user\n{prompt}<end_of_turn>\n<start_of_turn>model\n"
52
+
53
+ inputs = tokenizer(formatted_prompt, return_tensors="pt", padding=True).to(model.device)
54
+
55
+ with torch.no_grad():
56
+ outputs = model.generate(
57
+ inputs.input_ids,
58
+ max_new_tokens=int(max_tokens),
59
+ temperature=float(temperature),
60
+ top_p=float(top_p),
61
+ top_k=int(top_k),
62
+ do_sample=True,
63
+ pad_token_id=tokenizer.pad_token_id,
64
+ eos_token_id=tokenizer.eos_token_id
65
+ )
66
+
67
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
68
+
69
+ # Extract only the model's response
70
+ if "<start_of_turn>model" in generated_text:
71
+ response = generated_text.split("<start_of_turn>model")[-1].strip()
72
+ else:
73
+ response = generated_text[len(formatted_prompt):].strip()
74
+
75
+ logger.info("Text generation successful")
76
+
77
+ return response
78
+
79
+ except Exception as e:
80
+ logger.error(f"Error generating text: {str(e)}")
81
+ return f"Error: {str(e)}"
82
+
83
+ def generate_code(prompt, max_tokens=500, temperature=0.2, top_p=0.95):
84
+ """Generate code from prompt"""
85
+ code_prompt = f"Write code for the following task:\n\n{prompt}\n\nProvide clean, well-commented code:"
86
+ return generate_text(code_prompt, max_tokens, temperature, top_p, 50)
87
+
88
+ def complete_code(code, max_tokens=300, temperature=0.2):
89
+ """Complete partial code"""
90
+ try:
91
+ logger.info(f"Completing code: {code[:50]}...")
92
+
93
+ formatted_prompt = f"<start_of_turn>user\nComplete this code:\n\n{code}<end_of_turn>\n<start_of_turn>model\n"
94
+
95
+ inputs = tokenizer(formatted_prompt, return_tensors="pt", padding=True).to(model.device)
96
+
97
+ with torch.no_grad():
98
+ outputs = model.generate(
99
+ inputs.input_ids,
100
+ max_new_tokens=int(max_tokens),
101
+ temperature=float(temperature),
102
+ do_sample=True,
103
+ pad_token_id=tokenizer.pad_token_id,
104
+ eos_token_id=tokenizer.eos_token_id
105
+ )
106
+
107
+ completed = tokenizer.decode(outputs[0], skip_special_tokens=True)
108
+
109
+ # Extract completion
110
+ if "<start_of_turn>model" in completed:
111
+ completion = completed.split("<start_of_turn>model")[-1].strip()
112
+ else:
113
+ completion = completed[len(formatted_prompt):].strip()
114
+
115
+ logger.info("Code completion successful")
116
+
117
+ return f"**Original Code:**\n```\n{code}\n```\n\n**Completed Code:**\n```\n{completion}\n```"
118
+
119
+ except Exception as e:
120
+ logger.error(f"Error completing code: {str(e)}")
121
+ return f"Error: {str(e)}"
122
+
123
+ def chat(message, history, max_tokens=500, temperature=0.7):
124
+ """Chat with conversation history"""
125
+ try:
126
+ # Build conversation context
127
+ conversation = ""
128
+ for user_msg, assistant_msg in history:
129
+ conversation += f"<start_of_turn>user\n{user_msg}<end_of_turn>\n"
130
+ conversation += f"<start_of_turn>model\n{assistant_msg}<end_of_turn>\n"
131
+
132
+ conversation += f"<start_of_turn>user\n{message}<end_of_turn>\n<start_of_turn>model\n"
133
+
134
+ inputs = tokenizer(conversation, return_tensors="pt", padding=True).to(model.device)
135
+
136
+ with torch.no_grad():
137
+ outputs = model.generate(
138
+ inputs.input_ids,
139
+ max_new_tokens=int(max_tokens),
140
+ temperature=float(temperature),
141
+ do_sample=True,
142
+ pad_token_id=tokenizer.pad_token_id,
143
+ eos_token_id=tokenizer.eos_token_id
144
+ )
145
+
146
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
147
+
148
+ # Extract only the new response
149
+ if "<start_of_turn>model" in response:
150
+ response = response.split("<start_of_turn>model")[-1].strip()
151
+
152
+ return response
153
+
154
+ except Exception as e:
155
+ logger.error(f"Error in chat: {str(e)}")
156
+ return f"Error: {str(e)}"
157
+
158
+ # Create Gradio interface with tabs
159
+ with gr.Blocks(title="Gemma-4-31B Uncensored API", theme=gr.themes.Soft()) as demo:
160
+ gr.Markdown("""
161
+ # 🚀 Gemma-4-31B-it-abliterated (Uncensored)
162
+
163
+ **Powerful uncensored AI model for coding and general tasks**
164
+
165
+ - Generate code and text without restrictions
166
+ - Complete partial code
167
+ - Interactive chat interface
168
+ - 31B parameters with 4-bit quantization
169
+
170
+ **Model**: `paperscarecrow/Gemma-4-31B-it-abliterated`
171
+
172
+ ⚠️ **Note**: This is an uncensored model. Use responsibly.
173
+ """)
174
+
175
+ with gr.Tabs():
176
+ # Tab 1: Chat
177
+ with gr.Tab("💬 Chat"):
178
+ gr.Markdown("### Interactive chat with the uncensored model")
179
+
180
+ chatbot = gr.Chatbot(height=400)
181
+ msg = gr.Textbox(label="Message", placeholder="Ask me anything...")
182
+
183
+ with gr.Row():
184
+ chat_max_tokens = gr.Slider(100, 1000, value=500, label="Max Tokens", step=50)
185
+ chat_temperature = gr.Slider(0.1, 2.0, value=0.7, label="Temperature", step=0.1)
186
+
187
+ with gr.Row():
188
+ submit = gr.Button("Send", variant="primary")
189
+ clear = gr.Button("Clear")
190
+
191
+ def respond(message, chat_history, max_tokens, temperature):
192
+ bot_message = chat(message, chat_history, max_tokens, temperature)
193
+ chat_history.append((message, bot_message))
194
+ return "", chat_history
195
+
196
+ submit.click(respond, [msg, chatbot, chat_max_tokens, chat_temperature], [msg, chatbot])
197
+ msg.submit(respond, [msg, chatbot, chat_max_tokens, chat_temperature], [msg, chatbot])
198
+ clear.click(lambda: None, None, chatbot, queue=False)
199
+
200
+ # Tab 2: Generate Code
201
+ with gr.Tab("💻 Generate Code"):
202
+ gr.Markdown("### Generate code from natural language description")
203
+ with gr.Row():
204
+ with gr.Column():
205
+ gen_prompt = gr.Textbox(
206
+ label="Code Prompt",
207
+ placeholder="Write a Python function to...",
208
+ lines=5
209
+ )
210
+ gen_max_tokens = gr.Slider(100, 1000, value=500, label="Max Tokens", step=50)
211
+ gen_temperature = gr.Slider(0.1, 1.0, value=0.2, label="Temperature", step=0.1)
212
+ gen_top_p = gr.Slider(0.1, 1.0, value=0.95, label="Top P", step=0.05)
213
+ gen_button = gr.Button("Generate Code", variant="primary")
214
+
215
+ with gr.Column():
216
+ gen_output = gr.Textbox(label="Generated Code", lines=20)
217
+
218
+ gen_button.click(
219
+ fn=generate_code,
220
+ inputs=[gen_prompt, gen_max_tokens, gen_temperature, gen_top_p],
221
+ outputs=gen_output
222
+ )
223
+
224
+ gr.Examples(
225
+ examples=[
226
+ ["Write a Python function to implement quicksort algorithm", 500, 0.2, 0.95],
227
+ ["Create a REST API in Flask with authentication", 600, 0.2, 0.95],
228
+ ["Write a React component for a todo list with hooks", 500, 0.2, 0.95],
229
+ ],
230
+ inputs=[gen_prompt, gen_max_tokens, gen_temperature, gen_top_p]
231
+ )
232
+
233
+ # Tab 3: Complete Code
234
+ with gr.Tab("✨ Complete Code"):
235
+ gr.Markdown("### Complete partial code")
236
+ with gr.Row():
237
+ with gr.Column():
238
+ comp_code = gr.Textbox(
239
+ label="Partial Code",
240
+ placeholder="def fibonacci(n):\n if n <= 1:\n return n\n ",
241
+ lines=10
242
+ )
243
+ comp_max_tokens = gr.Slider(100, 500, value=300, label="Max Tokens", step=50)
244
+ comp_temperature = gr.Slider(0.1, 1.0, value=0.2, label="Temperature", step=0.1)
245
+ comp_button = gr.Button("Complete Code", variant="primary")
246
+
247
+ with gr.Column():
248
+ comp_output = gr.Markdown(label="Completion")
249
+
250
+ comp_button.click(
251
+ fn=complete_code,
252
+ inputs=[comp_code, comp_max_tokens, comp_temperature],
253
+ outputs=comp_output
254
+ )
255
+
256
+ # Tab 4: General Text Generation
257
+ with gr.Tab("📝 Generate Text"):
258
+ gr.Markdown("### Generate any text without restrictions")
259
+ with gr.Row():
260
+ with gr.Column():
261
+ text_prompt = gr.Textbox(
262
+ label="Prompt",
263
+ placeholder="Write about...",
264
+ lines=5
265
+ )
266
+ text_max_tokens = gr.Slider(100, 1000, value=500, label="Max Tokens", step=50)
267
+ text_temperature = gr.Slider(0.1, 2.0, value=0.7, label="Temperature", step=0.1)
268
+ text_top_p = gr.Slider(0.1, 1.0, value=0.9, label="Top P", step=0.05)
269
+ text_top_k = gr.Slider(1, 100, value=50, label="Top K", step=1)
270
+ text_button = gr.Button("Generate", variant="primary")
271
+
272
+ with gr.Column():
273
+ text_output = gr.Textbox(label="Generated Text", lines=20)
274
+
275
+ text_button.click(
276
+ fn=generate_text,
277
+ inputs=[text_prompt, text_max_tokens, text_temperature, text_top_p, text_top_k],
278
+ outputs=text_output
279
+ )
280
+
281
+ # Tab 5: API Documentation
282
+ with gr.Tab("📚 API Documentation"):
283
+ gr.Markdown("""
284
+ ## REST API Endpoints
285
+
286
+ This Space provides REST API endpoints for programmatic access.
287
+
288
+ ### Base URL
289
+ ```
290
+ https://YOUR-USERNAME-YOUR-SPACE-NAME.hf.space
291
+ ```
292
+
293
+ ### Python Client
294
+ ```python
295
+ from gradio_client import Client
296
+
297
+ client = Client("YOUR-USERNAME/YOUR-SPACE-NAME")
298
+
299
+ # Generate code
300
+ result = client.predict(
301
+ "Write a Python function to reverse a string",
302
+ 500, # max_tokens
303
+ 0.2, # temperature
304
+ 0.95, # top_p
305
+ api_name="/predict"
306
+ )
307
+ print(result)
308
+ ```
309
+
310
+ ### cURL Example
311
+ ```bash
312
+ curl -X POST "https://YOUR-SPACE.hf.space/api/predict" \\
313
+ -H "Content-Type: application/json" \\
314
+ -d '{
315
+ "data": ["Write a Python function", 500, 0.2, 0.95],
316
+ "fn_index": 1
317
+ }'
318
+ ```
319
+
320
+ ## Model Information
321
+
322
+ - **Model**: Gemma-4-31B-it-abliterated
323
+ - **Parameters**: 31 billion
324
+ - **Type**: Uncensored/Abliterated
325
+ - **Quantization**: 4-bit (NF4)
326
+ - **Context Length**: 8K tokens
327
+ - **Hardware Required**: GPU (T4 or better)
328
+
329
+ ## Hardware Requirements
330
+
331
+ ⚠️ **Important**: This model requires GPU hardware due to its size (31B parameters).
332
+
333
+ When creating your Space:
334
+ 1. Select **T4 small** (free) or **A10G small** (paid) hardware
335
+ 2. Do NOT use CPU - the model won't load
336
+
337
+ ## Tips for Best Results
338
+
339
+ 1. **Lower temperature** (0.1-0.3) for factual/code tasks
340
+ 2. **Higher temperature** (0.7-1.5) for creative tasks
341
+ 3. **Adjust top_p and top_k** for diversity control
342
+ 4. **Be specific** in your prompts
343
+
344
+ ## Responsible Use
345
+
346
+ This is an uncensored model that can generate any content. Please use responsibly and ethically.
347
+ """)
348
+
349
+ gr.Markdown("""
350
+ ---
351
+ **Model**: [Gemma-4-31B-it-abliterated](https://huggingface.co/paperscarecrow/Gemma-4-31B-it-abliterated) | **Powered by**: HuggingFace Spaces
352
+
353
+ ⚠️ **Disclaimer**: This is an uncensored AI model. The outputs are generated by AI and may not reflect the views of the deployer.
354
+ """)
355
+
356
+ # Launch the app
357
+ if __name__ == "__main__":
358
+ demo.launch(
359
+ server_name="0.0.0.0",
360
+ server_port=7860,
361
+ share=False
362
+ )
363
+
364
+ # Made with Bob
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio==4.19.0
2
+ transformers==4.36.0
3
+ torch==2.1.0
4
+ accelerate==0.25.0
5
+ bitsandbytes==0.41.3
6
+ scipy==1.11.4