File: prepend_dim_test.py

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (51 lines) | stat: -rw-r--r-- 1,505 bytes parent folder | download | duplicates (2)
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
51




import numpy as np

from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
from caffe2.proto import caffe2_pb2


class TestPrependDim(TestCase):
    def _test_fwd_bwd(self):
        old_shape = (128, 2, 4)
        new_shape = (8, 16, 2, 4)
        X = np.random.rand(*old_shape).astype(np.float32)
        Y = np.random.rand(*new_shape).astype(np.float32)

        net = core.Net('net')

        net.GivenTensorFill([], 'X', shape=old_shape, values=X.flatten())
        net.GivenTensorFill([], 'Y', shape=new_shape, values=Y.flatten())

        net.PrependDim(['X'], ['X_out'], dim_size=8)
        net.DotProduct(['X_out', 'Y'], 'Z')
        net.AddGradientOperators(['Z'])

        workspace.RunNetOnce(net)

        X_out = workspace.FetchBlob('X_out')
        X_grad = workspace.FetchBlob('X_grad')
        Y_grad = workspace.FetchBlob('Y_grad')

        # Check the shape of the gradient
        np.testing.assert_array_equal(X_out.shape, Y.shape)
        np.testing.assert_array_equal(X_grad.shape, X.shape)
        np.testing.assert_array_equal(Y_grad.shape, Y.shape)

    def test_prepend_dim(self):
        devices = [core.DeviceOption(caffe2_pb2.CPU, 0)]
        if workspace.NumGpuDevices() > 0:
            devices.append(core.DeviceOption(workspace.GpuDeviceType, 0))

        for device_opt in devices:
            with core.DeviceScope(device_opt):
                self._test_fwd_bwd()


if __name__ == "__main__":
    import unittest
    unittest.main()