### Install XAD with vcpkg Source: https://github.com/auto-differentiation/xad/blob/main/README.md Install XAD using vcpkg package manager. After installation, link against XAD::xad in CMake. ```bash vcpkg install xad ``` -------------------------------- ### Adjoint mode derivative example in C++ Source: https://github.com/auto-differentiation/xad/blob/main/README.md Shows how to compute all derivatives of a function in one adjoint sweep using XAD's adjoint (reverse) mode. Register inputs and output, set derivative of output to 1.0, then call computeAdjoints() to get derivatives of inputs. ```c++ #include #include using mode = xad::adj; // adjoint (reverse) mode using AD = mode::active_type; template T f(T x, T y) { return x * sin(y) + exp(x * y); } // your code, unchanged int main() { mode::tape_type tape; AD x = 1.3, y = 5.2; tape.registerInput(x); tape.registerInput(y); tape.newRecording(); AD z = f(x, y); tape.registerOutput(z); derivative(z) = 1.0; tape.computeAdjoints(); // every input derivative in one sweep std::cout << "dz/dx = " << derivative(x) << ", dz/dy = " << derivative(y) << "\n"; } ``` -------------------------------- ### Install CMake export configuration files for XAD Source: https://github.com/auto-differentiation/xad/blob/main/src/CMakeLists.txt Configures CMake package config files for the XAD library. Uses write_basic_package_version_file with SameMajorVersion compatibility, exports the XADTargets with the XAD:: namespace, and installs the generated config files to ${CMAKE_INSTALL_LIBDIR}/cmake/XAD. ```cmake # install CMake export configuration files include(CMakePackageConfigHelpers) set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated") set(version_file "${generated_dir}/XADConfigVersion.cmake") set(config_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/XAD") write_basic_package_version_file(${version_file} VERSION ${XAD_VERSION} COMPATIBILITY SameMajorVersion ) export(EXPORT XADTargets FILE "${PROJECT_BINARY_DIR}/cmake/XADTargets.cmake" NAMESPACE XAD:: ) install(EXPORT XADTargets FILE XADTargets.cmake NAMESPACE XAD:: DESTINATION ${config_install_dir} ) configure_package_config_file( "${PROJECT_SOURCE_DIR}/cmake/XADConfig.cmake.in" "${generated_dir}/XADConfig.cmake" INSTALL_DESTINATION ${config_install_dir} ) install(FILES "${generated_dir}/XADConfigVersion.cmake" "${generated_dir}/XADConfig.cmake" DESTINATION ${config_install_dir} ) ``` -------------------------------- ### Setup Tape and Active Types Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jacobian.md Sets up the tape and active data types for adjoint mode. If no tape is setup, one will be created when computing the Jacobian. ```c++ typedef xad::adj mode; typedef mode::tape_type tape_type; typedef mode::active_type AD; tape_type tape; ``` -------------------------------- ### newRecording Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-compiler.md Starts a new recording using the existing registered inputs, which must stay alive; clearAll drops them. ```APIDOC ## newRecording ### Description Starts a new recording using the existing registered inputs, which must stay alive; clearAll drops them. ### Method void newRecording() ### Parameters None ### Returns None ``` -------------------------------- ### newRecording Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Starts recording derivatives. Should be called after independent variables are initialized and registered. ```APIDOC ## newRecording ### Description Starts recording derivatives. This function should be called after the independent variables are initialized and registered, as the computeAdjoints method will roll back the adjoints until the point where newRecording was called. ### Method newRecording ``` -------------------------------- ### CMakeLists.txt for XAD library build configuration Source: https://github.com/auto-differentiation/xad/blob/main/src/CMakeLists.txt Defines the XAD library build, including optional JIT/codegen support, shared/static library selection, linking against xad_codegen, and installation rules for headers, targets, and PDB files. The codegen-related blocks are conditional on XAD_ENABLE_CODEGEN, and PDB installation is handled for MSVC builds. ```cmake # JIT/Codegen compilation support headers (optional) if(XAD_ENABLE_CODEGEN) list(APPEND public_headers XAD/JITCompiler.hpp XAD/JITGraph.hpp XAD/JITBackendInterface.hpp XAD/JITGraphInterpreter.hpp XAD/JITOpCodeTraits.hpp XAD/JITExprTraits.hpp XAD/ABool.hpp ) endif() set(srcfiles Tape.cpp ${public_headers}) if (MSVC) list(APPEND srcfiles ${PROJECT_SOURCE_DIR}/XAD.natvis) endif() # JIT TLS storage (required when codegen/JIT is ON) if(XAD_ENABLE_CODEGEN) list(APPEND srcfiles XAD/JITGraphInterpreter.cpp XAD/JITCompilerTLS.cpp ) endif() if(XAD_SHARED_LIBS) set(xad_lib_type SHARED) else() set(xad_lib_type STATIC) endif() xad_add_library(xad ${xad_lib_type} ${srcfiles}) target_include_directories(xad PUBLIC "$" "$" "$/${CMAKE_INSTALL_INCLUDEDIR}>" ) # Link codegen when enabled if(XAD_ENABLE_CODEGEN) target_link_libraries(xad PUBLIC xad_codegen) endif() # Install targets install(FILES ${public_headers} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/XAD) install(TARGETS xad EXPORT XADTargets RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") if(MSVC AND XAD_SHARED_LIBS) install(FILES "$" DESTINATION "${CMAKE_INSTALL_BINDIR}" OPTIONAL) elseif(MSVC AND NOT CMAKE_CXX_COMPILER_ID STREQUAL "Clang") # clang-cl does not generate PDB files, but rather embeds them # install PDB files get_target_property(xad_pdb_name xad COMPILE_PDB_NAME) get_target_property(xad_pdb_name_debug xad COMPILE_PDB_NAME_DEBUG) get_target_property(xad_pdb_output_dir xad PDB_OUTPUT_DIRECTORY) get_property(multiconf GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(multiconf) install(FILES "${xad_pdb_output_dir}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$:${xad_pdb_name_debug}>$<$>:${xad_pdb_name}>.pdb" DESTINATION "${CMAKE_INSTALL_LIBDIR}" CONFIGURATIONS Debug RelWithDebInfo ) else() install(FILES "${xad_pdb_output_dir}/$<$:${xad_pdb_name_debug}>$<$>:${xad_pdb_name}>.pdb" DESTINATION "${CMAKE_INSTALL_LIBDIR}" CONFIGURATIONS Debug RelWithDebInfo ) endif() endif() ``` -------------------------------- ### Fetch XAD from GitHub with CMake FetchContent Source: https://github.com/auto-differentiation/xad/blob/main/README.md Fetch XAD directly from GitHub using CMake's FetchContent module. Specify the repository and tag (v2.1.0) to get a specific version. ```cmake include(FetchContent) FetchContent_Declare(XAD GIT_REPOSITORY https://github.com/auto-differentiation/xad.git GIT_TAG v2.1.0) FetchContent_MakeAvailable(XAD) target_link_libraries(my_app PRIVATE XAD::xad) ``` -------------------------------- ### Setup Tape and Active Types for Hessian Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/hessian.md Sets up the tape and active data types for fwd_adj mode. If no tape is set up, one is created when computing the Hessian. fwd_fwd mode is supported similarly. ```c++ typedef xad::fwd_adj mode; typedef mode::tape_type tape_type; typedef mode::active_type AD; tape_type tape; ``` -------------------------------- ### CMake find_package for XAD Source: https://github.com/auto-differentiation/xad/blob/main/README.md Use find_package to locate XAD and link it to your target. Requires XAD installed via vcpkg or system package. ```cmake find_package(XAD CONFIG REQUIRED) target_link_libraries(my_app PRIVATE XAD::xad) ``` -------------------------------- ### Typical usage of Tape for adjoint computation Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Shows the standard workflow for recording and computing adjoints with a Tape: register inputs, start a new recording, perform operations, register the output, set its derivative, and call computeAdjoints(). Requires the tape to be active and variables to be registered as inputs. ```c++ Tape tape; // initialize independent variables AReal x1 = 1.2, x2 = 12.1; // register independents with the tape tape.registerInput(x1); tape.registerInput(x2); // start recording derivatives on tape tape.newRecording(); AReal y = sin(x1) + x1*x2; // register output and set adjoint values tape.registerOutput(y); derivative(y) = 1.0; // compute the adjoints of the independent variables tape.computeAdjoints(); // output/use results std::cout << "y = " << value(y) << "\n" << "dy/dx1 = " << derivative(x1) << "\n" << "dy/dx2 = " << derivative(x2) << "\n"; ``` -------------------------------- ### getNumCallbacks Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Gets the number of callback objects that have been pushed by pushCallback. ```APIDOC ## getNumCallbacks ### Description Gets the number of callback objects that have been pushed by `pushCallback`. ### Method size_type ### Signature `size_type getNumCallbacks() const` ### Parameters None ### Returns - **size_type** - The number of callback objects pushed. ``` -------------------------------- ### Example Function for Hessian Computation Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/hessian.md Defines the function f(x, y, z, w) = sin(xy) - cos(yz) - sin(zw) - cos(wx) as a lambda taking a vector of active types. This function is used in the Hessian example. ```c++ auto foo = [](std::vector &x) -> AD { return sin(x[0] * x[1]) - cos(x[1] * x[2]) - sin(x[2] * x[3]) - cos(x[3] * x[0]); }; ``` -------------------------------- ### newNestedRecording Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Starts a new nested recording that can be rolled-back on its own. Must be ended with endNestedRecording. ```APIDOC ## newNestedRecording ### Description Starts a new nested recording that can be rolled-back on its own. It must be ended with `endNestedRecording`. It is intended for use within a `CheckpointCallback::computeAdjoints` implementation, when from a checkpoint, the adjoints are computed using XAD in a nested recording. ### Method void ### Signature `void newNestedRecording()` ### Parameters None ``` -------------------------------- ### Example Function Definition Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jacobian.md Defines the function f(x, y, z, w) = [sin(x+y), sin(y+z), cos(z+w), cos(w+x)] as a lambda taking a vector of active types. ```c++ std::function(std::vector&)> foo = [](std::vector &x) -> std::vector { return {sin(x[0] + x[1]), sin(x[1] + x[2]), cos(x[2] + x[3]), cos(x[3] + x[0])}; }; ``` -------------------------------- ### derivative Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Gets a reference to the derivative associated with a slot. ```APIDOC ## derivative ### Description Gets a reference to the derivative associated with the slot s. It throws OutOfRange if the given slot is not associated with a stored derivative. (Note that it is only thrown in debug mode for performance reasons, otherwise the behaviour is undefined in this case) ### Method derivative ### Parameters - **s** (slot_type) - Required - The slot whose derivative to get. ### Returns - **T&** - Reference to the derivative associated with the slot. ### Exceptions - Throws OutOfRange if the slot is not associated with a stored derivative (debug mode only). ### Exception Safety Gives strong exception safety guarantee - tape state unchanged in case of exception. ### Const Version - `const T& derivative(slot_type s) const` - Gets a const reference to the derivative associated with the slot s and otherwise behaves the same. ``` -------------------------------- ### ScopedNestedRecording constructor Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Constructs a ScopedNestedRecording object, starting a new nested recording on the given tape. The constructor calls newNestedRecording on the tape. ```APIDOC ## ScopedNestedRecording(TapeType* t) ### Description Constructs a ScopedNestedRecording object, starting a new nested recording on the given tape. The constructor calls `newNestedRecording` on the tape. ### Method Constructor ### Parameters - **t** (TapeType*) - Required - Pointer to the tape on which to start the nested recording. ### Usage ```c++ ScopedNestedRecording recording(tape); ``` ``` -------------------------------- ### getAndResetOutputAdjoint Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Obtains the output adjoint stored in a slot and resets it to 0. Should be called by CheckpointCallback::computeAdjoints to get the current value of the adjoint. ```APIDOC ## getAndResetOutputAdjoint ### Description Obtains the output adjoint stored in `slot` and resets it to 0. This function should be called by `CheckpointCallback::computeAdjoints` to get the current value of the adjoint. It also resets its adjoint to 0 on the tape to allow re-use of that variable. ### Method T ### Signature `T getAndResetOutputAdjoint(slot_type slot)` ### Parameters - **slot** (slot_type) - Required - The slot whose adjoint is to be obtained and reset. ### Returns - **T** - The current value of the adjoint. ### Exceptions - **OutOfRange** - If the given slot is not associated with a stored derivative (only thrown in debug mode; otherwise behavior is undefined). ### Exception Safety Strong exception safety guarantee - tape state unchanged in case of exception. ``` -------------------------------- ### Using xad::adj mode interface Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/interface.md Shows how to access AD mode-specific types via the xad::adj traits class, including the active type and tape type. The active type is used in function signatures and the tape type is instantiated for tape setup. ```c++ using mode = xad::adj; using adouble = mode::active_type; // use active type in functions, etc. adouble my_function(adouble x) {...} mode::tape_type tape; // setup tape ``` -------------------------------- ### Tape::registerInput Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Registers the given variable with the tape and starts recording dependents of it. A call to this function or its overloads is required in order to calculate adjoints. ```APIDOC ## [METHOD] Tape::registerInput ### Description Registers the given variable with the tape and starts recording dependents of it. A call to this function or its overloads is required in order to calculate adjoints. ### Method void registerInput(active_type& inp) ### Endpoint `void registerInput(active_type& inp)` ### Parameters #### Parameters - **inp** (active_type&) - Required - The variable to register as an input. ### Overloads - `void registerInput(std::complex& inp)` - For complex values. ### Example ```c++ tape.registerInput(x1); ``` ``` -------------------------------- ### CMakeLists.txt for jit_tutorial sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/jit_tutorial/CMakeLists.txt CMake configuration for the jit_tutorial sample. It checks if XAD_ENABLE_JIT is enabled; if not, it skips the sample with a status message, otherwise it adds the sample using xad_add_sample with main.cpp as the source. ```cmake if (NOT XAD_ENABLE_JIT) message(STATUS "Skipping jit_tutorial sample (XAD_ENABLE_JIT is OFF)") else() xad_add_sample(jit_tutorial SOURCES main.cpp) endif() ``` -------------------------------- ### CMake configuration for fwd_1st sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/fwd_1st/CMakeLists.txt CMake file that adds the fwd_1st sample using the xad_add_sample function, specifying main.cpp and the common functions.hpp as sources. ```cmake xad_add_sample(fwd_1st SOURCES main.cpp ../common/functions.hpp) ``` -------------------------------- ### Build XAD from source Source: https://github.com/auto-differentiation/xad/blob/main/README.md Clone the XAD repository and build it using CMake. The commands create a build directory and compile the library. ```bash git clone https://github.com/auto-differentiation/xad.git cmake -S xad -B xad/build cmake --build xad/build ``` -------------------------------- ### CMakeLists.txt for SwapPricer sample using xad_add_sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/SwapPricer/CMakeLists.txt CMake configuration file for the 1st order adjoint mode swap pricer sample in the XAD library. It invokes the xad_add_sample macro with the SwapPricer target name and lists main.cpp and SwapPricer.hpp as sources. This file is part of XAD, a C++ automatic differentiation library, and is licensed under the GNU Affero General Public License v3. ```cmake ############################################################################## # # Cmake file for 1st order adjoint mode swap pricer # # This file is part of XAD, a comprehensive C++ library for # automatic differentiation. # # Copyright (C) 2010-2026 Xcelerit Computing Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, version 3 of the License only. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## xad_add_sample(SwapPricer SOURCES main.cpp SwapPricer.hpp ) ``` -------------------------------- ### Build and test commands Source: https://github.com/auto-differentiation/xad/blob/main/AGENTS.md Commands to configure, build, and run tests for the XAD library. Use these in sequence to set up a build directory and execute the test suite. ```bash cmake -S . -B build -DCMAKE_BUILD_TYPE=Release ``` ```bash cmake --build build -j ``` ```bash ctest --test-dir build -j8 --output-on-failure ``` -------------------------------- ### getDerivative Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Gets a copy of the value of the derivative associated with a slot. ```APIDOC ## getDerivative ### Description Gets a copy of the value of the derivative associated with the slot s. It throws OutOfRange if the given slot is not associated with a stored derivative. (Note that it is only thrown in debug mode for performance reasons, otherwise the behaviour is undefined in this case) ### Method getDerivative ### Parameters - **s** (slot_type) - Required - The slot whose derivative to get. ### Returns - **T** - Copy of the derivative value. ### Exceptions - Throws OutOfRange if the slot is not associated with a stored derivative (debug mode only). ### Exception Safety Gives strong exception safety guarantee - tape state unchanged in case of exception. ``` -------------------------------- ### Build and run commands for LogisticRegression sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/LogisticRegression/README.md Commands to configure, build, and run the sample from the repository root. Alternatively, run `ctest -R LogisticRegression` from the build directory. The sample returns a non-zero exit code if either finite-difference check fails. ```bash cmake -S . -B build cmake --build build --target LogisticRegression build/samples/LogisticRegression/LogisticRegression ``` -------------------------------- ### Build and run SparseJacobian sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/SparseJacobian/README.md Commands to configure, build, and run the SparseJacobian sample. From the build directory, you can also run `ctest -R SparseJacobian`. The sample returns a non-zero exit code if sparse and dense results differ by more than 1e-12. ```bash cmake -S . -B build cmake --build build --target SparseJacobian build/samples/SparseJacobian/SparseJacobian ``` -------------------------------- ### FReal Value and Derivative Accessors Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/freal.md Methods to get and set the value and derivative of an FReal instance. ```APIDOC ## FReal Value and Derivative Accessors ### Description Methods to get and set the value and derivative of an FReal instance. ### Methods #### getValue ```c++ T getValue() const ``` Returns the value as the underlying type (without tape information). #### getDerivative ```c++ DerivativeType getDerivative() const ``` Returns the derivative. #### setDerivative ```c++ void setDerivative(const DerivativeType& a) ``` Sets the derivative in the object. Typically called on independent variables before the operation is started. #### value ```c++ T& value() const T& value() const ``` Returns a reference to the underlying passive type value. Can be used to assign a value without affecting the derivative. #### derivative ```c++ DerivativeType& derivative() const DerivativeType& derivative() const ``` Returns a reference to the derivative value. Can be used to assign a value, equivalent to setDerivative, or as a replacement for getDerivative. ``` -------------------------------- ### CMakeLists.txt for LiborSwaptionPricerJIT Source: https://github.com/auto-differentiation/xad/blob/main/samples/LiborSwaptionPricer/JIT/CMakeLists.txt Build configuration for the JIT-accelerated LIBOR swaption pricer. Requires XAD_ENABLE_CODEGEN to be enabled; otherwise the build is skipped with a status message. Defines the executable, links against the XAD target (either 'xad' or 'XAD::xad'), sets C++17, and registers a quick-mode test for CI. ```cmake ############################################################################## # # Cmake file for LiborSwaptionPricer JIT Benchmark # # This builds the JIT-accelerated version of the LIBOR swaption pricer # using Codegen JIT compilation backend. # # Requires: # - XAD with JIT enabled (XAD_ENABLE_JIT=ON) # - codegen library # - Codegen C API # # This file is part of XAD, a comprehensive C++ library for # automatic differentiation. # # Copyright (C) 2010-2026 Xcelerit Computing Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, version 3 of the License only. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## # Requires XAD_ENABLE_CODEGEN if(NOT XAD_ENABLE_CODEGEN) message(STATUS "XAD_ENABLE_CODEGEN not enabled - skipping LiborSwaptionPricerJIT") return() endif() add_executable(LiborSwaptionPricerJIT main.cpp LiborPricersJIT.cpp LiborPricersJIT.hpp LiborFunctionsJIT.hpp ../LiborData.hpp ../LiborFunctions.hpp ../LiborPricers.hpp ../LiborPricers.cpp ../PlatformInfo.hpp ) # Link to xad (use target name based on context) if(TARGET xad) set(XAD_TARGET xad) elseif(TARGET XAD::xad) set(XAD_TARGET XAD::xad) else() message(FATAL_ERROR "XAD target not found") endif() target_link_libraries(LiborSwaptionPricerJIT PRIVATE ${XAD_TARGET} ) target_include_directories(LiborSwaptionPricerJIT PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/.. ) # Set C++ standard set_target_properties(LiborSwaptionPricerJIT PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON ) # Add as a test (quick mode for CI) add_test( NAME LiborSwaptionPricerJIT COMMAND LiborSwaptionPricerJIT --quick ) ``` -------------------------------- ### complex::getAdjoint() Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/complex.md Alias for getDerivative. Gets the derivatives for both the real and imaginary parts, represented as a complex number of the underlying type. ```APIDOC ## Member Function: getAdjoint() ### Description Alias for getDerivative. Gets the derivatives for both the real and imaginary parts, represented as a complex number of the underlying type. ### Method Member function ### Signature `std::complex getAdjoint() const` ### Parameters None ### Returns - **std::complex** - The derivatives as a complex number. ``` -------------------------------- ### xad_add_sample for LiborSwaptionPricer Source: https://github.com/auto-differentiation/xad/blob/main/samples/LiborSwaptionPricer/CMakeLists.txt Defines the main sample executable for the Libor Swaption pricer demo. It compiles the listed source files and runs with test arguments '100' and 'test'. ```cmake xad_add_sample(LiborSwaptionPricer SOURCES LiborData.hpp LiborFunctions.hpp LiborPricers.hpp LiborPricers.cpp PlatformInfo.hpp main.cpp TEST_ARGS 100 test ) ``` -------------------------------- ### complex::getDerivative() Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/complex.md Gets the derivatives (either forward or adjoint) for both the real and imaginary parts, represented as a complex number of the underlying type. ```APIDOC ## Member Function: getDerivative() ### Description Gets the derivatives (either forward or adjoint) for both the real and imaginary parts, represented as a complex number of the underlying type. ### Method Member function ### Signature `std::complex getDerivative() const` ### Parameters None ### Returns - **std::complex** - The derivatives as a complex number. ``` -------------------------------- ### CMakeLists.txt for fwdvec_1st sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/fwdvec_1st/CMakeLists.txt CMake configuration for the 1st order vector-forward mode sample. It uses the xad_add_sample function to build the sample from main.cpp and the common functions.hpp header. ```cmake xad_add_sample(fwdvec_1st SOURCES main.cpp ../common/functions.hpp) ``` -------------------------------- ### xad_add_sample for LiborSwaptionPricerBenchmark Source: https://github.com/auto-differentiation/xad/blob/main/samples/LiborSwaptionPricer/CMakeLists.txt Defines the baseline benchmark executable that compares finite differences (FD) and XAD. It compiles the same core sources with benchmark.cpp and runs with the '--quick' test argument. ```cmake xad_add_sample(LiborSwaptionPricerBenchmark SOURCES LiborData.hpp LiborFunctions.hpp LiborPricers.hpp LiborPricers.cpp PlatformInfo.hpp benchmark.cpp TEST_ARGS --quick ) ``` -------------------------------- ### Clone the repository Source: https://github.com/auto-differentiation/xad/blob/main/CONTRIBUTING.md Clone the forked repository to your local machine. Replace 'yourusername' with your GitHub username. ```bash git clone https://github.com/yourusername/xad.git ``` -------------------------------- ### ExprTraits Struct Definition Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/expressions.md Main traits class to get information on an AD type. Provides static members for expression properties and typedefs for underlying types. ```c++ template struct ExprTraits { static const bool isExpr; // true if an expression of XAD active type static const int numVariables; // Number of variables in an expression static const bool isForward; // true if forward-mode AD static const bool isReverse; // true if reverse-mode AD static const bool isLiteral; // true if it's an elementary XAD active type // and not an expression static const Direction direction; // direction of the expression or type typedef ... nested_type; // underlying type of the expression // e.g. double for AReal typedef ... value_type; // the base active type of a more // complex expression template typedef ... scalar_type; // Type when unwrapping a higher order // expression, e.g. FReal for // an expression of AReal> }; ``` -------------------------------- ### CMakeLists.txt for fwd_adj_2nd sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/fwd_adj_2nd/CMakeLists.txt Defines the CMake build configuration for the 2nd order forward over adjoint mode sample. It uses the xad_add_sample function to register the sample with its source file main.cpp and a common header functions.hpp. ```cmake xad_add_sample(fwd_adj_2nd SOURCES main.cpp ../common/functions.hpp) ``` -------------------------------- ### CMake sample definition for adjvec_1st using xad_add_sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/adjvec_1st/CMakeLists.txt Defines the CMake build target for the adjvec_1st sample, listing main.cpp and the shared functions.hpp as sources. Uses the project's xad_add_sample macro. The file is part of the XAD automatic differentiation library and is licensed under AGPL v3. ```CMake xad_add_sample(adjvec_1st SOURCES main.cpp ../common/functions.hpp) ``` -------------------------------- ### Define adj_1st sample with xad_add_sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/adj_1st/CMakeLists.txt CMake configuration for the adj_1st sample. It uses the xad_add_sample function to build the sample from main.cpp and the shared header ../common/functions.hpp. ```cmake xad_add_sample(adj_1st SOURCES main.cpp ../common/functions.hpp) ``` -------------------------------- ### ExprTraits Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/expressions.md Main traits class to get information on an AD type. Provides static members to query whether a type is an expression, the number of variables, the AD mode, and nested type information. ```APIDOC ## ExprTraits ### Description Main traits class to get information on an AD type. Provides static members to query whether a type is an expression, the number of variables, the AD mode, and nested type information. ### Template Parameters - **T** (type) - Required - The type to query. ### Static Members - **isExpr** (bool) - true if an expression of XAD active type. - **numVariables** (int) - Number of variables in an expression. - **isForward** (bool) - true if forward-mode AD. - **isReverse** (bool) - true if reverse-mode AD. - **isLiteral** (bool) - true if it's an elementary XAD active type and not an expression. - **direction** (Direction) - Direction of the expression or type. ### Nested Types - **nested_type** - Underlying type of the expression (e.g., double for AReal). - **value_type** - The base active type of a more complex expression template. - **scalar_type** - Type when unwrapping a higher order expression (e.g., FReal for an expression of AReal>). ``` -------------------------------- ### Typical JITCompiler usage with AReal Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-compiler.md Shows the standard workflow: create a JITCompiler, register inputs, record a computation, register the output, compile, and run the forward pass. Requires XAD_ENABLE_CODEGEN at compile time. ```c++ using AD = xad::AReal; xad::JITCompiler jit; AD x = 2.0; AD y = 3.0; jit.registerInput(x); jit.registerInput(y); jit.newRecording(); AD z = x * y + x; jit.registerOutput(z); jit.compile(); double out = 0.0; jit.forward(&out); ``` -------------------------------- ### Tape constructor Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Constructs a new Tape instance, optionally activating it as the global active tape for the current thread. Throws TapeAlreadyActive if another tape is already active and activation is requested. ```APIDOC ## [CONSTRUCTOR] Tape ### Description Constructs a new Tape instance, optionally activating it as the global active tape for the current thread. Throws TapeAlreadyActive if another tape is already active and activation is requested. ### Method Constructor ### Endpoint `explicit Tape(bool activate = true)` ### Parameters #### Parameters - **activate** (bool) - Optional - If true, sets this tape as the active tape for the current thread. ### Exceptions - **TapeAlreadyActive** - If activate is true and another tape is already active for the current thread. ### Example ```c++ Tape tape; // constructs and activates ``` ``` -------------------------------- ### ABool Constructor Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-abool.md Constructs an ABool from a plain bool. The result has no JIT slot (passive only). ```APIDOC ## Constructor ### Description Constructs an ABool from a plain bool. The result has no JIT slot (passive only). ### Signature `explicit ABool(bool b = false);` ### Parameters - **b** (bool) - Optional - The boolean value to initialize the ABool with. Defaults to false. ### Returns An ABool object with no JIT slot. ``` -------------------------------- ### JITBackend and JITGraphInterpreter Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit.md JITBackend is the abstract interface for executing a JITGraph. JITGraphInterpreter is the reference implementation that interprets the graph. Available only when XAD is compiled with XAD_ENABLE_CODEGEN. ```APIDOC ## JITBackend and JITGraphInterpreter ### Description `JITBackend` is the abstract interface for executing a `JITGraph`. `JITGraphInterpreter` is the reference implementation that interprets the graph. ### Availability Only available when XAD is compiled with `XAD_ENABLE_CODEGEN`. ### See Also - [JIT Backend Interface](jit-backend.md) ``` -------------------------------- ### Add SparseJacobian sample to build Source: https://github.com/auto-differentiation/xad/blob/main/samples/SparseJacobian/CMakeLists.txt Registers the SparseJacobian sample with the XAD build system, compiling main.cpp as its source. Uses the xad_add_sample CMake function. ```cmake xad_add_sample(SparseJacobian SOURCES main.cpp) ``` -------------------------------- ### JITGraphInterpreter double backend usage Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-backend.md Creates a JITGraphInterpreter backend and passes it to JITCompiler. The graph is recorded before calling compile(). ```cpp auto backend = std::make_unique>(); xad::JITCompiler jit(std::move(backend)); // ... record graph ... jit.compile(); ``` -------------------------------- ### Comparison Functions Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-abool.md Free functions in the xad namespace that create ABool values from comparisons. When a JIT compiler is active, comparison nodes are recorded in the graph; otherwise they return a passive ABool. ```APIDOC ## Comparison Functions All functions have two overloads: `(AReal, AReal)` and `(AReal, Scalar)`. ### less(a, b) - **Description**: Returns true if a < b. - **Equivalent**: `a < b` ### greater(a, b) - **Description**: Returns true if a > b. - **Equivalent**: `a > b` ### lessEqual(a, b) - **Description**: Returns true if a <= b. - **Equivalent**: `a <= b` ### greaterEqual(a, b) - **Description**: Returns true if a >= b. - **Equivalent**: `a >= b` ``` -------------------------------- ### Add JIT subdirectory Source: https://github.com/auto-differentiation/xad/blob/main/samples/LiborSwaptionPricer/CMakeLists.txt Adds the JIT subdirectory when codegen is available, enabling just-in-time compilation support. ```cmake add_subdirectory(JIT) ``` -------------------------------- ### JITGraphInterpreter float backend usage Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-backend.md Creates a JITGraphInterpreter backend and passes it to JITCompiler. The graph is recorded before calling compile(). ```cpp auto backend = std::make_unique>(); xad::JITCompiler jit(std::move(backend)); // ... record graph ... jit.compile(); ``` -------------------------------- ### Create a feature branch Source: https://github.com/auto-differentiation/xad/blob/main/CONTRIBUTING.md Create a new feature branch based on main for your changes. ```bash git checkout -b feature/my-changed-main ``` -------------------------------- ### ABool Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit.md Trackable boolean helper used for JIT-recorded comparisons and conditional selection (`If`). Available only when XAD is compiled with XAD_ENABLE_CODEGEN. ```APIDOC ## ABool ### Description Trackable boolean helper used for JIT-recorded comparisons and conditional selection (`If`). ### Availability Only available when XAD is compiled with `XAD_ENABLE_CODEGEN`. ### See Also - [ABool](jit-abool.md) ``` -------------------------------- ### activate Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-compiler.md Sets this instance as the active compiler for the current thread. ```APIDOC ## activate ### Description Sets this instance as the active compiler for the current thread. ### Method void activate() ### Parameters None ### Returns None ``` -------------------------------- ### forward Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-compiler.md Executes the forward pass and fills the output array. ```APIDOC ## forward ### Description Executes the forward pass and fills the output array. ### Method void forward(double* outputs) ### Parameters - **outputs** (double*) - Required - Pointer to the array where the outputs will be stored. ### Returns None ``` -------------------------------- ### Expected output of SparseJacobian sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/SparseJacobian/README.md Deterministic error lines and machine-dependent timings and checksum. The error lines show that sparse and dense Jacobians match exactly for n=10 and n=1000. Timings and checksum vary by machine. ```text n = 10: max |sparse - dense| = 0 (OK) n = 1000: max |sparse - dense| = 0 (OK) median of 11 runs: sparse (3 forward passes): 0.1421 ms dense (1000 adjoint passes): 6.6153 ms checksum (ignore): -42.4038 ``` -------------------------------- ### compile Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-compiler.md Compiles the currently recorded graph with the current backend. ```APIDOC ## compile ### Description Compiles the currently recorded graph with the current backend. ### Method void compile() ### Parameters None ### Returns None ``` -------------------------------- ### registerOutputs Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Convenience functions to register multiple variables as outputs. ```APIDOC ## registerOutputs ### Description Convenience functions to register all variables in a vector or a range as outputs. ### Method registerOutputs ### Parameters - **v** (std::vector&) - Required - Vector of variables to register. - **first** (It) - Required - Iterator to the first element of the range. - **last** (It) - Required - Iterator to one past the last element of the range. ``` -------------------------------- ### setBackend Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-compiler.md Replaces the execution backend. Requires recompilation of the current graph. ```APIDOC ## setBackend ### Description Replaces the execution backend. Requires recompilation of the current graph. ### Method void setBackend(std::unique_ptr backend) ### Parameters - **backend** (std::unique_ptr) - Required - The new backend to use. ### Returns None ``` -------------------------------- ### computeAdjointsTo Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Works like computeAdjoints, but stops rolling back the adjoints at a given position. ```APIDOC ## computeAdjointsTo ### Description Works like computeAdjoints, but stops rolling back the adjoints at the given position in the tape. ### Method computeAdjointsTo ### Parameters - **pos** (position_type) - Required - The position at which to stop rolling back adjoints. ``` -------------------------------- ### JITGraphInterpreter Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-backend.md Reference backend that interprets the graph directly. Intended as a correctness reference, a simple fallback backend, and a baseline for testing and debugging. ```APIDOC ## JITGraphInterpreter ### Description Reference backend that interprets the graph directly. It is mainly intended as a correctness reference implementation, a simple fallback backend, and a baseline for testing and debugging. ### Example Usage For double backend: ```cpp auto backend = std::make_unique>(); xad::JITCompiler jit(std::move(backend)); // ... record graph ... jit.compile(); ``` For float backend: ```cpp auto backend = std::make_unique>(); xad::JITCompiler jit(std::move(backend)); // ... record graph ... jit.compile(); ``` ``` -------------------------------- ### CMake sample definition for Jacobian Source: https://github.com/auto-differentiation/xad/blob/main/samples/Jacobian/CMakeLists.txt Adds the Jacobian sample to the build using the xad_add_sample CMake function, specifying main.cpp as the source file. ```cmake xad_add_sample(Jacobian SOURCES main.cpp) ``` -------------------------------- ### registerInputs Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-compiler.md Registers multiple independent variables as graph inputs. ```APIDOC ## registerInputs ### Description Registers multiple independent variables as graph inputs. ### Method void registerInputs(AD* inputs, std::size_t count) ### Parameters - **inputs** (AD*) - Required - Pointer to the array of independent variables. - **count** (std::size_t) - Required - Number of inputs to register. ### Returns None ``` -------------------------------- ### scalbn Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/math.md Calculates arg * pow(FLT_RADIX, exp). ```APIDOC ## scalbn ### Description Calculates `arg * pow(FLT_RADIX, exp)`. ### Signature `T scalbn(T arg, int exp)` ### Parameters - **arg** (T) - The value to be scaled. - **exp** (int) - The exponent. ### Returns - **T** - The scaled value. ``` -------------------------------- ### Expected output of LogisticRegression sample Source: https://github.com/auto-differentiation/xad/blob/main/samples/LogisticRegression/README.md Shows the fixed structure of the sample's output. Exact gradients and loss values may vary between C++ standard-library implementations; the ellipses indicate omitted lines. ```text Dataset: 1000 points, 10 features adjoint sweep at w = 0 loss = 0.693147 gradients dL/dw: w[ 0] = 0.088978 w[ 1] = -0.054788 ... finite-difference check index adjoint grad FD grad rel. diff 0 0.088978 0.088978 2.336e-10 1 -0.054788 -0.054788 1.148e-09 gradient descent (lr = 0.1, 20 iterations) iter 0 loss = 0.693147 ... iter 19 loss = 0.497008 ``` -------------------------------- ### JITBackend Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/jit-backend.md Abstract base class for JIT execution backends. Provides the interface for compiling and executing a JITGraph, including forward and backward passes. ```APIDOC ## JITBackend ### Description Abstract base class for JIT execution backends. The `Scalar` template parameter specifies the floating-point type used for computations and must match the type used by `JITCompiler`. ### Methods #### compile `virtual void compile(const JITGraph& graph) = 0;` Prepare the backend for executing the given graph. #### vectorWidth `virtual std::size_t vectorWidth() const = 0;` Returns the number of parallel evaluations per execution (1 for scalar backends, 4 for AVX2). #### numInputs `virtual std::size_t numInputs() const = 0;` Return the number of inputs in the compiled graph. #### numOutputs `virtual std::size_t numOutputs() const = 0;` Return the number of outputs in the compiled graph. #### setInput `virtual void setInput(std::size_t inputIndex, const Scalar* values) = 0;` Set input values for an input variable. The `values` array must contain `vectorWidth()` elements. #### forward `virtual void forward(Scalar* outputs) = 0;` Run a forward pass. The `outputs` array must have space for `numOutputs() * vectorWidth()` elements. #### forwardAndBackward `virtual void forwardAndBackward(Scalar* outputs, Scalar* inputGradients) = 0;` Run forward and backward passes combined. The `outputs` array must have space for `numOutputs() * vectorWidth()` elements, and `inputGradients` must have space for `numInputs() * vectorWidth()` elements. #### reset `virtual void reset() = 0;` Reset any cached backend state. ``` -------------------------------- ### haveCallbacks Source: https://github.com/auto-differentiation/xad/blob/main/docs/ref/tape.md Checks if there have been any checkpoint callbacks registered by pushCallback. ```APIDOC ## haveCallbacks ### Description Checks if there have been any checkpoint callbacks registered by `pushCallback`. ### Method bool ### Signature `bool haveCallbacks() const` ### Parameters None ### Returns - **bool** - True if there are any checkpoint callbacks registered. ```