|
| 1 | +using Enzyme |
| 2 | +using Test |
| 3 | + |
| 4 | +const FREE_LIST = Vector{Any}() |
| 5 | + |
| 6 | +mutable struct Container |
| 7 | + value::Float64 |
| 8 | + function Container(v::Float64) |
| 9 | + c = new(v) |
| 10 | + finalizer(c) do c |
| 11 | + # Necromance object |
| 12 | + push!(FREE_LIST, c) |
| 13 | + end |
| 14 | + return c |
| 15 | + end |
| 16 | +end |
| 17 | + |
| 18 | +@noinline function compute(c) |
| 19 | + return c.value^2 |
| 20 | +end |
| 21 | + |
| 22 | +function compute(x::Float64) |
| 23 | + c = Container(x) |
| 24 | + return compute(c) |
| 25 | +end |
| 26 | + |
| 27 | +@testset "primal" begin |
| 28 | + x = compute(1.0) |
| 29 | + @test x == 1.0 |
| 30 | + GC.gc() |
| 31 | + @test length(FREE_LIST) == 1 |
| 32 | + empty!(FREE_LIST) |
| 33 | +end |
| 34 | + |
| 35 | +@testset "forward" begin |
| 36 | + dx, x = autodiff(ForwardWithPrimal, compute, Duplicated(1.0, 2.0)) |
| 37 | + @test x == 1.0 |
| 38 | + @test dx == 4.0 |
| 39 | + GC.gc() |
| 40 | + @test length(FREE_LIST) == 2 |
| 41 | + empty!(FREE_LIST) |
| 42 | + |
| 43 | + dx, = autodiff(Forward, compute, Duplicated(1.0, 2.0)) |
| 44 | + @test dx == 4.0 |
| 45 | + GC.gc() |
| 46 | + @test length(FREE_LIST) == 2 |
| 47 | + empty!(FREE_LIST) |
| 48 | +end |
| 49 | + |
| 50 | +@testset "batched forward" begin |
| 51 | + dx, x = autodiff(ForwardWithPrimal, compute, BatchDuplicated(1.0, (1.0, 2.0))) |
| 52 | + @test x == 1.0 |
| 53 | + @test dx[1] == 2.0 |
| 54 | + @test dx[2] == 4.0 |
| 55 | + GC.gc() |
| 56 | + @test length(FREE_LIST) == 3 |
| 57 | + empty!(FREE_LIST) |
| 58 | + |
| 59 | + dx, = autodiff(Forward, compute, BatchDuplicated(1.0, (1.0, 2.0))) |
| 60 | + @test dx[1] == 2.0 |
| 61 | + @test dx[2] == 4.0 |
| 62 | + GC.gc() |
| 63 | + @test length(FREE_LIST) == 3 |
| 64 | + empty!(FREE_LIST) |
| 65 | +end |
| 66 | + |
| 67 | +@testset "reverse" begin |
| 68 | + ((dx,), x) = autodiff(ReverseWithPrimal, compute, Active(1.0)) |
| 69 | + @test x == 1.0 |
| 70 | + @test dx == 2.0 |
| 71 | + GC.gc() |
| 72 | + @test length(FREE_LIST) == 2 |
| 73 | + empty!(FREE_LIST) |
| 74 | + |
| 75 | + ((dx,),) = autodiff(Reverse, compute, Active(1.0)) |
| 76 | + @test dx == 2.0 |
| 77 | + GC.gc() |
| 78 | + @test length(FREE_LIST) == 2 |
| 79 | + empty!(FREE_LIST) |
| 80 | +end |
0 commit comments