@@ -42,10 +42,16 @@ using FiniteDifferences: FiniteDifferences
4242using Zygote: Zygote
4343using Flux: Flux
4444
45+ # Mooncake.jl requires Julia >= 1.12
46+ const TEST_MOONCAKE = VERSION >= v " 1.12"
47+ if TEST_MOONCAKE
48+ import Mooncake
49+ end
50+
4551# from this module
4652export D_IN, D_OUT, GRAPH_TYPES, TEST_GRAPHS,
4753 test_gradients, finitediff_withgradient,
48- check_equal_leaves, gpu_backend
54+ check_equal_leaves, gpu_backend, TEST_MOONCAKE
4955
5056
5157const D_IN = 3
@@ -81,12 +87,13 @@ function test_gradients(
8187 test_grad_f = true ,
8288 test_grad_x = true ,
8389 compare_finite_diff = true ,
90+ test_mooncake = false ,
8491 loss = (f, g, xs... ) -> mean (f (g, xs... )),
8592 )
8693
87- if ! test_gpu && ! compare_finite_diff
88- error (" You should either compare finite diff vs CPU AD \
89- or CPU AD vs GPU AD." )
94+ if ! test_gpu && ! compare_finite_diff && ! test_mooncake
95+ error (" You should either compare finite diff vs CPU AD, \
96+ CPU AD vs GPU AD, or test Mooncake AD." )
9097 end
9198
9299 # # Let's make sure first that the forward pass works.
@@ -115,6 +122,14 @@ function test_gradients(
115122 check_equal_leaves (g, g_fd; rtol, atol)
116123 end
117124
125+ if test_mooncake && ! (graph. graph isa AbstractSparseMatrix) # Mooncake friendly tangents currently error on sparse graph internals
126+ # Mooncake gradient with respect to input via Flux integration, compared against Zygote.
127+ loss_mc_x = (xs... ) -> loss (f, graph, xs... )
128+ y_mc, g_mc = Flux. withgradient (loss_mc_x, Flux. AutoMooncake (), xs... )
129+ @assert isapprox (y, y_mc; rtol, atol)
130+ check_equal_leaves (g, g_mc; rtol, atol)
131+ end
132+
118133 if test_gpu
119134 # Zygote gradient with respect to input on GPU.
120135 y_gpu, g_gpu = Zygote. withgradient ((xs... ) -> loss (f_gpu, graph_gpu, xs... ), xs_gpu... )
@@ -138,6 +153,13 @@ function test_gradients(
138153 check_equal_leaves (g, g_fd; rtol, atol)
139154 end
140155
156+ if test_mooncake && ! (graph. graph isa AbstractSparseMatrix) # Mooncake friendly tangents currently error on sparse graph internals
157+ # Mooncake gradient with respect to f via Flux integration, compared against Zygote.
158+ y_mc, g_mc = Flux. withgradient (f -> loss (f, graph, xs... ), Flux. AutoMooncake (), f)
159+ @assert isapprox (y, y_mc; rtol, atol)
160+ check_equal_leaves (g, g_mc; rtol, atol)
161+ end
162+
141163 if test_gpu
142164 # Zygote gradient with respect to f on GPU.
143165 y_gpu, g_gpu = Zygote. withgradient (f -> loss (f,graph_gpu, xs_gpu... ), f_gpu)
0 commit comments