MCPcopy Create free account
hub / github.com/PaddlePaddle/Paddle / register_buffer

Method register_buffer

python/paddle/nn/layer/layers.py:1609–1676  ·  view source on GitHub ↗

Registers a tensor as buffer into the layer. `buffer` is a non-trainable tensor and will not be updated by optimizer, but is necessary for evaluation and inference. For example, the mean and variance in BatchNorm layers. The registered buffer is persistable by defau

(
        self, name: str, tensor: Tensor, persistable: bool = True
    )

Source from the content-addressed store, hash-verified

1607
1608 @param_one_alias(["persistable", "persistent"])
1609 def register_buffer(
1610 self, name: str, tensor: Tensor, persistable: bool = True
1611 ) -> None:
1612 """
1613 Registers a tensor as buffer into the layer.
1614
1615 `buffer` is a non-trainable tensor and will not be updated by optimizer,
1616 but is necessary for evaluation and inference. For example, the mean and variance in BatchNorm layers.
1617 The registered buffer is persistable by default, and will be saved into
1618 `state_dict` alongside parameters. If set persistable=False, it registers
1619 a non-persistable buffer, so that it will not be a part of `state_dict` .
1620
1621 Buffers can be accessed as attributes using given names.
1622
1623 Parameters:
1624 name (string): name of the buffer. The buffer can be accessed
1625 from this layer using the given name
1626 tensor (Tensor): the tensor to be registered as buffer.
1627 persistable (bool): whether the buffer is part of this layer's
1628 state_dict.
1629
1630 Returns:
1631 None
1632
1633 Examples:
1634 .. code-block:: pycon
1635
1636 >>> import numpy as np
1637 >>> import paddle
1638
1639 >>> linear = paddle.nn.Linear(10, 3)
1640 >>> value = np.array([0]).astype("float32")
1641 >>> buffer = paddle.to_tensor(value)
1642 >>> linear.register_buffer("buf_name", buffer, persistable=True)
1643
1644 >>> # get the buffer by attribute.
1645 >>> print(linear.buf_name)
1646 Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
1647 [0.])
1648
1649 """
1650
1651 if '_buffers' not in self.__dict__:
1652 raise ValueError("super().__init__() should be called first")
1653 elif not isinstance(name, str):
1654 raise TypeError(
1655 f"The name of buffer should be a string, but received {type(name).__name__}."
1656 )
1657 elif '.' in name:
1658 raise KeyError(
1659 "The name of buffer can not contain `.`, "
1660 "because when you access the newly added buffer in the "
1661 "form of `self.**.**`, it will cause AttributeError."
1662 )
1663 elif name == '':
1664 raise KeyError("The name of buffer can not be empty.")
1665 elif hasattr(self, name) and name not in self._buffers:
1666 raise KeyError(f"attribute '{name}' already exists.")

Calls 6

ValueErrorClass · 0.85
TypeErrorClass · 0.85
KeyErrorClass · 0.85
typeFunction · 0.50
discardMethod · 0.45
addMethod · 0.45