def test_conditional(): with pf.Graph() as graph: x = pf.constant(4) y = pf.placeholder(name='y') condition = pf.placeholder(name='condition') z = pf.conditional(condition, x, y) assert graph(z, condition=True) == 4 assert graph(z, condition=False, y=5) == 5 # We expect a value error if we evaluate the other branch without a placeholder with pytest.raises(ValueError): graph(z, condition=False)
def test_conditional_with_length(): def f(a): return a, a with pf.Graph() as graph: x = pf.constant(4) y = pf.placeholder(name='y') condition = pf.placeholder(name='condition') z1, z2 = pf.conditional(condition, pf.func_op(f, x), pf.func_op(f, y), length=2) assert graph([z1, z2], condition=True) == (4, 4) assert graph([z1, z2], condition=False, y=5) == (5, 5)
def test_conditional_callback(): with pf.Graph() as graph: a = pf.constant(1) b = pf.constant(2) c = pf.placeholder() d = pf.conditional(c, a, b + 1) # Check that we have "traced" the correct number of operation evaluations tracer = pf.Profiler() assert graph(d, {c: True}, callback=tracer) == 1 assert len(tracer.times) == 2 tracer = pf.Profiler() assert graph(d, {c: False}, callback=tracer) == 3 assert len(tracer.times) == 3
def test_profiling(): with pf.Graph() as graph: duration = pf.placeholder('duration') # Use a conditional to make sure we also test the evaluation of conditionals with callbacks positive_duration = pf.conditional(duration < 0, 0, duration) sleep = pf.import_('time').sleep(positive_duration) callback = pf.Profiler() graph(sleep, callback=callback, duration=0.5) assert callback.times[sleep] > 0.5 # We never evaluate duration because it is already provided in the context assert duration not in callback.times # Check that the slowest operation comes first callback_str = str(callback) assert callback_str.startswith(str(sleep)) assert len(callback_str.split('\n')) == 5