codeShare commited on
Commit
681509b
Β·
verified Β·
1 Parent(s): 157995e

Upload HauhauCS_Abliterated_Qwen_3_5_4B_LLM_model.ipynb

Browse files
HauhauCS_Abliterated_Qwen_3_5_4B_LLM_model.ipynb ADDED
@@ -0,0 +1 @@
 
 
1
+ {"cells":[{"cell_type":"markdown","metadata":{"id":"gZTGUb5FShVL"},"source":["# Qwen3.5-4B HauhauCS β€” Google Colab\n","\n","This notebook loads the DreamFast Qwen3.5-4B multimodal model in 4-bit NF4 and provides a Gradio chat interface for text and image conversations. Because the fine-tuned repository does not include its own chat template, the notebook downloads `chat_template.jinja` directly from the official `Qwen/Qwen3.5-4B` repository and assigns it to both the tokenizer and processor.\n","\n","**Important setup:** Run the dependency-install cell once, then restart the Colab runtime before running the remaining cells. In Colab, enable a GPU under **Runtime β†’ Change runtime type β†’ GPU** and add a Hugging Face token named `HF_TOKEN` under **Secrets**.\n"],"id":"gZTGUb5FShVL"},{"cell_type":"code","execution_count":null,"metadata":{"id":"nAUyO568ShVN"},"outputs":[],"source":["# CELL 1 β€” Install compatible dependencies\n","# IMPORTANT: Run this cell once. It will automatically restart the runtime if package updates are detected.\n","# Do not force-reinstall torch/torchvision: Colab supplies a matched CUDA build.\n","\n","import sys\n","import os\n","import time\n","import pkg_resources\n","\n","# Record the currently installed packages and versions\n","pre_installed = {pkg.key: pkg.version for pkg in pkg_resources.working_set}\n","\n","# Run the installation command\n","get_ipython().run_line_magic('pip', 'install -q --upgrade --no-cache-dir \"Pillow>=10.4.0\" \"transformers>=5.0.0\" \"accelerate>=1.2.0\" \"bitsandbytes>=0.45.0\" \"gradio>=5.0.0\" \"huggingface_hub>=0.27.0\"')\n","\n","# Reload working set to detect newly installed or modified packages\n","import importlib\n","importlib.reload(pkg_resources)\n","post_installed = {pkg.key: pkg.version for pkg in pkg_resources.working_set}\n","\n","# Check if anything changed\n","changes_detected = False\n","for pkg, version in post_installed.items():\n"," if pkg not in pre_installed or pre_installed[pkg] != version:\n"," changes_detected = True\n"," break\n","\n","if changes_detected:\n"," print(\"\\n[INFO] New dependencies installed or updated.\")\n"," print(\"Preparing to restart the Google Colab session to apply changes...\")\n"," print(\"NOTE: Google Colab might show a pop-up saying the runtime 'Crashed for an unknown reason'.\")\n"," print(\"This is completely normal when programmatically restarting. The session is simply refreshing.\")\n","\n"," for i in range(5, 0, -1):\n"," print(f\"Restarting in {i} seconds...\")\n"," time.sleep(1)\n","\n"," print(\"Restarting session now...\")\n"," # Programmatically restart the Colab runtime session\n"," os.kill(os.getpid(), 9)\n","else:\n"," print(\"\\nNo package updates detected. Runtime restart is not required.\")"],"id":"nAUyO568ShVN"},{"cell_type":"code","execution_count":null,"metadata":{"id":"c9VvMbzuShVO"},"outputs":[],"source":["# ============================================================\n","# QWEN3.5-4B HAUHAUCS β€” GOOGLE COLAB\n","# Text + image chat, 4-bit NF4, Gradio interface\n","# Recommended GPU: T4 (16 GB) or better\n","# ============================================================\n","\n","# CELL 2 β€” Imports and environment checks\n","import os\n","import re\n","import gc\n","import torch\n","import gradio as gr\n","from PIL import Image\n","from google.colab import userdata\n","from huggingface_hub import hf_hub_download\n","from transformers import (\n"," AutoProcessor,\n"," AutoTokenizer,\n"," AutoModelForMultimodalLM,\n"," BitsAndBytesConfig,\n",")\n","\n","MODEL_ID = \"DreamFast/Qwen3.5-4B-Uncensored-HauhauCS-Aggressive-Safetensor-Benchmark\"\n","BASE_MODEL_ID = \"Qwen/Qwen3.5-4B\"\n","\n","# Read the Hugging Face token from Colab Secrets.\n","# In Colab: left sidebar > Secrets (key icon) > add HF_TOKEN.\n","HF_TOKEN = userdata.get(\"HF_TOKEN\")\n","if not HF_TOKEN:\n"," raise ValueError(\n"," \"HF_TOKEN was not found in Colab Secrets. Add a secret named HF_TOKEN \"\n"," \"containing your Hugging Face access token, then rerun this cell.\"\n"," )\n","\n","if not torch.cuda.is_available():\n"," raise RuntimeError(\n"," \"No CUDA GPU is available. In Colab select Runtime > Change runtime type > GPU.\"\n"," )\n","\n","print(\"PyTorch:\", torch.__version__)\n","print(\"CUDA:\", torch.version.cuda)\n","print(\"Pillow:\", Image.__version__)\n","print(\"GPU:\", torch.cuda.get_device_name(0))\n","print(\"VRAM:\", round(torch.cuda.get_device_properties(0).total_memory / 1024**3, 2), \"GB\")\n","\n","# Helpful diagnostic: detect mismatched/broken Pillow installations early.\n","try:\n"," from PIL import ImageDraw\n"," from torchvision.transforms import InterpolationMode\n"," print(\"Pillow and torchvision imports: OK\")\n","except Exception as exc:\n"," raise RuntimeError(\n"," \"A vision dependency failed to import. Run CELL 1, restart the Colab \"\n"," \"runtime, and then run this notebook from CELL 2. Original error: \"\n"," + repr(exc)\n"," ) from exc\n","\n","torch.backends.cuda.matmul.allow_tf32 = True\n","\n","\n","# ============================================================\n","# CELL 3 β€” Load processor, tokenizer and 4-bit model\n","# ============================================================\n","\n","print(\"\\\\nLoading tokenizer...\")\n","tokenizer = AutoTokenizer.from_pretrained(\n"," BASE_MODEL_ID,\n"," token=HF_TOKEN,\n"," trust_remote_code=True,\n",")\n","\n","# The fine-tuned DreamFast repository may not contain a chat template.\n","# Always fetch the official Qwen3.5-4B template directly from the base repo.\n","print(\"Downloading the official Qwen3.5-4B chat template...\")\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 template_file:\n"," qwen_chat_template = template_file.read()\n","\n","if not qwen_chat_template.strip():\n"," raise RuntimeError(\"The chat_template.jinja downloaded from the base repo is empty.\")\n","\n","# Explicitly override any missing or inherited template on the tokenizer.\n","tokenizer.chat_template = qwen_chat_template\n","print(\"Official Qwen3.5-4B chat template loaded and assigned to tokenizer.\")\n","\n","print(\"Loading multimodal processor...\")\n","processor = AutoProcessor.from_pretrained(\n"," MODEL_ID,\n"," token=HF_TOKEN,\n"," trust_remote_code=True,\n",")\n","\n","# Ensure both tokenizer and processor use the exact same official template.\n","processor.tokenizer = tokenizer\n","processor.chat_template = qwen_chat_template\n","print(\"Official Qwen3.5-4B chat template assigned to processor.\")\n","\n","print(\"Configuring 4-bit NF4 quantization...\")\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","print(\"Loading model. This may take several minutes...\")\n","model = AutoModelForMultimodalLM.from_pretrained(\n"," MODEL_ID,\n"," token=HF_TOKEN,\n"," quantization_config=quantization_config,\n"," torch_dtype=torch.float16,\n"," device_map=\"auto\",\n"," low_cpu_mem_usage=True,\n"," attn_implementation=\"sdpa\",\n"," trust_remote_code=True,\n",")\n","model.eval()\n","\n","INPUT_DEVICE = model.get_input_embeddings().weight.device\n","print(\"Model loaded.\")\n","print(\"Input device:\", INPUT_DEVICE)\n","\n","\n","# ============================================================\n","# CELL 4 β€” Input preparation and response parsing\n","# ============================================================\n","\n","def prepare_inputs(messages):\n"," \"\"\"\n"," Apply the official Qwen3.5-4B chat template downloaded from the base repo,\n"," then let the multimodal processor tokenize text and preprocess images.\n"," \"\"\"\n"," # Keep the template assignment explicit in case another component changed it.\n"," processor.chat_template = qwen_chat_template\n"," processor.tokenizer.chat_template = qwen_chat_template\n","\n"," batch = processor.apply_chat_template(\n"," messages,\n"," chat_template=qwen_chat_template,\n"," tokenize=True,\n"," add_generation_prompt=True,\n"," return_dict=True,\n"," return_tensors=\"pt\",\n"," )\n"," return batch\n","\n","\n","def split_thinking_and_answer(raw_text):\n"," raw_text = re.sub(\n"," r\"<\\\\|im_end\\\\|>|<\\\\|endoftext\\\\|>|</s>\",\n"," \"\",\n"," raw_text,\n"," ).strip()\n","\n"," match = re.search(\n"," r\"<think>(.*?)</think>\",\n"," raw_text,\n"," flags=re.DOTALL | re.IGNORECASE,\n"," )\n","\n"," if match:\n"," thinking = match.group(1).strip()\n"," answer = (raw_text[:match.start()] + raw_text[match.end():]).strip()\n"," else:\n"," # Do not label an entire response as hidden reasoning if no think\n"," # section was emitted.\n"," thinking = \"No separate <think> section was returned by the model.\"\n"," answer = raw_text\n","\n"," answer = re.sub(r\"<\\\\|im_start\\\\|>|<\\\\|im_sep\\\\|>|<\\\\|im_end\\\\|>\", \"\", answer).strip()\n"," thinking = re.sub(r\"<\\\\|im_start\\\\|>|<\\\\|im_sep\\\\|>|<\\\\|im_end\\\\|>\", \"\", thinking).strip()\n","\n"," if not answer:\n"," answer = \"(No separate final answer was returned.)\"\n"," if not thinking:\n"," thinking = \"(Empty thinking section.)\"\n","\n"," return thinking, answer\n","\n","\n","# ============================================================\n","# CELL 5 β€” Generation\n","# ============================================================\n","\n","def generate_response(\n"," messages,\n"," max_new_tokens=1024,\n"," temperature=0.7,\n"," top_p=0.9,\n","):\n"," inputs = prepare_inputs(messages)\n","\n"," # The model is loaded with device_map=\"auto\". Move processor tensors to\n"," # the input embedding device; this is normally the GPU on a T4.\n"," inputs = {\n"," key: value.to(INPUT_DEVICE) if hasattr(value, \"to\") else value\n"," for key, value in inputs.items()\n"," }\n","\n"," input_ids = inputs[\"input_ids\"]\n"," input_length = input_ids.shape[-1]\n","\n"," do_sample = float(temperature) > 0\n"," generation_kwargs = {\n"," \"max_new_tokens\": int(max_new_tokens),\n"," \"do_sample\": do_sample,\n"," \"repetition_penalty\": 1.05,\n"," \"use_cache\": True,\n"," }\n","\n"," if tokenizer.eos_token_id is not None:\n"," generation_kwargs[\"eos_token_id\"] = tokenizer.eos_token_id\n"," if tokenizer.pad_token_id is not None:\n"," generation_kwargs[\"pad_token_id\"] = tokenizer.pad_token_id\n"," elif tokenizer.eos_token_id is not None:\n"," generation_kwargs[\"pad_token_id\"] = tokenizer.eos_token_id\n","\n"," if do_sample:\n"," generation_kwargs[\"temperature\"] = max(float(temperature), 1e-5)\n"," generation_kwargs[\"top_p\"] = float(top_p)\n","\n"," with torch.inference_mode():\n"," output_ids = model.generate(**inputs, **generation_kwargs)\n","\n"," new_tokens = output_ids[0, input_length:]\n"," raw_response = tokenizer.decode(\n"," new_tokens,\n"," skip_special_tokens=False,\n"," clean_up_tokenization_spaces=False,\n"," ).strip()\n","\n"," thinking, answer = split_thinking_and_answer(raw_response)\n"," return raw_response, thinking, answer\n","\n","\n","# ============================================================\n","# CELL 6 β€” Gradio chat callbacks\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"," chat_history = list(chat_history or [])\n"," conversation_history = list(conversation_history or [])\n"," message = (message or \"\").strip()\n","\n"," if not message and image is None:\n"," return (\n"," chat_history,\n"," conversation_history,\n"," message,\n"," image,\n"," \"\",\n"," \"Please enter a message or upload an image.\",\n"," )\n","\n"," user_content = []\n"," if message:\n"," user_content.append({\"type\": \"text\", \"text\": message})\n","\n"," if image is not None:\n"," if not isinstance(image, Image.Image):\n"," image = Image.fromarray(image)\n"," user_content.append({\"type\": \"image\", \"image\": image.convert(\"RGB\")})\n","\n"," conversation_history.append({\"role\": \"user\", \"content\": user_content})\n","\n"," display_text = message or \"Please describe this image.\"\n"," if image is not None:\n"," display_text += \"\\\\n\\\\nπŸ“· Image attached\"\n"," chat_history.append({\"role\": \"user\", \"content\": display_text})\n","\n"," try:\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"," conversation_history.append({\n"," \"role\": \"assistant\",\n"," \"content\": raw_response,\n"," })\n","\n"," chat_history.append({\n"," \"role\": \"assistant\",\n"," \"content\": \"### πŸ’­ WHAT THE MODEL THINKS\\\\n\\\\n\" + thinking,\n"," })\n"," chat_history.append({\n"," \"role\": \"assistant\",\n"," \"content\": \"### πŸ—£οΈ WHAT THE MODEL SAYS\\\\n\\\\n\" + answer,\n"," })\n","\n"," return chat_history, conversation_history, \"\", None, thinking, answer\n","\n"," except Exception as exc:\n"," error_message = f\"Generation error:\\\\n\\\\n{type(exc).__name__}: {exc}\"\n"," chat_history.append({\"role\": \"assistant\", \"content\": error_message})\n"," # Remove the failed user turn from model context so retrying does not\n"," # leave a malformed/incomplete conversation.\n"," if conversation_history and conversation_history[-1].get(\"role\") == \"user\":\n"," conversation_history.pop()\n"," return chat_history, conversation_history, message, image, \"\", error_message\n","\n","\n","def clear_chat():\n"," return [], [], \"\", None, \"\", \"\"\n","\n","\n","# ============================================================\n","# CELL 7 β€” Gradio interface\n","# ============================================================\n","\n","CUSTOM_CSS = \"\"\"\n",".gradio-container { max-width: 1500px !important; margin: auto !important; }\n","#main-title { text-align: center; margin-bottom: 5px; }\n","#chat-window { min-height: 600px !important; }\n","#chat-window .message { font-size: 16px !important; line-height: 1.6 !important; }\n","#send-button { font-weight: bold !important; }\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 HauhauCS Chat\",\n",") as demo:\n","\n"," gr.Markdown(\n"," \"\"\"\n"," # Qwen3.5-4B HauhauCS Chat\n"," **DreamFast / HauhauCS Β· 4-bit NF4 Β· NVIDIA GPU**\n","\n"," Supports text and image input. The model's generated response is\n"," displayed in the conversation and split into separate panels when\n"," it returns a `<think>` section.\n"," \"\"\",\n"," elem_id=\"main-title\",\n"," )\n","\n"," conversation_state = gr.State([])\n","\n"," with gr.Row():\n"," with gr.Column(scale=7):\n"," chatbot = gr.Chatbot(\n"," label=\"Conversation\",\n"," height=620,\n"," autoscroll=True,\n"," elem_id=\"chat-window\",\n"," )\n","\n"," with gr.Row():\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"," )\n"," image_input = gr.Image(\n"," label=\"Optional image\",\n"," height=150,\n"," sources=[\"upload\", \"clipboard\"],\n"," scale=2,\n"," )\n","\n"," with gr.Row():\n"," send_button = gr.Button(\"Send\", variant=\"primary\", scale=3, elem_id=\"send-button\")\n"," clear_button = gr.Button(\"Clear conversation\", variant=\"secondary\", scale=1)\n","\n"," with gr.Column(scale=3):\n"," gr.Markdown(\"## Generation settings\")\n"," max_new_tokens = gr.Slider(\n"," minimum=128, maximum=4096, value=1024, step=128,\n"," label=\"Maximum new tokens\",\n"," )\n"," temperature = gr.Slider(\n"," minimum=0.0, maximum=1.5, value=0.7, step=0.05,\n"," label=\"Temperature (0 = deterministic)\",\n"," )\n"," top_p = gr.Slider(\n"," minimum=0.1, maximum=1.0, value=0.9, step=0.05,\n"," label=\"Top-p\",\n"," )\n","\n"," gr.Markdown(\"---\")\n"," gr.Markdown(\"## Latest model response\")\n","\n"," with gr.Row():\n"," with gr.Column():\n"," thinking_output = gr.Textbox(\n"," label=\"πŸ’­ What the model thinks\",\n"," lines=12,\n"," max_lines=25,\n"," interactive=False,\n"," placeholder=\"A separate think section, if returned, appears here.\",\n"," )\n"," with gr.Column():\n"," answer_output = gr.Textbox(\n"," label=\"πŸ—£οΈ What the model says\",\n"," lines=12,\n"," max_lines=25,\n"," interactive=False,\n"," placeholder=\"The model's answer appears here.\",\n"," )\n","\n"," callback_inputs = [\n"," message_input,\n"," image_input,\n"," chatbot,\n"," conversation_state,\n"," max_new_tokens,\n"," temperature,\n"," top_p,\n"," ]\n"," callback_outputs = [\n"," chatbot,\n"," conversation_state,\n"," message_input,\n"," image_input,\n"," thinking_output,\n"," answer_output,\n"," ]\n","\n"," send_button.click(chat, inputs=callback_inputs, outputs=callback_outputs)\n"," message_input.submit(chat, inputs=callback_inputs, outputs=callback_outputs)\n"," clear_button.click(clear_chat, inputs=[], outputs=callback_outputs)\n","\n","\n","# ============================================================\n","# CELL 8 β€” Launch\n","# ============================================================\n","\n","print(\"Starting Gradio. The public share link will appear below.\")\n","demo.queue().launch(\n"," share=True,\n"," debug=True,\n"," show_error=True,\n",")\n"],"id":"c9VvMbzuShVO"}],"metadata":{"colab":{"provenance":[],"gpuType":"T4"},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":5}