diff --git "a/klein_prepare_lora_set.ipynb" "b/klein_prepare_lora_set.ipynb" --- "a/klein_prepare_lora_set.ipynb" +++ "b/klein_prepare_lora_set.ipynb" @@ -1 +1 @@ -{"cells":[{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"r6q_m-6Pmm5w"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Set path to zip file on your drive , and set klein edit prompt\n","input_zip_path = '/content/drive/MyDrive/my_images.zip' #@param {type:'string'}\n","zip_path = input_zip_path\n","edit_prompt = 'make sure the bare skin against the very dark background looks like a real photo. remove the background at the centre so that it has the same color as the corners. remove the corners. remove the background. the background is a single color. ' #@param }¥{type:'string'}"],"metadata":{"id":"K13pRro0lxAw","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# ⚙️ Run Klein Edit AIO (GPU)"],"metadata":{"id":"_zmT9hq3WRn_"}},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"QWb_m0FaWu4Y"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 1**: Mount Drive + HF auth\n","# =============================================================================\n","\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","import shutil\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n","else:\n"," print(\"⚠️ No HF_TOKEN found in secrets.\")\n","\n","print(\"🧹 Removing old diffusers...\")\n","!pip uninstall -y diffusers > /dev/null 2>&1\n","!rm -rf /usr/local/lib/python3.12/dist-packages/diffusers* ~/.cache/pip/*diffusers*\n","\n","print(\"🔄 Installing latest diffusers...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!python -m pip cache purge\n","\n","print(\"✅ Cell 1 complete!\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"XJjiAPLuW1ni"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 2**: Fixed settings (resolution + options)\n","# =============================================================================\n","\n","resolution = '1024 x 1024 (Square)' #@param [\"1024 x 1024 (Square)\", \"512 x 1024 (Portrait)\", \"768 x 1024 (Slight Portrait)\", \"1536 x 1024 (Landscape)\", \"2048 x 1024 (Wide Landscape)\"] {type:\"string\"}\n","use_txt_prompts = False #@param {type:\"boolean\"}\n","debug = False #@param {type:\"boolean\"}\n","\n","res_map = {\n"," \"1024 x 1024 (Square)\": (1024, 1024),\n"," \"512 x 1024 (Portrait)\": (512, 1024),\n"," \"768 x 1024 (Slight Portrait)\": (768, 1024),\n"," \"1536 x 1024 (Landscape)\": (1536, 1024),\n"," \"2048 x 1024 (Wide Landscape)\": (2048, 1024)\n","}\n","target_width, target_height = res_map[resolution]\n","\n","print(\"✅ Cell 2 settings loaded\")\n","print(f\" Resolution: {target_width}×{target_height}\")\n","print(f\" Use .txt prompts: {use_txt_prompts}\")\n","print(f\" Debug mode: {debug}\")\n","print(\"\\nNow run Cell 3 (model load), then Cell 4 (inference)\")"]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 3**: Load YOUR QUANTIZED Flux2KleinPipeline (codeShare) + SDNQ optimizations\n","# =============================================================================\n","\n","import torch\n","import gc\n","from diffusers import Flux2KleinPipeline\n","\n","print(\"📦 Installing sdnq...\")\n","!pip install -q sdnq\n","\n","from sdnq.common import use_torch_compile as triton_is_available\n","from sdnq.loader import apply_sdnq_options_to_model\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","print(\"🔄 Loading YOUR quantized model: codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic\")\n","pipe = Flux2KleinPipeline.from_pretrained(\n"," \"codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic\",\n"," torch_dtype=torch.float16\n",")\n","\n","print(f\"✅ Pipeline loaded – VRAM: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# ====================== Optimizations for T4 ======================\n","print(\"🔥 Applying SDNQ + T4 optimizations...\")\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","\n","if triton_is_available and torch.cuda.is_available():\n"," pipe.transformer = apply_sdnq_options_to_model(pipe.transformer, use_quantized_matmul=True)\n"," pipe.text_encoder = apply_sdnq_options_to_model(pipe.text_encoder, use_quantized_matmul=True)\n"," print(\" ✅ INT8 MatMul enabled\")\n","\n","pipe.enable_model_cpu_offload()\n","pipe.vae.enable_slicing()\n","pipe.vae.enable_tiling()\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","torch.cuda.reset_peak_memory_stats()\n","\n","print(\"✅ Cell 3 complete – your model is ready!\")\n","print(\" Now go to Cell 4 and run it (you can change zip/prompt in Cell 4 and re-run Cell 4 only)\")"],"metadata":{"cellView":"form","id":"cG3vOa7mW4IM"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 4**: MULTI-IMAGE INFERENCE (Klein Edit with custom/gray reference)\n","# • First image = your original (the one being edited)\n","# • Second image = custom uploaded OR solid #181818 gray square\n","# • Re-run this cell only after changing settings\n","# =============================================================================\n","\n","edit_prompt = 'remove the background. the background is gray.' #@param {type:\"string\"}\n","zip_path = '/content/drive/MyDrive/input_images.zip' #@param {type:\"string\"}\n","upload_custom_reference = False #@param {type:\"boolean\"}\n","max_image_dimension = 2048 #@param {type:\"slider\", min:512, max:4096, step:256}\n","add_gray_corners = True #@param {type:\"boolean\"}\n","gray_square_size = 50 #@param {type:\"slider\", min:10, max:200, step:10}\n","\n","output_folder = '/content/edited_images_multi'\n","\n","print(\"🧹 Clearing old temporary folders...\")\n","if os.path.exists('/content/input_images'):\n"," shutil.rmtree('/content/input_images')\n","if os.path.exists(output_folder):\n"," shutil.rmtree(output_folder)\n","os.makedirs(output_folder, exist_ok=True)\n","\n","# ====================== Unzip + build prompt map ======================\n","print(f\"📦 Unzipping: {zip_path}...\")\n","with zipfile.ZipFile(zip_path, 'r') as z:\n"," z.extractall('/content/input_images')\n","\n","image_files = sorted(glob.glob('/content/input_images/*.*'))\n","image_files = [f for f in image_files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]\n","print(f\"Found {len(image_files)} images.\")\n","\n","prompt_map = {}\n","txt_count = 0\n","for img_path in image_files:\n"," base = os.path.splitext(os.path.basename(img_path))[0]\n"," txt_path = os.path.join('/content/input_images', f\"{base}.txt\")\n"," if use_txt_prompts and os.path.exists(txt_path):\n"," with open(txt_path, 'r', encoding='utf-8') as f:\n"," prompt_map[img_path] = f.read().strip()\n"," txt_count += 1\n"," else:\n"," prompt_map[img_path] = None\n","\n","print(f\"Found {txt_count} matching .txt files\")\n","\n","# ====================== Create or load the second reference image ======================\n","uploaded_reference_filepath = None\n","reference_image_to_pair = None\n","\n","if upload_custom_reference:\n"," print(\"Please upload your reference image now.\")\n"," uploaded_files = files.upload()\n"," if uploaded_files:\n"," uploaded_reference_filepath = list(uploaded_files.keys())[0]\n"," print(f\"✅ Uploaded reference image: {uploaded_reference_filepath}\")\n"," reference_image_to_pair = Image.open(uploaded_reference_filepath).convert(\"RGB\")\n","else:\n"," print(\"🚫 Custom reference disabled → using solid #181818 gray square\")\n"," reference_image_to_pair = Image.new(\"RGB\", (target_width, target_height), \"#181818\")\n","\n","# Clean up temporary upload file\n","if uploaded_reference_filepath and os.path.exists(uploaded_reference_filepath):\n"," os.remove(uploaded_reference_filepath)\n","\n","# ==================== Helper: add gray corner squares ====================\n","def add_corner_squares(image: Image.Image, square_size: int, color=(24, 24, 24)) -> Image.Image:\n"," img_copy = image.copy()\n"," draw = ImageDraw.Draw(img_copy)\n"," width, height = img_copy.size\n"," draw.rectangle([(0, 0), (square_size, square_size)], fill=color)\n"," draw.rectangle([(width - square_size, 0), (width, square_size)], fill=color)\n"," draw.rectangle([(0, height - square_size), (square_size, height)], fill=color)\n"," draw.rectangle([(width - square_size, height - square_size), (width, height)], fill=color)\n"," return img_copy\n","\n","# ====================== BATCH INFERENCE ======================\n","print(f\"\\n🚀 Starting multi-image edit on {len(image_files)} images...\")\n","\n","for i, img_path in enumerate(image_files):\n"," filename = os.path.basename(img_path)\n"," gc.collect()\n"," torch.cuda.empty_cache()\n","\n"," input_image = Image.open(img_path).convert(\"RGB\")\n","\n"," # Resize if too large\n"," if max(input_image.width, input_image.height) > max_image_dimension:\n"," print(f\" ⚠️ Resizing {filename} to max dimension {max_image_dimension}\")\n"," aspect = input_image.width / input_image.height\n"," if input_image.width > input_image.height:\n"," new_w = max_image_dimension\n"," new_h = int(max_image_dimension / aspect)\n"," else:\n"," new_h = max_image_dimension\n"," new_w = int(max_image_dimension * aspect)\n"," input_image = input_image.resize((new_w, new_h), Image.LANCZOS)\n","\n"," if add_gray_corners:\n"," input_image = add_corner_squares(input_image, gray_square_size)\n","\n"," # Multi-image list for Klein Edit\n"," if reference_image_to_pair is not None:\n"," reference_images = [input_image, reference_image_to_pair]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} → + custom/gray reference\")\n"," else:\n"," reference_images = [input_image]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} → (no reference)\")\n","\n"," current_prompt = prompt_map[img_path] if use_txt_prompts and prompt_map[img_path] is not None else edit_prompt\n","\n"," result = pipe(\n"," prompt=current_prompt,\n"," image=reference_images, # ← Klein multi-reference\n"," height=target_height,\n"," width=target_width,\n"," guidance_scale=1.0,\n"," num_inference_steps=4,\n"," generator=torch.Generator(\"cuda\").manual_seed(42),\n"," output_type=\"pil\",\n"," ).images[0]\n","\n"," output_path = os.path.join(output_folder, f\"multi_edited_{filename}\")\n"," result.save(output_path)\n","\n","print(\"\\n→ MULTI-IMAGE BATCH COMPLETE!\")\n","\n","# ====================== ZIP TO DRIVE ======================\n","timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n","drive_zip_path = f\"/content/drive/MyDrive/klein_edited_{timestamp}.zip\"\n","\n","print(f\"📦 Creating zip → {drive_zip_path}\")\n","shutil.make_archive(drive_zip_path.replace('.zip', ''), 'zip', output_folder)\n","\n","print(\"✅ ALL DONE!\")\n","print(f\"Zip saved to Google Drive: {drive_zip_path}\")"],"metadata":{"cellView":"form","id":"-maumr_vW9br"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# Auto Disconnect"],"metadata":{"id":"BsPp1a4wXTbf"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"FQF71-mvmlc1","cellView":"form"},"outputs":[],"source":["# ================================================\n","#@title 🔌 Auto Disconnect Colab Session\n","# ================================================\n","\n","enable = False #@param {type:'boolean'}\n","print(\"🔌 Disconnecting Colab session in 15 seconds...\")\n","import time\n","time.sleep(3)\n","\n","from google.colab import runtime\n","runtime.unassign()\n","\n","print(\"Session disconnected.\")"]},{"cell_type":"markdown","source":["# Select klein edited zip file to process next\n","Results from earlier cell have been saved to your drive as
'content/drive/MyDrive/klein_processed_(date_number).zip'\n","\n","You can disconnect from the session , and reconnect to new runtime to prevent conflict in installed libraries. you can run this code on CPU"],"metadata":{"id":"F5NDcZ6rZw6Q"}},{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"ijzwEoboHVPR"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"OdcEXFs4oBt_","cellView":"form"},"outputs":[],"source":["import os\n","\n","klein_edited_zip_path = '/content/drive/MyDrive/klein_processed.zip' #@param {type:'string'}\n","zip_path = klein_edited_zip_path\n","\n","if not os.path.exists(zip_path):\n"," raise FileNotFoundError(f\"❌ Klein edited zip file not found:\\n{zip_path}\\n\\nPlease ensure the path is correct and the file exists in your Drive.\")"]},{"cell_type":"markdown","source":["# ⚙️ Create 1024x1024 frames from selected klein edited set"],"metadata":{"id":"4PjK9a8Sni3A"}},{"cell_type":"code","source":["#@title 🖼️ **Image Background Processor (v1)**\n","#@markdown ---\n","#@markdown ## Enable Processor V1\n","enable_processor_v1 = False #@param {type:\"boolean\"}\n","\n","#@title 🖼️ **Image Background Processor**\n","#(v2 - Solid #181818 Flood-Fill + Auto-Clear)\n","#**Crop left/right empty space + Convert *any* gray background to exact #181818**\n","#@markdown ---\n","#**New**: Automatically clears all previous processed images on re-run\n","#(no more mixing old files when you run again)\n","\n","#Run this cell (Shift + Enter)\n","#Fill the form below\n","#Click **Run**\n","\n","# ==================== FORM PARAMETERS ====================\n","\n","#input_zip_path = \"/content/drive/MyDrive/klein_processed.zip\" #@param {type:\"string\", placeholder:\"Paste full path to your ZIP file here\"}\n","input_zip_path = zip_path\n","\n","tolerance_crop = 50 #@param {type:\"slider\", min:0, max:100, step:1, title:\"🟦 Crop Tolerance (higher = more aggressive cropping)\"}\n","\n","bg_replace_threshold = 20 #@param {type:\"slider\", min:10, max:100, step:1}\n","\n","force_remount = False #@param {type:\"boolean\", title:\"🔄 Force remount Drive (recommended)\"}\n","\n","#@markdown ---\n","\n","\n","if enable_processor_v1:\n"," from google.colab import drive\n"," import zipfile\n"," import os\n"," import shutil # ← NEW for clearing folders\n"," from PIL import Image\n"," from collections import deque\n","\n"," # ========================= CONFIG =========================\n"," TARGET_GRAY = (24, 24, 24) # Exact #181818 - do not change\n"," # =======================================================\n","\n"," print(\"🚀 Starting image processor (Solid Background v2 + Auto-Clear)...\")\n","\n"," # 1. Mount Google Drive\n"," drive.mount('/content/drive', force_remount=force_remount)\n","\n"," # 2. Validate ZIP path\n"," if not input_zip_path or not os.path.exists(input_zip_path):\n"," raise FileNotFoundError(f\"❌ ZIP file not found:\\n{input_zip_path}\\n\\nPlease paste the correct full path (e.g. /content/drive/MyDrive/my_photos.zip)\")\n","\n"," print(f\"✅ ZIP found: {input_zip_path}\")\n","\n"," # 3. Define working folders\n"," extract_dir = '/content/extracted_images'\n"," processed_dir = '/content/processed_images'\n","\n"," # === NEW: Clear previous processed & extracted images on every run ===\n"," for directory in [extract_dir, processed_dir]:\n"," if os.path.exists(directory):\n"," shutil.rmtree(directory)\n"," print(f\"🧹 Cleared old folder: {directory}\")\n"," os.makedirs(extract_dir, exist_ok=True)\n"," os.makedirs(processed_dir, exist_ok=True)\n"," print(\"✅ Fresh folders ready\")\n","\n"," # 4. Unzip\n"," print(\"📦 Unzipping...\")\n"," with zipfile.ZipFile(input_zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n"," print(f\"✅ Unzipped to {extract_dir}\")\n","\n"," # ==================== HELPER 1: Crop only left & right ====================\n"," def crop_left_right(img):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," bg_color = img.getpixel((0, 0))\n","\n"," left = width\n"," right = 0\n","\n"," for x in range(width):\n"," column_is_empty = True\n"," for y in range(height):\n"," px = img.getpixel((x, y))\n"," if any(abs(a - b) > tolerance_crop for a, b in zip(px, bg_color)):\n"," column_is_empty = False\n"," break\n"," if not column_is_empty:\n"," left = min(left, x)\n"," right = max(right, x)\n","\n"," if left >= right:\n"," return img\n","\n"," return img.crop((left, 0, right + 1, height))\n","\n"," # ==================== HELPER 2: FLOOD-FILL BACKGROUND FROM EDGES ====================\n"," def adjust_background(img, original_bg_color):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," pixels = img.load()\n"," threshold = bg_replace_threshold\n","\n"," visited = set()\n"," queue = deque()\n"," directions = [(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if not (dx == 0 and dy == 0)]\n","\n"," # Seed from borders\n"," for x in range(width):\n"," for y in (0, height - 1):\n"," if (x, y) not in visited:\n"," px = pixels[x, y]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," queue.append((x, y))\n"," visited.add((x, y))\n"," pixels[x, y] = TARGET_GRAY\n","\n"," for y in range(height):\n"," for x in (0, width - 1):\n"," if (x, y) not in visited:\n"," px = pixels[x, y]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," queue.append((x, y))\n"," visited.add((x, y))\n"," pixels[x, y] = TARGET_GRAY\n","\n"," # Flood fill\n"," while queue:\n"," x, y = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = x + dx, y + dy\n"," if 0 <= nx < width and 0 <= ny < height and (nx, ny) not in visited:\n"," px = pixels[nx, ny]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," visited.add((nx, ny))\n"," pixels[nx, ny] = TARGET_GRAY\n"," queue.append((nx, ny))\n","\n"," return img\n","\n"," # 5. Process every image\n"," print(\"🖼️ Processing images...\")\n"," image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')\n","\n"," processed_count = 0\n"," for filename in os.listdir(extract_dir):\n"," if filename.lower().endswith(image_extensions):\n"," img_path = os.path.join(extract_dir, filename)\n"," try:\n"," with Image.open(img_path) as original_img:\n"," cropped = crop_left_right(original_img)\n"," orig_bg = original_img.getpixel((0, 0))\n"," processed = adjust_background(cropped, orig_bg)\n","\n"," out_path = os.path.join(processed_dir, filename)\n"," processed.save(out_path, quality=95 if filename.lower().endswith(('.jpg', '.jpeg')) else None)\n","\n"," processed_count += 1\n"," print(f\" ✅ {filename}\")\n"," except Exception as e:\n"," print(f\" ❌ Skipped {filename}: {e}\")\n","\n"," print(f\"\\n🎉 Processed {processed_count} images!\")\n","\n"," # 6. Create final ZIP in Drive\n"," output_zip_name = \"PROCESSED_\" + os.path.basename(zip_path)\n"," output_zip_path = os.path.join(os.path.dirname(zip_path), output_zip_name)\n"," zip_path = output_zip_path\n","\n"," print(f\"📦 Creating final ZIP: {output_zip_name}\")\n"," with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zip_out:\n"," for root, _, files in os.walk(processed_dir):\n"," for file in files:\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, processed_dir)\n"," zip_out.write(file_path, arcname)\n","\n"," print(\"\\n✅ ALL DONE! Solid #181818 background achieved.\")\n"," print(f\"📍 Saved to your Drive at:\\n {output_zip_path}\")\n"],"metadata":{"id":"HN4kta-OpZ4W","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title **🖼️ Image Background Processor V2 (WIP)**\n","#@markdown ---\n","#@markdown ## Enable Processor V2\n","enable_processor_v2 = True #@param {type:\"boolean\"}\n","\n","#@title **🖼️ Image Background Processor V2 (WIP)**\n","#(v2.7 - **Inverse speck removal** + Border-protected forward speck + % Margin + Solid #181818)\n","\n","#**Crop left/right empty space + Convert *any* gray background to exact #181818**\n","#**New in v2.7**:\n","# • **Inverse speck removal**: finds tiny foreground (subject-colored) specks/islands inside the background and replaces them with solid #181818\n","# • Forward speck removal (previous) still protects any #181818 connected to the outer image edge\n","# • Anti-aliasing is guaranteed to be the **very last step** (after both forward + inverse speck removal)\n","# • All previous features (4-corner BG, % margin, checkboxes, distance-based enclosed speck removal) unchanged\n","\n","# ==================== FORM PARAMETERS ====================\n","\n","input_zip_path = zip_path\n","\n","tolerance_crop = 60 #@param {type:\"slider\", min:0, max:100, step:1, title:\"🔵 Crop Tolerance (higher = more aggressive cropping)\"}\n","\n","bg_replace_threshold = 10 #@param {type:\"slider\", min:10, max:100, step:1, title:\"🎨 Legacy absolute threshold (kept for compatibility)\"}\n","\n","# ── % Margin for BG color estimation ──\n","bg_margin_percent = 6 #@param {type:\"slider\", min:0, max:50, step:1, title:\"% Margin for BG color estimation (wider = more tolerant to inner-loop gray variations)\"}\n","\n","# ── Feature Checkboxes ──\n","enable_robust_bg_detection = True #@param {type:\"boolean\", title:\"✅ Use 4-corner robust BG color (best for inner loops)\"}\n","enable_floodfill_background_adjustment = True #@param {type:\"boolean\", title:\"✅ Enable solid #181818 background replacement\"}\n","enable_small_speck_removal = True #@param {type:\"boolean\"}\n","#title:\"✅ Forward speck removal: remove tiny #181818 specks on subject\"}\n","enable_inverse_speck_removal = True #@param {type:\"boolean\"}\n","#title:\"✅ Inverse speck removal: fill tiny subject specks inside background with #181818\"}\n","enable_anti_aliasing = True #@param {type:\"boolean\", title:\"✅ Smooth edges (Gaussian anti-aliasing)\"}\n","\n","anti_aliasing_strength = 6 #@param {type:\"slider\", min:1, max:40, step:1, title:\" ↳ Anti-aliasing Strength (pixels to blend)\"}\n","\n","# ── Forward speck removal (enclosed only) ──\n","min_floodfill_steps = 8 #@param {type:\"slider\", min:1, max:20, step:1, title:\" ↳ Min floodfill steps to foreground (N) for ENCLOSED BG only (outer-edge-connected BG always protected)\"}\n","\n","# ── Inverse speck removal ──\n","max_inverse_speck_size = 10 #@param {type:\"slider\", min:1, max:100, step:1, title:\" ↳ Max size of foreground specks to fill with #181818\"}\n","\n","force_remount = False #@param {type:\"boolean\", title:\"🔄 Force remount Drive\"}\n","\n","#@markdown ---\n","\n","\n","if enable_processor_v2:\n"," from google.colab import drive\n"," import zipfile\n"," import os\n"," import shutil\n"," from PIL import Image, ImageFilter\n"," from collections import deque\n","\n"," # ========================= CONFIG =========================\n"," TARGET_GRAY = (24, 24, 24) # Exact #181818\n"," # =======================================================\n","\n"," print(\"🚀 Starting Image Background Processor v2.7 (Forward + Inverse speck removal)...\")\n","\n"," # 1. Mount Google Drive\n"," drive.mount('/content/drive', force_remount=force_remount)\n","\n"," # 2. Validate ZIP path\n"," if not input_zip_path or not os.path.exists(input_zip_path):\n"," raise FileNotFoundError(f\"❌ ZIP file not found:\\n{input_zip_path}\\n\\nPlease paste the correct full path\")\n","\n"," print(f\"✅ ZIP found: {input_zip_path}\")\n","\n"," # 3. Define working folders\n"," extract_dir = '/content/extracted_images'\n"," processed_dir = '/content/processed_images'\n","\n"," # Clear previous runs\n"," for directory in [extract_dir, processed_dir]:\n"," if os.path.exists(directory):\n"," shutil.rmtree(directory)\n"," print(f\"﹅ Cleared old folder: {directory}\")\n"," os.makedirs(extract_dir, exist_ok=True)\n"," os.makedirs(processed_dir, exist_ok=True)\n"," print(\"✅ Fresh folders ready\")\n","\n"," # 4. Unzip\n"," print(\"🚀 Unzipping...\")\n"," with zipfile.ZipFile(input_zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n"," print(f\"✅ Unzipped to {extract_dir}\")\n","\n"," # ==================== HELPER 1: Crop only left & right ====================\n"," def crop_left_right(img):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n"," width, height = img.size\n"," bg_color = img.getpixel((0, 0))\n"," left = width\n"," right = 0\n"," for x in range(width):\n"," column_is_empty = True\n"," for y in range(height):\n"," px = img.getpixel((x, y))\n"," if any(abs(a - b) > tolerance_crop for a, b in zip(px, bg_color)):\n"," column_is_empty = False\n"," break\n"," if not column_is_empty:\n"," left = min(left, x)\n"," right = max(right, x)\n"," if left >= right:\n"," return img\n"," return img.crop((left, 0, right + 1, height))\n","\n"," # ==================== HELPER 2: FULL BACKGROUND PROCESSOR (v2.7) ====================\n"," def adjust_background(img, original_bg_color,\n"," enable_floodfill_background_adjustment,\n"," enable_small_speck_removal,\n"," enable_inverse_speck_removal,\n"," enable_anti_aliasing,\n"," anti_aliasing_strength,\n"," min_floodfill_steps,\n"," max_inverse_speck_size,\n"," bg_margin_percent):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," pixels_access = img.load()\n"," target_gray = TARGET_GRAY\n"," directions = [(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if not (dx == 0 and dy == 0)]\n","\n"," # 1. Identify foreground using % margin\n"," per_channel_margin = int(255 * (bg_margin_percent / 100.0))\n"," is_foreground = [[False for _ in range(height)] for _ in range(width)]\n"," for y in range(height):\n"," for x in range(width):\n"," px = pixels_access[(x, y)]\n"," is_bg = all(abs(px[i] - original_bg_color[i]) <= per_channel_margin for i in range(3))\n"," if not is_bg:\n"," is_foreground[x][y] = True\n","\n"," # 2. Base image: solid #181818 + foreground\n"," base_processed_img = Image.new(\"RGB\", (width, height), target_gray)\n"," base_processed_pixels = base_processed_img.load()\n"," for y in range(height):\n"," for x in range(width):\n"," if is_foreground[x][y]:\n"," base_processed_pixels[(x, y)] = pixels_access[(x, y)]\n","\n"," # 3. Forward speck removal (border-protected, enclosed only)\n"," if enable_floodfill_background_adjustment and enable_small_speck_removal:\n"," print(\" 🔍 Running forward speck removal (border-protected)...\")\n"," refined_img = base_processed_img.copy()\n"," refined_pixels = refined_img.load()\n","\n"," # Mark border-connected #181818\n"," connected_to_border = [[False] * height for _ in range(width)]\n"," queue = deque()\n"," for x in range(width):\n"," for y_border in [0, height-1]:\n"," if refined_pixels[(x, y_border)] == target_gray and not connected_to_border[x][y_border]:\n"," connected_to_border[x][y_border] = True\n"," queue.append((x, y_border))\n"," for y in range(height):\n"," for x_border in [0, width-1]:\n"," if refined_pixels[(x_border, y)] == target_gray and not connected_to_border[x_border][y]:\n"," connected_to_border[x_border][y] = True\n"," queue.append((x_border, y))\n"," while queue:\n"," cx, cy = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = cx + dx, cy + dy\n"," if 0 <= nx < width and 0 <= ny < height and not connected_to_border[nx][ny] and refined_pixels[(nx, ny)] == target_gray:\n"," connected_to_border[nx][ny] = True\n"," queue.append((nx, ny))\n","\n"," # Distance to foreground (for enclosed BG only)\n"," distance = [[-1] * height for _ in range(width)]\n"," queue = deque()\n"," for y in range(height):\n"," for x in range(width):\n"," if is_foreground[x][y]:\n"," for dx, dy in directions:\n"," nx, ny = x + dx, y + dy\n"," if 0 <= nx < width and 0 <= ny < height and not is_foreground[nx][ny] and distance[nx][ny] == -1:\n"," distance[nx][ny] = 1\n"," queue.append((nx, ny))\n"," break\n"," while queue:\n"," cx, cy = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = cx + dx, cy + dy\n"," if 0 <= nx < width and 0 <= ny < height and not is_foreground[nx][ny] and distance[nx][ny] == -1:\n"," distance[nx][ny] = distance[cx][cy] + 1\n"," queue.append((nx, ny))\n","\n"," # Revert only enclosed + too-close BG pixels\n"," for y in range(height):\n"," for x in range(width):\n"," if refined_pixels[(x, y)] == target_gray:\n"," if not connected_to_border[x][y] and (distance[x][y] == -1 or distance[x][y] < min_floodfill_steps):\n"," refined_pixels[(x, y)] = pixels_access[(x, y)]\n","\n"," base_processed_img = refined_img\n"," base_processed_pixels = base_processed_img.load()\n","\n"," # 4. INVERSE speck removal (tiny foreground specks inside background → #181818)\n"," if enable_floodfill_background_adjustment and enable_inverse_speck_removal:\n"," print(\" 🔍 Running inverse speck removal (small FG specks → #181818)...\")\n"," refined_img = base_processed_img.copy()\n"," refined_pixels = refined_img.load()\n"," visited = [[False] * height for _ in range(width)]\n","\n"," for y in range(height):\n"," for x in range(width):\n"," if refined_pixels[(x, y)] != target_gray and not visited[x][y]:\n"," component = []\n"," queue = deque([(x, y)])\n"," visited[x][y] = True\n"," while queue:\n"," cx, cy = queue.popleft()\n"," component.append((cx, cy))\n"," for dx, dy in directions:\n"," nx, ny = cx + dx, cy + dy\n"," if 0 <= nx < width and 0 <= ny < height and not visited[nx][ny] and refined_pixels[(nx, ny)] != target_gray:\n"," visited[nx][ny] = True\n"," queue.append((nx, ny))\n"," # Fill small foreground specks with solid #181818\n"," if len(component) < max_inverse_speck_size:\n"," for px, py in component:\n"," refined_pixels[(px, py)] = target_gray\n","\n"," base_processed_img = refined_img\n"," base_processed_pixels = base_processed_img.load()\n","\n"," # 5. Anti-aliasing – ALWAYS LAST (as requested)\n"," if not enable_anti_aliasing:\n"," return base_processed_img\n","\n"," mask = Image.new(\"L\", (width, height), 0)\n"," mask_pixels = mask.load()\n"," for y in range(height):\n"," for x in range(width):\n"," if base_processed_pixels[(x, y)] != target_gray:\n"," mask_pixels[(x, y)] = 255\n","\n"," blur_radius = anti_aliasing_strength / 2.0\n"," blurred_mask = mask.filter(ImageFilter.GaussianBlur(radius=blur_radius))\n","\n"," solid_bg = Image.new(\"RGB\", (width, height), target_gray)\n"," final_img_with_aa = Image.composite(base_processed_img, solid_bg, blurred_mask)\n","\n"," return final_img_with_aa\n","\n"," # ==================== MAIN PROCESSING LOOP ====================\n"," print(\"🚀 Processing images...\")\n"," image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')\n","\n"," processed_count = 0\n"," for filename in os.listdir(extract_dir):\n"," if filename.lower().endswith(image_extensions):\n"," img_path = os.path.join(extract_dir, filename)\n"," try:\n"," with Image.open(img_path) as original_img:\n"," # === ROBUST BACKGROUND COLOR DETECTION ===\n"," cropped = crop_left_right(original_img)\n"," if cropped.mode != 'RGB':\n"," cropped = cropped.convert('RGB')\n","\n"," if enable_robust_bg_detection:\n"," w, h = cropped.size\n"," samples = [\n"," cropped.getpixel((0, 0)),\n"," cropped.getpixel((w-1, 0)),\n"," cropped.getpixel((0, h-1)),\n"," cropped.getpixel((w-1, h-1))\n"," ]\n"," orig_bg = tuple(sum(c) // len(samples) for c in zip(*samples))\n"," print(f\" 📍 Using robust 4-corner BG color for {filename}\")\n"," else:\n"," orig_bg = cropped.getpixel((0, 0))\n","\n"," # === PROCESS IMAGE ===\n"," if enable_floodfill_background_adjustment:\n"," processed = adjust_background(\n"," cropped,\n"," orig_bg,\n"," enable_floodfill_background_adjustment,\n"," enable_small_speck_removal,\n"," enable_inverse_speck_removal,\n"," enable_anti_aliasing,\n"," anti_aliasing_strength,\n"," min_floodfill_steps,\n"," max_inverse_speck_size,\n"," bg_margin_percent\n"," )\n"," else:\n"," processed = cropped\n","\n"," out_path = os.path.join(processed_dir, filename)\n"," processed.save(out_path, quality=95 if filename.lower().endswith(('.jpg', '.jpeg')) else None)\n","\n"," processed_count += 1\n"," print(f\" ✅ {filename}\")\n","\n"," except Exception as e:\n"," print(f\" ❌ Skipped {filename}: {e}\")\n","\n"," print(f\"\\n🎉 Processed {processed_count} images!\")\n","\n"," # 6. Create final ZIP\n"," output_zip_name = \"PROCESSED_\" + os.path.basename(input_zip_path)\n"," output_zip_path = os.path.join(os.path.dirname(input_zip_path), output_zip_name)\n","\n"," print(f\"🚀 Creating final ZIP: {output_zip_name}\")\n"," with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zip_out:\n"," for root, _, files in os.walk(processed_dir):\n"," for file in files:\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, processed_dir)\n"," zip_out.write(file_path, arcname)\n","\n"," print(\"\\n✅ ALL DONE! Solid #181818 everywhere (forward + inverse specks cleaned) + smooth AA last\")\n"," print(f\"📍 Saved to your Drive at:\\n {output_zip_path}\")\n"],"metadata":{"cellView":"form","id":"tFGWg7jNv4mo"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# ⚙️ Create composites"],"metadata":{"id":"kVAe29swHo4I"}},{"cell_type":"code","source":["#@markdown Set zip file input path for making composites\n","input_zip_path = \"/content/drive/MyDrive/PROCESSED_klein_processed.zip\" #@param {type:'string'}\n","zip_file_path = input_zip_path"],"metadata":{"id":"IXQKiBVrNPcE"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"93JpoQJ77NGu","cellView":"form"},"outputs":[],"source":["# ────────────────────────────────────────────────\n","# 🎨 CLEAN ROW → PURE 1024x1024 FRAMES (NO DISTORTION)\n","# ────────────────────────────────────────────────\n","\n","#@markdown ## ⚙️ Main Settings\n","num_frames = 100 #@param {type:\"slider\", min:10, max:2000, step:10}\n","overlap_percent = 0 #@param {type:\"slider\", min:0, max:50, step:1}\n","min_step_ratio = 0.8 #@param {type:\"slider\", min:0.5, max:1.0, step:0.05}\n","max_step_ratio = 1.0 #@param {type:\"slider\", min:0.8, max:1.5, step:0.05}\n","\n","#@markdown ## 🧱 Border\n","border_width = 8 #@param {type:\"slider\", min:0, max:100}\n","\n","#@markdown ## 💾 Input / Output\n","save_to_google_drive = True #@param {type:\"boolean\"}\n","drive_folder_name = \"vertical_slices_output\" #@param {type:\"string\"}\n","# ────────────────────────────────────────────────\n","\n","FRAME_SIZE = 1024\n","INNER_SIZE = FRAME_SIZE - 2 * border_width\n","BORDER_COLOR = (24, 24, 24)\n","\n","import os, random, zipfile\n","import numpy as np\n","from PIL import Image\n","from google.colab import drive\n","\n","# ────────────────────────────────────────────────\n","# Mount Drive\n","# ────────────────────────────────────────────────\n","\n","drive_mounted = False\n","if save_to_google_drive:\n"," try:\n"," drive.mount('/content/drive', force_remount=False)\n"," drive_mounted = True\n"," drive_output_dir = os.path.join(\"/content/drive/MyDrive\", drive_folder_name)\n"," os.makedirs(drive_output_dir, exist_ok=True)\n"," print(\"Drive mounted\")\n"," except:\n"," save_to_google_drive = False\n","\n","# ────────────────────────────────────────────────\n","# Extract ZIP\n","# ────────────────────────────────────────────────\n","\n","extract_root = \"/content/extracted_images\"\n","output_dir = \"/content/frames\"\n","\n","os.makedirs(extract_root, exist_ok=True)\n","os.makedirs(output_dir, exist_ok=True)\n","\n","with zipfile.ZipFile(zip_file_path, 'r') as zf:\n"," zf.extractall(extract_root)\n","\n","# ────────────────────────────────────────────────\n","# Load images\n","# ────────────────────────────────────────────────\n","\n","valid_exts = ('.jpg','.jpeg','.png','.webp')\n","all_sources = []\n","\n","for root, _, files in os.walk(extract_root):\n"," for f in files:\n"," if f.lower().endswith(valid_exts):\n"," all_sources.append(os.path.join(root, f))\n","\n","print(\"Images found:\", len(all_sources))\n","\n","# ────────────────────────────────────────────────\n","# Build row UNTIL enough width\n","# ────────────────────────────────────────────────\n","\n","def build_row_until_width(all_sources, target_h, overlap_ratio, required_width):\n"," canvas = Image.new(\"RGB\", (required_width, target_h))\n"," x = 0\n","\n"," while x < required_width:\n"," src = random.choice(all_sources)\n","\n"," try:\n"," im = Image.open(src).convert(\"RGB\")\n"," w, h = im.size\n","\n"," scale = target_h / h\n"," new_w = int(w * scale)\n","\n"," im = im.resize((new_w, target_h), Image.LANCZOS)\n","\n"," # overlap\n"," if x > 0:\n"," x -= int(new_w * overlap_ratio)\n","\n"," canvas.paste(im, (x, 0))\n"," x += new_w\n","\n"," except:\n"," continue\n","\n"," return canvas\n","\n","# ────────────────────────────────────────────────\n","# Calculate required width\n","# ────────────────────────────────────────────────\n","\n","overlap_ratio = overlap_percent / 100.0\n","\n","avg_step = (min_step_ratio + max_step_ratio) / 2\n","estimated_width = int(num_frames * INNER_SIZE * avg_step * 1.2)\n","\n","print(\"Building row width:\", estimated_width)\n","\n","row_img = build_row_until_width(\n"," all_sources,\n"," INNER_SIZE,\n"," overlap_ratio,\n"," estimated_width\n",")\n","\n","row_np = np.array(row_img)\n","row_h, row_w = row_np.shape[:2]\n","\n","# ────────────────────────────────────────────────\n","# Generate frames (NO distortion)\n","# ────────────────────────────────────────────────\n","\n","frame_idx = 0\n","x_cursor = 0\n","\n","while x_cursor + INNER_SIZE <= row_w and frame_idx < num_frames:\n","\n"," step = random.randint(\n"," int(INNER_SIZE * min_step_ratio),\n"," int(INNER_SIZE * max_step_ratio)\n"," )\n","\n"," crop = row_np[:, x_cursor:x_cursor + INNER_SIZE]\n","\n"," final = Image.new(\"RGB\", (FRAME_SIZE, FRAME_SIZE), BORDER_COLOR)\n"," final.paste(Image.fromarray(crop), (border_width, border_width))\n","\n"," fname = f\"frame_{frame_idx:04d}.jpg\"\n"," final.save(os.path.join(output_dir, fname), \"JPEG\", quality=90)\n","\n"," frame_idx += 1\n"," x_cursor += step\n","\n"," if frame_idx % 50 == 0:\n"," print(frame_idx, \"frames done\")\n","\n","print(\"Finished:\", frame_idx)\n","\n","# ────────────────────────────────────────────────\n","# Save ZIP\n","# ────────────────────────────────────────────────\n","\n","if save_to_google_drive and drive_mounted:\n","\n"," zip_path = \"/content/output.zip\"\n"," drive_path = os.path.join(drive_output_dir, \"vertical_slices.zip\")\n","\n"," with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:\n"," for f in os.listdir(output_dir):\n"," if f.endswith(\".jpg\"):\n"," zf.write(os.path.join(output_dir, f), arcname=f)\n","\n"," !cp -f \"{zip_path}\" \"{drive_path}\"\n","\n"," print(\"Saved to Drive:\", drive_path)"]},{"cell_type":"markdown","source":["# Done!\n","\n","In the zip file /content/drive/MyDrive/vertical_slices_output/vertical_slices.zip , there you will find 100 image composites to choose for lora training\n","\n","//-----//"],"metadata":{"id":"tJlvhf9xDmA7"}},{"cell_type":"markdown","metadata":{"id":"HX3I-YqowwO9"},"source":["# ⚙️ Run Klein Edit (GPU)"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"OXGhsHQwWue_"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 1**: Mount Drive + HF auth\n","# =============================================================================\n","\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","import shutil\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n","else:\n"," print(\"⚠️ No HF_TOKEN found in secrets.\")\n","\n","print(\"🧹 Removing old diffusers...\")\n","!pip uninstall -y diffusers > /dev/null 2>&1\n","!rm -rf /usr/local/lib/python3.12/dist-packages/diffusers* ~/.cache/pip/*diffusers*\n","\n","print(\"🔄 Installing latest diffusers...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!python -m pip cache purge\n","\n","print(\"✅ Cell 1 complete!\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"a1wZv8PrXAe2"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 2**: Fixed settings (resolution + options)\n","# =============================================================================\n","\n","resolution = '1024 x 1024 (Square)' #@param [\"1024 x 1024 (Square)\", \"512 x 1024 (Portrait)\", \"768 x 1024 (Slight Portrait)\", \"1536 x 1024 (Landscape)\", \"2048 x 1024 (Wide Landscape)\"] {type:\"string\"}\n","use_txt_prompts = False #@param {type:\"boolean\"}\n","debug = False #@param {type:\"boolean\"}\n","\n","res_map = {\n"," \"1024 x 1024 (Square)\": (1024, 1024),\n"," \"512 x 1024 (Portrait)\": (512, 1024),\n"," \"768 x 1024 (Slight Portrait)\": (768, 1024),\n"," \"1536 x 1024 (Landscape)\": (1536, 1024),\n"," \"2048 x 1024 (Wide Landscape)\": (2048, 1024)\n","}\n","target_width, target_height = res_map[resolution]\n","\n","print(\"✅ Cell 2 settings loaded\")\n","print(f\" Resolution: {target_width}×{target_height}\")\n","print(f\" Use .txt prompts: {use_txt_prompts}\")\n","print(f\" Debug mode: {debug}\")\n","print(\"\\nNow run Cell 3 (model load), then Cell 4 (inference)\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"WdNfo33NXNEa"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 3**: Load QUANTIZED Flux2KleinPipeline + SDNQ optimizations\n","#(model stays in memory)\n","# =============================================================================\n","\n","import torch\n","import gc\n","from diffusers import Flux2KleinPipeline\n","import zipfile\n","import glob\n","import os\n","\n","print(\"📦 Installing sdnq...\")\n","!pip install -q sdnq\n","\n","from sdnq.common import use_torch_compile as triton_is_available\n","from sdnq.loader import apply_sdnq_options_to_model\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","print(\"🔄 Loading QUANTIZED Flux2KleinPipeline (4-bit SDNQ + float16 for T4)...\")\n","pipe = Flux2KleinPipeline.from_pretrained(\n"," \"Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic\",\n"," torch_dtype=torch.float16\n",")\n","\n","print(f\"✅ Pipeline loaded – VRAM: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# ====================== Optimizations for T4 ======================\n","print(\"🔥 Applying SDNQ + T4 optimizations...\")\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","\n","if triton_is_available and torch.cuda.is_available():\n"," pipe.transformer = apply_sdnq_options_to_model(pipe.transformer, use_quantized_matmul=True)\n"," pipe.text_encoder = apply_sdnq_options_to_model(pipe.text_encoder, use_quantized_matmul=True)\n"," print(\" ✅ INT8 MatMul enabled\")\n","\n","pipe.enable_model_cpu_offload()\n","pipe.vae.enable_slicing()\n","pipe.vae.enable_tiling()\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","torch.cuda.reset_peak_memory_stats()\n","\n","print(\"✅ Cell 3 complete – model is ready!\")\n","print(\" Now go to Cell 4 and run it (you can change zip/prompt in Cell 4 and re-run Cell 4 only)\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"q9I9wxghuUGP","cellView":"form"},"outputs":[],"source":["import shutil\n","import datetime\n","import os\n","import glob\n","import zipfile\n","import gc\n","import torch\n","from PIL import Image, ImageDraw # Added ImageDraw\n","from google.colab import files\n","\n","# =============================================================================\n","#@markdown # **CELL 4**: MULTI-IMAGE INFERENCE (Klein + custom/gray reference)\n","# • Uses the **same zip** as Cell 4 but now does true multi-image editing\n","# • First image = your original (the one being edited)\n","# • Second image = your custom uploaded image OR a solid #181818 gray square (perfect for background replacement)\n","# • Re-run this cell only with new values\n","# • Auto-clears old data → processes → saves **only ZIP** to Drive\n","# =============================================================================\n","\n","#edit_prompt = 'remove the background. the background is gray. ' #@param {type:\"string\"}\n","#zip_path = '/content/drive/MyDrive/input_images.zip' #@param {type:\"string\"}\n","upload_custom_reference = False #@param {type:\"boolean\"}\n","max_image_dimension = 2048 #@param {type:\"slider\", min:512, max:4096, step:256}\n","add_gray_corners = True #@param {type:\"boolean\"}\n","gray_square_size = 50 #@param {type:\"slider\", min:10, max:200, step:10}\n","\n","output_folder = '/content/edited_images_multi' # ← separate temp folder so it doesn't clash with Cell 4\n","\n","print(\"🧹 Clearing old temporary folders so you can reuse with new zip/prompt...\")\n","if os.path.exists('/content/input_images'):\n"," shutil.rmtree('/content/input_images')\n","if os.path.exists(output_folder):\n"," shutil.rmtree(output_folder)\n","os.makedirs(output_folder, exist_ok=True)\n","\n","# ====================== Unzip + build prompt map ======================\n","print(f\"📦 Unzipping: {zip_path}...\")\n","with zipfile.ZipFile(zip_path, 'r') as z:\n"," z.extractall('/content/input_images')\n","\n","image_files = sorted(glob.glob('/content/input_images/*.*'))\n","image_files = [f for f in image_files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]\n","print(f\"Found {len(image_files)} images.\")\n","\n","prompt_map = {}\n","txt_count = 0\n","for img_path in image_files:\n"," base = os.path.splitext(os.path.basename(img_path))[0]\n"," txt_path = os.path.join('/content/input_images', f\"{base}.txt\")\n"," if use_txt_prompts and os.path.exists(txt_path):\n"," with open(txt_path, 'r', encoding='utf-8') as f:\n"," prompt_map[img_path] = f.read().strip()\n"," txt_count += 1\n"," else:\n"," prompt_map[img_path] = None\n","\n","print(f\"Found {txt_count} matching .txt files\")\n","\n","# ====================== Create or load the second reference image (once) ======================\n","uploaded_reference_filepath = None\n","reference_image_to_pair = None # Initialize to None\n","\n","if upload_custom_reference: # Only attempt to get a reference if the checkbox is enabled\n"," print(\"Please upload your reference image now.\")\n"," uploaded_files = files.upload()\n","\n"," if uploaded_files:\n"," uploaded_reference_filepath = list(uploaded_files.keys())[0]\n"," print(f\"✅ Uploaded reference image: {uploaded_reference_filepath}\")\n"," # Save the uploaded file to a temporary location to be opened by PIL\n"," with open(uploaded_reference_filepath, 'wb') as f:\n"," f.write(uploaded_files[uploaded_reference_filepath])\n","\n"," if uploaded_reference_filepath: # Check if a file was actually uploaded\n"," print(\"📁 Using uploaded reference image...\")\n"," try:\n"," # Open the temporary file\n"," reference_image_to_pair = Image.open(uploaded_reference_filepath).convert(\"RGB\")\n"," #if reference_image_to_pair.size != (target_width, target_height):\n"," # print(f\" ⚠️ Resizing uploaded reference image from {reference_image_to_pair.size} to {target_width}x{target_height}\")\n"," # reference_image_to_pair = reference_image_to_pair.resize((target_width, target_height), Image.LANCZOS)\n"," except Exception as e:\n"," print(f\" ❌ Error loading uploaded image: {e}. Falling back to gray reference.\")\n"," reference_image_to_pair = Image.new(\"RGB\", (target_width, target_height), \"#181818\")\n"," else: # If upload_custom_reference is True but no file was uploaded\n"," print(f\"🟩 No custom reference image uploaded. Creating {target_width}x{target_height} #181818 solid gray reference image...\")\n"," reference_image_to_pair = Image.new(\"RGB\", (target_width, target_height), \"#181818\")\n","else:\n"," print(\"🚫 Custom reference image upload disabled. Will process images without a second reference.\")\n"," # reference_image_to_pair remains None, which is the desired behavior for the pipe call.\n","\n","# Clean up the temporarily saved file if it was uploadedi\n","if uploaded_reference_filepath and os.path.exists(uploaded_reference_filepath):\n"," os.remove(uploaded_reference_filepath)\n","\n","# ==================== Helper function for adding gray squares ====================\n","def add_corner_squares(image: Image.Image, square_size: int, color=(24, 24, 24)) -> Image.Image:\n"," \"\"\"Adds four gray squares to the corners of the input image.\"\"\"\n"," img_copy = image.copy()\n"," draw = ImageDraw.Draw(img_copy)\n"," width, height = img_copy.size\n","\n"," # Top-left\n"," draw.rectangle([(0, 0), (square_size, square_size)], fill=color)\n"," # Top-right\n"," draw.rectangle([(width - square_size, 0), (width, square_size)], fill=color)\n"," # Bottom-left\n"," draw.rectangle([(0, height - square_size), (square_size, height)], fill=color)\n"," # Bottom-right\n"," draw.rectangle([(width - square_size, height - square_size), (width, height)], fill=color)\n"," return img_copy\n","\n","# ====================== FULL BATCH MULTI-IMAGE INFERENCE ======================\n","print(f\"\\n🚀 Starting batch MULTI-IMAGE edit on {len(image_files)} images...\")\n","\n","for i, img_path in enumerate(image_files):\n"," filename = os.path.basename(img_path)\n","\n"," gc.collect()\n"," torch.cuda.empty_cache()\n","\n"," input_image = Image.open(img_path).convert(\"RGB\")\n","\n"," # Resize input_image if its largest dimension exceeds max_image_dimension\n"," if max(input_image.width, input_image.height) > max_image_dimension:\n"," print(f\" ⚠️ Resizing {filename} from {input_image.size} to max dimension {max_image_dimension}\")\n"," aspect_ratio = input_image.width / input_image.height\n"," if input_image.width > input_image.height:\n"," new_width = max_image_dimension\n"," new_height = int(max_image_dimension / aspect_ratio)\n"," else:\n"," new_height = max_image_dimension\n"," new_width = int(max_image_dimension * aspect_ratio)\n"," input_image = input_image.resize((new_width, new_height), Image.LANCZOS)\n","\n"," # Apply gray corners if enabled\n"," if add_gray_corners:\n"," print(f\" Adding {gray_square_size}x{gray_square_size} gray squares to corners of {filename}\")\n"," input_image = add_corner_squares(input_image, gray_square_size)\n","\n"," # === MULTI-IMAGE LIST: base image first, the chosen reference second ===\n"," if reference_image_to_pair is not None:\n"," reference_images = [input_image, reference_image_to_pair]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} → + custom reference\")\n"," else:\n"," reference_images = [input_image]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} → (no custom reference)\")\n","\n"," current_prompt = prompt_map[img_path] if use_txt_prompts and prompt_map[img_path] is not None else edit_prompt\n","\n"," result = pipe(\n"," prompt=current_prompt,\n"," image=reference_images, # ← KEY: list of images for Klein multi-reference\n"," height=target_height,\n"," width=target_width,\n"," guidance_scale=1.0,\n"," num_inference_steps=4,\n"," generator=torch.Generator(\"cuda\").manual_seed(42),\n"," output_type=\"pil\",\n"," ).images[0]\n","\n"," output_filename = f\"multi_edited_{filename}\"\n"," output_path = os.path.join(output_folder, output_filename)\n"," result.save(output_path)\n","\n"," if debug:\n"," print(f\" → Saved {output_filename} (multi-ref with custom/gray image)\") # Updated message\n","\n","print(\"\\n→ MULTI-IMAGE BATCH COMPLETE!\")\n","\n","# ====================== AUTO ZIP TO DRIVE (unique name) ======================\n","timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n","drive_zip_path = f\"/content/drive/MyDrive/klein_processed_{timestamp}.zip\"\n","\n","print(f\"📦 Creating zip → {drive_zip_path}\")\n","shutil.make_archive(drive_zip_path.replace('.zip', ''), 'zip', output_folder)\n","\n","print(\"✅ ALL DONE!\")\n","print(f\"Zip file saved to your Google Drive:\")\n","print(drive_zip_path)"]},{"cell_type":"markdown","source":["# Quantized Img2img lora training klein 4B (Ostris AI toolkit) WIP"],"metadata":{"id":"Sl3MykNlqAop"}},{"cell_type":"code","source":["#@markdown # **CELL 1**: Mount Drive + HF auth + Global Debug\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n"," if debug: print(\"✅ HF login successful – gated FLUX.2-klein-4B download enabled\")\n","else:\n"," if debug: print(\"⚠️ No HF_TOKEN found. You may need to accept the model gate on HF.\")\n","\n","print(\"🧹 Clearing GPU memory...\")\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","if debug:\n"," print(f\" VRAM after cleanup: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","print(\"✅ CELL 1 complete! → Run Cell 2\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"3PEqiDyaqJMe","executionInfo":{"status":"ok","timestamp":1776805017450,"user_tz":-120,"elapsed":31831,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"41a31f88-8633-481b-deae-de64deeb74a6"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Mounted at /content/drive\n","✅ HF login successful – gated FLUX.2-klein-4B download enabled\n","🧹 Clearing GPU memory...\n"," VRAM after cleanup: 0.00 GB\n","✅ CELL 1 complete! → Run Cell 2\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 2 (FIXED)**: Install Ostris AI Toolkit + Torch for Colab\n","\n","import os\n","debug = True #@param {type:\"boolean\"}\n","\n","%cd /content\n","!git clone https://github.com/ostris/ai-toolkit.git --depth 1 # faster clone\n","%cd ai-toolkit\n","\n","print(\"🔄 Installing Torch for Colab CUDA...\")\n","!pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 -q\n","\n","print(\"🔄 Installing AI Toolkit requirements...\")\n","!pip install -r requirements.txt -q\n","\n","# Optional but helpful for quantized Klein\n","!pip install bitsandbytes accelerate peft -q\n","\n","if debug:\n"," print(\"\\n\" + \"=\"*70)\n"," print(\"✅ DEBUG: Package versions\")\n"," !pip list | grep -E 'torch|diffusers|peft|accelerate|bitsandbytes|lycoris'\n"," print(\"=\"*70)\n","\n","print(\"✅ CELL 2 FIXED & complete!\")\n","print(\" → **Restart runtime** (Runtime → Restart session)\")\n","print(\" → Then run the fixed Cell 3\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"5sg8uZVDs64s","executionInfo":{"status":"ok","timestamp":1776805123046,"user_tz":-120,"elapsed":105592,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"89e62a52-0432-41a5-b5fd-6e3e16ebe063"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["/content\n","Cloning into 'ai-toolkit'...\n","remote: Enumerating objects: 649, done.\u001b[K\n","remote: Counting objects: 100% (649/649), done.\u001b[K\n","remote: Compressing objects: 100% (520/520), done.\u001b[K\n","remote: Total 649 (delta 82), reused 520 (delta 67), pack-reused 0 (from 0)\u001b[K\n","Receiving objects: 100% (649/649), 30.06 MiB | 30.53 MiB/s, done.\n","Resolving deltas: 100% (82/82), done.\n","/content/ai-toolkit\n","🔄 Installing Torch for Colab CUDA...\n","🔄 Installing AI Toolkit requirements...\n"," Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n"," Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n"," Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m96.5/96.5 kB\u001b[0m \u001b[31m4.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m63.1/63.1 kB\u001b[0m \u001b[31m6.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m60.4/60.4 kB\u001b[0m \u001b[31m4.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.0/61.0 kB\u001b[0m \u001b[31m5.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.2/10.2 MB\u001b[0m \u001b[31m80.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m200.3/200.3 kB\u001b[0m \u001b[31m22.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.5/2.5 MB\u001b[0m \u001b[31m100.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m290.4/290.4 kB\u001b[0m \u001b[31m29.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m109.7/109.7 kB\u001b[0m \u001b[31m12.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m54.9/54.9 kB\u001b[0m \u001b[31m5.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m8.6/8.6 MB\u001b[0m \u001b[31m119.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m894.6/894.6 kB\u001b[0m \u001b[31m55.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m40.5/40.5 MB\u001b[0m \u001b[31m23.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.1/2.1 MB\u001b[0m \u001b[31m85.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m194.4/194.4 kB\u001b[0m \u001b[31m19.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m37.8/37.8 MB\u001b[0m \u001b[31m24.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.1/1.1 MB\u001b[0m \u001b[31m65.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.6/1.6 MB\u001b[0m \u001b[31m85.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.5/1.5 MB\u001b[0m \u001b[31m33.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m60.7/60.7 MB\u001b[0m \u001b[31m12.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.6/3.6 MB\u001b[0m \u001b[31m56.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m53.8/53.8 kB\u001b[0m \u001b[31m5.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m63.0/63.0 MB\u001b[0m \u001b[31m15.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.0/3.0 MB\u001b[0m \u001b[31m104.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m18.0/18.0 MB\u001b[0m \u001b[31m98.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m50.0/50.0 MB\u001b[0m \u001b[31m13.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.4/1.4 MB\u001b[0m \u001b[31m70.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m44.8/44.8 kB\u001b[0m \u001b[31m4.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m180.7/180.7 kB\u001b[0m \u001b[31m19.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.2/61.2 kB\u001b[0m \u001b[31m6.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h Building wheel for lycoris-lora (setup.py) ... \u001b[?25l\u001b[?25hdone\n"," Building wheel for diffusers (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n","ipython 7.34.0 requires jedi>=0.16, which is not installed.\n","tobler 0.14.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","tobler 0.14.0 requires scipy>=1.13, but you have scipy 1.12.0 which is incompatible.\n","rasterio 1.5.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n","access 1.1.10.post3 requires scipy>=1.14.1, but you have scipy 1.12.0 which is incompatible.\n","shap 0.51.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n","xarray-einstats 0.10.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","xarray-einstats 0.10.0 requires scipy>=1.13, but you have scipy 1.12.0 which is incompatible.\n","jaxlib 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","jaxlib 0.7.2 requires scipy>=1.13, but you have scipy 1.12.0 which is incompatible.\n","cuml-cu12 26.2.0 requires scipy>=1.13.0, but you have scipy 1.12.0 which is incompatible.\n","tsfresh 0.21.1 requires scipy>=1.14.0; python_version >= \"3.10\", but you have scipy 1.12.0 which is incompatible.\n","pytensor 2.38.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","jax 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","jax 0.7.2 requires scipy>=1.13, but you have scipy 1.12.0 which is incompatible.\n","cupy-cuda12x 14.0.1 requires numpy<2.6,>=2.0, but you have numpy 1.26.4 which is incompatible.\n","opencv-contrib-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\u001b[0m\u001b[31m\n","\u001b[0m\n","======================================================================\n","✅ DEBUG: Package versions\n","accelerate 1.13.0\n","bitsandbytes 0.49.2\n","clip-anytorch 2.6.0\n","dctorch 0.1.2\n","diffusers 0.38.0.dev0\n","lycoris_lora 1.8.3\n","open_clip_torch 3.3.0\n","peft 0.18.1\n","pytorch-fid 0.3.0\n","pytorch-wavelets 1.3.0\n","torch 2.10.0+cu128\n","torchao 0.10.0\n","torchaudio 2.10.0+cu128\n","torchcodec 0.9.1\n","torchdata 0.11.0\n","torchdiffeq 0.2.5\n","torchsde 0.2.6\n","torchsummary 1.5.1\n","torchtune 0.6.1\n","torchvision 0.25.0+cu128\n","======================================================================\n","✅ CELL 2 FIXED & complete!\n"," → **Restart runtime** (Runtime → Restart session)\n"," → Then run the fixed Cell 3\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 3 (FIXED)**: Verify Ostris AI Toolkit\n","\n","import torch\n","import gc\n","import os\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🔄 Verifying after restart...\")\n","\n","# No need to import ai_toolkit — the scripts run directly\n","if os.path.exists(\"/content/ai-toolkit/flux_train_ui.py\"):\n"," print(\"✅ flux_train_ui.py found → toolkit is ready!\")\n","else:\n"," print(\"❌ flux_train_ui.py missing — something went wrong with clone\")\n","\n","if debug:\n"," print(\"\\n\" + \"=\"*80)\n"," print(\"✅ ENVIRONMENT READY FOR QUANTIZED KLEIN IMG2IMG\")\n"," print(\"Torch:\", torch.__version__)\n"," print(f\"VRAM free: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n"," print(\"=\"*80)\n","\n","torch.cuda.empty_cache()\n","gc.collect()\n","print(\"✅ CELL 3 complete! → Run Cell 4\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"kE80uoMbtA7B","executionInfo":{"status":"ok","timestamp":1776805123253,"user_tz":-120,"elapsed":45,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"b8d72235-e623-4536-e137-14bbd17883dd"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🔄 Verifying after restart...\n","✅ flux_train_ui.py found → toolkit is ready!\n","\n","================================================================================\n","✅ ENVIRONMENT READY FOR QUANTIZED KLEIN IMG2IMG\n","Torch: 2.10.0+cu128\n","VRAM free: 0.00 GB\n","================================================================================\n","✅ CELL 3 complete! → Run Cell 4\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 4**: Prepare paired dataset for Klein img2img\n","\n","import os\n","import shutil\n","import glob\n","import zipfile # ←←← THIS WAS MISSING → fixed the crash\n","from PIL import Image\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","training_zip_path = '/content/drive/MyDrive/set1.zip' #@param {type:\"string\"}\n","max_images = 2 #@param {type:\"integer\"}\n","\n","dataset_dir = \"/content/klein_img2img_dataset\"\n","target_dir = f\"{dataset_dir}/target\" # full-color images\n","control_dir = f\"{dataset_dir}/control\" # grayscale condition images\n","\n","print(\"🧹 Clearing old folders...\")\n","if os.path.exists(dataset_dir):\n"," shutil.rmtree(dataset_dir)\n","os.makedirs(target_dir, exist_ok=True)\n","os.makedirs(control_dir, exist_ok=True)\n","\n","print(f\"📦 Unzipping: {training_zip_path}\")\n","with zipfile.ZipFile(training_zip_path, 'r') as z:\n"," z.extractall('/content/raw')\n","\n","image_files = sorted(glob.glob('/content/raw/*.*'))[:max_images]\n","image_files = [f for f in image_files if f.lower().endswith(('.png','.jpg','.jpeg','.webp'))]\n","\n","print(f\"Found {len(image_files)} images → creating paired dataset...\")\n","\n","for i, img_path in enumerate(image_files):\n"," base = os.path.splitext(os.path.basename(img_path))[0]\n","\n"," color_img = Image.open(img_path).convert(\"RGB\")\n"," gray_img = color_img.convert(\"L\").convert(\"RGB\")\n","\n"," color_path = os.path.join(target_dir, f\"{base}.png\")\n"," gray_path = os.path.join(control_dir, f\"{base}.png\")\n","\n"," color_img.save(color_path)\n"," gray_img.save(gray_path)\n","\n"," # Create caption file (required by toolkit)\n"," with open(os.path.join(target_dir, f\"{base}.txt\"), \"w\", encoding=\"utf-8\") as f:\n"," f.write(\"colorize this image\") # or your custom prompt\n","\n"," if debug:\n"," print(f\" ✅ Pair {i+1}: {base}.png (gray control → color target)\")\n","\n","print(f\"✅ Dataset ready – {len(image_files)} pairs\")\n","print(f\" Target → {target_dir}\")\n","print(f\" Control → {control_dir}\")\n","print(\"✅ CELL 4 complete! → Run Cell 5\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"l7UnDSq8sNJP","executionInfo":{"status":"ok","timestamp":1776805137801,"user_tz":-120,"elapsed":4148,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"c3fa4c18-8908-4f95-ff93-eb458fb4beb3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🧹 Clearing old folders...\n","📦 Unzipping: /content/drive/MyDrive/set1.zip\n","Found 2 images → creating paired dataset...\n"," ✅ Pair 1: TA-2026-04-20-23-52-36-988910702213220633-989750588436660545.png (gray control → color target)\n"," ✅ Pair 2: TA-2026-04-20-23-52-36-988910702213220633-989750588436660546.png (gray control → color target)\n","✅ Dataset ready – 2 pairs\n"," Target → /content/klein_img2img_dataset/target\n"," Control → /content/klein_img2img_dataset/control\n","✅ CELL 4 complete! → Run Cell 5\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 5**: Create quantized config.yaml for FLUX.2-klein-4B img2img\n","\n","import yaml\n","import os\n","\n","config = {\n"," \"model\": {\n"," \"name_or_path\": \"black-forest-labs/FLUX.2-klein-base-4B\",\n"," \"is_flux\": True,\n"," \"quantize\": True, # enables 8-bit / 4-bit quantization\n"," \"low_vram\": True, # critical for Colab T4\n"," },\n"," \"training\": {\n"," \"learning_rate\": 1e-4,\n"," \"max_train_steps\": 20,\n"," \"train_batch_size\": 1,\n"," \"gradient_accumulation_steps\": 4,\n"," \"lr_scheduler\": \"constant\",\n"," \"lr_warmup_steps\": 10,\n"," \"rank\": 16,\n"," \"lora_alpha\": 16,\n"," \"use_8bit_adam\": True,\n"," \"mixed_precision\": \"bf16\",\n"," \"gradient_checkpointing\": True,\n"," \"cache_latents\": False, # ←←← CRITICAL for Klein control/edit mode\n"," \"cache_latents_to_disk\": False,\n"," },\n"," \"datasets\": [\n"," {\n"," \"folder_path\": \"/content/klein_img2img_dataset/target\",\n"," \"control_path\": \"/content/klein_img2img_dataset/control\", # correct key for single control image\n"," \"caption_file_extension\": \".txt\",\n"," \"resolution\": 1024,\n"," }\n"," ],\n"," \"output\": {\n"," \"output_dir\": \"/content/flux_klein_colorize_lora\",\n"," \"save_every_n_steps\": 10,\n"," },\n"," \"general\": {\n"," \"seed\": 42,\n"," \"report_to\": \"tensorboard\",\n"," \"skip_final_inference\": True,\n"," }\n","}\n","\n","config_path = \"/content/klein_img2img_quantized_config.yaml\"\n","with open(config_path, \"w\", encoding=\"utf-8\") as f:\n"," yaml.dump(config, f, default_flow_style=False, sort_keys=False)\n","\n","print(\"✅ Quantized Klein img2img config created at:\", config_path)\n","!cat {config_path}\n","print(\"✅ CELL 5 complete! → Run Cell 6\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"EnjnT4XIsSOh","executionInfo":{"status":"ok","timestamp":1776802973666,"user_tz":-120,"elapsed":130,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"da2d03eb-cce1-4dd9-ba0d-84038a3a331a"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["✅ Quantized Klein img2img config created at: /content/klein_img2img_quantized_config.yaml\n","model:\n"," name_or_path: black-forest-labs/FLUX.2-klein-base-4B\n"," is_flux: true\n"," quantize: true\n"," low_vram: true\n","training:\n"," learning_rate: 0.0001\n"," max_train_steps: 20\n"," train_batch_size: 1\n"," gradient_accumulation_steps: 4\n"," lr_scheduler: constant\n"," lr_warmup_steps: 10\n"," rank: 16\n"," lora_alpha: 16\n"," use_8bit_adam: true\n"," mixed_precision: bf16\n"," gradient_checkpointing: true\n"," cache_latents: false\n"," cache_latents_to_disk: false\n","datasets:\n","- folder_path: /content/klein_img2img_dataset/target\n"," control_path: /content/klein_img2img_dataset/control\n"," caption_file_extension: .txt\n"," resolution: 1024\n","output:\n"," output_dir: /content/flux_klein_colorize_lora\n"," save_every_n_steps: 10\n","general:\n"," seed: 42\n"," report_to: tensorboard\n"," skip_final_inference: true\n","✅ CELL 5 complete! → Run Cell 6\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 6**: Launch Ostris Gradio UI\n","\n","print(\"🚀 Starting Ostris Gradio UI for FLUX.2-klein-4B...\")\n","!python flux_train_ui.py"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"uYQyhgwytILG","outputId":"d5f3b5ca-a440-40a4-e42e-8a938b1b0057"},"execution_count":null,"outputs":[{"metadata":{"tags":null},"name":"stdout","output_type":"stream","text":["🚀 Starting Ostris Gradio UI for FLUX.2-klein-4B...\n","/content/ai-toolkit/flux_train_ui.py:286: DeprecationWarning: The 'theme' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'theme' to Blocks.launch() instead.\n"," with gr.Blocks(theme=theme, css=css) as demo:\n","/content/ai-toolkit/flux_train_ui.py:286: DeprecationWarning: The 'css' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'css' to Blocks.launch() instead.\n"," with gr.Blocks(theme=theme, css=css) as demo:\n","* Running on local URL: http://127.0.0.1:7860\n","* Running on public URL: https://0b137bc832de861392.gradio.live\n","\n","This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n","IMG_4592\n","/tmp/gradio/ba4715f59f1408da7d96a62dd1bfad2f5b428d544c1c1a4101d89aa01ecfcea6/IMG_4592.png\n","IMG_4591\n","/tmp/gradio/2ecbd7fe1249c4788737dff2c9ccdee049e8fa7c58c2918a4f0b719630e5e22c/IMG_4591.png\n","Creating dataset\n","Started training\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","/usr/local/lib/python3.12/dist-packages/albumentations/__init__.py:13: UserWarning: A new version of Albumentations is available: 2.0.8 (you have 1.4.15). Upgrade using: pip install -U albumentations. To disable automatic update checks, set the environment variable NO_ALBUMENTATIONS_UPDATE to 1.\n"," check_for_updates()\n","{\n"," \"type\": \"sd_trainer\",\n"," \"training_folder\": \"output\",\n"," \"device\": \"cuda:0\",\n"," \"network\": {\n"," \"type\": \"lora\",\n"," \"linear\": 16,\n"," \"linear_alpha\": 16\n"," },\n"," \"save\": {\n"," \"dtype\": \"float16\",\n"," \"save_every\": 250,\n"," \"max_step_saves_to_keep\": 4,\n"," \"push_to_hub\": false\n"," },\n"," \"datasets\": [\n"," {\n"," \"folder_path\": \"datasets/fe94761a-7b66-4883-982a-96ea87e178a3\",\n"," \"caption_ext\": \"txt\",\n"," \"caption_dropout_rate\": 0.05,\n"," \"shuffle_tokens\": false,\n"," \"cache_latents_to_disk\": true,\n"," \"resolution\": [\n"," 512,\n"," 768,\n"," 1024\n"," ]\n"," }\n"," ],\n"," \"train\": {\n"," \"batch_size\": 1,\n"," \"steps\": 1000,\n"," \"gradient_accumulation_steps\": 1,\n"," \"train_unet\": true,\n"," \"train_text_encoder\": false,\n"," \"gradient_checkpointing\": true,\n"," \"noise_scheduler\": \"flowmatch\",\n"," \"optimizer\": \"adamw8bit\",\n"," \"lr\": 0.0004,\n"," \"ema_config\": {\n"," \"use_ema\": true,\n"," \"ema_decay\": 0.99\n"," },\n"," \"dtype\": \"bf16\",\n"," \"skip_first_sample\": true,\n"," \"disable_sampling\": false\n"," },\n"," \"model\": {\n"," \"name_or_path\": \"black-forest-labs/FLUX.1-dev\",\n"," \"is_flux\": true,\n"," \"quantize\": true,\n"," \"low_vram\": true\n"," },\n"," \"sample\": {\n"," \"sampler\": \"flowmatch\",\n"," \"sample_every\": 1000,\n"," \"width\": 1024,\n"," \"height\": 1024,\n"," \"prompts\": [\n"," \"A person in a bustling cafe \"\n"," ],\n"," \"neg\": \"\",\n"," \"seed\": 42,\n"," \"walk_seed\": true,\n"," \"guidance_scale\": 4,\n"," \"sample_steps\": 28\n"," }\n","}\n","Using EMA\n","\n","#############################################\n","# Running job: test\n","#############################################\n","\n","\n","Running 1 process\n","Loading Flux model\n","Loading transformer\n","config.json: 100% 378/378 [00:00<00:00, 1.18MB/s]\n","(…)ion_pytorch_model.safetensors.index.json: 121kB [00:00, 20.9MB/s]\n","Downloading (incomplete total...): 0.00B [00:00, ?B/s]\n","Downloading (incomplete total...): 100% 23.8G/23.8G [06:37<00:00, 85.3MB/s]\n","Fetching 3 files: 100% 3/3 [06:37<00:00, 132.59s/it]\n","Download complete: 100% 23.8G/23.8G [06:37<00:00, 59.8MB/s]\n","Loading checkpoint shards: 100% 3/3 [00:02<00:00, 1.41it/s]\n","Quantizing transformer\n"]}]},{"cell_type":"markdown","source":["# Quantized Klein Edit txt2img LoRa Training (Dreambooth) Unused"],"metadata":{"id":"AOicVDnxWOhD"}},{"cell_type":"code","source":["#@markdown # **CELL 1**: Mount Drive + HF auth + Global Debug\n","# =============================================================================\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n"," if debug: print(\"✅ HF login successful – gated model download enabled\")\n","else:\n"," if debug: print(\"⚠️ No HF_TOKEN found in secrets. FLUX.2-klein-4B download may fail.\")\n","\n","print(\"🧹 Clearing GPU memory...\")\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","if debug:\n"," print(f\" VRAM after cleanup: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","print(\"✅ CELL 1 complete! Now run Cell 2\")"],"metadata":{"cellView":"form","id":"r7lG5GGKWNQT","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1776797201603,"user_tz":-120,"elapsed":34238,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"ff7cd54d-4aa7-4d3a-ab44-0c2b7aab9b68"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Mounted at /content/drive\n","✅ HF login successful – gated model download enabled\n","🧹 Clearing GPU memory...\n"," VRAM after cleanup: 0.00 GB\n","✅ CELL 1 complete! Now run Cell 2\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 2**: Environment Setup – Clean + FLUX requirements (FIXED)\n","# =============================================================================\n","import os\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🧹 Resetting working directory...\")\n","%cd /content\n","\n","# Remove old diffusers completely\n","print(\"🧹 Removing any existing diffusers...\")\n","!pip uninstall -y diffusers peft accelerate transformers bitsandbytes -q\n","!rm -rf /content/diffusers /usr/local/lib/python*/dist-packages/diffusers*\n","\n","print(\"🔄 Installing latest diffusers from GitHub main...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","\n","print(\"🔄 Cloning training scripts...\")\n","!git clone https://github.com/huggingface/diffusers.git --depth=1 /content/diffusers\n","\n","# FLUX-specific requirements\n","print(\"🔄 Installing FLUX requirements...\")\n","!pip install -q -r /content/diffusers/examples/dreambooth/requirements_flux.txt --no-deps\n","\n","print(\"🔄 Installing bitsandbytes + dreambooth requirements...\")\n","!pip install -q bitsandbytes\n","%cd /content/diffusers/examples/dreambooth\n","!pip install -q -r requirements.txt --no-deps\n","!pip install -q --upgrade peft\n","\n","if debug:\n"," print(\"\\n\" + \"=\"*70)\n"," print(\"✅ DEBUG: Package versions\")\n"," !pip list | grep -E 'diffusers|peft|accelerate|transformers|torch|bitsandbytes'\n"," print(\"=\"*70)\n","\n","import diffusers\n","if debug: print(f\"✅ diffusers version: {diffusers.__version__}\")\n","\n","print(\"✅ CELL 2 complete!\")\n","print(\" → **Restart runtime now** (Runtime → Restart session)\")\n","print(\" → Then run Cell 3\")"],"metadata":{"cellView":"form","id":"n5T6wTmbWaSM","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1776797271134,"user_tz":-120,"elapsed":69529,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"d14b7fb4-4306-4844-ade7-faa75dd8323e"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🧹 Resetting working directory...\n","/content\n","🧹 Removing any existing diffusers...\n","\u001b[33mWARNING: Skipping bitsandbytes as it is not installed.\u001b[0m\u001b[33m\n","\u001b[0m🔄 Installing latest diffusers from GitHub main...\n"," Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n"," Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n"," Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n"," Building wheel for diffusers (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","🔄 Cloning training scripts...\n","Cloning into '/content/diffusers'...\n","remote: Enumerating objects: 2809, done.\u001b[K\n","remote: Counting objects: 100% (2809/2809), done.\u001b[K\n","remote: Compressing objects: 100% (1947/1947), done.\u001b[K\n","remote: Total 2809 (delta 1117), reused 1525 (delta 833), pack-reused 0 (from 0)\u001b[K\n","Receiving objects: 100% (2809/2809), 9.00 MiB | 18.17 MiB/s, done.\n","Resolving deltas: 100% (1117/1117), done.\n","🔄 Installing FLUX requirements...\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m383.7/383.7 kB\u001b[0m \u001b[31m35.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.2/10.2 MB\u001b[0m \u001b[31m98.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m44.8/44.8 kB\u001b[0m \u001b[31m3.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m680.7/680.7 kB\u001b[0m \u001b[31m35.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h🔄 Installing bitsandbytes + dreambooth requirements...\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m60.7/60.7 MB\u001b[0m \u001b[31m11.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h/content/diffusers/examples/dreambooth\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m168.3/168.3 kB\u001b[0m \u001b[31m18.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h\n","======================================================================\n","✅ DEBUG: Package versions\n","accelerate 1.13.0\n","bitsandbytes 0.49.2\n","diffusers 0.38.0.dev0\n","peft 0.19.1\n","sentence-transformers 5.4.0\n","torch 2.10.0+cu128\n","torchao 0.10.0\n","torchaudio 2.10.0+cu128\n","torchcodec 0.10.0+cu128\n","torchdata 0.11.0\n","torchsummary 1.5.1\n","torchtune 0.6.1\n","torchvision 0.25.0+cu128\n","transformers 5.5.4\n","======================================================================\n","✅ diffusers version: 0.38.0.dev0\n","✅ CELL 2 complete!\n"," → **Restart runtime now** (Runtime → Restart session)\n"," → Then run Cell 3\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 3**: Verify diffusers + Flux2KleinPipeline (post-restart)\n","# =============================================================================\n","import torch\n","import gc\n","import sys\n","import importlib\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🔄 Verifying environment after restart...\")\n","\n","importlib.invalidate_caches()\n","\n","import diffusers\n","print(f\"✅ diffusers imported from: {diffusers.__file__}\")\n","print(f\" version: {diffusers.__version__}\")\n","\n","print(\"\\n🔍 Testing Flux2KleinPipeline import...\")\n","from diffusers import Flux2KleinPipeline\n","print(\"✅ Flux2KleinPipeline imported successfully! 🎉\")\n","\n","if debug:\n"," print(\"\\n\" + \"=\"*80)\n"," print(\"✅ ENVIRONMENT IS NOW FULLY READY FOR QLoRA TRAINING\")\n"," print(\"=\"*80)\n","\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","print(\"✅ CELL 3 complete! Ready for dataset preparation in Cell 4\")"],"metadata":{"cellView":"form","id":"_ylc37ayWdzp","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1776797296536,"user_tz":-120,"elapsed":25401,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"8dfd86cc-5f12-43a2-c6ff-b5c5eb38482d"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🔄 Verifying environment after restart...\n","✅ diffusers imported from: /usr/local/lib/python3.12/dist-packages/diffusers/__init__.py\n"," version: 0.38.0.dev0\n","\n","🔍 Testing Flux2KleinPipeline import...\n"]},{"output_type":"stream","name":"stderr","text":["Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n"]},{"output_type":"stream","name":"stdout","text":["✅ Flux2KleinPipeline imported successfully! 🎉\n","\n","================================================================================\n","✅ ENVIRONMENT IS NOW FULLY READY FOR QLoRA TRAINING\n","================================================================================\n","✅ CELL 3 complete! Ready for dataset preparation in Cell 4\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 4**: Prepare dataset (COLOR images only + prompt)\n","import os\n","import shutil\n","import glob\n","import zipfile\n","from PIL import Image\n","import torch\n","import gc\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","training_zip_path = '/content/drive/MyDrive/morbids/morbid4.zip' #@param {type:\"string\"}\n","max_images = 2 #@param {type:\"integer\"}\n","\n","train_data_dir = \"/content/colorization_train_pairs\"\n","output_dir = \"/content/flux_klein_colorize_lora\"\n","\n","print(\"🧹 Clearing old folders...\")\n","if os.path.exists(train_data_dir):\n"," shutil.rmtree(train_data_dir)\n","if os.path.exists(output_dir):\n"," shutil.rmtree(output_dir)\n","os.makedirs(train_data_dir, exist_ok=True)\n","\n","print(f\"📦 Unzipping: {training_zip_path}\")\n","with zipfile.ZipFile(training_zip_path, 'r') as z:\n"," z.extractall('/content/raw_training_images')\n","\n","image_files = sorted(glob.glob('/content/raw_training_images/*.*'))\n","image_files = [f for f in image_files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))][:max_images]\n","\n","print(f\"Found {len(image_files)} images → preparing color-only dataset...\")\n","\n","for i, img_path in enumerate(image_files):\n"," base = os.path.splitext(os.path.basename(img_path))[0]\n"," color_img = Image.open(img_path).convert(\"RGB\")\n"," color_img.save(os.path.join(train_data_dir, f\"{base}.png\"))\n"," if debug:\n"," print(f\" ✅ Saved {base}.png\")\n","\n","print(f\"✅ Dataset ready – {len(image_files)} color images in {train_data_dir}\")\n","print(\" • Prompt: 'colorize this image' (will be passed via --instance_prompt)\")\n","\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","if debug:\n"," print(f\" VRAM after prep: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","print(\"✅ CELL 4 complete! → Run Cell 5\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"kVvyMgscbElb","executionInfo":{"status":"ok","timestamp":1776798171599,"user_tz":-120,"elapsed":3849,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"cd18fdfd-89f8-4c09-e2d7-f7b037e742e0"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🧹 Clearing old folders...\n","📦 Unzipping: /content/drive/MyDrive/morbids/morbid4.zip\n","Found 2 images → preparing color-only dataset...\n"," ✅ Saved 53537172992_145a9daed1_k.png\n"," ✅ Saved 53537173032_18aa14e83b_k.png\n","✅ Dataset ready – 2 color images in /content/colorization_train_pairs\n"," • Prompt: 'colorize this image' (will be passed via --instance_prompt)\n"," VRAM after prep: 0.00 GB\n","✅ CELL 4 complete! → Run Cell 5\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 5**: Setup bnb 4-bit config\n","# =============================================================================\n","import torch\n","import gc\n","import json\n","import os\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🚀 Preparing quantized QLoRA training...\")\n","\n","bnb_config_path = \"/content/bnb_config.json\"\n","bnb_config = {\n"," \"load_in_4bit\": True,\n"," \"bnb_4bit_quant_type\": \"nf4\",\n"," \"bnb_4bit_compute_dtype\": \"float16\",\n"," \"bnb_4bit_use_double_quant\": True\n","}\n","with open(bnb_config_path, \"w\") as f:\n"," json.dump(bnb_config, f)\n","\n","if debug:\n"," print(f\"✅ 4-bit NF4 config saved → {bnb_config_path}\")\n"," with open(bnb_config_path, \"r\") as f:\n"," print(\" Config content:\", f.read())\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","print(\"\\n✅ CELL 5 complete! Now run Cell 6 to start training\")"],"metadata":{"cellView":"form","id":"XVcpaPhAWm0M","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1776797336836,"user_tz":-120,"elapsed":786,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"eb9f14bf-4c38-4436-bbae-d7ebc7e1e617"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🚀 Preparing quantized QLoRA training...\n","✅ 4-bit NF4 config saved → /content/bnb_config.json\n"," Config content: {\"load_in_4bit\": true, \"bnb_4bit_quant_type\": \"nf4\", \"bnb_4bit_compute_dtype\": \"float16\", \"bnb_4bit_use_double_quant\": true}\n","\n","✅ CELL 5 complete! Now run Cell 6 to start training\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 6**: Quantized QLoRA Training (TEXT + PROMPT) + DETAILED LOSS LOG\n","import datetime\n","import os\n","import re\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🚀 Starting **quantized QLoRA** on FLUX.2-klein-4B...\")\n","\n","# ========================== TRAINING PARAMETERS ==========================\n","max_train_steps = 100 #@param {type:\"slider\", min:100, max:2000, step:50}\n","learning_rate = 1e-4 #@param {type:\"slider\", min:5e-5, max:5e-4, step:5e-5, format:\"0.0e\"}\n","rank = 16 #@param {type:\"slider\", min:8, max:64, step:8}\n","gradient_accumulation_steps = 4 #@param {type:\"slider\", min:4, max:16, step:4}\n","lr_warmup_steps = 10 #@param {type:\"slider\", min:0, max:200, step:10}\n","lora_alpha = 32 #@param {type:\"slider\", min:16, max:64, step:8}\n","\n","if debug:\n"," print(f\" • max_train_steps = {max_train_steps}\")\n"," print(f\" • learning_rate = {learning_rate}\")\n"," print(f\" • rank = {rank}\")\n"," print(f\" • gradient_accumulation = {gradient_accumulation_steps}\")\n"," print(f\" • lr_warmup_steps = {lr_warmup_steps}\")\n"," print(f\" • lora_alpha = {lora_alpha}\")\n","\n","# ====================== TRAINING ======================\n","print(\"\\n🔥 Launching training (text + prompt mode)...\")\n","\n","!accelerate launch /content/diffusers/examples/dreambooth/train_dreambooth_lora_flux2_klein.py \\\n"," --pretrained_model_name_or_path=\"black-forest-labs/FLUX.2-klein-4B\" \\\n"," --instance_data_dir=\"/content/colorization_train_pairs\" \\\n"," --instance_prompt=\"colorize this image\" \\\n"," --resolution=1024 \\\n"," --train_batch_size=1 \\\n"," --gradient_accumulation_steps={gradient_accumulation_steps} \\\n"," --gradient_checkpointing \\\n"," --cache_latents \\\n"," --learning_rate={learning_rate} \\\n"," --lr_scheduler=\"constant\" \\\n"," --lr_warmup_steps={lr_warmup_steps} \\\n"," --max_train_steps={max_train_steps} \\\n"," --use_8bit_adam \\\n"," --mixed_precision=\"fp16\" \\\n"," --rank={rank} \\\n"," --lora_alpha={lora_alpha} \\\n"," --output_dir=\"/content/flux_klein_colorize_lora\" \\\n"," --report_to=\"tensorboard\" \\\n"," --seed=42 \\\n"," --bnb_quantization_config_path=\"/content/bnb_config.json\" \\\n"," --offload \\\n"," --skip_final_inference 2>&1 | tee training_log.txt\n","\n","# ====================== DETAILED LOSS RATE LOG ======================\n","print(\"\\n\" + \"=\"*80)\n","print(\"📊 FULL TRAINING LOSS LOG (per step)\")\n","print(\"=\"*80)\n","\n","if os.path.exists(\"training_log.txt\"):\n"," with open(\"training_log.txt\", \"r\", encoding=\"utf-8\") as f:\n"," log_content = f.read()\n","\n"," loss_matches = re.findall(r'loss=([\\d.]+)', log_content)\n","\n"," if loss_matches:\n"," losses = [float(x) for x in loss_matches]\n"," total_steps = len(losses)\n","\n"," print(f\"✅ Training completed {total_steps} steps\")\n"," print(f\" Average loss: {sum(losses)/total_steps:.4f}\")\n"," print(f\" Final loss: {losses[-1]:.4f}\")\n","\n"," print(\"\\nStep-by-Step Loss Table:\")\n"," print(\"┌──────────────┬──────────────┐\")\n"," print(\"│ Step │ Loss │\")\n"," print(\"├──────────────┼──────────────┤\")\n"," for i, loss in enumerate(losses):\n"," step_num = i + 1\n"," print(f\"│ {step_num:4d}/{total_steps:<4d} │ {loss:8.4f} │\")\n"," print(\"└──────────────┴──────────────┘\")\n","\n"," if debug:\n"," print(\"\\nLast 10 losses:\")\n"," for i, loss in enumerate(losses[-10:]):\n"," step_num = total_steps - 10 + i + 1\n"," print(f\" Step {step_num:4d} → loss = {loss:.4f}\")\n","\n"," timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n"," log_zip = f\"/content/drive/MyDrive/flux_klein_colorize_lora_log_{timestamp}.txt\"\n"," with open(log_zip, \"w\", encoding=\"utf-8\") as f:\n"," f.write(log_content)\n"," print(f\"\\n📁 Full training log saved to Drive: {log_zip}\")\n"," else:\n"," print(\"⚠️ No loss values found in log\")\n","else:\n"," print(\"⚠️ training_log.txt not found\")\n","\n","print(\"\\n🎉 TRAINING COMPLETE!\")\n","print(f\"LoRA saved to: /content/flux_klein_colorize_lora\")\n","\n","timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n","drive_zip = f\"/content/drive/MyDrive/flux_klein_colorize_lora_{timestamp}.zip\"\n","!zip -r -q \"{drive_zip}\" /content/flux_klein_colorize_lora\n","print(f\"✅ LoRA ZIP saved to Drive: {drive_zip}\")\n","print(\"\\n✅ CELL 6 complete!\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"cellView":"form","id":"Huz9zNZQbM1Y","executionInfo":{"status":"ok","timestamp":1776800582536,"user_tz":-120,"elapsed":1182262,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"41b9b12e-45fb-45d6-d9bf-53e610234c37"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🚀 Starting **quantized QLoRA** on FLUX.2-klein-4B...\n"," • max_train_steps = 100\n"," • learning_rate = 0.0001\n"," • rank = 16\n"," • gradient_accumulation = 4\n"," • lr_warmup_steps = 10\n"," • lora_alpha = 32\n","\n","🔥 Launching training (text + prompt mode)...\n","The following values were not passed to `accelerate launch` and had defaults used instead:\n","\t`--num_processes` was set to a value of `1`\n","\t`--num_machines` was set to a value of `1`\n","\t`--mixed_precision` was set to a value of `'no'`\n","\t`--dynamo_backend` was set to a value of `'no'`\n","To avoid this warning pass in values for each of the problematic parameters or run `accelerate config`.\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","/usr/local/lib/python3.12/dist-packages/huggingface_hub/utils/_validators.py:205: UserWarning: The `local_dir_use_symlinks` argument is deprecated and ignored in `hf_hub_download`. Downloading to a local directory does not use symlinks anymore.\n"," warnings.warn(\n","{'decoder_block_out_channels'} was not found in config. Values will be initialized to default values.\n","All model checkpoint weights were used when initializing AutoencoderKLFlux2.\n","\n","All the weights of AutoencoderKLFlux2 were initialized from the model checkpoint at black-forest-labs/FLUX.2-klein-4B.\n","If your task is similar to the task the model of the checkpoint was trained on, you can already use AutoencoderKLFlux2 for predictions without further training.\n","The device_map was not initialized. Setting device_map to {: {current_device}}. If you want to use the model for inference, please set device_map ='auto' \n","Instantiating Flux2Transformer2DModel model under default dtype torch.float16.\n","All model checkpoint weights were used when initializing Flux2Transformer2DModel.\n","\n","All the weights of Flux2Transformer2DModel were initialized from the model checkpoint at black-forest-labs/FLUX.2-klein-4B.\n","If your task is similar to the task the model of the checkpoint was trained on, you can already use Flux2Transformer2DModel for predictions without further training.\n","Fetching 2 files: 100%|██████████| 2/2 [00:00<00:00, 8338.58it/s]\n","Loading weights: 100%|██████████| 398/398 [00:00<00:00, 983.47it/s] \n","Loading pipeline components...: 100%|██████████| 2/2 [00:00<00:00, 5384.22it/s]\n","Pipelines loaded with `dtype=torch.float16` cannot run with `cpu` device. It is not recommended to move them to `cpu` as running them will fail. Please make sure to use an accelerator to run the pipeline in inference, due to the lack of support for`float16` operations on this device in PyTorch. Please, remove the `torch_dtype=torch.float16` argument, or use another device for inference.\n","Caching latents: 100%|██████████| 2/2 [00:01<00:00, 1.23it/s]\n","Pipelines loaded with `dtype=torch.float16` cannot run with `cpu` device. It is not recommended to move them to `cpu` as running them will fail. Please make sure to use an accelerator to run the pipeline in inference, due to the lack of support for`float16` operations on this device in PyTorch. Please, remove the `torch_dtype=torch.float16` argument, or use another device for inference.\n","2026-04-21 19:05:41.252120: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n","WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n","E0000 00:00:1776798341.458693 6518 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n","E0000 00:00:1776798341.510650 6518 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n","W0000 00:00:1776798341.924014 6518 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","W0000 00:00:1776798341.924051 6518 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","W0000 00:00:1776798341.924055 6518 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","W0000 00:00:1776798341.924058 6518 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","Steps: 100%|██████████| 100/100 [36:58<00:00, 22.39s/it, loss=0.935, lr=0.0001]Model weights saved in /content/flux_klein_colorize_lora/pytorch_lora_weights.safetensors\n","Steps: 100%|██████████| 100/100 [37:00<00:00, 22.20s/it, loss=0.935, lr=0.0001]\n","\n","================================================================================\n","📊 FULL TRAINING LOSS LOG (per step)\n","================================================================================\n","✅ Training completed 301 steps\n"," Average loss: 0.6535\n"," Final loss: 0.9350\n","\n","Step-by-Step Loss Table:\n","┌──────────────┬──────────────┐\n","│ Step │ Loss │\n","├──────────────┼──────────────┤\n","│ 1/301 │ 0.9510 │\n","│ 2/301 │ 0.9510 │\n","│ 3/301 │ 0.7790 │\n","│ 4/301 │ 0.5550 │\n","│ 5/301 │ 0.5550 │\n","│ 6/301 │ 1.0000 │\n","│ 7/301 │ 0.6010 │\n","│ 8/301 │ 0.6010 │\n","│ 9/301 │ 0.6830 │\n","│ 10/301 │ 0.6160 │\n","│ 11/301 │ 0.6160 │\n","│ 12/301 │ 0.6290 │\n","│ 13/301 │ 1.2400 │\n","│ 14/301 │ 1.2400 │\n","│ 15/301 │ 0.5750 │\n","│ 16/301 │ 0.6220 │\n","│ 17/301 │ 0.6220 │\n","│ 18/301 │ 0.5230 │\n","│ 19/301 │ 0.5250 │\n","│ 20/301 │ 0.5250 │\n","│ 21/301 │ 0.5400 │\n","│ 22/301 │ 0.4580 │\n","│ 23/301 │ 0.4580 │\n","│ 24/301 │ 0.6940 │\n","│ 25/301 │ 0.4460 │\n","│ 26/301 │ 0.4460 │\n","│ 27/301 │ 0.6010 │\n","│ 28/301 │ 1.0100 │\n","│ 29/301 │ 1.0100 │\n","│ 30/301 │ 0.8500 │\n","│ 31/301 │ 0.5470 │\n","│ 32/301 │ 0.5470 │\n","│ 33/301 │ 0.4950 │\n","│ 34/301 │ 1.0700 │\n","│ 35/301 │ 1.0700 │\n","│ 36/301 │ 1.0100 │\n","│ 37/301 │ 0.9330 │\n","│ 38/301 │ 0.9330 │\n","│ 39/301 │ 0.5740 │\n","│ 40/301 │ 0.4210 │\n","│ 41/301 │ 0.4210 │\n","│ 42/301 │ 0.5640 │\n","│ 43/301 │ 0.5590 │\n","│ 44/301 │ 0.5590 │\n","│ 45/301 │ 0.6900 │\n","│ 46/301 │ 0.5450 │\n","│ 47/301 │ 0.5450 │\n","│ 48/301 │ 0.6130 │\n","│ 49/301 │ 0.4160 │\n","│ 50/301 │ 0.4160 │\n","│ 51/301 │ 0.8240 │\n","│ 52/301 │ 0.4680 │\n","│ 53/301 │ 0.4680 │\n","│ 54/301 │ 0.5390 │\n","│ 55/301 │ 0.7720 │\n","│ 56/301 │ 0.7720 │\n","│ 57/301 │ 1.0400 │\n","│ 58/301 │ 0.5230 │\n","│ 59/301 │ 0.5230 │\n","│ 60/301 │ 0.5650 │\n","│ 61/301 │ 0.4210 │\n","│ 62/301 │ 0.4210 │\n","│ 63/301 │ 0.9280 │\n","│ 64/301 │ 0.6240 │\n","│ 65/301 │ 0.6240 │\n","│ 66/301 │ 0.4940 │\n","│ 67/301 │ 0.4800 │\n","│ 68/301 │ 0.4800 │\n","│ 69/301 │ 0.5080 │\n","│ 70/301 │ 0.7360 │\n","│ 71/301 │ 0.7360 │\n","│ 72/301 │ 1.0600 │\n","│ 73/301 │ 0.7130 │\n","│ 74/301 │ 0.7130 │\n","│ 75/301 │ 0.7350 │\n","│ 76/301 │ 0.7280 │\n","│ 77/301 │ 0.7280 │\n","│ 78/301 │ 1.0200 │\n","│ 79/301 │ 0.4570 │\n","│ 80/301 │ 0.4570 │\n","│ 81/301 │ 0.5480 │\n","│ 82/301 │ 0.5340 │\n","│ 83/301 │ 0.5340 │\n","│ 84/301 │ 1.0400 │\n","│ 85/301 │ 0.6140 │\n","│ 86/301 │ 0.6140 │\n","│ 87/301 │ 0.5250 │\n","│ 88/301 │ 0.4560 │\n","│ 89/301 │ 0.4560 │\n","│ 90/301 │ 0.4730 │\n","│ 91/301 │ 0.4050 │\n","│ 92/301 │ 0.4050 │\n","│ 93/301 │ 1.0300 │\n","│ 94/301 │ 0.9090 │\n","│ 95/301 │ 0.9090 │\n","│ 96/301 │ 0.5460 │\n","│ 97/301 │ 0.4860 │\n","│ 98/301 │ 0.4860 │\n","│ 99/301 │ 1.0500 │\n","│ 100/301 │ 0.5320 │\n","│ 101/301 │ 0.5320 │\n","│ 102/301 │ 0.6550 │\n","│ 103/301 │ 0.6690 │\n","│ 104/301 │ 0.6690 │\n","│ 105/301 │ 0.6930 │\n","│ 106/301 │ 0.5550 │\n","│ 107/301 │ 0.5550 │\n","│ 108/301 │ 0.7150 │\n","│ 109/301 │ 0.4440 │\n","│ 110/301 │ 0.4440 │\n","│ 111/301 │ 0.4680 │\n","│ 112/301 │ 0.4160 │\n","│ 113/301 │ 0.4160 │\n","│ 114/301 │ 0.5110 │\n","│ 115/301 │ 1.0500 │\n","│ 116/301 │ 1.0500 │\n","│ 117/301 │ 0.5690 │\n","│ 118/301 │ 0.9510 │\n","│ 119/301 │ 0.9510 │\n","│ 120/301 │ 0.5520 │\n","│ 121/301 │ 0.5350 │\n","│ 122/301 │ 0.5350 │\n","│ 123/301 │ 0.7260 │\n","│ 124/301 │ 0.4060 │\n","│ 125/301 │ 0.4060 │\n","│ 126/301 │ 0.5520 │\n","│ 127/301 │ 0.5360 │\n","│ 128/301 │ 0.5360 │\n","│ 129/301 │ 0.6420 │\n","│ 130/301 │ 0.3940 │\n","│ 131/301 │ 0.3940 │\n","│ 132/301 │ 0.4670 │\n","│ 133/301 │ 0.7970 │\n","│ 134/301 │ 0.7970 │\n","│ 135/301 │ 0.8860 │\n","│ 136/301 │ 0.3960 │\n","│ 137/301 │ 0.3960 │\n","│ 138/301 │ 0.7590 │\n","│ 139/301 │ 1.0700 │\n","│ 140/301 │ 1.0700 │\n","│ 141/301 │ 0.7620 │\n","│ 142/301 │ 0.5150 │\n","│ 143/301 │ 0.5150 │\n","│ 144/301 │ 0.5690 │\n","│ 145/301 │ 0.8970 │\n","│ 146/301 │ 0.8970 │\n","│ 147/301 │ 0.4790 │\n","│ 148/301 │ 0.6300 │\n","│ 149/301 │ 0.6300 │\n","│ 150/301 │ 0.9050 │\n","│ 151/301 │ 0.3860 │\n","│ 152/301 │ 0.3860 │\n","│ 153/301 │ 0.4640 │\n","│ 154/301 │ 0.5010 │\n","│ 155/301 │ 0.5010 │\n","│ 156/301 │ 0.5240 │\n","│ 157/301 │ 0.9970 │\n","│ 158/301 │ 0.9970 │\n","│ 159/301 │ 0.4910 │\n","│ 160/301 │ 1.0400 │\n","│ 161/301 │ 1.0400 │\n","│ 162/301 │ 0.9860 │\n","│ 163/301 │ 0.8960 │\n","│ 164/301 │ 0.8960 │\n","│ 165/301 │ 0.4660 │\n","│ 166/301 │ 0.5750 │\n","│ 167/301 │ 0.5750 │\n","│ 168/301 │ 0.4560 │\n","│ 169/301 │ 0.3940 │\n","│ 170/301 │ 0.3940 │\n","│ 171/301 │ 0.5970 │\n","│ 172/301 │ 0.6300 │\n","│ 173/301 │ 0.6300 │\n","│ 174/301 │ 0.8040 │\n","│ 175/301 │ 0.4960 │\n","│ 176/301 │ 0.4960 │\n","│ 177/301 │ 0.5070 │\n","│ 178/301 │ 0.9070 │\n","│ 179/301 │ 0.9070 │\n","│ 180/301 │ 0.5680 │\n","│ 181/301 │ 0.5410 │\n","│ 182/301 │ 0.5410 │\n","│ 183/301 │ 0.4620 │\n","│ 184/301 │ 1.0500 │\n","│ 185/301 │ 1.0500 │\n","│ 186/301 │ 1.0200 │\n","│ 187/301 │ 0.3900 │\n","│ 188/301 │ 0.3900 │\n","│ 189/301 │ 0.5770 │\n","│ 190/301 │ 0.4760 │\n","│ 191/301 │ 0.4760 │\n","│ 192/301 │ 0.7570 │\n","│ 193/301 │ 0.8230 │\n","│ 194/301 │ 0.8230 │\n","│ 195/301 │ 1.0200 │\n","│ 196/301 │ 1.0300 │\n","│ 197/301 │ 1.0300 │\n","│ 198/301 │ 0.4870 │\n","│ 199/301 │ 0.9780 │\n","│ 200/301 │ 0.9780 │\n","│ 201/301 │ 0.4990 │\n","│ 202/301 │ 1.0500 │\n","│ 203/301 │ 1.0500 │\n","│ 204/301 │ 1.0400 │\n","│ 205/301 │ 0.3890 │\n","│ 206/301 │ 0.3890 │\n","│ 207/301 │ 0.5600 │\n","│ 208/301 │ 0.4600 │\n","│ 209/301 │ 0.4600 │\n","│ 210/301 │ 0.6820 │\n","│ 211/301 │ 0.4000 │\n","│ 212/301 │ 0.4000 │\n","│ 213/301 │ 0.4490 │\n","│ 214/301 │ 0.3880 │\n","│ 215/301 │ 0.3880 │\n","│ 216/301 │ 0.6710 │\n","│ 217/301 │ 0.9290 │\n","│ 218/301 │ 0.9290 │\n","│ 219/301 │ 0.8170 │\n","│ 220/301 │ 0.4550 │\n","│ 221/301 │ 0.4550 │\n","│ 222/301 │ 1.0400 │\n","│ 223/301 │ 1.0300 │\n","│ 224/301 │ 1.0300 │\n","│ 225/301 │ 0.6230 │\n","│ 226/301 │ 0.9650 │\n","│ 227/301 │ 0.9650 │\n","│ 228/301 │ 0.4760 │\n","│ 229/301 │ 0.4670 │\n","│ 230/301 │ 0.4670 │\n","│ 231/301 │ 0.6500 │\n","│ 232/301 │ 0.3840 │\n","│ 233/301 │ 0.3840 │\n","│ 234/301 │ 0.4530 │\n","│ 235/301 │ 0.3920 │\n","│ 236/301 │ 0.3920 │\n","│ 237/301 │ 0.4840 │\n","│ 238/301 │ 0.4610 │\n","│ 239/301 │ 0.4610 │\n","│ 240/301 │ 0.4480 │\n","│ 241/301 │ 0.4450 │\n","│ 242/301 │ 0.4450 │\n","│ 243/301 │ 0.4480 │\n","│ 244/301 │ 0.7440 │\n","│ 245/301 │ 0.7440 │\n","│ 246/301 │ 0.7110 │\n","│ 247/301 │ 1.0300 │\n","│ 248/301 │ 1.0300 │\n","│ 249/301 │ 0.4570 │\n","│ 250/301 │ 0.6120 │\n","│ 251/301 │ 0.6120 │\n","│ 252/301 │ 0.6180 │\n","│ 253/301 │ 0.6340 │\n","│ 254/301 │ 0.6340 │\n","│ 255/301 │ 0.7680 │\n","│ 256/301 │ 0.9350 │\n","│ 257/301 │ 0.9350 │\n","│ 258/301 │ 0.7000 │\n","│ 259/301 │ 0.4500 │\n","│ 260/301 │ 0.4500 │\n","│ 261/301 │ 0.5080 │\n","│ 262/301 │ 0.3910 │\n","│ 263/301 │ 0.3910 │\n","│ 264/301 │ 0.4560 │\n","│ 265/301 │ 0.3850 │\n","│ 266/301 │ 0.3850 │\n","│ 267/301 │ 0.9270 │\n","│ 268/301 │ 0.4140 │\n","│ 269/301 │ 0.4140 │\n","│ 270/301 │ 0.8810 │\n","│ 271/301 │ 0.5720 │\n","│ 272/301 │ 0.5720 │\n","│ 273/301 │ 0.7160 │\n","│ 274/301 │ 0.8380 │\n","│ 275/301 │ 0.8380 │\n","│ 276/301 │ 0.4430 │\n","│ 277/301 │ 0.6600 │\n","│ 278/301 │ 0.6600 │\n","│ 279/301 │ 0.5170 │\n","│ 280/301 │ 1.0500 │\n","│ 281/301 │ 1.0500 │\n","│ 282/301 │ 0.5060 │\n","│ 283/301 │ 0.7400 │\n","│ 284/301 │ 0.7400 │\n","│ 285/301 │ 0.9090 │\n","│ 286/301 │ 0.3690 │\n","│ 287/301 │ 0.3690 │\n","│ 288/301 │ 0.4970 │\n","│ 289/301 │ 0.6750 │\n","│ 290/301 │ 0.6750 │\n","│ 291/301 │ 0.5350 │\n","│ 292/301 │ 0.8340 │\n","│ 293/301 │ 0.8340 │\n","│ 294/301 │ 0.4420 │\n","│ 295/301 │ 1.0400 │\n","│ 296/301 │ 1.0400 │\n","│ 297/301 │ 0.5880 │\n","│ 298/301 │ 0.4010 │\n","│ 299/301 │ 0.4010 │\n","│ 300/301 │ 0.9350 │\n","│ 301/301 │ 0.9350 │\n","└──────────────┴──────────────┘\n","\n","Last 10 losses:\n"," Step 292 → loss = 0.8340\n"," Step 293 → loss = 0.8340\n"," Step 294 → loss = 0.4420\n"," Step 295 → loss = 1.0400\n"," Step 296 → loss = 1.0400\n"," Step 297 → loss = 0.5880\n"," Step 298 → loss = 0.4010\n"," Step 299 → loss = 0.4010\n"," Step 300 → loss = 0.9350\n"," Step 301 → loss = 0.9350\n","\n","📁 Full training log saved to Drive: /content/drive/MyDrive/flux_klein_colorize_lora_log_20260421_194257.txt\n","\n","🎉 TRAINING COMPLETE!\n","LoRA saved to: /content/flux_klein_colorize_lora\n","✅ LoRA ZIP saved to Drive: /content/drive/MyDrive/flux_klein_colorize_lora_20260421_194257.zip\n","\n","✅ CELL 6 complete!\n"]}]},{"cell_type":"markdown","metadata":{"id":"8h4peBAYFzV6"},"source":["# ⚙️ Quantize Klein Edit AIO (GPU)"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":39032,"status":"ok","timestamp":1776809493020,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"},"user_tz":-120},"id":"zA8tl2ZLFzV6","outputId":"2038f697-43be-4ebd-ed73-15fb0bce9d99"},"outputs":[{"name":"stdout","output_type":"stream","text":["Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n","🧹 Removing old diffusers...\n","🔄 Installing latest diffusers...\n"," Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n"," Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n"," Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n"," Building wheel for diffusers (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","Files removed: 6\n","✅ Cell 1 complete!\n"]}],"source":["# =============================================================================\n","#@markdown # **CELL 1**: Mount Drive + HF auth\n","# =============================================================================\n","\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","import shutil\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n","else:\n"," print(\"⚠️ No HF_TOKEN found in secrets.\")\n","\n","print(\"🧹 Removing old diffusers...\")\n","!pip uninstall -y diffusers > /dev/null 2>&1\n","!rm -rf /usr/local/lib/python3.12/dist-packages/diffusers* ~/.cache/pip/*diffusers*\n","\n","print(\"🔄 Installing latest diffusers...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!python -m pip cache purge\n","\n","print(\"✅ Cell 1 complete!\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":8,"status":"ok","timestamp":1776809493169,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"},"user_tz":-120},"id":"oASypGDAFzV7","outputId":"74faab46-b2fc-4d42-f8ed-2b742bcb7b3c"},"outputs":[{"name":"stdout","output_type":"stream","text":["✅ Cell 2 settings loaded\n"," Resolution: 1024×1024\n"," Use .txt prompts: False\n"," Debug mode: False\n","\n","Now run Cell 3 (model load), then Cell 4 (inference)\n"]}],"source":["# =============================================================================\n","#@markdown # **CELL 2**: Fixed settings (resolution + options)\n","# =============================================================================\n","\n","resolution = '1024 x 1024 (Square)' #@param [\"1024 x 1024 (Square)\", \"512 x 1024 (Portrait)\", \"768 x 1024 (Slight Portrait)\", \"1536 x 1024 (Landscape)\", \"2048 x 1024 (Wide Landscape)\"] {type:\"string\"}\n","use_txt_prompts = False #@param {type:\"boolean\"}\n","debug = False #@param {type:\"boolean\"}\n","\n","res_map = {\n"," \"1024 x 1024 (Square)\": (1024, 1024),\n"," \"512 x 1024 (Portrait)\": (512, 1024),\n"," \"768 x 1024 (Slight Portrait)\": (768, 1024),\n"," \"1536 x 1024 (Landscape)\": (1536, 1024),\n"," \"2048 x 1024 (Wide Landscape)\": (2048, 1024)\n","}\n","target_width, target_height = res_map[resolution]\n","\n","print(\"✅ Cell 2 settings loaded\")\n","print(f\" Resolution: {target_width}×{target_height}\")\n","print(f\" Use .txt prompts: {use_txt_prompts}\")\n","print(f\" Debug mode: {debug}\")\n","print(\"\\nNow run Cell 3 (model load), then Cell 4 (inference)\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"sT7EYxbtQsEA"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 3: Quantize official FLUX.2-klein-4B (Distill) → 4-bit SDNQ Dynamic + Upload**\n","#@markdown • Correct classes for Klein (`Flux2Transformer2DModel` + `Qwen3ForCausalLM`)\n","#@markdown • Quantizes **only the weights** (transformer + text_encoder) with exact same SDNQ 4-bit dynamic as Disty0\n","#@markdown • `low_cpu_mem_usage=True` everywhere + explicit CPU move before save → T4 safe, no OOM\n","#@markdown • Matches `Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic` exactly\n","# =============================================================================\n","\n","from google.colab import userdata\n","from huggingface_hub import login, HfApi, create_repo\n","import torch\n","import gc\n","import os\n","import shutil\n","\n","# -------------------------- HF Login --------------------------\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n"," print(\"✅ Logged into Hugging Face\")\n","else:\n"," raise ValueError(\"⚠️ HF_TOKEN not found in Colab secrets. Add it in Secrets.\")\n","\n","# -------------------------- Settings --------------------------\n","#@markdown **Which official Klein variant to quantize?** (Distill = the one you chose before)\n","model_variant = \"Distill\" #@param [\"Base\", \"Distill\"] {type:\"string\"}\n","\n","if model_variant == \"Base\":\n"," base_pipeline_repo = \"black-forest-labs/FLUX.2-klein-base-4B\"\n","else:\n"," base_pipeline_repo = \"black-forest-labs/FLUX.2-klein-4B\"\n","\n","#@markdown **Repo name on your account** (will be created if it doesn't exist)\n","repo_id = \"codeshare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic\" #@param {type:\"string\"}\n","\n","#@markdown **Torch dtype**\n","torch_dtype = torch.float16 #@param [\"torch.float16\", \"torch.bfloat16\"] {type:\"raw\"}\n","\n","local_save_path = \"/content/quantized_flux2_klein_aio_sdnq\"\n","\n","# -------------------------- Install latest diffusers + sdnq --------------------------\n","print(\"🧹 Removing old diffusers...\")\n","!pip uninstall -y diffusers > /dev/null 2>&1\n","!rm -rf /usr/local/lib/python3.12/dist-packages/diffusers* ~/.cache/pip/*diffusers*\n","\n","print(\"🔄 Installing latest diffusers + sdnq...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!pip install -q sdnq\n","!python -m pip cache purge\n","\n","# -------------------------- Correct Imports for Klein --------------------------\n","from diffusers import Flux2KleinPipeline, Flux2Transformer2DModel\n","from transformers import Qwen3ForCausalLM\n","from sdnq import SDNQConfig\n","from sdnq.common import use_torch_compile as triton_is_available\n","from sdnq.loader import apply_sdnq_options_to_model\n","\n","# -------------------------- SDNQ 4-bit dynamic config (exact match to Disty0) --------------------------\n","print(\"⚙️ Creating SDNQ 4-bit dynamic config...\")\n","sdnq_config = SDNQConfig(\n"," use_dynamic_quantization=True,\n"," weights_dtype=\"uint4\",\n"," dynamic_loss_threshold=1e-2,\n"," use_svd=False,\n"," group_size=0,\n"," quantization_device=\"cuda\",\n"," return_device=\"cuda\",\n"," quant_conv=False,\n"," quant_embedding=False,\n",")\n","\n","print(\"✅ SDNQ 4-bit dynamic config created (matches Disty0)\")\n","\n","# -------------------------- Quantize transformer --------------------------\n","print(f\"🔄 Loading + quantizing transformer from official repo ({base_pipeline_repo})...\")\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","print(f\" VRAM before: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","transformer = Flux2Transformer2DModel.from_pretrained(\n"," base_pipeline_repo,\n"," subfolder=\"transformer\",\n"," quantization_config=sdnq_config,\n"," torch_dtype=torch_dtype,\n"," low_cpu_mem_usage=True,\n",")\n","\n","print(f\"✅ Transformer quantized! VRAM now: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# -------------------------- Quantize text_encoder (Qwen3) --------------------------\n","print(f\"🔄 Loading + quantizing text_encoder (Qwen3) from official repo...\")\n","\n","text_encoder = Qwen3ForCausalLM.from_pretrained(\n"," base_pipeline_repo,\n"," subfolder=\"text_encoder\",\n"," quantization_config=sdnq_config,\n"," torch_dtype=torch_dtype,\n"," low_cpu_mem_usage=True,\n",")\n","\n","print(f\"✅ Text encoder quantized! VRAM now: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# -------------------------- Build pipeline --------------------------\n","print(f\" → Building Flux2KleinPipeline from {base_pipeline_repo}...\")\n","\n","pipe = Flux2KleinPipeline.from_pretrained(\n"," base_pipeline_repo,\n"," transformer=transformer,\n"," text_encoder=text_encoder,\n"," torch_dtype=torch_dtype,\n"," low_cpu_mem_usage=True,\n"," device_map=None,\n",")\n","\n","print(f\"✅ Full pipeline ready (quantized weights only)! VRAM now: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# -------------------------- Optional: INT8 MatMul (skip during save to save VRAM) --------------------------\n","# We apply it in Cell 4 (inference) instead\n","\n","# -------------------------- Save with explicit CPU move (prevents OOM) --------------------------\n","print(\"🧹 Moving model to CPU before save to avoid any OOM...\")\n","pipe = pipe.to(\"cpu\")\n","gc.collect()\n","torch.cuda.empty_cache()\n","print(f\" VRAM before save: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","print(f\"💾 Saving quantized pipeline to {local_save_path}...\")\n","if os.path.exists(local_save_path):\n"," shutil.rmtree(local_save_path)\n","pipe.save_pretrained(local_save_path)\n","\n","print(\"✅ Pipeline saved locally\")\n","\n","# -------------------------- Push to HF --------------------------\n","print(f\"🚀 Uploading to https://huggingface.co/{repo_id} ...\")\n","api = HfApi()\n","create_repo(repo_id, exist_ok=True, private=False)\n","\n","api.upload_folder(\n"," folder_path=local_save_path,\n"," repo_id=repo_id,\n"," repo_type=\"model\",\n"," commit_message=\"SDNQ 4-bit dynamic quantized FLUX.2-klein-4B (official repo + correct classes, matches Disty0)\",\n",")\n","\n","print(\"🎉 DONE!\")\n","print(f\"✅ Quantized model live at: https://huggingface.co/{repo_id}\")\n","\n","# -------------------------- Cleanup --------------------------\n","gc.collect()\n","torch.cuda.empty_cache()\n","print(\"🧹 Cleanup complete\")"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"background_save":true},"id":"GGlGCB-DTlMz"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 4: Upload quantized model to your HF repo (codeShare)**\n","#@markdown • Only uploads the already-saved folder (no re-quantization)\n","#@markdown • Uses your correct username `codeShare` (capital S)\n","#@markdown • Change repo name below if you want something else\n","# =============================================================================\n","\n","from huggingface_hub import HfApi, create_repo\n","from google.colab import userdata\n","import os\n","\n","# -------------------------- HF Login (just in case) --------------------------\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," from huggingface_hub import login\n"," login(token=hf_token)\n"," print(\"✅ Logged into Hugging Face\")\n","else:\n"," raise ValueError(\"⚠️ HF_TOKEN not found in Colab secrets.\")\n","\n","# -------------------------- Settings --------------------------\n","#@markdown **Your exact HF username (already set correctly)**\n","repo_id = \"codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic\" #@param {type:\"string\"}\n","\n","local_save_path = \"/content/quantized_flux2_klein_aio_sdnq\"\n","\n","# -------------------------- Create repo + Upload --------------------------\n","print(f\"🚀 Uploading to https://huggingface.co/{repo_id} ...\")\n","\n","api = HfApi()\n","create_repo(repo_id, exist_ok=True, private=False)\n","\n","api.upload_folder(\n"," folder_path=local_save_path,\n"," repo_id=repo_id,\n"," repo_type=\"model\",\n"," commit_message=\"SDNQ 4-bit dynamic quantized FLUX.2-klein-4B (official repo, matches Disty0)\",\n",")\n","\n","print(\"🎉 DONE!\")\n","print(f\"✅ Quantized model is now live at: https://huggingface.co/{repo_id}\")\n","print(\"\\nYou can now use it in Cell 4 (inference) exactly like Disty0:\")\n","print(f'pipe = Flux2KleinPipeline.from_pretrained(\"{repo_id}\", torch_dtype=torch.float16)')\n","print(\"pipe.transformer = apply_sdnq_options_to_model(pipe.transformer, use_quantized_matmul=True)\")\n","print(\"pipe.text_encoder = apply_sdnq_options_to_model(pipe.text_encoder, use_quantized_matmul=True)\")\n","print(\"pipe.enable_model_cpu_offload()\")"]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776813501802},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776796861814},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776795061697},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776794307247},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776790556621},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776789720072},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776787634021},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776773678064},{"file_id":"151XI3nRFxLRbwRc8V6OfWyqp-zTnfySv","timestamp":1776764241991},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_edit.ipynb","timestamp":1776702729526},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/vertical_slice_prepper.ipynb","timestamp":1776687886662},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/vertical_slice_prepper.ipynb","timestamp":1776366149549},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776287741995},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776178739426},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776027716448},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1773663661932},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773663290922},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773264797996},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773163850245},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773090196076},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773089575687},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773080355474},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1772998638620},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1763646205520},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1760993725927},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760450712160},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1756712618300},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1747490904984},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1740037333374},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1736477078136},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1725365086834}],"collapsed_sections":["_zmT9hq3WRn_","BsPp1a4wXTbf","4PjK9a8Sni3A","kVAe29swHo4I","HX3I-YqowwO9","Sl3MykNlqAop","AOicVDnxWOhD","8h4peBAYFzV6"],"gpuType":"T4"},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":0} \ No newline at end of file +{"cells":[{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"r6q_m-6Pmm5w"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Set path to zip file on your drive , and set klein edit prompt\n","input_zip_path = '' #@param {type:'string'}\n","zip_path = input_zip_path\n","edit_prompt = 'make sure the bare skin against the very dark background looks like a real photo. remove the background at the centre so that it has the same color as the corners. remove the corners. remove the background. the background is a single color. ' #@param }¥{type:'string'}"],"metadata":{"id":"K13pRro0lxAw","executionInfo":{"status":"ok","timestamp":1776816412767,"user_tz":-120,"elapsed":38,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"execution_count":15,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"HX3I-YqowwO9"},"source":["# ⚙️ Run Klein Edit (GPU)"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"OXGhsHQwWue_"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 1**: Mount Drive + HF auth\n","# =============================================================================\n","\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","import shutil\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n","else:\n"," print(\"⚠️ No HF_TOKEN found in secrets.\")\n","\n","print(\"🧹 Removing old diffusers...\")\n","!pip uninstall -y diffusers > /dev/null 2>&1\n","!rm -rf /usr/local/lib/python3.12/dist-packages/diffusers* ~/.cache/pip/*diffusers*\n","\n","print(\"🔄 Installing latest diffusers...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!python -m pip cache purge\n","\n","print(\"✅ Cell 1 complete!\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"a1wZv8PrXAe2"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 2**: Fixed settings (resolution + options)\n","# =============================================================================\n","\n","resolution = '1024 x 1024 (Square)' #@param [\"1024 x 1024 (Square)\", \"512 x 1024 (Portrait)\", \"768 x 1024 (Slight Portrait)\", \"1536 x 1024 (Landscape)\", \"2048 x 1024 (Wide Landscape)\"] {type:\"string\"}\n","use_txt_prompts = False #@param {type:\"boolean\"}\n","debug = False #@param {type:\"boolean\"}\n","\n","res_map = {\n"," \"1024 x 1024 (Square)\": (1024, 1024),\n"," \"512 x 1024 (Portrait)\": (512, 1024),\n"," \"768 x 1024 (Slight Portrait)\": (768, 1024),\n"," \"1536 x 1024 (Landscape)\": (1536, 1024),\n"," \"2048 x 1024 (Wide Landscape)\": (2048, 1024)\n","}\n","target_width, target_height = res_map[resolution]\n","\n","print(\"✅ Cell 2 settings loaded\")\n","print(f\" Resolution: {target_width}×{target_height}\")\n","print(f\" Use .txt prompts: {use_txt_prompts}\")\n","print(f\" Debug mode: {debug}\")\n","print(\"\\nNow run Cell 3 (model load), then Cell 4 (inference)\")"]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 3**: Load YOUR QUANTIZED Flux2KleinPipeline (codeShare) + SDNQ optimizations\n","# =============================================================================\n","\n","import torch\n","import gc\n","from diffusers import Flux2KleinPipeline\n","\n","print(\"📦 Installing sdnq...\")\n","!pip install -q sdnq\n","\n","from sdnq.common import use_torch_compile as triton_is_available\n","from sdnq.loader import apply_sdnq_options_to_model\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","print(\"🔄 Loading YOUR quantized model: codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic\")\n","pipe = Flux2KleinPipeline.from_pretrained(\n"," \"codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic\",\n"," torch_dtype=torch.float16\n",")\n","\n","print(f\"✅ Pipeline loaded – VRAM: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# ====================== Optimizations for T4 ======================\n","print(\"🔥 Applying SDNQ + T4 optimizations...\")\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","\n","if triton_is_available and torch.cuda.is_available():\n"," pipe.transformer = apply_sdnq_options_to_model(pipe.transformer, use_quantized_matmul=True)\n"," pipe.text_encoder = apply_sdnq_options_to_model(pipe.text_encoder, use_quantized_matmul=True)\n"," print(\" ✅ INT8 MatMul enabled\")\n","\n","pipe.enable_model_cpu_offload()\n","pipe.vae.enable_slicing()\n","pipe.vae.enable_tiling()\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","torch.cuda.reset_peak_memory_stats()\n","\n","print(\"✅ Cell 3 complete – your model is ready!\")\n","print(\" Now go to Cell 4 and run it (you can change zip/prompt in Cell 4 and re-run Cell 4 only)\")"],"metadata":{"id":"e8YfZ9NkaguO"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 4**: MULTI-IMAGE INFERENCE (Klein Edit with custom/gray reference)\n","# • First image = your original (the one being edited)\n","# • Second image = custom uploaded OR solid #181818 gray square\n","# • Re-run this cell only after changing settings\n","# =============================================================================\n","import zipfile\n","import os\n","import shutil\n","import glob # Added: Import glob module\n","from PIL import Image, ImageDraw # Added: Import Image and ImageDraw for image manipulation\n","import torch\n","import gc\n","import datetime\n","from google.colab import files # Added: Import files for file upload\n","\n","#edit_prompt = 'remove the background. the background is gray.' #@param {type:\"string\"}\n","#zip_path = '/content/drive/MyDrive/aiotest.zip' #@param {type:\"string\"}\n","upload_custom_reference = False #@param {type:\"boolean\"}\n","max_image_dimension = 2048 #@param {type:\"slider\", min:512, max:4096, step:256}\n","add_gray_corners = True #@param {type:\"boolean\"}\n","gray_square_size = 50 #@param {type:\"slider\", min:10, max:200, step:10}\n","\n","output_folder = '/content/edited_images_multi'\n","\n","print(\"🧹 Clearing old temporary folders...\")\n","if os.path.exists('/content/input_images'):\n"," shutil.rmtree('/content/input_images')\n","if os.path.exists(output_folder):\n"," shutil.rmtree(output_folder)\n","os.makedirs(output_folder, exist_ok=True)\n","\n","# ====================== Unzip + build prompt map ======================\n","print(f\"📦 Unzipping: {zip_path}...\")\n","with zipfile.ZipFile(zip_path, 'r') as z:\n"," z.extractall('/content/input_images')\n","\n","image_files = sorted(glob.glob('/content/input_images/*.*'))\n","image_files = [f for f in image_files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]\n","print(f\"Found {len(image_files)} images.\")\n","\n","prompt_map = {}\n","txt_count = 0\n","for img_path in image_files:\n"," base = os.path.splitext(os.path.basename(img_path))[0]\n"," txt_path = os.path.join('/content/input_images', f\"{base}.txt\")\n"," if use_txt_prompts and os.path.exists(txt_path):\n"," with open(txt_path, 'r', encoding='utf-8') as f:\n"," prompt_map[img_path] = f.read().strip()\n"," txt_count += 1\n"," else:\n"," prompt_map[img_path] = None\n","\n","print(f\"Found {txt_count} matching .txt files\")\n","\n","# ====================== Create or load the second reference image ======================\n","uploaded_reference_filepath = None\n","reference_image_to_pair = None\n","\n","if upload_custom_reference:\n"," print(\"Please upload your reference image now.\")\n"," uploaded_files = files.upload()\n"," if uploaded_files:\n"," uploaded_reference_filepath = list(uploaded_files.keys())[0]\n"," print(f\"✅ Uploaded reference image: {uploaded_reference_filepath}\")\n"," reference_image_to_pair = Image.open(uploaded_reference_filepath).convert(\"RGB\")\n","else:\n"," print(\"🚫 Custom reference disabled → using solid #181818 gray square\")\n"," reference_image_to_pair = Image.new(\"RGB\", (target_width, target_height), \"#181818\")\n","\n","# Clean up temporary upload file\n","if uploaded_reference_filepath and os.path.exists(uploaded_reference_filepath):\n"," os.remove(uploaded_reference_filepath)\n","\n","# ==================== Helper: add gray corner squares ====================\n","def add_corner_squares(image: Image.Image, square_size: int, color=(24, 24, 24)) -> Image.Image:\n"," img_copy = image.copy()\n"," draw = ImageDraw.Draw(img_copy)\n"," width, height = img_copy.size\n"," draw.rectangle([(0, 0), (square_size, square_size)], fill=color)\n"," draw.rectangle([(width - square_size, 0), (width, square_size)], fill=color)\n"," draw.rectangle([(0, height - square_size), (square_size, height)], fill=color)\n"," draw.rectangle([(width - square_size, height - square_size), (width, height)], fill=color)\n"," return img_copy\n","\n","# ====================== BATCH INFERENCE ======================\n","print(f\"\\n🚀 Starting multi-image edit on {len(image_files)} images...\")\n","\n","for i, img_path in enumerate(image_files):\n"," filename = os.path.basename(img_path)\n"," gc.collect()\n"," torch.cuda.empty_cache()\n","\n"," input_image = Image.open(img_path).convert(\"RGB\")\n","\n"," # Resize if too large\n"," if max(input_image.width, input_image.height) > max_image_dimension:\n"," print(f\" ⚠️ Resizing {filename} to max dimension {max_image_dimension}\")\n"," aspect = input_image.width / input_image.height\n"," if input_image.width > input_image.height:\n"," new_w = max_image_dimension\n"," new_h = int(max_image_dimension / aspect)\n"," else:\n"," new_h = max_image_dimension\n"," new_w = int(max_image_dimension * aspect)\n"," input_image = input_image.resize((new_w, new_h), Image.LANCZOS)\n","\n"," if add_gray_corners:\n"," input_image = add_corner_squares(input_image, gray_square_size)\n","\n"," # Multi-image list for Klein Edit\n"," if reference_image_to_pair is not None:\n"," reference_images = [input_image, reference_image_to_pair]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} → + custom/gray reference\")\n"," else:\n"," reference_images = [input_image]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} → (no reference)\")\n","\n"," current_prompt = prompt_map[img_path] if use_txt_prompts and prompt_map[img_path] is not None else edit_prompt\n","\n"," result = pipe(\n"," prompt=current_prompt,\n"," image=reference_images, # ← Klein multi-reference\n"," height=target_height,\n"," width=target_width,\n"," guidance_scale=1.0,\n"," num_inference_steps=4,\n"," generator=torch.Generator(\"cuda\").manual_seed(42),\n"," output_type=\"pil\",\n"," ).images[0]\n","\n"," output_path = os.path.join(output_folder, f\"multi_edited_{filename}\")\n"," result.save(output_path)\n","\n","print(\"\\n→ MULTI-IMAGE BATCH COMPLETE!\")\n","\n","# ====================== ZIP TO DRIVE ======================\n","timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n","drive_zip_path = f\"/content/drive/MyDrive/klein_edited_{timestamp}.zip\"\n","\n","print(f\"📦 Creating zip → {drive_zip_path}\")\n","shutil.make_archive(drive_zip_path.replace('.zip', ''), 'zip', output_folder)\n","\n","print(\"✅ ALL DONE!\")\n","print(f\"Zip saved to Google Drive: {drive_zip_path}\")"],"metadata":{"cellView":"form","id":"KI-qCePZaj_e"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# 🔌 Auto Disconnect from Drive\n","\n","Results from earlier cell have been saved to your drive as\n","'content/drive/MyDrive/klein_processed_(date_number).zip'\n","\n","You can disconnect from the session , and reconnect to new runtime to prevent conflict in installed libraries. you can run this code on CPU"],"metadata":{"id":"7eeX3_qpYpwl"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"FQF71-mvmlc1","cellView":"form"},"outputs":[],"source":["# ================================================\n","#@title 🔌 Auto Disconnect Colab Session\n","# ================================================\n","\n","enable = False #@param {type:'boolean'}\n","if enable:\n"," print(\"🔌 Disconnecting Colab session in 3 seconds...\")\n"," import time\n"," time.sleep(3)\n","\n"," from google.colab import runtime\n"," runtime.unassign()\n","\n"," print(\"Session disconnected.\")"]},{"cell_type":"markdown","source":["# Select Klein processed file to use next"],"metadata":{"id":"s7R3l3-pY5W7"}},{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"ijzwEoboHVPR"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"OdcEXFs4oBt_","cellView":"form"},"outputs":[],"source":["import os\n","\n","klein_edited_zip_path = '/content/drive/MyDrive/klein_processed.zip' #@param {type:'string'}\n","zip_path = klein_edited_zip_path\n","\n","if not os.path.exists(zip_path):\n"," raise FileNotFoundError(f\"❌ Klein edited zip file not found:\\n{zip_path}\\n\\nPlease ensure the path is correct and the file exists in your Drive.\")"]},{"cell_type":"markdown","source":["# ⚙️ Create 1024x1024 frames from selected klein edited set"],"metadata":{"id":"4PjK9a8Sni3A"}},{"cell_type":"code","source":["#@title 🖼️ **Image Background Processor (v1)**\n","#@markdown ---\n","#@markdown ## Enable Processor V1\n","enable_processor_v1 = False #@param {type:\"boolean\"}\n","\n","#@title 🖼️ **Image Background Processor**\n","#(v2 - Solid #181818 Flood-Fill + Auto-Clear)\n","#**Crop left/right empty space + Convert *any* gray background to exact #181818**\n","#@markdown ---\n","#**New**: Automatically clears all previous processed images on re-run\n","#(no more mixing old files when you run again)\n","\n","#Run this cell (Shift + Enter)\n","#Fill the form below\n","#Click **Run**\n","\n","# ==================== FORM PARAMETERS ====================\n","\n","#input_zip_path = \"/content/drive/MyDrive/klein_processed.zip\" #@param {type:\"string\", placeholder:\"Paste full path to your ZIP file here\"}\n","input_zip_path = zip_path\n","\n","tolerance_crop = 50 #@param {type:\"slider\", min:0, max:100, step:1, title:\"🟦 Crop Tolerance (higher = more aggressive cropping)\"}\n","\n","bg_replace_threshold = 20 #@param {type:\"slider\", min:10, max:100, step:1}\n","\n","force_remount = False #@param {type:\"boolean\", title:\"🔄 Force remount Drive (recommended)\"}\n","\n","#@markdown ---\n","\n","\n","if enable_processor_v1:\n"," from google.colab import drive\n"," import zipfile\n"," import os\n"," import shutil # ← NEW for clearing folders\n"," from PIL import Image\n"," from collections import deque\n","\n"," # ========================= CONFIG =========================\n"," TARGET_GRAY = (24, 24, 24) # Exact #181818 - do not change\n"," # =======================================================\n","\n"," print(\"🚀 Starting image processor (Solid Background v2 + Auto-Clear)...\")\n","\n"," # 1. Mount Google Drive\n"," drive.mount('/content/drive', force_remount=force_remount)\n","\n"," # 2. Validate ZIP path\n"," if not input_zip_path or not os.path.exists(input_zip_path):\n"," raise FileNotFoundError(f\"❌ ZIP file not found:\\n{input_zip_path}\\n\\nPlease paste the correct full path (e.g. /content/drive/MyDrive/my_photos.zip)\")\n","\n"," print(f\"✅ ZIP found: {input_zip_path}\")\n","\n"," # 3. Define working folders\n"," extract_dir = '/content/extracted_images'\n"," processed_dir = '/content/processed_images'\n","\n"," # === NEW: Clear previous processed & extracted images on every run ===\n"," for directory in [extract_dir, processed_dir]:\n"," if os.path.exists(directory):\n"," shutil.rmtree(directory)\n"," print(f\"🧹 Cleared old folder: {directory}\")\n"," os.makedirs(extract_dir, exist_ok=True)\n"," os.makedirs(processed_dir, exist_ok=True)\n"," print(\"✅ Fresh folders ready\")\n","\n"," # 4. Unzip\n"," print(\"📦 Unzipping...\")\n"," with zipfile.ZipFile(input_zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n"," print(f\"✅ Unzipped to {extract_dir}\")\n","\n"," # ==================== HELPER 1: Crop only left & right ====================\n"," def crop_left_right(img):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," bg_color = img.getpixel((0, 0))\n","\n"," left = width\n"," right = 0\n","\n"," for x in range(width):\n"," column_is_empty = True\n"," for y in range(height):\n"," px = img.getpixel((x, y))\n"," if any(abs(a - b) > tolerance_crop for a, b in zip(px, bg_color)):\n"," column_is_empty = False\n"," break\n"," if not column_is_empty:\n"," left = min(left, x)\n"," right = max(right, x)\n","\n"," if left >= right:\n"," return img\n","\n"," return img.crop((left, 0, right + 1, height))\n","\n"," # ==================== HELPER 2: FLOOD-FILL BACKGROUND FROM EDGES ====================\n"," def adjust_background(img, original_bg_color):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," pixels = img.load()\n"," threshold = bg_replace_threshold\n","\n"," visited = set()\n"," queue = deque()\n"," directions = [(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if not (dx == 0 and dy == 0)]\n","\n"," # Seed from borders\n"," for x in range(width):\n"," for y in (0, height - 1):\n"," if (x, y) not in visited:\n"," px = pixels[x, y]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," queue.append((x, y))\n"," visited.add((x, y))\n"," pixels[x, y] = TARGET_GRAY\n","\n"," for y in range(height):\n"," for x in (0, width - 1):\n"," if (x, y) not in visited:\n"," px = pixels[x, y]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," queue.append((x, y))\n"," visited.add((x, y))\n"," pixels[x, y] = TARGET_GRAY\n","\n"," # Flood fill\n"," while queue:\n"," x, y = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = x + dx, y + dy\n"," if 0 <= nx < width and 0 <= ny < height and (nx, ny) not in visited:\n"," px = pixels[nx, ny]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," visited.add((nx, ny))\n"," pixels[nx, ny] = TARGET_GRAY\n"," queue.append((nx, ny))\n","\n"," return img\n","\n"," # 5. Process every image\n"," print(\"🖼️ Processing images...\")\n"," image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')\n","\n"," processed_count = 0\n"," for filename in os.listdir(extract_dir):\n"," if filename.lower().endswith(image_extensions):\n"," img_path = os.path.join(extract_dir, filename)\n"," try:\n"," with Image.open(img_path) as original_img:\n"," cropped = crop_left_right(original_img)\n"," orig_bg = original_img.getpixel((0, 0))\n"," processed = adjust_background(cropped, orig_bg)\n","\n"," out_path = os.path.join(processed_dir, filename)\n"," processed.save(out_path, quality=95 if filename.lower().endswith(('.jpg', '.jpeg')) else None)\n","\n"," processed_count += 1\n"," print(f\" ✅ {filename}\")\n"," except Exception as e:\n"," print(f\" ❌ Skipped {filename}: {e}\")\n","\n"," print(f\"\\n🎉 Processed {processed_count} images!\")\n","\n"," # 6. Create final ZIP in Drive\n"," output_zip_name = \"PROCESSED_\" + os.path.basename(zip_path)\n"," output_zip_path = os.path.join(os.path.dirname(zip_path), output_zip_name)\n"," zip_path = output_zip_path\n","\n"," print(f\"📦 Creating final ZIP: {output_zip_name}\")\n"," with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zip_out:\n"," for root, _, files in os.walk(processed_dir):\n"," for file in files:\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, processed_dir)\n"," zip_out.write(file_path, arcname)\n","\n"," print(\"\\n✅ ALL DONE! Solid #181818 background achieved.\")\n"," print(f\"📍 Saved to your Drive at:\\n {output_zip_path}\")\n"],"metadata":{"id":"HN4kta-OpZ4W","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title **🖼️ Image Background Processor V2 (WIP)**\n","#@markdown ---\n","#@markdown ## Enable Processor V2\n","enable_processor_v2 = True #@param {type:\"boolean\"}\n","\n","#@title **🖼️ Image Background Processor V2 (WIP)**\n","#(v2.7 - **Inverse speck removal** + Border-protected forward speck + % Margin + Solid #181818)\n","\n","#**Crop left/right empty space + Convert *any* gray background to exact #181818**\n","#**New in v2.7**:\n","# • **Inverse speck removal**: finds tiny foreground (subject-colored) specks/islands inside the background and replaces them with solid #181818\n","# • Forward speck removal (previous) still protects any #181818 connected to the outer image edge\n","# • Anti-aliasing is guaranteed to be the **very last step** (after both forward + inverse speck removal)\n","# • All previous features (4-corner BG, % margin, checkboxes, distance-based enclosed speck removal) unchanged\n","\n","# ==================== FORM PARAMETERS ====================\n","\n","input_zip_path = zip_path\n","\n","tolerance_crop = 60 #@param {type:\"slider\", min:0, max:100, step:1, title:\"🔵 Crop Tolerance (higher = more aggressive cropping)\"}\n","\n","bg_replace_threshold = 10 #@param {type:\"slider\", min:10, max:100, step:1, title:\"🎨 Legacy absolute threshold (kept for compatibility)\"}\n","\n","# ── % Margin for BG color estimation ──\n","bg_margin_percent = 6 #@param {type:\"slider\", min:0, max:50, step:1, title:\"% Margin for BG color estimation (wider = more tolerant to inner-loop gray variations)\"}\n","\n","# ── Feature Checkboxes ──\n","enable_robust_bg_detection = True #@param {type:\"boolean\", title:\"✅ Use 4-corner robust BG color (best for inner loops)\"}\n","enable_floodfill_background_adjustment = True #@param {type:\"boolean\", title:\"✅ Enable solid #181818 background replacement\"}\n","enable_small_speck_removal = True #@param {type:\"boolean\"}\n","#title:\"✅ Forward speck removal: remove tiny #181818 specks on subject\"}\n","enable_inverse_speck_removal = True #@param {type:\"boolean\"}\n","#title:\"✅ Inverse speck removal: fill tiny subject specks inside background with #181818\"}\n","enable_anti_aliasing = True #@param {type:\"boolean\", title:\"✅ Smooth edges (Gaussian anti-aliasing)\"}\n","\n","anti_aliasing_strength = 6 #@param {type:\"slider\", min:1, max:40, step:1, title:\" ↳ Anti-aliasing Strength (pixels to blend)\"}\n","\n","# ── Forward speck removal (enclosed only) ──\n","min_floodfill_steps = 8 #@param {type:\"slider\", min:1, max:20, step:1, title:\" ↳ Min floodfill steps to foreground (N) for ENCLOSED BG only (outer-edge-connected BG always protected)\"}\n","\n","# ── Inverse speck removal ──\n","max_inverse_speck_size = 10 #@param {type:\"slider\", min:1, max:100, step:1, title:\" ↳ Max size of foreground specks to fill with #181818\"}\n","\n","force_remount = False #@param {type:\"boolean\", title:\"🔄 Force remount Drive\"}\n","\n","#@markdown ---\n","\n","\n","if enable_processor_v2:\n"," from google.colab import drive\n"," import zipfile\n"," import os\n"," import shutil\n"," from PIL import Image, ImageFilter\n"," from collections import deque\n","\n"," # ========================= CONFIG =========================\n"," TARGET_GRAY = (24, 24, 24) # Exact #181818\n"," # =======================================================\n","\n"," print(\"🚀 Starting Image Background Processor v2.7 (Forward + Inverse speck removal)...\")\n","\n"," # 1. Mount Google Drive\n"," drive.mount('/content/drive', force_remount=force_remount)\n","\n"," # 2. Validate ZIP path\n"," if not input_zip_path or not os.path.exists(input_zip_path):\n"," raise FileNotFoundError(f\"❌ ZIP file not found:\\n{input_zip_path}\\n\\nPlease paste the correct full path\")\n","\n"," print(f\"✅ ZIP found: {input_zip_path}\")\n","\n"," # 3. Define working folders\n"," extract_dir = '/content/extracted_images'\n"," processed_dir = '/content/processed_images'\n","\n"," # Clear previous runs\n"," for directory in [extract_dir, processed_dir]:\n"," if os.path.exists(directory):\n"," shutil.rmtree(directory)\n"," print(f\"﹅ Cleared old folder: {directory}\")\n"," os.makedirs(extract_dir, exist_ok=True)\n"," os.makedirs(processed_dir, exist_ok=True)\n"," print(\"✅ Fresh folders ready\")\n","\n"," # 4. Unzip\n"," print(\"🚀 Unzipping...\")\n"," with zipfile.ZipFile(input_zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n"," print(f\"✅ Unzipped to {extract_dir}\")\n","\n"," # ==================== HELPER 1: Crop only left & right ====================\n"," def crop_left_right(img):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n"," width, height = img.size\n"," bg_color = img.getpixel((0, 0))\n"," left = width\n"," right = 0\n"," for x in range(width):\n"," column_is_empty = True\n"," for y in range(height):\n"," px = img.getpixel((x, y))\n"," if any(abs(a - b) > tolerance_crop for a, b in zip(px, bg_color)):\n"," column_is_empty = False\n"," break\n"," if not column_is_empty:\n"," left = min(left, x)\n"," right = max(right, x)\n"," if left >= right:\n"," return img\n"," return img.crop((left, 0, right + 1, height))\n","\n"," # ==================== HELPER 2: FULL BACKGROUND PROCESSOR (v2.7) ====================\n"," def adjust_background(img, original_bg_color,\n"," enable_floodfill_background_adjustment,\n"," enable_small_speck_removal,\n"," enable_inverse_speck_removal,\n"," enable_anti_aliasing,\n"," anti_aliasing_strength,\n"," min_floodfill_steps,\n"," max_inverse_speck_size,\n"," bg_margin_percent):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," pixels_access = img.load()\n"," target_gray = TARGET_GRAY\n"," directions = [(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if not (dx == 0 and dy == 0)]\n","\n"," # 1. Identify foreground using % margin\n"," per_channel_margin = int(255 * (bg_margin_percent / 100.0))\n"," is_foreground = [[False for _ in range(height)] for _ in range(width)]\n"," for y in range(height):\n"," for x in range(width):\n"," px = pixels_access[(x, y)]\n"," is_bg = all(abs(px[i] - original_bg_color[i]) <= per_channel_margin for i in range(3))\n"," if not is_bg:\n"," is_foreground[x][y] = True\n","\n"," # 2. Base image: solid #181818 + foreground\n"," base_processed_img = Image.new(\"RGB\", (width, height), target_gray)\n"," base_processed_pixels = base_processed_img.load()\n"," for y in range(height):\n"," for x in range(width):\n"," if is_foreground[x][y]:\n"," base_processed_pixels[(x, y)] = pixels_access[(x, y)]\n","\n"," # 3. Forward speck removal (border-protected, enclosed only)\n"," if enable_floodfill_background_adjustment and enable_small_speck_removal:\n"," print(\" 🔍 Running forward speck removal (border-protected)...\")\n"," refined_img = base_processed_img.copy()\n"," refined_pixels = refined_img.load()\n","\n"," # Mark border-connected #181818\n"," connected_to_border = [[False] * height for _ in range(width)]\n"," queue = deque()\n"," for x in range(width):\n"," for y_border in [0, height-1]:\n"," if refined_pixels[(x, y_border)] == target_gray and not connected_to_border[x][y_border]:\n"," connected_to_border[x][y_border] = True\n"," queue.append((x, y_border))\n"," for y in range(height):\n"," for x_border in [0, width-1]:\n"," if refined_pixels[(x_border, y)] == target_gray and not connected_to_border[x_border][y]:\n"," connected_to_border[x_border][y] = True\n"," queue.append((x_border, y))\n"," while queue:\n"," cx, cy = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = cx + dx, cy + dy\n"," if 0 <= nx < width and 0 <= ny < height and not connected_to_border[nx][ny] and refined_pixels[(nx, ny)] == target_gray:\n"," connected_to_border[nx][ny] = True\n"," queue.append((nx, ny))\n","\n"," # Distance to foreground (for enclosed BG only)\n"," distance = [[-1] * height for _ in range(width)]\n"," queue = deque()\n"," for y in range(height):\n"," for x in range(width):\n"," if is_foreground[x][y]:\n"," for dx, dy in directions:\n"," nx, ny = x + dx, y + dy\n"," if 0 <= nx < width and 0 <= ny < height and not is_foreground[nx][ny] and distance[nx][ny] == -1:\n"," distance[nx][ny] = 1\n"," queue.append((nx, ny))\n"," break\n"," while queue:\n"," cx, cy = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = cx + dx, cy + dy\n"," if 0 <= nx < width and 0 <= ny < height and not is_foreground[nx][ny] and distance[nx][ny] == -1:\n"," distance[nx][ny] = distance[cx][cy] + 1\n"," queue.append((nx, ny))\n","\n"," # Revert only enclosed + too-close BG pixels\n"," for y in range(height):\n"," for x in range(width):\n"," if refined_pixels[(x, y)] == target_gray:\n"," if not connected_to_border[x][y] and (distance[x][y] == -1 or distance[x][y] < min_floodfill_steps):\n"," refined_pixels[(x, y)] = pixels_access[(x, y)]\n","\n"," base_processed_img = refined_img\n"," base_processed_pixels = base_processed_img.load()\n","\n"," # 4. INVERSE speck removal (tiny foreground specks inside background → #181818)\n"," if enable_floodfill_background_adjustment and enable_inverse_speck_removal:\n"," print(\" 🔍 Running inverse speck removal (small FG specks → #181818)...\")\n"," refined_img = base_processed_img.copy()\n"," refined_pixels = refined_img.load()\n"," visited = [[False] * height for _ in range(width)]\n","\n"," for y in range(height):\n"," for x in range(width):\n"," if refined_pixels[(x, y)] != target_gray and not visited[x][y]:\n"," component = []\n"," queue = deque([(x, y)])\n"," visited[x][y] = True\n"," while queue:\n"," cx, cy = queue.popleft()\n"," component.append((cx, cy))\n"," for dx, dy in directions:\n"," nx, ny = cx + dx, cy + dy\n"," if 0 <= nx < width and 0 <= ny < height and not visited[nx][ny] and refined_pixels[(nx, ny)] != target_gray:\n"," visited[nx][ny] = True\n"," queue.append((nx, ny))\n"," # Fill small foreground specks with solid #181818\n"," if len(component) < max_inverse_speck_size:\n"," for px, py in component:\n"," refined_pixels[(px, py)] = target_gray\n","\n"," base_processed_img = refined_img\n"," base_processed_pixels = base_processed_img.load()\n","\n"," # 5. Anti-aliasing – ALWAYS LAST (as requested)\n"," if not enable_anti_aliasing:\n"," return base_processed_img\n","\n"," mask = Image.new(\"L\", (width, height), 0)\n"," mask_pixels = mask.load()\n"," for y in range(height):\n"," for x in range(width):\n"," if base_processed_pixels[(x, y)] != target_gray:\n"," mask_pixels[(x, y)] = 255\n","\n"," blur_radius = anti_aliasing_strength / 2.0\n"," blurred_mask = mask.filter(ImageFilter.GaussianBlur(radius=blur_radius))\n","\n"," solid_bg = Image.new(\"RGB\", (width, height), target_gray)\n"," final_img_with_aa = Image.composite(base_processed_img, solid_bg, blurred_mask)\n","\n"," return final_img_with_aa\n","\n"," # ==================== MAIN PROCESSING LOOP ====================\n"," print(\"🚀 Processing images...\")\n"," image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')\n","\n"," processed_count = 0\n"," for filename in os.listdir(extract_dir):\n"," if filename.lower().endswith(image_extensions):\n"," img_path = os.path.join(extract_dir, filename)\n"," try:\n"," with Image.open(img_path) as original_img:\n"," # === ROBUST BACKGROUND COLOR DETECTION ===\n"," cropped = crop_left_right(original_img)\n"," if cropped.mode != 'RGB':\n"," cropped = cropped.convert('RGB')\n","\n"," if enable_robust_bg_detection:\n"," w, h = cropped.size\n"," samples = [\n"," cropped.getpixel((0, 0)),\n"," cropped.getpixel((w-1, 0)),\n"," cropped.getpixel((0, h-1)),\n"," cropped.getpixel((w-1, h-1))\n"," ]\n"," orig_bg = tuple(sum(c) // len(samples) for c in zip(*samples))\n"," print(f\" 📍 Using robust 4-corner BG color for {filename}\")\n"," else:\n"," orig_bg = cropped.getpixel((0, 0))\n","\n"," # === PROCESS IMAGE ===\n"," if enable_floodfill_background_adjustment:\n"," processed = adjust_background(\n"," cropped,\n"," orig_bg,\n"," enable_floodfill_background_adjustment,\n"," enable_small_speck_removal,\n"," enable_inverse_speck_removal,\n"," enable_anti_aliasing,\n"," anti_aliasing_strength,\n"," min_floodfill_steps,\n"," max_inverse_speck_size,\n"," bg_margin_percent\n"," )\n"," else:\n"," processed = cropped\n","\n"," out_path = os.path.join(processed_dir, filename)\n"," processed.save(out_path, quality=95 if filename.lower().endswith(('.jpg', '.jpeg')) else None)\n","\n"," processed_count += 1\n"," print(f\" ✅ {filename}\")\n","\n"," except Exception as e:\n"," print(f\" ❌ Skipped {filename}: {e}\")\n","\n"," print(f\"\\n🎉 Processed {processed_count} images!\")\n","\n"," # 6. Create final ZIP\n"," output_zip_name = \"PROCESSED_\" + os.path.basename(input_zip_path)\n"," output_zip_path = os.path.join(os.path.dirname(input_zip_path), output_zip_name)\n","\n"," print(f\"🚀 Creating final ZIP: {output_zip_name}\")\n"," with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zip_out:\n"," for root, _, files in os.walk(processed_dir):\n"," for file in files:\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, processed_dir)\n"," zip_out.write(file_path, arcname)\n","\n"," print(\"\\n✅ ALL DONE! Solid #181818 everywhere (forward + inverse specks cleaned) + smooth AA last\")\n"," print(f\"📍 Saved to your Drive at:\\n {output_zip_path}\")\n"],"metadata":{"cellView":"form","id":"tFGWg7jNv4mo"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# ⚙️ Create composites"],"metadata":{"id":"kVAe29swHo4I"}},{"cell_type":"code","source":["#@markdown Set zip file input path for making composites\n","input_zip_path = \"/content/drive/MyDrive/PROCESSED_klein_processed.zip\" #@param {type:'string'}\n","zip_file_path = input_zip_path"],"metadata":{"id":"IXQKiBVrNPcE"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"93JpoQJ77NGu","cellView":"form"},"outputs":[],"source":["# ────────────────────────────────────────────────\n","# 🎨 CLEAN ROW → PURE 1024x1024 FRAMES (NO DISTORTION)\n","# ────────────────────────────────────────────────\n","\n","#@markdown ## ⚙️ Main Settings\n","num_frames = 100 #@param {type:\"slider\", min:10, max:2000, step:10}\n","overlap_percent = 0 #@param {type:\"slider\", min:0, max:50, step:1}\n","min_step_ratio = 0.8 #@param {type:\"slider\", min:0.5, max:1.0, step:0.05}\n","max_step_ratio = 1.0 #@param {type:\"slider\", min:0.8, max:1.5, step:0.05}\n","\n","#@markdown ## 🧱 Border\n","border_width = 8 #@param {type:\"slider\", min:0, max:100}\n","\n","#@markdown ## 💾 Input / Output\n","save_to_google_drive = True #@param {type:\"boolean\"}\n","drive_folder_name = \"vertical_slices_output\" #@param {type:\"string\"}\n","# ────────────────────────────────────────────────\n","\n","FRAME_SIZE = 1024\n","INNER_SIZE = FRAME_SIZE - 2 * border_width\n","BORDER_COLOR = (24, 24, 24)\n","\n","import os, random, zipfile\n","import numpy as np\n","from PIL import Image\n","from google.colab import drive\n","\n","# ────────────────────────────────────────────────\n","# Mount Drive\n","# ────────────────────────────────────────────────\n","\n","drive_mounted = False\n","if save_to_google_drive:\n"," try:\n"," drive.mount('/content/drive', force_remount=False)\n"," drive_mounted = True\n"," drive_output_dir = os.path.join(\"/content/drive/MyDrive\", drive_folder_name)\n"," os.makedirs(drive_output_dir, exist_ok=True)\n"," print(\"Drive mounted\")\n"," except:\n"," save_to_google_drive = False\n","\n","# ────────────────────────────────────────────────\n","# Extract ZIP\n","# ────────────────────────────────────────────────\n","\n","extract_root = \"/content/extracted_images\"\n","output_dir = \"/content/frames\"\n","\n","os.makedirs(extract_root, exist_ok=True)\n","os.makedirs(output_dir, exist_ok=True)\n","\n","with zipfile.ZipFile(zip_file_path, 'r') as zf:\n"," zf.extractall(extract_root)\n","\n","# ────────────────────────────────────────────────\n","# Load images\n","# ────────────────────────────────────────────────\n","\n","valid_exts = ('.jpg','.jpeg','.png','.webp')\n","all_sources = []\n","\n","for root, _, files in os.walk(extract_root):\n"," for f in files:\n"," if f.lower().endswith(valid_exts):\n"," all_sources.append(os.path.join(root, f))\n","\n","print(\"Images found:\", len(all_sources))\n","\n","# ────────────────────────────────────────────────\n","# Build row UNTIL enough width\n","# ────────────────────────────────────────────────\n","\n","def build_row_until_width(all_sources, target_h, overlap_ratio, required_width):\n"," canvas = Image.new(\"RGB\", (required_width, target_h))\n"," x = 0\n","\n"," while x < required_width:\n"," src = random.choice(all_sources)\n","\n"," try:\n"," im = Image.open(src).convert(\"RGB\")\n"," w, h = im.size\n","\n"," scale = target_h / h\n"," new_w = int(w * scale)\n","\n"," im = im.resize((new_w, target_h), Image.LANCZOS)\n","\n"," # overlap\n"," if x > 0:\n"," x -= int(new_w * overlap_ratio)\n","\n"," canvas.paste(im, (x, 0))\n"," x += new_w\n","\n"," except:\n"," continue\n","\n"," return canvas\n","\n","# ────────────────────────────────────────────────\n","# Calculate required width\n","# ────────────────────────────────────────────────\n","\n","overlap_ratio = overlap_percent / 100.0\n","\n","avg_step = (min_step_ratio + max_step_ratio) / 2\n","estimated_width = int(num_frames * INNER_SIZE * avg_step * 1.2)\n","\n","print(\"Building row width:\", estimated_width)\n","\n","row_img = build_row_until_width(\n"," all_sources,\n"," INNER_SIZE,\n"," overlap_ratio,\n"," estimated_width\n",")\n","\n","row_np = np.array(row_img)\n","row_h, row_w = row_np.shape[:2]\n","\n","# ────────────────────────────────────────────────\n","# Generate frames (NO distortion)\n","# ────────────────────────────────────────────────\n","\n","frame_idx = 0\n","x_cursor = 0\n","\n","while x_cursor + INNER_SIZE <= row_w and frame_idx < num_frames:\n","\n"," step = random.randint(\n"," int(INNER_SIZE * min_step_ratio),\n"," int(INNER_SIZE * max_step_ratio)\n"," )\n","\n"," crop = row_np[:, x_cursor:x_cursor + INNER_SIZE]\n","\n"," final = Image.new(\"RGB\", (FRAME_SIZE, FRAME_SIZE), BORDER_COLOR)\n"," final.paste(Image.fromarray(crop), (border_width, border_width))\n","\n"," fname = f\"frame_{frame_idx:04d}.jpg\"\n"," final.save(os.path.join(output_dir, fname), \"JPEG\", quality=90)\n","\n"," frame_idx += 1\n"," x_cursor += step\n","\n"," if frame_idx % 50 == 0:\n"," print(frame_idx, \"frames done\")\n","\n","print(\"Finished:\", frame_idx)\n","\n","# ────────────────────────────────────────────────\n","# Save ZIP\n","# ────────────────────────────────────────────────\n","\n","if save_to_google_drive and drive_mounted:\n","\n"," zip_path = \"/content/output.zip\"\n"," drive_path = os.path.join(drive_output_dir, \"vertical_slices.zip\")\n","\n"," with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:\n"," for f in os.listdir(output_dir):\n"," if f.endswith(\".jpg\"):\n"," zf.write(os.path.join(output_dir, f), arcname=f)\n","\n"," !cp -f \"{zip_path}\" \"{drive_path}\"\n","\n"," print(\"Saved to Drive:\", drive_path)"]},{"cell_type":"markdown","source":["# Done!\n","\n","In the zip file /content/drive/MyDrive/vertical_slices_output/vertical_slices.zip , there you will find 100 image composites to choose for lora training\n","\n","//-----//"],"metadata":{"id":"tJlvhf9xDmA7"}},{"cell_type":"markdown","source":["# Quantized Img2img lora training klein 4B (Ostris AI toolkit) WIP"],"metadata":{"id":"Sl3MykNlqAop"}},{"cell_type":"code","source":["#@markdown # **CELL 1**: Mount Drive + HF auth + Global Debug\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n"," if debug: print(\"✅ HF login successful – gated FLUX.2-klein-4B download enabled\")\n","else:\n"," if debug: print(\"⚠️ No HF_TOKEN found. You may need to accept the model gate on HF.\")\n","\n","print(\"🧹 Clearing GPU memory...\")\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","if debug:\n"," print(f\" VRAM after cleanup: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","print(\"✅ CELL 1 complete! → Run Cell 2\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"3PEqiDyaqJMe","executionInfo":{"status":"ok","timestamp":1776805017450,"user_tz":-120,"elapsed":31831,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"41a31f88-8633-481b-deae-de64deeb74a6"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Mounted at /content/drive\n","✅ HF login successful – gated FLUX.2-klein-4B download enabled\n","🧹 Clearing GPU memory...\n"," VRAM after cleanup: 0.00 GB\n","✅ CELL 1 complete! → Run Cell 2\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 2 (FIXED)**: Install Ostris AI Toolkit + Torch for Colab\n","\n","import os\n","debug = True #@param {type:\"boolean\"}\n","\n","%cd /content\n","!git clone https://github.com/ostris/ai-toolkit.git --depth 1 # faster clone\n","%cd ai-toolkit\n","\n","print(\"🔄 Installing Torch for Colab CUDA...\")\n","!pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 -q\n","\n","print(\"🔄 Installing AI Toolkit requirements...\")\n","!pip install -r requirements.txt -q\n","\n","# Optional but helpful for quantized Klein\n","!pip install bitsandbytes accelerate peft -q\n","\n","if debug:\n"," print(\"\\n\" + \"=\"*70)\n"," print(\"✅ DEBUG: Package versions\")\n"," !pip list | grep -E 'torch|diffusers|peft|accelerate|bitsandbytes|lycoris'\n"," print(\"=\"*70)\n","\n","print(\"✅ CELL 2 FIXED & complete!\")\n","print(\" → **Restart runtime** (Runtime → Restart session)\")\n","print(\" → Then run the fixed Cell 3\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"5sg8uZVDs64s","executionInfo":{"status":"ok","timestamp":1776805123046,"user_tz":-120,"elapsed":105592,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"89e62a52-0432-41a5-b5fd-6e3e16ebe063"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["/content\n","Cloning into 'ai-toolkit'...\n","remote: Enumerating objects: 649, done.\u001b[K\n","remote: Counting objects: 100% (649/649), done.\u001b[K\n","remote: Compressing objects: 100% (520/520), done.\u001b[K\n","remote: Total 649 (delta 82), reused 520 (delta 67), pack-reused 0 (from 0)\u001b[K\n","Receiving objects: 100% (649/649), 30.06 MiB | 30.53 MiB/s, done.\n","Resolving deltas: 100% (82/82), done.\n","/content/ai-toolkit\n","🔄 Installing Torch for Colab CUDA...\n","🔄 Installing AI Toolkit requirements...\n"," Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n"," Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n"," Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m96.5/96.5 kB\u001b[0m \u001b[31m4.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m63.1/63.1 kB\u001b[0m \u001b[31m6.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m60.4/60.4 kB\u001b[0m \u001b[31m4.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.0/61.0 kB\u001b[0m \u001b[31m5.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.2/10.2 MB\u001b[0m \u001b[31m80.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m200.3/200.3 kB\u001b[0m \u001b[31m22.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.5/2.5 MB\u001b[0m \u001b[31m100.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m290.4/290.4 kB\u001b[0m \u001b[31m29.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m109.7/109.7 kB\u001b[0m \u001b[31m12.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m54.9/54.9 kB\u001b[0m \u001b[31m5.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m8.6/8.6 MB\u001b[0m \u001b[31m119.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m894.6/894.6 kB\u001b[0m \u001b[31m55.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m40.5/40.5 MB\u001b[0m \u001b[31m23.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━��━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.1/2.1 MB\u001b[0m \u001b[31m85.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m194.4/194.4 kB\u001b[0m \u001b[31m19.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m37.8/37.8 MB\u001b[0m \u001b[31m24.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.1/1.1 MB\u001b[0m \u001b[31m65.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.6/1.6 MB\u001b[0m \u001b[31m85.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.5/1.5 MB\u001b[0m \u001b[31m33.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m60.7/60.7 MB\u001b[0m \u001b[31m12.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.6/3.6 MB\u001b[0m \u001b[31m56.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m53.8/53.8 kB\u001b[0m \u001b[31m5.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m63.0/63.0 MB\u001b[0m \u001b[31m15.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.0/3.0 MB\u001b[0m \u001b[31m104.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m18.0/18.0 MB\u001b[0m \u001b[31m98.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m50.0/50.0 MB\u001b[0m \u001b[31m13.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.4/1.4 MB\u001b[0m \u001b[31m70.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m44.8/44.8 kB\u001b[0m \u001b[31m4.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m180.7/180.7 kB\u001b[0m \u001b[31m19.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.2/61.2 kB\u001b[0m \u001b[31m6.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h Building wheel for lycoris-lora (setup.py) ... \u001b[?25l\u001b[?25hdone\n"," Building wheel for diffusers (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n","ipython 7.34.0 requires jedi>=0.16, which is not installed.\n","tobler 0.14.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","tobler 0.14.0 requires scipy>=1.13, but you have scipy 1.12.0 which is incompatible.\n","rasterio 1.5.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n","access 1.1.10.post3 requires scipy>=1.14.1, but you have scipy 1.12.0 which is incompatible.\n","shap 0.51.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n","xarray-einstats 0.10.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","xarray-einstats 0.10.0 requires scipy>=1.13, but you have scipy 1.12.0 which is incompatible.\n","jaxlib 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","jaxlib 0.7.2 requires scipy>=1.13, but you have scipy 1.12.0 which is incompatible.\n","cuml-cu12 26.2.0 requires scipy>=1.13.0, but you have scipy 1.12.0 which is incompatible.\n","tsfresh 0.21.1 requires scipy>=1.14.0; python_version >= \"3.10\", but you have scipy 1.12.0 which is incompatible.\n","pytensor 2.38.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","jax 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n","jax 0.7.2 requires scipy>=1.13, but you have scipy 1.12.0 which is incompatible.\n","cupy-cuda12x 14.0.1 requires numpy<2.6,>=2.0, but you have numpy 1.26.4 which is incompatible.\n","opencv-contrib-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\u001b[0m\u001b[31m\n","\u001b[0m\n","======================================================================\n","✅ DEBUG: Package versions\n","accelerate 1.13.0\n","bitsandbytes 0.49.2\n","clip-anytorch 2.6.0\n","dctorch 0.1.2\n","diffusers 0.38.0.dev0\n","lycoris_lora 1.8.3\n","open_clip_torch 3.3.0\n","peft 0.18.1\n","pytorch-fid 0.3.0\n","pytorch-wavelets 1.3.0\n","torch 2.10.0+cu128\n","torchao 0.10.0\n","torchaudio 2.10.0+cu128\n","torchcodec 0.9.1\n","torchdata 0.11.0\n","torchdiffeq 0.2.5\n","torchsde 0.2.6\n","torchsummary 1.5.1\n","torchtune 0.6.1\n","torchvision 0.25.0+cu128\n","======================================================================\n","✅ CELL 2 FIXED & complete!\n"," → **Restart runtime** (Runtime → Restart session)\n"," → Then run the fixed Cell 3\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 3 (FIXED)**: Verify Ostris AI Toolkit\n","\n","import torch\n","import gc\n","import os\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🔄 Verifying after restart...\")\n","\n","# No need to import ai_toolkit — the scripts run directly\n","if os.path.exists(\"/content/ai-toolkit/flux_train_ui.py\"):\n"," print(\"✅ flux_train_ui.py found → toolkit is ready!\")\n","else:\n"," print(\"❌ flux_train_ui.py missing — something went wrong with clone\")\n","\n","if debug:\n"," print(\"\\n\" + \"=\"*80)\n"," print(\"✅ ENVIRONMENT READY FOR QUANTIZED KLEIN IMG2IMG\")\n"," print(\"Torch:\", torch.__version__)\n"," print(f\"VRAM free: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n"," print(\"=\"*80)\n","\n","torch.cuda.empty_cache()\n","gc.collect()\n","print(\"✅ CELL 3 complete! → Run Cell 4\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"kE80uoMbtA7B","executionInfo":{"status":"ok","timestamp":1776805123253,"user_tz":-120,"elapsed":45,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"b8d72235-e623-4536-e137-14bbd17883dd"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🔄 Verifying after restart...\n","✅ flux_train_ui.py found → toolkit is ready!\n","\n","================================================================================\n","✅ ENVIRONMENT READY FOR QUANTIZED KLEIN IMG2IMG\n","Torch: 2.10.0+cu128\n","VRAM free: 0.00 GB\n","================================================================================\n","✅ CELL 3 complete! → Run Cell 4\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 4**: Prepare paired dataset for Klein img2img\n","\n","import os\n","import shutil\n","import glob\n","import zipfile # ←←← THIS WAS MISSING → fixed the crash\n","from PIL import Image\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","training_zip_path = '/content/drive/MyDrive/set1.zip' #@param {type:\"string\"}\n","max_images = 2 #@param {type:\"integer\"}\n","\n","dataset_dir = \"/content/klein_img2img_dataset\"\n","target_dir = f\"{dataset_dir}/target\" # full-color images\n","control_dir = f\"{dataset_dir}/control\" # grayscale condition images\n","\n","print(\"🧹 Clearing old folders...\")\n","if os.path.exists(dataset_dir):\n"," shutil.rmtree(dataset_dir)\n","os.makedirs(target_dir, exist_ok=True)\n","os.makedirs(control_dir, exist_ok=True)\n","\n","print(f\"📦 Unzipping: {training_zip_path}\")\n","with zipfile.ZipFile(training_zip_path, 'r') as z:\n"," z.extractall('/content/raw')\n","\n","image_files = sorted(glob.glob('/content/raw/*.*'))[:max_images]\n","image_files = [f for f in image_files if f.lower().endswith(('.png','.jpg','.jpeg','.webp'))]\n","\n","print(f\"Found {len(image_files)} images → creating paired dataset...\")\n","\n","for i, img_path in enumerate(image_files):\n"," base = os.path.splitext(os.path.basename(img_path))[0]\n","\n"," color_img = Image.open(img_path).convert(\"RGB\")\n"," gray_img = color_img.convert(\"L\").convert(\"RGB\")\n","\n"," color_path = os.path.join(target_dir, f\"{base}.png\")\n"," gray_path = os.path.join(control_dir, f\"{base}.png\")\n","\n"," color_img.save(color_path)\n"," gray_img.save(gray_path)\n","\n"," # Create caption file (required by toolkit)\n"," with open(os.path.join(target_dir, f\"{base}.txt\"), \"w\", encoding=\"utf-8\") as f:\n"," f.write(\"colorize this image\") # or your custom prompt\n","\n"," if debug:\n"," print(f\" ✅ Pair {i+1}: {base}.png (gray control → color target)\")\n","\n","print(f\"✅ Dataset ready – {len(image_files)} pairs\")\n","print(f\" Target → {target_dir}\")\n","print(f\" Control → {control_dir}\")\n","print(\"✅ CELL 4 complete! → Run Cell 5\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"l7UnDSq8sNJP","executionInfo":{"status":"ok","timestamp":1776805137801,"user_tz":-120,"elapsed":4148,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"c3fa4c18-8908-4f95-ff93-eb458fb4beb3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🧹 Clearing old folders...\n","📦 Unzipping: /content/drive/MyDrive/set1.zip\n","Found 2 images → creating paired dataset...\n"," ✅ Pair 1: TA-2026-04-20-23-52-36-988910702213220633-989750588436660545.png (gray control → color target)\n"," ✅ Pair 2: TA-2026-04-20-23-52-36-988910702213220633-989750588436660546.png (gray control → color target)\n","✅ Dataset ready – 2 pairs\n"," Target → /content/klein_img2img_dataset/target\n"," Control → /content/klein_img2img_dataset/control\n","✅ CELL 4 complete! → Run Cell 5\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 5**: Create quantized config.yaml for FLUX.2-klein-4B img2img\n","\n","import yaml\n","import os\n","\n","config = {\n"," \"model\": {\n"," \"name_or_path\": \"black-forest-labs/FLUX.2-klein-base-4B\",\n"," \"is_flux\": True,\n"," \"quantize\": True, # enables 8-bit / 4-bit quantization\n"," \"low_vram\": True, # critical for Colab T4\n"," },\n"," \"training\": {\n"," \"learning_rate\": 1e-4,\n"," \"max_train_steps\": 20,\n"," \"train_batch_size\": 1,\n"," \"gradient_accumulation_steps\": 4,\n"," \"lr_scheduler\": \"constant\",\n"," \"lr_warmup_steps\": 10,\n"," \"rank\": 16,\n"," \"lora_alpha\": 16,\n"," \"use_8bit_adam\": True,\n"," \"mixed_precision\": \"bf16\",\n"," \"gradient_checkpointing\": True,\n"," \"cache_latents\": False, # ←←← CRITICAL for Klein control/edit mode\n"," \"cache_latents_to_disk\": False,\n"," },\n"," \"datasets\": [\n"," {\n"," \"folder_path\": \"/content/klein_img2img_dataset/target\",\n"," \"control_path\": \"/content/klein_img2img_dataset/control\", # correct key for single control image\n"," \"caption_file_extension\": \".txt\",\n"," \"resolution\": 1024,\n"," }\n"," ],\n"," \"output\": {\n"," \"output_dir\": \"/content/flux_klein_colorize_lora\",\n"," \"save_every_n_steps\": 10,\n"," },\n"," \"general\": {\n"," \"seed\": 42,\n"," \"report_to\": \"tensorboard\",\n"," \"skip_final_inference\": True,\n"," }\n","}\n","\n","config_path = \"/content/klein_img2img_quantized_config.yaml\"\n","with open(config_path, \"w\", encoding=\"utf-8\") as f:\n"," yaml.dump(config, f, default_flow_style=False, sort_keys=False)\n","\n","print(\"✅ Quantized Klein img2img config created at:\", config_path)\n","!cat {config_path}\n","print(\"✅ CELL 5 complete! → Run Cell 6\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"EnjnT4XIsSOh","executionInfo":{"status":"ok","timestamp":1776802973666,"user_tz":-120,"elapsed":130,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"da2d03eb-cce1-4dd9-ba0d-84038a3a331a"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["✅ Quantized Klein img2img config created at: /content/klein_img2img_quantized_config.yaml\n","model:\n"," name_or_path: black-forest-labs/FLUX.2-klein-base-4B\n"," is_flux: true\n"," quantize: true\n"," low_vram: true\n","training:\n"," learning_rate: 0.0001\n"," max_train_steps: 20\n"," train_batch_size: 1\n"," gradient_accumulation_steps: 4\n"," lr_scheduler: constant\n"," lr_warmup_steps: 10\n"," rank: 16\n"," lora_alpha: 16\n"," use_8bit_adam: true\n"," mixed_precision: bf16\n"," gradient_checkpointing: true\n"," cache_latents: false\n"," cache_latents_to_disk: false\n","datasets:\n","- folder_path: /content/klein_img2img_dataset/target\n"," control_path: /content/klein_img2img_dataset/control\n"," caption_file_extension: .txt\n"," resolution: 1024\n","output:\n"," output_dir: /content/flux_klein_colorize_lora\n"," save_every_n_steps: 10\n","general:\n"," seed: 42\n"," report_to: tensorboard\n"," skip_final_inference: true\n","✅ CELL 5 complete! → Run Cell 6\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 6**: Launch Ostris Gradio UI\n","\n","print(\"🚀 Starting Ostris Gradio UI for FLUX.2-klein-4B...\")\n","!python flux_train_ui.py"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"uYQyhgwytILG","outputId":"d5f3b5ca-a440-40a4-e42e-8a938b1b0057"},"execution_count":null,"outputs":[{"metadata":{"tags":null},"name":"stdout","output_type":"stream","text":["🚀 Starting Ostris Gradio UI for FLUX.2-klein-4B...\n","/content/ai-toolkit/flux_train_ui.py:286: DeprecationWarning: The 'theme' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'theme' to Blocks.launch() instead.\n"," with gr.Blocks(theme=theme, css=css) as demo:\n","/content/ai-toolkit/flux_train_ui.py:286: DeprecationWarning: The 'css' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'css' to Blocks.launch() instead.\n"," with gr.Blocks(theme=theme, css=css) as demo:\n","* Running on local URL: http://127.0.0.1:7860\n","* Running on public URL: https://0b137bc832de861392.gradio.live\n","\n","This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n","IMG_4592\n","/tmp/gradio/ba4715f59f1408da7d96a62dd1bfad2f5b428d544c1c1a4101d89aa01ecfcea6/IMG_4592.png\n","IMG_4591\n","/tmp/gradio/2ecbd7fe1249c4788737dff2c9ccdee049e8fa7c58c2918a4f0b719630e5e22c/IMG_4591.png\n","Creating dataset\n","Started training\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","/usr/local/lib/python3.12/dist-packages/albumentations/__init__.py:13: UserWarning: A new version of Albumentations is available: 2.0.8 (you have 1.4.15). Upgrade using: pip install -U albumentations. To disable automatic update checks, set the environment variable NO_ALBUMENTATIONS_UPDATE to 1.\n"," check_for_updates()\n","{\n"," \"type\": \"sd_trainer\",\n"," \"training_folder\": \"output\",\n"," \"device\": \"cuda:0\",\n"," \"network\": {\n"," \"type\": \"lora\",\n"," \"linear\": 16,\n"," \"linear_alpha\": 16\n"," },\n"," \"save\": {\n"," \"dtype\": \"float16\",\n"," \"save_every\": 250,\n"," \"max_step_saves_to_keep\": 4,\n"," \"push_to_hub\": false\n"," },\n"," \"datasets\": [\n"," {\n"," \"folder_path\": \"datasets/fe94761a-7b66-4883-982a-96ea87e178a3\",\n"," \"caption_ext\": \"txt\",\n"," \"caption_dropout_rate\": 0.05,\n"," \"shuffle_tokens\": false,\n"," \"cache_latents_to_disk\": true,\n"," \"resolution\": [\n"," 512,\n"," 768,\n"," 1024\n"," ]\n"," }\n"," ],\n"," \"train\": {\n"," \"batch_size\": 1,\n"," \"steps\": 1000,\n"," \"gradient_accumulation_steps\": 1,\n"," \"train_unet\": true,\n"," \"train_text_encoder\": false,\n"," \"gradient_checkpointing\": true,\n"," \"noise_scheduler\": \"flowmatch\",\n"," \"optimizer\": \"adamw8bit\",\n"," \"lr\": 0.0004,\n"," \"ema_config\": {\n"," \"use_ema\": true,\n"," \"ema_decay\": 0.99\n"," },\n"," \"dtype\": \"bf16\",\n"," \"skip_first_sample\": true,\n"," \"disable_sampling\": false\n"," },\n"," \"model\": {\n"," \"name_or_path\": \"black-forest-labs/FLUX.1-dev\",\n"," \"is_flux\": true,\n"," \"quantize\": true,\n"," \"low_vram\": true\n"," },\n"," \"sample\": {\n"," \"sampler\": \"flowmatch\",\n"," \"sample_every\": 1000,\n"," \"width\": 1024,\n"," \"height\": 1024,\n"," \"prompts\": [\n"," \"A person in a bustling cafe \"\n"," ],\n"," \"neg\": \"\",\n"," \"seed\": 42,\n"," \"walk_seed\": true,\n"," \"guidance_scale\": 4,\n"," \"sample_steps\": 28\n"," }\n","}\n","Using EMA\n","\n","#############################################\n","# Running job: test\n","#############################################\n","\n","\n","Running 1 process\n","Loading Flux model\n","Loading transformer\n","config.json: 100% 378/378 [00:00<00:00, 1.18MB/s]\n","(…)ion_pytorch_model.safetensors.index.json: 121kB [00:00, 20.9MB/s]\n","Downloading (incomplete total...): 0.00B [00:00, ?B/s]\n","Downloading (incomplete total...): 100% 23.8G/23.8G [06:37<00:00, 85.3MB/s]\n","Fetching 3 files: 100% 3/3 [06:37<00:00, 132.59s/it]\n","Download complete: 100% 23.8G/23.8G [06:37<00:00, 59.8MB/s]\n","Loading checkpoint shards: 100% 3/3 [00:02<00:00, 1.41it/s]\n","Quantizing transformer\n"]}]},{"cell_type":"markdown","source":["# Quantized Klein Edit txt2img LoRa Training (Dreambooth) Unused"],"metadata":{"id":"AOicVDnxWOhD"}},{"cell_type":"code","source":["#@markdown # **CELL 1**: Mount Drive + HF auth + Global Debug\n","# =============================================================================\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n"," if debug: print(\"✅ HF login successful – gated model download enabled\")\n","else:\n"," if debug: print(\"⚠️ No HF_TOKEN found in secrets. FLUX.2-klein-4B download may fail.\")\n","\n","print(\"🧹 Clearing GPU memory...\")\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","if debug:\n"," print(f\" VRAM after cleanup: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","print(\"✅ CELL 1 complete! Now run Cell 2\")"],"metadata":{"cellView":"form","id":"r7lG5GGKWNQT","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1776797201603,"user_tz":-120,"elapsed":34238,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"ff7cd54d-4aa7-4d3a-ab44-0c2b7aab9b68"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Mounted at /content/drive\n","✅ HF login successful – gated model download enabled\n","🧹 Clearing GPU memory...\n"," VRAM after cleanup: 0.00 GB\n","✅ CELL 1 complete! Now run Cell 2\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 2**: Environment Setup – Clean + FLUX requirements (FIXED)\n","# =============================================================================\n","import os\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🧹 Resetting working directory...\")\n","%cd /content\n","\n","# Remove old diffusers completely\n","print(\"🧹 Removing any existing diffusers...\")\n","!pip uninstall -y diffusers peft accelerate transformers bitsandbytes -q\n","!rm -rf /content/diffusers /usr/local/lib/python*/dist-packages/diffusers*\n","\n","print(\"🔄 Installing latest diffusers from GitHub main...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","\n","print(\"🔄 Cloning training scripts...\")\n","!git clone https://github.com/huggingface/diffusers.git --depth=1 /content/diffusers\n","\n","# FLUX-specific requirements\n","print(\"🔄 Installing FLUX requirements...\")\n","!pip install -q -r /content/diffusers/examples/dreambooth/requirements_flux.txt --no-deps\n","\n","print(\"🔄 Installing bitsandbytes + dreambooth requirements...\")\n","!pip install -q bitsandbytes\n","%cd /content/diffusers/examples/dreambooth\n","!pip install -q -r requirements.txt --no-deps\n","!pip install -q --upgrade peft\n","\n","if debug:\n"," print(\"\\n\" + \"=\"*70)\n"," print(\"✅ DEBUG: Package versions\")\n"," !pip list | grep -E 'diffusers|peft|accelerate|transformers|torch|bitsandbytes'\n"," print(\"=\"*70)\n","\n","import diffusers\n","if debug: print(f\"✅ diffusers version: {diffusers.__version__}\")\n","\n","print(\"✅ CELL 2 complete!\")\n","print(\" → **Restart runtime now** (Runtime → Restart session)\")\n","print(\" → Then run Cell 3\")"],"metadata":{"cellView":"form","id":"n5T6wTmbWaSM","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1776797271134,"user_tz":-120,"elapsed":69529,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"d14b7fb4-4306-4844-ade7-faa75dd8323e"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🧹 Resetting working directory...\n","/content\n","🧹 Removing any existing diffusers...\n","\u001b[33mWARNING: Skipping bitsandbytes as it is not installed.\u001b[0m\u001b[33m\n","\u001b[0m🔄 Installing latest diffusers from GitHub main...\n"," Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n"," Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n"," Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n"," Building wheel for diffusers (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","🔄 Cloning training scripts...\n","Cloning into '/content/diffusers'...\n","remote: Enumerating objects: 2809, done.\u001b[K\n","remote: Counting objects: 100% (2809/2809), done.\u001b[K\n","remote: Compressing objects: 100% (1947/1947), done.\u001b[K\n","remote: Total 2809 (delta 1117), reused 1525 (delta 833), pack-reused 0 (from 0)\u001b[K\n","Receiving objects: 100% (2809/2809), 9.00 MiB | 18.17 MiB/s, done.\n","Resolving deltas: 100% (1117/1117), done.\n","🔄 Installing FLUX requirements...\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m383.7/383.7 kB\u001b[0m \u001b[31m35.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.2/10.2 MB\u001b[0m \u001b[31m98.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m44.8/44.8 kB\u001b[0m \u001b[31m3.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m680.7/680.7 kB\u001b[0m \u001b[31m35.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h🔄 Installing bitsandbytes + dreambooth requirements...\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m60.7/60.7 MB\u001b[0m \u001b[31m11.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h/content/diffusers/examples/dreambooth\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m168.3/168.3 kB\u001b[0m \u001b[31m18.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h\n","======================================================================\n","✅ DEBUG: Package versions\n","accelerate 1.13.0\n","bitsandbytes 0.49.2\n","diffusers 0.38.0.dev0\n","peft 0.19.1\n","sentence-transformers 5.4.0\n","torch 2.10.0+cu128\n","torchao 0.10.0\n","torchaudio 2.10.0+cu128\n","torchcodec 0.10.0+cu128\n","torchdata 0.11.0\n","torchsummary 1.5.1\n","torchtune 0.6.1\n","torchvision 0.25.0+cu128\n","transformers 5.5.4\n","======================================================================\n","✅ diffusers version: 0.38.0.dev0\n","✅ CELL 2 complete!\n"," → **Restart runtime now** (Runtime → Restart session)\n"," → Then run Cell 3\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 3**: Verify diffusers + Flux2KleinPipeline (post-restart)\n","# =============================================================================\n","import torch\n","import gc\n","import sys\n","import importlib\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🔄 Verifying environment after restart...\")\n","\n","importlib.invalidate_caches()\n","\n","import diffusers\n","print(f\"✅ diffusers imported from: {diffusers.__file__}\")\n","print(f\" version: {diffusers.__version__}\")\n","\n","print(\"\\n🔍 Testing Flux2KleinPipeline import...\")\n","from diffusers import Flux2KleinPipeline\n","print(\"✅ Flux2KleinPipeline imported successfully! 🎉\")\n","\n","if debug:\n"," print(\"\\n\" + \"=\"*80)\n"," print(\"✅ ENVIRONMENT IS NOW FULLY READY FOR QLoRA TRAINING\")\n"," print(\"=\"*80)\n","\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","print(\"✅ CELL 3 complete! Ready for dataset preparation in Cell 4\")"],"metadata":{"cellView":"form","id":"_ylc37ayWdzp","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1776797296536,"user_tz":-120,"elapsed":25401,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"8dfd86cc-5f12-43a2-c6ff-b5c5eb38482d"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🔄 Verifying environment after restart...\n","✅ diffusers imported from: /usr/local/lib/python3.12/dist-packages/diffusers/__init__.py\n"," version: 0.38.0.dev0\n","\n","🔍 Testing Flux2KleinPipeline import...\n"]},{"output_type":"stream","name":"stderr","text":["Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n"]},{"output_type":"stream","name":"stdout","text":["✅ Flux2KleinPipeline imported successfully! 🎉\n","\n","================================================================================\n","✅ ENVIRONMENT IS NOW FULLY READY FOR QLoRA TRAINING\n","================================================================================\n","✅ CELL 3 complete! Ready for dataset preparation in Cell 4\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 4**: Prepare dataset (COLOR images only + prompt)\n","import os\n","import shutil\n","import glob\n","import zipfile\n","from PIL import Image\n","import torch\n","import gc\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","training_zip_path = '/content/drive/MyDrive/morbids/morbid4.zip' #@param {type:\"string\"}\n","max_images = 2 #@param {type:\"integer\"}\n","\n","train_data_dir = \"/content/colorization_train_pairs\"\n","output_dir = \"/content/flux_klein_colorize_lora\"\n","\n","print(\"🧹 Clearing old folders...\")\n","if os.path.exists(train_data_dir):\n"," shutil.rmtree(train_data_dir)\n","if os.path.exists(output_dir):\n"," shutil.rmtree(output_dir)\n","os.makedirs(train_data_dir, exist_ok=True)\n","\n","print(f\"📦 Unzipping: {training_zip_path}\")\n","with zipfile.ZipFile(training_zip_path, 'r') as z:\n"," z.extractall('/content/raw_training_images')\n","\n","image_files = sorted(glob.glob('/content/raw_training_images/*.*'))\n","image_files = [f for f in image_files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))][:max_images]\n","\n","print(f\"Found {len(image_files)} images → preparing color-only dataset...\")\n","\n","for i, img_path in enumerate(image_files):\n"," base = os.path.splitext(os.path.basename(img_path))[0]\n"," color_img = Image.open(img_path).convert(\"RGB\")\n"," color_img.save(os.path.join(train_data_dir, f\"{base}.png\"))\n"," if debug:\n"," print(f\" ✅ Saved {base}.png\")\n","\n","print(f\"✅ Dataset ready – {len(image_files)} color images in {train_data_dir}\")\n","print(\" • Prompt: 'colorize this image' (will be passed via --instance_prompt)\")\n","\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","if debug:\n"," print(f\" VRAM after prep: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","print(\"✅ CELL 4 complete! → Run Cell 5\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"kVvyMgscbElb","executionInfo":{"status":"ok","timestamp":1776798171599,"user_tz":-120,"elapsed":3849,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"cd18fdfd-89f8-4c09-e2d7-f7b037e742e0"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🧹 Clearing old folders...\n","📦 Unzipping: /content/drive/MyDrive/morbids/morbid4.zip\n","Found 2 images → preparing color-only dataset...\n"," ✅ Saved 53537172992_145a9daed1_k.png\n"," ✅ Saved 53537173032_18aa14e83b_k.png\n","✅ Dataset ready – 2 color images in /content/colorization_train_pairs\n"," • Prompt: 'colorize this image' (will be passed via --instance_prompt)\n"," VRAM after prep: 0.00 GB\n","✅ CELL 4 complete! → Run Cell 5\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 5**: Setup bnb 4-bit config\n","# =============================================================================\n","import torch\n","import gc\n","import json\n","import os\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🚀 Preparing quantized QLoRA training...\")\n","\n","bnb_config_path = \"/content/bnb_config.json\"\n","bnb_config = {\n"," \"load_in_4bit\": True,\n"," \"bnb_4bit_quant_type\": \"nf4\",\n"," \"bnb_4bit_compute_dtype\": \"float16\",\n"," \"bnb_4bit_use_double_quant\": True\n","}\n","with open(bnb_config_path, \"w\") as f:\n"," json.dump(bnb_config, f)\n","\n","if debug:\n"," print(f\"✅ 4-bit NF4 config saved → {bnb_config_path}\")\n"," with open(bnb_config_path, \"r\") as f:\n"," print(\" Config content:\", f.read())\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","print(\"\\n✅ CELL 5 complete! Now run Cell 6 to start training\")"],"metadata":{"cellView":"form","id":"XVcpaPhAWm0M","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1776797336836,"user_tz":-120,"elapsed":786,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"eb9f14bf-4c38-4436-bbae-d7ebc7e1e617"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🚀 Preparing quantized QLoRA training...\n","✅ 4-bit NF4 config saved → /content/bnb_config.json\n"," Config content: {\"load_in_4bit\": true, \"bnb_4bit_quant_type\": \"nf4\", \"bnb_4bit_compute_dtype\": \"float16\", \"bnb_4bit_use_double_quant\": true}\n","\n","✅ CELL 5 complete! Now run Cell 6 to start training\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 6**: Quantized QLoRA Training (TEXT + PROMPT) + DETAILED LOSS LOG\n","import datetime\n","import os\n","import re\n","\n","debug = True #@param {type:\"boolean\"}\n","\n","print(\"🚀 Starting **quantized QLoRA** on FLUX.2-klein-4B...\")\n","\n","# ========================== TRAINING PARAMETERS ==========================\n","max_train_steps = 100 #@param {type:\"slider\", min:100, max:2000, step:50}\n","learning_rate = 1e-4 #@param {type:\"slider\", min:5e-5, max:5e-4, step:5e-5, format:\"0.0e\"}\n","rank = 16 #@param {type:\"slider\", min:8, max:64, step:8}\n","gradient_accumulation_steps = 4 #@param {type:\"slider\", min:4, max:16, step:4}\n","lr_warmup_steps = 10 #@param {type:\"slider\", min:0, max:200, step:10}\n","lora_alpha = 32 #@param {type:\"slider\", min:16, max:64, step:8}\n","\n","if debug:\n"," print(f\" • max_train_steps = {max_train_steps}\")\n"," print(f\" • learning_rate = {learning_rate}\")\n"," print(f\" • rank = {rank}\")\n"," print(f\" • gradient_accumulation = {gradient_accumulation_steps}\")\n"," print(f\" • lr_warmup_steps = {lr_warmup_steps}\")\n"," print(f\" • lora_alpha = {lora_alpha}\")\n","\n","# ====================== TRAINING ======================\n","print(\"\\n🔥 Launching training (text + prompt mode)...\")\n","\n","!accelerate launch /content/diffusers/examples/dreambooth/train_dreambooth_lora_flux2_klein.py \\\n"," --pretrained_model_name_or_path=\"black-forest-labs/FLUX.2-klein-4B\" \\\n"," --instance_data_dir=\"/content/colorization_train_pairs\" \\\n"," --instance_prompt=\"colorize this image\" \\\n"," --resolution=1024 \\\n"," --train_batch_size=1 \\\n"," --gradient_accumulation_steps={gradient_accumulation_steps} \\\n"," --gradient_checkpointing \\\n"," --cache_latents \\\n"," --learning_rate={learning_rate} \\\n"," --lr_scheduler=\"constant\" \\\n"," --lr_warmup_steps={lr_warmup_steps} \\\n"," --max_train_steps={max_train_steps} \\\n"," --use_8bit_adam \\\n"," --mixed_precision=\"fp16\" \\\n"," --rank={rank} \\\n"," --lora_alpha={lora_alpha} \\\n"," --output_dir=\"/content/flux_klein_colorize_lora\" \\\n"," --report_to=\"tensorboard\" \\\n"," --seed=42 \\\n"," --bnb_quantization_config_path=\"/content/bnb_config.json\" \\\n"," --offload \\\n"," --skip_final_inference 2>&1 | tee training_log.txt\n","\n","# ====================== DETAILED LOSS RATE LOG ======================\n","print(\"\\n\" + \"=\"*80)\n","print(\"📊 FULL TRAINING LOSS LOG (per step)\")\n","print(\"=\"*80)\n","\n","if os.path.exists(\"training_log.txt\"):\n"," with open(\"training_log.txt\", \"r\", encoding=\"utf-8\") as f:\n"," log_content = f.read()\n","\n"," loss_matches = re.findall(r'loss=([\\d.]+)', log_content)\n","\n"," if loss_matches:\n"," losses = [float(x) for x in loss_matches]\n"," total_steps = len(losses)\n","\n"," print(f\"✅ Training completed {total_steps} steps\")\n"," print(f\" Average loss: {sum(losses)/total_steps:.4f}\")\n"," print(f\" Final loss: {losses[-1]:.4f}\")\n","\n"," print(\"\\nStep-by-Step Loss Table:\")\n"," print(\"┌──────────────┬──────────────┐\")\n"," print(\"│ Step │ Loss │\")\n"," print(\"├──────────────┼──────────────┤\")\n"," for i, loss in enumerate(losses):\n"," step_num = i + 1\n"," print(f\"│ {step_num:4d}/{total_steps:<4d} │ {loss:8.4f} │\")\n"," print(\"└──────────────┴──────────────┘\")\n","\n"," if debug:\n"," print(\"\\nLast 10 losses:\")\n"," for i, loss in enumerate(losses[-10:]):\n"," step_num = total_steps - 10 + i + 1\n"," print(f\" Step {step_num:4d} → loss = {loss:.4f}\")\n","\n"," timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n"," log_zip = f\"/content/drive/MyDrive/flux_klein_colorize_lora_log_{timestamp}.txt\"\n"," with open(log_zip, \"w\", encoding=\"utf-8\") as f:\n"," f.write(log_content)\n"," print(f\"\\n📁 Full training log saved to Drive: {log_zip}\")\n"," else:\n"," print(\"⚠️ No loss values found in log\")\n","else:\n"," print(\"⚠️ training_log.txt not found\")\n","\n","print(\"\\n🎉 TRAINING COMPLETE!\")\n","print(f\"LoRA saved to: /content/flux_klein_colorize_lora\")\n","\n","timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n","drive_zip = f\"/content/drive/MyDrive/flux_klein_colorize_lora_{timestamp}.zip\"\n","!zip -r -q \"{drive_zip}\" /content/flux_klein_colorize_lora\n","print(f\"✅ LoRA ZIP saved to Drive: {drive_zip}\")\n","print(\"\\n✅ CELL 6 complete!\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"cellView":"form","id":"Huz9zNZQbM1Y","executionInfo":{"status":"ok","timestamp":1776800582536,"user_tz":-120,"elapsed":1182262,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"41b9b12e-45fb-45d6-d9bf-53e610234c37"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["🚀 Starting **quantized QLoRA** on FLUX.2-klein-4B...\n"," • max_train_steps = 100\n"," • learning_rate = 0.0001\n"," • rank = 16\n"," • gradient_accumulation = 4\n"," • lr_warmup_steps = 10\n"," • lora_alpha = 32\n","\n","🔥 Launching training (text + prompt mode)...\n","The following values were not passed to `accelerate launch` and had defaults used instead:\n","\t`--num_processes` was set to a value of `1`\n","\t`--num_machines` was set to a value of `1`\n","\t`--mixed_precision` was set to a value of `'no'`\n","\t`--dynamo_backend` was set to a value of `'no'`\n","To avoid this warning pass in values for each of the problematic parameters or run `accelerate config`.\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","Flax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.\n","/usr/local/lib/python3.12/dist-packages/huggingface_hub/utils/_validators.py:205: UserWarning: The `local_dir_use_symlinks` argument is deprecated and ignored in `hf_hub_download`. Downloading to a local directory does not use symlinks anymore.\n"," warnings.warn(\n","{'decoder_block_out_channels'} was not found in config. Values will be initialized to default values.\n","All model checkpoint weights were used when initializing AutoencoderKLFlux2.\n","\n","All the weights of AutoencoderKLFlux2 were initialized from the model checkpoint at black-forest-labs/FLUX.2-klein-4B.\n","If your task is similar to the task the model of the checkpoint was trained on, you can already use AutoencoderKLFlux2 for predictions without further training.\n","The device_map was not initialized. Setting device_map to {: {current_device}}. If you want to use the model for inference, please set device_map ='auto' \n","Instantiating Flux2Transformer2DModel model under default dtype torch.float16.\n","All model checkpoint weights were used when initializing Flux2Transformer2DModel.\n","\n","All the weights of Flux2Transformer2DModel were initialized from the model checkpoint at black-forest-labs/FLUX.2-klein-4B.\n","If your task is similar to the task the model of the checkpoint was trained on, you can already use Flux2Transformer2DModel for predictions without further training.\n","Fetching 2 files: 100%|██████████| 2/2 [00:00<00:00, 8338.58it/s]\n","Loading weights: 100%|██████████| 398/398 [00:00<00:00, 983.47it/s] \n","Loading pipeline components...: 100%|██████████| 2/2 [00:00<00:00, 5384.22it/s]\n","Pipelines loaded with `dtype=torch.float16` cannot run with `cpu` device. It is not recommended to move them to `cpu` as running them will fail. Please make sure to use an accelerator to run the pipeline in inference, due to the lack of support for`float16` operations on this device in PyTorch. Please, remove the `torch_dtype=torch.float16` argument, or use another device for inference.\n","Caching latents: 100%|██████████| 2/2 [00:01<00:00, 1.23it/s]\n","Pipelines loaded with `dtype=torch.float16` cannot run with `cpu` device. It is not recommended to move them to `cpu` as running them will fail. Please make sure to use an accelerator to run the pipeline in inference, due to the lack of support for`float16` operations on this device in PyTorch. Please, remove the `torch_dtype=torch.float16` argument, or use another device for inference.\n","2026-04-21 19:05:41.252120: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n","WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n","E0000 00:00:1776798341.458693 6518 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n","E0000 00:00:1776798341.510650 6518 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n","W0000 00:00:1776798341.924014 6518 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","W0000 00:00:1776798341.924051 6518 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","W0000 00:00:1776798341.924055 6518 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","W0000 00:00:1776798341.924058 6518 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n","Steps: 100%|██████████| 100/100 [36:58<00:00, 22.39s/it, loss=0.935, lr=0.0001]Model weights saved in /content/flux_klein_colorize_lora/pytorch_lora_weights.safetensors\n","Steps: 100%|██████████| 100/100 [37:00<00:00, 22.20s/it, loss=0.935, lr=0.0001]\n","\n","================================================================================\n","📊 FULL TRAINING LOSS LOG (per step)\n","================================================================================\n","✅ Training completed 301 steps\n"," Average loss: 0.6535\n"," Final loss: 0.9350\n","\n","Step-by-Step Loss Table:\n","┌──────────────┬──────────────┐\n","│ Step │ Loss │\n","├──────────────┼──────────────┤\n","│ 1/301 │ 0.9510 │\n","│ 2/301 │ 0.9510 │\n","│ 3/301 │ 0.7790 │\n","│ 4/301 │ 0.5550 │\n","│ 5/301 │ 0.5550 │\n","│ 6/301 │ 1.0000 │\n","│ 7/301 │ 0.6010 │\n","│ 8/301 │ 0.6010 │\n","│ 9/301 │ 0.6830 │\n","│ 10/301 │ 0.6160 │\n","│ 11/301 │ 0.6160 │\n","│ 12/301 │ 0.6290 │\n","│ 13/301 │ 1.2400 │\n","│ 14/301 │ 1.2400 │\n","│ 15/301 │ 0.5750 │\n","│ 16/301 │ 0.6220 │\n","│ 17/301 │ 0.6220 │\n","│ 18/301 │ 0.5230 │\n","│ 19/301 │ 0.5250 │\n","│ 20/301 │ 0.5250 │\n","│ 21/301 │ 0.5400 │\n","│ 22/301 │ 0.4580 │\n","│ 23/301 │ 0.4580 │\n","│ 24/301 │ 0.6940 │\n","│ 25/301 │ 0.4460 │\n","│ 26/301 │ 0.4460 │\n","│ 27/301 │ 0.6010 │\n","│ 28/301 │ 1.0100 │\n","│ 29/301 │ 1.0100 │\n","│ 30/301 │ 0.8500 │\n","│ 31/301 │ 0.5470 │\n","│ 32/301 │ 0.5470 │\n","│ 33/301 │ 0.4950 │\n","│ 34/301 │ 1.0700 │\n","│ 35/301 │ 1.0700 │\n","│ 36/301 │ 1.0100 │\n","│ 37/301 │ 0.9330 │\n","│ 38/301 │ 0.9330 │\n","│ 39/301 │ 0.5740 │\n","│ 40/301 │ 0.4210 │\n","│ 41/301 │ 0.4210 │\n","│ 42/301 │ 0.5640 │\n","│ 43/301 │ 0.5590 │\n","│ 44/301 │ 0.5590 │\n","│ 45/301 │ 0.6900 │\n","│ 46/301 │ 0.5450 │\n","│ 47/301 │ 0.5450 │\n","│ 48/301 │ 0.6130 │\n","│ 49/301 │ 0.4160 │\n","│ 50/301 │ 0.4160 │\n","│ 51/301 │ 0.8240 │\n","│ 52/301 │ 0.4680 │\n","│ 53/301 │ 0.4680 │\n","│ 54/301 │ 0.5390 │\n","│ 55/301 │ 0.7720 │\n","│ 56/301 │ 0.7720 │\n","│ 57/301 │ 1.0400 │\n","│ 58/301 │ 0.5230 │\n","│ 59/301 │ 0.5230 │\n","│ 60/301 │ 0.5650 │\n","│ 61/301 │ 0.4210 │\n","│ 62/301 │ 0.4210 │\n","│ 63/301 │ 0.9280 │\n","│ 64/301 │ 0.6240 │\n","│ 65/301 │ 0.6240 │\n","│ 66/301 │ 0.4940 │\n","│ 67/301 │ 0.4800 │\n","│ 68/301 │ 0.4800 │\n","│ 69/301 │ 0.5080 │\n","│ 70/301 │ 0.7360 │\n","│ 71/301 │ 0.7360 │\n","│ 72/301 │ 1.0600 │\n","│ 73/301 │ 0.7130 │\n","│ 74/301 │ 0.7130 │\n","│ 75/301 │ 0.7350 │\n","│ 76/301 │ 0.7280 │\n","│ 77/301 │ 0.7280 │\n","│ 78/301 │ 1.0200 │\n","│ 79/301 │ 0.4570 │\n","│ 80/301 │ 0.4570 │\n","│ 81/301 │ 0.5480 │\n","│ 82/301 │ 0.5340 │\n","│ 83/301 │ 0.5340 │\n","│ 84/301 │ 1.0400 │\n","│ 85/301 │ 0.6140 │\n","│ 86/301 │ 0.6140 │\n","│ 87/301 │ 0.5250 │\n","│ 88/301 │ 0.4560 │\n","│ 89/301 │ 0.4560 │\n","│ 90/301 │ 0.4730 │\n","│ 91/301 │ 0.4050 │\n","│ 92/301 │ 0.4050 │\n","│ 93/301 │ 1.0300 │\n","│ 94/301 │ 0.9090 │\n","│ 95/301 │ 0.9090 │\n","│ 96/301 │ 0.5460 │\n","│ 97/301 │ 0.4860 │\n","│ 98/301 │ 0.4860 │\n","│ 99/301 │ 1.0500 │\n","│ 100/301 │ 0.5320 │\n","│ 101/301 │ 0.5320 │\n","│ 102/301 │ 0.6550 │\n","│ 103/301 │ 0.6690 │\n","│ 104/301 │ 0.6690 │\n","│ 105/301 │ 0.6930 │\n","│ 106/301 │ 0.5550 │\n","│ 107/301 │ 0.5550 │\n","│ 108/301 │ 0.7150 │\n","│ 109/301 │ 0.4440 │\n","│ 110/301 │ 0.4440 │\n","│ 111/301 │ 0.4680 │\n","│ 112/301 │ 0.4160 │\n","│ 113/301 │ 0.4160 │\n","│ 114/301 │ 0.5110 │\n","│ 115/301 │ 1.0500 │\n","│ 116/301 │ 1.0500 │\n","│ 117/301 │ 0.5690 │\n","│ 118/301 │ 0.9510 │\n","│ 119/301 │ 0.9510 │\n","│ 120/301 │ 0.5520 │\n","│ 121/301 │ 0.5350 │\n","│ 122/301 │ 0.5350 │\n","│ 123/301 │ 0.7260 │\n","│ 124/301 │ 0.4060 │\n","│ 125/301 │ 0.4060 │\n","│ 126/301 │ 0.5520 │\n","│ 127/301 │ 0.5360 │\n","│ 128/301 │ 0.5360 │\n","│ 129/301 │ 0.6420 │\n","│ 130/301 │ 0.3940 │\n","│ 131/301 │ 0.3940 │\n","│ 132/301 │ 0.4670 │\n","│ 133/301 │ 0.7970 │\n","│ 134/301 │ 0.7970 │\n","│ 135/301 │ 0.8860 │\n","│ 136/301 │ 0.3960 │\n","│ 137/301 │ 0.3960 │\n","│ 138/301 │ 0.7590 │\n","│ 139/301 │ 1.0700 │\n","│ 140/301 │ 1.0700 │\n","│ 141/301 │ 0.7620 │\n","│ 142/301 │ 0.5150 │\n","│ 143/301 │ 0.5150 │\n","│ 144/301 │ 0.5690 │\n","│ 145/301 │ 0.8970 │\n","│ 146/301 │ 0.8970 │\n","│ 147/301 │ 0.4790 │\n","│ 148/301 │ 0.6300 │\n","│ 149/301 │ 0.6300 │\n","│ 150/301 │ 0.9050 │\n","│ 151/301 │ 0.3860 │\n","│ 152/301 │ 0.3860 │\n","│ 153/301 │ 0.4640 │\n","│ 154/301 │ 0.5010 │\n","│ 155/301 │ 0.5010 │\n","│ 156/301 │ 0.5240 │\n","│ 157/301 │ 0.9970 │\n","│ 158/301 │ 0.9970 │\n","│ 159/301 │ 0.4910 │\n","│ 160/301 │ 1.0400 │\n","│ 161/301 │ 1.0400 │\n","│ 162/301 │ 0.9860 │\n","│ 163/301 │ 0.8960 │\n","│ 164/301 │ 0.8960 │\n","│ 165/301 │ 0.4660 │\n","│ 166/301 │ 0.5750 │\n","│ 167/301 │ 0.5750 │\n","│ 168/301 │ 0.4560 │\n","│ 169/301 │ 0.3940 │\n","│ 170/301 │ 0.3940 │\n","│ 171/301 │ 0.5970 │\n","│ 172/301 │ 0.6300 │\n","│ 173/301 │ 0.6300 │\n","│ 174/301 │ 0.8040 │\n","│ 175/301 │ 0.4960 │\n","│ 176/301 │ 0.4960 │\n","│ 177/301 │ 0.5070 │\n","│ 178/301 │ 0.9070 │\n","│ 179/301 │ 0.9070 │\n","│ 180/301 │ 0.5680 │\n","│ 181/301 │ 0.5410 │\n","│ 182/301 │ 0.5410 │\n","│ 183/301 │ 0.4620 │\n","│ 184/301 │ 1.0500 │\n","│ 185/301 │ 1.0500 │\n","│ 186/301 │ 1.0200 │\n","│ 187/301 │ 0.3900 │\n","│ 188/301 │ 0.3900 │\n","│ 189/301 │ 0.5770 │\n","│ 190/301 │ 0.4760 │\n","│ 191/301 │ 0.4760 │\n","│ 192/301 │ 0.7570 │\n","│ 193/301 │ 0.8230 │\n","│ 194/301 │ 0.8230 │\n","│ 195/301 │ 1.0200 │\n","│ 196/301 │ 1.0300 │\n","│ 197/301 │ 1.0300 │\n","│ 198/301 │ 0.4870 │\n","│ 199/301 │ 0.9780 │\n","│ 200/301 │ 0.9780 │\n","│ 201/301 │ 0.4990 │\n","│ 202/301 │ 1.0500 │\n","│ 203/301 │ 1.0500 │\n","│ 204/301 │ 1.0400 │\n","│ 205/301 │ 0.3890 │\n","│ 206/301 │ 0.3890 │\n","│ 207/301 │ 0.5600 │\n","│ 208/301 │ 0.4600 │\n","│ 209/301 │ 0.4600 │\n","│ 210/301 │ 0.6820 │\n","│ 211/301 │ 0.4000 │\n","│ 212/301 │ 0.4000 │\n","│ 213/301 │ 0.4490 │\n","│ 214/301 │ 0.3880 │\n","│ 215/301 │ 0.3880 │\n","│ 216/301 │ 0.6710 │\n","│ 217/301 │ 0.9290 │\n","│ 218/301 │ 0.9290 │\n","│ 219/301 │ 0.8170 │\n","│ 220/301 │ 0.4550 │\n","│ 221/301 │ 0.4550 │\n","│ 222/301 │ 1.0400 │\n","│ 223/301 │ 1.0300 │\n","│ 224/301 │ 1.0300 │\n","│ 225/301 │ 0.6230 │\n","│ 226/301 │ 0.9650 │\n","│ 227/301 │ 0.9650 │\n","│ 228/301 │ 0.4760 │\n","│ 229/301 │ 0.4670 │\n","│ 230/301 │ 0.4670 │\n","│ 231/301 │ 0.6500 │\n","│ 232/301 │ 0.3840 │\n","│ 233/301 │ 0.3840 │\n","│ 234/301 │ 0.4530 │\n","│ 235/301 │ 0.3920 │\n","│ 236/301 │ 0.3920 │\n","│ 237/301 │ 0.4840 │\n","│ 238/301 │ 0.4610 │\n","│ 239/301 │ 0.4610 │\n","│ 240/301 │ 0.4480 │\n","│ 241/301 │ 0.4450 │\n","│ 242/301 │ 0.4450 │\n","│ 243/301 │ 0.4480 │\n","│ 244/301 │ 0.7440 │\n","│ 245/301 │ 0.7440 │\n","│ 246/301 │ 0.7110 │\n","│ 247/301 │ 1.0300 │\n","│ 248/301 │ 1.0300 │\n","│ 249/301 │ 0.4570 │\n","│ 250/301 │ 0.6120 │\n","│ 251/301 │ 0.6120 │\n","│ 252/301 │ 0.6180 │\n","│ 253/301 │ 0.6340 │\n","│ 254/301 │ 0.6340 │\n","│ 255/301 │ 0.7680 │\n","│ 256/301 │ 0.9350 │\n","│ 257/301 │ 0.9350 │\n","│ 258/301 │ 0.7000 │\n","│ 259/301 │ 0.4500 │\n","│ 260/301 │ 0.4500 │\n","│ 261/301 │ 0.5080 │\n","│ 262/301 │ 0.3910 │\n","│ 263/301 │ 0.3910 │\n","│ 264/301 │ 0.4560 │\n","│ 265/301 │ 0.3850 │\n","│ 266/301 │ 0.3850 │\n","│ 267/301 │ 0.9270 │\n","│ 268/301 │ 0.4140 │\n","│ 269/301 │ 0.4140 │\n","│ 270/301 │ 0.8810 │\n","│ 271/301 │ 0.5720 │\n","│ 272/301 │ 0.5720 │\n","│ 273/301 │ 0.7160 │\n","│ 274/301 │ 0.8380 │\n","│ 275/301 │ 0.8380 │\n","│ 276/301 │ 0.4430 │\n","│ 277/301 │ 0.6600 │\n","│ 278/301 │ 0.6600 │\n","│ 279/301 │ 0.5170 │\n","│ 280/301 │ 1.0500 │\n","│ 281/301 │ 1.0500 │\n","│ 282/301 │ 0.5060 │\n","│ 283/301 │ 0.7400 │\n","│ 284/301 │ 0.7400 │\n","│ 285/301 │ 0.9090 │\n","│ 286/301 │ 0.3690 │\n","│ 287/301 │ 0.3690 │\n","│ 288/301 │ 0.4970 │\n","│ 289/301 │ 0.6750 │\n","│ 290/301 │ 0.6750 │\n","│ 291/301 │ 0.5350 │\n","│ 292/301 │ 0.8340 │\n","│ 293/301 │ 0.8340 │\n","│ 294/301 │ 0.4420 │\n","│ 295/301 │ 1.0400 │\n","│ 296/301 │ 1.0400 │\n","│ 297/301 │ 0.5880 │\n","│ 298/301 │ 0.4010 │\n","│ 299/301 │ 0.4010 │\n","│ 300/301 │ 0.9350 │\n","│ 301/301 │ 0.9350 │\n","└──────────────┴──────────────┘\n","\n","Last 10 losses:\n"," Step 292 → loss = 0.8340\n"," Step 293 → loss = 0.8340\n"," Step 294 → loss = 0.4420\n"," Step 295 → loss = 1.0400\n"," Step 296 → loss = 1.0400\n"," Step 297 → loss = 0.5880\n"," Step 298 → loss = 0.4010\n"," Step 299 → loss = 0.4010\n"," Step 300 → loss = 0.9350\n"," Step 301 → loss = 0.9350\n","\n","📁 Full training log saved to Drive: /content/drive/MyDrive/flux_klein_colorize_lora_log_20260421_194257.txt\n","\n","🎉 TRAINING COMPLETE!\n","LoRA saved to: /content/flux_klein_colorize_lora\n","✅ LoRA ZIP saved to Drive: /content/drive/MyDrive/flux_klein_colorize_lora_20260421_194257.zip\n","\n","✅ CELL 6 complete!\n"]}]},{"cell_type":"markdown","metadata":{"id":"8h4peBAYFzV6"},"source":["# ⚙️ Quantize Klein Edit AIO (GPU)"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":39032,"status":"ok","timestamp":1776809493020,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"},"user_tz":-120},"id":"zA8tl2ZLFzV6","outputId":"2038f697-43be-4ebd-ed73-15fb0bce9d99"},"outputs":[{"name":"stdout","output_type":"stream","text":["Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n","🧹 Removing old diffusers...\n","🔄 Installing latest diffusers...\n"," Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n"," Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n"," Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n"," Building wheel for diffusers (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","Files removed: 6\n","✅ Cell 1 complete!\n"]}],"source":["# =============================================================================\n","#@markdown # **CELL 1**: Mount Drive + HF auth\n","# =============================================================================\n","\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","import shutil\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n","else:\n"," print(\"⚠️ No HF_TOKEN found in secrets.\")\n","\n","print(\"🧹 Removing old diffusers...\")\n","!pip uninstall -y diffusers > /dev/null 2>&1\n","!rm -rf /usr/local/lib/python3.12/dist-packages/diffusers* ~/.cache/pip/*diffusers*\n","\n","print(\"🔄 Installing latest diffusers...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!python -m pip cache purge\n","\n","print(\"✅ Cell 1 complete!\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":8,"status":"ok","timestamp":1776809493169,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"},"user_tz":-120},"id":"oASypGDAFzV7","outputId":"74faab46-b2fc-4d42-f8ed-2b742bcb7b3c"},"outputs":[{"name":"stdout","output_type":"stream","text":["✅ Cell 2 settings loaded\n"," Resolution: 1024×1024\n"," Use .txt prompts: False\n"," Debug mode: False\n","\n","Now run Cell 3 (model load), then Cell 4 (inference)\n"]}],"source":["# =============================================================================\n","#@markdown # **CELL 2**: Fixed settings (resolution + options)\n","# =============================================================================\n","\n","resolution = '1024 x 1024 (Square)' #@param [\"1024 x 1024 (Square)\", \"512 x 1024 (Portrait)\", \"768 x 1024 (Slight Portrait)\", \"1536 x 1024 (Landscape)\", \"2048 x 1024 (Wide Landscape)\"] {type:\"string\"}\n","use_txt_prompts = False #@param {type:\"boolean\"}\n","debug = False #@param {type:\"boolean\"}\n","\n","res_map = {\n"," \"1024 x 1024 (Square)\": (1024, 1024),\n"," \"512 x 1024 (Portrait)\": (512, 1024),\n"," \"768 x 1024 (Slight Portrait)\": (768, 1024),\n"," \"1536 x 1024 (Landscape)\": (1536, 1024),\n"," \"2048 x 1024 (Wide Landscape)\": (2048, 1024)\n","}\n","target_width, target_height = res_map[resolution]\n","\n","print(\"✅ Cell 2 settings loaded\")\n","print(f\" Resolution: {target_width}×{target_height}\")\n","print(f\" Use .txt prompts: {use_txt_prompts}\")\n","print(f\" Debug mode: {debug}\")\n","print(\"\\nNow run Cell 3 (model load), then Cell 4 (inference)\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"sT7EYxbtQsEA"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 3: Quantize official FLUX.2-klein-4B (Distill) → 4-bit SDNQ Dynamic + Upload**\n","#@markdown • Correct classes for Klein (`Flux2Transformer2DModel` + `Qwen3ForCausalLM`)\n","#@markdown • Quantizes **only the weights** (transformer + text_encoder) with exact same SDNQ 4-bit dynamic as Disty0\n","#@markdown • `low_cpu_mem_usage=True` everywhere + explicit CPU move before save → T4 safe, no OOM\n","#@markdown • Matches `Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic` exactly\n","# =============================================================================\n","\n","from google.colab import userdata\n","from huggingface_hub import login, HfApi, create_repo\n","import torch\n","import gc\n","import os\n","import shutil\n","\n","# -------------------------- HF Login --------------------------\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n"," print(\"✅ Logged into Hugging Face\")\n","else:\n"," raise ValueError(\"⚠️ HF_TOKEN not found in Colab secrets. Add it in Secrets.\")\n","\n","# -------------------------- Settings --------------------------\n","#@markdown **Which official Klein variant to quantize?** (Distill = the one you chose before)\n","model_variant = \"Distill\" #@param [\"Base\", \"Distill\"] {type:\"string\"}\n","\n","if model_variant == \"Base\":\n"," base_pipeline_repo = \"black-forest-labs/FLUX.2-klein-base-4B\"\n","else:\n"," base_pipeline_repo = \"black-forest-labs/FLUX.2-klein-4B\"\n","\n","#@markdown **Repo name on your account** (will be created if it doesn't exist)\n","repo_id = \"codeshare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic\" #@param {type:\"string\"}\n","\n","#@markdown **Torch dtype**\n","torch_dtype = torch.float16 #@param [\"torch.float16\", \"torch.bfloat16\"] {type:\"raw\"}\n","\n","local_save_path = \"/content/quantized_flux2_klein_aio_sdnq\"\n","\n","# -------------------------- Install latest diffusers + sdnq --------------------------\n","print(\"🧹 Removing old diffusers...\")\n","!pip uninstall -y diffusers > /dev/null 2>&1\n","!rm -rf /usr/local/lib/python3.12/dist-packages/diffusers* ~/.cache/pip/*diffusers*\n","\n","print(\"🔄 Installing latest diffusers + sdnq...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!pip install -q sdnq\n","!python -m pip cache purge\n","\n","# -------------------------- Correct Imports for Klein --------------------------\n","from diffusers import Flux2KleinPipeline, Flux2Transformer2DModel\n","from transformers import Qwen3ForCausalLM\n","from sdnq import SDNQConfig\n","from sdnq.common import use_torch_compile as triton_is_available\n","from sdnq.loader import apply_sdnq_options_to_model\n","\n","# -------------------------- SDNQ 4-bit dynamic config (exact match to Disty0) --------------------------\n","print(\"⚙️ Creating SDNQ 4-bit dynamic config...\")\n","sdnq_config = SDNQConfig(\n"," use_dynamic_quantization=True,\n"," weights_dtype=\"uint4\",\n"," dynamic_loss_threshold=1e-2,\n"," use_svd=False,\n"," group_size=0,\n"," quantization_device=\"cuda\",\n"," return_device=\"cuda\",\n"," quant_conv=False,\n"," quant_embedding=False,\n",")\n","\n","print(\"✅ SDNQ 4-bit dynamic config created (matches Disty0)\")\n","\n","# -------------------------- Quantize transformer --------------------------\n","print(f\"🔄 Loading + quantizing transformer from official repo ({base_pipeline_repo})...\")\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","print(f\" VRAM before: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","transformer = Flux2Transformer2DModel.from_pretrained(\n"," base_pipeline_repo,\n"," subfolder=\"transformer\",\n"," quantization_config=sdnq_config,\n"," torch_dtype=torch_dtype,\n"," low_cpu_mem_usage=True,\n",")\n","\n","print(f\"✅ Transformer quantized! VRAM now: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# -------------------------- Quantize text_encoder (Qwen3) --------------------------\n","print(f\"🔄 Loading + quantizing text_encoder (Qwen3) from official repo...\")\n","\n","text_encoder = Qwen3ForCausalLM.from_pretrained(\n"," base_pipeline_repo,\n"," subfolder=\"text_encoder\",\n"," quantization_config=sdnq_config,\n"," torch_dtype=torch_dtype,\n"," low_cpu_mem_usage=True,\n",")\n","\n","print(f\"✅ Text encoder quantized! VRAM now: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# -------------------------- Build pipeline --------------------------\n","print(f\" → Building Flux2KleinPipeline from {base_pipeline_repo}...\")\n","\n","pipe = Flux2KleinPipeline.from_pretrained(\n"," base_pipeline_repo,\n"," transformer=transformer,\n"," text_encoder=text_encoder,\n"," torch_dtype=torch_dtype,\n"," low_cpu_mem_usage=True,\n"," device_map=None,\n",")\n","\n","print(f\"✅ Full pipeline ready (quantized weights only)! VRAM now: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# -------------------------- Optional: INT8 MatMul (skip during save to save VRAM) --------------------------\n","# We apply it in Cell 4 (inference) instead\n","\n","# -------------------------- Save with explicit CPU move (prevents OOM) --------------------------\n","print(\"🧹 Moving model to CPU before save to avoid any OOM...\")\n","pipe = pipe.to(\"cpu\")\n","gc.collect()\n","torch.cuda.empty_cache()\n","print(f\" VRAM before save: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","print(f\"💾 Saving quantized pipeline to {local_save_path}...\")\n","if os.path.exists(local_save_path):\n"," shutil.rmtree(local_save_path)\n","pipe.save_pretrained(local_save_path)\n","\n","print(\"✅ Pipeline saved locally\")\n","\n","# -------------------------- Push to HF --------------------------\n","print(f\"🚀 Uploading to https://huggingface.co/{repo_id} ...\")\n","api = HfApi()\n","create_repo(repo_id, exist_ok=True, private=False)\n","\n","api.upload_folder(\n"," folder_path=local_save_path,\n"," repo_id=repo_id,\n"," repo_type=\"model\",\n"," commit_message=\"SDNQ 4-bit dynamic quantized FLUX.2-klein-4B (official repo + correct classes, matches Disty0)\",\n",")\n","\n","print(\"🎉 DONE!\")\n","print(f\"✅ Quantized model live at: https://huggingface.co/{repo_id}\")\n","\n","# -------------------------- Cleanup --------------------------\n","gc.collect()\n","torch.cuda.empty_cache()\n","print(\"🧹 Cleanup complete\")"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"background_save":true},"id":"GGlGCB-DTlMz"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 4: Upload quantized model to your HF repo (codeShare)**\n","#@markdown • Only uploads the already-saved folder (no re-quantization)\n","#@markdown • Uses your correct username `codeShare` (capital S)\n","#@markdown • Change repo name below if you want something else\n","# =============================================================================\n","\n","from huggingface_hub import HfApi, create_repo\n","from google.colab import userdata\n","import os\n","\n","# -------------------------- HF Login (just in case) --------------------------\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," from huggingface_hub import login\n"," login(token=hf_token)\n"," print(\"✅ Logged into Hugging Face\")\n","else:\n"," raise ValueError(\"⚠️ HF_TOKEN not found in Colab secrets.\")\n","\n","# -------------------------- Settings --------------------------\n","#@markdown **Your exact HF username (already set correctly)**\n","repo_id = \"codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic\" #@param {type:\"string\"}\n","\n","local_save_path = \"/content/quantized_flux2_klein_aio_sdnq\"\n","\n","# -------------------------- Create repo + Upload --------------------------\n","print(f\"🚀 Uploading to https://huggingface.co/{repo_id} ...\")\n","\n","api = HfApi()\n","create_repo(repo_id, exist_ok=True, private=False)\n","\n","api.upload_folder(\n"," folder_path=local_save_path,\n"," repo_id=repo_id,\n"," repo_type=\"model\",\n"," commit_message=\"SDNQ 4-bit dynamic quantized FLUX.2-klein-4B (official repo, matches Disty0)\",\n",")\n","\n","print(\"🎉 DONE!\")\n","print(f\"✅ Quantized model is now live at: https://huggingface.co/{repo_id}\")\n","print(\"\\nYou can now use it in Cell 4 (inference) exactly like Disty0:\")\n","print(f'pipe = Flux2KleinPipeline.from_pretrained(\"{repo_id}\", torch_dtype=torch.float16)')\n","print(\"pipe.transformer = apply_sdnq_options_to_model(pipe.transformer, use_quantized_matmul=True)\")\n","print(\"pipe.text_encoder = apply_sdnq_options_to_model(pipe.text_encoder, use_quantized_matmul=True)\")\n","print(\"pipe.enable_model_cpu_offload()\")"]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776814708184},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776796861814},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776795061697},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776794307247},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776790556621},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776789720072},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776787634021},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776773678064},{"file_id":"151XI3nRFxLRbwRc8V6OfWyqp-zTnfySv","timestamp":1776764241991},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_edit.ipynb","timestamp":1776702729526},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/vertical_slice_prepper.ipynb","timestamp":1776687886662},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/vertical_slice_prepper.ipynb","timestamp":1776366149549},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776287741995},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776178739426},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776027716448},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1773663661932},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773663290922},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773264797996},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773163850245},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773090196076},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773089575687},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773080355474},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1772998638620},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1763646205520},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1760993725927},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760450712160},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1756712618300},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1747490904984},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1740037333374},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1736477078136},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1725365086834}],"collapsed_sections":["4PjK9a8Sni3A","kVAe29swHo4I","Sl3MykNlqAop","AOicVDnxWOhD","8h4peBAYFzV6"],"gpuType":"T4"},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":0} \ No newline at end of file