stfc / PSyclone

Domain-specific compiler and code transformation system for Finite Difference/Volume/Element Earth-system models in Fortran
BSD 3-Clause "New" or "Revised" License
107 stars 29 forks source link

[LFRic] [PSyAD] Integer assignments related to active variables are in wrong order in adjoint #2764

Open DrTVockerodtMO opened 2 weeks ago

DrTVockerodtMO commented 2 weeks ago

Suppose we have some forward code of the form

k = 0
call some_function( ... , k )

do k = 1, nlayers – 2
  call some_function( ... , k )
end do

k = nlayers - 1
call some_function( ... , k )

When PSyAD generates the adjoint of this code, the k assignments are treated as passive, so they all precipitate up to the top which yields

k = 0
k = nlayers - 1
call adj_some_function( ... , k )

do k = nlayers - 1, 1, -1
  call adj_some_function( ... , k )
end do

call adj_some_function( ... , k )

When it should be

k = nlayers - 1
call adj_some_function( ... , k )

do k = nlayers - 1, 1, -1
  call adj_some_function( ... , k )
end do

k = 0
call adj_some_function( ... , k )
arporter commented 2 weeks ago

Thanks for reporting this Terry. @LonelyCat124 will the new DA you're working on enable us to look backwards and find the earliest point to which we could move the assignment k = 0 in this example?

LonelyCat124 commented 2 weeks ago

It would be able to find the previous dependency to k (which in this case would either be the loop or the call inside the loop, maybe both) I think but you'd then have to do something with that information.

arporter commented 2 weeks ago

It would be able to find the previous dependency to k (which in this case would either be the loop or the call inside the loop, maybe both) I think but you'd then have to do something with that information.

Great - it was only the information I was after. We'd just have to modify the current code that moves the assignment all the way to the top.

arporter commented 2 weeks ago

I have a question for @DrTVockerodtMO: I thought we didn't support constructing the adjoint of code with Call in it? Is that example code exactly what you're giving PSyAD?

DrTVockerodtMO commented 1 week ago

I have a question for @DrTVockerodtMO: I thought we didn't support constructing the adjoint of code with Call in it? Is that example code exactly what you're giving PSyAD?

This is just a conceptual example, not fed to PSyAD.