codeShare commited on
Commit
b852895
Β·
verified Β·
1 Parent(s): a7ba393

Upload klein_edit.ipynb

Browse files
Files changed (1) hide show
  1. klein_edit.ipynb +1 -1
klein_edit.ipynb CHANGED
@@ -1 +1 @@
1
- {"cells":[{"cell_type":"code","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! RESTART RUNTIME now, then run Cell 2 β†’ Cell 3 β†’ Cell 4\")"],"metadata":{"cellView":"form","id":"OXGhsHQwWue_"},"execution_count":null,"outputs":[]},{"cell_type":"code","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 = True #@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)\")"],"metadata":{"cellView":"form","id":"a1wZv8PrXAe2"},"execution_count":null,"outputs":[]},{"cell_type":"code","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)\")"],"metadata":{"cellView":"form","id":"WdNfo33NXNEa"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 4**: INFERENCE\n","# β€’ Edit prompt and zip_path below\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 dark gray.' #@param {type:\"string\"}\n","zip_path = '/content/drive/MyDrive/images.zip' #@param {type:\"string\"}\n","\n","import shutil\n","import datetime\n","\n","output_folder = '/content/edited_images' # ← TEMP folder only (never saved to Drive directly)\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","# ====================== FULL BATCH INFERENCE ======================\n","print(f\"\\nπŸš€ Starting batch edit on {len(image_files)} images...\")\n","\n","for i, img_path in enumerate(image_files):\n"," filename = os.path.basename(img_path)\n"," print(f\"[{i+1}/{len(image_files)}] {filename}\")\n","\n"," gc.collect()\n"," torch.cuda.empty_cache()\n","\n"," input_image = Image.open(img_path).convert(\"RGB\")\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=input_image,\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\"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}\")\n","\n","print(\"\\nπŸŽ‰ 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/edited_images_{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)\n","print(\"\\nImages are NOT saved directly to Drive – only the zip file.\")"],"metadata":{"cellView":"form","id":"bY-m1KJJXdia"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 5**: MULTI-IMAGE INFERENCE (Klein + 1024Γ—1024 #181818 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 = 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. replace it with the exact solid dark gray background from the second reference image.' #@param {type:\"string\"}\n","zip_path = '/content/drive/MyDrive/images.zipi' #@param {type:\"string\"}\n","\n","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\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 the 1024x1024 gray reference image (once) ======================\n","print(\"🟩 Creating 1024Γ—1024 #181818 solid gray reference image...\")\n","gray_image = Image.new(\"RGB\", (1024, 1024), \"#181818\")\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"," print(f\"[{i+1}/{len(image_files)}] {filename} β†’ + gray #181818 reference\")\n","\n"," gc.collect()\n"," torch.cuda.empty_cache()\n","\n"," input_image = Image.open(img_path).convert(\"RGB\")\n","\n"," # === MULTI-IMAGE LIST: base image first, gray reference second ===\n"," reference_images = [input_image, gray_image]\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 gray #181818)\")\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/multi_edited_images_{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)"],"metadata":{"cellView":"form","id":"q9I9wxghuUGP"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"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}],"gpuType":"T4"},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":0}
 
1
+ {"cells":[{"cell_type":"code","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! RESTART RUNTIME now, then run Cell 2 β†’ Cell 3 β†’ Cell 4\")"],"metadata":{"cellView":"form","id":"OXGhsHQwWue_"},"execution_count":null,"outputs":[]},{"cell_type":"code","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 = True #@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)\")"],"metadata":{"cellView":"form","id":"a1wZv8PrXAe2"},"execution_count":null,"outputs":[]},{"cell_type":"code","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)\")"],"metadata":{"cellView":"form","id":"WdNfo33NXNEa"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 4**: MULTI-IMAGE INFERENCE (Klein + 1024Γ—1024 #181818 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 = 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 dark gray. ' #@param {type:\"string\"}\n","zip_path = '/content/drive/MyDrive/images.zip' #@param {type:\"string\"}\n","\n","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\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 the 1024x1024 gray reference image (once) ======================\n","print(\"🟩 Creating 1024Γ—1024 #181818 solid gray reference image...\")\n","gray_image = Image.new(\"RGB\", (1024, 1024), \"#181818\")\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"," print(f\"[{i+1}/{len(image_files)}] {filename} β†’ + gray #181818 reference\")\n","\n"," gc.collect()\n"," torch.cuda.empty_cache()\n","\n"," input_image = Image.open(img_path).convert(\"RGB\")\n","\n"," # === MULTI-IMAGE LIST: base image first, gray reference second ===\n"," reference_images = [input_image, gray_image]\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 gray #181818)\")\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/multi_edited_images_{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)"],"metadata":{"cellView":"form","id":"q9I9wxghuUGP"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# Quantized lora training (unfinished)"],"metadata":{"id":"11YbjJrYStFb"}},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 1**: Mount Drive + HF auth (for gated FLUX.2-klein-4B download)\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","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n"," print(\"βœ… HF login successful – gated model download enabled\")\n","else:\n"," 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","print(\"βœ… Cell 1 complete! Now run Cell 2\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"cellView":"form","id":"kq7t09c0S4A1","executionInfo":{"status":"ok","timestamp":1776715812901,"user_tz":-120,"elapsed":31732,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"9d5ca416-5519-401b-82a0-4ad53f6413da"},"execution_count":1,"outputs":[{"output_type":"stream","name":"stdout","text":["Mounted at /content/drive\n","βœ… HF login successful – gated model download enabled\n","🧹 Clearing GPU memory...\n","βœ… Cell 1 complete! Now run Cell 2\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 2A**: Environment Setup – Clean packages + clone diffusers (FIXED)\n","# =============================================================================\n","\n","import os\n","import subprocess\n","import sys\n","\n","print(\"🧹 Resetting working directory to /content...\")\n","%cd /content\n","\n","# === CRITICAL FIX: Remove any leftover diffusers folder ===\n","print(\"🧹 Removing any existing /content/diffusers folder for a clean clone...\")\n","!rm -rf /content/diffusers\n","\n","print(\"🧹 Cleaning old conflicting packages...\")\n","!pip uninstall -y diffusers peft accelerate transformers\n","\n","print(\"πŸ”„ Installing latest peft (>=0.17.0) first...\")\n","!pip install \"peft>=0.17.0\" --quiet\n","\n","print(\"πŸ”„ Cloning fresh diffusers repo...\")\n","!git clone https://github.com/huggingface/diffusers.git --depth=1 /content/diffusers\n","\n","print(\"πŸ”„ Installing diffusers in editable mode...\")\n","%cd /content/diffusers\n","!pip install -e . --no-deps --quiet\n","\n","print(\"πŸ”„ Moving to training script folder...\")\n","%cd /content/diffusers/examples/dreambooth\n","\n","print(\"πŸ› οΈ Patching requirements.txt to prevent peft downgrade...\")\n","!sed -i 's/peft.*/peft>=0.17.0/' requirements.txt\n","\n","print(\"πŸ”„ Installing script requirements WITHOUT downgrading peft...\")\n","!pip install -r requirements.txt --no-deps --quiet\n","\n","print(\"πŸ”„ Re-enforcing latest peft...\")\n","!pip install --upgrade peft --quiet\n","\n","# ==================== SAFE DEBUG PRINTS ====================\n","print(\"\\n\" + \"=\"*70)\n","print(\"βœ… DEBUG: Package versions after install\")\n","!pip list | grep -E 'diffusers|peft|accelerate|transformers|torch|bitsandbytes'\n","\n","print(\"\\nπŸ” Testing import...\")\n","import diffusers\n","print(f\"βœ… diffusers imported from: {getattr(diffusers, '__file__', 'None (no __file__)')}\")\n","print(f\" diffusers version: {getattr(diffusers, '__version__', 'unknown (attribute missing)')}\")\n","\n","# Extra safety for Colab editable installs\n","import importlib\n","importlib.invalidate_caches()\n","print(\"βœ… importlib caches invalidated\")\n","\n","print(\"=\"*70)\n","\n","print(\"βœ… Cell 2A complete! (Everything installed cleanly)\")\n","print(\" β†’ **Strongly recommended**: Runtime β†’ Restart session\")\n","print(\" β†’ Then run Cell 2B\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"cellView":"form","id":"5ds2r5eMegBF","executionInfo":{"status":"ok","timestamp":1776715854216,"user_tz":-120,"elapsed":41313,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"1b797e93-865e-42cc-a532-3cb5f569d3ba"},"execution_count":2,"outputs":[{"output_type":"stream","name":"stdout","text":["🧹 Resetting working directory to /content...\n","/content\n","🧹 Removing any existing /content/diffusers folder for a clean clone...\n","🧹 Cleaning old conflicting packages...\n","Found existing installation: diffusers 0.37.1\n","Uninstalling diffusers-0.37.1:\n"," Successfully uninstalled diffusers-0.37.1\n","Found existing installation: peft 0.18.1\n","Uninstalling peft-0.18.1:\n"," Successfully uninstalled peft-0.18.1\n","Found existing installation: accelerate 1.13.0\n","Uninstalling accelerate-1.13.0:\n"," Successfully uninstalled accelerate-1.13.0\n","Found existing installation: transformers 5.0.0\n","Uninstalling transformers-5.0.0:\n"," Successfully uninstalled transformers-5.0.0\n","πŸ”„ Installing latest peft (>=0.17.0) first...\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m680.7/680.7 kB\u001b[0m \u001b[31m49.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m383.7/383.7 kB\u001b[0m \u001b[31m39.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[31m130.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hπŸ”„ Cloning fresh diffusers repo...\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 1526 (delta 833), pack-reused 0 (from 0)\u001b[K\n","Receiving objects: 100% (2809/2809), 8.99 MiB | 18.99 MiB/s, done.\n","Resolving deltas: 100% (1117/1117), done.\n","πŸ”„ Installing diffusers in editable mode...\n","/content/diffusers\n"," Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n"," Checking if build backend supports build_editable ... \u001b[?25l\u001b[?25hdone\n"," Getting requirements to build editable ... \u001b[?25l\u001b[?25hdone\n"," Preparing editable metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n"," Building editable for diffusers (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n","πŸ”„ Moving to training script folder...\n","/content/diffusers/examples/dreambooth\n","πŸ› οΈ Patching requirements.txt to prevent peft downgrade...\n","πŸ”„ Installing script requirements WITHOUT downgrading peft...\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m44.8/44.8 kB\u001b[0m \u001b[31m5.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hπŸ”„ Re-enforcing latest peft...\n","\n","======================================================================\n","βœ… DEBUG: Package versions after install\n","accelerate 1.13.0\n","diffusers 0.38.0.dev0 /content/diffusers\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","πŸ” Testing import...\n","βœ… diffusers imported from: None\n"," diffusers version: unknown (attribute missing)\n","βœ… importlib caches invalidated\n","======================================================================\n","βœ… Cell 2A complete! (Everything installed cleanly)\n"," β†’ **Strongly recommended**: Runtime β†’ Restart session\n"," β†’ Then run Cell 2B\n"]}]},{"cell_type":"code","source":["#@markdown # **CELL 2B**: Verify diffusers + Environment Ready (FIXED β€” Namespace Cleanup)\n","\n","# =============================================================================\n","import torch\n","import gc\n","import sys\n","import importlib\n","import os\n","import importlib.util\n","import glob\n","\n","print(\"πŸ”„ Verifying diffusers installation after restart… (Namespace fix applied)\\n\")\n","\n","# ====================== CRITICAL CLEANUP ======================\n","print(\"🧹 Cleaning ALL leftover diffusers .pth / .egg-link / dist-packages remnants...\")\n","!rm -f /usr/local/lib/python*/dist-packages/diffusers*.pth\n","!rm -f /usr/local/lib/python*/dist-packages/diffusers-*.egg-link\n","!rm -rf /usr/local/lib/python*/dist-packages/diffusers*\n","\n","print(\" β†’ All conflicting files removed\\n\")\n","\n","# ====================== FORCE CORRECT PATH ======================\n","importlib.invalidate_caches()\n","\n","src_path = \"/content/diffusers/src\"\n","if src_path not in sys.path:\n"," sys.path.insert(0, src_path) # MUST be first\n"," print(f\" β†’ Added {src_path} to PYTHONPATH (position 0)\")\n","\n","# Remove any stray /content/diffusers from path (prevents namespace)\n","sys.path = [p for p in sys.path if p != \"/content/diffusers\" and not p.endswith(\"/diffusers\")]\n","\n","print(f\"Current working directory: {os.getcwd()}\")\n","print(f\"First 10 entries in sys.path:\\n{sys.path[:10]}\\n\")\n","\n","# ====================== DEBUG IMPORT ======================\n","print(\"πŸ” DEBUG: diffusers import location\")\n","spec = importlib.util.find_spec(\"diffusers\")\n","if spec:\n"," print(f\" β€’ spec.origin : {spec.origin}\")\n"," print(f\" β€’ submodule_search_locations : {spec.submodule_search_locations}\")\n"," print(f\" β€’ __file__ : {getattr(diffusers, '__file__', 'None')}\")\n"," print(f\" β€’ __version__ : {getattr(diffusers, '__version__', 'MISSING')}\")\n","else:\n"," print(\" ❌ diffusers spec not found!\")\n"," raise ImportError(\"diffusers not found\")\n","\n","# ====================== TEST PIPELINES ======================\n","print(\"\\nπŸ” Testing diffusers.pipelines submodule…\")\n","try:\n"," import diffusers.pipelines\n"," print(\" βœ… diffusers.pipelines imported successfully\")\n","\n"," flux_pipelines = [x for x in dir(diffusers.pipelines) if \"flux\" in x.lower()]\n"," print(f\" Available FLUX pipelines: {flux_pipelines}\")\n","\n"," if any(\"klein\" in p.lower() or \"flux\" in p.lower() for p in flux_pipelines):\n"," print(\" βœ… FLUX / FLUX.2-klein pipeline support found β€” ready for training!\")\n","except Exception as e:\n"," print(f\" ❌ Still failed to access pipelines: {e}\")\n"," raise\n","\n","# ====================== FINAL CHECK ======================\n","print(\"\\n\" + \"=\"*80)\n","print(\"βœ… ENVIRONMENT IS NOW FIXED!\")\n","print(\" β†’ diffusers is correctly loaded from /content/diffusers/src\")\n","print(\" β†’ Namespace conflict resolved\")\n","print(\" β†’ You can now run Cell 3 β†’ Cell 4 safely\")\n","print(\"=\"*80)\n","\n","print(\"🧹 Final GPU memory clear…\")\n","torch.cuda.empty_cache()\n","gc.collect()\n","\n","print(\"βœ… Cell 2B (fixed) complete!\")"],"metadata":{"cellView":"form","colab":{"base_uri":"https://localhost:8080/","height":1000},"id":"NeGJaC8xheZk","executionInfo":{"status":"error","timestamp":1776715960034,"user_tz":-120,"elapsed":594,"user":{"displayName":"fukU Google","userId":"02763165356193834046"}},"outputId":"beb8ffba-57bb-42f5-c1d6-e923923fb017"},"execution_count":4,"outputs":[{"output_type":"stream","name":"stdout","text":["πŸ”„ Verifying diffusers installation after restart… (Namespace fix applied)\n","\n","🧹 Cleaning ALL leftover diffusers .pth / .egg-link / dist-packages remnants...\n"," β†’ All conflicting files removed\n","\n","Current working directory: /content/diffusers/examples/dreambooth\n","First 10 entries in sys.path:\n","['/content/diffusers/src', '/content', '/env/python', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '', '/usr/local/lib/python3.12/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.12/dist-packages/IPython/extensions']\n","\n","πŸ” DEBUG: diffusers import location\n"," β€’ spec.origin : None\n"," β€’ submodule_search_locations : _NamespacePath(['/content/diffusers'])\n"," β€’ __file__ : None\n"," β€’ __version__ : MISSING\n","\n","πŸ” Testing diffusers.pipelines submodule…\n"," ❌ Still failed to access pipelines: No module named 'diffusers.pipelines'\n"]},{"output_type":"error","ename":"ModuleNotFoundError","evalue":"No module named 'diffusers.pipelines'","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)","\u001b[0;32m/tmp/ipykernel_3162/1764755345.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 49\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"\\nπŸ” Testing diffusers.pipelines submodule…\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 50\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 51\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mdiffusers\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpipelines\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 52\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\" βœ… diffusers.pipelines imported successfully\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 53\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'diffusers.pipelines'","","\u001b[0;31m---------------------------------------------------------------------------\u001b[0;32m\nNOTE: If your import is failing due to a missing package, you can\nmanually install dependencies using either !pip or !apt.\n\nTo view examples of installing some common dependencies, click the\n\"Open Examples\" button below.\n\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n"],"errorDetails":{"actions":[{"action":"open_url","actionText":"Open Examples","url":"/notebooks/snippets/importing_libraries.ipynb"}]}}]},{"cell_type":"code","source":["#@markdown # **CELL 3**: Prepare environment + dataset + VRAM setup\n","# =============================================================================\n","\n","import os\n","import shutil\n","import glob\n","import zipfile\n","from PIL import Image\n","import datetime\n","import torch\n","import gc\n","\n","# ====================== SETTINGS ======================\n","training_zip_path = '/content/drive/MyDrive/morbids/morbid4.zip' #@param {type:\"string\"}\n","max_images = 2 #@param {type:\"integer\"} # T4-friendly (increase on Pro+)\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","# ====================== LOAD DATASET + CREATE PAIRED FORMAT ======================\n","print(f\"πŸ“¦ Unzipping training ZIP: {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)} colored images β†’ preparing for QLoRA colorization training...\")\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","\n"," # Save colored original as target image (script expects this as the training image)\n"," color_img.save(os.path.join(train_data_dir, f\"{base}.png\"))\n","\n"," # Fixed prompt for every image\n"," with open(os.path.join(train_data_dir, f\"{base}.txt\"), \"w\", encoding=\"utf-8\") as f:\n"," f.write(\"colorize this image\")\n","\n"," if (i + 1) % 10 == 0:\n"," print(f\" βœ… Processed {i+1}/{len(image_files)}\")\n","\n","print(f\"βœ… Dataset ready – {len(image_files)} paired examples in {train_data_dir}\")\n","\n","# ====================== VRAM + OPTIMIZATIONS ======================\n","print(\"πŸ”₯ Setting up T4-optimized VRAM configuration...\")\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","os.environ[\"TORCH_DYNAMO_MODE\"] = \"default\"\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","torch.cuda.reset_peak_memory_stats()\n","\n","print(f\" Current VRAM usage: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","print(\" Model will be loaded in 4-bit (via bitsandbytes) + fp16 during training in next cell\")\n","\n","print(\"\\nβœ… Cell 3 complete! Everything is prepared. Now run Cell 4 to start quantized training\")"],"metadata":{"cellView":"form","id":"M6ryXYTdd4-4"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # **CELL 4**: Run quantized QLoRA training (4-bit NF4 + 8-bit Adam) β€” REVISED\n","# =============================================================================\n","\n","import torch\n","import gc\n","import datetime\n","import json\n","import os\n","\n","print(\"πŸš€ Launching **quantized QLoRA** training on FLUX.2-klein-4B (T4-optimized)...\")\n","\n","# ====================== CREATE BNB 4-BIT CONFIG FOR QLoRA ======================\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","print(f\"βœ… 4-bit NF4 quantization config saved to {bnb_config_path}\")\n","\n","# ====================== LAUNCH TRAINING ======================\n","!accelerate launch 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"," --caption_column=\"txt\" \\\n"," --resolution=1024 \\\n"," --train_batch_size=1 \\\n"," --gradient_accumulation_steps=8 \\\n"," --gradient_checkpointing \\\n"," --learning_rate=8e-5 \\\n"," --lr_scheduler=\"constant\" \\\n"," --lr_warmup_steps=100 \\\n"," --max_train_steps=2500 \\\n"," --num_train_epochs=5 \\\n"," --use_8bit_adam \\\n"," --mixed_precision=\"fp16\" \\\n"," --rank=32 \\\n"," --output_dir=\"/content/flux_klein_colorize_lora\" \\\n"," --push_to_hub=False \\\n"," --report_to=\"tensorboard\" \\\n"," --validation_prompt=\"colorize this image\" \\\n"," --seed=42 \\\n"," --bnb_quantization_config_path=\"/content/bnb_config.json\"\n","\n","print(\"\\nπŸŽ‰ TRAINING FINISHED!\")\n","print(f\"LoRA adapter saved to: /content/flux_klein_colorize_lora\")\n","\n","# Zip and save to Drive\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 \"{drive_zip}\" /content/flux_klein_colorize_lora\n","\n","print(f\"βœ… LoRA ZIP saved to Drive: {drive_zip}\")\n","print(\"\\nπŸ’‘ Next: Create Cell 5 to load this LoRA on top of your quantized Flux2KleinPipeline for fast colorization inference!\")"],"metadata":{"cellView":"form","id":"fDsbqY7PeAZI"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"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}],"gpuType":"T4","collapsed_sections":["11YbjJrYStFb"]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":0}