-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPrintHook.py
50 lines (35 loc) · 1.52 KB
/
PrintHook.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
#!/usr/bin/env python
from Marker import Marker
#----------------------------------------------------------------------
class PrintHook:
""" class for debugging the flow of calls to forward().
Uses indentation to visualize hierarchy of class.
"""
def __init__(self):
self.indent = ""
def inputRepr(self, input):
if isinstance(input, list) or isinstance(input, tuple):
# it's a list or tuple
return [ self.inputRepr(x) for x in input ]
else:
return input.size()
def before(self, module, input):
# will be called before calling forward()
# print information about the module and the input sizes
import sys
print >> sys.stderr,"%srunning forward on module" % self.indent,
if isinstance(module, Marker):
print >> sys.stderr,"marker %s" % module.markerText,
else:
# generic module
print >> sys.stderr,"of type",module.__class__,
print >> sys.stderr,"input shape:",self.inputRepr(input)
self.indent += " "
def after(self, module, input, output):
# will be called after calling forward()
self.indent = self.indent[:-2]
def registerWith(self, model):
# register this print hook with the model
model.apply(lambda module: module.register_forward_pre_hook(self.before))
model.apply(lambda module: module.register_forward_hook(self.after))
#----------------------------------------------------------------------