Init a conv 2d operator
| 1636 | |
| 1637 | |
| 1638 | class _Conv2d(Operator): |
| 1639 | """ |
| 1640 | Init a conv 2d operator |
| 1641 | """ |
| 1642 | |
| 1643 | def __init__(self, handle, odd_padding=(0, 0, 0, 0)): |
| 1644 | """ |
| 1645 | Args: |
| 1646 | handle (object): ConvHandle for cpu or CudnnConvHandle for gpu |
| 1647 | odd_padding (tuple of four ints):, the odd paddding is the value |
| 1648 | that cannot be handled by the tuple padding (w, h) mode so |
| 1649 | we need to firstly handle the input, then use the nomal padding |
| 1650 | method. |
| 1651 | """ |
| 1652 | super(_Conv2d, self).__init__() |
| 1653 | self.handle = handle |
| 1654 | self.odd_padding = odd_padding |
| 1655 | |
| 1656 | def forward(self, x, W, b=None): |
| 1657 | """ |
| 1658 | Args: |
| 1659 | x (CTensor): input |
| 1660 | W (CTensor): weight |
| 1661 | b (CTensor): bias |
| 1662 | Returns: |
| 1663 | CTensor |
| 1664 | """ |
| 1665 | assert x.nDim() == 4, "The dimensions of input should be 4D." |
| 1666 | if self.odd_padding != (0, 0, 0, 0): |
| 1667 | x = utils.handle_odd_pad_fwd(x, self.odd_padding) |
| 1668 | |
| 1669 | if training: |
| 1670 | if self.handle.bias_term: |
| 1671 | self.inputs = (x, W, b) |
| 1672 | else: |
| 1673 | self.inputs = (x, W) |
| 1674 | |
| 1675 | if not self.handle.bias_term: |
| 1676 | # create empty bias tensor for Cpp API |
| 1677 | b = CTensor((self.handle.num_filters,), x.device()) |
| 1678 | b.SetFloatValue(0.0) |
| 1679 | |
| 1680 | if (type(self.handle) != singa.ConvHandle): |
| 1681 | return singa.GpuConvForward(x, W, b, self.handle) |
| 1682 | else: |
| 1683 | return singa.CpuConvForward(x, W, b, self.handle) |
| 1684 | |
| 1685 | def backward(self, dy): |
| 1686 | """ |
| 1687 | Args: |
| 1688 | dy (CTensor): dL / dy |
| 1689 | Returns: |
| 1690 | dx (CTensor): dL / dx |
| 1691 | """ |
| 1692 | assert training is True and hasattr( |
| 1693 | self, "inputs"), "Please set training as True before do BP. " |
| 1694 | |
| 1695 | if (type(self.handle) != singa.ConvHandle): |