chainer.LinkHook¶
-
class
chainer.LinkHook[source]¶ Base class of hooks for links.
LinkHookis a callback object that is registered to aLink. Registered link hooks are invoked before and after callingLink.forward()method of each link.Link hooks that derive from
LinkHookmay override the following method:By default, these methods do nothing.
Specifically, when the
__call__()method of some link is invoked,forward_preprocess()(resp.forward_postprocess()) of all link hooks registered to this link are called before (resp. after)Link.forward()method of the link.There are two ways to register
LinkHookobjects toLinkobjects.The first one is to use
withstatement. Link hooks hooked in this way are registered to all links withinwithstatement and are unregistered at the end ofwithstatement.Example
The following code is a simple example in which we measure the elapsed time of a part of forward propagation procedure with
TimerHook, which is a subclass ofLinkHook.>>> class Model(chainer.Chain): ... def __init__(self): ... super(Model, self).__init__() ... with self.init_scope(): ... self.l = L.Linear(10, 10) ... def __call__(self, x1): ... return F.exp(self.l(x1)) >>> model1 = Model() >>> model2 = Model() >>> x = chainer.Variable(np.zeros((1, 10), np.float32)) >>> with chainer.link_hooks.TimerHook() as m: ... _ = model1(x) ... y = model2(x) >>> model3 = Model() >>> z = model3(y) >>> print('Total time : {}'.format(m.total_time())) ... # doctest:+ELLIPSIS Total time : ...
In this example, we measure the elapsed times for each forward propagation of all functions in
model1andmodel2. Note thatmodel3is not a target measurement asTimerHookis unregistered before forward propagation ofmodel3.Note
Chainer stores the dictionary of registered link hooks as a thread local object. So, link hooks registered are different depending on threads.
The other one is to register directly to a
Linkobject by calling itsadd_hook()method. Link hooks registered in this way can be removed bydelete_hook()method. Contrary to former registration method, link hooks are registered only to the link whichadd_hook()is called.- Parameters
name (str) – Name of this link hook.
Methods
-
added(link)[source]¶ Callback function invoked when the link hook is registered
- Parameters
link (Link) – Link object to which the link hook is registered.
Noneif the link hook is registered globally.
-
deleted(link)[source]¶ Callback function invoked when the link hook is unregistered
- Parameters
link (Link) – Link object to which the link hook is unregistered.
Noneif the link hook had been registered globally.
Attributes
-
name= 'LinkHook'¶