codeShare commited on
Commit
a3ba9b3
·
verified ·
1 Parent(s): 39fc3bc

Upload lokr_to_lora_klein9b.ipynb

Browse files
Files changed (1) hide show
  1. lokr_to_lora_klein9b.ipynb +637 -0
lokr_to_lora_klein9b.ipynb ADDED
@@ -0,0 +1,637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": "code",
21
+ "source": [
22
+ "#@markdown # CELL 1 — Setup environment + login\n",
23
+ "\n",
24
+ "from google.colab import drive, userdata\n",
25
+ "from huggingface_hub import login\n",
26
+ "import torch, os, gc\n",
27
+ "\n",
28
+ "drive.mount(\"/content/drive\")\n",
29
+ "\n",
30
+ "hf_token = userdata.get(\"HF_TOKEN\")\n",
31
+ "if hf_token:\n",
32
+ " login(token=hf_token)\n",
33
+ "else:\n",
34
+ " raise ValueError(\"HF_TOKEN not found in Google Colab secrets\")\n",
35
+ "\n",
36
+ "print(\"✅ Logged into Hugging Face\")"
37
+ ],
38
+ "metadata": {
39
+ "colab": {
40
+ "base_uri": "https://localhost:8080/"
41
+ },
42
+ "id": "FyTqzDtuIXeN",
43
+ "outputId": "fa2fc6f3-0ee9-44eb-8a45-12b292775737"
44
+ },
45
+ "execution_count": 2,
46
+ "outputs": [
47
+ {
48
+ "output_type": "stream",
49
+ "name": "stdout",
50
+ "text": [
51
+ "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n",
52
+ "✅ Logged into Hugging Face\n"
53
+ ]
54
+ }
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "execution_count": 5,
60
+ "metadata": {
61
+ "colab": {
62
+ "base_uri": "https://localhost:8080/",
63
+ "height": 873
64
+ },
65
+ "id": "ALQyKP5OHZ_N",
66
+ "outputId": "1efb903b-4aa1-4f4c-80af-6c040614a9a6"
67
+ },
68
+ "outputs": [
69
+ {
70
+ "output_type": "stream",
71
+ "name": "stdout",
72
+ "text": [
73
+ "✅ Using device: cuda\n",
74
+ "\n",
75
+ "Loading LoKr: /content/klein9b_snofs_v1.safetensors\n",
76
+ "Total keys in original LoKr: 336\n",
77
+ "\n",
78
+ "Detected 112 LoKr modules.\n",
79
+ "\n",
80
+ "🔄 Converting LoKr → LoRA layers...\n"
81
+ ]
82
+ },
83
+ {
84
+ "output_type": "stream",
85
+ "name": "stderr",
86
+ "text": [
87
+ "\rConverting: 0%| | 0/112 [00:00<?, ?it/s]"
88
+ ]
89
+ },
90
+ {
91
+ "output_type": "stream",
92
+ "name": "stdout",
93
+ "text": [
94
+ " diffusion_model.double_blocks.0.img_attn.proj | w1=torch.Size([4, 4]) | w2=torch.Size([1024, 1024]) | α=9999220736.000\n"
95
+ ]
96
+ },
97
+ {
98
+ "output_type": "stream",
99
+ "name": "stderr",
100
+ "text": [
101
+ "\rConverting: 1%| | 1/112 [00:11<21:58, 11.87s/it]"
102
+ ]
103
+ },
104
+ {
105
+ "output_type": "stream",
106
+ "name": "stdout",
107
+ "text": [
108
+ " → lora_A: torch.Size([1, 4096]) | lora_B: torch.Size([4096, 1])\n",
109
+ " diffusion_model.double_blocks.0.img_attn.qkv | w1=torch.Size([4, 4]) | w2=torch.Size([3072, 1024]) | α=9999220736.000\n"
110
+ ]
111
+ },
112
+ {
113
+ "output_type": "stream",
114
+ "name": "stderr",
115
+ "text": [
116
+ "\rConverting: 2%|▏ | 2/112 [00:24<22:38, 12.35s/it]"
117
+ ]
118
+ },
119
+ {
120
+ "output_type": "stream",
121
+ "name": "stdout",
122
+ "text": [
123
+ " → lora_A: torch.Size([1, 4096]) | lora_B: torch.Size([12288, 1])\n",
124
+ " diffusion_model.double_blocks.0.img_mlp.0 | w1=torch.Size([4, 4]) | w2=torch.Size([6144, 1024]) | α=9999220736.000\n"
125
+ ]
126
+ },
127
+ {
128
+ "output_type": "stream",
129
+ "name": "stderr",
130
+ "text": [
131
+ "\rConverting: 3%|▎ | 3/112 [00:40<25:38, 14.11s/it]"
132
+ ]
133
+ },
134
+ {
135
+ "output_type": "stream",
136
+ "name": "stdout",
137
+ "text": [
138
+ " → lora_A: torch.Size([1, 4096]) | lora_B: torch.Size([24576, 1])\n",
139
+ " diffusion_model.double_blocks.0.img_mlp.2 | w1=torch.Size([4, 4]) | w2=torch.Size([1024, 3072]) | α=9999220736.000\n"
140
+ ]
141
+ },
142
+ {
143
+ "output_type": "stream",
144
+ "name": "stderr",
145
+ "text": [
146
+ "\rConverting: 4%|▎ | 4/112 [00:51<23:14, 12.91s/it]"
147
+ ]
148
+ },
149
+ {
150
+ "output_type": "stream",
151
+ "name": "stdout",
152
+ "text": [
153
+ " → lora_A: torch.Size([1, 12288]) | lora_B: torch.Size([4096, 1])\n",
154
+ " diffusion_model.double_blocks.0.txt_attn.proj | w1=torch.Size([4, 4]) | w2=torch.Size([1024, 1024]) | α=9999220736.000\n"
155
+ ]
156
+ },
157
+ {
158
+ "output_type": "stream",
159
+ "name": "stderr",
160
+ "text": [
161
+ "\rConverting: 4%|▍ | 5/112 [01:03<22:04, 12.38s/it]"
162
+ ]
163
+ },
164
+ {
165
+ "output_type": "stream",
166
+ "name": "stdout",
167
+ "text": [
168
+ " → lora_A: torch.Size([1, 4096]) | lora_B: torch.Size([4096, 1])\n",
169
+ " diffusion_model.double_blocks.0.txt_attn.qkv | w1=torch.Size([4, 4]) | w2=torch.Size([3072, 1024]) | α=9999220736.000\n"
170
+ ]
171
+ },
172
+ {
173
+ "output_type": "stream",
174
+ "name": "stderr",
175
+ "text": [
176
+ "\rConverting: 5%|▌ | 6/112 [01:15<21:31, 12.18s/it]"
177
+ ]
178
+ },
179
+ {
180
+ "output_type": "stream",
181
+ "name": "stdout",
182
+ "text": [
183
+ " → lora_A: torch.Size([1, 4096]) | lora_B: torch.Size([12288, 1])\n",
184
+ " diffusion_model.double_blocks.0.txt_mlp.0 | w1=torch.Size([4, 4]) | w2=torch.Size([6144, 1024]) | α=9999220736.000\n"
185
+ ]
186
+ },
187
+ {
188
+ "output_type": "stream",
189
+ "name": "stderr",
190
+ "text": [
191
+ "\rConverting: 6%|▋ | 7/112 [01:30<22:59, 13.13s/it]"
192
+ ]
193
+ },
194
+ {
195
+ "output_type": "stream",
196
+ "name": "stdout",
197
+ "text": [
198
+ " → lora_A: torch.Size([1, 4096]) | lora_B: torch.Size([24576, 1])\n",
199
+ " diffusion_model.double_blocks.0.txt_mlp.2 | w1=torch.Size([4, 4]) | w2=torch.Size([1024, 3072]) | α=9999220736.000\n"
200
+ ]
201
+ },
202
+ {
203
+ "output_type": "stream",
204
+ "name": "stderr",
205
+ "text": [
206
+ "\rConverting: 7%|▋ | 8/112 [01:41<21:54, 12.63s/it]"
207
+ ]
208
+ },
209
+ {
210
+ "output_type": "stream",
211
+ "name": "stdout",
212
+ "text": [
213
+ " → lora_A: torch.Size([1, 12288]) | lora_B: torch.Size([4096, 1])\n",
214
+ " diffusion_model.double_blocks.1.img_attn.proj | w1=torch.Size([4, 4]) | w2=torch.Size([1024, 1024]) | α=9999220736.000\n"
215
+ ]
216
+ },
217
+ {
218
+ "output_type": "stream",
219
+ "name": "stderr",
220
+ "text": [
221
+ "\rConverting: 8%|▊ | 9/112 [01:53<21:18, 12.42s/it]"
222
+ ]
223
+ },
224
+ {
225
+ "output_type": "stream",
226
+ "name": "stdout",
227
+ "text": [
228
+ " → lora_A: torch.Size([1, 4096]) | lora_B: torch.Size([4096, 1])\n",
229
+ " diffusion_model.double_blocks.1.img_attn.qkv | w1=torch.Size([4, 4]) | w2=torch.Size([3072, 1024]) | α=9999220736.000\n"
230
+ ]
231
+ },
232
+ {
233
+ "output_type": "stream",
234
+ "name": "stderr",
235
+ "text": [
236
+ "\rConverting: 9%|▉ | 10/112 [02:05<20:58, 12.33s/it]"
237
+ ]
238
+ },
239
+ {
240
+ "output_type": "stream",
241
+ "name": "stdout",
242
+ "text": [
243
+ " → lora_A: torch.Size([1, 4096]) | lora_B: torch.Size([12288, 1])\n",
244
+ " diffusion_model.double_blocks.1.img_mlp.0 | w1=torch.Size([4, 4]) | w2=torch.Size([6144, 1024]) | α=9999220736.000\n"
245
+ ]
246
+ },
247
+ {
248
+ "output_type": "stream",
249
+ "name": "stderr",
250
+ "text": [
251
+ "\rConverting: 9%|▉ | 10/112 [02:21<24:05, 14.17s/it]\n"
252
+ ]
253
+ },
254
+ {
255
+ "output_type": "error",
256
+ "ename": "KeyboardInterrupt",
257
+ "evalue": "",
258
+ "traceback": [
259
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
260
+ "\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)",
261
+ "\u001b[0;32m/tmp/ipykernel_22195/4205228776.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 123\u001b[0m \u001b[0;31m# ====================== RUN THE SCRIPT ======================\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 124\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 125\u001b[0;31m output_dir, full_lora_path = convert_lokr_to_lora(\n\u001b[0m\u001b[1;32m 126\u001b[0m \u001b[0mrepo_id\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m\"codeShare/flux-klein-9B-loras\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 127\u001b[0m \u001b[0mlokr_filename\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m\"klein9b_snofs_v1.safetensors\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
262
+ "\u001b[0;32m/tmp/ipykernel_22195/4205228776.py\u001b[0m in \u001b[0;36mconvert_lokr_to_lora\u001b[0;34m(repo_id, lokr_filename, output_dir, final_lora_name, target_rank, hf_token)\u001b[0m\n\u001b[1;32m 65\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 66\u001b[0m \u001b[0;31m# SVD Decomposition\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 67\u001b[0;31m \u001b[0mU\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mS\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mVh\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinalg\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msvd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdelta\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 68\u001b[0m \u001b[0mr\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmin\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtarget_rank\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mS\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 69\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
263
+ "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
264
+ ]
265
+ }
266
+ ],
267
+ "source": [
268
+ "import torch\n",
269
+ "import os\n",
270
+ "from safetensors.torch import load_file, save_file\n",
271
+ "from huggingface_hub import hf_hub_download\n",
272
+ "from collections import defaultdict\n",
273
+ "from tqdm import tqdm\n",
274
+ "import math\n",
275
+ "import glob\n",
276
+ "\n",
277
+ "\n",
278
+ "def convert_lokr_to_lora(\n",
279
+ " repo_id: str = \"codeShare/flux-klein-9B-loras\",\n",
280
+ " lokr_filename: str = \"klein9b_snofs_v1.safetensors\",\n",
281
+ " output_dir: str = \"/content/lora_individual_layers\",\n",
282
+ " final_lora_name: str = \"klein9b_snofs_v1_full_lora.safetensors\",\n",
283
+ " target_rank: int = 128,\n",
284
+ " hf_token: str = None\n",
285
+ "):\n",
286
+ " device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
287
+ " print(f\"✅ Using device: {device}\\n\")\n",
288
+ "\n",
289
+ " # ====================== 1. DOWNLOAD & LOAD LoKr ======================\n",
290
+ " lokr_path = hf_hub_download(repo_id=repo_id, filename=lokr_filename, token=hf_token, local_dir=\"/content\")\n",
291
+ " print(f\"Loading LoKr: {lokr_path}\")\n",
292
+ " state_dict = load_file(lokr_path, device=\"cpu\")\n",
293
+ "\n",
294
+ " print(f\"Total keys in original LoKr: {len(state_dict)}\\n\")\n",
295
+ "\n",
296
+ " modules = defaultdict(dict)\n",
297
+ "\n",
298
+ " # Parse LoKr modules\n",
299
+ " for key, tensor in state_dict.items():\n",
300
+ " if key.endswith('.alpha'):\n",
301
+ " base = key[:-6]\n",
302
+ " modules[base]['alpha'] = float(tensor.item())\n",
303
+ " continue\n",
304
+ " if '.lokr_' in key:\n",
305
+ " base = key.split('.lokr_')[0]\n",
306
+ " part = key.split('.')[-1]\n",
307
+ " modules[base][part] = tensor\n",
308
+ "\n",
309
+ " print(f\"Detected {len(modules)} LoKr modules.\\n\")\n",
310
+ "\n",
311
+ " os.makedirs(output_dir, exist_ok=True)\n",
312
+ "\n",
313
+ " converted = 0\n",
314
+ " merged_state_dict = {}\n",
315
+ "\n",
316
+ " print(\"🔄 Converting LoKr → LoRA layers...\")\n",
317
+ "\n",
318
+ " for base_key, weights in tqdm(modules.items(), desc=\"Converting\"):\n",
319
+ " alpha = weights.get('alpha', 1.0)\n",
320
+ "\n",
321
+ " if 'lokr_w1' not in weights or 'lokr_w2' not in weights:\n",
322
+ " print(f\"⚠️ Skipping {base_key} (missing w1/w2)\")\n",
323
+ " continue\n",
324
+ "\n",
325
+ " w1 = weights['lokr_w1'].to(device, dtype=torch.float32)\n",
326
+ " w2 = weights['lokr_w2'].to(device, dtype=torch.float32)\n",
327
+ "\n",
328
+ " print(f\" {base_key:60} | w1={w1.shape} | w2={w2.shape} | α={alpha:.3f}\")\n",
329
+ "\n",
330
+ " # Kronecker product\n",
331
+ " delta = torch.kron(w1, w2)\n",
332
+ "\n",
333
+ " # SVD Decomposition\n",
334
+ " U, S, Vh = torch.linalg.svd(delta)\n",
335
+ " r = min(target_rank, S.shape[0])\n",
336
+ "\n",
337
+ " sqrt_s = S[:r].sqrt().unsqueeze(1)\n",
338
+ "\n",
339
+ " # Correct LoRA matrices (Standard convention)\n",
340
+ " lora_A = (sqrt_s.T @ Vh[:r, :]) # (rank, in_features)\n",
341
+ " lora_B = (U[:, :r] @ sqrt_s) # (out_features, rank)\n",
342
+ "\n",
343
+ " scale = alpha / math.sqrt(r)\n",
344
+ "\n",
345
+ " lora_A = (lora_A * scale).to(torch.bfloat16).cpu()\n",
346
+ " lora_B = (lora_B * scale).to(torch.bfloat16).cpu()\n",
347
+ "\n",
348
+ " print(f\" → lora_A: {lora_A.shape} | lora_B: {lora_B.shape}\")\n",
349
+ "\n",
350
+ " # Save individual layer\n",
351
+ " layer_dict = {\n",
352
+ " f\"{base_key}.lora_A.weight\": lora_A,\n",
353
+ " f\"{base_key}.lora_B.weight\": lora_B,\n",
354
+ " }\n",
355
+ "\n",
356
+ " safe_name = base_key.replace(\".\", \"_\").replace(\"/\", \"_\")\n",
357
+ " layer_path = os.path.join(output_dir, f\"{safe_name}.safetensors\")\n",
358
+ " save_file(layer_dict, layer_path)\n",
359
+ "\n",
360
+ " # Add to merged dict\n",
361
+ " merged_state_dict.update(layer_dict)\n",
362
+ " converted += 1\n",
363
+ "\n",
364
+ " print(f\"\\n✅ Successfully converted {converted} layers to individual files.\")\n",
365
+ " print(f\"Individual layers saved in: {output_dir}\\n\")\n",
366
+ "\n",
367
+ " # ====================== 2. CREATE FULL LORA FROM SAVED FILES ======================\n",
368
+ " print(\"🔗 Merging all individual LoRA files into one full LoRA...\")\n",
369
+ "\n",
370
+ " full_merged = {}\n",
371
+ " individual_files = glob.glob(os.path.join(output_dir, \"*.safetensors\"))\n",
372
+ "\n",
373
+ " for file_path in tqdm(individual_files, desc=\"Merging files\"):\n",
374
+ " layer_dict = load_file(file_path, device=\"cpu\")\n",
375
+ " full_merged.update(layer_dict)\n",
376
+ "\n",
377
+ " # Save final full LoRA\n",
378
+ " final_path = f\"/content/{final_lora_name}\"\n",
379
+ " save_file(full_merged, final_path)\n",
380
+ "\n",
381
+ " size_mb = os.path.getsize(final_path) / (1024 * 1024)\n",
382
+ " print(f\"\\n🎉 Full LoRA successfully created!\")\n",
383
+ " print(f\" Path: {final_path}\")\n",
384
+ " print(f\" Size: {size_mb:.2f} MB\")\n",
385
+ " print(f\" Total keys: {len(full_merged)}\")\n",
386
+ "\n",
387
+ " return output_dir, final_path\n",
388
+ "\n",
389
+ "\n",
390
+ "# ====================== RUN THE SCRIPT ======================\n",
391
+ "if __name__ == \"__main__\":\n",
392
+ " output_dir, full_lora_path = convert_lokr_to_lora(\n",
393
+ " repo_id=\"codeShare/flux-klein-9B-loras\",\n",
394
+ " lokr_filename=\"klein9b_snofs_v1.safetensors\",\n",
395
+ " output_dir=\"/content/lora_individual_layers\",\n",
396
+ " final_lora_name=\"klein9b_snofs_v1_full_lora.safetensors\",\n",
397
+ " target_rank=32, # Try 192 or 256 if quality is insufficient\n",
398
+ " hf_token=None # Add your HF token if needed\n",
399
+ " )\n",
400
+ "\n",
401
+ " print(\"\\nAll done! You can now use the full LoRA file:\")\n",
402
+ " print(f\"→ {full_lora_path}\")"
403
+ ]
404
+ },
405
+ {
406
+ "cell_type": "code",
407
+ "source": [
408
+ "import torch\n",
409
+ "import os\n",
410
+ "from safetensors.torch import load_file, save_file\n",
411
+ "from huggingface_hub import hf_hub_download\n",
412
+ "from collections import defaultdict\n",
413
+ "from tqdm import tqdm\n",
414
+ "import math\n",
415
+ "import glob\n",
416
+ "\n",
417
+ "\n",
418
+ "def convert_lokr_to_lora(\n",
419
+ " repo_id: str = \"codeShare/flux-klein-9B-loras\",\n",
420
+ " lokr_filename: str = \"klein9b_snofs_v1.safetensors\",\n",
421
+ " output_dir: str = \"/content/lora_individual_layers\",\n",
422
+ " final_lora_name: str = \"klein9b_snofs_v1_full_lora.safetensors\",\n",
423
+ " target_rank: int = 128,\n",
424
+ " min_rank: int = 32, # ← Prevents rank collapse\n",
425
+ " alpha_clip: float = 1.0, # ← Safety for huge alpha values\n",
426
+ " hf_token: str = None\n",
427
+ "):\n",
428
+ " device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
429
+ " print(f\"✅ Using device: {device}\\n\")\n",
430
+ "\n",
431
+ " # ====================== DOWNLOAD & LOAD LoKr ======================\n",
432
+ " lokr_path = hf_hub_download(repo_id=repo_id, filename=lokr_filename, token=hf_token, local_dir=\"/content\")\n",
433
+ " print(f\"Loading LoKr: {lokr_path}\")\n",
434
+ " state_dict = load_file(lokr_path, device=\"cpu\")\n",
435
+ "\n",
436
+ " print(f\"Total keys in original LoKr: {len(state_dict)}\\n\")\n",
437
+ "\n",
438
+ " modules = defaultdict(dict)\n",
439
+ "\n",
440
+ " # Parse modules\n",
441
+ " for key, tensor in state_dict.items():\n",
442
+ " if key.endswith('.alpha'):\n",
443
+ " base = key[:-6]\n",
444
+ " alpha_val = float(tensor.item())\n",
445
+ " # Safety clamp on alpha\n",
446
+ " modules[base]['alpha'] = max(0.01, min(alpha_val, alpha_clip))\n",
447
+ " continue\n",
448
+ " if '.lokr_' in key:\n",
449
+ " base = key.split('.lokr_')[0]\n",
450
+ " part = key.split('.')[-1]\n",
451
+ " modules[base][part] = tensor\n",
452
+ "\n",
453
+ " print(f\"Detected {len(modules)} LoKr modules.\\n\")\n",
454
+ "\n",
455
+ " os.makedirs(output_dir, exist_ok=True)\n",
456
+ "\n",
457
+ " merged_state_dict = {}\n",
458
+ " converted = 0\n",
459
+ "\n",
460
+ " print(\"🔄 Converting LoKr → LoRA layers with minimum rank enforcement...\")\n",
461
+ "\n",
462
+ " for base_key, weights in tqdm(modules.items(), desc=\"Converting\"):\n",
463
+ " alpha = weights.get('alpha', 1.0)\n",
464
+ "\n",
465
+ " if 'lokr_w1' not in weights or 'lokr_w2' not in weights:\n",
466
+ " print(f\"⚠️ Skipping {base_key} (missing w1/w2)\")\n",
467
+ " continue\n",
468
+ "\n",
469
+ " w1 = weights['lokr_w1'].to(device, dtype=torch.float32)\n",
470
+ " w2 = weights['lokr_w2'].to(device, dtype=torch.float32)\n",
471
+ "\n",
472
+ " # Kronecker product\n",
473
+ " delta = torch.kron(w1, w2)\n",
474
+ "\n",
475
+ " # SVD\n",
476
+ " U, S, Vh = torch.linalg.svd(delta, full_matrices=False)\n",
477
+ "\n",
478
+ " # === FORCE MINIMUM RANK ===\n",
479
+ " possible_rank = min(S.shape[0], target_rank)\n",
480
+ " r = max(min_rank, possible_rank)\n",
481
+ "\n",
482
+ " sqrt_s = S[:r].sqrt().unsqueeze(1)\n",
483
+ "\n",
484
+ " # Standard LoRA convention for Flux / SDXL / etc.\n",
485
+ " lora_A = (sqrt_s.T @ Vh[:r, :]) # (rank, in_features)\n",
486
+ " lora_B = (U[:, :r] @ sqrt_s) # (out_features, rank)\n",
487
+ "\n",
488
+ " scale = alpha / math.sqrt(r)\n",
489
+ "\n",
490
+ " lora_A = (lora_A * scale).to(torch.bfloat16).cpu()\n",
491
+ " lora_B = (lora_B * scale).to(torch.bfloat16).cpu()\n",
492
+ "\n",
493
+ " print(f\" {base_key:65} | w1={w1.shape} | w2={w2.shape} | α={alpha:.3f} | rank={r:3d}\")\n",
494
+ "\n",
495
+ " # Individual layer dictionary\n",
496
+ " layer_dict = {\n",
497
+ " f\"{base_key}.lora_A.weight\": lora_A,\n",
498
+ " f\"{base_key}.lora_B.weight\": lora_B,\n",
499
+ " }\n",
500
+ "\n",
501
+ " # Save individual safetensors file\n",
502
+ " safe_name = base_key.replace(\".\", \"_\").replace(\"/\", \"_\")\n",
503
+ " layer_path = os.path.join(output_dir, f\"{safe_name}.safetensors\")\n",
504
+ " save_file(layer_dict, layer_path)\n",
505
+ "\n",
506
+ " # Add to final merged dict\n",
507
+ " merged_state_dict.update(layer_dict)\n",
508
+ " converted += 1\n",
509
+ "\n",
510
+ " # ====================== CREATE FULL LORA ======================\n",
511
+ " print(f\"\\n🔗 Saving full merged LoRA ({len(merged_state_dict)} keys)...\")\n",
512
+ " final_path = f\"/content/{final_lora_name}\"\n",
513
+ " save_file(merged_state_dict, final_path)\n",
514
+ "\n",
515
+ " size_mb = os.path.getsize(final_path) / (1024 * 1024)\n",
516
+ " print(f\"\\n🎉 Conversion completed!\")\n",
517
+ " print(f\" Converted layers : {converted}\")\n",
518
+ " print(f\" Full LoRA path : {final_path}\")\n",
519
+ " print(f\" File size : {size_mb:.2f} MB\")\n",
520
+ " print(f\" Individual layers: {output_dir}/\")\n",
521
+ "\n",
522
+ " return output_dir, final_path\n",
523
+ "\n",
524
+ "\n",
525
+ "# ====================== RUN ======================\n",
526
+ "if __name__ == \"__main__\":\n",
527
+ " output_dir, full_lora_path = convert_lokr_to_lora(\n",
528
+ " repo_id=\"codeShare/flux-klein-9B-loras\",\n",
529
+ " lokr_filename=\"klein9b_snofs_v1.safetensors\",\n",
530
+ " output_dir=\"/content/lora_individual_layers\",\n",
531
+ " final_lora_name=\"klein9b_snofs_v1_full_lora.safetensors\",\n",
532
+ " target_rank=32,\n",
533
+ " min_rank=8, # Change to 16, 48, or 64 depending on quality\n",
534
+ " alpha_clip=100, # Try 0.5 or 2.0 if the model is too strong/weak\n",
535
+ " hf_token=None\n",
536
+ " )\n",
537
+ "\n",
538
+ " print(\"\\n✅ Done! You can now use:\")\n",
539
+ " print(f\" → {full_lora_path}\")"
540
+ ],
541
+ "metadata": {
542
+ "colab": {
543
+ "base_uri": "https://localhost:8080/"
544
+ },
545
+ "id": "F1yPQS7Dg2fD",
546
+ "outputId": "3c4593c8-5f1b-4bed-b8df-3057174dd894"
547
+ },
548
+ "execution_count": null,
549
+ "outputs": [
550
+ {
551
+ "output_type": "stream",
552
+ "name": "stdout",
553
+ "text": [
554
+ "✅ Using device: cuda\n",
555
+ "\n",
556
+ "Loading LoKr: /content/klein9b_snofs_v1.safetensors\n",
557
+ "Total keys in original LoKr: 336\n",
558
+ "\n",
559
+ "Detected 112 LoKr modules.\n",
560
+ "\n",
561
+ "🔄 Converting LoKr → LoRA layers with minimum rank enforcement...\n"
562
+ ]
563
+ },
564
+ {
565
+ "output_type": "stream",
566
+ "name": "stderr",
567
+ "text": [
568
+ "Converting: 1%| | 1/112 [00:11<21:47, 11.78s/it]"
569
+ ]
570
+ },
571
+ {
572
+ "output_type": "stream",
573
+ "name": "stdout",
574
+ "text": [
575
+ " diffusion_model.double_blocks.0.img_attn.proj | w1=torch.Size([4, 4]) | w2=torch.Size([1024, 1024]) | α=100.000 | rank= 32\n"
576
+ ]
577
+ },
578
+ {
579
+ "output_type": "stream",
580
+ "name": "stderr",
581
+ "text": [
582
+ "\rConverting: 2%|▏ | 2/112 [00:23<21:43, 11.85s/it]"
583
+ ]
584
+ },
585
+ {
586
+ "output_type": "stream",
587
+ "name": "stdout",
588
+ "text": [
589
+ " diffusion_model.double_blocks.0.img_attn.qkv | w1=torch.Size([4, 4]) | w2=torch.Size([3072, 1024]) | α=100.000 | rank= 32\n"
590
+ ]
591
+ },
592
+ {
593
+ "output_type": "stream",
594
+ "name": "stderr",
595
+ "text": [
596
+ "\rConverting: 3%|▎ | 3/112 [00:36<22:05, 12.16s/it]"
597
+ ]
598
+ },
599
+ {
600
+ "output_type": "stream",
601
+ "name": "stdout",
602
+ "text": [
603
+ " diffusion_model.double_blocks.0.img_mlp.0 | w1=torch.Size([4, 4]) | w2=torch.Size([6144, 1024]) | α=100.000 | rank= 32\n"
604
+ ]
605
+ },
606
+ {
607
+ "output_type": "stream",
608
+ "name": "stderr",
609
+ "text": [
610
+ "\rConverting: 4%|▎ | 4/112 [00:46<20:47, 11.56s/it]"
611
+ ]
612
+ },
613
+ {
614
+ "output_type": "stream",
615
+ "name": "stdout",
616
+ "text": [
617
+ " diffusion_model.double_blocks.0.img_mlp.2 | w1=torch.Size([4, 4]) | w2=torch.Size([1024, 3072]) | α=100.000 | rank= 32\n"
618
+ ]
619
+ },
620
+ {
621
+ "output_type": "stream",
622
+ "name": "stderr",
623
+ "text": [
624
+ "\rConverting: 4%|▍ | 5/112 [00:58<20:39, 11.58s/it]"
625
+ ]
626
+ },
627
+ {
628
+ "output_type": "stream",
629
+ "name": "stdout",
630
+ "text": [
631
+ " diffusion_model.double_blocks.0.txt_attn.proj | w1=torch.Size([4, 4]) | w2=torch.Size([1024, 1024]) | α=100.000 | rank= 32\n"
632
+ ]
633
+ }
634
+ ]
635
+ }
636
+ ]
637
+ }