codeShare commited on
Commit
4b3de45
Β·
verified Β·
1 Parent(s): 8ff6d1d

Upload svd_prune_loras.ipynb

Browse files
Files changed (1) hide show
  1. svd_prune_loras.ipynb +784 -0
svd_prune_loras.ipynb ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "d1f55737"
7
+ },
8
+ "source": [
9
+ "# SVD Rank Pruning from Google Drive"
10
+ ],
11
+ "id": "d1f55737"
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "metadata": {
16
+ "id": "e1d3c3ce"
17
+ },
18
+ "source": [
19
+ "# =============================================================================\n",
20
+ "# CELL 1: Mount Google Drive & Install Dependencies\n",
21
+ "# =============================================================================\n",
22
+ "from google.colab import drive\n",
23
+ "drive.mount('/content/drive')\n",
24
+ "\n",
25
+ "!pip install -q safetensors torch matplotlib numpy"
26
+ ],
27
+ "id": "e1d3c3ce",
28
+ "execution_count": null,
29
+ "outputs": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {
34
+ "id": "a5f68552"
35
+ },
36
+ "source": [
37
+ "# =============================================================================\n",
38
+ "# CELL 2: Configure Paths\n",
39
+ "# =============================================================================\n",
40
+ "import os\n",
41
+ "import torch\n",
42
+ "import gc\n",
43
+ "import datetime\n",
44
+ "from pathlib import Path\n",
45
+ "from collections import defaultdict\n",
46
+ "from safetensors import safe_open\n",
47
+ "import safetensors.torch\n",
48
+ "\n",
49
+ "# Configure Paths\n",
50
+ "drive_root = \"/content/drive/MyDrive\"\n",
51
+ "input_filename = \"4-steps-dmd-lora.safetensors\"\n",
52
+ "input_path = os.path.join(drive_root, input_filename)\n",
53
+ "\n",
54
+ "# Output to top-level Google Drive with a suffix\n",
55
+ "output_filename = \"4-steps-dmd-lora_pruned_90.safetensors\"\n",
56
+ "output_path = os.path.join(drive_root, output_filename)\n",
57
+ "\n",
58
+ "print(f\"βœ… Target Input Path: {input_path}\")\n",
59
+ "print(f\"βœ… Target Output Path: {output_path}\")\n",
60
+ "if not os.path.exists(input_path):\n",
61
+ " raise FileNotFoundError(f\"❌ Could not find the file '{input_filename}' at the top level of your Google Drive.\")\n",
62
+ "else:\n",
63
+ " print(\"βœ… File found!\")"
64
+ ],
65
+ "id": "a5f68552",
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {
72
+ "id": "a21ae0ee"
73
+ },
74
+ "source": [
75
+ "# =============================================================================\n",
76
+ "# CELL 3: SVD Rank Pruning (90% Target Accuracy)\n",
77
+ "# =============================================================================\n",
78
+ "desired_accuracy = 90 # 90% Target Accuracy\n",
79
+ "\n",
80
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
81
+ "print(f\"Using device: {device}\")\n",
82
+ "\n",
83
+ "size_before = os.path.getsize(input_path) / (1024 * 1024)\n",
84
+ "print(f\"πŸ”„ Loading LoRA ({size_before:.2f} MB)... \")\n",
85
+ "\n",
86
+ "# Load the state_dict\n",
87
+ "state_dict = safetensors.torch.load_file(input_path, device=\"cpu\")\n",
88
+ "\n",
89
+ "# Attempt to extract metadata\n",
90
+ "original_metadata = {}\n",
91
+ "try:\n",
92
+ " with safe_open(input_path, framework=\"pt\", device=\"cpu\") as f:\n",
93
+ " original_metadata = f.metadata() or {}\n",
94
+ "except Exception:\n",
95
+ " pass\n",
96
+ "\n",
97
+ "# Parse Layers\n",
98
+ "lora_pairs = defaultdict(dict)\n",
99
+ "original_ranks = {}\n",
100
+ "\n",
101
+ "for key, tensor in state_dict.items():\n",
102
+ " if \".lora_A.weight\" in key or \".lora_down.weight\" in key:\n",
103
+ " base = key.replace(\".lora_A.weight\", \"\").replace(\".lora_down.weight\", \"\")\n",
104
+ " lora_pairs[base][\"A\"] = tensor\n",
105
+ " original_ranks[base] = tensor.shape[0]\n",
106
+ " elif \".lora_B.weight\" in key or \".lora_up.weight\" in key:\n",
107
+ " base = key.replace(\".lora_B.weight\", \"\").replace(\".lora_up.weight\", \"\")\n",
108
+ " lora_pairs[base][\"B\"] = tensor\n",
109
+ "\n",
110
+ "new_state_dict = dict(state_dict)\n",
111
+ "changes_made = False\n",
112
+ "pruned_count = 0\n",
113
+ "total_layers = len(lora_pairs)\n",
114
+ "\n",
115
+ "print(f\"Processing {total_layers} layers for rank reduction...\")\n",
116
+ "\n",
117
+ "for base_key, matrices in lora_pairs.items():\n",
118
+ " if \"A\" not in matrices or \"B\" not in matrices:\n",
119
+ " continue\n",
120
+ "\n",
121
+ " A = matrices[\"A\"].to(device)\n",
122
+ " B = matrices[\"B\"].to(device)\n",
123
+ " orig_rank = original_ranks.get(base_key, A.shape[0])\n",
124
+ "\n",
125
+ " # Reconstruct original weight matrix representation\n",
126
+ " delta_W = torch.matmul(B, A).float()\n",
127
+ " original_norm = torch.norm(delta_W, p='fro').item()\n",
128
+ "\n",
129
+ " # Perform SVD\n",
130
+ " U, S, Vh = torch.linalg.svd(delta_W, full_matrices=False)\n",
131
+ "\n",
132
+ " # SVD-based rank reduction candidates\n",
133
+ " candidates = [max(1, int(orig_rank * f)) for f in [0.95, 0.9, 0.85, 0.8, 0.75, 0.7, 0.65, 0.6]]\n",
134
+ " test_ranks = sorted(set(r for r in candidates if r < orig_rank))\n",
135
+ "\n",
136
+ " best_rank = orig_rank\n",
137
+ " best_acc = 100.0\n",
138
+ "\n",
139
+ " for r in test_ranks:\n",
140
+ " if r >= len(S):\n",
141
+ " continue\n",
142
+ " S_trunc = torch.zeros_like(S)\n",
143
+ " S_trunc[:r] = S[:r]\n",
144
+ " approx = U @ torch.diag(S_trunc) @ Vh\n",
145
+ " error = torch.norm(delta_W - approx, p='fro').item()\n",
146
+ " rel_error = (error / original_norm * 100) if original_norm > 1e-8 else 0.0\n",
147
+ " acc = 100 - rel_error\n",
148
+ "\n",
149
+ " if acc >= desired_accuracy:\n",
150
+ " best_rank = r\n",
151
+ " best_acc = acc\n",
152
+ " break\n",
153
+ "\n",
154
+ " if best_rank < orig_rank:\n",
155
+ " changes_made = True\n",
156
+ " pruned_count += 1\n",
157
+ " r = best_rank\n",
158
+ "\n",
159
+ " # Reconstruct scaled factors using the reduced rank components\n",
160
+ " sqrt_S = torch.sqrt(S[:r])\n",
161
+ " new_up = (U[:, :r] * sqrt_S.unsqueeze(0)).to(torch.bfloat16)\n",
162
+ " new_down = (sqrt_S.unsqueeze(1) * Vh[:r, :]).to(torch.bfloat16)\n",
163
+ "\n",
164
+ " # Delete old weight representation keys from the dictionary\n",
165
+ " for suffix in [\".lora_A.weight\", \".lora_B.weight\", \".lora_down.weight\", \".lora_up.weight\", \".alpha\"]:\n",
166
+ " new_state_dict.pop(base_key + suffix, None)\n",
167
+ "\n",
168
+ " # Re-save matching key structure (down / up representation)\n",
169
+ " new_state_dict[base_key + \".lora_down.weight\"] = new_down.contiguous().cpu()\n",
170
+ " new_state_dict[base_key + \".lora_up.weight\"] = new_up.contiguous().cpu()\n",
171
+ "\n",
172
+ " print(f\" β†’ {base_key} | {orig_rank} β†’ {best_rank} | Acc: {best_acc:.2f}%\")\n",
173
+ "\n",
174
+ " # Clean up tensors to conserve GPU RAM\n",
175
+ " del delta_W, U, S, Vh, A, B\n",
176
+ " torch.cuda.empty_cache()\n",
177
+ "\n",
178
+ "# Save modified safetensors state dict if changes occurred\n",
179
+ "if changes_made:\n",
180
+ " new_metadata = dict(original_metadata)\n",
181
+ " new_metadata.update({\n",
182
+ " \"original_file\": input_filename,\n",
183
+ " \"pruned_with\": f\"SVD Rank Reduction at {desired_accuracy}% accuracy threshold\",\n",
184
+ " \"pruning_date\": datetime.datetime.now().isoformat(),\n",
185
+ " \"layers_pruned\": f\"{pruned_count}/{total_layers}\"\n",
186
+ " })\n",
187
+ "\n",
188
+ " # Ensure tensors are saved as contiguous blocks\n",
189
+ " for k, v in new_state_dict.items():\n",
190
+ " if isinstance(v, torch.Tensor):\n",
191
+ " new_state_dict[k] = v.contiguous()\n",
192
+ "\n",
193
+ " print(f\"πŸ’Ύ Saving pruned LoRA back to Drive at: {output_path}...\")\n",
194
+ " safetensors.torch.save_file(new_state_dict, output_path, metadata=new_metadata)\n",
195
+ "\n",
196
+ " size_after = os.path.getsize(output_path) / (1024 * 1024)\n",
197
+ " print(f\"βœ… Completed! Size reduction: {size_before:.2f} MB β†’ {size_after:.2f} MB ({pruned_count}/{total_layers} layers updated)\")\n",
198
+ "else:\n",
199
+ " print(\"ℹ️ No layers met rank-pruning criteria under the 90% accuracy constraint. No new file written.\")\n",
200
+ "\n",
201
+ "del state_dict, new_state_dict\n",
202
+ "gc.collect()"
203
+ ],
204
+ "id": "a21ae0ee",
205
+ "execution_count": null,
206
+ "outputs": []
207
+ },
208
+ {
209
+ "cell_type": "markdown",
210
+ "source": [
211
+ "# Kaggle version"
212
+ ],
213
+ "metadata": {
214
+ "id": "EJAKMbW1bIFx"
215
+ },
216
+ "id": "EJAKMbW1bIFx"
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "execution_count": null,
221
+ "id": "507c1488",
222
+ "metadata": {
223
+ "execution": {
224
+ "iopub.execute_input": "2026-05-14T18:09:45.284673Z",
225
+ "iopub.status.busy": "2026-05-14T18:09:45.284222Z",
226
+ "iopub.status.idle": "2026-05-14T18:10:01.729025Z",
227
+ "shell.execute_reply": "2026-05-14T18:10:01.727975Z"
228
+ },
229
+ "papermill": {
230
+ "duration": 16.450904,
231
+ "end_time": "2026-05-14T18:10:01.730955+00:00",
232
+ "exception": false,
233
+ "start_time": "2026-05-14T18:09:45.280051+00:00",
234
+ "status": "completed"
235
+ },
236
+ "tags": [],
237
+ "id": "507c1488"
238
+ },
239
+ "outputs": [],
240
+ "source": [
241
+ "# =============================================================================\n",
242
+ "# CELL 1: Install dependencies\n",
243
+ "# =============================================================================\n",
244
+ "!pip install -q safetensors torch matplotlib numpy huggingface_hub pynacl py7zr\n",
245
+ "\n",
246
+ "import os\n",
247
+ "import torch\n",
248
+ "import gc\n",
249
+ "import random\n",
250
+ "import datetime\n",
251
+ "\n",
252
+ "print(f\"βœ… PyTorch version: {torch.__version__}\")\n",
253
+ "print(f\"βœ… Available GPUs: {torch.cuda.device_count()}\")\n",
254
+ "for i in range(torch.cuda.device_count()):\n",
255
+ " print(f\" GPU {i}: {torch.cuda.get_device_name(i)}\")"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "execution_count": null,
261
+ "id": "fc6693b0",
262
+ "metadata": {
263
+ "execution": {
264
+ "iopub.execute_input": "2026-05-14T18:10:01.737730Z",
265
+ "iopub.status.busy": "2026-05-14T18:10:01.736685Z",
266
+ "iopub.status.idle": "2026-05-14T18:10:03.127601Z",
267
+ "shell.execute_reply": "2026-05-14T18:10:03.126560Z"
268
+ },
269
+ "papermill": {
270
+ "duration": 1.395897,
271
+ "end_time": "2026-05-14T18:10:03.129339+00:00",
272
+ "exception": false,
273
+ "start_time": "2026-05-14T18:10:01.733442+00:00",
274
+ "status": "completed"
275
+ },
276
+ "tags": [],
277
+ "id": "fc6693b0"
278
+ },
279
+ "outputs": [],
280
+ "source": [
281
+ "# =============================================================================\n",
282
+ "# CELL 2: Secrets + Config from Kaggle Dataset\n",
283
+ "# =============================================================================\n",
284
+ "from kaggle_secrets import UserSecretsClient\n",
285
+ "from huggingface_hub import snapshot_download, login\n",
286
+ "import torch\n",
287
+ "import safetensors.torch\n",
288
+ "from safetensors import safe_open\n",
289
+ "import os\n",
290
+ "import random\n",
291
+ "import datetime\n",
292
+ "import gc\n",
293
+ "from pathlib import Path\n",
294
+ "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
295
+ "from collections import defaultdict\n",
296
+ "\n",
297
+ "print(\"βœ… Libraries imported!\")\n",
298
+ "\n",
299
+ "# === Kaggle Dataset Path ===\n",
300
+ "kaggle_repo_path = \"/kaggle/input/datasets/nekos4lyfe/image-caption-dataset/\" #@param {type:\"string\"}\n",
301
+ "\n",
302
+ "# Read HF_TOKEN from HF_TOKEN.txt\n",
303
+ "hf_token = None\n",
304
+ "try:\n",
305
+ " token_path = Path(kaggle_repo_path) / \"HF_TOKEN.txt\"\n",
306
+ " if token_path.exists():\n",
307
+ " hf_token = token_path.read_text(encoding=\"utf-8\").strip()\n",
308
+ " print(\"βœ… HF_TOKEN loaded from HF_TOKEN.txt\")\n",
309
+ "\n",
310
+ " if hf_token:\n",
311
+ " login(token=hf_token)\n",
312
+ " print(\"βœ… Successfully logged into Hugging Face\")\n",
313
+ " else:\n",
314
+ " print(f\"⚠️ HF_TOKEN.txt not found at {token_path}\")\n",
315
+ "except Exception as e:\n",
316
+ " print(f\"⚠️ Failed to read HF_TOKEN.txt: {e}\")"
317
+ ]
318
+ },
319
+ {
320
+ "cell_type": "code",
321
+ "execution_count": null,
322
+ "id": "d3cddbf0",
323
+ "metadata": {
324
+ "execution": {
325
+ "iopub.execute_input": "2026-05-14T18:10:03.140540Z",
326
+ "iopub.status.busy": "2026-05-14T18:10:03.139445Z",
327
+ "iopub.status.idle": "2026-05-14T18:10:03.153972Z",
328
+ "shell.execute_reply": "2026-05-14T18:10:03.152857Z"
329
+ },
330
+ "papermill": {
331
+ "duration": 0.019317,
332
+ "end_time": "2026-05-14T18:10:03.155565+00:00",
333
+ "exception": false,
334
+ "start_time": "2026-05-14T18:10:03.136248+00:00",
335
+ "status": "completed"
336
+ },
337
+ "tags": [],
338
+ "id": "d3cddbf0"
339
+ },
340
+ "outputs": [],
341
+ "source": [
342
+ "# =============================================================================\n",
343
+ "# CELL 3: Setup Folders\n",
344
+ "# =============================================================================\n",
345
+ "base_dir = \"/kaggle/working/pruned_loras\"\n",
346
+ "os.makedirs(base_dir, exist_ok=True)\n",
347
+ "os.makedirs(f\"{base_dir}/processed\", exist_ok=True)\n",
348
+ "os.makedirs(f\"{base_dir}/metadata\", exist_ok=True)\n",
349
+ "\n",
350
+ "print(f\"Working directory: {base_dir}\")\n",
351
+ "\n",
352
+ "# Read repo_id from repo_id.txt\n",
353
+ "repo_id = None\n",
354
+ "try:\n",
355
+ " repo_id_path = Path(kaggle_repo_path) / \"repo_id.txt\"\n",
356
+ " if repo_id_path.exists():\n",
357
+ " repo_id = repo_id_path.read_text(encoding=\"utf-8\").strip()\n",
358
+ " print(\"βœ… repo_id loaded from repo_id.txt\")\n",
359
+ " else:\n",
360
+ " print(f\"⚠️ repo_id.txt not found at {repo_id_path}\")\n",
361
+ "except Exception as e:\n",
362
+ " print(f\"⚠️ Failed to read repo_id.txt: {e}\")\n",
363
+ "#-----#"
364
+ ]
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "execution_count": null,
369
+ "id": "d3005a43",
370
+ "metadata": {
371
+ "execution": {
372
+ "iopub.execute_input": "2026-05-14T18:10:03.161814Z",
373
+ "iopub.status.busy": "2026-05-14T18:10:03.161246Z",
374
+ "iopub.status.idle": "2026-05-14T18:10:26.771985Z",
375
+ "shell.execute_reply": "2026-05-14T18:10:26.770854Z"
376
+ },
377
+ "papermill": {
378
+ "duration": 23.615718,
379
+ "end_time": "2026-05-14T18:10:26.773639+00:00",
380
+ "exception": false,
381
+ "start_time": "2026-05-14T18:10:03.157921+00:00",
382
+ "status": "completed"
383
+ },
384
+ "tags": [],
385
+ "id": "d3005a43"
386
+ },
387
+ "outputs": [],
388
+ "source": [
389
+ "repo_id = \"codeShare/flux-klein-colorize-lora\" #@param {type:\"string\"}\n",
390
+ "#\"Realism_Engine_Klein_V2.*\",\n",
391
+ "#\"Flux.2 Klein 9B - Thong Panties.*\" , \"F2K9B_chairtied_cha1rt1ed_V2E10.*\", \"klein_snofs_v1_2.*\" , \"f2k_consist_20260225.*\" , \"darkBeastMar2126Latest_dbkBlitzV15.*\"],\n",
392
+ "# =============================================================================\n",
393
+ "# CELL 4: Download + Smart Letter Naming\n",
394
+ "# =============================================================================\n",
395
+ "print(f\"Downloading .safetensors from {repo_id} ...\")\n",
396
+ "\n",
397
+ "snapshot_download(\n",
398
+ " repo_id=repo_id,\n",
399
+ " local_dir=base_dir,\n",
400
+ " token=hf_token,\n",
401
+ " ignore_patterns=[\"*.md\", \"*.txt\", \"*.json\", \"*.png\", \"*.jpg\"],\n",
402
+ ")\n",
403
+ "\n",
404
+ "original_files = sorted([f for f in os.listdir(base_dir) if f.endswith(\".safetensors\")])\n",
405
+ "print(f\"βœ… Downloaded {len(original_files)} LoRA files.\")\n",
406
+ "\n",
407
+ "# ====================== SMART LETTER GENERATOR ======================\n",
408
+ "def generate_letter_labels(n):\n",
409
+ " labels = []\n",
410
+ " i = 0\n",
411
+ " while len(labels) < n:\n",
412
+ " if i < 26:\n",
413
+ " labels.append(chr(65 + i))\n",
414
+ " else:\n",
415
+ " first = chr(65 + (i - 26) // 26)\n",
416
+ " second = chr(65 + (i - 26) % 26)\n",
417
+ " labels.append(first + second)\n",
418
+ " i += 1\n",
419
+ " return labels\n",
420
+ "\n",
421
+ "letters = generate_letter_labels(len(original_files))\n",
422
+ "\n",
423
+ "# Create mapping file BEFORE renaming\n",
424
+ "mapping_path = os.path.join(base_dir, \"original_mapping.txt\")\n",
425
+ "with open(mapping_path, \"w\", encoding=\"utf-8\") as f:\n",
426
+ " f.write(\"Original Name β†’ New Short Name\\n\")\n",
427
+ " f.write(\"=\" * 70 + \"\\n\")\n",
428
+ " for old_name, letter in zip(original_files, letters):\n",
429
+ " f.write(f\"{old_name} β†’ {letter}.safetensors\\n\")\n",
430
+ "\n",
431
+ "print(f\"βœ… Mapping saved to: {mapping_path}\")\n",
432
+ "\n",
433
+ "# Rename files\n",
434
+ "lora_files = []\n",
435
+ "for old_name, letter in zip(original_files, letters):\n",
436
+ " new_name = f\"{letter}.safetensors\"\n",
437
+ " old_path = os.path.join(base_dir, old_name)\n",
438
+ " new_path = os.path.join(base_dir, new_name)\n",
439
+ "\n",
440
+ " os.rename(old_path, new_path)\n",
441
+ " lora_files.append(new_name)\n",
442
+ " print(f\" {old_name} β†’ {new_name}\")\n",
443
+ "\n",
444
+ "print(f\"βœ… All files renamed using A-Z + AA, AB... system.\")"
445
+ ]
446
+ },
447
+ {
448
+ "cell_type": "code",
449
+ "execution_count": null,
450
+ "id": "d328be3b",
451
+ "metadata": {
452
+ "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
453
+ "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
454
+ "execution": {
455
+ "iopub.execute_input": "2026-05-14T18:10:26.781049Z",
456
+ "iopub.status.busy": "2026-05-14T18:10:26.780630Z",
457
+ "iopub.status.idle": "2026-05-14T21:19:09.863745Z",
458
+ "shell.execute_reply": "2026-05-14T21:19:09.862844Z"
459
+ },
460
+ "papermill": {
461
+ "duration": 11323.149894,
462
+ "end_time": "2026-05-14T21:19:09.926355+00:00",
463
+ "exception": false,
464
+ "start_time": "2026-05-14T18:10:26.776461+00:00",
465
+ "status": "completed"
466
+ },
467
+ "tags": [],
468
+ "id": "d328be3b"
469
+ },
470
+ "outputs": [],
471
+ "source": [
472
+ "# =============================================================================\n",
473
+ "# CELL 5: Pruning - Supports Regular LoRA + LoKr (Kronecker)\n",
474
+ "# =============================================================================\n",
475
+ "from collections import defaultdict\n",
476
+ "import time\n",
477
+ "import datetime\n",
478
+ "import os\n",
479
+ "import random\n",
480
+ "import gc\n",
481
+ "import torch\n",
482
+ "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
483
+ "from pathlib import Path\n",
484
+ "from safetensors import safe_open\n",
485
+ "\n",
486
+ "desired_accuracy = 85 #@param {type:\"slider\", min:80, max:100, step:1}\n",
487
+ "\n",
488
+ "print(f\"🎯 Target Accuracy: {desired_accuracy}% | LoRA + LoKr Support\")\n",
489
+ "\n",
490
+ "# ====================== LOAD ORIGINAL NAME MAPPING ======================\n",
491
+ "original_to_letter = {}\n",
492
+ "mapping_path = os.path.join(base_dir, \"original_mapping.txt\")\n",
493
+ "if os.path.exists(mapping_path):\n",
494
+ " with open(mapping_path, \"r\", encoding=\"utf-8\") as f:\n",
495
+ " for line in f:\n",
496
+ " if \"β†’\" in line:\n",
497
+ " parts = line.strip().split(\"β†’\")\n",
498
+ " if len(parts) == 2:\n",
499
+ " old = parts[0].strip()\n",
500
+ " new = parts[1].strip()\n",
501
+ " original_to_letter[new] = old\n",
502
+ " print(f\"βœ… Loaded {len(original_to_letter)} original filename mappings\")\n",
503
+ "else:\n",
504
+ " print(\"⚠️ original_mapping.txt not found - using short names\")\n",
505
+ "\n",
506
+ "# ====================== WORKER FUNCTION ======================\n",
507
+ "def worker(thread_id: int, gpu_id: int, file_list: list):\n",
508
+ " print(f\"[Thread {thread_id} | GPU {gpu_id}] πŸš€ Started with {len(file_list)} files\")\n",
509
+ " torch.cuda.set_device(gpu_id)\n",
510
+ "\n",
511
+ " for idx, filename in enumerate(file_list):\n",
512
+ " letter = filename.replace(\".safetensors\", \"\")\n",
513
+ " input_path = os.path.join(base_dir, filename)\n",
514
+ " size_before = os.path.getsize(input_path) / (1024 * 1024)\n",
515
+ "\n",
516
+ " print(f\"[Thread {thread_id} | GPU {gpu_id}] πŸ”„ Processing [{letter}] {filename} ({size_before:.2f} MB)\")\n",
517
+ "\n",
518
+ " torch.cuda.empty_cache()\n",
519
+ " gc.collect()\n",
520
+ "\n",
521
+ " original_filename = original_to_letter.get(filename, filename)\n",
522
+ "\n",
523
+ " random_suffix = random.randint(10000, 99999)\n",
524
+ " output_name = f\"{letter}_{random_suffix}.safetensors\"\n",
525
+ " output_path = f\"{base_dir}/processed/{output_name}\"\n",
526
+ "\n",
527
+ " # Load file\n",
528
+ " state_dict = safetensors.torch.load_file(input_path, device=\"cpu\")\n",
529
+ "\n",
530
+ " original_metadata = {}\n",
531
+ " try:\n",
532
+ " with safe_open(input_path, framework=\"pt\", device=\"cpu\") as f:\n",
533
+ " original_metadata = f.metadata() or {}\n",
534
+ " except:\n",
535
+ " pass\n",
536
+ "\n",
537
+ " # ====================== PARSE LAYERS (LoRA + LoKr) ======================\n",
538
+ " lora_pairs = defaultdict(dict)\n",
539
+ " original_ranks = {}\n",
540
+ " is_lokr = False\n",
541
+ "\n",
542
+ " for key, tensor in state_dict.items():\n",
543
+ " if \".lokr_\" in key:\n",
544
+ " is_lokr = True\n",
545
+ " # Extract base key\n",
546
+ " base = key.split(\".lokr_\")[0]\n",
547
+ "\n",
548
+ " if \".lokr_w1\" in key:\n",
549
+ " lora_pairs[base][\"w1\"] = tensor\n",
550
+ " original_ranks[base] = tensor.shape[0] * tensor.shape[1] # approximate full rank\n",
551
+ " elif \".lokr_w2\" in key:\n",
552
+ " lora_pairs[base][\"w2\"] = tensor\n",
553
+ " elif \".lokr_w\" in key: # some LoKr have single lokr_w\n",
554
+ " lora_pairs[base][\"w\"] = tensor\n",
555
+ " original_ranks[base] = tensor.shape[0]\n",
556
+ "\n",
557
+ " elif \".lora_A.weight\" in key or \".lora_down.weight\" in key:\n",
558
+ " base = key.replace(\".lora_A.weight\", \"\").replace(\".lora_down.weight\", \"\")\n",
559
+ " lora_pairs[base][\"A\"] = tensor\n",
560
+ " original_ranks[base] = tensor.shape[0]\n",
561
+ " elif \".lora_B.weight\" in key or \".lora_up.weight\" in key:\n",
562
+ " base = key.replace(\".lora_B.weight\", \"\").replace(\".lora_up.weight\", \"\")\n",
563
+ " lora_pairs[base][\"B\"] = tensor\n",
564
+ "\n",
565
+ " # Pruning\n",
566
+ " new_state_dict = dict(state_dict)\n",
567
+ " changes_made = False\n",
568
+ " pruned_count = 0\n",
569
+ " total_layers = len(lora_pairs)\n",
570
+ " layer_log = []\n",
571
+ "\n",
572
+ " for base_key, matrices in lora_pairs.items():\n",
573
+ " if not matrices:\n",
574
+ " continue\n",
575
+ "\n",
576
+ " # ==================== LoKr Handling ====================\n",
577
+ " if \"w1\" in matrices and \"w2\" in matrices:\n",
578
+ " # Reconstruct delta_W = kron(w1, w2)\n",
579
+ " w1 = matrices[\"w1\"].to(gpu_id)\n",
580
+ " w2 = matrices[\"w2\"].to(gpu_id)\n",
581
+ " delta_W = torch.kron(w1, w2).float()\n",
582
+ " orig_rank = original_ranks.get(base_key, w1.shape[0] * w1.shape[1])\n",
583
+ " is_lokr_layer = True\n",
584
+ " elif \"w\" in matrices:\n",
585
+ " delta_W = matrices[\"w\"].to(gpu_id).float()\n",
586
+ " orig_rank = original_ranks.get(base_key, delta_W.shape[0])\n",
587
+ " is_lokr_layer = True\n",
588
+ " # ==================== Standard LoRA ====================\n",
589
+ " elif \"A\" in matrices and \"B\" in matrices:\n",
590
+ " A = matrices[\"A\"].to(gpu_id)\n",
591
+ " B = matrices[\"B\"].to(gpu_id)\n",
592
+ " delta_W = torch.matmul(B, A).float()\n",
593
+ " orig_rank = original_ranks.get(base_key, A.shape[0])\n",
594
+ " is_lokr_layer = False\n",
595
+ " else:\n",
596
+ " continue\n",
597
+ "\n",
598
+ " original_norm = torch.norm(delta_W, p='fro').item()\n",
599
+ "\n",
600
+ " U, S, Vh = torch.linalg.svd(delta_W, full_matrices=False)\n",
601
+ "\n",
602
+ " # Try reduced ranks\n",
603
+ " candidates = [max(1, int(orig_rank * f)) for f in [0.95, 0.9, 0.85, 0.8, 0.75, 0.7, 0.65, 0.6]]\n",
604
+ " test_ranks = sorted(set(r for r in candidates if r < orig_rank))\n",
605
+ "\n",
606
+ " best_rank = orig_rank\n",
607
+ " best_acc = 100.0\n",
608
+ "\n",
609
+ " for r in test_ranks:\n",
610
+ " if r >= len(S): continue\n",
611
+ " S_trunc = torch.zeros_like(S)\n",
612
+ " S_trunc[:r] = S[:r]\n",
613
+ " approx = U @ torch.diag(S_trunc) @ Vh\n",
614
+ " error = torch.norm(delta_W - approx, p='fro').item()\n",
615
+ " rel_error = (error / original_norm * 100) if original_norm > 1e-8 else 0.0\n",
616
+ " acc = 100 - rel_error\n",
617
+ "\n",
618
+ " if acc >= desired_accuracy:\n",
619
+ " best_rank = r\n",
620
+ " best_acc = acc\n",
621
+ " break\n",
622
+ "\n",
623
+ " if best_rank < orig_rank:\n",
624
+ " changes_made = True\n",
625
+ " pruned_count += 1\n",
626
+ " r = best_rank\n",
627
+ "\n",
628
+ " sqrt_S = torch.sqrt(S[:r])\n",
629
+ " new_up = (U[:, :r] * sqrt_S.unsqueeze(0)).to(torch.bfloat16)\n",
630
+ " new_down = (sqrt_S.unsqueeze(1) * Vh[:r, :]).to(torch.bfloat16)\n",
631
+ "\n",
632
+ " # Remove ALL old keys for this layer\n",
633
+ " for suffix in [\".lora_A.weight\", \".lora_B.weight\",\n",
634
+ " \".lora_down.weight\", \".lora_up.weight\",\n",
635
+ " \".lokr_w1\", \".lokr_w2\", \".lokr_w\", \".alpha\"]:\n",
636
+ " new_state_dict.pop(base_key + suffix, None)\n",
637
+ "\n",
638
+ " # Save as standard LoRA (most compatible)\n",
639
+ " new_state_dict[base_key + \".lora_down.weight\"] = new_down.contiguous().cpu()\n",
640
+ " new_state_dict[base_key + \".lora_up.weight\"] = new_up.contiguous().cpu()\n",
641
+ "\n",
642
+ " print(f\" β†’ {base_key} | {orig_rank} β†’ {best_rank} | Acc {best_acc:.2f}% {'(LoKr)' if is_lokr_layer else ''}\")\n",
643
+ " layer_log.append(f\"{base_key} | {orig_rank:3} β†’ {best_rank:3} | Pruned | Acc {best_acc:.2f}% {'(LoKr)' if is_lokr_layer else ''}\")\n",
644
+ " else:\n",
645
+ " layer_log.append(f\"{base_key} | {orig_rank:3} β†’ {orig_rank:3} | No change\")\n",
646
+ "\n",
647
+ " # Cleanup\n",
648
+ " del delta_W, U, S, Vh\n",
649
+ " if 'w1' in locals(): del w1\n",
650
+ " if 'w2' in locals(): del w2\n",
651
+ " torch.cuda.empty_cache()\n",
652
+ "\n",
653
+ " # Delete original\n",
654
+ " if os.path.exists(input_path):\n",
655
+ " os.remove(input_path)\n",
656
+ "\n",
657
+ " if not changes_made:\n",
658
+ " print(f\"[Thread {thread_id} | GPU {gpu_id}] β†’ No pruning needed for [{letter}]\")\n",
659
+ " continue\n",
660
+ "\n",
661
+ " # ====================== SAVE FILE ======================\n",
662
+ " new_metadata = dict(original_metadata)\n",
663
+ " new_metadata.update({\n",
664
+ " \"original_file\": original_filename,\n",
665
+ " \"pruned_with\": f\"SVD Rank Reduction at {desired_accuracy}% accuracy\",\n",
666
+ " \"pruning_date\": datetime.datetime.now().isoformat(),\n",
667
+ " \"random_id\": str(random_suffix),\n",
668
+ " \"layers_pruned\": f\"{pruned_count}/{total_layers}\",\n",
669
+ " \"note\": \"Converted LoKr to standard LoRA where applicable\"\n",
670
+ " })\n",
671
+ "\n",
672
+ " for k, v in new_state_dict.items():\n",
673
+ " if isinstance(v, torch.Tensor):\n",
674
+ " new_state_dict[k] = v.contiguous()\n",
675
+ "\n",
676
+ " safetensors.torch.save_file(new_state_dict, output_path, metadata=new_metadata)\n",
677
+ "\n",
678
+ " size_after = os.path.getsize(output_path) / (1024 * 1024)\n",
679
+ "\n",
680
+ " # Save metadata log\n",
681
+ " meta_dir = f\"{base_dir}/metadata/{letter}\"\n",
682
+ " os.makedirs(meta_dir, exist_ok=True)\n",
683
+ " with open(f\"{meta_dir}/{letter}_metadata.txt\", \"w\", encoding=\"utf-8\") as f:\n",
684
+ " f.write(f\"Original filename: {original_filename}\\n\")\n",
685
+ " f.write(f\"Pruned filename : {output_name}\\n\")\n",
686
+ " f.write(f\"Size Before : {size_before:.2f} MB\\n\")\n",
687
+ " f.write(f\"Size After : {size_after:.2f} MB\\n\")\n",
688
+ " f.write(f\"Layers Pruned : {pruned_count}/{total_layers}\\n\\n\")\n",
689
+ " f.write(\"=== LAYER DETAILS ===\\n\")\n",
690
+ " for line in layer_log:\n",
691
+ " f.write(line + \"\\n\")\n",
692
+ "\n",
693
+ " print(f\"[Thread {thread_id} | GPU {gpu_id}] βœ… Saved [{letter}] | {size_before:.1f}MB β†’ {size_after:.1f}MB\")\n",
694
+ "\n",
695
+ " del state_dict, new_state_dict\n",
696
+ " torch.cuda.empty_cache()\n",
697
+ " gc.collect()\n",
698
+ "\n",
699
+ " print(f\"[Thread {thread_id} | GPU {gpu_id}] 🏁 Worker completed\")\n",
700
+ " return True\n",
701
+ "\n",
702
+ "\n",
703
+ "# ====================== LAUNCH THREADS ======================\n",
704
+ "print(f\"\\nDistributing {len(lora_files)} files...\")\n",
705
+ "\n",
706
+ "num_threads = 2\n",
707
+ "chunks = [[] for _ in range(num_threads)]\n",
708
+ "for i, f in enumerate(lora_files):\n",
709
+ " chunks[i % num_threads].append(f)\n",
710
+ "\n",
711
+ "with ThreadPoolExecutor(max_workers=num_threads) as executor:\n",
712
+ " futures = []\n",
713
+ " for t in range(num_threads):\n",
714
+ " gpu_id = t % 2\n",
715
+ " future = executor.submit(worker, t, gpu_id, chunks[t])\n",
716
+ " futures.append(future)\n",
717
+ " print(f\" β†’ Thread {t} on GPU {gpu_id} ({len(chunks[t])} files)\")\n",
718
+ " if t < num_threads - 1:\n",
719
+ " time.sleep(15)\n",
720
+ "\n",
721
+ " for future in as_completed(futures):\n",
722
+ " future.result()\n",
723
+ "\n",
724
+ "print(\"\\nπŸŽ‰ All pruning completed! (LoRA + LoKr supported)\")"
725
+ ]
726
+ }
727
+ ],
728
+ "metadata": {
729
+ "kaggle": {
730
+ "accelerator": "nvidiaTeslaT4",
731
+ "dataSources": [
732
+ {
733
+ "databundleVersionId": 17239359,
734
+ "datasetId": 8022630,
735
+ "sourceId": 16255844,
736
+ "sourceType": "datasetVersion"
737
+ }
738
+ ],
739
+ "dockerImageVersionId": 31329,
740
+ "isGpuEnabled": true,
741
+ "isInternetEnabled": true,
742
+ "language": "python",
743
+ "sourceType": "notebook"
744
+ },
745
+ "kernelspec": {
746
+ "display_name": "Python 3",
747
+ "name": "python3"
748
+ },
749
+ "language_info": {
750
+ "codemirror_mode": {
751
+ "name": "ipython",
752
+ "version": 3
753
+ },
754
+ "file_extension": ".py",
755
+ "mimetype": "text/x-python",
756
+ "name": "python",
757
+ "nbconvert_exporter": "python",
758
+ "pygments_lexer": "ipython3",
759
+ "version": "3.12.12"
760
+ },
761
+ "papermill": {
762
+ "default_parameters": {},
763
+ "duration": 11372.148303,
764
+ "end_time": "2026-05-14T21:19:13.559262+00:00",
765
+ "environment_variables": {},
766
+ "exception": null,
767
+ "input_path": "__notebook__.ipynb",
768
+ "output_path": "__notebook__.ipynb",
769
+ "parameters": {},
770
+ "start_time": "2026-05-14T18:09:41.410959+00:00",
771
+ "version": "2.7.0"
772
+ },
773
+ "colab": {
774
+ "provenance": [],
775
+ "gpuType": "T4",
776
+ "collapsed_sections": [
777
+ "EJAKMbW1bIFx"
778
+ ]
779
+ },
780
+ "accelerator": "GPU"
781
+ },
782
+ "nbformat": 4,
783
+ "nbformat_minor": 5
784
+ }