camenduru commited on
Commit
7b2449b
1 Parent(s): 4e62f64

thanks to christophschuhmann ❤

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLIP+MLP Aesthetic Score Predictor
2
+
3
+ Train, use and visualize an aesthetic score predictor ( how much people like on average an image ) based on a simple neural net that takes CLIP embeddings as inputs.
4
+
5
+
6
+ Link to the AVA training data ( already prepared) :
7
+ https://drive.google.com/drive/folders/186XiniJup5Rt9FXsHiAGWhgWz-nmCK_r?usp=sharing
8
+
9
+
10
+ Visualizations of all images from LAION 5B (english subset with 2.37B images) in 40 buckets with the model sac+logos+ava1-l14-linearMSE.pth:
11
+ http://captions.christoph-schuhmann.de/aesthetic_viz_laion_sac+logos+ava1-l14-linearMSE-en-2.37B.html
12
+
13
+
ava+logos-l14-linearMSE.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:390a3aafaf3b37d57148f9b22f30556de38343064b7d915acfa80d3812b4c9ff
3
+ size 3714759
ava+logos-l14-reluMSE.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0af3254c651d55b7ea851429c20f26ec880bb0169805a4df85b814bd7966f3e4
3
+ size 3714887
prepare-data-for-training.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # This script prepares the training images and ratings for the training.
3
+ # It assumes that all images are stored as files that PIL can read.
4
+ # It also assumes that the paths to the images files and the average ratings are in a .parquet files that can be read into a dataframe ( df ).
5
+
6
+ from datasets import load_dataset
7
+ import pandas as pd
8
+ import statistics
9
+ from torch.utils.data import Dataset, DataLoader
10
+ import clip
11
+ import torch
12
+ from PIL import Image, ImageFile
13
+ import numpy as np
14
+ import time
15
+
16
+ def normalized(a, axis=-1, order=2):
17
+ import numpy as np # pylint: disable=import-outside-toplevel
18
+
19
+ l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
20
+ l2[l2 == 0] = 1
21
+ return a / np.expand_dims(l2, axis)
22
+
23
+
24
+
25
+ device = "cuda" if torch.cuda.is_available() else "cpu"
26
+ model, preprocess = clip.load("ViT-L/14", device=device)
27
+
28
+
29
+ f = "trainingdata.parquet"
30
+ df = pd.read_parquet(f) #assumes that the df has the columns IMAGEPATH & AVERAGE_RATING
31
+
32
+
33
+ x = []
34
+ y = []
35
+ c= 0
36
+
37
+ for idx, row in df.iterrows():
38
+ start = time.time()
39
+
40
+ average_rating = float(row.AVERAGE_RATING)
41
+ print(average_rating)
42
+ if average_rating <1:
43
+ continue
44
+
45
+ img= row.IMAGEPATH #assumes that the df has the column IMAGEPATH
46
+ print(img)
47
+
48
+ try:
49
+ image = preprocess(Image.open(img)).unsqueeze(0).to(device)
50
+ except:
51
+ continue
52
+
53
+ with torch.no_grad():
54
+ image_features = model.encode_image(image)
55
+
56
+ im_emb_arr = image_features.cpu().detach().numpy()
57
+ x.append(normalized ( im_emb_arr) ) # all CLIP embeddings are getting normalized. This also has to be done when inputting an embedding later for inference
58
+ y_ = np.zeros((1, 1))
59
+ y_[0][0] = average_rating
60
+ #y_[0][1] = stdev # I initially considered also predicting the standard deviation, but then didn't do it
61
+
62
+ y.append(y_)
63
+
64
+
65
+ print(c)
66
+ c+=1
67
+
68
+
69
+
70
+
71
+ x = np.vstack(x)
72
+ y = np.vstack(y)
73
+ print(x.shape)
74
+ print(y.shape)
75
+ np.save('x_OpenAI_CLIP_L14_embeddings.npy', x)
76
+ np.save('y_ratings.npy', y)
sac+logos+ava1-l14-linearMSE.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21dd590f3ccdc646f0d53120778b296013b096a035a2718c9cb0d511bff0f1e0
3
+ size 3714759
simple_inference.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import webdataset as wds
2
+ from PIL import Image
3
+ import io
4
+ import matplotlib.pyplot as plt
5
+ import os
6
+ import json
7
+
8
+ from warnings import filterwarnings
9
+
10
+
11
+ # os.environ["CUDA_VISIBLE_DEVICES"] = "0" # choose GPU if you are on a multi GPU server
12
+ import numpy as np
13
+ import torch
14
+ import pytorch_lightning as pl
15
+ import torch.nn as nn
16
+ from torchvision import datasets, transforms
17
+ import tqdm
18
+
19
+ from os.path import join
20
+ from datasets import load_dataset
21
+ import pandas as pd
22
+ from torch.utils.data import Dataset, DataLoader
23
+ import json
24
+
25
+ import clip
26
+
27
+
28
+ from PIL import Image, ImageFile
29
+
30
+
31
+ ##### This script will predict the aesthetic score for this image file:
32
+
33
+ img_path = "test.jpg"
34
+
35
+
36
+
37
+
38
+
39
+ # if you changed the MLP architecture during training, change it also here:
40
+ class MLP(pl.LightningModule):
41
+ def __init__(self, input_size, xcol='emb', ycol='avg_rating'):
42
+ super().__init__()
43
+ self.input_size = input_size
44
+ self.xcol = xcol
45
+ self.ycol = ycol
46
+ self.layers = nn.Sequential(
47
+ nn.Linear(self.input_size, 1024),
48
+ #nn.ReLU(),
49
+ nn.Dropout(0.2),
50
+ nn.Linear(1024, 128),
51
+ #nn.ReLU(),
52
+ nn.Dropout(0.2),
53
+ nn.Linear(128, 64),
54
+ #nn.ReLU(),
55
+ nn.Dropout(0.1),
56
+
57
+ nn.Linear(64, 16),
58
+ #nn.ReLU(),
59
+
60
+ nn.Linear(16, 1)
61
+ )
62
+
63
+ def forward(self, x):
64
+ return self.layers(x)
65
+
66
+ def training_step(self, batch, batch_idx):
67
+ x = batch[self.xcol]
68
+ y = batch[self.ycol].reshape(-1, 1)
69
+ x_hat = self.layers(x)
70
+ loss = F.mse_loss(x_hat, y)
71
+ return loss
72
+
73
+ def validation_step(self, batch, batch_idx):
74
+ x = batch[self.xcol]
75
+ y = batch[self.ycol].reshape(-1, 1)
76
+ x_hat = self.layers(x)
77
+ loss = F.mse_loss(x_hat, y)
78
+ return loss
79
+
80
+ def configure_optimizers(self):
81
+ optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
82
+ return optimizer
83
+
84
+ def normalized(a, axis=-1, order=2):
85
+ import numpy as np # pylint: disable=import-outside-toplevel
86
+
87
+ l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
88
+ l2[l2 == 0] = 1
89
+ return a / np.expand_dims(l2, axis)
90
+
91
+
92
+ model = MLP(768) # CLIP embedding dim is 768 for CLIP ViT L 14
93
+
94
+ s = torch.load("sac+logos+ava1-l14-linearMSE.pth") # load the model you trained previously or the model available in this repo
95
+
96
+ model.load_state_dict(s)
97
+
98
+ model.to("cuda")
99
+ model.eval()
100
+
101
+
102
+ device = "cuda" if torch.cuda.is_available() else "cpu"
103
+ model2, preprocess = clip.load("ViT-L/14", device=device) #RN50x64
104
+
105
+
106
+ pil_image = Image.open(img_path)
107
+
108
+ image = preprocess(pil_image).unsqueeze(0).to(device)
109
+
110
+
111
+
112
+ with torch.no_grad():
113
+ image_features = model2.encode_image(image)
114
+
115
+ im_emb_arr = normalized(image_features.cpu().detach().numpy() )
116
+
117
+ prediction = model(torch.from_numpy(im_emb_arr).to(device).type(torch.cuda.FloatTensor))
118
+
119
+ print( "Aesthetic score predicted by the model:")
120
+ print( prediction )
121
+
122
+
train_predictor.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ # os.environ['CUDA_VISIBLE_DEVICES'] = "0" # in case you are using a multi GPU workstation, choose your GPU here
3
+ import tqdm
4
+ import pytorch_lightning as pl
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.utils.data import DataLoader
8
+ import torch.nn.functional as F
9
+ import pandas as pd
10
+ from datasets import load_dataset
11
+ from torch.utils.data import TensorDataset, DataLoader
12
+
13
+ import numpy as np
14
+
15
+ #define your neural net here:
16
+
17
+ class MLP(pl.LightningModule):
18
+ def __init__(self, input_size, xcol='emb', ycol='avg_rating'):
19
+ super().__init__()
20
+ self.input_size = input_size
21
+ self.xcol = xcol
22
+ self.ycol = ycol
23
+ self.layers = nn.Sequential(
24
+ nn.Linear(self.input_size, 1024),
25
+ #nn.ReLU(),
26
+ nn.Dropout(0.2),
27
+ nn.Linear(1024, 128),
28
+ #nn.ReLU(),
29
+ nn.Dropout(0.2),
30
+ nn.Linear(128, 64),
31
+ #nn.ReLU(),
32
+ nn.Dropout(0.1),
33
+
34
+ nn.Linear(64, 16),
35
+ #nn.ReLU(),
36
+
37
+ nn.Linear(16, 1)
38
+ )
39
+
40
+ def forward(self, x):
41
+ return self.layers(x)
42
+
43
+ def training_step(self, batch, batch_idx):
44
+ x = batch[self.xcol]
45
+ y = batch[self.ycol].reshape(-1, 1)
46
+ x_hat = self.layers(x)
47
+ loss = F.mse_loss(x_hat, y)
48
+ return loss
49
+
50
+ def validation_step(self, batch, batch_idx):
51
+ x = batch[self.xcol]
52
+ y = batch[self.ycol].reshape(-1, 1)
53
+ x_hat = self.layers(x)
54
+ loss = F.mse_loss(x_hat, y)
55
+ return loss
56
+
57
+ def configure_optimizers(self):
58
+ optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
59
+ return optimizer
60
+
61
+
62
+
63
+ # load the training data
64
+
65
+ x = np.load ("/mnt/spirit/ava_x.npy")
66
+
67
+ y = np.load ("/mnt/spirit/ava_y.npy")
68
+
69
+ val_percentage = 0.05 # 5% of the trainingdata will be used for validation
70
+
71
+ train_border = int(x.shape()[0] * (1 - val_percentage) )
72
+
73
+ train_tensor_x = torch.Tensor(x[:train_border]) # transform to torch tensor
74
+ train_tensor_y = torch.Tensor(y[:train_border])
75
+
76
+ train_dataset = TensorDataset(train_tensor_x,train_tensor_y) # create your datset
77
+ train_loader = DataLoader(train_dataset, batch_size=256, shuffle=True, num_workers=16) # create your dataloader
78
+
79
+
80
+ val_tensor_x = torch.Tensor(x[train_border:]) # transform to torch tensor
81
+ val_tensor_y = torch.Tensor(y[train_border:])
82
+
83
+ '''
84
+ print(train_tensor_x.size())
85
+ print(val_tensor_x.size())
86
+ print( val_tensor_x.dtype)
87
+ print( val_tensor_x[0].dtype)
88
+ '''
89
+
90
+ val_dataset = TensorDataset(val_tensor_x,val_tensor_y) # create your datset
91
+ val_loader = DataLoader(val_dataset, batch_size=512, num_workers=16) # create your dataloader
92
+
93
+
94
+
95
+
96
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
97
+
98
+ model = MLP(768).to(device) # CLIP embedding dim is 768 for CLIP ViT L 14
99
+
100
+ optimizer = torch.optim.Adam(model.parameters())
101
+
102
+ # choose the loss you want to optimze for
103
+ criterion = nn.MSELoss()
104
+ criterion2 = nn.L1Loss()
105
+
106
+ epochs = 50
107
+
108
+ model.train()
109
+ best_loss =999
110
+ save_name = "linear_predictor_L14_MSE.pth"
111
+
112
+
113
+ for epoch in range(epochs):
114
+ losses = []
115
+ losses2 = []
116
+ for batch_num, input_data in enumerate(train_loader):
117
+ optimizer.zero_grad()
118
+ x, y = input_data
119
+ x = x.to(device).float()
120
+ y = y.to(device)
121
+
122
+ output = model(x)
123
+ loss = criterion(output, y)
124
+ loss.backward()
125
+ losses.append(loss.item())
126
+
127
+
128
+ optimizer.step()
129
+
130
+ if batch_num % 1000 == 0:
131
+ print('\tEpoch %d | Batch %d | Loss %6.2f' % (epoch, batch_num, loss.item()))
132
+ #print(y)
133
+
134
+ print('Epoch %d | Loss %6.2f' % (epoch, sum(losses)/len(losses)))
135
+ losses = []
136
+ losses2 = []
137
+
138
+ for batch_num, input_data in enumerate(val_loader):
139
+ optimizer.zero_grad()
140
+ x, y = input_data
141
+ x = x.to(device).float()
142
+ y = y.to(device)
143
+
144
+ output = model(x)
145
+ loss = criterion(output, y)
146
+ lossMAE = criterion2(output, y)
147
+ #loss.backward()
148
+ losses.append(loss.item())
149
+ losses2.append(lossMAE.item())
150
+ #optimizer.step()
151
+
152
+ if batch_num % 1000 == 0:
153
+ print('\tValidation - Epoch %d | Batch %d | MSE Loss %6.2f' % (epoch, batch_num, loss.item()))
154
+ print('\tValidation - Epoch %d | Batch %d | MAE Loss %6.2f' % (epoch, batch_num, lossMAE.item()))
155
+
156
+ #print(y)
157
+
158
+ print('Validation - Epoch %d | MSE Loss %6.2f' % (epoch, sum(losses)/len(losses)))
159
+ print('Validation - Epoch %d | MAE Loss %6.2f' % (epoch, sum(losses2)/len(losses2)))
160
+ if sum(losses)/len(losses) < best_loss:
161
+ print("Best MAE Val loss so far. Saving model")
162
+ best_loss = sum(losses)/len(losses)
163
+ print( best_loss )
164
+
165
+ torch.save(model.state_dict(), save_name )
166
+
167
+
168
+ torch.save(model.state_dict(), save_name)
169
+
170
+ print( best_loss )
171
+
172
+ print("training done")
173
+ # inferece test with dummy samples from the val set, sanity check
174
+ print( "inferece test with dummy samples from the val set, sanity check")
175
+ model.eval()
176
+ output = model(x[:5].to(device))
177
+ print(output.size())
178
+ print(output)
visulaize_100k_from_LAION400M.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import webdataset as wds
2
+ from PIL import Image
3
+ import io
4
+ import matplotlib.pyplot as plt
5
+ import os
6
+ import json
7
+
8
+ from warnings import filterwarnings
9
+
10
+
11
+ # os.environ["CUDA_VISIBLE_DEVICES"] = "0" # choose GPU if you are on a multi GPU server
12
+ import numpy as np
13
+ import torch
14
+ import pytorch_lightning as pl
15
+ import torch.nn as nn
16
+ from torchvision import datasets, transforms
17
+ import tqdm
18
+
19
+ from os.path import join
20
+ from datasets import load_dataset
21
+ import pandas as pd
22
+ from torch.utils.data import Dataset, DataLoader
23
+ import json
24
+
25
+ import clip
26
+ #import open_clip
27
+
28
+ from PIL import Image, ImageFile
29
+
30
+
31
+ # if you changed the MLP architecture during training, change it also here:
32
+
33
+ class MLP(pl.LightningModule):
34
+ def __init__(self, input_size, xcol='emb', ycol='avg_rating'):
35
+ super().__init__()
36
+ self.input_size = input_size
37
+ self.xcol = xcol
38
+ self.ycol = ycol
39
+ self.layers = nn.Sequential(
40
+ nn.Linear(self.input_size, 1024),
41
+ #nn.ReLU(),
42
+ nn.Dropout(0.2),
43
+ nn.Linear(1024, 128),
44
+ #nn.ReLU(),
45
+ nn.Dropout(0.2),
46
+ nn.Linear(128, 64),
47
+ #nn.ReLU(),
48
+ nn.Dropout(0.1),
49
+
50
+ nn.Linear(64, 16),
51
+ #nn.ReLU(),
52
+
53
+ nn.Linear(16, 1)
54
+ )
55
+
56
+ def forward(self, x):
57
+ return self.layers(x)
58
+
59
+ def training_step(self, batch, batch_idx):
60
+ x = batch[self.xcol]
61
+ y = batch[self.ycol].reshape(-1, 1)
62
+ x_hat = self.layers(x)
63
+ loss = F.mse_loss(x_hat, y)
64
+ return loss
65
+
66
+ def validation_step(self, batch, batch_idx):
67
+ x = batch[self.xcol]
68
+ y = batch[self.ycol].reshape(-1, 1)
69
+ x_hat = self.layers(x)
70
+ loss = F.mse_loss(x_hat, y)
71
+ return loss
72
+
73
+ def configure_optimizers(self):
74
+ optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
75
+ return optimizer
76
+
77
+ def normalized(a, axis=-1, order=2):
78
+ import numpy as np # pylint: disable=import-outside-toplevel
79
+
80
+ l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
81
+ l2[l2 == 0] = 1
82
+ return a / np.expand_dims(l2, axis)
83
+
84
+
85
+ model = MLP(768) # CLIP embedding dim is 768 for CLIP ViT L 14
86
+
87
+ s = torch.load("ava+logos-l14-linearMSE.pth") # load the model you trained previously or the model available in this repo
88
+
89
+ model.load_state_dict(s)
90
+
91
+
92
+ model.to("cuda")
93
+ model.eval()
94
+
95
+
96
+
97
+
98
+
99
+ device = "cuda" if torch.cuda.is_available() else "cpu"
100
+ model2, preprocess = clip.load("ViT-L/14", device=device) #RN50x64
101
+
102
+
103
+
104
+ c=0
105
+ urls= []
106
+ predictions=[]
107
+
108
+ # this will run inference over 10 webdataset tar files from LAION 400M and sort them into 20 categories
109
+ # you can DL LAION 400M and convert it to wds tar files with img2dataset ( https://github.com/rom1504/img2dataset )
110
+
111
+
112
+ for j in range(10):
113
+ if j<10:
114
+ # change the path to the tar files accordingly
115
+ dataset = wds.WebDataset("pipe:aws s3 cp s3://s-datasets/laion400m/laion400m-dat-release/0000"+str(j)+".tar -") #"pipe:aws s3 cp s3://s-datasets/laion400m/laion400m-dat-release/00625.tar -")
116
+ else:
117
+ dataset = wds.WebDataset("pipe:aws s3 cp s3://s-datasets/laion400m/laion400m-dat-release/000"+str(j)+".tar -") #"pipe:aws s3 cp s3://s-datasets/laion400m/laion400m-dat-release/00625.tar -")
118
+
119
+
120
+ for i, d in enumerate(dataset):
121
+ print(c)
122
+
123
+ metadata= json.loads(d['json'])
124
+
125
+ pil_image = Image.open(io.BytesIO(d['jpg']))
126
+ c=c+1
127
+ try:
128
+ image = preprocess(pil_image).unsqueeze(0).to(device)
129
+
130
+ except:
131
+ continue
132
+
133
+ with torch.no_grad():
134
+ image_features = model2.encode_image(image)
135
+
136
+
137
+ im_emb_arr = normalized(image_features.cpu().detach().numpy() )
138
+
139
+ prediction = model(torch.from_numpy(im_emb_arr).to(device).type(torch.cuda.FloatTensor))
140
+ urls.append(metadata["url"])
141
+ predictions.append(prediction)
142
+
143
+
144
+ df = pd.DataFrame(list(zip(urls, predictions)),
145
+ columns =['filepath', 'prediction'])
146
+
147
+
148
+ buckets = [(i, i+1) for i in range(20)]
149
+
150
+
151
+ html= "<h1>Aesthetic subsets in LAION 100k samples</h1>"
152
+
153
+ i =0
154
+ for [a,b] in buckets:
155
+ a = a/2
156
+ b = b/2
157
+ total_part = df[( (df["prediction"] ) *1>= a) & ( (df["prediction"] ) *1 <= b)]
158
+ print(a,b)
159
+ print(len(total_part) )
160
+ count_part = len(total_part) / len(df) * 100
161
+ estimated =int ( len(total_part) )
162
+ part = total_part[:50]
163
+
164
+ html+=f"<h2>In bucket {a} - {b} there is {count_part:.2f}% samples:{estimated:.2f} </h2> <div>"
165
+ for filepath in part["filepath"]:
166
+ html+='<img src="'+filepath +'" height="200" />'
167
+
168
+
169
+ html+="</div>"
170
+ i+=1
171
+ print(i)
172
+ with open("./aesthetic_viz_laion_ava+logos_L14_100k-linearMSE.html", "w") as f:
173
+ f.write(html)
174
+
175
+