-
Notifications
You must be signed in to change notification settings - Fork 3
/
cuda_hamming_server.py
299 lines (202 loc) · 8.5 KB
/
cuda_hamming_server.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
import numpy
import array
import time
import math
import argparse
import conn
import sys
import socket
from cuda_hamming import CudaHamming
cuda_hamming_obj = CudaHamming()
logging_info = {}
s = None
def init():
parser = argparse.ArgumentParser(description = 'The CUDA Hamming Distance Server')
parser.add_argument('-b', default = 'localhost', help = 'Binding host')
parser.add_argument('-p', default = '8080', help = 'Port to listen')
args = parser.parse_args()
args.p = int(args.p)
return args
def log_near(hamming_distances, distance):
nears = numpy.where(hamming_distances[0] <= distance)
nears = len(nears[0])
log('<= ' + str(distance) + ' nears: ' + str(nears))
if not 'total_nears (' + str(distance) + ')' in logging_info:
logging_info['total_nears (' + str(distance) + ')'] = nears
else:
logging_info['total_nears (' + str(distance) + ')'] += nears
logging_info['avg nears (' + str(distance) + ')'] = logging_info['total_nears (' + str(distance) + ')'] / float(logging_info['cuda_run'])
def log_info(hamming_distances):
cuda_time = hamming_distances[1]
log(hamming_distances[0].shape[0])
log('time: ' + str(cuda_time))
log('max: ' + str(numpy.amax(hamming_distances[0])))
log('min: ' + str(numpy.amin(hamming_distances[0])))
log('mean: ' + str(numpy.mean(hamming_distances[0])))
if not 'cuda_time' in logging_info:
logging_info['cuda_time'] = cuda_time
logging_info['cuda_run'] = 1
else:
logging_info['cuda_time'] += cuda_time
logging_info['cuda_run'] += 1
for i in range(0, 11):
log_near(hamming_distances, i)
logging_info['avg cuda_time'] = logging_info['cuda_time'] / float(logging_info['cuda_run'])
def reset_logging_info():
for key in logging_info:
logging_info[key] = 0
def log_logging_info(title):
log(title)
for key in logging_info:
log(key + ': ' + str(logging_info[key]))
def log(msg):
try:
sys.stderr.write(str(msg) + "\n")
except:
1
def loop(args):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((args.b, args.p))
s.listen(1)
print "Socket inited."
try:
while 1:
(client, address) = s.accept()
print "Connected by: ", address
data = client.recv(1024)
if not data:
client.close()
continue
try:
if data == 'cuda_hamming_dist_in_compressed_domain':
print "call cuda_hamming_dist_in_compressed_domain"
call_cuda_hamming_dist_in_compressed_domain(client)
log_logging_info('cuda_hamming_dist_in_compressed_domain')
elif data == 'multi_iteration':
print "call multi_iteration"
call_multi_iteration(client)
log_logging_info('multi_iteration')
elif data == 'reset':
reset_logging_info()
log('reset logging info')
print 'reset logging info'
else:
log(data)
print data
except Exception as e:
print e
print "Exception found. Close connection."
client.close()
except (KeyboardInterrupt, SystemExit):
for key in logging_info:
log(key + ': ' + str(logging_info[key]))
if s != None:
print "Closing socket."
s.shutdown(socket.SHUT_RDWR)
s.close()
def call_multi_iteration(client):
vec_a = None # the query
binary_codes = buffer('') # binary codes to match
if client.sendall('next') == None:
length = client.recv(1024)
if not length: raise ValueError('Socket Error')
#print 'length: ', int(length)
if client.sendall('next') == None:
# receive query
vec_a = client.recv(int(length))
if not vec_a: raise ValueError('Socket Error')
#print len(vec_a)
vec_a = numpy.frombuffer(vec_a, dtype = numpy.dtype(numpy.uint64))
if client.sendall('next') == None:
binary_codes = conn.recv_long_vector(client)
else:
raise ValueError('Socket Error')
else:
raise ValueError('Socket Error')
data = client.recv(1024)
if data != 'ready':
#print data
raise ValueError('Socket Error')
# hamming_distances: uint8 numpy array
hamming_distances = cuda_hamming_obj.multi_iteration(vec_a, binary_codes)
log_info(hamming_distances)
hamming_distances = hamming_distances[0].astype(numpy.uint8)
conn.send_long_vector(client, hamming_distances, 1)
def call_cuda_hamming_dist_in_compressed_domain(client):
vec_a = None
columns_vector = []
if client.sendall('next') == None:
length = client.recv(1024)
if not length: raise ValueError('Socket Error')
#print 'length: ', int(length)
if client.sendall('next') == None:
# receive query
vec_a = client.recv(int(length))
if not vec_a: raise ValueError('Socket Error')
#print len(vec_a)
vec_a = numpy.frombuffer(vec_a, dtype = numpy.dtype(numpy.uint64))
#print vec_a
if client.sendall('next') == None:
# begin to receive columns
cols_vec_length = client.recv(1024)
if not cols_vec_length: raise ValueError('Socket Error')
#print "cols_vec_length: ", cols_vec_length
cols_vec_length = int(cols_vec_length)
if client.sendall('next') == None:
while cols_vec_length > 0:
cols_length = client.recv(1024)
if not cols_length: raise ValueError('Socket Error')
#print "cols_length: ", cols_length
cols_length = int(cols_length)
if client.sendall('next') == None:
columns = conn.recv_long_vector(client, None)
columns_vector.append(columns)
cols_vec_length -= 1
else:
raise ValueError('Socket Error')
done = client.recv(1024)
if done != 'done': raise ValueError('Socket Error')
if client.sendall('ok') != None:
raise ValueError('Socket Error')
else:
raise ValueError('Socket Error')
else:
raise ValueError('Socket Error')
else:
raise ValueError('Socket Error')
else:
raise ValueError('Socket Error')
image_ids_leng = client.recv(1024)
if not image_ids_leng: raise ValueError('Socket Error')
#print "image ids length: ", image_ids_leng
image_ids = numpy.zeros(int(image_ids_leng)).tolist()
if client.sendall('next') == None:
vlq_mode = client.recv(1024)
if not vlq_mode: raise ValueError('Socket Error')
if not client.sendall('done') == None:
raise ValueError('Socket Error')
else:
raise ValueError('Socket Error')
if client.recv(1024) != 'ready':
raise ValueError('Socket Error')
reshape_columns_vector = []
for columns in columns_vector:
idx = 0
reshape_columns = []
np_columns = numpy.frombuffer(columns, dtype = numpy.uint32)
while idx < np_columns.shape[0]:
length = np_columns[idx]
np_array = np_columns[idx + 1: idx + 1 + length]
if vlq_mode == 'y': np_array = np_array.astype(numpy.uint8)
reshape_columns.append(buffer(np_array))
idx = idx + 1 + length
reshape_columns_vector.append(reshape_columns)
# hamming_distances: uint8 numpy array
hamming_distances = cuda_hamming_obj.cuda_hamming_dist_in_compressed_domain(vec_a, reshape_columns_vector, image_ids, vlq_mode)
log_info(hamming_distances)
hamming_distances = hamming_distances[0].astype(numpy.uint8)
conn.send_long_vector(client, hamming_distances, 1)
if __name__ == "__main__":
args = init()
loop(args)