How to "copy-past" quote expression in a function?


I have some code to copy past in different function / kernel.
I saw something about metaprogramming but I have to admit that this is very opaque for me …
I would like to know if I can define a quote that contain the code and eval this quote in a function / cuda kernel ?

I have 3 expressions

free_energy_1 = :(0.25*ar*ρ + ...)
free_energy_2 = :( - 0.5*ap*(ρ-ρcr)*P + ... )
free_energy_3 = :( - 0.5*ap*(ρ-ρcr)*P2 + ...) )

and I would like to define a variable in a function (CUDA kernel in this case) such that

f = eval(free_energy_1) + eval(free_energy_2) + eval(free_energy_3)

The Idea is to have many kernels where f can use only free_energy_1, or free_ernegy_2, or both, or… But I don’t want to repeat my code 0.25*ar*ρ + ... in each of this kernel. Also repeating this code makes it difficult when I want to edit one of this free_energy, because then I have to change it everywhere…
This is not working, that why I ask for help.

I can make some part working using macro, for example for indexing my 2D grid:

macro indexing_2D() 
        i = (blockIdx().x - 1) * blockDim().x + threadIdx().x
        j = (blockIdx().y - 1) * blockDim().y + threadIdx().y

and then, inside my kernel I can call @indexing_2D and it declares my i, j
This is not very useful, but I am trying to learn with “stupid” example.

Thank you for your help,
At this point anything can be useful :slight_smile:

Don’t use metaprogramming for this. Just pass functions.


Thank you,
I was thinking to do that, but I would make about 20 functions to pass in a kernel called 1024x1024x1’000’000 times.

I don’t know how it works in Julia but I am afraid about the time needed to call a fonction.
Does @inline can help ?

I am sorry I know almost nothing about these things…

Adding 20 functions as arguments makes it very difficult to read…
Is there a way of doing the same thing using metaprogramming ?
I mean just quote and eval() ?
The idea would be to have some lines of code to copy-past at the right place during compilation.

I tried with functions, but know it takes 8 to 10 times more times to run…
I am going back to my old code.

It seems there is no solution

Thank you for your help.

Then you are probably doing something wrong; it’s possible to have highly optimized inlined code with higher order functions in Julia, as has been demonstrated in many practical applications (from Julia itself, which uses this technique heavily, to packages like DifferentialEquations or Gridap).

If you can show a small self-contained example of code that is running slower than you think it should, people here may be able to help you.

1 Like