Datasets:
Tags:
Not-For-All-Audiences
Delete HauauCS_Abliterated_Qwen_3_5_4B_LLM_model.ipynb
Browse files
HauauCS_Abliterated_Qwen_3_5_4B_LLM_model.ipynb
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/HauauCS_Abliterated_Qwen_3_5_4B_LLM_model.ipynb","timestamp":1794394717019}],"gpuType":"T4"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"accelerator":"GPU"},"cells":[{"cell_type":"markdown","source":["# HauauCS Abliterated Qwen 3.5 -4B LLM model (image and/or text input)"],"metadata":{"id":"ewVsp7wRAH2j"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"lC55DC9m_4Zz"},"outputs":[],"source":["\n","# ============================================================\n","# QWEN3.5-4B UNCENSORED - GOOGLE COLAB T4\n","#\n","# Model:\n","# DreamFast/Qwen3.5-4B-Uncensored-HauhauCS-Aggressive-Safetensor-Benchmark\n","#\n","# GPU: NVIDIA T4 16GB\n","# Quantization: BitsAndBytes NF4 4-bit\n","# Compute: FP16\n","# Attention: SDPA\n","#\n","# Features:\n","# - Text and image conversations\n","# - Conversation history\n","# - Separate THINKS and SAYS sections\n","# - Larger Gradio chat interface\n","# - Expandable latest-response panels\n","# - Adjustable generation settings\n","# - HF_TOKEN from Colab Secrets\n","# ============================================================\n","\n","\n","# ============================================================\n","# 1. INSTALL DEPENDENCIES\n","# ============================================================\n","\n","import sys\n","import subprocess\n","\n","# Explicitly upgrade Pillow to ensure correct typing dependencies are resolved.\n","subprocess.run(\n"," [\n"," sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-U\",\n"," \"--force-reinstall\",\n"," \"pillow\",\n"," \"bitsandbytes\",\n"," \"accelerate\",\n"," \"transformers\",\n"," \"gradio>=6.0\",\n"," \"huggingface_hub\"\n"," ],\n"," check=True\n",")\n","\n","import transformers\n","# ============================================================\n","# 2. IMPORTS\n","# ============================================================\n","\n","import os\n","import re\n","import gc\n","import torch\n","import gradio as gr\n","\n","from PIL import Image\n","from pathlib import Path\n","\n","from google.colab import userdata\n","\n","from huggingface_hub import hf_hub_download\n","\n","from transformers import (\n"," AutoProcessor,\n"," AutoTokenizer,\n"," AutoModelForMultimodalLM,\n"," BitsAndBytesConfig\n",")\n","\n","\n","# ============================================================\n","# 3. CONFIGURATION\n","# ============================================================\n","\n","MODEL_ID = (\n"," \"DreamFast/\"\n"," \"Qwen3.5-4B-Uncensored-HauhauCS-Aggressive-Safetensor-Benchmark\"\n",")\n","\n","BASE_MODEL_ID = \"Qwen/Qwen3.5-4B\"\n","\n","HF_TOKEN = userdata.get(\"HF_TOKEN\")\n","\n","if not HF_TOKEN:\n"," raise ValueError(\n"," \"HF_TOKEN not found in Colab Secrets. \"\n"," \"Please add your Hugging Face token.\"\n"," )\n","\n","if not torch.cuda.is_available():\n"," raise RuntimeError(\"No CUDA GPU detected.\")\n","\n","print(\"GPU:\", torch.cuda.get_device_name(0))\n","print(\"VRAM:\", round(\n"," torch.cuda.get_device_properties(0).total_memory / 1024**3, 2\n","), \"GB\")\n","\n","torch.backends.cuda.matmul.allow_tf32 = True\n","\n","\n","# ============================================================\n","# 4. LOAD CHAT TEMPLATE\n","# ============================================================\n","\n","print(\"\\nLoading Qwen3.5 tokenizer...\")\n","\n","tokenizer = AutoTokenizer.from_pretrained(\n"," BASE_MODEL_ID,\n"," token=HF_TOKEN,\n"," trust_remote_code=True\n",")\n","\n","if not tokenizer.chat_template:\n","\n"," print(\"Downloading original Qwen3.5 chat template...\")\n","\n"," template_path = hf_hub_download(\n"," repo_id=BASE_MODEL_ID,\n"," filename=\"chat_template.jinja\",\n"," token=HF_TOKEN\n"," )\n","\n"," with open(template_path, \"r\", encoding=\"utf-8\") as f:\n"," chat_template = f.read()\n","\n"," tokenizer.chat_template = chat_template\n","\n","else:\n"," chat_template = tokenizer.chat_template\n","\n","print(\"Chat template loaded.\")\n","\n","\n","# ============================================================\n","# 5. LOAD PROCESSOR\n","# ============================================================\n","\n","print(\"\\nLoading multimodal processor...\")\n","\n","processor = AutoProcessor.from_pretrained(\n"," MODEL_ID,\n"," token=HF_TOKEN,\n"," trust_remote_code=True\n",")\n","\n","# Use the compatible original Qwen3.5 tokenizer/template.\n","processor.tokenizer = tokenizer\n","processor.chat_template = chat_template\n","\n","print(\"Processor loaded.\")\n","\n","\n","# ============================================================\n","# 6. 4-BIT QUANTIZATION\n","# ============================================================\n","\n","quantization_config = BitsAndBytesConfig(\n"," load_in_4bit=True,\n"," bnb_4bit_quant_type=\"nf4\",\n"," bnb_4bit_compute_dtype=torch.float16,\n"," bnb_4bit_use_double_quant=True\n",")\n","\n","\n","# ============================================================\n","# 7. LOAD MODEL\n","# ============================================================\n","\n","print(\"\\nLoading model in 4-bit...\")\n","\n","model = AutoModelForMultimodalLM.from_pretrained(\n"," MODEL_ID,\n"," token=HF_TOKEN,\n"," quantization_config=quantization_config,\n"," dtype=torch.float16,\n"," device_map=\"auto\",\n"," low_cpu_mem_usage=True,\n"," attn_implementation=\"sdpa\",\n"," trust_remote_code=True\n",")\n","\n","model.eval()\n","\n","print(\"\\nModel loaded successfully.\")\n","\n","print(\"Model device:\", model.get_input_embeddings().weight.device)\n","\n","# ============================================================\n","# 8. PREPARE MULTIMODAL INPUTS\n","# ============================================================\n","\n","def prepare_multimodal_inputs(messages):\n","\n"," # Apply the chat template using the tokenizer directly.\n"," prompt = tokenizer.apply_chat_template(\n"," messages,\n"," tokenize=False,\n"," add_generation_prompt=True\n"," )\n","\n"," # Collect images in conversation order.\n"," images = []\n","\n"," for msg in messages:\n","\n"," content = msg.get(\"content\", [])\n","\n"," if isinstance(content, str):\n"," continue\n","\n"," if not isinstance(content, list):\n"," continue\n","\n"," for item in content:\n","\n"," if (\n"," isinstance(item, dict)\n"," and item.get(\"type\") == \"image\"\n"," ):\n","\n"," image = item.get(\"image\")\n","\n"," if image is not None:\n"," images.append(image)\n","\n"," # Process text and images.\n"," if images:\n","\n"," formatted_inputs = processor(\n"," text=prompt,\n"," images=images,\n"," return_tensors=\"pt\"\n"," )\n","\n"," else:\n","\n"," formatted_inputs = processor(\n"," text=prompt,\n"," return_tensors=\"pt\"\n"," )\n","\n"," return formatted_inputs\n","\n","\n","# ============================================================\n","# 9. SPLIT THINKING AND FINAL ANSWER\n","# ============================================================\n","\n","def split_thinking_and_answer(raw_text):\n","\n"," \"\"\"\n"," Separates model-generated <think>...</think> content\n"," from the final answer.\n","\n"," If the model does not return a think block, its complete\n"," response is treated as the final answer.\n"," \"\"\"\n","\n"," raw_text = raw_text.strip()\n","\n"," # Remove common trailing generation tokens.\n"," raw_text = re.sub(\n"," r\"<\\|im_end\\|>|<\\|endoftext\\|>|</s>\",\n"," \"\",\n"," raw_text\n"," ).strip()\n","\n"," # Find a complete think block.\n"," match = re.search(\n"," r\"<think>(.*?)</think>\",\n"," raw_text,\n"," flags=re.DOTALL | re.IGNORECASE\n"," )\n","\n"," if match:\n","\n"," thinking = match.group(1).strip()\n","\n"," # Everything outside the think block is the answer.\n"," answer = (\n"," raw_text[:match.start()]\n"," + raw_text[match.end():]\n"," ).strip()\n","\n"," else:\n","\n"," # Handle an unclosed think block.\n"," open_match = re.search(\n"," r\"<think>\",\n"," raw_text,\n"," flags=re.IGNORECASE\n"," )\n","\n"," if open_match:\n","\n"," thinking = raw_text[open_match.end():].strip()\n"," answer = \"\"\n","\n"," else:\n","\n"," thinking = \"The model did not return a separate <think> block.\"\n"," answer = raw_text\n","\n"," # Remove any remaining template artifacts.\n"," answer = re.sub(\n"," r\"<\\|im_start\\|>|<\\|im_sep\\|>|<\\|im_end\\|>\",\n"," \"\",\n"," answer\n"," ).strip()\n","\n"," thinking = re.sub(\n"," r\"<\\|im_start\\|>|<\\|im_sep\\|>|<\\|im_end\\|>\",\n"," \"\",\n"," thinking\n"," ).strip()\n","\n"," if not answer:\n"," answer = \"(The model did not produce a separate final answer.)\"\n","\n"," if not thinking:\n"," thinking = \"(No thinking text was returned.)\"\n","\n"," return thinking, answer\n","\n","\n","# ============================================================\n","# 10. GENERATION FUNCTION\n","# ============================================================\n","\n","def generate_response(\n"," messages,\n"," max_new_tokens=1024,\n"," temperature=0.7,\n"," top_p=0.9\n","):\n","\n"," inputs = prepare_multimodal_inputs(messages)\n","\n"," # Move inputs to the model's embedding device.\n"," input_device = model.get_input_embeddings().weight.device\n","\n"," inputs = inputs.to(input_device)\n","\n"," input_length = inputs[\"input_ids\"].shape[-1]\n","\n"," do_sample = float(temperature) > 0\n","\n"," generation_kwargs = {\n"," \"max_new_tokens\": int(max_new_tokens),\n"," \"do_sample\": do_sample,\n"," \"repetition_penalty\": 1.05,\n"," \"pad_token_id\": tokenizer.pad_token_id\n"," if tokenizer.pad_token_id is not None\n"," else tokenizer.eos_token_id,\n"," \"eos_token_id\": tokenizer.eos_token_id,\n"," \"use_cache\": True\n"," }\n","\n"," if do_sample:\n","\n"," generation_kwargs.update({\n"," \"temperature\": float(temperature),\n"," \"top_p\": float(top_p)\n"," })\n","\n"," with torch.inference_mode():\n","\n"," output_ids = model.generate(\n"," **inputs,\n"," **generation_kwargs\n"," )\n","\n"," # Decode only newly generated tokens.\n"," generated_ids = output_ids[0][input_length:]\n","\n"," raw_response = tokenizer.decode(\n"," generated_ids,\n"," skip_special_tokens=False,\n"," clean_up_tokenization_spaces=False\n"," )\n","\n"," thinking, answer = split_thinking_and_answer(raw_response)\n","\n"," # Keep the original model response in the conversation history.\n"," return raw_response.strip(), thinking, answer\n","\n","\n","# ============================================================\n","# 11. GRADIO CHAT FUNCTION\n","# ============================================================\n","\n","def chat(\n"," message,\n"," image,\n"," chat_history,\n"," conversation_history,\n"," max_new_tokens,\n"," temperature,\n"," top_p\n","):\n","\n"," if chat_history is None:\n"," chat_history = []\n","\n"," if conversation_history is None:\n"," conversation_history = []\n","\n"," message = (message or \"\").strip()\n","\n"," if not message and image is None:\n","\n"," return (\n"," chat_history,\n"," conversation_history,\n"," \"\",\n"," None,\n"," \"\",\n"," \"Please enter a message or upload an image.\"\n"," )\n","\n"," # Build user content.\n"," user_content = []\n","\n"," if message:\n","\n"," user_content.append({\n"," \"type\": \"text\",\n"," \"text\": message\n"," })\n","\n"," if image is not None:\n","\n"," # Convert to RGB PIL image.\n"," if isinstance(image, Image.Image):\n"," image = image.convert(\"RGB\")\n","\n"," user_content.append({\n"," \"type\": \"image\",\n"," \"image\": image\n"," })\n","\n"," # Add user turn to actual model conversation.\n"," conversation_history = list(conversation_history)\n","\n"," conversation_history.append({\n"," \"role\": \"user\",\n"," \"content\": user_content\n"," })\n","\n"," # Display user message in the chat window.\n"," display_message = message if message else \"Please describe this image.\"\n","\n"," if image is not None:\n"," display_message += \"\\n\\n📷 *Image attached*\"\n","\n"," chat_history = list(chat_history)\n","\n"," chat_history.append({\n"," \"role\": \"user\",\n"," \"content\": display_message\n"," })\n","\n"," try:\n","\n"," raw_response, thinking, answer = generate_response(\n"," conversation_history,\n"," max_new_tokens=max_new_tokens,\n"," temperature=temperature,\n"," top_p=top_p\n"," )\n","\n"," # Store the complete response for subsequent turns.\n"," conversation_history.append({\n"," \"role\": \"assistant\",\n"," \"content\": raw_response\n"," })\n","\n"," # Add two separate assistant messages to the chat.\n"," chat_history.append({\n"," \"role\": \"assistant\",\n"," \"content\": \"### 💭 WHAT THE MODEL THINKS\\n\\n\" + thinking\n"," })\n","\n"," chat_history.append({\n"," \"role\": \"assistant\",\n"," \"content\": \"### 🗣️ WHAT THE MODEL SAYS\\n\\n\" + answer\n"," })\n","\n"," return (\n"," chat_history,\n"," conversation_history,\n"," \"\",\n"," None,\n"," thinking,\n"," answer\n"," )\n","\n"," except Exception as e:\n","\n"," error_message = f\"Generation error:\\n\\n{str(e)}\"\n","\n"," chat_history.append({\n"," \"role\": \"assistant\",\n"," \"content\": error_message\n"," })\n","\n"," return (\n"," chat_history,\n"," conversation_history,\n"," message,\n"," image,\n"," \"\",\n"," error_message\n"," )\n","\n","\n","# ============================================================\n","# 12. CLEAR CONVERSATION\n","# ============================================================\n","\n","def clear_chat():\n","\n"," return (\n"," [],\n"," [],\n"," \"\",\n"," None,\n"," \"\",\n"," \"\"\n"," )\n","\n","\n","# ============================================================\n","# 13. GRADIO INTERFACE\n","# ============================================================\n","\n","CUSTOM_CSS = \"\"\"\n","body {\n"," background: #181818 !important;\n","}\n","\n",".gradio-container {\n"," max-width: 1500px !important;\n"," margin: auto !important;\n","}\n","\n","#main-title {\n"," text-align: center;\n"," margin-bottom: 5px;\n","}\n","\n","#chat-window {\n"," min-height: 650px !important;\n","}\n","\n","#chat-window .message {\n"," font-size: 16px !important;\n"," line-height: 1.65 !important;\n","}\n","\n","#message-input textarea {\n"," font-size: 16px !important;\n"," line-height: 1.6 !important;\n","}\n","\n","#thinking-panel textarea,\n","#answer-panel textarea {\n"," font-size: 15px !important;\n"," line-height: 1.7 !important;\n","}\n","\n","#send-button {\n"," background: #a78bfa !important;\n"," color: #181818 !important;\n"," font-weight: bold !important;\n","}\n","\n","#clear-button {\n"," background: #383344 !important;\n","}\n","\"\"\"\n","\n","\n","with gr.Blocks(\n"," theme=gr.themes.Base(\n"," primary_hue=\"violet\",\n"," secondary_hue=\"orange\",\n"," neutral_hue=\"slate\"\n"," ),\n"," css=CUSTOM_CSS,\n"," title=\"Qwen3.5-4B Uncensored Chat\"\n",") as demo:\n","\n"," gr.Markdown(\n"," \"\"\"\n"," # Qwen3.5-4B Uncensored Chat\n","\n"," **DreamFast / HauhauCS — 4-bit NF4 — NVIDIA T4**\n","\n"," Model responses are separated into their generated thinking\n"," section and their final answer.\n"," \"\"\",\n"," elem_id=\"main-title\"\n"," )\n","\n"," # Actual model conversation and displayed chat are separate.\n"," conversation_state = gr.State([])\n","\n"," with gr.Row():\n","\n"," with gr.Column(scale=7):\n","\n"," chatbot = gr.Chatbot(\n"," label=\"Conversation\",\n"," height=650,\n"," autoscroll=True,\n"," elem_id=\"chat-window\"\n"," )\n","\n"," with gr.Row():\n","\n"," message_input = gr.Textbox(\n"," label=\"Your message\",\n"," placeholder=\"Write your message here...\",\n"," lines=4,\n"," max_lines=10,\n"," scale=5,\n"," elem_id=\"message-input\"\n"," )\n","\n"," image_input = gr.Image(\n"," label=\"Optional image\",\n"," type=\"pil\",\n"," height=150,\n"," sources=[\"upload\", \"clipboard\"],\n"," scale=2\n"," )\n","\n"," with gr.Row():\n","\n"," send_button = gr.Button(\n"," \"Send\",\n"," variant=\"primary\",\n"," elem_id=\"send-button\",\n"," scale=3\n"," )\n","\n"," clear_button = gr.Button(\n"," \"Clear conversation\",\n"," variant=\"secondary\",\n"," elem_id=\"clear-button\",\n"," scale=1\n"," )\n","\n"," with gr.Column(scale=3):\n","\n"," gr.Markdown(\"## Generation settings\")\n","\n"," max_new_tokens = gr.Slider(\n"," minimum=128,\n"," maximum=4096,\n"," value=1024,\n"," step=128,\n"," label=\"Maximum new tokens\"\n"," )\n","\n"," temperature = gr.Slider(\n"," minimum=0.0,\n"," maximum=1.5,\n"," value=0.7,\n"," step=0.05,\n"," label=\"Temperature\"\n"," )\n","\n"," top_p = gr.Slider(\n"," minimum=0.1,\n"," maximum=1.0,\n"," value=0.9,\n"," step=0.05,\n"," label=\"Top-p\"\n"," )\n","\n"," gr.Markdown(\n"," \"\"\"\n"," **Tip:** Set temperature to `0` for deterministic\n"," generation. Increase maximum tokens for longer responses.\n"," \"\"\"\n"," )\n","\n"," gr.Markdown(\"---\")\n","\n"," gr.Markdown(\"## Latest model response\")\n","\n"," with gr.Row():\n","\n"," with gr.Column():\n","\n"," thinking_output = gr.Textbox(\n"," label=\"💭 What the model thinks\",\n"," lines=12,\n"," max_lines=25,\n"," interactive=False,\n"," placeholder=\"Generated thinking will appear here...\",\n"," elem_id=\"thinking-panel\"\n"," )\n","\n"," with gr.Column():\n","\n"," answer_output = gr.Textbox(\n"," label=\"🗣️ What the model says\",\n"," lines=12,\n"," max_lines=25,\n"," interactive=False,\n"," placeholder=\"The final answer will appear here...\",\n"," elem_id=\"answer-panel\"\n"," )\n","\n"," # ========================================================\n"," # EVENTS\n"," # ========================================================\n","\n"," inputs = [\n"," message_input,\n"," image_input,\n"," chatbot,\n"," conversation_state,\n"," max_new_tokens,\n"," temperature,\n"," top_p\n"," ]\n","\n"," outputs = [\n"," chatbot,\n"," conversation_state,\n"," message_input,\n"," image_input,\n"," thinking_output,\n"," answer_output\n"," ]\n","\n"," send_button.click(\n"," fn=chat,\n"," inputs=inputs,\n"," outputs=outputs\n"," )\n","\n"," message_input.submit(\n"," fn=chat,\n"," inputs=inputs,\n"," outputs=outputs\n"," )\n","\n"," clear_button.click(\n"," fn=clear_chat,\n"," inputs=[],\n"," outputs=outputs\n"," )\n","\n","\n","# ============================================================\n","# 14. LAUNCH\n","# ============================================================\n","\n","print(\"\\nStarting Gradio interface...\")\n","\n","demo.queue().launch(\n"," share=True,\n"," debug=True,\n"," show_error=True\n",")\n"]}]}
|
|
|
|
|
|