-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.py
407 lines (371 loc) · 11.4 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import os
import sys
import argparse
from datetime import datetime
import random
from dotenv import load_dotenv
from encoders import MultiLayerRelu, Siren
import nlsh
from nlsh.hashings import MultivariateBernoulli, Categorical
from nlsh.data import Glove, SIFT
from nlsh.loggers import TensorboardX, CometML, WandB, NullLogger
from nlsh.trainers import (
TripletTrainer,
SiameseTrainer,
VQVAE,
ProposedTrainer,
AE,
HierarchicalNavigableSmallWorldGraph,
)
from nlsh.learning.distances import (
JSD_categorical,
MVBernoulliL2,
MVBernoulliKLDivergence,
MVBernoulliCrossEntropy,
MVBernoulliTanhCosine,
)
load_dotenv()
LOG_BASE_DIR = os.environ["NLSH_TENSORBOARD_LOG_DIR"]
MODEL_SAVE_DIR = os.environ["NLSH_MODEL_SAVE_DIR"]
COMET_API_KEY = os.environ["NLSH_COMET_API_KEY"]
COMET_PROJECT_NAME = os.environ["NLSH_COMET_PROJECT_NAME"]
COMET_WORKSPACE = os.environ["NLSH_COMET_WORKSPACE"]
def get_data_by_id(data_id):
data_setting = data_id.split("_")
if data_setting[0] == "glove":
glove_dim = data_setting[1]
assert glove_dim in ["25", "50", "100", "200"]
path = os.environ.get(f"NLSH_PROCESSED_GLOVE_{glove_dim}_PATH")
unit_norm = "norm" in data_id
unit_ball = "sphere" in data_id
return Glove(path, unit_norm, unit_ball)
elif data_setting[0] == "sift":
path = os.environ.get(f"NLSH_PROCESSED_SIFT_PATH")
return SIFT(path, unit_norm="norm" in data_id)
raise RuntimeError
def comma_separate_ints(value):
try:
str_ints = value.split(",")
ints = [int(i) for i in str_ints]
return ints
except:
msg = f"{value} is not a valid encoder structure." \
"Should be comma separated integers, e.g. '256,256'"
raise argparse.ArgumentTypeError(msg)
def hashing_type(value):
allowed_hashings = ["Categorical", "MultivariateBernoulli"]
if value not in allowed_hashings:
msg = f"{value} is not a valid hashing type." \
f"Only {', '.join(allowed_hashings)} are allowed"
raise argparse.ArgumentTypeError(msg)
return value
def get_hashing_from_args(args, enc):
hashing_type = args.hashing_type
distance_type = args.distance_type
if hashing_type == "Categorical":
# hash_size = int(2 ** args.hash_size)
# if distance_type == "L2":
# return Categorical(enc, hash_size, L2)
# elif distance_type == "JS":
# return Categorical(enc, hash_size, JSD_categorical)
# else:
# raise RuntimeError(f"{distance_type} is not valid for {hashing_type}")
raise RuntimeError("Categorical hashing not available temporarily")
elif hashing_type == "MultivariateBernoulli":
hash_size = args.hash_size
if distance_type == "L2":
return MultivariateBernoulli(
enc,
hash_size,
MVBernoulliL2(),
)
elif distance_type == "KL":
return MultivariateBernoulli(
enc,
hash_size,
MVBernoulliKLDivergence(epsilon=1e-20),
)
elif distance_type == "CrossEntropy":
return MultivariateBernoulli(
enc,
hash_size,
MVBernoulliCrossEntropy(epsilon=1e-20),
)
else:
raise RuntimeError(f"{distance_type} is not valid for {hashing_type}")
elif hashing_type == "MultivariateBernoulliTanh":
hash_size = args.hash_size
if distance_type == "Cosine":
return MultivariateBernoulli(
enc,
hash_size,
MVBernoulliTanhCosine(),
tanh_output=True,
)
else:
raise RuntimeError(f"{distance_type} is not valid for {hashing_type}")
else:
raise RuntimeError(f"{hashing_type} is not a valid hashing type")
def get_logger_from_args(args):
if args.debug:
logger = NullLogger()
else:
if args.logger_type == "cometml":
log_tags = args.log_tags
log_tags = log_tags.split(",") if log_tags is not None else None
logger = CometML(
api_key=COMET_API_KEY,
project_name=COMET_PROJECT_NAME,
workspace=COMET_WORKSPACE,
debug=args.debug,
tags=log_tags,
)
elif args.logger_type == "tensorboard":
run_time = datetime.now().strftime("%Y%m%d-%H%M%S")
run_name = f"{int(2**args.hash_size)}_triplet_{run_time}"
logger = TensorboardX(f"{LOG_BASE_DIR}/{run_name}", run_name)
elif args.logger_type == "wandb":
log_tags = args.log_tags
log_tags = log_tags.split(",") if log_tags is not None else None
logger = WandB(log_tags)
else:
raise RuntimeError(f"{args.logger_type} is not a valid logger type")
logger.meta(params={
'k': args.k,
# hash function related
'hash_size': args.hash_size,
'encoder_structure': args.encoder_structure,
'distance_type': args.distance_type,
# data related
'data_id': args.data_id,
# fitting related
'learning_rate': args.learning_rate,
'batch_size': args.batch_size,
})
logger.args(' '.join(sys.argv[1:]))
return logger
def get_learner_from_args(args, hashing, data, logger):
if args.learner_type == "triplet":
lambda1 = args.lambda1
margin = args.triplet_margin
triplet_positive_k = args.triplet_positive_k
triplet_negative_sampling_method = args.triplet_negative_sampling_method
logger.meta(params={
"learner_type": "triplet",
"learner_args": f"m={margin} l1={lambda1} pk={triplet_positive_k}",
"triplet_margin": margin,
"triplet_positive_k": triplet_positive_k,
"triplet_negative_sampling_method": triplet_negative_sampling_method,
"lambda1": lambda1,
})
learner = TripletTrainer(
hashing,
data,
MODEL_SAVE_DIR,
logger=logger,
lambda1=lambda1,
margin=margin,
positive_k=triplet_positive_k,
negative_sampling_method=triplet_negative_sampling_method,
)
elif args.learner_type == "siamese":
lambda1 = args.lambda1
positive_margin = args.siamese_positive_margin
negative_margin = args.siamese_negative_margin
positive_rate = args.siamese_positive_rate
logger.meta(params={
"learner_type": "siamese",
"learner_args": f"nm={negative_margin} pm={positive_margin} pr={positive_rate}",
'siamese_positive_margin': positive_margin,
'siamese_negative_margin': negative_margin,
'siamese_positive_rate': positive_rate,
"lambda1": lambda1,
})
learner = SiameseTrainer(
hashing,
data,
MODEL_SAVE_DIR,
logger=logger,
lambda1=lambda1,
positive_margin=positive_margin,
negative_margin=negative_margin,
positive_rate=positive_rate,
)
elif args.learner_type == "vqvae":
logger.meta(params={
"learner_type": "vqvae",
})
learner = VQVAE(
hashing,
data,
MODEL_SAVE_DIR,
logger=logger,
)
elif args.learner_type == "proposed":
lambda1 = args.lambda1
logger.meta(params={
"learner_type": "proposed",
"learner_args": f"train_k=10 l1={lambda1}",
})
learner = ProposedTrainer(
hashing,
data,
MODEL_SAVE_DIR,
logger=logger,
train_k=10,
lambda1=lambda1,
)
elif args.learner_type == "ae":
logger.meta(params={
"learner_type": "ae",
})
learner = AE(
hashing,
data,
MODEL_SAVE_DIR,
logger=logger,
)
elif args.learner_type == "hnsw":
logger.meta(params={
"learner_type": "hnsw",
})
learner = HierarchicalNavigableSmallWorldGraph(
data,
logger=logger,
)
return learner
def nlsh_argparse():
parser = argparse.ArgumentParser()
parser.add_argument(
"-k",
type=int,
default=10,
)
parser.add_argument(
"-hs",
"--hash_size",
type=int,
default=12,
)
parser.add_argument(
"-es",
"--encoder_structure",
type=comma_separate_ints,
default='256,256',
)
parser.add_argument(
"-ht",
"--hashing_type",
default='MultivariateBernoulli',
choices=("MultivariateBernoulli", "MultivariateBernoulliTanh", "Categorical"),
)
parser.add_argument(
"-dt",
"--distance_type",
default='L2',
choices=("L2", "JS", "KL", "CrossEntropy", "Cosine"),
)
parser.add_argument(
"--data_id",
# choices=("glove_25", "glove_50", "glove_100", "glove_200",),
)
parser.add_argument(
"--logger_type",
choices=("tensorboard", "cometml", "wandb"),
)
parser.add_argument(
"--log_tags",
default=None,
)
parser.add_argument(
"--learner_type",
choices=("triplet", "siamese", "vqvae", "proposed", "ae", "hnsw"),
)
parser.add_argument(
"-tm",
"--triplet_margin",
type=float,
default=None,
)
parser.add_argument(
"-tpk",
"--triplet_positive_k",
type=int,
default=None,
)
parser.add_argument(
"-tnsm",
"--triplet_negative_sampling_method",
type=str,
default="random",
choices=("random", "nearest"),
)
parser.add_argument(
"-spm",
"--siamese_positive_margin",
type=float,
default=None,
)
parser.add_argument(
"-snm",
"--siamese_negative_margin",
type=float,
default=None,
)
parser.add_argument(
"-spr",
"--siamese_positive_rate",
type=float,
default=None,
)
parser.add_argument(
"--lambda1",
type=float,
default=2e-2,
)
parser.add_argument(
"-bs",
"--batch_size",
type=int,
default=1024,
)
parser.add_argument(
"-lr",
"--learning_rate",
type=float,
default=3e-4,
)
parser.add_argument(
"--debug",
action="store_true",
)
return parser
def main():
parser = nlsh_argparse()
args = parser.parse_args()
# hyper params
k = args.k
learning_rate = args.learning_rate
batch_size = args.batch_size
print("=== read data ===")
data = get_data_by_id(args.data_id)
data.load()
print("=== prepare encoder ===")
# enc = MultiLayerRelu(
enc = Siren(
input_dim=data.dim,
hidden_dims=args.encoder_structure,
).cuda()
hashing = get_hashing_from_args(args, enc)
logger = get_logger_from_args(args)
print("=== prepare learner ===")
learner = get_learner_from_args(args, hashing, data, logger)
print("Start training")
learner.fit(
K=k,
batch_size=batch_size,
learning_rate=learning_rate,
test_every_updates=300,
)
if __name__ == '__main__':
main()