Chainer
6.0.0b2

Tutorials

  • Chainer at a Glance
  • Concepts Walkthrough

Examples

  • Neural Net Examples
  • Colab Notebook Examples
  • Awesome Chainer

References

  • API Reference
    • Variable and Parameter
    • Functions
    • Link and Chains
      • Learnable connections
      • Activation/loss/normalization functions with parameters
      • Machine learning models
      • Pre-trained models
      • Link and Chain base classes
        • chainer.Link
        • chainer.Chain
        • chainer.ChainList
        • chainer.Sequential
      • Link hooks
    • Probability Distributions
    • Optimizers
    • Weight Initializers
    • Training Tools
    • Datasets
    • Iterator
    • Serializers
    • Utilities
    • Configuring Chainer
    • Debug Mode
    • Visualization of Computational Graph
    • Static Subgraph Optimizations: Usage
    • Static Subgraph Optimizations: Design Notes
    • Caffe Model Support
    • Assertion and Testing
  • Installation
  • Distributed Deep Learning with ChainerMN

Other

  • API Compatibility Policy
  • Contribution Guide
  • Tips and FAQs
  • Performance Best Practices
  • Upgrade Guide
  • Comparison with Other Frameworks
  • License

Community

  • Slack Chat
  • Forums
Chainer
  • Docs »
  • API Reference »
  • Link and Chains »
  • chainer.Link

chainer.Link¶

class chainer.Link(**params)[source]¶

Building block of model definitions.

Link is a building block of neural network models that support various features like handling parameters, defining network fragments, serialization, etc.

Link is the primitive structure for the model definitions. It supports management of parameter variables and persistent values that should be incorporated to serialization.

Parameter is an instance of Parameter registered to a link. A Parameter object can be registered as a parameter of the link by assigning it to an attribute within an initialization scope, which is a code surrounded by a init_scope() context manager using the with statement.

Persistent values are arrays, scalars, or any other serializable values registered via register_persistent() or add_persistent().

Note

Whereas arbitrary serializable objects can be registered as persistent values, it is strongly recommended to just register values that should be treated as results of learning. A typical example of persistent values is ones computed during training and required for testing, e.g. running statistics for batch normalization.

Parameters and persistent values are referred by their names. They can be accessed as attributes of the links. Link class itself manages the lists of names of parameters and persistent values to distinguish parameters and persistent values from other attributes.

Link can be composed into more complex models. This composition feature is supported by child classes like Chain and ChainList. One can create a chain by combining one or more links. See the documents for these classes for details.

As noted above, Link supports the serialization protocol of the Serializer class. Note that only parameters and persistent values are saved and loaded. Other attributes are considered as a part of user program (i.e. a part of network definition). In order to construct a link from saved file, other attributes must be identically reconstructed by user codes.

Example

This is a simple example of custom link definition. Chainer itself also provides many links defined under the links module. They might serve as examples, too.

Consider we want to define a simple primitive link that implements a fully-connected layer based on the linear() function. Note that this function takes input units, a weight variable, and a bias variable as arguments. Then, the fully-connected layer can be defined as follows:

import chainer
import chainer.functions as F
from chainer import initializers
import numpy as np

class LinearLayer(chainer.Link):

    def __init__(self, n_in, n_out):
        super(LinearLayer, self).__init__()
        with self.init_scope():
            self.W = chainer.Parameter(
                initializers.Normal(), (n_out, n_in))
            self.b = chainer.Parameter(
                initializers.Zero(), (n_out,))

    def forward(self, x):
        return F.linear(x, self.W, self.b)

This example shows that a user can define arbitrary parameters and use them in any methods. Links typically implement the forward operator, although they can also provide other methods to implement the forward propagation.

Parameters

params – Names, shapes, and optional dtypes of initial parameters. The keywords are used as the parameter names and the corresponding values consist either of the shape or a tuple of shape and a dtype (shape, dtype). If only the shape is supplied, the default dtype will be used.

Variables

name (str) – Name of this link, given by the parent chain (if exists).

Methods

__call__(*args, **kwargs)[source]¶

Call self as a function.

add_hook(hook, name=None)[source]¶

Registers a link hook.

Parameters
  • hook (LinkHook) – Link hook to be registered.

  • name (str) – Name of the link hook. The name must be unique among link hooks registered to this link. If None, the default name of the link hook is used.

Returns

self

add_param(name, shape=None, dtype=<class 'numpy.float32'>, initializer=None)[source]¶

Registers a parameter to the link.

Parameters
  • name (str) – Name of the parameter. This name is also used as the attribute name.

  • shape (int or tuple of ints) – Shape of the parameter array. If it is omitted, the parameter variable is left uninitialized.

  • dtype – Data type of the parameter array.

  • initializer – If it is not None, the data is initialized with the given initializer. If it is an array, the data is directly initialized by it. If it is callable, it is used as a weight initializer. Note that in these cases, dtype argument is ignored.

add_persistent(name, value)[source]¶

Registers a persistent value to the link.

The registered value is saved and loaded on serialization and deserialization. The value is set to an attribute of the link.

Parameters
  • name (str) – Name of the persistent value. This name is also used for the attribute name.

  • value – Value to be registered.

addgrads(link)[source]¶

Accumulates gradient values from given link.

This method adds each gradient array of the given link to corresponding gradient array of this link. The accumulation is even done across host and different devices.

Parameters

link (Link) – Source link object.

children()[source]¶

Returns a generator of all child links.

Returns

A generator object that generates all child links.

cleargrads()[source]¶

Clears all gradient arrays.

This method should be called before the backward computation at every iteration of the optimization.

copy(mode='share')[source]¶

Copies the link hierarchy to new one.

The whole hierarchy rooted by this link is copied. There are three modes to perform copy. Please see the documentation for the argument mode below.

The name of the link is reset on the copy, since the copied instance does not belong to the original parent chain (even if exists).

Parameters

mode (str) – It should be either init, copy, or share. init means parameter variables under the returned link object is re-initialized by calling their initialize() method, so that all the parameters may have different initial values from the original link. copy means that the link object is deeply copied, so that its parameters are not re-initialized but are also deeply copied. Thus, all parameters have same initial values but can be changed independently. share means that the link is shallowly copied, so that its parameters’ arrays are shared with the original one. Thus, their values are changed synchronously. The default mode is share.

Returns

Copied link object.

Return type

Link

copyparams(link, copy_persistent=True)[source]¶

Copies all parameters from given link.

This method copies data arrays of all parameters in the hierarchy. The copy is even done across the host and devices. Note that this method does not copy the gradient arrays.

From v5.0.0: this method also copies the persistent values (e.g. the moving statistics of BatchNormalization). If the persistent value is an ndarray, the elements are copied. Otherwise, it is copied using copy.deepcopy(). The old behavior (not copying persistent values) can be reproduced with copy_persistent=False.

Parameters
  • link (Link) – Source link object.

  • copy_persistent (bool) – If True, persistent values are also copied. True by default.

count_params()[source]¶

Counts the total number of parameters.

This method counts the total number of scalar values included in all the Parameters held by this link and its descendants.

If the link containts uninitialized parameters, this method raises a warning.

Returns

The total size of parameters (int)

delete_hook(name)[source]¶

Unregisters the link hook.

Parameters

name (str) – The name of the link hook to be unregistered.

disable_update()[source]¶

Disables update rules of all parameters under the link hierarchy.

This method sets the enabled flag of the update rule of each parameter variable to False.

enable_update()[source]¶

Enables update rules of all parameters under the link hierarchy.

This method sets the enabled flag of the update rule of each parameter variable to True.

from_chainerx()[source]¶

Converts parameter variables and persistent values from ChainerX to NumPy/CuPy devices without any copy.

init_scope()[source]¶

Creates an initialization scope.

This method returns a context manager object that enables registration of parameters (and links for Chain) by an assignment. A Parameter object can be automatically registered by assigning it to an attribute under this context manager.

Example

In most cases, the parameter registration is done in the initializer method. Using the init_scope method, we can simply assign a Parameter object to register it to the link.

class MyLink(chainer.Link):
    def __init__(self):
        super().__init__()
        with self.init_scope():
            self.W = chainer.Parameter(0, (10, 5))
            self.b = chainer.Parameter(0, (5,))
links(skipself=False)[source]¶

Returns a generator of all links under the hierarchy.

Parameters

skipself (bool) – If True, then the generator skips this link and starts with the first child link.

Returns

A generator object that generates all links.

namedlinks(skipself=False)[source]¶

Returns a generator of all (path, link) pairs under the hierarchy.

Parameters

skipself (bool) – If True, then the generator skips this link and starts with the first child link.

Returns

A generator object that generates all (path, link) pairs.

namedparams(include_uninit=True)[source]¶

Returns a generator of all (path, param) pairs under the hierarchy.

Parameters

include_uninit (bool) – If True, it also generates uninitialized parameters.

Returns

A generator object that generates all (path, parameter) pairs. The paths are relative from this link.

params(include_uninit=True)[source]¶

Returns a generator of all parameters under the link hierarchy.

Parameters

include_uninit (bool) – If True, it also generates uninitialized parameters.

Returns

A generator object that generates all parameters.

register_persistent(name)[source]¶

Registers an attribute of a given name as a persistent value.

This is a convenient method to register an existing attribute as a persistent value. If name has been already registered as a parameter, this method removes it from the list of parameter names and re-registers it as a persistent value.

Parameters

name (str) – Name of the attribute to be registered.

repeat(n_repeat, mode='init')[source]¶

Repeats this link multiple times to make a Sequential.

This method returns a Sequential object which has the same Link multiple times repeatedly. The mode argument means how to copy this link to repeat.

Example

You can repeat the same link multiple times to create a longer Sequential block like this:

class ConvBNReLU(chainer.Chain):

    def __init__(self):
        super(ConvBNReLU, self).__init__()
        with self.init_scope():
            self.conv = L.Convolution2D(
                None, 64, 3, 1, 1, nobias=True)
            self.bn = L.BatchNormalization(64)

    def forward(self, x):
        return F.relu(self.bn(self.conv(x)))

net = ConvBNReLU().repeat(16, mode='init')

The net object contains 16 blocks, each of which is ConvBNReLU. And the mode was init, so each block is re-initialized with different parameters. If you give copy to this argument, each block has same values for its parameters but its object ID is different from others. If it is share, each block is same to others in terms of not only parameters but also the object IDs because they are shallow-copied, so that when the parameter of one block is changed, all the parameters in the others also change.

Parameters
  • n_repeat (int) – Number of times to repeat.

  • mode (str) – It should be either init, copy, or share. init means parameters of each repeated element in the returned Sequential will be re-initialized, so that all elements have different initial parameters. copy means that the parameters will not be re-initialized but object itself will be deep-copied, so that all elements have same initial parameters but can be changed independently. share means all the elements which consist the resulting Sequential object are same object because they are shallow-copied, so that all parameters of elements are shared with each other.

serialize(serializer)[source]¶

Serializes the link object.

Parameters

serializer (AbstractSerializer) – Serializer object.

to_chainerx()[source]¶

Converts parameter variables and persistent values to ChainerX without any copy.

This method does not handle non-registered attributes. If some of such attributes must be copied to ChainerX, the link implementation must override this method to do so.

Returns: self

to_cpu()[source]¶

Copies parameter variables and persistent values to CPU.

This method does not handle non-registered attributes. If some of such attributes must be copied to CPU, the link implementation must override Link.to_device() to do so.

Returns: self

to_device(device)[source]¶

Copies parameter variables and persistent values to the specified device.

This method does not handle non-registered attributes. If some of such attributes must be copied to the device, the link implementation must override this method to do so.

Parameters

device – Target device specifier. See get_device() for available values.

Returns: self

to_gpu(device=None)[source]¶

Copies parameter variables and persistent values to GPU.

This method does not handle non-registered attributes. If some of such attributes must be copied to GPU, the link implementation must override Link.to_device() to do so.

Parameters

device – Target device specifier. If omitted, the current device is used.

Returns: self

to_intel64()[source]¶

Copies parameter variables and persistent values to CPU.

zerograds()[source]¶

Initializes all gradient arrays by zero.

Deprecated since version v1.15: Use the more efficient cleargrads() instead.

Attributes

device¶
local_link_hooks¶

Ordered dictionary of registered link hooks.

Contrary to chainer.thread_local.link_hooks, which registers its elements to all functions, link hooks in this property are specific to this link.

update_enabled¶

True if at least one parameter has an update rule enabled.

within_init_scope¶

True if the current code is inside of an initialization scope.

See init_scope() for the details of the initialization scope.

xp¶

Array module for this link.

Depending on which of CPU/GPU this link is on, this property returns numpy or cupy.

Next Previous

© Copyright 2015, Preferred Networks, inc. and Preferred Infrastructure, inc.

Built with Sphinx using a theme provided by Read the Docs.