CoDiPack  2.2.0
A Code Differentiation Package
SciComp TU Kaiserslautern
Loading...
Searching...
No Matches
Example 24 - Enzyme external function helper

Goal: Add external functions to the tape via Enzyme.

Prerequisite: Example 10 - External function helper

Function:

template<typename Type>
Type func(Type const& v) {
return 42.0 * v * v;
}
void func_prim(double const* x, size_t m, double* y, size_t n, codi::ExternalFunctionUserData* d) {
y[0] = 42.0 * x[0] * x[0];
}
Ease of access structure for user-provided data on the tape for external functions....
Definition: externalFunctionUserData.hpp:59

Full code:

#include <iostream>
#include <codi.hpp>
template<typename Type>
Type func(Type const& v) {
return 42.0 * v * v;
}
void func_prim(double const* x, size_t m, double* y, size_t n, codi::ExternalFunctionUserData* d) {
y[0] = 42.0 * x[0] * x[0];
}
int main(int nargs, char** args) {
using Tape = typename Real::Tape;
Tape& tape = Real::getTape();
Real x = 10.0;
Real y[3];
tape.setActive();
tape.registerInput(x);
// Regular computation
y[0] = func(x);
#if CODI_EnableEnzyme
eh.addInput(x);
eh.addOutput(y[1]);
eh.template callAndAddToTape<func_prim>();
eh.template callAndAddToTape<func_prim>(&x, 1, &y[2], 1);
#else
std::cerr << "Enzyme is not enabled for CoDiPack. Enable it with: -DCODI_EnableEnzyme=1." << std::endl;
#endif
for(int i = 0; i < 3; i += 1) {
tape.registerOutput(y[i]);
}
tape.setPassive();
for(int i = 0; i < 3; i += 1) {
tape.clearAdjoints();
y[i].setGradient(1.0);
tape.evaluate();
std::cout << "Gradient of dy[" << i << "]/dx: " << x.getGradient() << std::endl;
}
}
RealReverseGen< double > RealReverse
Definition: codi.hpp:120
Represents a concrete lvalue in the CoDiPack expression tree.
Definition: activeType.hpp:52
static Tape & getTape()
Get a reference to the tape which manages this expression.
Definition: activeType.hpp:99
T_Tape Tape
See ActiveType.
Definition: activeType.hpp:55
Helper class for the implementation of an external function with Enzyme in CoDiPack.
Definition: enzymeExternalFunctionHelper.hpp:84
Helper class for the implementation of an external function in CoDiPack.
Definition: externalFunctionHelper.hpp:102
void addInput(Type const &input)
Add an input value.
Definition: externalFunctionHelper.hpp:451
void addOutput(Type &output)
Add an output value.
Definition: externalFunctionHelper.hpp:492
void setGradient(Gradient const &g)
Set the gradient of this lvalue in the tape.
Definition: lhsExpressionInterface.hpp:120
Gradient getGradient() const
Get the gradient of this lvalue from the tape.
Definition: lhsExpressionInterface.hpp:115