-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_subgraphs_age.py
289 lines (234 loc) · 8.76 KB
/
main_subgraphs_age.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
from ctypes import *
from typing import List
import csv
import cv2
import numpy as np
import xir
import vart
import os
import math
#import threading
import time
import sys
import queue
#from hashlib import md5
import argparse
import subprocess
from vaitrace_py import vai_tracepoint
DEBUG = False
PRINT_IMAGES = True
BUF_SIZE = 10
imgQ = queue.Queue(BUF_SIZE)
outQ = queue.Queue(BUF_SIZE)
morph_classes = ["0-19", "20-29", "30-39", "40-49", "50-100"]
def response_time_csv(data, filename: str = 'response_times.csv', header: list = ['img', 'time']):
"""
It creates 'csv' folder with .csv file inside.
Args:
- filename: str => name of csv file
- header: list => list of strings containing column names
- data: list of lists => each list with img_name and time
"""
if not os.path.isdir('csv'):
os.mkdir('csv')
if header is None:
header = ['img', 'time']
with open(f"csv{os.sep}{filename}", 'w', encoding='UTF8') as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(data) # writerows expects a list of lists!
return
def execute_async(dpu, tensor_buffers_dict):
input_tensor_buffers = [
tensor_buffers_dict[t.name] for t in dpu.get_input_tensors()
]
output_tensor_buffers = [
tensor_buffers_dict[t.name] for t in dpu.get_output_tensors()
]
jid = dpu.execute_async(input_tensor_buffers, output_tensor_buffers)
return dpu.wait(jid)
def DEBUG_runDPU(dpu_1):
print("Start DPU DEBUG with 1 input image")
# get DPU input/output tensors
inputTensor_1 = dpu_1.get_input_tensors()
outputTensor_1 = dpu_1.get_output_tensors()
input_1_ndim = tuple(inputTensor_1[0].dims)
output_1_ndim = tuple(outputTensor_1[0].dims)
batchSize = input_1_ndim[0]
out1 = np.zeros([batchSize,1], dtype='int8')
if DEBUG :
print(" inputTensor1={}\n".format( inputTensor_1[0]))
print("outputTensor1={}\n".format(outputTensor_1[0]))
if not imgQ.empty():
img_org = imgQ.get()
# run DPU
execute_async(
dpu_1, {
"quant_input_1": img_org,
"quant_dense_3_fix": out1
})
print("ou1 shape ", out1.shape)
print("DEBUG DONE")
@vai_tracepoint
def runDPU(dpu_1, img, images_list):
# get DPU input/output tensors
inputTensor_1 = dpu_1.get_input_tensors()
outputTensor_1 = dpu_1.get_output_tensors()
input_1_ndim = tuple(inputTensor_1[0].dims)
output_1_ndim = tuple(outputTensor_1[0].dims)
batchSize = input_1_ndim[0]
out1 = np.zeros([batchSize,1], dtype='int8')
n_of_images = len(img)
response_times = []
count = 0
write_index = 0
image_index = 0
while count < n_of_images:
if (count+batchSize<=n_of_images):
runSize = batchSize
else:
runSize=n_of_images-count
'''prepare batch input/output '''
outputData = []
inputData = []
inputData = [np.empty(input_1_ndim, dtype=np.int8, order="C")]
'''init input image to input buffer '''
for j in range(runSize):
imageRun = inputData[0]
#print(img[0].shape)
imageRun[j, ...] = img[(count + j) % n_of_images].reshape(input_1_ndim[1:])
''' run with batch '''
# run DPU
start_time = time.time()
execute_async(
dpu_1, {
"quant_input_1": imageRun,
"quant_dense_3_fix": out1
})
end_time = time.time()
inference_time = end_time - start_time
response_times.append([images_list[image_index], inference_time]) # csv header is [img, time]
#print(f"\nInference time (execute async): {inference_time:.4f} seconds\n")
cnn_out = out1.copy()
'''store output vectors '''
for j in range(runSize):
out_q[write_index] = cnn_out[0][j]
write_index += 1
count = count + runSize
image_index += 1
return response_times
#def app(images_dir,threads,model_name):
def app(images_dir,model_name):
images_list=os.listdir(images_dir)
runTotal = len(images_list)
print('Found',len(images_list),'images - processing',runTotal,'of them')
''' global list that all threads can write results to '''
global out_q
out_q = [None] * runTotal
''' get a list of subgraphs from the compiled model file '''
g = xir.Graph.deserialize(model_name)
subgraphs = g.get_root_subgraph().toposort_child_subgraph()
dpu_subgraph0 = subgraphs[0]
dpu_subgraph1 = subgraphs[1]
if DEBUG:
print("dpu_subgraph0 = " + dpu_subgraph0.get_name()) #dpu_subgraph0=subgraph_CNN__input_0
print("dpu_subgraph1 = " + dpu_subgraph1.get_name()) #dpu_subgraph1 = subgraph_CNN__CNN_Conv2d_conv1__18
dpu_1 = vart.Runner.create_runner(dpu_subgraph1, "run")
''' DEBUG with 1 input image '''
if DEBUG:
dbg_img = []
path = "./morph_test/021896_1F63.JPG"
dbg_img.append(preprocess_fn(path))
imgQ.put(dbg_img[0])
DEBUG_runDPU(dpu_1)
return
''' Pre Processing images '''
print("Pre-processing ",runTotal," images")
img = []
for i in range(runTotal):
path = os.path.join(images_dir,images_list[i])
image = cv2.imread(path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
data = np.asarray( [image] )
img.append(data)
''' DPU execution '''
print("run DPU")
start=0
end = len(img)
in_q = img[start:end]
time1 = time.time()
response_times = runDPU(dpu_1, img, images_list)
time2 = time.time()
timetotal = time2 - time1
fps = float(runTotal / timetotal)
print(" ")
print("FPS=%.2f, total frames = %.0f , time=%.4f seconds" %(fps,runTotal, timetotal))
print(" ")
''' Post Processing '''
print("Post-processing")
classes = morph_classes
correct = 0
wrong = 0
file = open('result_age.csv','w',newline='')
writer = csv.writer(file)
writer.writerow(["Path", "Età reale", "Età stimata", "Label stimato"])
for i in range(len(out_q)):
name,_ = images_list[i].split('.',1)
ground_truth = name[-2:]
if 0 <= int(ground_truth) <= 19:
label_true = classes[0]
elif 20 <= int(ground_truth) <= 29:
label_true = classes[1]
elif 30 <= int(ground_truth) <= 39:
label_true = classes[2]
elif 40 <= int(ground_truth) <= 49:
label_true = classes[3]
else:
label_true = classes[4]
if PRINT_IMAGES:
print("Image number ", i, ": ", images_list[i])
print("Predicted: ", out_q[i], " ground truth: ", ground_truth, "\n")
writer.writerow([images_list[i], ground_truth, out_q[i], label_true])
agemin, agemax = label_true.split('-')
if int(agemin) <= out_q[i] <= int(agemax):
correct += 1
else:
wrong += 1
accuracy = correct/len(out_q)
print(f"Correct: {correct} Wrong: {wrong} Accuracy: {accuracy} DPU Exec Time: {timetotal:.4f} seconds")
file.close()
return response_times
# only used if script is run as 'main' from command line
def main():
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument('-d', '--images_dir', type=str, default='./morph_test/', help='Path to folder of images. Default is images')
ap.add_argument('-m', '--model', type=str, default='./AgeGen/Age/Age.xmodel', help='Path of xmodel. Default is CNN.xmodel')
ap.add_argument('-b', '--membomb', type=str, default=False, required=False, help='Path to memory bomb C program. Default to False(?)')
args = ap.parse_args()
print("\n")
print ('Command line options:')
print (' --images_dir : ', args.images_dir)
print (' --model : ', args.model)
if args.membomb:
print (' --membomb : ', args.membomb)
proc = subprocess.Popen([args.membomb], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print (f'\nExecuting membomb...\nPID: {proc.pid}')
print("\n")
response_times = app(args.images_dir,args.model)
#csv_filename = f"{args.model.split('/')[-1]}"
#csv_header = None
if args.membomb:
pid = proc.pid
command = f"kill -0 {pid} 2>/dev/null && echo 'True' || echo 'False'"
output = subprocess.check_output(command, shell=True, text=True)
if output.strip() == 'True':
print("\nProcess with PID", pid, "is running.\n")
else:
print("\nProcess with PID", pid, "is not running.\n")
#csv_filename += f"_{args.membomb.split('/')[-1]}"
#csv_header = ["img", f"time_{args.membomb.split('/')[-1]}"]
#csv_filename += ".csv"
#response_time_csv(filename=csv_filename, header=csv_header, data=response_times)
if __name__ == '__main__':
main()