codeShare commited on
Commit
040c68a
Β·
verified Β·
1 Parent(s): 7182ce0

Upload run_flux3_klein_sdnq.ipynb

Browse files
Files changed (1) hide show
  1. run_flux3_klein_sdnq.ipynb +2313 -0
run_flux3_klein_sdnq.ipynb ADDED
@@ -0,0 +1,2313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4"
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "language_info": {
14
+ "name": "python"
15
+ },
16
+ "accelerator": "GPU"
17
+ },
18
+ "cells": [
19
+ {
20
+ "cell_type": "markdown",
21
+ "source": [
22
+ "# lwkenf"
23
+ ],
24
+ "metadata": {
25
+ "id": "x-5cE_4iH91I"
26
+ }
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "source": [
31
+ "# =============================================================================\n",
32
+ "# ENCODE IMAGES – FLUX 3 Image Klein (SDNQ int4)\n",
33
+ "# Repo: https://huggingface.co/codeShare/flux-3-image-klein-sdnq-int4\n",
34
+ "# =============================================================================\n",
35
+ "\n",
36
+ "from google.colab import drive\n",
37
+ "import os\n",
38
+ "import shutil\n",
39
+ "import zipfile\n",
40
+ "import glob\n",
41
+ "from PIL import Image\n",
42
+ "import io\n",
43
+ "import hashlib\n",
44
+ "import json\n",
45
+ "from google.colab import files\n",
46
+ "\n",
47
+ "!pip install -q pynacl\n",
48
+ "\n",
49
+ "from nacl.secret import SecretBox\n",
50
+ "from nacl.utils import random\n",
51
+ "\n",
52
+ "# Mount Drive\n",
53
+ "drive.mount('/content/drive', force_remount=True)\n",
54
+ "\n",
55
+ "# =============================================================================\n",
56
+ "#@markdown ### πŸ”§ Encrypt settings (FLUX 3 Image Klein + optional LoRA)\n",
57
+ "# =============================================================================\n",
58
+ "foreground_images_zip_path = '/content/drive/MyDrive/sm_merged.zip' #@param {type:\"string\"}\n",
59
+ "upload_foreground_manually = False #@param {type:\"boolean\"}\n",
60
+ "\n",
61
+ "background_images_zip_path = '/content/drive/MyDrive/backgrounds.zip' #@param {type:\"string\"}\n",
62
+ "upload_background_manually = False #@param {type:\"boolean\"}\n",
63
+ "\n",
64
+ "encryption_password = \"banana\" #@param {type:\"string\"}\n",
65
+ "\n",
66
+ "output_drive_base_path = \"/content/drive/MyDrive/\" #@param {type:\"string\"}\n",
67
+ "output_folder_name = \"my_flux_dataset\" #@param {type:\"string\"}\n",
68
+ "\n",
69
+ "# Additional config values\n",
70
+ "MODEL_ID = \"codeShare/flux-3-image-klein-sdnq-int4\" #@param ['codeShare/flux-3-image-klein-sdnq-int4']\n",
71
+ "edit_prompt = \"remove the white background. as a real photo this girl has bare skin. put this character on the color gradient background. add diagonal border with dark gray background. the background has a stylish pattern.\" #@param {type:\"string\"}\n",
72
+ "resolution = \"1024 x 1024 (Square)\" #@param {type:\"string\"}\n",
73
+ "\n",
74
+ "# LORA Settings (update repo / names when you have Flux-3 compatible LoRAs)\n",
75
+ "lora_name = \"No LoRa\" #@param [\"No LoRa\"]\n",
76
+ "lora_strength = 0.8 #@param {type:\"slider\", min:0, max:2, step:0.1}\n",
77
+ "\n",
78
+ "# =============================================================================\n",
79
+ "# ===== KEY DERIVATION =====\n",
80
+ "# =============================================================================\n",
81
+ "def derive_key(password):\n",
82
+ " return hashlib.sha256(password.encode()).digest()\n",
83
+ "\n",
84
+ "SECRET_KEY = derive_key(encryption_password)\n",
85
+ "box = SecretBox(SECRET_KEY)\n",
86
+ "\n",
87
+ "# =============================================================================\n",
88
+ "# ===== IMAGE β†’ BYTES =====\n",
89
+ "# =============================================================================\n",
90
+ "def pil_to_bytes(img):\n",
91
+ " buf = io.BytesIO()\n",
92
+ " img.save(buf, format=\"JPEG\", quality=95)\n",
93
+ " return buf.getvalue()\n",
94
+ "\n",
95
+ "# =============================================================================\n",
96
+ "# ===== ENCRYPT =====\n",
97
+ "# =============================================================================\n",
98
+ "def encrypt_bytes(data):\n",
99
+ " nonce = random(SecretBox.NONCE_SIZE)\n",
100
+ " return box.encrypt(data, nonce)\n",
101
+ "\n",
102
+ "# =============================================================================\n",
103
+ "# ====================== PROCESS AND ENCRYPT ZIP ======================\n",
104
+ "# =============================================================================\n",
105
+ "def process_and_encrypt_zip(input_zip_filepath, output_encrypted_zip_name, output_base_path, secret_box_instance):\n",
106
+ " print(f\"\\nπŸ“¦ Extracting images from {os.path.basename(input_zip_filepath)}...\")\n",
107
+ " func_temp_extract_dir = f'/content/func_temp_extract_{os.path.basename(input_zip_filepath).replace(\".zip\", \"\")}'\n",
108
+ "\n",
109
+ " if os.path.exists(func_temp_extract_dir):\n",
110
+ " shutil.rmtree(func_temp_extract_dir)\n",
111
+ " os.makedirs(func_temp_extract_dir, exist_ok=True)\n",
112
+ "\n",
113
+ " try:\n",
114
+ " with zipfile.ZipFile(input_zip_filepath, 'r') as z:\n",
115
+ " z.extractall(func_temp_extract_dir)\n",
116
+ " except FileNotFoundError:\n",
117
+ " print(f\"⚠️ Warning: Input zip file not found: {input_zip_filepath}. Skipping this zip.\")\n",
118
+ " return\n",
119
+ " except Exception as e:\n",
120
+ " print(f\"❌ Error extracting {input_zip_filepath}: {e}. Skipping this zip.\")\n",
121
+ " return\n",
122
+ "\n",
123
+ " image_files = sorted(glob.glob(os.path.join(func_temp_extract_dir, '*.*')))\n",
124
+ " image_files = [f for f in image_files if f.lower().endswith(('.png','.jpg','.jpeg','.webp','.gif'))]\n",
125
+ "\n",
126
+ " print(f\"βœ… Found {len(image_files)} images to encrypt in {os.path.basename(input_zip_filepath)}.\")\n",
127
+ "\n",
128
+ " encrypted_image_data_for_zip = []\n",
129
+ " for img_path in image_files:\n",
130
+ " try:\n",
131
+ " img = Image.open(img_path).convert(\"RGB\")\n",
132
+ " img_bytes = pil_to_bytes(img)\n",
133
+ " enc_msg = encrypt_bytes(img_bytes)\n",
134
+ " encrypted_image_data_for_zip.append((os.path.basename(img_path), enc_msg))\n",
135
+ " except Exception as e:\n",
136
+ " print(f\"❌ Error processing image {os.path.basename(img_path)}: {e}\")\n",
137
+ "\n",
138
+ " print(f\"πŸ” Encrypted {len(encrypted_image_data_for_zip)} images from {os.path.basename(input_zip_filepath)}.\")\n",
139
+ "\n",
140
+ " # Create encrypted zip\n",
141
+ " temp_encrypted_zip_path = os.path.join('/content', f'temp_{output_encrypted_zip_name}')\n",
142
+ "\n",
143
+ " with zipfile.ZipFile(temp_encrypted_zip_path, 'w') as ez:\n",
144
+ " for original_fname, enc_msg in encrypted_image_data_for_zip:\n",
145
+ " encrypted_filename = f\"{os.path.splitext(original_fname)[0]}_encrypted.bin\"\n",
146
+ " combined_bytes = enc_msg.nonce + enc_msg.ciphertext\n",
147
+ " ez.writestr(encrypted_filename, combined_bytes)\n",
148
+ "\n",
149
+ " final_zip_path = os.path.join(output_base_path, output_encrypted_zip_name)\n",
150
+ " shutil.move(temp_encrypted_zip_path, final_zip_path)\n",
151
+ "\n",
152
+ " print(f\"βœ… Saved: {final_zip_path}\")\n",
153
+ "\n",
154
+ " if os.path.exists(func_temp_extract_dir):\n",
155
+ " shutil.rmtree(func_temp_extract_dir)\n",
156
+ "\n",
157
+ "\n",
158
+ "# =============================================================================\n",
159
+ "# ====================== CREATE OUTPUT FOLDER ======================\n",
160
+ "# =============================================================================\n",
161
+ "output_drive_full_path = os.path.join(output_drive_base_path, output_folder_name)\n",
162
+ "os.makedirs(output_drive_full_path, exist_ok=True)\n",
163
+ "\n",
164
+ "print(f\"πŸ“ Output folder created: {output_drive_full_path}\")\n",
165
+ "\n",
166
+ "# =============================================================================\n",
167
+ "# ====================== PROCESS BOTH ZIPS ======================\n",
168
+ "# =============================================================================\n",
169
+ "\n",
170
+ "# --- Foreground Images ---\n",
171
+ "current_foreground_zip_path = foreground_images_zip_path\n",
172
+ "uploaded_fg_filename = None\n",
173
+ "uploaded_fg_temp_zip = None\n",
174
+ "fg_temp_dir = \"/content/temp_fg_images_individual_upload\"\n",
175
+ "\n",
176
+ "if upload_foreground_manually:\n",
177
+ " print(\"\\nπŸ“€ Upload your foreground images (zip or individual files):\")\n",
178
+ " uploaded = files.upload()\n",
179
+ " if uploaded:\n",
180
+ " zip_file_uploaded = False\n",
181
+ " uploaded_files_list = list(uploaded.keys())\n",
182
+ "\n",
183
+ " for fn in uploaded_files_list:\n",
184
+ " if fn.endswith('.zip'):\n",
185
+ " uploaded_fg_filename = fn\n",
186
+ " zip_file_uploaded = True\n",
187
+ " break\n",
188
+ "\n",
189
+ " if zip_file_uploaded:\n",
190
+ " current_foreground_zip_path = os.path.join('/content/', uploaded_fg_filename)\n",
191
+ " print(f\"βœ… Using uploaded foreground zip: {current_foreground_zip_path}\")\n",
192
+ " elif uploaded_files_list:\n",
193
+ " os.makedirs(fg_temp_dir, exist_ok=True)\n",
194
+ " for fname, data in uploaded.items():\n",
195
+ " with open(os.path.join(fg_temp_dir, fname), 'wb') as f:\n",
196
+ " f.write(data)\n",
197
+ " uploaded_fg_temp_zip = \"/content/temp_foreground_images_from_individual.zip\"\n",
198
+ " with zipfile.ZipFile(uploaded_fg_temp_zip, 'w') as zf:\n",
199
+ " for root, _, files_in_dir in os.walk(fg_temp_dir):\n",
200
+ " for file in files_in_dir:\n",
201
+ " zf.write(os.path.join(root, file), os.path.basename(file))\n",
202
+ " current_foreground_zip_path = uploaded_fg_temp_zip\n",
203
+ " print(f\"βœ… Using uploaded individual foreground images (temporarily zipped)\")\n",
204
+ " else:\n",
205
+ " print(\"⚠️ No foreground files uploaded. Falling back to Drive path.\")\n",
206
+ " else:\n",
207
+ " print(\"⚠️ No foreground files uploaded. Falling back to Drive path.\")\n",
208
+ "\n",
209
+ "process_and_encrypt_zip(current_foreground_zip_path, \"foregrounds.zip\", output_drive_full_path, box)\n",
210
+ "if upload_foreground_manually and uploaded_fg_filename and os.path.exists(current_foreground_zip_path):\n",
211
+ " os.remove(current_foreground_zip_path)\n",
212
+ "if upload_foreground_manually and uploaded_fg_temp_zip and os.path.exists(uploaded_fg_temp_zip):\n",
213
+ " os.remove(uploaded_fg_temp_zip)\n",
214
+ " shutil.rmtree(fg_temp_dir, ignore_errors=True)\n",
215
+ "\n",
216
+ "# --- Background Images ---\n",
217
+ "current_background_zip_path = background_images_zip_path\n",
218
+ "uploaded_bg_filename = None\n",
219
+ "uploaded_bg_temp_zip = None\n",
220
+ "bg_temp_dir = \"/content/temp_bg_images_individual_upload\"\n",
221
+ "\n",
222
+ "if upload_background_manually:\n",
223
+ " print(\"\\nπŸ“€ Upload your background images (zip or individual files):\")\n",
224
+ " uploaded = files.upload()\n",
225
+ " if uploaded:\n",
226
+ " zip_file_uploaded = False\n",
227
+ " uploaded_files_list = list(uploaded.keys())\n",
228
+ "\n",
229
+ " for fn in uploaded_files_list:\n",
230
+ " if fn.endswith('.zip'):\n",
231
+ " uploaded_bg_filename = fn\n",
232
+ " zip_file_uploaded = True\n",
233
+ " break\n",
234
+ "\n",
235
+ " if zip_file_uploaded:\n",
236
+ " current_background_zip_path = os.path.join('/content/', uploaded_bg_filename)\n",
237
+ " print(f\"βœ… Using uploaded background zip: {current_background_zip_path}\")\n",
238
+ " elif uploaded_files_list:\n",
239
+ " os.makedirs(bg_temp_dir, exist_ok=True)\n",
240
+ " for fname, data in uploaded.items():\n",
241
+ " with open(os.path.join(bg_temp_dir, fname), 'wb') as f:\n",
242
+ " f.write(data)\n",
243
+ " uploaded_bg_temp_zip = \"/content/temp_background_images_from_individual.zip\"\n",
244
+ " with zipfile.ZipFile(uploaded_bg_temp_zip, 'w') as zf:\n",
245
+ " for root, _, files_in_dir in os.walk(bg_temp_dir):\n",
246
+ " for file in files_in_dir:\n",
247
+ " zf.write(os.path.join(root, file), os.path.basename(file))\n",
248
+ " current_background_zip_path = uploaded_bg_temp_zip\n",
249
+ " print(f\"βœ… Using uploaded individual background images (temporarily zipped)\")\n",
250
+ " else:\n",
251
+ " print(\"⚠️ No background files uploaded. Falling back to Drive path.\")\n",
252
+ " else:\n",
253
+ " print(\"⚠️ No background files uploaded. Falling back to Drive path.\")\n",
254
+ "\n",
255
+ "process_and_encrypt_zip(current_background_zip_path, \"backgrounds.zip\", output_drive_full_path, box)\n",
256
+ "if upload_background_manually and uploaded_bg_filename and os.path.exists(current_background_zip_path):\n",
257
+ " os.remove(current_background_zip_path)\n",
258
+ "if upload_background_manually and uploaded_bg_temp_zip and os.path.exists(uploaded_bg_temp_zip):\n",
259
+ " os.remove(uploaded_bg_temp_zip)\n",
260
+ " shutil.rmtree(bg_temp_dir, ignore_errors=True)\n",
261
+ "\n",
262
+ "# =============================================================================\n",
263
+ "# ====================== SAVE CONFIG FILES ======================\n",
264
+ "# =============================================================================\n",
265
+ "print(\"\\nπŸ“ Saving config files...\")\n",
266
+ "\n",
267
+ "password_txt_path = os.path.join(output_drive_full_path, \"password.txt\")\n",
268
+ "model_id_path = os.path.join(output_drive_full_path, \"model_id.txt\")\n",
269
+ "resolution_path = os.path.join(output_drive_full_path, \"resolution.txt\")\n",
270
+ "edit_prompt_path = os.path.join(output_drive_full_path, \"edit_prompt.txt\")\n",
271
+ "lora_config_path = os.path.join(output_drive_full_path, \"include_lora_strength.json\")\n",
272
+ "\n",
273
+ "with open(password_txt_path, 'w', encoding='utf-8') as f:\n",
274
+ " f.write(encryption_password)\n",
275
+ "\n",
276
+ "with open(model_id_path, 'w', encoding='utf-8') as f:\n",
277
+ " f.write(MODEL_ID)\n",
278
+ "\n",
279
+ "with open(resolution_path, 'w', encoding='utf-8') as f:\n",
280
+ " f.write(resolution)\n",
281
+ "\n",
282
+ "with open(edit_prompt_path, 'w', encoding='utf-8') as f:\n",
283
+ " f.write(edit_prompt)\n",
284
+ "\n",
285
+ "lora_config_data = {\n",
286
+ " \"lora_name\": lora_name,\n",
287
+ " \"lora_strength\": lora_strength,\n",
288
+ " \"lora_base_model\": \"flux3_klein\",\n",
289
+ " \"repo_id\": \"\" # fill when you have Flux-3 compatible LoRAs\n",
290
+ "}\n",
291
+ "\n",
292
+ "with open(lora_config_path, 'w', encoding='utf-8') as f:\n",
293
+ " json.dump(lora_config_data, f, indent=4)\n",
294
+ "\n",
295
+ "print(f\"πŸ”‘ Saved: {password_txt_path}\")\n",
296
+ "print(f\"🧠 Saved: {model_id_path}\")\n",
297
+ "print(f\"πŸ“ Saved: {resolution_path}\")\n",
298
+ "print(f\"✏️ Saved: {edit_prompt_path}\")\n",
299
+ "print(f\"βš™οΈ Saved: {lora_config_path}\")\n",
300
+ "\n",
301
+ "print(\"\\nπŸŽ‰ DONE! Files saved to Google Drive:\")\n",
302
+ "print(f\" πŸ“‚ {output_drive_full_path}/\")\n",
303
+ "print(f\" β€’ foregrounds.zip\")\n",
304
+ "print(f\" β€’ backgrounds.zip\")\n",
305
+ "print(f\" β€’ password.txt\")\n",
306
+ "print(f\" β€’ model_id.txt\")\n",
307
+ "print(f\" β€’ edit_prompt.txt\")\n",
308
+ "print(f\" β€’ resolution.txt\")\n",
309
+ "print(f\" β€’ include_lora_strength.json\")"
310
+ ],
311
+ "metadata": {
312
+ "colab": {
313
+ "base_uri": "https://localhost:8080/"
314
+ },
315
+ "id": "TQGmIN8T0jyO",
316
+ "outputId": "629228a5-f76d-42e3-9bb4-6600a4efe36f"
317
+ },
318
+ "execution_count": 1,
319
+ "outputs": [
320
+ {
321
+ "output_type": "stream",
322
+ "name": "stdout",
323
+ "text": [
324
+ "Mounted at /content/drive\n",
325
+ "πŸ“ Output folder created: /content/drive/MyDrive/my_flux_dataset\n",
326
+ "\n",
327
+ "πŸ“¦ Extracting images from sm_merged.zip...\n",
328
+ "βœ… Found 7 images to encrypt in sm_merged.zip.\n",
329
+ "πŸ” Encrypted 7 images from sm_merged.zip.\n",
330
+ "βœ… Saved: /content/drive/MyDrive/my_flux_dataset/foregrounds.zip\n",
331
+ "\n",
332
+ "πŸ“¦ Extracting images from backgrounds.zip...\n",
333
+ "⚠️ Warning: Input zip file not found: /content/drive/MyDrive/backgrounds.zip. Skipping this zip.\n",
334
+ "\n",
335
+ "πŸ“ Saving config files...\n",
336
+ "πŸ”‘ Saved: /content/drive/MyDrive/my_flux_dataset/password.txt\n",
337
+ "🧠 Saved: /content/drive/MyDrive/my_flux_dataset/model_id.txt\n",
338
+ "πŸ“ Saved: /content/drive/MyDrive/my_flux_dataset/resolution.txt\n",
339
+ "✏️ Saved: /content/drive/MyDrive/my_flux_dataset/edit_prompt.txt\n",
340
+ "βš™οΈ Saved: /content/drive/MyDrive/my_flux_dataset/include_lora_strength.json\n",
341
+ "\n",
342
+ "πŸŽ‰ DONE! Files saved to Google Drive:\n",
343
+ " πŸ“‚ /content/drive/MyDrive/my_flux_dataset/\n",
344
+ " β€’ foregrounds.zip\n",
345
+ " β€’ backgrounds.zip\n",
346
+ " β€’ password.txt\n",
347
+ " β€’ model_id.txt\n",
348
+ " β€’ edit_prompt.txt\n",
349
+ " β€’ resolution.txt\n",
350
+ " β€’ include_lora_strength.json\n"
351
+ ]
352
+ }
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "source": [
358
+ "# =============================================================================\n",
359
+ "# CELL 2: VERIFY ENVIRONMENT\n",
360
+ "# =============================================================================\n",
361
+ "\n",
362
+ "import sys\n",
363
+ "import torch\n",
364
+ "import triton\n",
365
+ "import transformers\n",
366
+ "import diffusers\n",
367
+ "import sdnq\n",
368
+ "\n",
369
+ "print(\"=\" * 70)\n",
370
+ "print(\"ENVIRONMENT\")\n",
371
+ "print(\"=\" * 70)\n",
372
+ "\n",
373
+ "print(\"Python :\", sys.version.split()[0])\n",
374
+ "print(\"Torch :\", torch.__version__)\n",
375
+ "print(\"Torch CUDA :\", torch.version.cuda)\n",
376
+ "print(\"Triton :\", triton.__version__)\n",
377
+ "print(\"Transformers :\", transformers.__version__)\n",
378
+ "print(\"Diffusers :\", diffusers.__version__)\n",
379
+ "print(\"SDNQ :\", getattr(sdnq, \"__version__\", \"unknown\"))\n",
380
+ "\n",
381
+ "print()\n",
382
+ "print(\"=\" * 70)\n",
383
+ "print(\"GPU\")\n",
384
+ "print(\"=\" * 70)\n",
385
+ "\n",
386
+ "print(\"GPU :\", torch.cuda.get_device_name(0))\n",
387
+ "print(\"CC :\", torch.cuda.get_device_capability(0))\n",
388
+ "print(\"CUDA :\", torch.cuda.is_available())\n",
389
+ "\n",
390
+ "if torch.cuda.is_available():\n",
391
+ "\n",
392
+ " props = torch.cuda.get_device_properties(0)\n",
393
+ "\n",
394
+ " print(\"VRAM :\", round(props.total_memory / 1024**3, 2), \"GB\")\n",
395
+ " print(\"BF16 reported:\", torch.cuda.is_bf16_supported())\n",
396
+ "\n",
397
+ " major, minor = torch.cuda.get_device_capability(0)\n",
398
+ "\n",
399
+ " if (major, minor) == (7, 5):\n",
400
+ " print(\"βœ… Tesla T4 / Turing SM75 detected\")\n",
401
+ " print(\"βœ… FP16 is the preferred runtime dtype\")\n",
402
+ " else:\n",
403
+ " print(\"⚠️ Unexpected GPU compute capability\")\n",
404
+ "\n",
405
+ "print(\"=\" * 70)\n",
406
+ "\n",
407
+ "# ---------------------------------------------------------------------\n",
408
+ "# Basic FP16 CUDA test\n",
409
+ "# ---------------------------------------------------------------------\n",
410
+ "\n",
411
+ "print(\"\\nπŸ§ͺ Testing FP16 CUDA matmul...\")\n",
412
+ "\n",
413
+ "a = torch.randn(\n",
414
+ " 2048,\n",
415
+ " 2048,\n",
416
+ " device=\"cuda\",\n",
417
+ " dtype=torch.float16\n",
418
+ ")\n",
419
+ "\n",
420
+ "b = torch.randn(\n",
421
+ " 2048,\n",
422
+ " 2048,\n",
423
+ " device=\"cuda\",\n",
424
+ " dtype=torch.float16\n",
425
+ ")\n",
426
+ "\n",
427
+ "c = a @ b\n",
428
+ "\n",
429
+ "torch.cuda.synchronize()\n",
430
+ "\n",
431
+ "print(\"βœ… FP16 CUDA matmul works\")\n",
432
+ "print(\"Result:\", c.shape, c.dtype)\n",
433
+ "\n",
434
+ "del a, b, c\n",
435
+ "\n",
436
+ "torch.cuda.empty_cache()"
437
+ ],
438
+ "metadata": {
439
+ "colab": {
440
+ "base_uri": "https://localhost:8080/"
441
+ },
442
+ "id": "AFPdlEod04s1",
443
+ "outputId": "214d95b4-2340-49f2-b65b-fde0f2c340d2"
444
+ },
445
+ "execution_count": 2,
446
+ "outputs": [
447
+ {
448
+ "output_type": "stream",
449
+ "name": "stderr",
450
+ "text": [
451
+ "WARNING:sdnq:SDNQ: OpenVINO MM kernels are not available! Falling back to PyTorch Eager kernels for CPU device. Error message: No module named 'openvino'\n",
452
+ "Unable to import `torchao` Tensor objects. This may affect loading checkpoints serialized with `torchao`\n"
453
+ ]
454
+ },
455
+ {
456
+ "output_type": "stream",
457
+ "name": "stdout",
458
+ "text": [
459
+ "======================================================================\n",
460
+ "ENVIRONMENT\n",
461
+ "======================================================================\n",
462
+ "Python : 3.13.16\n",
463
+ "Torch : 2.11.0+cu130\n",
464
+ "Torch CUDA : 13.0\n",
465
+ "Triton : 3.6.0\n",
466
+ "Transformers : 5.22.1\n",
467
+ "Diffusers : 0.42.0.dev0\n",
468
+ "SDNQ : 0.2.8\n",
469
+ "\n",
470
+ "======================================================================\n",
471
+ "GPU\n",
472
+ "======================================================================\n",
473
+ "GPU : Tesla T4\n",
474
+ "CC : (7, 5)\n",
475
+ "CUDA : True\n",
476
+ "VRAM : 14.56 GB\n",
477
+ "BF16 reported: True\n",
478
+ "βœ… Tesla T4 / Turing SM75 detected\n",
479
+ "βœ… FP16 is the preferred runtime dtype\n",
480
+ "======================================================================\n",
481
+ "\n",
482
+ "πŸ§ͺ Testing FP16 CUDA matmul...\n",
483
+ "βœ… FP16 CUDA matmul works\n",
484
+ "Result: torch.Size([2048, 2048]) torch.float16\n"
485
+ ]
486
+ }
487
+ ]
488
+ },
489
+ {
490
+ "cell_type": "markdown",
491
+ "source": [
492
+ "# FLUX 3 KLEIN SDNQ\n",
493
+ "\n",
494
+ "\n"
495
+ ],
496
+ "metadata": {
497
+ "id": "3UdPl_hc-g-K"
498
+ }
499
+ },
500
+ {
501
+ "cell_type": "code",
502
+ "source": [
503
+ "# =============================================================================\n",
504
+ "# CELL 1: COLAB ENVIRONMENT\n",
505
+ "# T4 / SM75\n",
506
+ "# PyTorch 2.10 + CUDA 12.8\n",
507
+ "# Triton 3.6\n",
508
+ "# =============================================================================\n",
509
+ "\n",
510
+ "\n",
511
+ "# =============================================================================\n",
512
+ "# CELL 1 β€” T4 SAFE SDNQ ENVIRONMENT\n",
513
+ "# =============================================================================\n",
514
+ "\n",
515
+ "import os\n",
516
+ "\n",
517
+ "# Prevent SDNQ from selecting torch.compile/Triton optimization\n",
518
+ "os.environ[\"SDNQ_USE_TORCH_COMPILE\"] = \"0\"\n",
519
+ "\n",
520
+ "# Also prevent PyTorch/Inductor from compiling the SDNQ fallback.\n",
521
+ "os.environ[\"TORCH_COMPILE_DISABLE\"] = \"1\"\n",
522
+ "\n",
523
+ "# Useful for diagnostics\n",
524
+ "os.environ[\"TORCHDYNAMO_VERBOSE\"] = \"0\"\n",
525
+ "\n",
526
+ "print(\"SDNQ_USE_TORCH_COMPILE =\", os.environ[\"SDNQ_USE_TORCH_COMPILE\"])\n",
527
+ "print(\"TORCH_COMPILE_DISABLE =\", os.environ[\"TORCH_COMPILE_DISABLE\"])\n",
528
+ "\n",
529
+ "\n",
530
+ "import os\n",
531
+ "import sys\n",
532
+ "import subprocess\n",
533
+ "\n",
534
+ "# ---------------------------------------------------------------------\n",
535
+ "# Install pinned PyTorch\n",
536
+ "# ---------------------------------------------------------------------\n",
537
+ "\n",
538
+ "print(\"\\nπŸ”₯ Installing PyTorch 2.10 CUDA 12.8...\")\n",
539
+ "\n",
540
+ "# =============================================================================\n",
541
+ "# PIN EXACT PYTORCH VERSION\n",
542
+ "# =============================================================================\n",
543
+ "\n",
544
+ "subprocess.run(\n",
545
+ " [\n",
546
+ " sys.executable,\n",
547
+ " \"-m\",\n",
548
+ " \"pip\",\n",
549
+ " \"install\",\n",
550
+ " \"--force-reinstall\",\n",
551
+ " \"torch==2.10.0\",\n",
552
+ " \"torchvision==0.25.0\",\n",
553
+ " \"torchaudio==2.10.0\",\n",
554
+ " \"--index-url\",\n",
555
+ " \"https://download.pytorch.org/whl/cu128\",\n",
556
+ " ],\n",
557
+ " check=True,\n",
558
+ ")\n",
559
+ "\n",
560
+ "# ---------------------------------------------------------------------\n",
561
+ "# Triton\n",
562
+ "# ---------------------------------------------------------------------\n",
563
+ "\n",
564
+ "print(\"⚑ Installing Triton 3.6.0...\")\n",
565
+ "\n",
566
+ "subprocess.run(\n",
567
+ " [\n",
568
+ " sys.executable,\n",
569
+ " \"-m\",\n",
570
+ " \"pip\",\n",
571
+ " \"install\",\n",
572
+ " \"--upgrade\",\n",
573
+ " \"triton\",\n",
574
+ " ],\n",
575
+ " check=True\n",
576
+ ")\n",
577
+ "\n",
578
+ "# ---------------------------------------------------------------------\n",
579
+ "# Diffusers\n",
580
+ "# ---------------------------------------------------------------------\n",
581
+ "\n",
582
+ "print(\"πŸ“¦ Installing Diffusers...\")\n",
583
+ "\n",
584
+ "subprocess.run(\n",
585
+ " [\n",
586
+ " sys.executable,\n",
587
+ " \"-m\",\n",
588
+ " \"pip\",\n",
589
+ " \"install\",\n",
590
+ " \"--upgrade\",\n",
591
+ " \"git+https://github.com/huggingface/diffusers.git\",\n",
592
+ " \"--no-deps\",\n",
593
+ " ],\n",
594
+ " check=True\n",
595
+ ")\n",
596
+ "\n",
597
+ "# ---------------------------------------------------------------------\n",
598
+ "# Remaining packages\n",
599
+ "# ---------------------------------------------------------------------\n",
600
+ "\n",
601
+ "print(\"πŸ“¦ Installing SDNQ + dependencies...\")\n",
602
+ "\n",
603
+ "subprocess.run(\n",
604
+ " [\n",
605
+ " sys.executable,\n",
606
+ " \"-m\",\n",
607
+ " \"pip\",\n",
608
+ " \"install\",\n",
609
+ " \"--upgrade\",\n",
610
+ " \"sdnq\",\n",
611
+ " \"torchao\",\n",
612
+ " \"accelerate\",\n",
613
+ " \"transformers\",\n",
614
+ " \"sentencepiece\",\n",
615
+ " \"safetensors\",\n",
616
+ " \"huggingface_hub\",\n",
617
+ " \"datasets\",\n",
618
+ " \"pynacl\",\n",
619
+ " ],\n",
620
+ " check=True\n",
621
+ ")\n",
622
+ "\n",
623
+ "print(\"\\n\")\n",
624
+ "print(\"=\" * 70)\n",
625
+ "print(\"⚠️ INSTALLATION COMPLETE\")\n",
626
+ "print(\"=\" * 70)"
627
+ ],
628
+ "metadata": {
629
+ "colab": {
630
+ "base_uri": "https://localhost:8080/"
631
+ },
632
+ "id": "6hCNzUth0ksl",
633
+ "outputId": "305f2962-1637-448e-a53b-6779064835ee"
634
+ },
635
+ "execution_count": null,
636
+ "outputs": [
637
+ {
638
+ "output_type": "stream",
639
+ "name": "stdout",
640
+ "text": [
641
+ "SDNQ_USE_TORCH_COMPILE = 0\n",
642
+ "TORCH_COMPILE_DISABLE = 1\n",
643
+ "\n",
644
+ "πŸ”₯ Installing PyTorch 2.10 CUDA 12.8...\n"
645
+ ]
646
+ }
647
+ ]
648
+ },
649
+ {
650
+ "cell_type": "code",
651
+ "source": [
652
+ "import torch\n",
653
+ "import sys\n",
654
+ "\n",
655
+ "print(\"=\" * 70)\n",
656
+ "print(\"ENVIRONMENT\")\n",
657
+ "print(\"=\" * 70)\n",
658
+ "\n",
659
+ "print(\"Python :\", sys.version)\n",
660
+ "print(\"Torch :\", torch.__version__)\n",
661
+ "print(\"Torch CUDA :\", torch.version.cuda)\n",
662
+ "print(\"CUDA :\", torch.cuda.is_available())\n",
663
+ "\n",
664
+ "if torch.cuda.is_available():\n",
665
+ " print(\"GPU :\", torch.cuda.get_device_name(0))\n",
666
+ " print(\"CC :\", torch.cuda.get_device_capability(0))\n",
667
+ " print(\"VRAM :\", round(\n",
668
+ " torch.cuda.get_device_properties(0).total_memory / 1024**3,\n",
669
+ " 2\n",
670
+ " ), \"GB\")\n",
671
+ "\n",
672
+ "print(\"=\" * 70)"
673
+ ],
674
+ "metadata": {
675
+ "id": "DBOGpo9BJhzZ"
676
+ },
677
+ "execution_count": null,
678
+ "outputs": []
679
+ },
680
+ {
681
+ "cell_type": "code",
682
+ "source": [
683
+ "# =============================================================================\n",
684
+ "# CELL 3: CONFIG + DATASET PATHS\n",
685
+ "# =============================================================================\n",
686
+ "\n",
687
+ "import os\n",
688
+ "import gc\n",
689
+ "import sys\n",
690
+ "import time\n",
691
+ "import math\n",
692
+ "import random\n",
693
+ "import warnings\n",
694
+ "import subprocess\n",
695
+ "import traceback\n",
696
+ "import re\n",
697
+ "import shutil\n",
698
+ "import importlib.util\n",
699
+ "import logging\n",
700
+ "from pathlib import Path\n",
701
+ "from collections import Counter\n",
702
+ "from huggingface_hub import login, HfApi\n",
703
+ "def free():\n",
704
+ " gc.collect()\n",
705
+ " torch.cuda.empty_cache()\n",
706
+ "#---#\n",
707
+ "free()\n",
708
+ "\n",
709
+ "import os\n",
710
+ "import gc\n",
711
+ "import json\n",
712
+ "import torch\n",
713
+ "\n",
714
+ "from pathlib import Path\n",
715
+ "\n",
716
+ "# ---------------------------------------------------------------------\n",
717
+ "# Dataset\n",
718
+ "# ---------------------------------------------------------------------\n",
719
+ "\n",
720
+ "google_drive_dataset_path = (\n",
721
+ " \"/content/drive/MyDrive/my_flux_dataset\"\n",
722
+ ")\n",
723
+ "\n",
724
+ "dataset_path = Path(\n",
725
+ " google_drive_dataset_path\n",
726
+ ")\n",
727
+ "\n",
728
+ "# ---------------------------------------------------------------------\n",
729
+ "# Mount Drive\n",
730
+ "# ---------------------------------------------------------------------\n",
731
+ "\n",
732
+ "from google.colab import drive\n",
733
+ "\n",
734
+ "drive.mount(\n",
735
+ " \"/content/drive\",\n",
736
+ " force_remount=True\n",
737
+ ")\n",
738
+ "\n",
739
+ "# ---------------------------------------------------------------------\n",
740
+ "# Hugging Face login\n",
741
+ "# ---------------------------------------------------------------------\n",
742
+ "\n",
743
+ "hf_token_path = (\n",
744
+ " dataset_path /\n",
745
+ " \"HF_TOKEN.txt\"\n",
746
+ ")\n",
747
+ "\n",
748
+ "hf_token = None\n",
749
+ "\n",
750
+ "if hf_token_path.exists():\n",
751
+ "\n",
752
+ " hf_token = (\n",
753
+ " hf_token_path\n",
754
+ " .read_text(encoding=\"utf-8\")\n",
755
+ " .strip()\n",
756
+ " )\n",
757
+ "\n",
758
+ " print(\"βœ… HF_TOKEN loaded from dataset\")\n",
759
+ "\n",
760
+ "else:\n",
761
+ "\n",
762
+ " print(\"⚠️ HF_TOKEN.txt not found\")\n",
763
+ "\n",
764
+ " try:\n",
765
+ "\n",
766
+ " from google.colab import userdata\n",
767
+ "\n",
768
+ " hf_token = userdata.get(\"HF_TOKEN\")\n",
769
+ "\n",
770
+ " if hf_token:\n",
771
+ " print(\"βœ… HF token loaded from Colab Secrets\")\n",
772
+ "\n",
773
+ " except Exception:\n",
774
+ " pass\n",
775
+ "\n",
776
+ "if hf_token:\n",
777
+ "\n",
778
+ " from huggingface_hub import login\n",
779
+ "\n",
780
+ " login(\n",
781
+ " token=hf_token,\n",
782
+ " add_to_git_credential=False\n",
783
+ " )\n",
784
+ "\n",
785
+ " print(\"βœ… Hugging Face login complete\")\n",
786
+ "\n",
787
+ "else:\n",
788
+ "\n",
789
+ " print(\"⚠️ No HF token β€” public models only\")\n",
790
+ "\n",
791
+ "# ---------------------------------------------------------------------\n",
792
+ "# Read configuration\n",
793
+ "# ---------------------------------------------------------------------\n",
794
+ "\n",
795
+ "MODEL_ID = (\n",
796
+ " dataset_path /\n",
797
+ " \"model_id.txt\"\n",
798
+ ").read_text(\n",
799
+ " encoding=\"utf-8\"\n",
800
+ ").strip()\n",
801
+ "\n",
802
+ "edit_prompt = (\n",
803
+ " dataset_path /\n",
804
+ " \"edit_prompt.txt\"\n",
805
+ ").read_text(\n",
806
+ " encoding=\"utf-8\"\n",
807
+ ").strip()\n",
808
+ "\n",
809
+ "resolution = (\n",
810
+ " dataset_path /\n",
811
+ " \"resolution.txt\"\n",
812
+ ").read_text(\n",
813
+ " encoding=\"utf-8\"\n",
814
+ ").strip()\n",
815
+ "\n",
816
+ "# ---------------------------------------------------------------------\n",
817
+ "# LoRA config\n",
818
+ "# ---------------------------------------------------------------------\n",
819
+ "\n",
820
+ "lora_config_path = (\n",
821
+ " dataset_path /\n",
822
+ " \"include_lora_strength.json\"\n",
823
+ ")\n",
824
+ "\n",
825
+ "if lora_config_path.exists():\n",
826
+ "\n",
827
+ " with open(\n",
828
+ " lora_config_path,\n",
829
+ " \"r\",\n",
830
+ " encoding=\"utf-8\"\n",
831
+ " ) as f:\n",
832
+ "\n",
833
+ " lora_data = json.load(f)\n",
834
+ "\n",
835
+ "else:\n",
836
+ "\n",
837
+ " lora_data = {}\n",
838
+ "\n",
839
+ "lora_name_loaded = (\n",
840
+ " lora_data.get(\n",
841
+ " \"lora_name\",\n",
842
+ " \"No LoRa\"\n",
843
+ " )\n",
844
+ ")\n",
845
+ "\n",
846
+ "lora_strength_loaded = (\n",
847
+ " lora_data.get(\n",
848
+ " \"lora_strength\",\n",
849
+ " 0.8\n",
850
+ " )\n",
851
+ ")\n",
852
+ "\n",
853
+ "lora_base_model_loaded = (\n",
854
+ " lora_data.get(\n",
855
+ " \"lora_base_model\",\n",
856
+ " \"flux3_klein\"\n",
857
+ " )\n",
858
+ ")\n",
859
+ "\n",
860
+ "lora_repo_id_loaded = (\n",
861
+ " lora_data.get(\n",
862
+ " \"repo_id\",\n",
863
+ " \"\"\n",
864
+ " )\n",
865
+ ")\n",
866
+ "\n",
867
+ "# ---------------------------------------------------------------------\n",
868
+ "# Image size\n",
869
+ "# ---------------------------------------------------------------------\n",
870
+ "\n",
871
+ "target_height = 1024\n",
872
+ "target_width = 1024\n",
873
+ "\n",
874
+ "# ---------------------------------------------------------------------\n",
875
+ "# Dataset files\n",
876
+ "# ---------------------------------------------------------------------\n",
877
+ "\n",
878
+ "encrypted_input_dataset_path = (\n",
879
+ " dataset_path /\n",
880
+ " \"foregrounds.zip\"\n",
881
+ ")\n",
882
+ "\n",
883
+ "backgrounds_input_dataset_path = (\n",
884
+ " dataset_path /\n",
885
+ " \"backgrounds.zip\"\n",
886
+ ")\n",
887
+ "\n",
888
+ "# ---------------------------------------------------------------------\n",
889
+ "# Runtime dtype\n",
890
+ "# ---------------------------------------------------------------------\n",
891
+ "\n",
892
+ "DTYPE = torch.float16\n",
893
+ "\n",
894
+ "# ---------------------------------------------------------------------\n",
895
+ "# Print\n",
896
+ "# ---------------------------------------------------------------------\n",
897
+ "\n",
898
+ "print()\n",
899
+ "print(\"=\" * 70)\n",
900
+ "print(\"CONFIG\")\n",
901
+ "print(\"=\" * 70)\n",
902
+ "\n",
903
+ "print(\"Model :\", MODEL_ID)\n",
904
+ "print(\"Resolution :\", resolution)\n",
905
+ "print(\"Dtype :\", DTYPE)\n",
906
+ "print(\"Foregrounds :\", encrypted_input_dataset_path)\n",
907
+ "print(\"Backgrounds :\", backgrounds_input_dataset_path)\n",
908
+ "\n",
909
+ "print(\n",
910
+ " f\"LoRA : \"\n",
911
+ " f\"{lora_name_loaded} @ {lora_strength_loaded}\"\n",
912
+ ")\n",
913
+ "\n",
914
+ "print(\"=\" * 70)\n",
915
+ "\n",
916
+ "gc.collect()\n",
917
+ "torch.cuda.empty_cache()"
918
+ ],
919
+ "metadata": {
920
+ "id": "lRI6tGZN07B5"
921
+ },
922
+ "execution_count": null,
923
+ "outputs": []
924
+ },
925
+ {
926
+ "cell_type": "code",
927
+ "source": [
928
+ "# =============================================================================\n",
929
+ "# CELL 5: FORCE SDNQ PYTORCH FALLBACK AND RETEST PUP\n",
930
+ "# =============================================================================\n",
931
+ "\n",
932
+ "import os\n",
933
+ "import gc\n",
934
+ "import sys\n",
935
+ "import time\n",
936
+ "import math\n",
937
+ "import random\n",
938
+ "import warnings\n",
939
+ "import subprocess\n",
940
+ "import traceback\n",
941
+ "import re\n",
942
+ "import shutil\n",
943
+ "import importlib.util\n",
944
+ "import logging\n",
945
+ "from pathlib import Path\n",
946
+ "from collections import Counter\n",
947
+ "from huggingface_hub import login, HfApi , hf_hub_download\n",
948
+ "def free():\n",
949
+ " gc.collect()\n",
950
+ " torch.cuda.empty_cache()\n",
951
+ "#---#\n",
952
+ "free()\n",
953
+ "\n",
954
+ "import gc\n",
955
+ "import inspect\n",
956
+ "import traceback\n",
957
+ "import torch\n",
958
+ "\n",
959
+ "import sdnq.kernel_wrappers as kw\n",
960
+ "import sdnq.layers.linear.linear_int8 as linear_int8\n",
961
+ "\n",
962
+ "print(\"=\" * 70)\n",
963
+ "print(\"SDNQ FALLBACK TEST\")\n",
964
+ "print(\"=\" * 70)\n",
965
+ "\n",
966
+ "print(\"Triton path before:\", kw.sdnq_scaled_mm)\n",
967
+ "print(\"PyTorch fallback :\", getattr(linear_int8, \"int_scaled_mm_torch\", None))\n",
968
+ "\n",
969
+ "import os\n",
970
+ "import torch\n",
971
+ "import sdnq\n",
972
+ "import sdnq.kernel_wrappers as kw\n",
973
+ "\n",
974
+ "print(\"SDNQ_USE_TORCH_COMPILE:\",\n",
975
+ " os.environ.get(\"SDNQ_USE_TORCH_COMPILE\"))\n",
976
+ "\n",
977
+ "print(\"Torch:\",\n",
978
+ " torch.__version__)\n",
979
+ "\n",
980
+ "print(\"CUDA:\",\n",
981
+ " torch.version.cuda)\n",
982
+ "\n",
983
+ "print(\"SDNQ scaled_mm:\",\n",
984
+ " kw.sdnq_scaled_mm)\n",
985
+ "\n",
986
+ "\n",
987
+ "# -------------------------------------------------------------------------\n",
988
+ "# Reload PUP\n",
989
+ "# -------------------------------------------------------------------------\n",
990
+ "\n",
991
+ "from transformers import AutoProcessor, AutoModelForCausalLM\n",
992
+ "\n",
993
+ "PUP_REPO = MODEL_ID\n",
994
+ "PUP_SUBFOLDER = \"prompt_upsampler\"\n",
995
+ "OFFICIAL_PUP = \"black-forest-labs/flux-3-image-klein-pup\"\n",
996
+ "\n",
997
+ "print(\"πŸ“₯ Loading processor...\")\n",
998
+ "\n",
999
+ "processor = AutoProcessor.from_pretrained(\n",
1000
+ " OFFICIAL_PUP,\n",
1001
+ " trust_remote_code=True,\n",
1002
+ ")\n",
1003
+ "\n",
1004
+ "print(\"πŸ“₯ Loading PUP...\")\n",
1005
+ "\n",
1006
+ "upsampler = AutoModelForCausalLM.from_pretrained(\n",
1007
+ " PUP_REPO,\n",
1008
+ " subfolder=PUP_SUBFOLDER,\n",
1009
+ " dtype=torch.float16,\n",
1010
+ " device_map=\"cuda\",\n",
1011
+ " trust_remote_code=True,\n",
1012
+ " low_cpu_mem_usage=True,\n",
1013
+ ").eval()\n",
1014
+ "\n",
1015
+ "print(\"βœ… PUP loaded\")\n",
1016
+ "print()\n",
1017
+ "\n"
1018
+ ],
1019
+ "metadata": {
1020
+ "id": "KAgYgbkvFHLs"
1021
+ },
1022
+ "execution_count": null,
1023
+ "outputs": []
1024
+ },
1025
+ {
1026
+ "cell_type": "code",
1027
+ "source": [
1028
+ "# ---------------------------------------------------------------------\n",
1029
+ "# System prompts\n",
1030
+ "# ---------------------------------------------------------------------\n",
1031
+ "\n",
1032
+ "try:\n",
1033
+ "\n",
1034
+ " system_prompts_path = hf_hub_download(\n",
1035
+ " OFFICIAL_PUP,\n",
1036
+ " \"system_prompts.json\"\n",
1037
+ " )\n",
1038
+ "\n",
1039
+ " with open(\n",
1040
+ " system_prompts_path,\n",
1041
+ " \"r\",\n",
1042
+ " encoding=\"utf-8\"\n",
1043
+ " ) as f:\n",
1044
+ "\n",
1045
+ " system_prompts = json.load(f)\n",
1046
+ "\n",
1047
+ " print(\"βœ… Loaded official system prompts\")\n",
1048
+ "\n",
1049
+ "except Exception as e:\n",
1050
+ "\n",
1051
+ " print(\n",
1052
+ " f\"⚠️ Could not load official \"\n",
1053
+ " f\"system_prompts.json: {e}\"\n",
1054
+ " )\n",
1055
+ "\n",
1056
+ " system_prompts = {\n",
1057
+ " \"t2i\": (\n",
1058
+ " \"Expand the short prompt into a detailed \"\n",
1059
+ " \"photographic scene caption including subject, \"\n",
1060
+ " \"background, lighting, camera, materials and composition.\"\n",
1061
+ " ),\n",
1062
+ "\n",
1063
+ " \"i2i\": (\n",
1064
+ " \"Expand the edit instruction into a detailed \"\n",
1065
+ " \"scene caption that incorporates the reference images.\"\n",
1066
+ " )\n",
1067
+ " }\n",
1068
+ "\n",
1069
+ "\n",
1070
+ "# -------------------------------------------------------------------------\n",
1071
+ "# Minimal generation test\n",
1072
+ "# -------------------------------------------------------------------------\n",
1073
+ "\n",
1074
+ "messages = [\n",
1075
+ " {\n",
1076
+ " \"role\": \"system\",\n",
1077
+ " \"content\": system_prompts[\"t2i\"],\n",
1078
+ " },\n",
1079
+ " {\n",
1080
+ " \"role\": \"user\",\n",
1081
+ " \"content\": edit_prompt,\n",
1082
+ " },\n",
1083
+ "]\n",
1084
+ "\n",
1085
+ "inputs = processor.apply_chat_template(\n",
1086
+ " messages,\n",
1087
+ " add_generation_prompt=True,\n",
1088
+ " tokenize=True,\n",
1089
+ " return_dict=True,\n",
1090
+ " return_tensors=\"pt\",\n",
1091
+ " enable_thinking=False,\n",
1092
+ ")\n",
1093
+ "\n",
1094
+ "allowed_keys = {\n",
1095
+ " \"input_ids\",\n",
1096
+ " \"attention_mask\",\n",
1097
+ "}\n",
1098
+ "\n",
1099
+ "filtered_inputs = {\n",
1100
+ " k: v.to(upsampler.device)\n",
1101
+ " for k, v in inputs.items()\n",
1102
+ " if k in allowed_keys\n",
1103
+ "}\n",
1104
+ "\n",
1105
+ "print(\"Input:\", {\n",
1106
+ " k: tuple(v.shape)\n",
1107
+ " for k, v in filtered_inputs.items()\n",
1108
+ "})\n",
1109
+ "\n",
1110
+ "# -------------------------------------------------------------------------\n",
1111
+ "# Generate\n",
1112
+ "# -------------------------------------------------------------------------\n",
1113
+ "\n",
1114
+ "print()\n",
1115
+ "print(\"πŸ§ͺ Testing generation with PyTorch fallback...\")\n",
1116
+ "print()\n",
1117
+ "\n",
1118
+ "try:\n",
1119
+ "\n",
1120
+ " with torch.inference_mode():\n",
1121
+ "\n",
1122
+ " output = upsampler.generate(\n",
1123
+ " **filtered_inputs,\n",
1124
+ " max_new_tokens=256,\n",
1125
+ " do_sample=False,\n",
1126
+ " use_cache=True,\n",
1127
+ " )\n",
1128
+ "\n",
1129
+ " prompt_length = filtered_inputs[\"input_ids\"].shape[1]\n",
1130
+ "\n",
1131
+ " caption = processor.decode(\n",
1132
+ " output[0, prompt_length:],\n",
1133
+ " skip_special_tokens=True,\n",
1134
+ " ).strip()\n",
1135
+ "\n",
1136
+ " print(\"=\" * 70)\n",
1137
+ " print(\"πŸŽ‰ FALLBACK TEST SUCCEEDED\")\n",
1138
+ " print(\"=\" * 70)\n",
1139
+ " print()\n",
1140
+ " print(caption)\n",
1141
+ "\n",
1142
+ "except Exception as e:\n",
1143
+ "\n",
1144
+ " print(\"=\" * 70)\n",
1145
+ " print(\"❌ FALLBACK TEST FAILED\")\n",
1146
+ " print(\"=\" * 70)\n",
1147
+ "\n",
1148
+ " print()\n",
1149
+ " print(\"Error type:\", type(e).__name__)\n",
1150
+ " print(\"Error:\", e)\n",
1151
+ "\n",
1152
+ " traceback.print_exc()\n",
1153
+ "\n",
1154
+ "finally:\n",
1155
+ "\n",
1156
+ " try:\n",
1157
+ " del upsampler\n",
1158
+ " except:\n",
1159
+ " pass\n",
1160
+ "\n",
1161
+ " try:\n",
1162
+ " del processor\n",
1163
+ " except:\n",
1164
+ " pass\n",
1165
+ "\n",
1166
+ " gc.collect()\n",
1167
+ " torch.cuda.empty_cache()"
1168
+ ],
1169
+ "metadata": {
1170
+ "id": "A20k274KKEzZ"
1171
+ },
1172
+ "execution_count": null,
1173
+ "outputs": []
1174
+ },
1175
+ {
1176
+ "cell_type": "markdown",
1177
+ "source": [
1178
+ "#orwpjgwop"
1179
+ ],
1180
+ "metadata": {
1181
+ "id": "w6OVCivCI4ha"
1182
+ }
1183
+ },
1184
+ {
1185
+ "cell_type": "code",
1186
+ "source": [
1187
+ "# =============================================================================\n",
1188
+ "# CELL 4: PROMPT UPSAMPLER\n",
1189
+ "# FLUX 3 KLEIN SDNQ\n",
1190
+ "# =============================================================================\n",
1191
+ "\n",
1192
+ "import gc\n",
1193
+ "import json\n",
1194
+ "import traceback\n",
1195
+ "import torch\n",
1196
+ "\n",
1197
+ "from transformers import (\n",
1198
+ " AutoProcessor,\n",
1199
+ " AutoModelForCausalLM,\n",
1200
+ ")\n",
1201
+ "\n",
1202
+ "from huggingface_hub import hf_hub_download\n",
1203
+ "\n",
1204
+ "# ---------------------------------------------------------------------\n",
1205
+ "# Reclaim VRAM\n",
1206
+ "# ---------------------------------------------------------------------\n",
1207
+ "\n",
1208
+ "gc.collect()\n",
1209
+ "torch.cuda.empty_cache()\n",
1210
+ "\n",
1211
+ "# ---------------------------------------------------------------------\n",
1212
+ "# Repositories\n",
1213
+ "# ---------------------------------------------------------------------\n",
1214
+ "\n",
1215
+ "PUP_REPO = MODEL_ID\n",
1216
+ "\n",
1217
+ "PUP_SUBFOLDER = \"prompt_upsampler\"\n",
1218
+ "\n",
1219
+ "OFFICIAL_PUP = (\n",
1220
+ " \"black-forest-labs/\"\n",
1221
+ " \"flux-3-image-klein-pup\"\n",
1222
+ ")\n",
1223
+ "\n",
1224
+ "# ---------------------------------------------------------------------\n",
1225
+ "# System prompts\n",
1226
+ "# ---------------------------------------------------------------------\n",
1227
+ "\n",
1228
+ "try:\n",
1229
+ "\n",
1230
+ " system_prompts_path = hf_hub_download(\n",
1231
+ " OFFICIAL_PUP,\n",
1232
+ " \"system_prompts.json\"\n",
1233
+ " )\n",
1234
+ "\n",
1235
+ " with open(\n",
1236
+ " system_prompts_path,\n",
1237
+ " \"r\",\n",
1238
+ " encoding=\"utf-8\"\n",
1239
+ " ) as f:\n",
1240
+ "\n",
1241
+ " system_prompts = json.load(f)\n",
1242
+ "\n",
1243
+ " print(\"βœ… Loaded official system prompts\")\n",
1244
+ "\n",
1245
+ "except Exception as e:\n",
1246
+ "\n",
1247
+ " print(\n",
1248
+ " f\"⚠️ Could not load official \"\n",
1249
+ " f\"system_prompts.json: {e}\"\n",
1250
+ " )\n",
1251
+ "\n",
1252
+ " system_prompts = {\n",
1253
+ " \"t2i\": (\n",
1254
+ " \"Expand the short prompt into a detailed \"\n",
1255
+ " \"photographic scene caption including subject, \"\n",
1256
+ " \"background, lighting, camera, materials and composition.\"\n",
1257
+ " ),\n",
1258
+ "\n",
1259
+ " \"i2i\": (\n",
1260
+ " \"Expand the edit instruction into a detailed \"\n",
1261
+ " \"scene caption that incorporates the reference images.\"\n",
1262
+ " )\n",
1263
+ " }\n",
1264
+ "\n",
1265
+ "# ---------------------------------------------------------------------\n",
1266
+ "# Processor\n",
1267
+ "# ---------------------------------------------------------------------\n",
1268
+ "\n",
1269
+ "print(\"\\nπŸ“₯ Loading official PUP processor...\")\n",
1270
+ "\n",
1271
+ "processor = AutoProcessor.from_pretrained(\n",
1272
+ " OFFICIAL_PUP,\n",
1273
+ " trust_remote_code=True\n",
1274
+ ")\n",
1275
+ "\n",
1276
+ "print(\"βœ… Processor loaded\")\n",
1277
+ "\n",
1278
+ "# ---------------------------------------------------------------------\n",
1279
+ "# Quantized PUP model\n",
1280
+ "# ---------------------------------------------------------------------\n",
1281
+ "\n",
1282
+ "print(\"\\nπŸ“₯ Loading SDNQ prompt upsampler...\")\n",
1283
+ "print(\" Runtime dtype: FP16\")\n",
1284
+ "print(\" Device: CUDA\")\n",
1285
+ "\n",
1286
+ "upsampler = AutoModelForCausalLM.from_pretrained(\n",
1287
+ " PUP_REPO,\n",
1288
+ " subfolder=PUP_SUBFOLDER,\n",
1289
+ " dtype=torch.float16,\n",
1290
+ " device_map=\"cuda\",\n",
1291
+ " trust_remote_code=True,\n",
1292
+ " low_cpu_mem_usage=True,\n",
1293
+ ").eval()\n",
1294
+ "\n",
1295
+ "print(\"βœ… Prompt upsampler loaded\")\n",
1296
+ "\n",
1297
+ "# ---------------------------------------------------------------------\n",
1298
+ "# Prompt function\n",
1299
+ "# ---------------------------------------------------------------------\n",
1300
+ "\n",
1301
+ "def upsample_prompt(\n",
1302
+ " prompt: str,\n",
1303
+ " images=None\n",
1304
+ "):\n",
1305
+ "\n",
1306
+ " if images is None:\n",
1307
+ " images = []\n",
1308
+ "\n",
1309
+ " if not isinstance(\n",
1310
+ " images,\n",
1311
+ " (list, tuple)\n",
1312
+ " ):\n",
1313
+ " images = [images]\n",
1314
+ "\n",
1315
+ " # -------------------------------------------------------------\n",
1316
+ " # Messages\n",
1317
+ " # -------------------------------------------------------------\n",
1318
+ "\n",
1319
+ " if images:\n",
1320
+ "\n",
1321
+ " text = (\n",
1322
+ " \"Reference images follow in order \"\n",
1323
+ " \"(the first image, the second image, ...).\\n\"\n",
1324
+ " f\"User request: {prompt}\\n\"\n",
1325
+ " \"Output the caption.\"\n",
1326
+ " )\n",
1327
+ "\n",
1328
+ " content = (\n",
1329
+ " [\n",
1330
+ " {\n",
1331
+ " \"type\": \"image\",\n",
1332
+ " \"image\": img\n",
1333
+ " }\n",
1334
+ " for img in images\n",
1335
+ " ]\n",
1336
+ " +\n",
1337
+ " [\n",
1338
+ " {\n",
1339
+ " \"type\": \"text\",\n",
1340
+ " \"text\": text\n",
1341
+ " }\n",
1342
+ " ]\n",
1343
+ " )\n",
1344
+ "\n",
1345
+ " messages = [\n",
1346
+ " {\n",
1347
+ " \"role\": \"system\",\n",
1348
+ " \"content\": system_prompts.get(\n",
1349
+ " \"i2i\",\n",
1350
+ " system_prompts[\"t2i\"]\n",
1351
+ " )\n",
1352
+ " },\n",
1353
+ " {\n",
1354
+ " \"role\": \"user\",\n",
1355
+ " \"content\": content\n",
1356
+ " }\n",
1357
+ " ]\n",
1358
+ "\n",
1359
+ " else:\n",
1360
+ "\n",
1361
+ " messages = [\n",
1362
+ " {\n",
1363
+ " \"role\": \"system\",\n",
1364
+ " \"content\": system_prompts[\"t2i\"]\n",
1365
+ " },\n",
1366
+ " {\n",
1367
+ " \"role\": \"user\",\n",
1368
+ " \"content\": prompt\n",
1369
+ " }\n",
1370
+ " ]\n",
1371
+ "\n",
1372
+ " # -------------------------------------------------------------\n",
1373
+ " # Processor\n",
1374
+ " # -------------------------------------------------------------\n",
1375
+ "\n",
1376
+ " inputs = processor.apply_chat_template(\n",
1377
+ " messages,\n",
1378
+ " add_generation_prompt=True,\n",
1379
+ " tokenize=True,\n",
1380
+ " return_dict=True,\n",
1381
+ " return_tensors=\"pt\",\n",
1382
+ " enable_thinking=False\n",
1383
+ " )\n",
1384
+ "\n",
1385
+ " # -------------------------------------------------------------\n",
1386
+ " # Only pass model-supported text inputs\n",
1387
+ " # -------------------------------------------------------------\n",
1388
+ "\n",
1389
+ " allowed_keys = {\n",
1390
+ " \"input_ids\",\n",
1391
+ " \"attention_mask\"\n",
1392
+ " }\n",
1393
+ "\n",
1394
+ " if \"token_type_ids\" in inputs:\n",
1395
+ " allowed_keys.add(\n",
1396
+ " \"token_type_ids\"\n",
1397
+ " )\n",
1398
+ "\n",
1399
+ " filtered_inputs = {\n",
1400
+ " k: v.to(upsampler.device)\n",
1401
+ " if torch.is_tensor(v)\n",
1402
+ " else v\n",
1403
+ "\n",
1404
+ " for k, v in inputs.items()\n",
1405
+ "\n",
1406
+ " if k in allowed_keys\n",
1407
+ " }\n",
1408
+ "\n",
1409
+ " print(\n",
1410
+ " \"\\nπŸ§ͺ PUP input:\",\n",
1411
+ " {\n",
1412
+ " k: (\n",
1413
+ " tuple(v.shape)\n",
1414
+ " if torch.is_tensor(v)\n",
1415
+ " else type(v).__name__\n",
1416
+ " )\n",
1417
+ " for k, v in filtered_inputs.items()\n",
1418
+ " }\n",
1419
+ " )\n",
1420
+ "\n",
1421
+ " # -------------------------------------------------------------\n",
1422
+ " # Generate\n",
1423
+ " # -------------------------------------------------------------\n",
1424
+ "\n",
1425
+ " with torch.inference_mode():\n",
1426
+ "\n",
1427
+ " output = upsampler.generate(\n",
1428
+ " **filtered_inputs,\n",
1429
+ " max_new_tokens=1536,\n",
1430
+ " do_sample=False,\n",
1431
+ " use_cache=True\n",
1432
+ " )\n",
1433
+ "\n",
1434
+ " # -------------------------------------------------------------\n",
1435
+ " # Decode\n",
1436
+ " # -------------------------------------------------------------\n",
1437
+ "\n",
1438
+ " prompt_length = (\n",
1439
+ " filtered_inputs[\n",
1440
+ " \"input_ids\"\n",
1441
+ " ].shape[1]\n",
1442
+ " )\n",
1443
+ "\n",
1444
+ " caption = processor.decode(\n",
1445
+ " output[\n",
1446
+ " 0,\n",
1447
+ " prompt_length:\n",
1448
+ " ],\n",
1449
+ " skip_special_tokens=True\n",
1450
+ " ).strip()\n",
1451
+ "\n",
1452
+ " return caption\n",
1453
+ "\n",
1454
+ "# =============================================================================\n",
1455
+ "# GENERATE CAPTION\n",
1456
+ "# =============================================================================\n",
1457
+ "\n",
1458
+ "FULL_CAPTION = None\n",
1459
+ "PUP_ERROR = None\n",
1460
+ "\n",
1461
+ "print(\"\\n🧠 Generating expanded prompt...\")\n",
1462
+ "print(\" This is the point where the SDNQ/Triton issue\")\n",
1463
+ "print(\" previously occurred.\\n\")\n",
1464
+ "\n",
1465
+ "try:\n",
1466
+ "\n",
1467
+ " FULL_CAPTION = upsample_prompt(\n",
1468
+ " edit_prompt\n",
1469
+ " )\n",
1470
+ "\n",
1471
+ " print(\"\\n\" + \"=\" * 70)\n",
1472
+ " print(\"βœ… PROMPT UPSAMPLER SUCCESS\")\n",
1473
+ " print(\"=\" * 70)\n",
1474
+ "\n",
1475
+ " print(\n",
1476
+ " f\"\\nCaption length: \"\n",
1477
+ " f\"{len(FULL_CAPTION)} characters\\n\"\n",
1478
+ " )\n",
1479
+ "\n",
1480
+ " print(FULL_CAPTION)\n",
1481
+ "\n",
1482
+ "except Exception as e:\n",
1483
+ "\n",
1484
+ " PUP_ERROR = e\n",
1485
+ "\n",
1486
+ " print(\"\\n\" + \"=\" * 70)\n",
1487
+ " print(\"❌ PROMPT UPSAMPLER FAILED\")\n",
1488
+ " print(\"=\" * 70)\n",
1489
+ "\n",
1490
+ " print(\n",
1491
+ " \"\\nThis is expected to reach the diagnostic \"\n",
1492
+ " \"cell below if the SDNQ Triton kernel is still broken.\\n\"\n",
1493
+ " )\n",
1494
+ "\n",
1495
+ " print(\n",
1496
+ " f\"Error type: {type(e).__name__}\"\n",
1497
+ " )\n",
1498
+ "\n",
1499
+ " print(\n",
1500
+ " f\"Error: {e}\"\n",
1501
+ " )\n",
1502
+ "\n",
1503
+ " traceback.print_exc()\n",
1504
+ "\n",
1505
+ "# ---------------------------------------------------------------------\n",
1506
+ "# Free PUP\n",
1507
+ "# ---------------------------------------------------------------------\n",
1508
+ "\n",
1509
+ "print(\"\\n🧹 Freeing prompt upsampler...\")\n",
1510
+ "\n",
1511
+ "try:\n",
1512
+ " del upsampler\n",
1513
+ "except:\n",
1514
+ " pass\n",
1515
+ "\n",
1516
+ "try:\n",
1517
+ " del processor\n",
1518
+ "except:\n",
1519
+ " pass\n",
1520
+ "\n",
1521
+ "gc.collect()\n",
1522
+ "torch.cuda.empty_cache()\n",
1523
+ "\n",
1524
+ "print(\"βœ… PUP memory released\")\n",
1525
+ "\n",
1526
+ "if FULL_CAPTION is None:\n",
1527
+ " print(\n",
1528
+ " \"\\n⚠️ FULL_CAPTION is None.\"\n",
1529
+ " \"\\nThe final diagnostic cell will now determine \"\n",
1530
+ " \"whether SDNQ's Triton INT8 matmul is the problem.\"\n",
1531
+ " )"
1532
+ ],
1533
+ "metadata": {
1534
+ "id": "u6Pt0R69_Hv-"
1535
+ },
1536
+ "execution_count": null,
1537
+ "outputs": []
1538
+ },
1539
+ {
1540
+ "cell_type": "markdown",
1541
+ "source": [
1542
+ "# CONT"
1543
+ ],
1544
+ "metadata": {
1545
+ "id": "VkzXQxOK-ooR"
1546
+ }
1547
+ },
1548
+ {
1549
+ "cell_type": "code",
1550
+ "source": [
1551
+ "# =============================================================================\n",
1552
+ "# CELL 4: Parallel Workers\n",
1553
+ "# =============================================================================\n",
1554
+ "\n",
1555
+ "import io, gc, zipfile, hashlib, traceback, random as pyrandom, shutil, time\n",
1556
+ "from PIL import Image\n",
1557
+ "from nacl.secret import SecretBox\n",
1558
+ "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
1559
+ "from pathlib import Path\n",
1560
+ "\n",
1561
+ "output_folders = [f\"/content/edited_gpu{gpu}_pipe{p}\" for gpu in range(NUM_GPUS) for p in range(PIPES_PER_GPU)]\n",
1562
+ "final_output_folder = \"/content/final_encrypted\"\n",
1563
+ "for folder in output_folders + [final_output_folder]:\n",
1564
+ " os.makedirs(folder, exist_ok=True)\n",
1565
+ "\n",
1566
+ "password = (Path(google_drive_dataset_path) / \"password.txt\").read_text(encoding=\"utf-8\").strip()\n",
1567
+ "key = hashlib.sha256(password.encode()).digest()\n",
1568
+ "box = SecretBox(key)\n",
1569
+ "\n",
1570
+ "foreground_zip = zipfile.ZipFile(encrypted_input_dataset_path, \"r\")\n",
1571
+ "background_zip = zipfile.ZipFile(backgrounds_input_dataset_path, \"r\")\n",
1572
+ "\n",
1573
+ "input_files = sorted([x for x in foreground_zip.namelist() if x.endswith(\"_encrypted.bin\")])\n",
1574
+ "bg_files = sorted([x for x in background_zip.namelist() if x.endswith(\"_encrypted.bin\")])\n",
1575
+ "\n",
1576
+ "print(f\"πŸ“Š Found {len(input_files)} foregrounds | {len(bg_files)} backgrounds\")\n",
1577
+ "\n",
1578
+ "def worker_thread(pipe, gpu_id, start_idx, num_images, worker_id):\n",
1579
+ " torch.cuda.set_device(gpu_id)\n",
1580
+ " torch._dynamo.reset()\n",
1581
+ " torch._dynamo.config.suppress_errors = True\n",
1582
+ " torch._dynamo.config.disable = True\n",
1583
+ " os.environ[\"TORCHDYNAMO_DISABLE\"] = \"1\"\n",
1584
+ "\n",
1585
+ " def decrypt(data):\n",
1586
+ " return box.decrypt(data)\n",
1587
+ "\n",
1588
+ " def encrypt(data):\n",
1589
+ " return box.encrypt(data)\n",
1590
+ "\n",
1591
+ " def bytes_to_pil(b):\n",
1592
+ " return Image.open(io.BytesIO(b)).convert(\"RGB\")\n",
1593
+ "\n",
1594
+ " def pil_to_bytes(img):\n",
1595
+ " buf = io.BytesIO()\n",
1596
+ " img.save(buf, format=\"JPEG\", quality=90)\n",
1597
+ " return buf.getvalue()\n",
1598
+ "\n",
1599
+ " def resize_max_side(pil_image: Image.Image, max_size: int = 1024) -> Image.Image:\n",
1600
+ " if max(pil_image.size) <= max_size:\n",
1601
+ " return pil_image\n",
1602
+ " w, h = pil_image.size\n",
1603
+ " if w > h:\n",
1604
+ " new_w = max_size\n",
1605
+ " new_h = int(h * (max_size / w))\n",
1606
+ " else:\n",
1607
+ " new_h = max_size\n",
1608
+ " new_w = int(w * (max_size / h))\n",
1609
+ " return pil_image.resize((new_w, new_h), Image.LANCZOS)\n",
1610
+ "\n",
1611
+ " for i in range(num_images):\n",
1612
+ " global_idx = start_idx + i\n",
1613
+ " if global_idx >= len(input_files):\n",
1614
+ " break\n",
1615
+ "\n",
1616
+ " try:\n",
1617
+ " gc.collect()\n",
1618
+ " torch.cuda.empty_cache()\n",
1619
+ "\n",
1620
+ " # Foreground\n",
1621
+ " fg_name = input_files[global_idx]\n",
1622
+ " with foreground_zip.open(fg_name) as f:\n",
1623
+ " decrypted_fg = decrypt(f.read())\n",
1624
+ " input_image = bytes_to_pil(decrypted_fg)\n",
1625
+ " input_image = resize_max_side(input_image, 1024)\n",
1626
+ "\n",
1627
+ " # Background (random)\n",
1628
+ " bg_name = pyrandom.choice(bg_files)\n",
1629
+ " with background_zip.open(bg_name) as f:\n",
1630
+ " decrypted_bg = decrypt(f.read())\n",
1631
+ " bg_image = bytes_to_pil(decrypted_bg)\n",
1632
+ " bg_image = resize_max_side(bg_image, 1024)\n",
1633
+ "\n",
1634
+ " # ---- Prompt Upsampling (critical for Flux 3) ----\n",
1635
+ " full_caption = upsample_prompt(edit_prompt, images=[input_image, bg_image])\n",
1636
+ " # print(f\"Caption preview: {full_caption[:120]}...\")\n",
1637
+ "\n",
1638
+ " # ---- Inference ----\n",
1639
+ " with torch.inference_mode(), torch.no_grad():\n",
1640
+ " result = pipe(\n",
1641
+ " prompt=full_caption,\n",
1642
+ " image=[input_image, bg_image], # multi-reference\n",
1643
+ " height=target_height,\n",
1644
+ " width=target_width,\n",
1645
+ " num_inference_steps=16, # distilled default\n",
1646
+ " guidance_scale=1.0,\n",
1647
+ " generator=torch.Generator(f\"cuda:{gpu_id}\").manual_seed(42 + global_idx),\n",
1648
+ " output=\"images\",\n",
1649
+ " )[0]\n",
1650
+ "\n",
1651
+ " # Encrypt & save\n",
1652
+ " encrypted_result = encrypt(pil_to_bytes(result))\n",
1653
+ " out_path = os.path.join(output_folders[worker_id], f\"edited_{global_idx:06d}.enc\")\n",
1654
+ " with open(out_path, \"wb\") as f:\n",
1655
+ " f.write(encrypted_result)\n",
1656
+ "\n",
1657
+ " print(f\"βœ… Worker {worker_id} (GPU {gpu_id}) β†’ {global_idx+1}/{len(input_files)}\")\n",
1658
+ "\n",
1659
+ " del result, input_image, bg_image, decrypted_fg, decrypted_bg, encrypted_result, full_caption\n",
1660
+ "\n",
1661
+ " except Exception as e:\n",
1662
+ " print(f\"❌ Worker {worker_id} failed at {global_idx}: {e}\")\n",
1663
+ " traceback.print_exc()\n",
1664
+ "\n",
1665
+ " gc.collect()\n",
1666
+ "\n",
1667
+ " return True\n",
1668
+ "\n",
1669
+ "\n",
1670
+ "print(\"\\nπŸš€ Starting parallel workers...\")\n",
1671
+ "\n",
1672
+ "chunk_size = (len(input_files) + len(pipes) - 1) // len(pipes)\n",
1673
+ "\n",
1674
+ "futures = []\n",
1675
+ "with ThreadPoolExecutor(max_workers=len(pipes)) as executor:\n",
1676
+ " for w in range(len(pipes)):\n",
1677
+ " start_idx = w * chunk_size\n",
1678
+ " num_images = min(chunk_size, len(input_files) - start_idx)\n",
1679
+ " if num_images <= 0:\n",
1680
+ " continue\n",
1681
+ " if w > 0:\n",
1682
+ " time.sleep(1.5)\n",
1683
+ "\n",
1684
+ " future = executor.submit(\n",
1685
+ " worker_thread,\n",
1686
+ " pipes[w],\n",
1687
+ " gpu_ids_list[w],\n",
1688
+ " start_idx,\n",
1689
+ " num_images,\n",
1690
+ " w\n",
1691
+ " )\n",
1692
+ " futures.append(future)\n",
1693
+ "\n",
1694
+ " for future in as_completed(futures):\n",
1695
+ " try:\n",
1696
+ " future.result()\n",
1697
+ " except Exception as e:\n",
1698
+ " print(f\"Worker failed with: {e}\")\n",
1699
+ "\n",
1700
+ "print(\"\\nπŸŽ‰ All workers completed!\")\n",
1701
+ "\n",
1702
+ "foreground_zip.close()\n",
1703
+ "background_zip.close()\n",
1704
+ "gc.collect()"
1705
+ ],
1706
+ "metadata": {
1707
+ "id": "AzTKRdQE1Acx"
1708
+ },
1709
+ "execution_count": null,
1710
+ "outputs": []
1711
+ },
1712
+ {
1713
+ "cell_type": "code",
1714
+ "source": [
1715
+ "# =============================================================================\n",
1716
+ "# CELL 5: Combine into Final ZIP\n",
1717
+ "# =============================================================================\n",
1718
+ "\n",
1719
+ "import shutil\n",
1720
+ "from pathlib import Path\n",
1721
+ "\n",
1722
+ "print(\"πŸ“¦ Creating final zip...\")\n",
1723
+ "\n",
1724
+ "for folder in output_folders:\n",
1725
+ " if os.path.exists(folder):\n",
1726
+ " for f in Path(folder).glob(\"*.enc\"):\n",
1727
+ " shutil.copy2(f, os.path.join(final_output_folder, f.name))\n",
1728
+ "\n",
1729
+ "collected = len(list(Path(final_output_folder).glob(\"*.enc\")))\n",
1730
+ "print(f\"Collected {collected} encrypted files\")\n",
1731
+ "\n",
1732
+ "final_zip_base = \"/content/final_encrypted_outputs\"\n",
1733
+ "shutil.make_archive(final_zip_base, 'zip', final_output_folder)\n",
1734
+ "\n",
1735
+ "print(f\"\\nβœ… SUCCESS! Final file: {final_zip_base}.zip\")\n",
1736
+ "print(\"You can download it from the file browser.\")"
1737
+ ],
1738
+ "metadata": {
1739
+ "id": "mTxspyuT1DrZ"
1740
+ },
1741
+ "execution_count": null,
1742
+ "outputs": []
1743
+ },
1744
+ {
1745
+ "cell_type": "code",
1746
+ "source": [],
1747
+ "metadata": {
1748
+ "id": "RfFDaKSg1EUd"
1749
+ },
1750
+ "execution_count": null,
1751
+ "outputs": []
1752
+ },
1753
+ {
1754
+ "cell_type": "code",
1755
+ "source": [
1756
+ "import os\n",
1757
+ "import shutil\n",
1758
+ "import io\n",
1759
+ "import hashlib\n",
1760
+ "from pathlib import Path\n",
1761
+ "from PIL import Image\n",
1762
+ "!pip install pynacl\n",
1763
+ "from nacl.secret import SecretBox\n",
1764
+ "from google.colab import files\n",
1765
+ "import zipfile\n",
1766
+ "from google.colab import drive\n",
1767
+ "#@markdown πŸ”‘ Decrypt Results (either by widget uploading zip or by manual filepath to saved zip on drive)\n",
1768
+ "print(\"πŸ”“ Decryption Notebook Ready\")\n",
1769
+ "\n",
1770
+ "# ------------------- INPUTS -------------------\n",
1771
+ "password = 'banana' # @param {type:\"string\"}\n",
1772
+ "use_manual_filepath = True # @param {type:\"boolean\"}\n",
1773
+ "manual_filepath = '/content/final_encrypted_outputs.zip' # @param {type:\"string\"}\n",
1774
+ "\n",
1775
+ "# ------------------- FILE INPUT LOGIC -------------------\n",
1776
+ "zip_filename = None\n",
1777
+ "\n",
1778
+ "if use_manual_filepath:\n",
1779
+ " if not os.path.exists('/content/drive'):\n",
1780
+ " print(\"πŸ”„ Mounting Google Drive...\")\n",
1781
+ " drive.mount('/content/drive')\n",
1782
+ "\n",
1783
+ " if not manual_filepath:\n",
1784
+ " raise ValueError(\"❌ Manual filepath cannot be empty when 'Use manual filepath' is enabled!\")\n",
1785
+ "\n",
1786
+ " if not os.path.exists(manual_filepath):\n",
1787
+ " raise FileNotFoundError(f\"❌ File not found at manual filepath: {manual_filepath}\")\n",
1788
+ "\n",
1789
+ " zip_filename = manual_filepath\n",
1790
+ " print(f\"βœ… Using manual filepath: {zip_filename}\")\n",
1791
+ "else:\n",
1792
+ " print(\"\\nπŸ“€ Upload your final_encrypted_outputs.zip file:\")\n",
1793
+ " uploaded = files.upload()\n",
1794
+ "\n",
1795
+ " for fn in uploaded.keys():\n",
1796
+ " if fn.endswith('.zip'):\n",
1797
+ " zip_filename = fn\n",
1798
+ " break\n",
1799
+ "\n",
1800
+ " if not zip_filename:\n",
1801
+ " raise ValueError(\"❌ No .zip file was uploaded!\")\n",
1802
+ "\n",
1803
+ " print(f\"βœ… Uploaded: {zip_filename}\")\n",
1804
+ "\n",
1805
+ "# ------------------- DECRYPTION FUNCTION -------------------\n",
1806
+ "def decrypt_data(encrypted_data: bytes, box: SecretBox) -> bytes:\n",
1807
+ " try:\n",
1808
+ " return box.decrypt(encrypted_data)\n",
1809
+ " except Exception as e:\n",
1810
+ " raise ValueError(f\"Decryption failed (wrong password?): {e})\")\n",
1811
+ "\n",
1812
+ "# ------------------- MAIN DECRYPTION -------------------\n",
1813
+ "\n",
1814
+ "if not password:\n",
1815
+ " raise ValueError(\"❌ Password cannot be empty!\")\n",
1816
+ "\n",
1817
+ "# Derive the same key as in the encryption code\n",
1818
+ "key = hashlib.sha256(password.encode('utf-8')).digest()\n",
1819
+ "box = SecretBox(key)\n",
1820
+ "\n",
1821
+ "# Create output folder\n",
1822
+ "output_dir = \"/content/decrypted_images\"\n",
1823
+ "os.makedirs(output_dir, exist_ok=True)\n",
1824
+ "\n",
1825
+ "print(f\"\\nπŸ“‚ Extracting and decrypting to: {output_dir}\")\n",
1826
+ "\n",
1827
+ "# Extract zip\n",
1828
+ "with zipfile.ZipFile(zip_filename, 'r') as zip_ref:\n",
1829
+ " zip_ref.extractall(\"/content/temp_extracted\")\n",
1830
+ "\n",
1831
+ "# Find all .enc files\n",
1832
+ "enc_files = list(Path(\"/content/temp_extracted\").rglob(\"*.enc\"))\n",
1833
+ "\n",
1834
+ "print(f\"πŸ” Found {len(enc_files)} encrypted files\")\n",
1835
+ "\n",
1836
+ "success_count = 0\n",
1837
+ "\n",
1838
+ "for enc_path in enc_files:\n",
1839
+ " try:\n",
1840
+ " with open(enc_path, \"rb\") as f:\n",
1841
+ " encrypted_bytes = f.read()\n",
1842
+ "\n",
1843
+ " # Decrypt\n",
1844
+ " decrypted_bytes = decrypt_data(encrypted_bytes, box)\n",
1845
+ "\n",
1846
+ " # Convert to PIL Image and save as JPG\n",
1847
+ " img = Image.open(io.BytesIO(decrypted_bytes)).convert(\"RGB\")\n",
1848
+ "\n",
1849
+ " output_path = os.path.join(output_dir, enc_path.stem + \".jpg\")\n",
1850
+ " img.save(output_path, format=\"JPEG\", quality=95)\n",
1851
+ "\n",
1852
+ " success_count += 1\n",
1853
+ " print(f\"βœ… Decrypted: {enc_path.name} β†’ {Path(output_path).name}\")\n",
1854
+ "\n",
1855
+ " except Exception as e:\n",
1856
+ " print(f\"❌ Failed {enc_path.name}: {e}\")\n",
1857
+ "\n",
1858
+ "# Cleanup temp folder\n",
1859
+ "shutil.rmtree(\"/content/temp_extracted\", ignore_errors=True)\n",
1860
+ "\n",
1861
+ "print(f\"\\nπŸŽ‰ Decryption complete! {success_count}/{len(enc_files)} files decrypted successfully.\")\n",
1862
+ "print(f\"πŸ“ Decrypted images saved to: {output_dir}\")\n",
1863
+ "\n",
1864
+ "# Optional: Download all decrypted images as a new zip\n",
1865
+ "download_zip = True #input(\"\\nDo you want to download all decrypted images as a zip? (y/n): \").lower().strip() == 'y'\n",
1866
+ "\n",
1867
+ "if download_zip:\n",
1868
+ " download_zip_path = \"/content/decrypted_images.zip\"\n",
1869
+ " shutil.make_archive(\"/content/decrypted_images\", 'zip', output_dir)\n",
1870
+ " files.download(download_zip_path)\n",
1871
+ " print(\"πŸ“₯ Download started...\")"
1872
+ ],
1873
+ "metadata": {
1874
+ "id": "GvLYqh4iMBf_"
1875
+ },
1876
+ "execution_count": null,
1877
+ "outputs": []
1878
+ },
1879
+ {
1880
+ "cell_type": "markdown",
1881
+ "source": [
1882
+ "# CREATE SDNQ (For reference)"
1883
+ ],
1884
+ "metadata": {
1885
+ "id": "95PI6Rr74piE"
1886
+ }
1887
+ },
1888
+ {
1889
+ "cell_type": "code",
1890
+ "source": [
1891
+ "# CREATEW SDNQ - only kept for reference\n",
1892
+ "if False:\n",
1893
+ " #@title CELL 1 β€” Install + HF Login\n",
1894
+ " !pip install -q --upgrade huggingface_hub transformers accelerate safetensors\n",
1895
+ " !pip install -q git+https://github.com/huggingface/diffusers.git\n",
1896
+ " !pip install -q sdnq\n",
1897
+ "\n",
1898
+ " import os\n",
1899
+ " import gc\n",
1900
+ " import sys\n",
1901
+ " import time\n",
1902
+ " import math\n",
1903
+ " import random\n",
1904
+ " import warnings\n",
1905
+ " import subprocess\n",
1906
+ " import traceback\n",
1907
+ " import re\n",
1908
+ " import shutil\n",
1909
+ " import importlib.util\n",
1910
+ " import logging\n",
1911
+ " from pathlib import Path\n",
1912
+ " from collections import Counter\n",
1913
+ " from huggingface_hub import login, HfApi\n",
1914
+ "\n",
1915
+ "\n",
1916
+ " import os\n",
1917
+ " # Put your token in Kaggle Secrets as \"HF_TOKEN\"\n",
1918
+ " from kaggle_secrets import UserSecretsClient\n",
1919
+ " user_secrets = UserSecretsClient()\n",
1920
+ " DATASET_DIR = Path(\n",
1921
+ " \"/kaggle/input/datasets/nekos4lyfe/image-caption-dataset\"\n",
1922
+ " )\n",
1923
+ " hf_token_path = DATASET_DIR / \"HF_TOKEN.txt\"\n",
1924
+ "\n",
1925
+ " if hf_token_path.exists():\n",
1926
+ "\n",
1927
+ " hf_token = hf_token_path.read_text(\n",
1928
+ " encoding=\"utf-8\"\n",
1929
+ " ).strip()\n",
1930
+ " login(token=hf_token)\n",
1931
+ "\n",
1932
+ " print(\"βœ… Environment ready\")\n",
1933
+ "\n",
1934
+ " #@title CELL 2 β€” Load full transformer on CPU\n",
1935
+ " import torch, gc, os\n",
1936
+ " from diffusers import Flux3Transformer2DModel\n",
1937
+ "\n",
1938
+ " gc.collect()\n",
1939
+ " torch.cuda.empty_cache()\n",
1940
+ "\n",
1941
+ " print(\"Loading Flux3Transformer2DModel on CPU (low_cpu_mem_usage)...\")\n",
1942
+ " transformer = Flux3Transformer2DModel.from_pretrained(\n",
1943
+ " \"black-forest-labs/flux-3-image-klein\",\n",
1944
+ " subfolder=\"transformer\",\n",
1945
+ " torch_dtype=torch.float16,\n",
1946
+ " low_cpu_mem_usage=True,\n",
1947
+ " device_map=\"cpu\",\n",
1948
+ " token=hf_token,\n",
1949
+ " )\n",
1950
+ "\n",
1951
+ " print(\"βœ… Transformer loaded on CPU\")\n",
1952
+ " print(f\"Total parameters: {sum(p.numel() for p in transformer.parameters()) / 1e9:.2f} B\")\n",
1953
+ "\n",
1954
+ " #@title CELL 3 β€” Sequential SDNQ quantization (fixed)\n",
1955
+ " from sdnq import sdnq_post_load_quant\n",
1956
+ " import torch, gc\n",
1957
+ " from torch import nn\n",
1958
+ "\n",
1959
+ " def free():\n",
1960
+ " gc.collect()\n",
1961
+ " torch.cuda.empty_cache()\n",
1962
+ "\n",
1963
+ " # -------------------------------------------------\n",
1964
+ " # Same SDNQ config\n",
1965
+ " # -------------------------------------------------\n",
1966
+ " SDNQ_KWARGS = dict(\n",
1967
+ " weights_dtype=\"int4\",\n",
1968
+ " group_size=0,\n",
1969
+ " use_svd=False,\n",
1970
+ " quant_conv=False,\n",
1971
+ " quant_embedding=False,\n",
1972
+ " use_quantized_matmul=True,\n",
1973
+ " dequantize_fp32=True,\n",
1974
+ " non_blocking=False,\n",
1975
+ " add_skip_keys=True,\n",
1976
+ " quantization_device=\"cuda\",\n",
1977
+ " return_device=\"cpu\",\n",
1978
+ " modules_to_not_convert=[\n",
1979
+ " \"x_embedder\", \"context_embedder\", \"pos_embed\", \"norm_out\",\n",
1980
+ " \".proj_out\", \"time_guidance_embed\", \"final_layer\",\n",
1981
+ " \"double_stream_modulation_img\", \"double_stream_modulation_txt\",\n",
1982
+ " \"single_stream_modulation\",\n",
1983
+ " \"target_timestep_embedder\",\n",
1984
+ " ],\n",
1985
+ " )\n",
1986
+ "\n",
1987
+ " # -------------------------------------------------\n",
1988
+ " # Robustly collect every major block (ModuleList or ModuleDict)\n",
1989
+ " # -------------------------------------------------\n",
1990
+ " blocks = [] # list of (full_name, module)\n",
1991
+ "\n",
1992
+ " def collect_blocks(root, prefix=\"\"):\n",
1993
+ " \"\"\"Recursively find ModuleLists / ModuleDicts that contain transformer blocks.\"\"\"\n",
1994
+ " for name, child in root.named_children():\n",
1995
+ " full_name = f\"{prefix}.{name}\" if prefix else name\n",
1996
+ "\n",
1997
+ " # Case 1: ModuleList of blocks\n",
1998
+ " if isinstance(child, nn.ModuleList):\n",
1999
+ " for i, blk in enumerate(child):\n",
2000
+ " if isinstance(blk, nn.Module):\n",
2001
+ " blocks.append((f\"{full_name}.{i}\", blk))\n",
2002
+ " continue\n",
2003
+ "\n",
2004
+ " # Case 2: ModuleDict of blocks (or of ModuleLists)\n",
2005
+ " if isinstance(child, nn.ModuleDict):\n",
2006
+ " for key, sub in child.items():\n",
2007
+ " if isinstance(sub, nn.ModuleList):\n",
2008
+ " for i, blk in enumerate(sub):\n",
2009
+ " if isinstance(blk, nn.Module):\n",
2010
+ " blocks.append((f\"{full_name}.{key}.{i}\", blk))\n",
2011
+ " elif isinstance(sub, nn.Module):\n",
2012
+ " # single module under a key\n",
2013
+ " blocks.append((f\"{full_name}.{key}\", sub))\n",
2014
+ " continue\n",
2015
+ "\n",
2016
+ " # Recurse deeper for nested structures\n",
2017
+ " collect_blocks(child, full_name)\n",
2018
+ "\n",
2019
+ " # Run discovery\n",
2020
+ " collect_blocks(transformer)\n",
2021
+ "\n",
2022
+ " print(f\"Found {len(blocks)} major blocks\")\n",
2023
+ " for n, _ in blocks[:5]:\n",
2024
+ " print(\" \", n)\n",
2025
+ " if len(blocks) > 5:\n",
2026
+ " print(\" ...\")\n",
2027
+ "\n",
2028
+ " # Split into ~20 equal parts (or 1 block each if you prefer)\n",
2029
+ " N_PARTS = 20\n",
2030
+ " chunk_size = max(1, (len(blocks) + N_PARTS - 1) // N_PARTS)\n",
2031
+ " parts = [blocks[i:i + chunk_size] for i in range(0, len(blocks), chunk_size)]\n",
2032
+ " print(f\"Split into {len(parts)} parts (β‰ˆ{chunk_size} blocks each)\")\n",
2033
+ "\n",
2034
+ " # -------------------------------------------------\n",
2035
+ " # Quantize one part at a time\n",
2036
+ " # -------------------------------------------------\n",
2037
+ " num_gpus = torch.cuda.device_count()\n",
2038
+ " print(f\"Using {num_gpus} GPU(s)\")\n",
2039
+ "\n",
2040
+ " for part_idx, part in enumerate(parts):\n",
2041
+ " device = f\"cuda:{part_idx % num_gpus}\"\n",
2042
+ " print(f\"\\n=== Part {part_idx+1}/{len(parts)} on {device} ===\")\n",
2043
+ "\n",
2044
+ " # 1. Move blocks of this part to GPU\n",
2045
+ " for name, blk in part:\n",
2046
+ " blk.to(device)\n",
2047
+ " free()\n",
2048
+ "\n",
2049
+ " # 2. Quantize each block\n",
2050
+ " for name, blk in part:\n",
2051
+ " print(f\" Quantizing {name} ...\")\n",
2052
+ " quantized_blk = sdnq_post_load_quant(\n",
2053
+ " blk,\n",
2054
+ " **{**SDNQ_KWARGS, \"quantization_device\": device}\n",
2055
+ " )\n",
2056
+ "\n",
2057
+ " # Put the quantized module back into the original model tree\n",
2058
+ " parent = transformer\n",
2059
+ " attrs = name.split(\".\")\n",
2060
+ " for a in attrs[:-1]:\n",
2061
+ " parent = getattr(parent, a)\n",
2062
+ " setattr(parent, attrs[-1], quantized_blk.to(\"cpu\"))\n",
2063
+ "\n",
2064
+ " del quantized_blk\n",
2065
+ " free()\n",
2066
+ "\n",
2067
+ " # 3. Ensure everything is back on CPU\n",
2068
+ " for name, blk in part:\n",
2069
+ " # blk may already be replaced, so we re-fetch it\n",
2070
+ " parent = transformer\n",
2071
+ " attrs = name.split(\".\")\n",
2072
+ " for a in attrs[:-1]:\n",
2073
+ " parent = getattr(parent, a)\n",
2074
+ " getattr(parent, attrs[-1]).to(\"cpu\")\n",
2075
+ " free()\n",
2076
+ "\n",
2077
+ " print(\"\\nβœ… All major blocks quantized successfully\")\n",
2078
+ "\n",
2079
+ " #@title CELL 4 β€” Quantize remaining modules + Save\n",
2080
+ " print(\"Quantizing remaining (non-block) modules on cuda:0 ...\")\n",
2081
+ "\n",
2082
+ " # Everything that is still on CPU and not yet quantized\n",
2083
+ " # will be handled by one final call on the whole model.\n",
2084
+ " # Because the heavy blocks are already quantized, this is cheap.\n",
2085
+ " transformer = sdnq_post_load_quant(\n",
2086
+ " transformer,\n",
2087
+ " **{**SDNQ_KWARGS, \"quantization_device\": \"cuda:0\"}\n",
2088
+ " )\n",
2089
+ "\n",
2090
+ " free()\n",
2091
+ "\n",
2092
+ " save_dir = \"/kaggle/working/flux3-klein-sdnq-int4/transformer\"\n",
2093
+ " os.makedirs(save_dir, exist_ok=True)\n",
2094
+ "\n",
2095
+ " print(\"Saving quantized transformer (this writes the merged safetensors)...\")\n",
2096
+ " transformer.save_pretrained(save_dir, safe_serialization=True)\n",
2097
+ " print(f\"βœ… Saved to {save_dir}\")\n",
2098
+ "\n",
2099
+ " # Optional: show the files\n",
2100
+ " !ls -lh {save_dir}\n",
2101
+ "\n",
2102
+ " #@title CELL 5 β€” Upload to Hugging Face\n",
2103
+ " from huggingface_hub import HfApi, create_repo\n",
2104
+ " import os\n",
2105
+ "\n",
2106
+ " repo_id = \"codeShare/flux-3-image-klein-sdnq-int4\" # ← change if you want\n",
2107
+ "\n",
2108
+ " api = HfApi()\n",
2109
+ " try:\n",
2110
+ " if not api.repo_exists(repo_id=repo_id, repo_type=\"model\"):\n",
2111
+ " create_repo(repo_id=repo_id, repo_type=\"model\", private=False, token=hf_token)\n",
2112
+ " print(\"Repo created\")\n",
2113
+ " else:\n",
2114
+ " print(\"Repo already exists\")\n",
2115
+ " except Exception as e:\n",
2116
+ " print(e)\n",
2117
+ "\n",
2118
+ " print(\"Uploading transformer folder...\")\n",
2119
+ " api.upload_folder(\n",
2120
+ " folder_path=\"/kaggle/working/flux3-klein-sdnq-int4/transformer\",\n",
2121
+ " repo_id=repo_id,\n",
2122
+ " repo_type=\"model\",\n",
2123
+ " path_in_repo=\"transformer\",\n",
2124
+ " commit_message=\"SDNQ int4 quantized Flux3Transformer2DModel (split quantization)\",\n",
2125
+ " )\n",
2126
+ "\n",
2127
+ " print(f\"\\nπŸŽ‰ Done! β†’ https://huggingface.co/{repo_id}\")\n",
2128
+ "\n",
2129
+ " #@title CELL 6 β€” Quantize Text Encoder\n",
2130
+ " from transformers import AutoModel\n",
2131
+ " from sdnq import sdnq_post_load_quant\n",
2132
+ " import torch, gc, os\n",
2133
+ "\n",
2134
+ " def free():\n",
2135
+ " gc.collect()\n",
2136
+ " torch.cuda.empty_cache()\n",
2137
+ "\n",
2138
+ " print(\"Loading Text Encoder (Qwen3-VL-4B) on CPU...\")\n",
2139
+ " text_encoder = AutoModel.from_pretrained(\n",
2140
+ " \"black-forest-labs/flux-3-image-klein\",\n",
2141
+ " subfolder=\"text_encoder\",\n",
2142
+ " torch_dtype=torch.float16,\n",
2143
+ " low_cpu_mem_usage=True,\n",
2144
+ " device_map=\"cpu\",\n",
2145
+ " token=hf_token,\n",
2146
+ " )\n",
2147
+ "\n",
2148
+ " print(\"Applying SDNQ int4 to Text Encoder...\")\n",
2149
+ " text_encoder = sdnq_post_load_quant(\n",
2150
+ " text_encoder,\n",
2151
+ " weights_dtype=\"int4\",\n",
2152
+ " group_size=0,\n",
2153
+ " use_svd=False,\n",
2154
+ " quant_conv=False,\n",
2155
+ " quant_embedding=False, # keep embeddings full precision\n",
2156
+ " use_quantized_matmul=True,\n",
2157
+ " dequantize_fp32=True,\n",
2158
+ " quantization_device=\"cuda:0\",\n",
2159
+ " return_device=\"cpu\",\n",
2160
+ " modules_to_not_convert=[\n",
2161
+ " \"embed_tokens\",\n",
2162
+ " \"lm_head\",\n",
2163
+ " \"model.norm\",\n",
2164
+ " \"model.rotary_emb\",\n",
2165
+ " \"visual\", # vision tower\n",
2166
+ " ],\n",
2167
+ " )\n",
2168
+ "\n",
2169
+ " os.makedirs(\"/kaggle/working/flux3-klein-sdnq-int4/text_encoder\", exist_ok=True)\n",
2170
+ " text_encoder.save_pretrained(\n",
2171
+ " \"/kaggle/working/flux3-klein-sdnq-int4/text_encoder\",\n",
2172
+ " safe_serialization=True\n",
2173
+ " )\n",
2174
+ " print(\"βœ… Text Encoder quantized & saved\")\n",
2175
+ "\n",
2176
+ " del text_encoder\n",
2177
+ " free()\n",
2178
+ "\n",
2179
+ " #@title CELL 7 β€” Quantize Prompt Upsampler (9B)\n",
2180
+ " from transformers import AutoModelForCausalLM\n",
2181
+ " from sdnq import sdnq_post_load_quant\n",
2182
+ " import torch, gc, os\n",
2183
+ "\n",
2184
+ " print(\"Loading Prompt Upsampler (9B) on CPU (this takes time & RAM)...\")\n",
2185
+ " upsampler = AutoModelForCausalLM.from_pretrained(\n",
2186
+ " \"black-forest-labs/flux-3-image-klein-pup\",\n",
2187
+ " torch_dtype=torch.float16,\n",
2188
+ " low_cpu_mem_usage=True,\n",
2189
+ " device_map=\"cpu\",\n",
2190
+ " token=hf_token,\n",
2191
+ " )\n",
2192
+ "\n",
2193
+ " print(\"Applying SDNQ int4 to Prompt Upsampler...\")\n",
2194
+ " upsampler = sdnq_post_load_quant(\n",
2195
+ " upsampler,\n",
2196
+ " weights_dtype=\"int4\",\n",
2197
+ " group_size=0,\n",
2198
+ " use_svd=False,\n",
2199
+ " quant_conv=False,\n",
2200
+ " quant_embedding=False,\n",
2201
+ " use_quantized_matmul=True,\n",
2202
+ " dequantize_fp32=True,\n",
2203
+ " quantization_device=\"cuda:0\",\n",
2204
+ " return_device=\"cpu\",\n",
2205
+ " modules_to_not_convert=[\n",
2206
+ " \"embed_tokens\",\n",
2207
+ " \"lm_head\",\n",
2208
+ " \"model.norm\",\n",
2209
+ " \"model.rotary_emb\",\n",
2210
+ " \"model.layers.0\", # first layer\n",
2211
+ " \"model.layers.35\", # last layer (adjust if different)\n",
2212
+ " ],\n",
2213
+ " )\n",
2214
+ "\n",
2215
+ " os.makedirs(\"/kaggle/working/flux3-klein-sdnq-int4/prompt_upsampler\", exist_ok=True)\n",
2216
+ " upsampler.save_pretrained(\n",
2217
+ " \"/kaggle/working/flux3-klein-sdnq-int4/prompt_upsampler\",\n",
2218
+ " safe_serialization=True\n",
2219
+ " )\n",
2220
+ " print(\"βœ… Prompt Upsampler quantized & saved\")\n",
2221
+ "\n",
2222
+ " del upsampler\n",
2223
+ " free()\n",
2224
+ "\n",
2225
+ " #@title CELL 8 β€” Copy VAE + tokenizer + scheduler + config files\n",
2226
+ " from huggingface_hub import snapshot_download\n",
2227
+ " import shutil, os\n",
2228
+ "\n",
2229
+ " base_dir = \"/kaggle/working/flux3-klein-sdnq-int4\"\n",
2230
+ " os.makedirs(base_dir, exist_ok=True)\n",
2231
+ "\n",
2232
+ " print(\"Downloading remaining components from original repo...\")\n",
2233
+ " tmp = snapshot_download(\n",
2234
+ " repo_id=\"black-forest-labs/flux-3-image-klein\",\n",
2235
+ " token=hf_token,\n",
2236
+ " allow_patterns=[\n",
2237
+ " \"vae/*\",\n",
2238
+ " \"tokenizer/*\",\n",
2239
+ " \"scheduler/*\",\n",
2240
+ " \"model_index.json\",\n",
2241
+ " \"*.json\",\n",
2242
+ " \"README.md\",\n",
2243
+ " ],\n",
2244
+ " local_dir=\"/kaggle/working/tmp_flux3\",\n",
2245
+ " )\n",
2246
+ "\n",
2247
+ " # Copy the needed folders\n",
2248
+ " for folder in [\"vae\", \"tokenizer\", \"scheduler\"]:\n",
2249
+ " src = os.path.join(tmp, folder)\n",
2250
+ " dst = os.path.join(base_dir, folder)\n",
2251
+ " if os.path.exists(src):\n",
2252
+ " if os.path.exists(dst):\n",
2253
+ " shutil.rmtree(dst)\n",
2254
+ " shutil.copytree(src, dst)\n",
2255
+ " print(f\"βœ… Copied {folder}\")\n",
2256
+ "\n",
2257
+ " # Copy model_index.json and other root files\n",
2258
+ " for f in [\"model_index.json\", \"README.md\"]:\n",
2259
+ " src = os.path.join(tmp, f)\n",
2260
+ " if os.path.exists(src):\n",
2261
+ " shutil.copy2(src, base_dir)\n",
2262
+ " print(f\"βœ… Copied {f}\")\n",
2263
+ "\n",
2264
+ " print(\"βœ… All supporting components ready\")\n",
2265
+ "\n",
2266
+ " #@title CELL 9 β€” Create public repo & Upload\n",
2267
+ " from huggingface_hub import HfApi, create_repo\n",
2268
+ " from huggingface_hub.utils import HfHubHTTPError\n",
2269
+ " import os\n",
2270
+ "\n",
2271
+ " # ====== CHANGE THIS IF YOU WANT A DIFFERENT NAME ======\n",
2272
+ " repo_id = \"codeShare/flux-3-image-klein-sdnq-int4\"\n",
2273
+ " # ======================================================\n",
2274
+ "\n",
2275
+ " api = HfApi()\n",
2276
+ "\n",
2277
+ " print(f\"Creating / checking public repository: {repo_id}\")\n",
2278
+ " try:\n",
2279
+ " if not api.repo_exists(repo_id=repo_id, repo_type=\"model\"):\n",
2280
+ " create_repo(\n",
2281
+ " repo_id=repo_id,\n",
2282
+ " repo_type=\"model\",\n",
2283
+ " private=False, # ← public\n",
2284
+ " token=hf_token,\n",
2285
+ " exist_ok=True,\n",
2286
+ " )\n",
2287
+ " print(\"βœ… Public repository created\")\n",
2288
+ " else:\n",
2289
+ " print(\"βœ… Repository already exists\")\n",
2290
+ " except Exception as e:\n",
2291
+ " print(\"Repo check/create error:\", e)\n",
2292
+ "\n",
2293
+ " # Upload the entire folder structure\n",
2294
+ " print(\"\\nUploading full model (this may take a while)...\")\n",
2295
+ " api.upload_folder(\n",
2296
+ " folder_path=\"/kaggle/working/flux3-klein-sdnq-int4\",\n",
2297
+ " repo_id=repo_id,\n",
2298
+ " repo_type=\"model\",\n",
2299
+ " commit_message=\"SDNQ int4 quantized FLUX 3 Image Klein (transformer + text_encoder + prompt_upsampler)\",\n",
2300
+ " token=hf_token,\n",
2301
+ " )\n",
2302
+ "\n",
2303
+ " print(\"\\nπŸŽ‰ Upload complete!\")\n",
2304
+ " print(f\"Public model available at: https://huggingface.co/{repo_id}\")"
2305
+ ],
2306
+ "metadata": {
2307
+ "id": "SII5WEML4tCf"
2308
+ },
2309
+ "execution_count": null,
2310
+ "outputs": []
2311
+ }
2312
+ ]
2313
+ }