codeShare commited on
Commit
e7cbcf2
·
verified ·
1 Parent(s): 123d732

Delete kaggle_prune_loras.ipynb

Browse files
Files changed (1) hide show
  1. kaggle_prune_loras.ipynb +0 -565
kaggle_prune_loras.ipynb DELETED
@@ -1,565 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "code",
5
- "execution_count": null,
6
- "id": "507c1488",
7
- "metadata": {
8
- "execution": {
9
- "iopub.execute_input": "2026-05-14T18:09:45.284673Z",
10
- "iopub.status.busy": "2026-05-14T18:09:45.284222Z",
11
- "iopub.status.idle": "2026-05-14T18:10:01.729025Z",
12
- "shell.execute_reply": "2026-05-14T18:10:01.727975Z"
13
- },
14
- "papermill": {
15
- "duration": 16.450904,
16
- "end_time": "2026-05-14T18:10:01.730955+00:00",
17
- "exception": false,
18
- "start_time": "2026-05-14T18:09:45.280051+00:00",
19
- "status": "completed"
20
- },
21
- "tags": [],
22
- "id": "507c1488"
23
- },
24
- "outputs": [],
25
- "source": [
26
- "# =============================================================================\n",
27
- "# CELL 1: Install dependencies\n",
28
- "# =============================================================================\n",
29
- "!pip install -q safetensors torch matplotlib numpy huggingface_hub pynacl py7zr\n",
30
- "\n",
31
- "import os\n",
32
- "import torch\n",
33
- "import gc\n",
34
- "import random\n",
35
- "import datetime\n",
36
- "\n",
37
- "print(f\"✅ PyTorch version: {torch.__version__}\")\n",
38
- "print(f\"✅ Available GPUs: {torch.cuda.device_count()}\")\n",
39
- "for i in range(torch.cuda.device_count()):\n",
40
- " print(f\" GPU {i}: {torch.cuda.get_device_name(i)}\")"
41
- ]
42
- },
43
- {
44
- "cell_type": "code",
45
- "execution_count": null,
46
- "id": "fc6693b0",
47
- "metadata": {
48
- "execution": {
49
- "iopub.execute_input": "2026-05-14T18:10:01.737730Z",
50
- "iopub.status.busy": "2026-05-14T18:10:01.736685Z",
51
- "iopub.status.idle": "2026-05-14T18:10:03.127601Z",
52
- "shell.execute_reply": "2026-05-14T18:10:03.126560Z"
53
- },
54
- "papermill": {
55
- "duration": 1.395897,
56
- "end_time": "2026-05-14T18:10:03.129339+00:00",
57
- "exception": false,
58
- "start_time": "2026-05-14T18:10:01.733442+00:00",
59
- "status": "completed"
60
- },
61
- "tags": [],
62
- "id": "fc6693b0"
63
- },
64
- "outputs": [],
65
- "source": [
66
- "# =============================================================================\n",
67
- "# CELL 2: Secrets + Config from Kaggle Dataset\n",
68
- "# =============================================================================\n",
69
- "from kaggle_secrets import UserSecretsClient\n",
70
- "from huggingface_hub import snapshot_download, login\n",
71
- "import torch\n",
72
- "import safetensors.torch\n",
73
- "from safetensors import safe_open\n",
74
- "import os\n",
75
- "import random\n",
76
- "import datetime\n",
77
- "import gc\n",
78
- "from pathlib import Path\n",
79
- "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
80
- "from collections import defaultdict\n",
81
- "\n",
82
- "print(\"✅ Libraries imported!\")\n",
83
- "\n",
84
- "# === Kaggle Dataset Path ===\n",
85
- "kaggle_repo_path = \"/kaggle/input/datasets/nekos4lyfe/image-caption-dataset/\" #@param {type:\"string\"}\n",
86
- "\n",
87
- "# Read HF_TOKEN from HF_TOKEN.txt\n",
88
- "hf_token = None\n",
89
- "try:\n",
90
- " token_path = Path(kaggle_repo_path) / \"HF_TOKEN.txt\"\n",
91
- " if token_path.exists():\n",
92
- " hf_token = token_path.read_text(encoding=\"utf-8\").strip()\n",
93
- " print(\"✅ HF_TOKEN loaded from HF_TOKEN.txt\")\n",
94
- "\n",
95
- " if hf_token:\n",
96
- " login(token=hf_token)\n",
97
- " print(\"✅ Successfully logged into Hugging Face\")\n",
98
- " else:\n",
99
- " print(f\"⚠️ HF_TOKEN.txt not found at {token_path}\")\n",
100
- "except Exception as e:\n",
101
- " print(f\"⚠️ Failed to read HF_TOKEN.txt: {e}\")"
102
- ]
103
- },
104
- {
105
- "cell_type": "code",
106
- "execution_count": null,
107
- "id": "d3cddbf0",
108
- "metadata": {
109
- "execution": {
110
- "iopub.execute_input": "2026-05-14T18:10:03.140540Z",
111
- "iopub.status.busy": "2026-05-14T18:10:03.139445Z",
112
- "iopub.status.idle": "2026-05-14T18:10:03.153972Z",
113
- "shell.execute_reply": "2026-05-14T18:10:03.152857Z"
114
- },
115
- "papermill": {
116
- "duration": 0.019317,
117
- "end_time": "2026-05-14T18:10:03.155565+00:00",
118
- "exception": false,
119
- "start_time": "2026-05-14T18:10:03.136248+00:00",
120
- "status": "completed"
121
- },
122
- "tags": [],
123
- "id": "d3cddbf0"
124
- },
125
- "outputs": [],
126
- "source": [
127
- "# =============================================================================\n",
128
- "# CELL 3: Setup Folders\n",
129
- "# =============================================================================\n",
130
- "base_dir = \"/kaggle/working/pruned_loras\"\n",
131
- "os.makedirs(base_dir, exist_ok=True)\n",
132
- "os.makedirs(f\"{base_dir}/processed\", exist_ok=True)\n",
133
- "os.makedirs(f\"{base_dir}/metadata\", exist_ok=True)\n",
134
- "\n",
135
- "print(f\"Working directory: {base_dir}\")\n",
136
- "\n",
137
- "# Read repo_id from repo_id.txt\n",
138
- "repo_id = None\n",
139
- "try:\n",
140
- " repo_id_path = Path(kaggle_repo_path) / \"repo_id.txt\"\n",
141
- " if repo_id_path.exists():\n",
142
- " repo_id = repo_id_path.read_text(encoding=\"utf-8\").strip()\n",
143
- " print(\"✅ repo_id loaded from repo_id.txt\")\n",
144
- " else:\n",
145
- " print(f\"⚠️ repo_id.txt not found at {repo_id_path}\")\n",
146
- "except Exception as e:\n",
147
- " print(f\"⚠️ Failed to read repo_id.txt: {e}\")\n",
148
- "#-----#"
149
- ]
150
- },
151
- {
152
- "cell_type": "code",
153
- "execution_count": null,
154
- "id": "d3005a43",
155
- "metadata": {
156
- "execution": {
157
- "iopub.execute_input": "2026-05-14T18:10:03.161814Z",
158
- "iopub.status.busy": "2026-05-14T18:10:03.161246Z",
159
- "iopub.status.idle": "2026-05-14T18:10:26.771985Z",
160
- "shell.execute_reply": "2026-05-14T18:10:26.770854Z"
161
- },
162
- "papermill": {
163
- "duration": 23.615718,
164
- "end_time": "2026-05-14T18:10:26.773639+00:00",
165
- "exception": false,
166
- "start_time": "2026-05-14T18:10:03.157921+00:00",
167
- "status": "completed"
168
- },
169
- "tags": [],
170
- "id": "d3005a43"
171
- },
172
- "outputs": [],
173
- "source": [
174
- "repo_id = \"codeShare/flux-klein-colorize-lora\" #@param {type:\"string\"}\n",
175
- "#\"Realism_Engine_Klein_V2.*\",\n",
176
- "#\"Flux.2 Klein 9B - Thong Panties.*\" , \"F2K9B_chairtied_cha1rt1ed_V2E10.*\", \"klein_snofs_v1_2.*\" , \"f2k_consist_20260225.*\" , \"darkBeastMar2126Latest_dbkBlitzV15.*\"],\n",
177
- "# =============================================================================\n",
178
- "# CELL 4: Download + Smart Letter Naming\n",
179
- "# =============================================================================\n",
180
- "print(f\"Downloading .safetensors from {repo_id} ...\")\n",
181
- "\n",
182
- "snapshot_download(\n",
183
- " repo_id=repo_id,\n",
184
- " local_dir=base_dir,\n",
185
- " token=hf_token,\n",
186
- " ignore_patterns=[\"*.md\", \"*.txt\", \"*.json\", \"*.png\", \"*.jpg\"],\n",
187
- ")\n",
188
- "\n",
189
- "original_files = sorted([f for f in os.listdir(base_dir) if f.endswith(\".safetensors\")])\n",
190
- "print(f\"✅ Downloaded {len(original_files)} LoRA files.\")\n",
191
- "\n",
192
- "# ====================== SMART LETTER GENERATOR ======================\n",
193
- "def generate_letter_labels(n):\n",
194
- " labels = []\n",
195
- " i = 0\n",
196
- " while len(labels) < n:\n",
197
- " if i < 26:\n",
198
- " labels.append(chr(65 + i))\n",
199
- " else:\n",
200
- " first = chr(65 + (i - 26) // 26)\n",
201
- " second = chr(65 + (i - 26) % 26)\n",
202
- " labels.append(first + second)\n",
203
- " i += 1\n",
204
- " return labels\n",
205
- "\n",
206
- "letters = generate_letter_labels(len(original_files))\n",
207
- "\n",
208
- "# Create mapping file BEFORE renaming\n",
209
- "mapping_path = os.path.join(base_dir, \"original_mapping.txt\")\n",
210
- "with open(mapping_path, \"w\", encoding=\"utf-8\") as f:\n",
211
- " f.write(\"Original Name → New Short Name\\n\")\n",
212
- " f.write(\"=\" * 70 + \"\\n\")\n",
213
- " for old_name, letter in zip(original_files, letters):\n",
214
- " f.write(f\"{old_name} → {letter}.safetensors\\n\")\n",
215
- "\n",
216
- "print(f\"✅ Mapping saved to: {mapping_path}\")\n",
217
- "\n",
218
- "# Rename files\n",
219
- "lora_files = []\n",
220
- "for old_name, letter in zip(original_files, letters):\n",
221
- " new_name = f\"{letter}.safetensors\"\n",
222
- " old_path = os.path.join(base_dir, old_name)\n",
223
- " new_path = os.path.join(base_dir, new_name)\n",
224
- "\n",
225
- " os.rename(old_path, new_path)\n",
226
- " lora_files.append(new_name)\n",
227
- " print(f\" {old_name} → {new_name}\")\n",
228
- "\n",
229
- "print(f\"✅ All files renamed using A-Z + AA, AB... system.\")"
230
- ]
231
- },
232
- {
233
- "cell_type": "code",
234
- "execution_count": null,
235
- "id": "d328be3b",
236
- "metadata": {
237
- "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
238
- "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
239
- "execution": {
240
- "iopub.execute_input": "2026-05-14T18:10:26.781049Z",
241
- "iopub.status.busy": "2026-05-14T18:10:26.780630Z",
242
- "iopub.status.idle": "2026-05-14T21:19:09.863745Z",
243
- "shell.execute_reply": "2026-05-14T21:19:09.862844Z"
244
- },
245
- "papermill": {
246
- "duration": 11323.149894,
247
- "end_time": "2026-05-14T21:19:09.926355+00:00",
248
- "exception": false,
249
- "start_time": "2026-05-14T18:10:26.776461+00:00",
250
- "status": "completed"
251
- },
252
- "tags": [],
253
- "id": "d328be3b"
254
- },
255
- "outputs": [],
256
- "source": [
257
- "# =============================================================================\n",
258
- "# CELL 5: Pruning - Supports Regular LoRA + LoKr (Kronecker)\n",
259
- "# =============================================================================\n",
260
- "from collections import defaultdict\n",
261
- "import time\n",
262
- "import datetime\n",
263
- "import os\n",
264
- "import random\n",
265
- "import gc\n",
266
- "import torch\n",
267
- "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
268
- "from pathlib import Path\n",
269
- "from safetensors import safe_open\n",
270
- "\n",
271
- "desired_accuracy = 85 #@param {type:\"slider\", min:80, max:100, step:1}\n",
272
- "\n",
273
- "print(f\"🎯 Target Accuracy: {desired_accuracy}% | LoRA + LoKr Support\")\n",
274
- "\n",
275
- "# ====================== LOAD ORIGINAL NAME MAPPING ======================\n",
276
- "original_to_letter = {}\n",
277
- "mapping_path = os.path.join(base_dir, \"original_mapping.txt\")\n",
278
- "if os.path.exists(mapping_path):\n",
279
- " with open(mapping_path, \"r\", encoding=\"utf-8\") as f:\n",
280
- " for line in f:\n",
281
- " if \"→\" in line:\n",
282
- " parts = line.strip().split(\"→\")\n",
283
- " if len(parts) == 2:\n",
284
- " old = parts[0].strip()\n",
285
- " new = parts[1].strip()\n",
286
- " original_to_letter[new] = old\n",
287
- " print(f\"✅ Loaded {len(original_to_letter)} original filename mappings\")\n",
288
- "else:\n",
289
- " print(\"⚠️ original_mapping.txt not found - using short names\")\n",
290
- "\n",
291
- "# ====================== WORKER FUNCTION ======================\n",
292
- "def worker(thread_id: int, gpu_id: int, file_list: list):\n",
293
- " print(f\"[Thread {thread_id} | GPU {gpu_id}] 🚀 Started with {len(file_list)} files\")\n",
294
- " torch.cuda.set_device(gpu_id)\n",
295
- "\n",
296
- " for idx, filename in enumerate(file_list):\n",
297
- " letter = filename.replace(\".safetensors\", \"\")\n",
298
- " input_path = os.path.join(base_dir, filename)\n",
299
- " size_before = os.path.getsize(input_path) / (1024 * 1024)\n",
300
- "\n",
301
- " print(f\"[Thread {thread_id} | GPU {gpu_id}] 🔄 Processing [{letter}] {filename} ({size_before:.2f} MB)\")\n",
302
- "\n",
303
- " torch.cuda.empty_cache()\n",
304
- " gc.collect()\n",
305
- "\n",
306
- " original_filename = original_to_letter.get(filename, filename)\n",
307
- "\n",
308
- " random_suffix = random.randint(10000, 99999)\n",
309
- " output_name = f\"{letter}_{random_suffix}.safetensors\"\n",
310
- " output_path = f\"{base_dir}/processed/{output_name}\"\n",
311
- "\n",
312
- " # Load file\n",
313
- " state_dict = safetensors.torch.load_file(input_path, device=\"cpu\")\n",
314
- "\n",
315
- " original_metadata = {}\n",
316
- " try:\n",
317
- " with safe_open(input_path, framework=\"pt\", device=\"cpu\") as f:\n",
318
- " original_metadata = f.metadata() or {}\n",
319
- " except:\n",
320
- " pass\n",
321
- "\n",
322
- " # ====================== PARSE LAYERS (LoRA + LoKr) ======================\n",
323
- " lora_pairs = defaultdict(dict)\n",
324
- " original_ranks = {}\n",
325
- " is_lokr = False\n",
326
- "\n",
327
- " for key, tensor in state_dict.items():\n",
328
- " if \".lokr_\" in key:\n",
329
- " is_lokr = True\n",
330
- " # Extract base key\n",
331
- " base = key.split(\".lokr_\")[0]\n",
332
- "\n",
333
- " if \".lokr_w1\" in key:\n",
334
- " lora_pairs[base][\"w1\"] = tensor\n",
335
- " original_ranks[base] = tensor.shape[0] * tensor.shape[1] # approximate full rank\n",
336
- " elif \".lokr_w2\" in key:\n",
337
- " lora_pairs[base][\"w2\"] = tensor\n",
338
- " elif \".lokr_w\" in key: # some LoKr have single lokr_w\n",
339
- " lora_pairs[base][\"w\"] = tensor\n",
340
- " original_ranks[base] = tensor.shape[0]\n",
341
- "\n",
342
- " elif \".lora_A.weight\" in key or \".lora_down.weight\" in key:\n",
343
- " base = key.replace(\".lora_A.weight\", \"\").replace(\".lora_down.weight\", \"\")\n",
344
- " lora_pairs[base][\"A\"] = tensor\n",
345
- " original_ranks[base] = tensor.shape[0]\n",
346
- " elif \".lora_B.weight\" in key or \".lora_up.weight\" in key:\n",
347
- " base = key.replace(\".lora_B.weight\", \"\").replace(\".lora_up.weight\", \"\")\n",
348
- " lora_pairs[base][\"B\"] = tensor\n",
349
- "\n",
350
- " # Pruning\n",
351
- " new_state_dict = dict(state_dict)\n",
352
- " changes_made = False\n",
353
- " pruned_count = 0\n",
354
- " total_layers = len(lora_pairs)\n",
355
- " layer_log = []\n",
356
- "\n",
357
- " for base_key, matrices in lora_pairs.items():\n",
358
- " if not matrices:\n",
359
- " continue\n",
360
- "\n",
361
- " # ==================== LoKr Handling ====================\n",
362
- " if \"w1\" in matrices and \"w2\" in matrices:\n",
363
- " # Reconstruct delta_W = kron(w1, w2)\n",
364
- " w1 = matrices[\"w1\"].to(gpu_id)\n",
365
- " w2 = matrices[\"w2\"].to(gpu_id)\n",
366
- " delta_W = torch.kron(w1, w2).float()\n",
367
- " orig_rank = original_ranks.get(base_key, w1.shape[0] * w1.shape[1])\n",
368
- " is_lokr_layer = True\n",
369
- " elif \"w\" in matrices:\n",
370
- " delta_W = matrices[\"w\"].to(gpu_id).float()\n",
371
- " orig_rank = original_ranks.get(base_key, delta_W.shape[0])\n",
372
- " is_lokr_layer = True\n",
373
- " # ==================== Standard LoRA ====================\n",
374
- " elif \"A\" in matrices and \"B\" in matrices:\n",
375
- " A = matrices[\"A\"].to(gpu_id)\n",
376
- " B = matrices[\"B\"].to(gpu_id)\n",
377
- " delta_W = torch.matmul(B, A).float()\n",
378
- " orig_rank = original_ranks.get(base_key, A.shape[0])\n",
379
- " is_lokr_layer = False\n",
380
- " else:\n",
381
- " continue\n",
382
- "\n",
383
- " original_norm = torch.norm(delta_W, p='fro').item()\n",
384
- "\n",
385
- " U, S, Vh = torch.linalg.svd(delta_W, full_matrices=False)\n",
386
- "\n",
387
- " # Try reduced ranks\n",
388
- " 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",
389
- " test_ranks = sorted(set(r for r in candidates if r < orig_rank))\n",
390
- "\n",
391
- " best_rank = orig_rank\n",
392
- " best_acc = 100.0\n",
393
- "\n",
394
- " for r in test_ranks:\n",
395
- " if r >= len(S): continue\n",
396
- " S_trunc = torch.zeros_like(S)\n",
397
- " S_trunc[:r] = S[:r]\n",
398
- " approx = U @ torch.diag(S_trunc) @ Vh\n",
399
- " error = torch.norm(delta_W - approx, p='fro').item()\n",
400
- " rel_error = (error / original_norm * 100) if original_norm > 1e-8 else 0.0\n",
401
- " acc = 100 - rel_error\n",
402
- "\n",
403
- " if acc >= desired_accuracy:\n",
404
- " best_rank = r\n",
405
- " best_acc = acc\n",
406
- " break\n",
407
- "\n",
408
- " if best_rank < orig_rank:\n",
409
- " changes_made = True\n",
410
- " pruned_count += 1\n",
411
- " r = best_rank\n",
412
- "\n",
413
- " sqrt_S = torch.sqrt(S[:r])\n",
414
- " new_up = (U[:, :r] * sqrt_S.unsqueeze(0)).to(torch.bfloat16)\n",
415
- " new_down = (sqrt_S.unsqueeze(1) * Vh[:r, :]).to(torch.bfloat16)\n",
416
- "\n",
417
- " # Remove ALL old keys for this layer\n",
418
- " for suffix in [\".lora_A.weight\", \".lora_B.weight\",\n",
419
- " \".lora_down.weight\", \".lora_up.weight\",\n",
420
- " \".lokr_w1\", \".lokr_w2\", \".lokr_w\", \".alpha\"]:\n",
421
- " new_state_dict.pop(base_key + suffix, None)\n",
422
- "\n",
423
- " # Save as standard LoRA (most compatible)\n",
424
- " new_state_dict[base_key + \".lora_down.weight\"] = new_down.contiguous().cpu()\n",
425
- " new_state_dict[base_key + \".lora_up.weight\"] = new_up.contiguous().cpu()\n",
426
- "\n",
427
- " print(f\" → {base_key} | {orig_rank} → {best_rank} | Acc {best_acc:.2f}% {'(LoKr)' if is_lokr_layer else ''}\")\n",
428
- " layer_log.append(f\"{base_key} | {orig_rank:3} → {best_rank:3} | Pruned | Acc {best_acc:.2f}% {'(LoKr)' if is_lokr_layer else ''}\")\n",
429
- " else:\n",
430
- " layer_log.append(f\"{base_key} | {orig_rank:3} → {orig_rank:3} | No change\")\n",
431
- "\n",
432
- " # Cleanup\n",
433
- " del delta_W, U, S, Vh\n",
434
- " if 'w1' in locals(): del w1\n",
435
- " if 'w2' in locals(): del w2\n",
436
- " torch.cuda.empty_cache()\n",
437
- "\n",
438
- " # Delete original\n",
439
- " if os.path.exists(input_path):\n",
440
- " os.remove(input_path)\n",
441
- "\n",
442
- " if not changes_made:\n",
443
- " print(f\"[Thread {thread_id} | GPU {gpu_id}] → No pruning needed for [{letter}]\")\n",
444
- " continue\n",
445
- "\n",
446
- " # ====================== SAVE FILE ======================\n",
447
- " new_metadata = dict(original_metadata)\n",
448
- " new_metadata.update({\n",
449
- " \"original_file\": original_filename,\n",
450
- " \"pruned_with\": f\"SVD Rank Reduction at {desired_accuracy}% accuracy\",\n",
451
- " \"pruning_date\": datetime.datetime.now().isoformat(),\n",
452
- " \"random_id\": str(random_suffix),\n",
453
- " \"layers_pruned\": f\"{pruned_count}/{total_layers}\",\n",
454
- " \"note\": \"Converted LoKr to standard LoRA where applicable\"\n",
455
- " })\n",
456
- "\n",
457
- " for k, v in new_state_dict.items():\n",
458
- " if isinstance(v, torch.Tensor):\n",
459
- " new_state_dict[k] = v.contiguous()\n",
460
- "\n",
461
- " safetensors.torch.save_file(new_state_dict, output_path, metadata=new_metadata)\n",
462
- "\n",
463
- " size_after = os.path.getsize(output_path) / (1024 * 1024)\n",
464
- "\n",
465
- " # Save metadata log\n",
466
- " meta_dir = f\"{base_dir}/metadata/{letter}\"\n",
467
- " os.makedirs(meta_dir, exist_ok=True)\n",
468
- " with open(f\"{meta_dir}/{letter}_metadata.txt\", \"w\", encoding=\"utf-8\") as f:\n",
469
- " f.write(f\"Original filename: {original_filename}\\n\")\n",
470
- " f.write(f\"Pruned filename : {output_name}\\n\")\n",
471
- " f.write(f\"Size Before : {size_before:.2f} MB\\n\")\n",
472
- " f.write(f\"Size After : {size_after:.2f} MB\\n\")\n",
473
- " f.write(f\"Layers Pruned : {pruned_count}/{total_layers}\\n\\n\")\n",
474
- " f.write(\"=== LAYER DETAILS ===\\n\")\n",
475
- " for line in layer_log:\n",
476
- " f.write(line + \"\\n\")\n",
477
- "\n",
478
- " print(f\"[Thread {thread_id} | GPU {gpu_id}] ✅ Saved [{letter}] | {size_before:.1f}MB → {size_after:.1f}MB\")\n",
479
- "\n",
480
- " del state_dict, new_state_dict\n",
481
- " torch.cuda.empty_cache()\n",
482
- " gc.collect()\n",
483
- "\n",
484
- " print(f\"[Thread {thread_id} | GPU {gpu_id}] 🏁 Worker completed\")\n",
485
- " return True\n",
486
- "\n",
487
- "\n",
488
- "# ====================== LAUNCH THREADS ======================\n",
489
- "print(f\"\\nDistributing {len(lora_files)} files...\")\n",
490
- "\n",
491
- "num_threads = 2\n",
492
- "chunks = [[] for _ in range(num_threads)]\n",
493
- "for i, f in enumerate(lora_files):\n",
494
- " chunks[i % num_threads].append(f)\n",
495
- "\n",
496
- "with ThreadPoolExecutor(max_workers=num_threads) as executor:\n",
497
- " futures = []\n",
498
- " for t in range(num_threads):\n",
499
- " gpu_id = t % 2\n",
500
- " future = executor.submit(worker, t, gpu_id, chunks[t])\n",
501
- " futures.append(future)\n",
502
- " print(f\" → Thread {t} on GPU {gpu_id} ({len(chunks[t])} files)\")\n",
503
- " if t < num_threads - 1:\n",
504
- " time.sleep(15)\n",
505
- "\n",
506
- " for future in as_completed(futures):\n",
507
- " future.result()\n",
508
- "\n",
509
- "print(\"\\n🎉 All pruning completed! (LoRA + LoKr supported)\")"
510
- ]
511
- }
512
- ],
513
- "metadata": {
514
- "kaggle": {
515
- "accelerator": "nvidiaTeslaT4",
516
- "dataSources": [
517
- {
518
- "databundleVersionId": 17239359,
519
- "datasetId": 8022630,
520
- "sourceId": 16255844,
521
- "sourceType": "datasetVersion"
522
- }
523
- ],
524
- "dockerImageVersionId": 31329,
525
- "isGpuEnabled": true,
526
- "isInternetEnabled": true,
527
- "language": "python",
528
- "sourceType": "notebook"
529
- },
530
- "kernelspec": {
531
- "display_name": "Python 3",
532
- "language": "python",
533
- "name": "python3"
534
- },
535
- "language_info": {
536
- "codemirror_mode": {
537
- "name": "ipython",
538
- "version": 3
539
- },
540
- "file_extension": ".py",
541
- "mimetype": "text/x-python",
542
- "name": "python",
543
- "nbconvert_exporter": "python",
544
- "pygments_lexer": "ipython3",
545
- "version": "3.12.12"
546
- },
547
- "papermill": {
548
- "default_parameters": {},
549
- "duration": 11372.148303,
550
- "end_time": "2026-05-14T21:19:13.559262+00:00",
551
- "environment_variables": {},
552
- "exception": null,
553
- "input_path": "__notebook__.ipynb",
554
- "output_path": "__notebook__.ipynb",
555
- "parameters": {},
556
- "start_time": "2026-05-14T18:09:41.410959+00:00",
557
- "version": "2.7.0"
558
- },
559
- "colab": {
560
- "provenance": []
561
- }
562
- },
563
- "nbformat": 4,
564
- "nbformat_minor": 5
565
- }