-
Notifications
You must be signed in to change notification settings - Fork 1
/
brainfusetf.py
279 lines (245 loc) · 9.9 KB
/
brainfusetf.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
# file processed by 2to3
from __future__ import print_function, absolute_import
from builtins import map, filter, range
import sys
if sys.version_info < (3, 0):
import SocketServer
else:
import socketserver as SocketServer
import socket
import threading
import time
import os
import numpy as np
from numpy import *
import struct
def b2s(obj):
if isinstance(obj, bytes):
for error_handling in ['strict', 'replace', 'ignore']:
try:
return obj.decode("utf-8", errors=error_handling)
except:
pass
raise RuntimeError('A bytes object was passed to b2s, but not handled')
return obj
default_serve_port = 8883
# =======================
# helper functions
# =======================
def send_data(sock, path, data):
payload = '{path}&{shape}&[{data}]'.format(path=path,
shape=data.shape,
data=','.join(['%f' % x for x in data.flatten()]))
return send_msg(sock, payload)
def send_ask_info(sock, path):
payload = '{path}&(?,?)'.format(path=path)
return send_msg(sock, payload)
def send_info(sock, path, x_names, y_names):
payload = '{path}&{x_names}&{y_names}'.format(path=path,
x_names=repr(list(map(str, x_names))),
y_names=repr(list(map(str, y_names))))
return send_msg(sock, payload)
def send_msg(sock, msg):
# Prefix each message with a 4-byte length (network byte order)
if sys.version_info < (3, 0):
msg = struct.pack('=I', len(msg)) + msg
sock.sendall(msg)
else:
msg = bytes(msg, 'utf-8')
msg = struct.pack('=I', len(msg)) + msg
sock.sendall(msg)
def parse_data(data):
try:
path, shape, data = b2s(data).split('&')
except Exception:
raise Exception('Malformed input data')
return path, np.reshape(eval(data), eval(shape))
def parse_info(data):
path, x_names, y_names = b2s(data).split('&')
return path, eval(x_names), eval(y_names)
def recv_msg(sock):
# Read message length and unpack it into an integer
raw_msglen = recvall(sock, 4)
if not raw_msglen:
return None
msglen = struct.unpack('=I', raw_msglen)[0]
# Read the message data
return b2s(recvall(sock, msglen))
def recvall(sock, n):
# Helper function to recv n bytes or return None if EOF is hit
data = b''
while len(data) < n:
packet = sock.recv(n - len(data))
if not packet:
return None
data += packet
return data
# =======================
# client
# =======================
class btf_connect(object):
def __init__(self, path, host=None, port=None):
if host is None:
host = os.environ.get('BTF_HOST', 'gadb-harvest.duckdns.org')
if port is None:
port = int(os.environ.get('BTF_PORT', default_serve_port))
self.host = host
self.port = port
self.path = path
self.connection = None
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def __enter__(self):
try:
self.sock.connect((self.host, self.port))
except:
print('HOST:%s PORT:%s' % (self.host, self.port))
return self
def __exit__(self, exec_type, exec_value, exec_tb):
self.sock.close()
def info(self):
send_ask_info(self.sock, self.path)
data = recv_msg(self.sock)
if data is None:
raise ValueError('Error receiving infos for model: %s' % self.path)
path, self.x_names, self.y_names = parse_info(data)
return self.x_names, self.y_names
def run(self, input):
if isinstance(input, dict):
if not hasattr(self, 'x_names') or not hasattr(self, 'y_names'):
with btf_connect(host=self.host, port=self.port, path=self.path) as btf:
self.x_names, self.y_names = btf.info()
print(self.x_names)
print(self.y_names)
input = np.array([input[name] for name in self.x_names]).T
send_data(self.sock, self.path, input)
path, output = parse_data(recv_msg(self.sock))
if isinstance(input, dict):
output = {name: output[:, k] for k, name in enumerate(self.y_names)}
return output
def activateNets(nets, dB):
'''
:param nets: dictionary with OMFITbrainfuse objects (or path where to load NNs from)
:param dB: dictionary with entries to run on
:return: tuple with (out,sut,targets,nets,out_)
'''
if isinstance(nets, basestring):
nets = {k: OMFITpath(file) for k, file in enumerate(glob.glob(nets))}
elif not isinstance(nets, (list, tuple)):
nets = {0: nets}
net = list(nets.values())[0]
with btf_connect(path=net.filename) as btf:
inputNames, outputNames = btf.info()
targets = array([dB[k] for k in outputNames]).T
out_ = empty((len(atleast_1d(list(dB.values())[0])), len(outputNames), len(nets)))
for k, n in enumerate(nets):
with btf_connect(path=net.filename) as btf:
out_[:, :, k] = btf.run(dB)
out = mean(out_, -1)
sut = std(out_, -1)
return out, sut, targets, nets, out_
# =======================
# server
# =======================
if __name__ == "__main__":
import tensorflow as tf
from tensorflow.python.platform import gfile
__file__ = os.path.abspath(__file__)
serve_port = default_serve_port
if len(sys.argv) > 1:
serve_port = int(sys.argv[1])
models = {}
def activate(path, input):
'''
high level function that handles models buffering
:param path: path of the model
:param input: input array (or None to get xnames,ynames)
:return: output array or xnames,ynames
'''
if not path.startswith(os.sep):
path = os.path.split(__file__)[0] + os.sep + path
path = os.path.realpath(path)
if path not in models:
print('Loading %s' % path)
models[path] = model(path=path)
else:
print('mtime %f' % os.path.getmtime(path))
print('ltime %f' % models[path].load_time)
if os.path.getmtime(path) > models[path].load_time:
raise (Exception('Model reload functionality not implemented')) # somehow the model does not get updated?
# print('Updating %s'%path)
# models[path].close()
# models[path]=model(path=path)
if input is None:
return models[path].x_names, models[path].y_names
else:
return models[path].activate(input)
class model(tf.Session):
def __init__(self, target='', graph=None, config=None, path=None):
tf.Session.__init__(self, target=target, graph=graph, config=config)
self.__enter__()
if not path.startswith(os.sep):
path = os.path.split(__file__)[0] + os.sep + path
path = os.path.realpath(path)
self.path = path
self.load_time = os.path.getmtime(self.path)
with gfile.FastGFile(self.path, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
self.y, self.x_names, self.y_names = tf.import_graph_def(graph_def, return_elements=['unnormalized_nn/y:0',
'x_names:0',
'y_names:0'], name='')
self.x_names = self.x_names.eval()
self.y_names = self.y_names.eval()
def activate(self, input):
'''
:param input: input array
:return: output array
'''
print('Serving %s' % self.path)
return self.run(self.y, feed_dict={'x:0': input})
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
msg = recv_msg(self.request)
if msg is None:
print("{}: {}".format(self.client_address[0], '-- no message --'))
return
print("{}: message length {}".format(self.client_address[0], len(msg)))
query = msg.split('&')[1]
# respond to info request
if query == '(?,?)':
print('INFO-MODE')
path = msg.split('&')[0]
x_names, y_names = activate(path=path, input=None)
send_info(self.request, path, x_names, y_names)
# respond to data request
else:
print('DATA-MODE: serve starts')
while True:
try:
if msg is not None:
path, input = parse_data(msg)
output = activate(path=path, input=input)
send_data(self.request, path, output)
msg = recv_msg(self.request)
except Exception as _excp:
if 'Broken pipe' in repr(_excp) or 'Connection reset by peer' in repr(_excp) or 'Protocol wrong type for socket' in repr(_excp):
print('DATA-MODE: serve ends')
break
else:
raise
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
server = ThreadedTCPServer(('0.0.0.0', serve_port), ThreadedTCPRequestHandler)
print('-- BASH shell --')
print("export BTF_HOST=%s" % socket.gethostname())
print("export BTF_PORT=%d" % serve_port)
print('-- TCSH shell --')
print("setenv BTF_HOST %s" % socket.gethostname())
print("setenv BTF_PORT %d" % serve_port)
try:
server.serve_forever()
except (KeyboardInterrupt, SystemExit):
pass
finally:
server.shutdown()
server.server_close()