예제 #1
0
    def test_create_plan_from_proto_correctly(self):
        from caffe2.python.net_builder import ops
        with Node('trainer'), Task(name='my_task', num_instances=2) as task:
            with ops.task_init():
                globl = ops.Const(0)
            with ops.task_instance_init():
                local = ops.Const(0)
            with ops.loop(100):
                ops.Copy(globl, local)
            with ops.task_instance_exit():
                ops.Add([globl, local], [globl])
            with ops.task_exit():
                ops.Mul([globl, globl], [globl])

        plan = core.Plan(task.get_step())
        test_plan = core.Plan.create_from_proto(plan.Proto())

        self.assertEqual(len(plan.Steps()), 1)
        self.assertEqual(len(test_plan.Steps()), 1)
        self.assertEqual(len(plan.Proto().network), 9)
        self.assertEqual(len(test_plan.Proto().network), 9)
        self.assertEqual(len(plan.Proto().execution_step), 1)
        self.assertEqual(len(test_plan.Proto().execution_step), 1)
        self.assertEqual(plan.Steps()[0].Name(), test_plan.Steps()[0].Name())
        self.assertEqual(len(plan.Nets()), len(test_plan.Nets()))
        for idx in range(0, len(plan.Nets())):
            # When we create Net for test_plan, we will end up with new Net
            # name with postfix.
            net_1 = plan.Nets()[idx]
            net_2 = test_plan.Nets()[idx]
            trim_size = len(net_1.Name())
            self.assertEqual(net_1.Name(), net_2.Name()[:trim_size])
예제 #2
0
def example_task():
    with Task():
        with ops.task_init():
            one = ops.Const(1)
        two = ops.Add([one, one])
        with ops.task_init():
            three = ops.Const(3)
        accum = ops.Add([two, three])
        # here, accum should be 5
        with ops.task_exit():
            # here, accum should be 6, since this executes after lines below
            seven_1 = ops.Add([accum, one])
        six = ops.Add([accum, one])
        ops.Add([accum, one], [accum])
        seven_2 = ops.Add([accum, one])
        o6 = final_output(six)
        o7_1 = final_output(seven_1)
        o7_2 = final_output(seven_2)

    with Task(num_instances=2):
        with ops.task_init():
            one = ops.Const(1)
        with ops.task_instance_init():
            local = ops.Const(2)
        ops.Add([one, local], [one])
        ops.LogInfo('ble')

    return o6, o7_1, o7_2
예제 #3
0
def _test_loop():
    x = ops.Const(5)
    y = ops.Const(0)
    with ops.loop():
        ops.stop_if(ops.EQ([x, ops.Const(0)]))
        ops.Add([x, ops.Const(-1)], [x])
        ops.Add([y, ops.Const(1)], [y])
    return y
예제 #4
0
 def test_multiple_definition(self):
     job = example_job()
     with job:
         with Task():
             ops.Add([ops.Const(0), ops.Const(1)], 'out1')
         with Task():
             ops.Add([ops.Const(2), ops.Const(3)], 'out1')
     with self.assertRaises(AssertionError):
         net_printer.analyze(job)
예제 #5
0
 def check_db_exists(self, epoch):
     logger.info('Check existence of %s' % self._db_name(epoch))
     with Task() as task:
         existence = ops.Const(False)
         ops.DBExists([], [existence],
                      db_name=self._db_name(epoch),
                      db_type=self._db_type,
                      absolute_path=True)
         task.add_output(existence)
     return task
예제 #6
0
 def test_net_multi_use(self):
     with Task() as task:
         total = ops.Const(0)
         net = Net('my_net')
         net.Add([total, net.Const(1)], [total])
         ops.net(net)
         ops.net(net)
         result = final_output(total)
     with LocalSession() as session:
         session.run(task)
         self.assertEquals(2, result.fetch())
예제 #7
0
    def test_while_net(self):
        with NetBuilder() as nb:
            x = ops.Const(0)
            y = ops.Const(0)
            with ops.WhileNet():
                with ops.Condition():
                    ops.Add([x, ops.Const(1)], [x])
                    ops.LT([x, ops.Const(7)])
                ops.Add([x, y], [y])

        plan = Plan('while_net_test')
        plan.AddStep(to_execution_step(nb))
        ws = workspace.C.Workspace()
        ws.run(plan)

        x_value = ws.blobs[str(x)].fetch()
        y_value = ws.blobs[str(y)].fetch()

        self.assertEqual(x_value, 7)
        self.assertEqual(y_value, 21)
예제 #8
0
def _test_outer():
    x = ops.Const(10)
    # test stop_if(False)
    with ops.stop_guard() as g1:
        _test_inner_stop(x)

    # test stop_if(True)
    y = ops.Const(3)
    with ops.stop_guard() as g2:
        _test_inner_stop(y)

    # test no stop
    with ops.stop_guard() as g4:
        ops.Const(0)

    # test empty clause
    with ops.stop_guard() as g3:
        pass

    return (g1.has_stopped(), g2.has_stopped(), g3.has_stopped(),
            g4.has_stopped())
예제 #9
0
 def test_ops(self):
     with NetBuilder() as nb:
         y = _test_loop()
         z, w, a, b = _test_outer()
         p = _test_if(ops.Const(75))
         q = _test_if(ops.Const(25))
     plan = Plan('name')
     plan.AddStep(to_execution_step(nb))
     ws = workspace.C.Workspace()
     ws.run(plan)
     expected = [
         (y, 5),
         (z, False),
         (w, True),
         (a, False),
         (b, False),
         (p, 2),
         (q, 3),
     ]
     for b, expected in expected:
         actual = ws.blobs[str(b)].fetch()
         self.assertEquals(actual, expected)
예제 #10
0
 def test_setup(self):
     with Task() as task:
         with ops.task_init():
             one = ops.Const(1)
         two = ops.Add([one, one])
         with ops.task_init():
             three = ops.Const(3)
         accum = ops.Add([two, three])
         # here, accum should be 5
         with ops.task_exit():
             # here, accum should be 6, since this executes after lines below
             seven_1 = ops.Add([accum, one])
         six = ops.Add([accum, one])
         ops.Add([accum, one], [accum])
         seven_2 = ops.Add([accum, one])
         o6 = final_output(six)
         o7_1 = final_output(seven_1)
         o7_2 = final_output(seven_2)
     with LocalSession() as session:
         session.run(task)
         self.assertEquals(o6.fetch(), 6)
         self.assertEquals(o7_1.fetch(), 7)
         self.assertEquals(o7_2.fetch(), 7)
예제 #11
0
def _test_if(x):
    y = ops.Const(1)
    with ops.If(ops.GT([x, ops.Const(50)])):
        ops.Const(2, blob_out=y)
    with ops.If(ops.LT([x, ops.Const(50)])):
        ops.Const(3, blob_out=y)
        ops.stop()
        ops.Const(4, blob_out=y)
    return y
예제 #12
0
def build_pipeline(node_id):
    with Node('trainer_%d' % node_id):
        with Job.current().init_group, Task():
            data_arr = Struct(('val', np.array(list(range(10)))))
            data = ConstRecord(ops, data_arr)
            ds = Dataset(data, name='dataset:%d' % node_id)
            full_reader = ds.reader(ops)
            total = ops.Const([100])

        def inc_total(rec):
            ops.Add([total, rec.val()], [total])

        epoch_reader = ReaderWithLimit(full_reader, num_iter=3)
        pipe(epoch_reader, processor=inc_total)
        Job.current().add_stop_signal(epoch_reader.data_finished())
    return [total]
예제 #13
0
def example_loop():
    with Task():
        total = ops.Const(0)
        total_large = ops.Const(0)
        total_small = ops.Const(0)
        total_tiny = ops.Const(0)
        with ops.loop(10) as loop:
            outer = ops.Mul([loop.iter(), ops.Const(10)])
            with ops.loop(loop.iter()) as inner:
                val = ops.Add([outer, inner.iter()])
                with ops.If(ops.GE([val, ops.Const(80)])) as c:
                    ops.Add([total_large, val], [total_large])
                with c.Elif(ops.GE([val, ops.Const(50)])) as c:
                    ops.Add([total_small, val], [total_small])
                with c.Else():
                    ops.Add([total_tiny, val], [total_tiny])
                ops.Add([total, val], total)
예제 #14
0
 def _actual_loop(self):
     total = ops.Const(0)
     total_large = ops.Const(0)
     total_small = ops.Const(0)
     total_tiny = ops.Const(0)
     with ops.loop(10) as loop:
         outer = ops.Mul([loop.iter(), ops.Const(10)])
         with ops.loop(loop.iter()) as inner:
             val = ops.Add([outer, inner.iter()])
             with ops.If(ops.GE([val, ops.Const(80)])) as c:
                 ops.Add([total_large, val], [total_large])
             with c.Elif(ops.GE([val, ops.Const(50)])) as c:
                 ops.Add([total_small, val], [total_small])
             with c.Else():
                 ops.Add([total_tiny, val], [total_tiny])
             ops.Add([total, val], total)
     return map(final_output, (total, total_large, total_small, total_tiny))
예제 #15
0
    def testWhile(self):
        with NetBuilder(_use_control_ops=True) as nb:
            ops.Copy(ops.Const(0), "i")
            ops.Copy(ops.Const(1), "one")
            ops.Copy(ops.Const(2), "two")
            ops.Copy(ops.Const(2.0), "x")
            ops.Copy(ops.Const(3.0), "y")
            ops.Copy(ops.Const(2.0), "z")
            # raises x to the power of 4 and y to the power of 2
            # and z to the power of 3
            with ops.WhileNet():
                with ops.Condition():
                    ops.Add(["i", "one"], "i")
                    ops.LE(["i", "two"])
                ops.Pow("x", "x", exponent=2.0)
                with ops.IfNet(ops.LT(["i", "two"])):
                    ops.Pow("y", "y", exponent=2.0)
                with ops.Else():
                    ops.Pow("z", "z", exponent=3.0)

            ops.Add(["x", "y"], "x_plus_y")
            ops.Add(["x_plus_y", "z"], "s")

        assert len(nb.get()) == 1, "Expected a single net produced"
        net = nb.get()[0]

        net.AddGradientOperators(["s"])
        workspace.RunNetOnce(net)
        # (x^4)' = 4x^3
        self.assertAlmostEqual(workspace.FetchBlob("x_grad"), 32)
        self.assertAlmostEqual(workspace.FetchBlob("x"), 16)
        # (y^2)' = 2y
        self.assertAlmostEqual(workspace.FetchBlob("y_grad"), 6)
        self.assertAlmostEqual(workspace.FetchBlob("y"), 9)
        # (z^3)' = 3z^2
        self.assertAlmostEqual(workspace.FetchBlob("z_grad"), 12)
        self.assertAlmostEqual(workspace.FetchBlob("z"), 8)
예제 #16
0
def _test_inner_stop(x):
    ops.stop_if(ops.LT([x, ops.Const(5)]))
예제 #17
0
    def test_if_net(self):
        with NetBuilder() as nb:
            x0 = ops.Const(0)
            x1 = ops.Const(1)
            x2 = ops.Const(2)
            y0 = ops.Const(0)
            y1 = ops.Const(1)
            y2 = ops.Const(2)

            # basic logic
            first_res = ops.Const(0)
            with ops.IfNet(ops.Const(True)):
                ops.Const(1, blob_out=first_res)
            with ops.Else():
                ops.Const(2, blob_out=first_res)

            second_res = ops.Const(0)
            with ops.IfNet(ops.Const(False)):
                ops.Const(1, blob_out=second_res)
            with ops.Else():
                ops.Const(2, blob_out=second_res)

            # nested and sequential ifs,
            # empty then/else,
            # passing outer blobs into branches,
            # writing into outer blobs, incl. into input blob
            # using local blobs
            with ops.IfNet(ops.LT([x0, x1])):
                local_blob = ops.Const(900)
                ops.Add([ops.Const(100), local_blob], [y0])

                gt = ops.GT([x1, x2])
                with ops.IfNet(gt):
                    # empty then
                    pass
                with ops.Else():
                    ops.Add([y1, local_blob], [local_blob])
                    ops.Add([ops.Const(100), y1], [y1])

                with ops.IfNet(ops.EQ([local_blob, ops.Const(901)])):
                    ops.Const(7, blob_out=y2)
                    ops.Add([y1, y2], [y2])
            with ops.Else():
                # empty else
                pass

        plan = Plan('if_net_test')
        plan.AddStep(to_execution_step(nb))
        ws = workspace.C.Workspace()
        ws.run(plan)

        first_res_value = ws.blobs[str(first_res)].fetch()
        second_res_value = ws.blobs[str(second_res)].fetch()
        y0_value = ws.blobs[str(y0)].fetch()
        y1_value = ws.blobs[str(y1)].fetch()
        y2_value = ws.blobs[str(y2)].fetch()

        self.assertEquals(first_res_value, 1)
        self.assertEquals(second_res_value, 2)
        self.assertEquals(y0_value, 1000)
        self.assertEquals(y1_value, 101)
        self.assertEquals(y2_value, 108)
        self.assertTrue(str(local_blob) not in ws.blobs)
예제 #18
0
# ### Conditional Execution

# Let's start with conditional operator. We will demostrate how to use it in two Caffe2 APIs used for building nets: NetBuilder and Brew.

# In the first example, we first define several blobs and then use 'If' operator to set value of one of them conditionally depending on values of other blobs.

# In[1]:

from caffe2.python import workspace
from caffe2.python.core import Plan, to_execution_step, Net
from caffe2.python.net_builder import ops, NetBuilder

# In[2]:

with NetBuilder() as nb:
    ops.Const(0.0, blob_out="zero")
    ops.Const(1.0, blob_out="one")
    ops.Const(0.5, blob_out="x")
    ops.Const(0.0, blob_out="y")
    with ops.IfNet(ops.GT(["x", "zero"])):
        ops.Copy("one", "y")
    with ops.Else():
        ops.Copy("zero", "y")

# Note the usage of NetBuilder's ops.IfNet and ops.Else calls: ops.IfNet accepts a blob reference or blob name as an input, it expects an input blob to have a scalar value convertible to bool, also note that optional ops.Else is at the same level as ops.IfNet and immediately follows corresponding ops.IfNet. Let's execute resulting net (execution step) and check values of blobs.

# In[3]:

plan = Plan('if_net_test')
plan.AddStep(to_execution_step(nb))
ws = workspace.C.Workspace()