codeShare commited on
Commit
58bbe01
·
verified ·
1 Parent(s): 2f3b7e1

Upload LoRa_Merge_Script.ipynb

Browse files
Files changed (1) hide show
  1. LoRa_Merge_Script.ipynb +224 -26
LoRa_Merge_Script.ipynb CHANGED
@@ -36,10 +36,10 @@
36
  ],
37
  "metadata": {
38
  "id": "CBVTifA_ZwdC",
39
- "outputId": "8ce58389-8263-4016-8ebe-f61708ffef95",
40
  "colab": {
41
  "base_uri": "https://localhost:8080/"
42
- }
 
43
  },
44
  "execution_count": 1,
45
  "outputs": [
@@ -55,27 +55,225 @@
55
  {
56
  "cell_type": "code",
57
  "source": [
 
 
58
  "from safetensors.torch import load_file, save_file\n",
59
- "_puff = load_file('/content/drive/MyDrive/Saved from Chrome/pffy3FLUX.safetensors')\n",
60
- "puff = {}\n",
 
 
 
 
 
61
  "\n",
62
- "#alpha = 64\n",
63
- "#rank = 64\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  "\n",
65
- "# = > so scale = 1\n",
66
- "#desired scale = 0.5\n",
67
- "# so multiply matrices by 2 and set alpha to 32\n",
68
- "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
69
- "for key in _puff:\n",
70
- " if f'{key}'.find('alpha')>-1:\n",
71
- " puff[f'{key}'] = torch.tensor(32).to(device=device , dtype = torch.float16)\n",
72
- " #print(puff[f'{key}'])\n",
73
- " continue\n",
74
- " puff[f'{key}'] = 2*_puff[f'{key}'].to(device=device , dtype = torch.float16)\n",
75
  "\n",
76
- " #print(puff[f'{key}'].shape)\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  "\n",
78
- "save_file(puff, 'buff.safetensors')"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  ],
80
  "metadata": {
81
  "id": "SKYzFxehkfG8"
@@ -180,10 +378,10 @@
180
  "metadata": {
181
  "id": "1oxeJYHRqxQC",
182
  "collapsed": true,
183
- "outputId": "12e3a407-f9d1-403e-949b-31330be59577",
184
  "colab": {
185
  "base_uri": "https://localhost:8080/"
186
- }
 
187
  },
188
  "execution_count": 12,
189
  "outputs": [
@@ -1203,11 +1401,11 @@
1203
  "#print(torch.matmul(tgt[f'{up}'],tgt[f'{down}']).shape)\n"
1204
  ],
1205
  "metadata": {
1206
- "id": "GoDfgENYaWD7",
1207
- "outputId": "9336ae1a-6244-4e76-f291-82cda4482831",
1208
  "colab": {
1209
  "base_uri": "https://localhost:8080/"
1210
- }
 
 
1211
  },
1212
  "execution_count": 17,
1213
  "outputs": [
@@ -1230,11 +1428,11 @@
1230
  " print(oily[f'{key}'].shape)"
1231
  ],
1232
  "metadata": {
1233
- "id": "xQhVLouEfmGE",
1234
- "outputId": "662176b3-480d-48eb-f5db-97ec71b5e970",
1235
  "colab": {
1236
  "base_uri": "https://localhost:8080/"
1237
- }
 
 
1238
  },
1239
  "execution_count": 18,
1240
  "outputs": [
 
36
  ],
37
  "metadata": {
38
  "id": "CBVTifA_ZwdC",
 
39
  "colab": {
40
  "base_uri": "https://localhost:8080/"
41
+ },
42
+ "outputId": "8ce58389-8263-4016-8ebe-f61708ffef95"
43
  },
44
  "execution_count": 1,
45
  "outputs": [
 
55
  {
56
  "cell_type": "code",
57
  "source": [
58
+ "\n",
59
+ "import torch\n",
60
  "from safetensors.torch import load_file, save_file\n",
61
+ "import torch.nn as nn\n",
62
+ "from torch import linalg as LA\n",
63
+ "import os\n",
64
+ "import math\n",
65
+ "import random\n",
66
+ "import numpy as np\n",
67
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
68
  "\n",
69
+ "# For pcnt = 30 , 'filter_and_save' will keep all top 30 % values\n",
70
+ "#, and the lowest (negative) 30% values for each layer delta_W in this lora\n",
71
+ "# Then save the new filtered lora as a .safetensor file\n",
72
+ "def filter_and_save(_lora , savefile_name, new_rank , new_alpha, resolution):\n",
73
+ " lora = {}\n",
74
+ " count = 0\n",
75
+ " for key in _lora:count = count + 1\n",
76
+ " NUM_ITEMS = count\n",
77
+ " count = 0\n",
78
+ " thresh = resolution*0.000001 # 1e-6\n",
79
+ " #-------#\n",
80
+ " for key in _lora:\n",
81
+ " if f'{key}'.find('alpha') > -1:\n",
82
+ " lora[f'{key}'] = torch.tensor(new_alpha).to(device = device , dtype = torch.float32)\n",
83
+ " count = count + 1\n",
84
+ " print(f'{count} / {NUM_ITEMS}')\n",
85
+ " continue\n",
86
+ " #------#\n",
87
+ " if not f'{key}'.find('lora_down') > -1: continue\n",
88
+ " up = f'{key}'.replace('lora_down' , 'lora_up')\n",
89
+ " down = f'{key}'\n",
90
+ " #-------#\n",
91
+ " delta_W = torch.matmul(_lora[up],_lora[down]).to(device = device , dtype=torch.float32)\n",
92
+ " #---#\n",
93
+ " N = delta_W.numel()\n",
94
+ " y = delta_W.flatten().to(device = device , dtype=torch.float32)\n",
95
+ " values,indices = torch.sort(y, descending = False) # smallest -> largest elements\n",
96
+ " y = torch.zeros(y.shape).to(device = device , dtype=torch.float32)\n",
97
+ " y[indices[values>thresh]] = 1\n",
98
+ " y[indices[values<-thresh]] = 1\n",
99
+ " y = y.unflatten(0,delta_W.shape).to(device = device , dtype=torch.float32)\n",
100
+ " delta_W = torch.mul(delta_W,y).to(device = device , dtype=torch.float32)\n",
101
+ " #------#\n",
102
+ " tmp={}\n",
103
+ " tmp['u'], tmp['s'], tmp['Vh'] = torch.svd(delta_W)\n",
104
+ " tmp['u'] = tmp['u'][:,: new_rank]\n",
105
+ " tmp['s'] = tmp['s'][: new_rank]\n",
106
+ " #-------#\n",
107
+ " tmp['u'] = torch.round(torch.matmul(tmp['u'], torch.diag(tmp['s'])),decimals=6)\n",
108
+ " tmp['Vh'] = torch.round(tmp['Vh'].t()[: new_rank,:],decimals=6)\n",
109
+ " #-------#\n",
110
+ " for key in tmp:tmp[f'{key}'] = tmp[f'{key}'].contiguous()\n",
111
+ " lora[up] = tmp['u'].to(device = device , dtype=torch.float32)\n",
112
+ " lora[down] = tmp['Vh'].to(device = device , dtype=torch.float32)\n",
113
+ " #-------#\n",
114
+ " count = count + 2\n",
115
+ " print(f'{count} / {NUM_ITEMS}')\n",
116
+ " #-------#\n",
117
+ " print(f'done!')\n",
118
+ " print(f'casting params to fp16....')\n",
119
+ " for key in _lora: lora[f'{key}'] = lora[f'{key}'].to(device = device , dtype=torch.float16)\n",
120
+ " #-------#\n",
121
+ " print(f'done!')\n",
122
+ " print(f'saving {savefile_name}...')\n",
123
+ " save_file(lora , f'{savefile_name}')\n",
124
+ "#--------#\n",
125
  "\n",
126
+ "def count_zeros(_lora, resolution):\n",
127
+ " count = 0\n",
128
+ " for key in _lora:count = count + 1\n",
129
+ " NUM_ITEMS = count\n",
130
+ " count = 0\n",
131
+ " #-----#\n",
132
+ " thresh = resolution*0.000001 # 1e-6\n",
 
 
 
133
  "\n",
134
+ " print(f'at resolution = {resolution}e-6 :')\n",
135
+ " for key in _lora:\n",
136
+ " if f'{key}'.find('alpha') > -1:\n",
137
+ " count = count + 1\n",
138
+ " continue\n",
139
+ " #------#\n",
140
+ " if not f'{key}'.find('lora_down') > -1: continue\n",
141
+ " up = f'{key}'.replace('lora_down' , 'lora_up')\n",
142
+ " down = f'{key}'\n",
143
+ " #-------#\n",
144
+ " delta_W = torch.matmul(_lora[up],_lora[down]).to(device = device , dtype=torch.float32)\n",
145
+ " N = delta_W.numel()\n",
146
+ " y = delta_W.flatten().to(device = device , dtype=torch.float32)\n",
147
+ " values,indices = torch.sort(y, descending = False) # smallest -> largest elements\n",
148
+ " y = torch.ones(y.shape).to(device = device , dtype=torch.float32)\n",
149
+ " y[indices[values>thresh]] = 0\n",
150
+ " neg_pcnt = round((100*torch.sum(y) / N).item(),2)\n",
151
+ " y[indices[values<-thresh]] = 0\n",
152
+ " count = count + 2\n",
153
+ " pcnt = round((100*torch.sum(y) / N).item(),2)\n",
154
+ " neg_pcnt = round(neg_pcnt - pcnt,2) # remove zero % from neg_pcnt\n",
155
+ " pos_pcnt = round(100- pcnt - neg_pcnt,2)\n",
156
+ " print(f'at {count} / {NUM_ITEMS} : {pcnt} % zeros ,{pos_pcnt} % pos. , {neg_pcnt} % neg ')\n",
157
+ " #------#\n",
158
+ "#-----#\n",
159
+ "\n",
160
+ "def merge_and_save(_lora1 , _lora2 , _lora3, savefile_name, new_rank , new_alpha, resolution):\n",
161
+ " lora = {}\n",
162
+ " count = 0\n",
163
+ " for key in _lora1:count = count + 1\n",
164
+ " NUM_ITEMS = count\n",
165
+ " count = 0\n",
166
+ " thresh = resolution*0.000001 # 1e-6\n",
167
+ "\n",
168
+ " #-------#\n",
169
+ " for key in _lora1:\n",
170
+ " if f'{key}'.find('alpha') > -1:\n",
171
+ " lora[f'{key}'] = torch.tensor(new_alpha).to(device = device , dtype = torch.float32)\n",
172
+ " count = count + 1\n",
173
+ " print(f'{count} / {NUM_ITEMS}')\n",
174
+ " continue\n",
175
+ " #------#\n",
176
+ " #if count<462:\n",
177
+ " # count = count + 2\n",
178
+ " # continue\n",
179
+ " if not f'{key}'.find('lora_down') > -1: continue\n",
180
+ " up = f'{key}'.replace('lora_down' , 'lora_up')\n",
181
+ " down = f'{key}'\n",
182
+ " #-------#\n",
183
+ "\n",
184
+ " # Setup\n",
185
+ " delta_W = torch.matmul(_lora1[up]*0,_lora1[down]*0).to(device = device, dtype=torch.float32)\n",
186
+ " tgt_shape = delta_W.shape\n",
187
+ " N = delta_W.numel()\n",
188
+ " delta_W = torch.zeros(N).to(device = device , dtype=torch.float32)\n",
189
+ " #-----#\n",
190
+ "\n",
191
+ " #Positives\n",
192
+ " Y = torch.zeros(3,N).to(device = device , dtype=torch.float32)\n",
193
+ " Y[0] = torch.matmul(_lora1[up],_lora1[down]).flatten().to(device = device , dtype=torch.float32)\n",
194
+ " Y[1] = torch.matmul(_lora2[up],_lora2[down]).flatten().to(device = device , dtype=torch.float32)\n",
195
+ " Y[2] = torch.matmul(_lora2[up],_lora2[down]).flatten().to(device = device , dtype=torch.float32)\n",
196
+ " Y[torch.abs(Y)<thresh] = 0 #Trim\n",
197
+ " Y = torch.round(Y,decimals=6).t()\n",
198
+ " num_positives = torch.sum(Y>0,dim=1) + 0.1\n",
199
+ " elect = torch.sum(Y<0,dim=1) + 0.1\n",
200
+ " elect = (num_positives>=elect)\n",
201
+ " Y[Y<0] = 0\n",
202
+ " Y = torch.sum(Y, dim=1).to(device = device , dtype=torch.float32)\n",
203
+ " delta_W[elect] = torch.round((Y[elect]/num_positives[elect]),decimals=6).to(device = device , dtype=torch.float32)\n",
204
+ " #-----#\n",
205
+ "\n",
206
+ " #Negatives\n",
207
+ " Y = torch.zeros(3,N).to(device = device , dtype=torch.float32)\n",
208
+ " Y[0] = torch.matmul(_lora1[up],_lora1[down]).flatten().to(device = device , dtype=torch.float32)\n",
209
+ " Y[1] = torch.matmul(_lora2[up],_lora2[down]).flatten().to(device = device , dtype=torch.float32)\n",
210
+ " Y[2] = torch.matmul(_lora2[up],_lora2[down]).flatten().to(device = device , dtype=torch.float32)\n",
211
+ " Y[torch.abs(Y)<thresh] = 0 #Trim\n",
212
+ " Y = torch.round(Y,decimals=6).t()\n",
213
+ " num_negatives = torch.sum(Y<0,dim=1) + 0.1 # <-- to prevent divide by 0\n",
214
+ " elect = torch.sum(Y>0,dim=1) + 0.1\n",
215
+ " elect = (elect<num_negatives)\n",
216
+ " Y[Y>0] = 0\n",
217
+ " Y = torch.sum(Y, dim=1).to(device = device , dtype=torch.float32)\n",
218
+ " delta_W[elect] = torch.round(Y[elect]/num_positives[elect],decimals=6).to(device = device , dtype=torch.float32)\n",
219
+ " #----#\n",
220
+ "\n",
221
+ " # Free up memory prior to SVD\n",
222
+ " delta_W = delta_W.unflatten(0,tgt_shape).to(device = device , dtype=torch.float32)\n",
223
+ " delta_W = delta_W.clone().detach()\n",
224
+ " Y = {}\n",
225
+ " num_positives = {}\n",
226
+ " num_negatives = {}\n",
227
+ " elect = {}\n",
228
+ " #-----#\n",
229
+ "\n",
230
+ " # Run SVD (Single Value Decomposition)\n",
231
+ " #to get the new lora_up and lora_down for delta_W\n",
232
+ " tmp={}\n",
233
+ " tmp['u'], tmp['s'], tmp['Vh'] = torch.svd(delta_W)\n",
234
+ " tmp['u'] = tmp['u'][:,: new_rank]\n",
235
+ " tmp['s'] = tmp['s'][: new_rank]\n",
236
+ " tmp['u'] = torch.matmul(tmp['u'], torch.diag(tmp['s']))\n",
237
+ " tmp['Vh'] = tmp['Vh'].t()[: new_rank,:]\n",
238
+ " for key in tmp:tmp[f'{key}'] = tmp[f'{key}'].contiguous()\n",
239
+ " lora[up] = torch.round(tmp['u'],decimals=6).to(device = device , dtype=torch.float32)\n",
240
+ " lora[down] = torch.round(tmp['Vh'],decimals=6).to(device = device , dtype=torch.float32)\n",
241
+ " #-------#\n",
242
  "\n",
243
+ " count = count + 2\n",
244
+ " print(f'{count} / {NUM_ITEMS}')\n",
245
+ " #----#\n",
246
+ " #--------#\n",
247
+ " print(f'done!')\n",
248
+ " print(f'casting params to fp16....')\n",
249
+ " for key in lora: lora[f'{key}'] = lora[f'{key}'].to(device = device , dtype=torch.float16)\n",
250
+ " #-------#\n",
251
+ " print(f'done!')\n",
252
+ " print(f'saving {savefile_name}...')\n",
253
+ " save_file(lora , f'{savefile_name}')\n",
254
+ "#------#\n",
255
+ "\n",
256
+ "new_rank = 32\n",
257
+ "new_alpha = math.floor(new_rank/2)\n",
258
+ "resolution = 200\n",
259
+ "name = 'yeero_euro_puff'\n",
260
+ "yeero = load_file('/kaggle/input/flux-loras/yeero_100_r32_16alpha.safetensors')\n",
261
+ "euro = load_file('/kaggle/input/flux-loras/euro_100_r32_16alpha.safetensors')\n",
262
+ "puff = load_file('/kaggle/input/flux-loras/puff_200_r32_16alpha.safetensors')\n",
263
+ "savefile_name = f'{name}_{resolution}_r{new_rank}_a{new_alpha}.safetensors'\n",
264
+ "\n",
265
+ "#tgt = load_file(f'/kaggle/input/flux-loras/{name}_{resolution}_r32_16alpha.safetensors')\n",
266
+ "for key in yeero:\n",
267
+ " yeero[f'{key}'] = yeero[f'{key}'].to(device = device , dtype = torch.float32)\n",
268
+ " euro[f'{key}'] = euro[f'{key}'].to(device = device , dtype = torch.float32)\n",
269
+ " puff[f'{key}'] = puff[f'{key}'].to(device = device , dtype = torch.float32)\n",
270
+ "#-----#\n",
271
+ "print(f'for {name}.safetensors at scale = (rank/alpha) = 0.5')\n",
272
+ "merge_and_save(yeero , euro , puff, savefile_name, new_rank , new_alpha, resolution)\n",
273
+ "\n",
274
+ "\n",
275
+ "#Yeero + Scale + Puff\n",
276
+ "#filter_and_save(tgt , f'{name}_{resolution}_r{new_rank}_{new_alpha}alpha.safetensors' , new_rank , new_alpha, resolution)\n"
277
  ],
278
  "metadata": {
279
  "id": "SKYzFxehkfG8"
 
378
  "metadata": {
379
  "id": "1oxeJYHRqxQC",
380
  "collapsed": true,
 
381
  "colab": {
382
  "base_uri": "https://localhost:8080/"
383
+ },
384
+ "outputId": "12e3a407-f9d1-403e-949b-31330be59577"
385
  },
386
  "execution_count": 12,
387
  "outputs": [
 
1401
  "#print(torch.matmul(tgt[f'{up}'],tgt[f'{down}']).shape)\n"
1402
  ],
1403
  "metadata": {
 
 
1404
  "colab": {
1405
  "base_uri": "https://localhost:8080/"
1406
+ },
1407
+ "id": "GoDfgENYaWD7",
1408
+ "outputId": "9336ae1a-6244-4e76-f291-82cda4482831"
1409
  },
1410
  "execution_count": 17,
1411
  "outputs": [
 
1428
  " print(oily[f'{key}'].shape)"
1429
  ],
1430
  "metadata": {
 
 
1431
  "colab": {
1432
  "base_uri": "https://localhost:8080/"
1433
+ },
1434
+ "id": "xQhVLouEfmGE",
1435
+ "outputId": "662176b3-480d-48eb-f5db-97ec71b5e970"
1436
  },
1437
  "execution_count": 18,
1438
  "outputs": [