-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtf.jl
111 lines (93 loc) · 2.63 KB
/
tf.jl
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using Libtask
foo(x) = sin(cos(x))
bar(x) = foo(foo(x))
Libtask.is_primitive(::typeof(foo), args...) = false
@testset "tapedfunction" begin
# Test case 1: stack allocated objects are deep copied.
@testset "Instruction{typeof(__new__)}" begin
mutable struct S
i::Int
S(x, y) = new(x + y)
end
tf = Libtask.TapedFunction(S, 1, 2)
s1 = tf(1, 2)
@test s1.i == 3
newins = findall(x -> isa(x, Libtask.Instruction{typeof(Libtask.__new__)}), tf.tape)
@test length(newins) == 1
end
@testset "Compiled Tape" begin
function g(x, y)
if x>y
r= string(sin(x))
else
r= sin(x) * cos(y)
end
return r
end
tf = Libtask.TapedFunction(g, 1., 2.)
ctf = Libtask.compile(tf)
r = ctf(1., 2.)
@test typeof(r) === Float64
end
@testset "recurse into function" begin
# tf = Libtask.TapedFunction(bar, 5.0)
# count = 0
# tf(4.0; callback=() -> (count += 1))
# @test count == 9
function recurse(n::Int)
if n == 0
return 0
end
recurse(n-1)
produce(n)
end
Libtask.is_primitive(::typeof(recurse), args...) = false
ttask = TapedTask(recurse, 3)
@test consume(ttask) == 1
@test consume(ttask) == 2
@test consume(ttask) == 3
@test consume(ttask) === nothing
function recurse2(n::Int)
if n == 0
return 0
end
produce(n)
recurse2(n-1)
end
Libtask.is_primitive(::typeof(recurse2), args...) = false
ttask = TapedTask(recurse2, 3)
@test consume(ttask) == 3
@test consume(ttask) == 2
@test consume(ttask) == 1
@test consume(ttask) === nothing
end
@testset "Not optimize mutating call" begin
function f!(a)
a[1] = 2
return 1
end
function g1()
a = [1,2]
a[2] = f!(a)
produce(a[1])
end
ttask = TapedTask(g1)
@test consume(ttask) == 2
@test consume(ttask) === nothing
end
@testset "Not optimize producing call" begin
function f2()
produce(2)
return 1
end
function g2()
a = [1]
a[1] = f2()
produce(a[1])
end
ttask = TapedTask(g2)
@test consume(ttask) == 2
@test consume(ttask) == 1
@test consume(ttask) === nothing
end
end