Datasets:
Tags:
Not-For-All-Audiences
Upload klein_edit.ipynb
Browse files- klein_edit.ipynb +1 -1
klein_edit.ipynb
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
{"cells":[{"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! RESTART RUNTIME now, then run Cell 2 β Cell 3 β Cell 4\")"]},{"cell_type":"markdown","metadata":{"id":"HX3I-YqowwO9"},"source":["# Klein Edit"]},{"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 = 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)\")"]},{"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":["# =============================================================================\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 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","from google.colab import files\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","print(\"Please upload your reference image now, or skip to use a gray background.\")\n","uploaded_files = files.upload()\n","\n","uploaded_reference_filepath = None\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","reference_image_to_pair = None\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:\n"," print(f\"π© No 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","\n","# Clean up the temporarily saved file if it was uploaded\n","if uploaded_reference_filepath and os.path.exists(uploaded_reference_filepath):\n"," os.remove(uploaded_reference_filepath)\n","\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} β + custom reference\") # Updated message\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, the chosen reference second ===\n"," reference_images = [input_image, reference_image_to_pair] # Use the chosen 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/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)"]},{"cell_type":"markdown","metadata":{"id":"11YbjJrYStFb"},"source":["# Quantized lora training (unfinished)"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":31732,"status":"ok","timestamp":1776715812901,"user":{"displayName":"fukU Google","userId":"02763165356193834046"},"user_tz":-120},"id":"kq7t09c0S4A1","outputId":"9d5ca416-5519-401b-82a0-4ad53f6413da"},"outputs":[{"name":"stdout","output_type":"stream","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"]}],"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\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":41313,"status":"ok","timestamp":1776715854216,"user":{"displayName":"fukU Google","userId":"02763165356193834046"},"user_tz":-120},"id":"5ds2r5eMegBF","outputId":"1b797e93-865e-42cc-a532-3cb5f569d3ba"},"outputs":[{"name":"stdout","output_type":"stream","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"]}],"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\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","colab":{"base_uri":"https://localhost:8080/","height":1000},"executionInfo":{"elapsed":594,"status":"error","timestamp":1776715960034,"user":{"displayName":"fukU Google","userId":"02763165356193834046"},"user_tz":-120},"id":"NeGJaC8xheZk","outputId":"beb8ffba-57bb-42f5-c1d6-e923923fb017"},"outputs":[{"name":"stdout","output_type":"stream","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"]},{"ename":"ModuleNotFoundError","evalue":"No module named 'diffusers.pipelines'","output_type":"error","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"]}],"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!\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"M6ryXYTdd4-4"},"outputs":[],"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\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"fDsbqY7PeAZI"},"outputs":[],"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":{"accelerator":"GPU","colab":{"collapsed_sections":["HX3I-YqowwO9","11YbjJrYStFb"],"gpuType":"T4","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}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
|
|
|
|
| 1 |
+
{"cells":[{"cell_type":"markdown","metadata":{"id":"HX3I-YqowwO9"},"source":["# Klein Edit"]},{"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! RESTART RUNTIME now, then run Cell 2 β Cell 3 β Cell 4\")"]},{"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 = 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)\")"]},{"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":{"cellView":"form","colab":{"background_save":true},"id":"q9I9wxghuUGP"},"outputs":[],"source":["# =============================================================================\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/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","from google.colab import files\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","print(\"Please upload your reference image now, or skip to use a gray background.\")\n","uploaded_files = files.upload()\n","\n","uploaded_reference_filepath = None\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","reference_image_to_pair = None\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:\n"," print(f\"π© No 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","\n","# Clean up the temporarily saved file if it was uploaded\n","if uploaded_reference_filepath and os.path.exists(uploaded_reference_filepath):\n"," os.remove(uploaded_reference_filepath)\n","\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} β + custom reference\") # Updated message\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, the chosen reference second ===\n"," reference_images = [input_image, reference_image_to_pair] # Use the chosen 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/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)"]},{"cell_type":"markdown","metadata":{"id":"11YbjJrYStFb"},"source":["# Quantized lora training (unfinished)"]},{"cell_type":"code","source":["#@markdown # **CELL 1**: Mount Drive + HF auth\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","\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 2A\")"],"metadata":{"cellView":"form","id":"9mZkQOvtx-7k"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # **CELL 2A**: Environment Setup β Clean + FLUX requirements (FIXED pipeline import)\n","\n","import os\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 (this fixes Flux2KleinPipeline)...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","\n","print(\"π Cloning training scripts (we only need the dreambooth folder)...\")\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","# bitsandbytes for QLoRA\n","print(\"π Installing bitsandbytes...\")\n","!pip install -q bitsandbytes\n","\n","print(\"π Installing dreambooth script requirements...\")\n","%cd /content/diffusers/examples/dreambooth\n","!pip install -q -r requirements.txt --no-deps\n","!pip install -q --upgrade peft\n","\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","print(f\"β
diffusers version: {diffusers.__version__}\")\n","print(\"β
Cell 2A complete!\")\n","\n","print(\" β **Restart runtime now** (Runtime β Restart session)\")\n","print(\" β Then run the new Cell 2B\")"],"metadata":{"cellView":"form","id":"wjhleprr0Xj6"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # **CELL 2B**: Verify diffusers + Flux2KleinPipeline (now fixed)\n","\n","import torch\n","import gc\n","import sys\n","import importlib\n","\n","print(\"π Verifying environment after restart...\")\n","\n","# No more path hacks needed β git install puts everything in the right place\n","importlib.invalidate_caches()\n","\n","import diffusers\n","print(f\"β
diffusers imported from: {diffusers.__file__}\")\n","print(f\" version: {diffusers.__version__}\")\n","\n","# Test the pipeline that was failing\n","print(\"\\nπ Testing Flux2KleinPipeline import...\")\n","from diffusers import Flux2KleinPipeline\n","print(\"β
Flux2KleinPipeline imported successfully! π\")\n","\n","print(\"\\n\" + \"=\"*80)\n","print(\"β
ENVIRONMENT IS NOW FULLY READY FOR QLoRA TRAINING\")\n","print(\" β You can safely run Cell 3 β Cell 4\")\n","print(\"=\"*80)\n","\n","torch.cuda.empty_cache()\n","gc.collect()"],"metadata":{"cellView":"form","id":"9wZsOy760Yha"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # **CELL 3**: Prepare environment + dataset\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","# ====================== SETTINGS ======================\n","training_zip_path = '/content/drive/MyDrive/morbids/morbid4.zip' #@param {type:\"string\"}\n","max_images = 2 #@param {type:\"integer\"} # Increase on Pro+\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","# ====================== LOAD DATASET ======================\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 for 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"," color_img.save(os.path.join(train_data_dir, f\"{base}.png\"))\n","\n"," # Same 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","print(f\"β
Dataset ready β {len(image_files)} examples in {train_data_dir}\")\n","\n","# ====================== VRAM OPTIMIZATIONS ======================\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","print(\"β
Cell 3 complete! Ready for training.\")"],"metadata":{"id":"6nUSv-atykR-"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # **CELL 4**: Run quantized QLoRA training (4-bit NF4 + 8-bit Adam)\n","\n","import torch\n","import gc\n","import datetime\n","import json\n","import os\n","\n","print(\"π Starting **quantized QLoRA** on FLUX.2-klein-4B...\")\n","\n","# 4-bit NF4 config\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 config saved β {bnb_config_path}\")\n","\n","# ====================== 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"," --instance_prompt=\"colorize this image\" \\\n"," --resolution=1024 \\\n"," --train_batch_size=1 \\\n"," --gradient_accumulation_steps=8 \\\n"," --gradient_checkpointing \\\n"," --cache_latents \\\n"," --learning_rate=8e-5 \\\n"," --lr_scheduler=\"constant\" \\\n"," --lr_warmup_steps=100 \\\n"," --max_train_steps=2500 \\\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"," --validation_epochs=50 \\\n"," --seed=42 \\\n"," --bnb_quantization_config_path=\"/content/bnb_config.json\"\n","\n","print(\"\\nπ TRAINING COMPLETE!\")\n","print(f\"LoRA saved to: /content/flux_klein_colorize_lora\")\n","\n","# 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 -q\n","print(f\"β
ZIP saved to Drive: {drive_zip}\")"],"metadata":{"id":"ZelrhpBTym24"},"execution_count":null,"outputs":[]}],"metadata":{"accelerator":"GPU","colab":{"collapsed_sections":["HX3I-YqowwO9","11YbjJrYStFb"],"gpuType":"T4","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}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
|