Optimizing DiffEq Code

Chris Rackauckas

In this notebook we will walk through some of the main tools for optimizing your code in order to efficiently solve DifferentialEquations.jl. User-side optimizations are important because, for sufficiently difficult problems, most of the time will be spent inside of your f function, the function you are trying to solve. "Efficient" integrators are those that reduce the required number of f calls to hit the error tolerance. The main ideas for optimizing your DiffEq code, or any Julia function, are the following:

  • Make it non-allocating

  • Use StaticArrays for small arrays

  • Use broadcast fusion

  • Make it type-stable

  • Reduce redundant calculations

  • Make use of BLAS calls

  • Optimize algorithm choice

We'll discuss these strategies in the context of small and large systems. Let's start with small systems.

Optimizing Small Systems (<100 DEs)

Let's take the classic Lorenz system from before. Let's start by naively writing the system in its out-of-place form:

function lorenz(u,p,t)
 dx = 10.0*(u[2]-u[1])
 dy = u[1]*(28.0-u[3]) - u[2]
 dz = u[1]*u[2] - (8/3)*u[3]
 [dx,dy,dz]
end
lorenz (generic function with 1 method)

Here, lorenz returns an object, [dx,dy,dz], which is created within the body of lorenz.

This is a common code pattern from high-level languages like MATLAB, SciPy, or R's deSolve. However, the issue with this form is that it allocates a vector, [dx,dy,dz], at each step. Let's benchmark the solution process with this choice of function:

using DifferentialEquations, BenchmarkTools
u0 = [1.0;0.0;0.0]
tspan = (0.0,100.0)
prob = ODEProblem(lorenz,u0,tspan)
@benchmark solve(prob,Tsit5())
BenchmarkTools.Trial: 
  memory estimate:  10.83 MiB
  allocs estimate:  101447
  --------------
  minimum time:     3.490 ms (0.00% GC)
  median time:      7.874 ms (0.00% GC)
  mean time:        8.214 ms (20.31% GC)
  maximum time:     45.420 ms (81.62% GC)
  --------------
  samples:          608
  evals/sample:     1

The BenchmarkTools package's @benchmark runs the code multiple times to get an accurate measurement. The minimum time is the time it takes when your OS and other background processes aren't getting in the way. Notice that in this case it takes about 5ms to solve and allocates around 11.11 MiB. However, if we were to use this inside of a real user code we'd see a lot of time spent doing garbage collection (GC) to clean up all of the arrays we made. Even if we turn off saving we have these allocations.

@benchmark solve(prob,Tsit5(),save_everystep=false)
BenchmarkTools.Trial: 
  memory estimate:  9.47 MiB
  allocs estimate:  88665
  --------------
  minimum time:     3.021 ms (0.00% GC)
  median time:      6.996 ms (0.00% GC)
  mean time:        7.380 ms (20.47% GC)
  maximum time:     46.410 ms (88.00% GC)
  --------------
  samples:          681
  evals/sample:     1

The problem of course is that arrays are created every time our derivative function is called. This function is called multiple times per step and is thus the main source of memory usage. To fix this, we can use the in-place form to ***make our code non-allocating***:

function lorenz!(du,u,p,t)
 du[1] = 10.0*(u[2]-u[1])
 du[2] = u[1]*(28.0-u[3]) - u[2]
 du[3] = u[1]*u[2] - (8/3)*u[3]
end
lorenz! (generic function with 1 method)

Here, instead of creating an array each time, we utilized the cache array du. When the inplace form is used, DifferentialEquations.jl takes a different internal route that minimizes the internal allocations as well. When we benchmark this function, we will see quite a difference.

u0 = [1.0;0.0;0.0]
tspan = (0.0,100.0)
prob = ODEProblem(lorenz!,u0,tspan)
@benchmark solve(prob,Tsit5())
BenchmarkTools.Trial: 
  memory estimate:  1.38 MiB
  allocs estimate:  13009
  --------------
  minimum time:     717.801 μs (0.00% GC)
  median time:      1.254 ms (0.00% GC)
  mean time:        1.352 ms (15.08% GC)
  maximum time:     36.320 ms (96.24% GC)
  --------------
  samples:          3691
  evals/sample:     1
@benchmark solve(prob,Tsit5(),save_everystep=false)
BenchmarkTools.Trial: 
  memory estimate:  6.28 KiB
  allocs estimate:  67
  --------------
  minimum time:     312.099 μs (0.00% GC)
  median time:      371.600 μs (0.00% GC)
  mean time:        366.242 μs (0.00% GC)
  maximum time:     936.400 μs (0.00% GC)
  --------------
  samples:          10000
  evals/sample:     1

There is a 4x time difference just from that change! Notice there are still some allocations and this is due to the construction of the integration cache. But this doesn't scale with the problem size:

tspan = (0.0,500.0) # 5x longer than before
prob = ODEProblem(lorenz!,u0,tspan)
@benchmark solve(prob,Tsit5(),save_everystep=false)
BenchmarkTools.Trial: 
  memory estimate:  6.28 KiB
  allocs estimate:  67
  --------------
  minimum time:     1.557 ms (0.00% GC)
  median time:      1.844 ms (0.00% GC)
  mean time:        1.815 ms (0.00% GC)
  maximum time:     4.056 ms (0.00% GC)
  --------------
  samples:          2752
  evals/sample:     1

since that's all just setup allocations.

But if the system is small we can optimize even more.

Allocations are only expensive if they are "heap allocations". For a more in-depth definition of heap allocations, there are a lot of sources online. But a good working definition is that heap allocations are variable-sized slabs of memory which have to be pointed to, and this pointer indirection costs time. Additionally, the heap has to be managed and the garbage controllers has to actively keep track of what's on the heap.

However, there's an alternative to heap allocations, known as stack allocations. The stack is statically-sized (known at compile time) and thus its accesses are quick. Additionally, the exact block of memory is known in advance by the compiler, and thus re-using the memory is cheap. This means that allocating on the stack has essentially no cost!

Arrays have to be heap allocated because their size (and thus the amount of memory they take up) is determined at runtime. But there are structures in Julia which are stack-allocated. structs for example are stack-allocated "value-type"s. Tuples are a stack-allocated collection. The most useful data structure for DiffEq though is the StaticArray from the package StaticArrays.jl. These arrays have their length determined at compile-time. They are created using macros attached to normal array expressions, for example:

using StaticArrays
A = @SVector [2.0,3.0,5.0]
3-element StaticArrays.SArray{Tuple{3},Float64,1,3} with indices SOneTo(3):
 2.0
 3.0
 5.0

Notice that the 3 after SVector gives the size of the SVector. It cannot be changed. Additionally, SVectors are immutable, so we have to create a new SVector to change values. But remember, we don't have to worry about allocations because this data structure is stack-allocated. SArrays have a lot of extra optimizations as well: they have fast matrix multiplication, fast QR factorizations, etc. which directly make use of the information about the size of the array. Thus, when possible they should be used.

Unfortunately static arrays can only be used for sufficiently small arrays. After a certain size, they are forced to heap allocate after some instructions and their compile time balloons. Thus static arrays shouldn't be used if your system has more than 100 variables. Additionally, only the native Julia algorithms can fully utilize static arrays.

Let's ***optimize lorenz using static arrays***. Note that in this case, we want to use the out-of-place allocating form, but this time we want to output a static array:

function lorenz_static(u,p,t)
 dx = 10.0*(u[2]-u[1])
 dy = u[1]*(28.0-u[3]) - u[2]
 dz = u[1]*u[2] - (8/3)*u[3]
 @SVector [dx,dy,dz]
end
lorenz_static (generic function with 1 method)

To make the solver internally use static arrays, we simply give it a static array as the initial condition:

u0 = @SVector [1.0,0.0,0.0]
tspan = (0.0,100.0)
prob = ODEProblem(lorenz_static,u0,tspan)
@benchmark solve(prob,Tsit5())
BenchmarkTools.Trial: 
  memory estimate:  467.31 KiB
  allocs estimate:  2608
  --------------
  minimum time:     303.001 μs (0.00% GC)
  median time:      469.950 μs (0.00% GC)
  mean time:        501.543 μs (11.23% GC)
  maximum time:     30.844 ms (98.49% GC)
  --------------
  samples:          9924
  evals/sample:     1
@benchmark solve(prob,Tsit5(),save_everystep=false)
BenchmarkTools.Trial: 
  memory estimate:  4.36 KiB
  allocs estimate:  41
  --------------
  minimum time:     205.499 μs (0.00% GC)
  median time:      221.201 μs (0.00% GC)
  mean time:        226.097 μs (0.00% GC)
  maximum time:     477.000 μs (0.00% GC)
  --------------
  samples:          10000
  evals/sample:     1

And that's pretty much all there is to it. With static arrays you don't have to worry about allocating, so use operations like * and don't worry about fusing operations (discussed in the next section). Do "the vectorized code" of R/MATLAB/Python and your code in this case will be fast, or directly use the numbers/values.

Exercise 1

Implement the out-of-place array, in-place array, and out-of-place static array forms for the Henon-Heiles System and time the results.

Optimizing Large Systems

Interlude: Managing Allocations with Broadcast Fusion

When your system is sufficiently large, or you have to make use of a non-native Julia algorithm, you have to make use of Arrays. In order to use arrays in the most efficient manner, you need to be careful about temporary allocations. Vectorized calculations naturally have plenty of temporary array allocations. This is because a vectorized calculation outputs a vector. Thus:

A = rand(1000,1000); B = rand(1000,1000); C = rand(1000,1000)
test(A,B,C) = A + B + C
@benchmark test(A,B,C)
BenchmarkTools.Trial: 
  memory estimate:  7.63 MiB
  allocs estimate:  2
  --------------
  minimum time:     3.561 ms (0.00% GC)
  median time:      4.168 ms (0.00% GC)
  mean time:        5.047 ms (17.50% GC)
  maximum time:     35.999 ms (87.74% GC)
  --------------
  samples:          989
  evals/sample:     1

That expression A + B + C creates 2 arrays. It first creates one for the output of A + B, then uses that result array to + C to get the final result. 2 arrays! We don't want that! The first thing to do to fix this is to use broadcast fusion. Broadcast fusion puts expressions together. For example, instead of doing the + operations separately, if we were to add them all at the same time, then we would only have a single array that's created. For example:

test2(A,B,C) = map((a,b,c)->a+b+c,A,B,C)
@benchmark test2(A,B,C)
BenchmarkTools.Trial: 
  memory estimate:  7.63 MiB
  allocs estimate:  5
  --------------
  minimum time:     4.399 ms (0.00% GC)
  median time:      5.127 ms (0.00% GC)
  mean time:        5.942 ms (14.29% GC)
  maximum time:     34.669 ms (84.21% GC)
  --------------
  samples:          840
  evals/sample:     1

Puts the whole expression into a single function call, and thus only one array is required to store output. This is the same as writing the loop:

function test3(A,B,C)
    D = similar(A)
    @inbounds for i in eachindex(A)
        D[i] = A[i] + B[i] + C[i]
    end
    D
end
@benchmark test3(A,B,C)
BenchmarkTools.Trial: 
  memory estimate:  7.63 MiB
  allocs estimate:  2
  --------------
  minimum time:     3.587 ms (0.00% GC)
  median time:      4.144 ms (0.00% GC)
  mean time:        5.035 ms (17.50% GC)
  maximum time:     37.301 ms (87.82% GC)
  --------------
  samples:          991
  evals/sample:     1

However, Julia's broadcast is syntactic sugar for this. If multiple expressions have a ., then it will put those vectorized operations together. Thus:

test4(A,B,C) = A .+ B .+ C
@benchmark test4(A,B,C)
BenchmarkTools.Trial: 
  memory estimate:  7.63 MiB
  allocs estimate:  2
  --------------
  minimum time:     3.626 ms (0.00% GC)
  median time:      4.207 ms (0.00% GC)
  mean time:        5.081 ms (17.30% GC)
  maximum time:     34.847 ms (87.34% GC)
  --------------
  samples:          988
  evals/sample:     1

is a version with only 1 array created (the output). Note that .s can be used with function calls as well:

sin.(A) .+ sin.(B)
1000×1000 Array{Float64,2}:
 1.23074   0.770735  1.40398   1.20566   …  1.19531   0.507854  0.649256
 0.280529  0.875496  0.801137  1.44204      0.480046  0.816581  0.415801
 0.669258  0.596906  1.01409   1.40303      1.05212   0.86394   0.623618
 1.11451   0.686278  0.308361  0.534904     0.916103  1.11719   0.406924
 0.950551  0.628722  1.13269   0.915757     0.899245  0.377555  1.44704 
 0.843156  0.34465   0.46859   0.546089  …  1.45271   1.04233   0.867582
 0.460862  0.758125  0.601958  1.5598       0.537673  0.80698   0.138396
 0.993976  0.90449   0.972553  0.51289      1.14063   0.51861   1.60609 
 0.736641  0.693553  0.983337  1.49108      1.3348    0.888186  0.109057
 0.464628  0.538744  1.07186   1.18152      1.04414   0.615261  0.488774
 ⋮                                       ⋱                              
 1.13972   0.537876  0.815131  0.583471     1.1459    1.57634   0.585572
 0.955525  1.23423   0.470441  0.764784     1.27764   1.54545   0.999992
 1.35584   0.826459  1.33828   0.513222     0.614164  0.783288  1.21039 
 1.48426   0.922197  1.15361   0.489693     0.902448  0.889153  1.30189 
 0.189634  0.709967  0.816463  0.888767  …  0.62633   1.29931   1.48634 
 0.343573  0.749291  0.465562  1.2515       1.50666   1.16117   0.77892 
 0.731632  0.741903  1.42065   0.316267     0.962526  0.748503  1.12686 
 1.0874    0.644417  1.05551   1.48595      0.218991  0.71031   0.927539
 1.52412   0.660437  1.18888   1.56623      1.44941   1.46365   1.38034

Also, the @. macro applys a dot to every operator:

test5(A,B,C) = @. A + B + C #only one array allocated
@benchmark test5(A,B,C)
BenchmarkTools.Trial: 
  memory estimate:  7.63 MiB
  allocs estimate:  2
  --------------
  minimum time:     3.586 ms (0.00% GC)
  median time:      4.185 ms (0.00% GC)
  mean time:        5.071 ms (17.39% GC)
  maximum time:     34.170 ms (87.13% GC)
  --------------
  samples:          988
  evals/sample:     1

Using these tools we can get rid of our intermediate array allocations for many vectorized function calls. But we are still allocating the output array. To get rid of that allocation, we can instead use mutation. Mutating broadcast is done via .=. For example, if we pre-allocate the output:

D = zeros(1000,1000);

Then we can keep re-using this cache for subsequent calculations. The mutating broadcasting form is:

test6!(D,A,B,C) = D .= A .+ B .+ C #only one array allocated
@benchmark test6!(D,A,B,C)
BenchmarkTools.Trial: 
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     1.529 ms (0.00% GC)
  median time:      1.643 ms (0.00% GC)
  mean time:        1.662 ms (0.00% GC)
  maximum time:     2.267 ms (0.00% GC)
  --------------
  samples:          2989
  evals/sample:     1

If we use @. before the =, then it will turn it into .=:

test7!(D,A,B,C) = @. D = A + B + C #only one array allocated
@benchmark test7!(D,A,B,C)
BenchmarkTools.Trial: 
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     1.548 ms (0.00% GC)
  median time:      1.651 ms (0.00% GC)
  mean time:        1.670 ms (0.00% GC)
  maximum time:     2.873 ms (0.00% GC)
  --------------
  samples:          2974
  evals/sample:     1

Notice that in this case, there is no "output", and instead the values inside of D are what are changed (like with the DiffEq inplace function). Many Julia functions have a mutating form which is denoted with a !. For example, the mutating form of the map is map!:

test8!(D,A,B,C) = map!((a,b,c)->a+b+c,D,A,B,C)
@benchmark test8!(D,A,B,C)
BenchmarkTools.Trial: 
  memory estimate:  32 bytes
  allocs estimate:  1
  --------------
  minimum time:     2.647 ms (0.00% GC)
  median time:      2.811 ms (0.00% GC)
  mean time:        2.868 ms (0.00% GC)
  maximum time:     4.274 ms (0.00% GC)
  --------------
  samples:          1738
  evals/sample:     1

Some operations require using an alternate mutating form in order to be fast. For example, matrix multiplication via * allocates a temporary:

@benchmark A*B
BenchmarkTools.Trial: 
  memory estimate:  7.63 MiB
  allocs estimate:  2
  --------------
  minimum time:     17.174 ms (0.00% GC)
  median time:      27.314 ms (0.00% GC)
  mean time:        27.871 ms (4.42% GC)
  maximum time:     79.480 ms (58.51% GC)
  --------------
  samples:          180
  evals/sample:     1

Instead, we can use the mutating form mul! into a cache array to avoid allocating the output:

using LinearAlgebra
@benchmark mul!(D,A,B) # same as D = A * B
BenchmarkTools.Trial: 
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     14.611 ms (0.00% GC)
  median time:      24.874 ms (0.00% GC)
  mean time:        24.727 ms (0.00% GC)
  maximum time:     34.506 ms (0.00% GC)
  --------------
  samples:          202
  evals/sample:     1

For repeated calculations this reduced allocation can stop GC cycles and thus lead to more efficient code. Additionally, ***we can fuse together higher level linear algebra operations using BLAS***. The package SugarBLAS.jl makes it easy to write higher level operations like alpha*B*A + beta*C as mutating BLAS calls.

Example Optimization: Gierer-Meinhardt Reaction-Diffusion PDE Discretization

Let's optimize the solution of a Reaction-Diffusion PDE's discretization. In its discretized form, this is the ODE:

\[ \begin{align} du &= D_1 (A_y u + u A_x) + \frac{au^2}{v} + \bar{u} - \alpha u\\ dv &= D_2 (A_y v + v A_x) + a u^2 + \beta v \end{align} \]

where $u$, $v$, and $A$ are matrices. Here, we will use the simplified version where $A$ is the tridiagonal stencil $[1,-2,1]$, i.e. it's the 2D discretization of the LaPlacian. The native code would be something along the lines of:

# Generate the constants
p = (1.0,1.0,1.0,10.0,0.001,100.0) # a,α,ubar,β,D1,D2
N = 100
Ax = Array(Tridiagonal([1.0 for i in 1:N-1],[-2.0 for i in 1:N],[1.0 for i in 1:N-1]))
Ay = copy(Ax)
Ax[2,1] = 2.0
Ax[end-1,end] = 2.0
Ay[1,2] = 2.0
Ay[end,end-1] = 2.0

function basic_version!(dr,r,p,t)
  a,α,ubar,β,D1,D2 = p
  u = r[:,:,1]
  v = r[:,:,2]
  Du = D1*(Ay*u + u*Ax)
  Dv = D2*(Ay*v + v*Ax)
  dr[:,:,1] = Du .+ a.*u.*u./v .+ ubar .- α*u
  dr[:,:,2] = Dv .+ a.*u.*u .- β*v
end

a,α,ubar,β,D1,D2 = p
uss = (ubar+β)/α
vss = (a/β)*uss^2
r0 = zeros(100,100,2)
r0[:,:,1] .= uss.+0.1.*rand.()
r0[:,:,2] .= vss

prob = ODEProblem(basic_version!,r0,(0.0,0.1),p)
ODEProblem with uType Array{Float64,3} and tType Float64. In-place: true
timespan: (0.0, 0.1)
u0: [11.029484026399125 11.047006717653689 … 11.069435478435803 11.03062442
559491; 11.052810875660354 11.076952301895952 … 11.03226969440141 11.097021
636160882; … ; 11.06163270731687 11.030559494455526 … 11.05839608081399 11.
088064535673093; 11.021322005847871 11.099268986892948 … 11.099497582412962
 11.00293580103967]

[12.100000000000001 12.100000000000001 … 12.100000000000001 12.100000000000
001; 12.100000000000001 12.100000000000001 … 12.100000000000001 12.10000000
0000001; … ; 12.100000000000001 12.100000000000001 … 12.100000000000001 12.
100000000000001; 12.100000000000001 12.100000000000001 … 12.100000000000001
 12.100000000000001]

In this version we have encoded our initial condition to be a 3-dimensional array, with u[:,:,1] being the A part and u[:,:,2] being the B part.

@benchmark solve(prob,Tsit5())
BenchmarkTools.Trial: 
  memory estimate:  186.88 MiB
  allocs estimate:  8564
  --------------
  minimum time:     88.280 ms (0.00% GC)
  median time:      134.482 ms (18.65% GC)
  mean time:        132.932 ms (14.47% GC)
  maximum time:     213.343 ms (22.50% GC)
  --------------
  samples:          38
  evals/sample:     1

While this version isn't very efficient,

We recommend writing the "high-level" code first, and iteratively optimizing it!

The first thing that we can do is get rid of the slicing allocations. The operation r[:,:,1] creates a temporary array instead of a "view", i.e. a pointer to the already existing memory. To make it a view, add @view. Note that we have to be careful with views because they point to the same memory, and thus changing a view changes the original values:

A = rand(4)
@show A
A = [0.42646245106083813, 0.8867534678805218, 0.11984596318454832, 0.807239
7186313645]
B = @view A[1:3]
B[2] = 2
@show A
A = [0.42646245106083813, 2.0, 0.11984596318454832, 0.8072397186313645]
4-element Array{Float64,1}:
 0.42646245106083813
 2.0                
 0.11984596318454832
 0.8072397186313645

Notice that changing B changed A. This is something to be careful of, but at the same time we want to use this since we want to modify the output dr. Additionally, the last statement is a purely element-wise operation, and thus we can make use of broadcast fusion there. Let's rewrite basic_version! to ***avoid slicing allocations*** and to ***use broadcast fusion***:

function gm2!(dr,r,p,t)
  a,α,ubar,β,D1,D2 = p
  u = @view r[:,:,1]
  v = @view r[:,:,2]
  du = @view dr[:,:,1]
  dv = @view dr[:,:,2]
  Du = D1*(Ay*u + u*Ax)
  Dv = D2*(Ay*v + v*Ax)
  @. du = Du + a.*u.*u./v + ubar - α*u
  @. dv = Dv + a.*u.*u - β*v
end
prob = ODEProblem(gm2!,r0,(0.0,0.1),p)
@benchmark solve(prob,Tsit5())
BenchmarkTools.Trial: 
  memory estimate:  119.55 MiB
  allocs estimate:  7094
  --------------
  minimum time:     66.481 ms (0.00% GC)
  median time:      97.255 ms (0.00% GC)
  mean time:        101.286 ms (12.35% GC)
  maximum time:     150.328 ms (28.89% GC)
  --------------
  samples:          50
  evals/sample:     1

Now, most of the allocations are taking place in Du = D1*(Ay*u + u*Ax) since those operations are vectorized and not mutating. We should instead replace the matrix multiplications with mul!. When doing so, we will need to have cache variables to write into. This looks like:

Ayu = zeros(N,N)
uAx = zeros(N,N)
Du = zeros(N,N)
Ayv = zeros(N,N)
vAx = zeros(N,N)
Dv = zeros(N,N)
function gm3!(dr,r,p,t)
  a,α,ubar,β,D1,D2 = p
  u = @view r[:,:,1]
  v = @view r[:,:,2]
  du = @view dr[:,:,1]
  dv = @view dr[:,:,2]
  mul!(Ayu,Ay,u)
  mul!(uAx,u,Ax)
  mul!(Ayv,Ay,v)
  mul!(vAx,v,Ax)
  @. Du = D1*(Ayu + uAx)
  @. Dv = D2*(Ayv + vAx)
  @. du = Du + a*u*u./v + ubar - α*u
  @. dv = Dv + a*u*u - β*v
end
prob = ODEProblem(gm3!,r0,(0.0,0.1),p)
@benchmark solve(prob,Tsit5())
BenchmarkTools.Trial: 
  memory estimate:  29.76 MiB
  allocs estimate:  5330
  --------------
  minimum time:     48.425 ms (0.00% GC)
  median time:      63.189 ms (0.00% GC)
  mean time:        65.725 ms (3.44% GC)
  maximum time:     96.058 ms (26.44% GC)
  --------------
  samples:          77
  evals/sample:     1

But our temporary variables are global variables. We need to either declare the caches as const or localize them. We can localize them by adding them to the parameters, p. It's easier for the compiler to reason about local variables than global variables. ***Localizing variables helps to ensure type stability***.

p = (1.0,1.0,1.0,10.0,0.001,100.0,Ayu,uAx,Du,Ayv,vAx,Dv) # a,α,ubar,β,D1,D2
function gm4!(dr,r,p,t)
  a,α,ubar,β,D1,D2,Ayu,uAx,Du,Ayv,vAx,Dv = p
  u = @view r[:,:,1]
  v = @view r[:,:,2]
  du = @view dr[:,:,1]
  dv = @view dr[:,:,2]
  mul!(Ayu,Ay,u)
  mul!(uAx,u,Ax)
  mul!(Ayv,Ay,v)
  mul!(vAx,v,Ax)
  @. Du = D1*(Ayu + uAx)
  @. Dv = D2*(Ayv + vAx)
  @. du = Du + a*u*u./v + ubar - α*u
  @. dv = Dv + a*u*u - β*v
end
prob = ODEProblem(gm4!,r0,(0.0,0.1),p)
@benchmark solve(prob,Tsit5())
BenchmarkTools.Trial: 
  memory estimate:  29.66 MiB
  allocs estimate:  1066
  --------------
  minimum time:     43.321 ms (0.00% GC)
  median time:      54.658 ms (0.00% GC)
  mean time:        59.537 ms (4.21% GC)
  maximum time:     96.548 ms (23.32% GC)
  --------------
  samples:          84
  evals/sample:     1

We could then use the BLAS gemmv to optimize the matrix multiplications some more, but instead let's devectorize the stencil.

p = (1.0,1.0,1.0,10.0,0.001,100.0,N)
function fast_gm!(du,u,p,t)
  a,α,ubar,β,D1,D2,N = p

  @inbounds for j in 2:N-1, i in 2:N-1
    du[i,j,1] = D1*(u[i-1,j,1] + u[i+1,j,1] + u[i,j+1,1] + u[i,j-1,1] - 4u[i,j,1]) +
              a*u[i,j,1]^2/u[i,j,2] + ubar - α*u[i,j,1]
  end

  @inbounds for j in 2:N-1, i in 2:N-1
    du[i,j,2] = D2*(u[i-1,j,2] + u[i+1,j,2] + u[i,j+1,2] + u[i,j-1,2] - 4u[i,j,2]) +
            a*u[i,j,1]^2 - β*u[i,j,2]
  end

  @inbounds for j in 2:N-1
    i = 1
    du[1,j,1] = D1*(2u[i+1,j,1] + u[i,j+1,1] + u[i,j-1,1] - 4u[i,j,1]) +
            a*u[i,j,1]^2/u[i,j,2] + ubar - α*u[i,j,1]
  end
  @inbounds for j in 2:N-1
    i = 1
    du[1,j,2] = D2*(2u[i+1,j,2] + u[i,j+1,2] + u[i,j-1,2] - 4u[i,j,2]) +
            a*u[i,j,1]^2 - β*u[i,j,2]
  end
  @inbounds for j in 2:N-1
    i = N
    du[end,j,1] = D1*(2u[i-1,j,1] + u[i,j+1,1] + u[i,j-1,1] - 4u[i,j,1]) +
           a*u[i,j,1]^2/u[i,j,2] + ubar - α*u[i,j,1]
  end
  @inbounds for j in 2:N-1
    i = N
    du[end,j,2] = D2*(2u[i-1,j,2] + u[i,j+1,2] + u[i,j-1,2] - 4u[i,j,2]) +
           a*u[i,j,1]^2 - β*u[i,j,2]
  end

  @inbounds for i in 2:N-1
    j = 1
    du[i,1,1] = D1*(u[i-1,j,1] + u[i+1,j,1] + 2u[i,j+1,1] - 4u[i,j,1]) +
              a*u[i,j,1]^2/u[i,j,2] + ubar - α*u[i,j,1]
  end
  @inbounds for i in 2:N-1
    j = 1
    du[i,1,2] = D2*(u[i-1,j,2] + u[i+1,j,2] + 2u[i,j+1,2] - 4u[i,j,2]) +
              a*u[i,j,1]^2 - β*u[i,j,2]
  end
  @inbounds for i in 2:N-1
    j = N
    du[i,end,1] = D1*(u[i-1,j,1] + u[i+1,j,1] + 2u[i,j-1,1] - 4u[i,j,1]) +
             a*u[i,j,1]^2/u[i,j,2] + ubar - α*u[i,j,1]
  end
  @inbounds for i in 2:N-1
    j = N
    du[i,end,2] = D2*(u[i-1,j,2] + u[i+1,j,2] + 2u[i,j-1,2] - 4u[i,j,2]) +
             a*u[i,j,1]^2 - β*u[i,j,2]
  end

  @inbounds begin
    i = 1; j = 1
    du[1,1,1] = D1*(2u[i+1,j,1] + 2u[i,j+1,1] - 4u[i,j,1]) +
              a*u[i,j,1]^2/u[i,j,2] + ubar - α*u[i,j,1]
    du[1,1,2] = D2*(2u[i+1,j,2] + 2u[i,j+1,2] - 4u[i,j,2]) +
              a*u[i,j,1]^2 - β*u[i,j,2]

    i = 1; j = N
    du[1,N,1] = D1*(2u[i+1,j,1] + 2u[i,j-1,1] - 4u[i,j,1]) +
             a*u[i,j,1]^2/u[i,j,2] + ubar - α*u[i,j,1]
    du[1,N,2] = D2*(2u[i+1,j,2] + 2u[i,j-1,2] - 4u[i,j,2]) +
             a*u[i,j,1]^2 - β*u[i,j,2]

    i = N; j = 1
    du[N,1,1] = D1*(2u[i-1,j,1] + 2u[i,j+1,1] - 4u[i,j,1]) +
             a*u[i,j,1]^2/u[i,j,2] + ubar - α*u[i,j,1]
    du[N,1,2] = D2*(2u[i-1,j,2] + 2u[i,j+1,2] - 4u[i,j,2]) +
             a*u[i,j,1]^2 - β*u[i,j,2]

    i = N; j = N
    du[end,end,1] = D1*(2u[i-1,j,1] + 2u[i,j-1,1] - 4u[i,j,1]) +
             a*u[i,j,1]^2/u[i,j,2] + ubar - α*u[i,j,1]
    du[end,end,2] = D2*(2u[i-1,j,2] + 2u[i,j-1,2] - 4u[i,j,2]) +
             a*u[i,j,1]^2 - β*u[i,j,2]
   end
end
prob = ODEProblem(fast_gm!,r0,(0.0,0.1),p)
@benchmark solve(prob,Tsit5())
BenchmarkTools.Trial: 
  memory estimate:  29.63 MiB
  allocs estimate:  479
  --------------
  minimum time:     9.998 ms (0.00% GC)
  median time:      16.181 ms (0.00% GC)
  mean time:        19.605 ms (13.68% GC)
  maximum time:     72.368 ms (69.77% GC)
  --------------
  samples:          255
  evals/sample:     1

Lastly, we can do other things like multithread the main loops, but these optimizations get the last 2x-3x out. The main optimizations which apply everywhere are the ones we just performed (though the last one only works if your matrix is a stencil. This is known as a matrix-free implementation of the PDE discretization).

This gets us to about 8x faster than our original MATLAB/SciPy/R vectorized style code!

The last thing to do is then ***optimize our algorithm choice***. We have been using Tsit5() as our test algorithm, but in reality this problem is a stiff PDE discretization and thus one recommendation is to use CVODE_BDF(). However, instead of using the default dense Jacobian, we should make use of the sparse Jacobian afforded by the problem. The Jacobian is the matrix $\frac{df_i}{dr_j}$, where $r$ is read by the linear index (i.e. down columns). But since the $u$ variables depend on the $v$, the band size here is large, and thus this will not do well with a Banded Jacobian solver. Instead, we utilize sparse Jacobian algorithms. CVODE_BDF allows us to use a sparse Newton-Krylov solver by setting linear_solver = :GMRES (see the solver documentation, and thus we can solve this problem efficiently. Let's see how this scales as we increase the integration time.

prob = ODEProblem(fast_gm!,r0,(0.0,10.0),p)
@benchmark solve(prob,Tsit5())
BenchmarkTools.Trial: 
  memory estimate:  2.76 GiB
  allocs estimate:  41663
  --------------
  minimum time:     2.885 s (32.88% GC)
  median time:      2.899 s (28.56% GC)
  mean time:        2.899 s (28.56% GC)
  maximum time:     2.913 s (24.28% GC)
  --------------
  samples:          2
  evals/sample:     1
using Sundials
@benchmark solve(prob,CVODE_BDF(linear_solver=:GMRES))
BenchmarkTools.Trial: 
  memory estimate:  51.87 MiB
  allocs estimate:  8291
  --------------
  minimum time:     255.113 ms (0.00% GC)
  median time:      288.455 ms (0.00% GC)
  mean time:        283.839 ms (0.82% GC)
  maximum time:     309.844 ms (5.24% GC)
  --------------
  samples:          18
  evals/sample:     1
prob = ODEProblem(fast_gm!,r0,(0.0,100.0),p)
# Will go out of memory if we don't turn off `save_everystep`!
@benchmark solve(prob,Tsit5(),save_everystep=false)
BenchmarkTools.Trial: 
  memory estimate:  2.90 MiB
  allocs estimate:  87
  --------------
  minimum time:     6.271 s (0.00% GC)
  median time:      6.271 s (0.00% GC)
  mean time:        6.271 s (0.00% GC)
  maximum time:     6.271 s (0.00% GC)
  --------------
  samples:          1
  evals/sample:     1
@benchmark solve(prob,CVODE_BDF(linear_solver=:GMRES))
BenchmarkTools.Trial: 
  memory estimate:  275.45 MiB
  allocs estimate:  55100
  --------------
  minimum time:     1.626 s (0.47% GC)
  median time:      1.810 s (0.47% GC)
  mean time:        1.774 s (1.00% GC)
  maximum time:     1.885 s (1.97% GC)
  --------------
  samples:          3
  evals/sample:     1

Now let's check the allocation growth.

@benchmark solve(prob,CVODE_BDF(linear_solver=:GMRES),save_everystep=false)
BenchmarkTools.Trial: 
  memory estimate:  3.33 MiB
  allocs estimate:  41596
  --------------
  minimum time:     1.616 s (0.00% GC)
  median time:      1.734 s (0.00% GC)
  mean time:        1.696 s (0.00% GC)
  maximum time:     1.738 s (0.00% GC)
  --------------
  samples:          3
  evals/sample:     1
prob = ODEProblem(fast_gm!,r0,(0.0,500.0),p)
@benchmark solve(prob,CVODE_BDF(linear_solver=:GMRES),save_everystep=false)
BenchmarkTools.Trial: 
  memory estimate:  3.70 MiB
  allocs estimate:  48071
  --------------
  minimum time:     1.862 s (0.00% GC)
  median time:      2.004 s (0.00% GC)
  mean time:        1.963 s (0.00% GC)
  maximum time:     2.024 s (0.00% GC)
  --------------
  samples:          3
  evals/sample:     1

Notice that we've elimated almost all allocations, allowing the code to grow without hitting garbage collection and slowing down.

Why is CVODE_BDF doing well? What's happening is that, because the problem is stiff, the number of steps required by the explicit Runge-Kutta method grows rapidly, whereas CVODE_BDF is taking large steps. Additionally, the GMRES linear solver form is quite an efficient way to solve the implicit system in this case. This is problem-dependent, and in many cases using a Krylov method effectively requires a preconditioner, so you need to play around with testing other algorithms and linear solvers to find out what works best with your problem.

Conclusion

Julia gives you the tools to optimize the solver "all the way", but you need to make use of it. The main thing to avoid is temporary allocations. For small systems, this is effectively done via static arrays. For large systems, this is done via in-place operations and cache arrays. Either way, the resulting solution can be immensely sped up over vectorized formulations by using these principles.

Appendix

This tutorial is part of the DiffEqTutorials.jl repository, found at: https://github.com/JuliaDiffEq/DiffEqTutorials.jl

To locally run this tutorial, do the following commands:

using DiffEqTutorials
DiffEqTutorials.weave_file("introduction","03-optimizing_diffeq_code.jmd")

Computer Information:

Julia Version 1.3.0
Commit 46ce4d7933 (2019-11-26 06:09 UTC)
Platform Info:
  OS: Windows (x86_64-w64-mingw32)
  CPU: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-6.0.1 (ORCJIT, skylake)
Environment:
  JULIA_EDITOR = "C:\Users\accou\AppData\Local\atom\app-1.42.0\atom.exe"  -a
  JULIA_NUM_THREADS = 4

Package Information:

Status `~\.julia\dev\DiffEqTutorials\Project.toml`