codeShare commited on
Commit
55b3d84
·
verified ·
1 Parent(s): 385c678

Upload HauauCS_Abliterated_Qwen_3_5_4B_LLM_model.ipynb

Browse files
HauauCS_Abliterated_Qwen_3_5_4B_LLM_model.ipynb ADDED
@@ -0,0 +1,808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4"
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "language_info": {
14
+ "name": "python"
15
+ },
16
+ "accelerator": "GPU"
17
+ },
18
+ "cells": [
19
+ {
20
+ "cell_type": "markdown",
21
+ "source": [
22
+ "# HauauCS Abliterated Qwen 3.5 -4B LLM model (image and/or text input)"
23
+ ],
24
+ "metadata": {
25
+ "id": "ewVsp7wRAH2j"
26
+ }
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": null,
31
+ "metadata": {
32
+ "id": "lC55DC9m_4Zz"
33
+ },
34
+ "outputs": [],
35
+ "source": [
36
+ "\n",
37
+ "# ============================================================\n",
38
+ "# QWEN3.5-4B UNCENSORED - GOOGLE COLAB T4\n",
39
+ "#\n",
40
+ "# Model:\n",
41
+ "# DreamFast/Qwen3.5-4B-Uncensored-HauhauCS-Aggressive-Safetensor-Benchmark\n",
42
+ "#\n",
43
+ "# GPU: NVIDIA T4 16GB\n",
44
+ "# Quantization: BitsAndBytes NF4 4-bit\n",
45
+ "# Compute: FP16\n",
46
+ "# Attention: SDPA\n",
47
+ "#\n",
48
+ "# Features:\n",
49
+ "# - Text and image conversations\n",
50
+ "# - Conversation history\n",
51
+ "# - Separate THINKS and SAYS sections\n",
52
+ "# - Larger Gradio chat interface\n",
53
+ "# - Expandable latest-response panels\n",
54
+ "# - Adjustable generation settings\n",
55
+ "# - HF_TOKEN from Colab Secrets\n",
56
+ "# ============================================================\n",
57
+ "\n",
58
+ "\n",
59
+ "# ============================================================\n",
60
+ "# 1. INSTALL DEPENDENCIES\n",
61
+ "# ============================================================\n",
62
+ "\n",
63
+ "import sys\n",
64
+ "import subprocess\n",
65
+ "\n",
66
+ "subprocess.run(\n",
67
+ " [\n",
68
+ " sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-U\",\n",
69
+ " \"bitsandbytes\",\n",
70
+ " \"accelerate\",\n",
71
+ " \"transformers\",\n",
72
+ " \"gradio>=6.0\",\n",
73
+ " \"huggingface_hub\",\n",
74
+ " \"pillow\"\n",
75
+ " ],\n",
76
+ " check=True\n",
77
+ ")\n",
78
+ "\n",
79
+ "\n",
80
+ "# ============================================================\n",
81
+ "# 2. IMPORTS\n",
82
+ "# ============================================================\n",
83
+ "\n",
84
+ "import os\n",
85
+ "import re\n",
86
+ "import gc\n",
87
+ "import torch\n",
88
+ "import gradio as gr\n",
89
+ "\n",
90
+ "from PIL import Image\n",
91
+ "from pathlib import Path\n",
92
+ "\n",
93
+ "from google.colab import userdata\n",
94
+ "\n",
95
+ "from huggingface_hub import hf_hub_download\n",
96
+ "\n",
97
+ "from transformers import (\n",
98
+ " AutoProcessor,\n",
99
+ " AutoTokenizer,\n",
100
+ " AutoModelForMultimodalLM,\n",
101
+ " BitsAndBytesConfig\n",
102
+ ")\n",
103
+ "\n",
104
+ "\n",
105
+ "# ============================================================\n",
106
+ "# 3. CONFIGURATION\n",
107
+ "# ============================================================\n",
108
+ "\n",
109
+ "MODEL_ID = (\n",
110
+ " \"DreamFast/\"\n",
111
+ " \"Qwen3.5-4B-Uncensored-HauhauCS-Aggressive-Safetensor-Benchmark\"\n",
112
+ ")\n",
113
+ "\n",
114
+ "BASE_MODEL_ID = \"Qwen/Qwen3.5-4B\"\n",
115
+ "\n",
116
+ "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
117
+ "\n",
118
+ "if not HF_TOKEN:\n",
119
+ " raise ValueError(\n",
120
+ " \"HF_TOKEN not found in Colab Secrets. \"\n",
121
+ " \"Please add your Hugging Face token.\"\n",
122
+ " )\n",
123
+ "\n",
124
+ "if not torch.cuda.is_available():\n",
125
+ " raise RuntimeError(\"No CUDA GPU detected.\")\n",
126
+ "\n",
127
+ "print(\"GPU:\", torch.cuda.get_device_name(0))\n",
128
+ "print(\"VRAM:\", round(\n",
129
+ " torch.cuda.get_device_properties(0).total_memory / 1024**3, 2\n",
130
+ "), \"GB\")\n",
131
+ "\n",
132
+ "torch.backends.cuda.matmul.allow_tf32 = True\n",
133
+ "\n",
134
+ "\n",
135
+ "# ============================================================\n",
136
+ "# 4. LOAD CHAT TEMPLATE\n",
137
+ "# ============================================================\n",
138
+ "\n",
139
+ "print(\"\\nLoading Qwen3.5 tokenizer...\")\n",
140
+ "\n",
141
+ "tokenizer = AutoTokenizer.from_pretrained(\n",
142
+ " BASE_MODEL_ID,\n",
143
+ " token=HF_TOKEN,\n",
144
+ " trust_remote_code=True\n",
145
+ ")\n",
146
+ "\n",
147
+ "if not tokenizer.chat_template:\n",
148
+ "\n",
149
+ " print(\"Downloading original Qwen3.5 chat template...\")\n",
150
+ "\n",
151
+ " template_path = hf_hub_download(\n",
152
+ " repo_id=BASE_MODEL_ID,\n",
153
+ " filename=\"chat_template.jinja\",\n",
154
+ " token=HF_TOKEN\n",
155
+ " )\n",
156
+ "\n",
157
+ " with open(template_path, \"r\", encoding=\"utf-8\") as f:\n",
158
+ " chat_template = f.read()\n",
159
+ "\n",
160
+ " tokenizer.chat_template = chat_template\n",
161
+ "\n",
162
+ "else:\n",
163
+ " chat_template = tokenizer.chat_template\n",
164
+ "\n",
165
+ "print(\"Chat template loaded.\")\n",
166
+ "\n",
167
+ "\n",
168
+ "# ============================================================\n",
169
+ "# 5. LOAD PROCESSOR\n",
170
+ "# ============================================================\n",
171
+ "\n",
172
+ "print(\"\\nLoading multimodal processor...\")\n",
173
+ "\n",
174
+ "processor = AutoProcessor.from_pretrained(\n",
175
+ " MODEL_ID,\n",
176
+ " token=HF_TOKEN,\n",
177
+ " trust_remote_code=True\n",
178
+ ")\n",
179
+ "\n",
180
+ "# Use the compatible original Qwen3.5 tokenizer/template.\n",
181
+ "processor.tokenizer = tokenizer\n",
182
+ "processor.chat_template = chat_template\n",
183
+ "\n",
184
+ "print(\"Processor loaded.\")\n",
185
+ "\n",
186
+ "\n",
187
+ "# ============================================================\n",
188
+ "# 6. 4-BIT QUANTIZATION\n",
189
+ "# ============================================================\n",
190
+ "\n",
191
+ "quantization_config = BitsAndBytesConfig(\n",
192
+ " load_in_4bit=True,\n",
193
+ " bnb_4bit_quant_type=\"nf4\",\n",
194
+ " bnb_4bit_compute_dtype=torch.float16,\n",
195
+ " bnb_4bit_use_double_quant=True\n",
196
+ ")\n",
197
+ "\n",
198
+ "\n",
199
+ "# ============================================================\n",
200
+ "# 7. LOAD MODEL\n",
201
+ "# ============================================================\n",
202
+ "\n",
203
+ "print(\"\\nLoading model in 4-bit...\")\n",
204
+ "\n",
205
+ "model = AutoModelForMultimodalLM.from_pretrained(\n",
206
+ " MODEL_ID,\n",
207
+ " token=HF_TOKEN,\n",
208
+ " quantization_config=quantization_config,\n",
209
+ " dtype=torch.float16,\n",
210
+ " device_map=\"auto\",\n",
211
+ " low_cpu_mem_usage=True,\n",
212
+ " attn_implementation=\"sdpa\",\n",
213
+ " trust_remote_code=True\n",
214
+ ")\n",
215
+ "\n",
216
+ "model.eval()\n",
217
+ "\n",
218
+ "print(\"\\nModel loaded successfully.\")\n",
219
+ "\n",
220
+ "print(\"Model device:\", model.get_input_embeddings().weight.device)\n",
221
+ "\n",
222
+ "# ============================================================\n",
223
+ "# 8. PREPARE MULTIMODAL INPUTS\n",
224
+ "# ============================================================\n",
225
+ "\n",
226
+ "def prepare_multimodal_inputs(messages):\n",
227
+ "\n",
228
+ " # Apply the chat template using the tokenizer directly.\n",
229
+ " prompt = tokenizer.apply_chat_template(\n",
230
+ " messages,\n",
231
+ " tokenize=False,\n",
232
+ " add_generation_prompt=True\n",
233
+ " )\n",
234
+ "\n",
235
+ " # Collect images in conversation order.\n",
236
+ " images = []\n",
237
+ "\n",
238
+ " for msg in messages:\n",
239
+ "\n",
240
+ " content = msg.get(\"content\", [])\n",
241
+ "\n",
242
+ " if isinstance(content, str):\n",
243
+ " continue\n",
244
+ "\n",
245
+ " if not isinstance(content, list):\n",
246
+ " continue\n",
247
+ "\n",
248
+ " for item in content:\n",
249
+ "\n",
250
+ " if (\n",
251
+ " isinstance(item, dict)\n",
252
+ " and item.get(\"type\") == \"image\"\n",
253
+ " ):\n",
254
+ "\n",
255
+ " image = item.get(\"image\")\n",
256
+ "\n",
257
+ " if image is not None:\n",
258
+ " images.append(image)\n",
259
+ "\n",
260
+ " # Process text and images.\n",
261
+ " if images:\n",
262
+ "\n",
263
+ " formatted_inputs = processor(\n",
264
+ " text=prompt,\n",
265
+ " images=images,\n",
266
+ " return_tensors=\"pt\"\n",
267
+ " )\n",
268
+ "\n",
269
+ " else:\n",
270
+ "\n",
271
+ " formatted_inputs = processor(\n",
272
+ " text=prompt,\n",
273
+ " return_tensors=\"pt\"\n",
274
+ " )\n",
275
+ "\n",
276
+ " return formatted_inputs\n",
277
+ "\n",
278
+ "\n",
279
+ "# ============================================================\n",
280
+ "# 9. SPLIT THINKING AND FINAL ANSWER\n",
281
+ "# ============================================================\n",
282
+ "\n",
283
+ "def split_thinking_and_answer(raw_text):\n",
284
+ "\n",
285
+ " \"\"\"\n",
286
+ " Separates model-generated <think>...</think> content\n",
287
+ " from the final answer.\n",
288
+ "\n",
289
+ " If the model does not return a think block, its complete\n",
290
+ " response is treated as the final answer.\n",
291
+ " \"\"\"\n",
292
+ "\n",
293
+ " raw_text = raw_text.strip()\n",
294
+ "\n",
295
+ " # Remove common trailing generation tokens.\n",
296
+ " raw_text = re.sub(\n",
297
+ " r\"<\\|im_end\\|>|<\\|endoftext\\|>|</s>\",\n",
298
+ " \"\",\n",
299
+ " raw_text\n",
300
+ " ).strip()\n",
301
+ "\n",
302
+ " # Find a complete think block.\n",
303
+ " match = re.search(\n",
304
+ " r\"<think>(.*?)</think>\",\n",
305
+ " raw_text,\n",
306
+ " flags=re.DOTALL | re.IGNORECASE\n",
307
+ " )\n",
308
+ "\n",
309
+ " if match:\n",
310
+ "\n",
311
+ " thinking = match.group(1).strip()\n",
312
+ "\n",
313
+ " # Everything outside the think block is the answer.\n",
314
+ " answer = (\n",
315
+ " raw_text[:match.start()]\n",
316
+ " + raw_text[match.end():]\n",
317
+ " ).strip()\n",
318
+ "\n",
319
+ " else:\n",
320
+ "\n",
321
+ " # Handle an unclosed think block.\n",
322
+ " open_match = re.search(\n",
323
+ " r\"<think>\",\n",
324
+ " raw_text,\n",
325
+ " flags=re.IGNORECASE\n",
326
+ " )\n",
327
+ "\n",
328
+ " if open_match:\n",
329
+ "\n",
330
+ " thinking = raw_text[open_match.end():].strip()\n",
331
+ " answer = \"\"\n",
332
+ "\n",
333
+ " else:\n",
334
+ "\n",
335
+ " thinking = \"The model did not return a separate <think> block.\"\n",
336
+ " answer = raw_text\n",
337
+ "\n",
338
+ " # Remove any remaining template artifacts.\n",
339
+ " answer = re.sub(\n",
340
+ " r\"<\\|im_start\\|>|<\\|im_sep\\|>|<\\|im_end\\|>\",\n",
341
+ " \"\",\n",
342
+ " answer\n",
343
+ " ).strip()\n",
344
+ "\n",
345
+ " thinking = re.sub(\n",
346
+ " r\"<\\|im_start\\|>|<\\|im_sep\\|>|<\\|im_end\\|>\",\n",
347
+ " \"\",\n",
348
+ " thinking\n",
349
+ " ).strip()\n",
350
+ "\n",
351
+ " if not answer:\n",
352
+ " answer = \"(The model did not produce a separate final answer.)\"\n",
353
+ "\n",
354
+ " if not thinking:\n",
355
+ " thinking = \"(No thinking text was returned.)\"\n",
356
+ "\n",
357
+ " return thinking, answer\n",
358
+ "\n",
359
+ "\n",
360
+ "# ============================================================\n",
361
+ "# 10. GENERATION FUNCTION\n",
362
+ "# ============================================================\n",
363
+ "\n",
364
+ "def generate_response(\n",
365
+ " messages,\n",
366
+ " max_new_tokens=1024,\n",
367
+ " temperature=0.7,\n",
368
+ " top_p=0.9\n",
369
+ "):\n",
370
+ "\n",
371
+ " inputs = prepare_multimodal_inputs(messages)\n",
372
+ "\n",
373
+ " # Move inputs to the model's embedding device.\n",
374
+ " input_device = model.get_input_embeddings().weight.device\n",
375
+ "\n",
376
+ " inputs = inputs.to(input_device)\n",
377
+ "\n",
378
+ " input_length = inputs[\"input_ids\"].shape[-1]\n",
379
+ "\n",
380
+ " do_sample = float(temperature) > 0\n",
381
+ "\n",
382
+ " generation_kwargs = {\n",
383
+ " \"max_new_tokens\": int(max_new_tokens),\n",
384
+ " \"do_sample\": do_sample,\n",
385
+ " \"repetition_penalty\": 1.05,\n",
386
+ " \"pad_token_id\": tokenizer.pad_token_id\n",
387
+ " if tokenizer.pad_token_id is not None\n",
388
+ " else tokenizer.eos_token_id,\n",
389
+ " \"eos_token_id\": tokenizer.eos_token_id,\n",
390
+ " \"use_cache\": True\n",
391
+ " }\n",
392
+ "\n",
393
+ " if do_sample:\n",
394
+ "\n",
395
+ " generation_kwargs.update({\n",
396
+ " \"temperature\": float(temperature),\n",
397
+ " \"top_p\": float(top_p)\n",
398
+ " })\n",
399
+ "\n",
400
+ " with torch.inference_mode():\n",
401
+ "\n",
402
+ " output_ids = model.generate(\n",
403
+ " **inputs,\n",
404
+ " **generation_kwargs\n",
405
+ " )\n",
406
+ "\n",
407
+ " # Decode only newly generated tokens.\n",
408
+ " generated_ids = output_ids[0][input_length:]\n",
409
+ "\n",
410
+ " raw_response = tokenizer.decode(\n",
411
+ " generated_ids,\n",
412
+ " skip_special_tokens=False,\n",
413
+ " clean_up_tokenization_spaces=False\n",
414
+ " )\n",
415
+ "\n",
416
+ " thinking, answer = split_thinking_and_answer(raw_response)\n",
417
+ "\n",
418
+ " # Keep the original model response in the conversation history.\n",
419
+ " return raw_response.strip(), thinking, answer\n",
420
+ "\n",
421
+ "\n",
422
+ "# ============================================================\n",
423
+ "# 11. GRADIO CHAT FUNCTION\n",
424
+ "# ============================================================\n",
425
+ "\n",
426
+ "def chat(\n",
427
+ " message,\n",
428
+ " image,\n",
429
+ " chat_history,\n",
430
+ " conversation_history,\n",
431
+ " max_new_tokens,\n",
432
+ " temperature,\n",
433
+ " top_p\n",
434
+ "):\n",
435
+ "\n",
436
+ " if chat_history is None:\n",
437
+ " chat_history = []\n",
438
+ "\n",
439
+ " if conversation_history is None:\n",
440
+ " conversation_history = []\n",
441
+ "\n",
442
+ " message = (message or \"\").strip()\n",
443
+ "\n",
444
+ " if not message and image is None:\n",
445
+ "\n",
446
+ " return (\n",
447
+ " chat_history,\n",
448
+ " conversation_history,\n",
449
+ " \"\",\n",
450
+ " None,\n",
451
+ " \"\",\n",
452
+ " \"Please enter a message or upload an image.\"\n",
453
+ " )\n",
454
+ "\n",
455
+ " # Build user content.\n",
456
+ " user_content = []\n",
457
+ "\n",
458
+ " if message:\n",
459
+ "\n",
460
+ " user_content.append({\n",
461
+ " \"type\": \"text\",\n",
462
+ " \"text\": message\n",
463
+ " })\n",
464
+ "\n",
465
+ " if image is not None:\n",
466
+ "\n",
467
+ " # Convert to RGB PIL image.\n",
468
+ " if isinstance(image, Image.Image):\n",
469
+ " image = image.convert(\"RGB\")\n",
470
+ "\n",
471
+ " user_content.append({\n",
472
+ " \"type\": \"image\",\n",
473
+ " \"image\": image\n",
474
+ " })\n",
475
+ "\n",
476
+ " # Add user turn to actual model conversation.\n",
477
+ " conversation_history = list(conversation_history)\n",
478
+ "\n",
479
+ " conversation_history.append({\n",
480
+ " \"role\": \"user\",\n",
481
+ " \"content\": user_content\n",
482
+ " })\n",
483
+ "\n",
484
+ " # Display user message in the chat window.\n",
485
+ " display_message = message if message else \"Please describe this image.\"\n",
486
+ "\n",
487
+ " if image is not None:\n",
488
+ " display_message += \"\\n\\n📷 *Image attached*\"\n",
489
+ "\n",
490
+ " chat_history = list(chat_history)\n",
491
+ "\n",
492
+ " chat_history.append({\n",
493
+ " \"role\": \"user\",\n",
494
+ " \"content\": display_message\n",
495
+ " })\n",
496
+ "\n",
497
+ " try:\n",
498
+ "\n",
499
+ " raw_response, thinking, answer = generate_response(\n",
500
+ " conversation_history,\n",
501
+ " max_new_tokens=max_new_tokens,\n",
502
+ " temperature=temperature,\n",
503
+ " top_p=top_p\n",
504
+ " )\n",
505
+ "\n",
506
+ " # Store the complete response for subsequent turns.\n",
507
+ " conversation_history.append({\n",
508
+ " \"role\": \"assistant\",\n",
509
+ " \"content\": raw_response\n",
510
+ " })\n",
511
+ "\n",
512
+ " # Add two separate assistant messages to the chat.\n",
513
+ " chat_history.append({\n",
514
+ " \"role\": \"assistant\",\n",
515
+ " \"content\": \"### 💭 WHAT THE MODEL THINKS\\n\\n\" + thinking\n",
516
+ " })\n",
517
+ "\n",
518
+ " chat_history.append({\n",
519
+ " \"role\": \"assistant\",\n",
520
+ " \"content\": \"### 🗣️ WHAT THE MODEL SAYS\\n\\n\" + answer\n",
521
+ " })\n",
522
+ "\n",
523
+ " return (\n",
524
+ " chat_history,\n",
525
+ " conversation_history,\n",
526
+ " \"\",\n",
527
+ " None,\n",
528
+ " thinking,\n",
529
+ " answer\n",
530
+ " )\n",
531
+ "\n",
532
+ " except Exception as e:\n",
533
+ "\n",
534
+ " error_message = f\"Generation error:\\n\\n{str(e)}\"\n",
535
+ "\n",
536
+ " chat_history.append({\n",
537
+ " \"role\": \"assistant\",\n",
538
+ " \"content\": error_message\n",
539
+ " })\n",
540
+ "\n",
541
+ " return (\n",
542
+ " chat_history,\n",
543
+ " conversation_history,\n",
544
+ " message,\n",
545
+ " image,\n",
546
+ " \"\",\n",
547
+ " error_message\n",
548
+ " )\n",
549
+ "\n",
550
+ "\n",
551
+ "# ============================================================\n",
552
+ "# 12. CLEAR CONVERSATION\n",
553
+ "# ============================================================\n",
554
+ "\n",
555
+ "def clear_chat():\n",
556
+ "\n",
557
+ " return (\n",
558
+ " [],\n",
559
+ " [],\n",
560
+ " \"\",\n",
561
+ " None,\n",
562
+ " \"\",\n",
563
+ " \"\"\n",
564
+ " )\n",
565
+ "\n",
566
+ "\n",
567
+ "# ============================================================\n",
568
+ "# 13. GRADIO INTERFACE\n",
569
+ "# ============================================================\n",
570
+ "\n",
571
+ "CUSTOM_CSS = \"\"\"\n",
572
+ "body {\n",
573
+ " background: #181818 !important;\n",
574
+ "}\n",
575
+ "\n",
576
+ ".gradio-container {\n",
577
+ " max-width: 1500px !important;\n",
578
+ " margin: auto !important;\n",
579
+ "}\n",
580
+ "\n",
581
+ "#main-title {\n",
582
+ " text-align: center;\n",
583
+ " margin-bottom: 5px;\n",
584
+ "}\n",
585
+ "\n",
586
+ "#chat-window {\n",
587
+ " min-height: 650px !important;\n",
588
+ "}\n",
589
+ "\n",
590
+ "#chat-window .message {\n",
591
+ " font-size: 16px !important;\n",
592
+ " line-height: 1.65 !important;\n",
593
+ "}\n",
594
+ "\n",
595
+ "#message-input textarea {\n",
596
+ " font-size: 16px !important;\n",
597
+ " line-height: 1.6 !important;\n",
598
+ "}\n",
599
+ "\n",
600
+ "#thinking-panel textarea,\n",
601
+ "#answer-panel textarea {\n",
602
+ " font-size: 15px !important;\n",
603
+ " line-height: 1.7 !important;\n",
604
+ "}\n",
605
+ "\n",
606
+ "#send-button {\n",
607
+ " background: #a78bfa !important;\n",
608
+ " color: #181818 !important;\n",
609
+ " font-weight: bold !important;\n",
610
+ "}\n",
611
+ "\n",
612
+ "#clear-button {\n",
613
+ " background: #383344 !important;\n",
614
+ "}\n",
615
+ "\"\"\"\n",
616
+ "\n",
617
+ "\n",
618
+ "with gr.Blocks(\n",
619
+ " theme=gr.themes.Base(\n",
620
+ " primary_hue=\"violet\",\n",
621
+ " secondary_hue=\"orange\",\n",
622
+ " neutral_hue=\"slate\"\n",
623
+ " ),\n",
624
+ " css=CUSTOM_CSS,\n",
625
+ " title=\"Qwen3.5-4B Uncensored Chat\"\n",
626
+ ") as demo:\n",
627
+ "\n",
628
+ " gr.Markdown(\n",
629
+ " \"\"\"\n",
630
+ " # Qwen3.5-4B Uncensored Chat\n",
631
+ "\n",
632
+ " **DreamFast / HauhauCS — 4-bit NF4 — NVIDIA T4**\n",
633
+ "\n",
634
+ " Model responses are separated into their generated thinking\n",
635
+ " section and their final answer.\n",
636
+ " \"\"\",\n",
637
+ " elem_id=\"main-title\"\n",
638
+ " )\n",
639
+ "\n",
640
+ " # Actual model conversation and displayed chat are separate.\n",
641
+ " conversation_state = gr.State([])\n",
642
+ "\n",
643
+ " with gr.Row():\n",
644
+ "\n",
645
+ " with gr.Column(scale=7):\n",
646
+ "\n",
647
+ " chatbot = gr.Chatbot(\n",
648
+ " label=\"Conversation\",\n",
649
+ " height=650,\n",
650
+ " autoscroll=True,\n",
651
+ " elem_id=\"chat-window\"\n",
652
+ " )\n",
653
+ "\n",
654
+ " with gr.Row():\n",
655
+ "\n",
656
+ " message_input = gr.Textbox(\n",
657
+ " label=\"Your message\",\n",
658
+ " placeholder=\"Write your message here...\",\n",
659
+ " lines=4,\n",
660
+ " max_lines=10,\n",
661
+ " scale=5,\n",
662
+ " elem_id=\"message-input\"\n",
663
+ " )\n",
664
+ "\n",
665
+ " image_input = gr.Image(\n",
666
+ " label=\"Optional image\",\n",
667
+ " type=\"pil\",\n",
668
+ " height=150,\n",
669
+ " sources=[\"upload\", \"clipboard\"],\n",
670
+ " scale=2\n",
671
+ " )\n",
672
+ "\n",
673
+ " with gr.Row():\n",
674
+ "\n",
675
+ " send_button = gr.Button(\n",
676
+ " \"Send\",\n",
677
+ " variant=\"primary\",\n",
678
+ " elem_id=\"send-button\",\n",
679
+ " scale=3\n",
680
+ " )\n",
681
+ "\n",
682
+ " clear_button = gr.Button(\n",
683
+ " \"Clear conversation\",\n",
684
+ " variant=\"secondary\",\n",
685
+ " elem_id=\"clear-button\",\n",
686
+ " scale=1\n",
687
+ " )\n",
688
+ "\n",
689
+ " with gr.Column(scale=3):\n",
690
+ "\n",
691
+ " gr.Markdown(\"## Generation settings\")\n",
692
+ "\n",
693
+ " max_new_tokens = gr.Slider(\n",
694
+ " minimum=128,\n",
695
+ " maximum=4096,\n",
696
+ " value=1024,\n",
697
+ " step=128,\n",
698
+ " label=\"Maximum new tokens\"\n",
699
+ " )\n",
700
+ "\n",
701
+ " temperature = gr.Slider(\n",
702
+ " minimum=0.0,\n",
703
+ " maximum=1.5,\n",
704
+ " value=0.7,\n",
705
+ " step=0.05,\n",
706
+ " label=\"Temperature\"\n",
707
+ " )\n",
708
+ "\n",
709
+ " top_p = gr.Slider(\n",
710
+ " minimum=0.1,\n",
711
+ " maximum=1.0,\n",
712
+ " value=0.9,\n",
713
+ " step=0.05,\n",
714
+ " label=\"Top-p\"\n",
715
+ " )\n",
716
+ "\n",
717
+ " gr.Markdown(\n",
718
+ " \"\"\"\n",
719
+ " **Tip:** Set temperature to `0` for deterministic\n",
720
+ " generation. Increase maximum tokens for longer responses.\n",
721
+ " \"\"\"\n",
722
+ " )\n",
723
+ "\n",
724
+ " gr.Markdown(\"---\")\n",
725
+ "\n",
726
+ " gr.Markdown(\"## Latest model response\")\n",
727
+ "\n",
728
+ " with gr.Row():\n",
729
+ "\n",
730
+ " with gr.Column():\n",
731
+ "\n",
732
+ " thinking_output = gr.Textbox(\n",
733
+ " label=\"💭 What the model thinks\",\n",
734
+ " lines=12,\n",
735
+ " max_lines=25,\n",
736
+ " interactive=False,\n",
737
+ " placeholder=\"Generated thinking will appear here...\",\n",
738
+ " elem_id=\"thinking-panel\"\n",
739
+ " )\n",
740
+ "\n",
741
+ " with gr.Column():\n",
742
+ "\n",
743
+ " answer_output = gr.Textbox(\n",
744
+ " label=\"🗣️ What the model says\",\n",
745
+ " lines=12,\n",
746
+ " max_lines=25,\n",
747
+ " interactive=False,\n",
748
+ " placeholder=\"The final answer will appear here...\",\n",
749
+ " elem_id=\"answer-panel\"\n",
750
+ " )\n",
751
+ "\n",
752
+ " # ========================================================\n",
753
+ " # EVENTS\n",
754
+ " # ========================================================\n",
755
+ "\n",
756
+ " inputs = [\n",
757
+ " message_input,\n",
758
+ " image_input,\n",
759
+ " chatbot,\n",
760
+ " conversation_state,\n",
761
+ " max_new_tokens,\n",
762
+ " temperature,\n",
763
+ " top_p\n",
764
+ " ]\n",
765
+ "\n",
766
+ " outputs = [\n",
767
+ " chatbot,\n",
768
+ " conversation_state,\n",
769
+ " message_input,\n",
770
+ " image_input,\n",
771
+ " thinking_output,\n",
772
+ " answer_output\n",
773
+ " ]\n",
774
+ "\n",
775
+ " send_button.click(\n",
776
+ " fn=chat,\n",
777
+ " inputs=inputs,\n",
778
+ " outputs=outputs\n",
779
+ " )\n",
780
+ "\n",
781
+ " message_input.submit(\n",
782
+ " fn=chat,\n",
783
+ " inputs=inputs,\n",
784
+ " outputs=outputs\n",
785
+ " )\n",
786
+ "\n",
787
+ " clear_button.click(\n",
788
+ " fn=clear_chat,\n",
789
+ " inputs=[],\n",
790
+ " outputs=outputs\n",
791
+ " )\n",
792
+ "\n",
793
+ "\n",
794
+ "# ============================================================\n",
795
+ "# 14. LAUNCH\n",
796
+ "# ============================================================\n",
797
+ "\n",
798
+ "print(\"\\nStarting Gradio interface...\")\n",
799
+ "\n",
800
+ "demo.queue().launch(\n",
801
+ " share=True,\n",
802
+ " debug=True,\n",
803
+ " show_error=True\n",
804
+ ")\n"
805
+ ]
806
+ }
807
+ ]
808
+ }