Skip to content

Commit b1dc0d8

Browse files
committed
[tools] add Python script for at-a-glance prototxt summary
1 parent 2e1c1cb commit b1dc0d8

File tree

1 file changed

+138
-0
lines changed

1 file changed

+138
-0
lines changed

tools/extra/summarize.py

+138
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
"""Net summarization tool.
2+
3+
This tool summarizes the structure of a net in a concise but comprehensive
4+
tabular listing, taking a prototxt file as input.
5+
6+
Use this tool to check at a glance that the computation you've specified is the
7+
computation you expect.
8+
"""
9+
10+
from caffe.proto import caffe_pb2
11+
from google import protobuf
12+
import re
13+
import argparse
14+
15+
# ANSI codes for coloring blobs (used cyclically)
16+
COLORS = ['92', '93', '94', '95', '97', '96', '42', '43;30', '100',
17+
'444', '103;30', '107;30']
18+
DISCONNECTED_COLOR = '41'
19+
20+
def read_net(filename):
21+
net = caffe_pb2.NetParameter()
22+
with open(filename) as f:
23+
protobuf.text_format.Parse(f.read(), net)
24+
return net
25+
26+
def format_param(param):
27+
out = []
28+
if len(param.name) > 0:
29+
out.append(param.name)
30+
if param.lr_mult != 1:
31+
out.append('x{}'.format(param.lr_mult))
32+
if param.decay_mult != 1:
33+
out.append('Dx{}'.format(param.decay_mult))
34+
return ' '.join(out)
35+
36+
def printed_len(s):
37+
return len(re.sub(r'\033\[[\d;]+m', '', s))
38+
39+
def print_table(table, max_width):
40+
"""Print a simple nicely-aligned table.
41+
42+
table must be a list of (equal-length) lists. Columns are space-separated,
43+
and as narrow as possible, but no wider than max_width. Text may overflow
44+
columns; note that unlike string.format, this will not affect subsequent
45+
columns, if possible."""
46+
47+
max_widths = [max_width] * len(table[0])
48+
column_widths = [max(printed_len(row[j]) + 1 for row in table)
49+
for j in range(len(table[0]))]
50+
column_widths = [min(w, max_w) for w, max_w in zip(column_widths, max_widths)]
51+
52+
for row in table:
53+
row_str = ''
54+
right_col = 0
55+
for cell, width in zip(row, column_widths):
56+
right_col += width
57+
row_str += cell + ' '
58+
row_str += ' ' * max(right_col - printed_len(row_str), 0)
59+
print row_str
60+
61+
def summarize_net(net):
62+
disconnected_tops = set()
63+
for lr in net.layer:
64+
disconnected_tops |= set(lr.top)
65+
disconnected_tops -= set(lr.bottom)
66+
67+
table = []
68+
colors = {}
69+
for lr in net.layer:
70+
tops = []
71+
for ind, top in enumerate(lr.top):
72+
color = colors.setdefault(top, COLORS[len(colors) % len(COLORS)])
73+
if top in disconnected_tops:
74+
top = '\033[1;4m' + top
75+
if len(lr.loss_weight) > 0:
76+
top = '{} * {}'.format(lr.loss_weight[ind], top)
77+
tops.append('\033[{}m{}\033[0m'.format(color, top))
78+
top_str = ', '.join(tops)
79+
80+
bottoms = []
81+
for bottom in lr.bottom:
82+
color = colors.get(bottom, DISCONNECTED_COLOR)
83+
bottoms.append('\033[{}m{}\033[0m'.format(color, bottom))
84+
bottom_str = ', '.join(bottoms)
85+
86+
if lr.type == 'Python':
87+
type_str = lr.python_param.module + '.' + lr.python_param.layer
88+
else:
89+
type_str = lr.type
90+
91+
# Summarize conv/pool parameters.
92+
# TODO support rectangular/ND parameters
93+
conv_param = lr.convolution_param
94+
if (lr.type in ['Convolution', 'Deconvolution']
95+
and len(conv_param.kernel_size) == 1):
96+
arg_str = str(conv_param.kernel_size[0])
97+
if len(conv_param.stride) > 0 and conv_param.stride[0] != 1:
98+
arg_str += '/' + str(conv_param.stride[0])
99+
if len(conv_param.pad) > 0 and conv_param.pad[0] != 0:
100+
arg_str += '+' + str(conv_param.pad[0])
101+
arg_str += ' ' + str(conv_param.num_output)
102+
if conv_param.group != 1:
103+
arg_str += '/' + str(conv_param.group)
104+
elif lr.type == 'Pooling':
105+
arg_str = str(lr.pooling_param.kernel_size)
106+
if lr.pooling_param.stride != 1:
107+
arg_str += '/' + str(lr.pooling_param.stride)
108+
if lr.pooling_param.pad != 0:
109+
arg_str += '+' + str(lr.pooling_param.pad)
110+
else:
111+
arg_str = ''
112+
113+
if len(lr.param) > 0:
114+
param_strs = map(format_param, lr.param)
115+
if max(map(len, param_strs)) > 0:
116+
param_str = '({})'.format(', '.join(param_strs))
117+
else:
118+
param_str = ''
119+
else:
120+
param_str = ''
121+
122+
table.append([lr.name, type_str, param_str, bottom_str, '->', top_str,
123+
arg_str])
124+
return table
125+
126+
def main():
127+
parser = argparse.ArgumentParser(description="Print a concise summary of net computation.")
128+
parser.add_argument('filename', help='net prototxt file to summarize')
129+
parser.add_argument('-w', '--max-width', help='maximum field width',
130+
type=int, default=30)
131+
args = parser.parse_args()
132+
133+
net = read_net(args.filename)
134+
table = summarize_net(net)
135+
print_table(table, max_width=args.max_width)
136+
137+
if __name__ == '__main__':
138+
main()

0 commit comments

Comments
 (0)