Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
fully_differentiable_skeleton_error_function.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8#pragma once
9
12
13#include <Eigen/SparseCore>
14#include <vector>
15
16namespace momentum {
17
18// An error function which can compute the gradients wrt all its inputs.
19// For example, a "normal" position error function can compute the gradient
20// of the error wrt the solved modelParameters. A "FullyDifferentiable"
21// error function also knows how to compute the derivative of the gradient
22// wrt the per-constraint weights, the per-constraint targets, etc.
23//
24// To make this work, we need a mechanism to specify which inputs we can
25// differentiate wrt. Thus the inputs()/getInput()/setInput() stuff below.
26// This design is a bit "string-heavy" but ensures that we can use the various
27// derivatives in code that doesn't know a priori which inputs a given
28// constraint has.
29//
30// Note that the resulting inputs are all specified as Eigen::VectorXf. This
31// tends to mean that the resulting error functions are going to operate on
32// big homogenous Tensor types instead of the mixed-struct types like
33// MarkerErrorFunction uses.
34template <typename T>
36 public:
38
39 [[nodiscard]] virtual const char* name() const = 0;
40
41 // Get a list of all the differentiable inputs for this error function
42 // (excluding the modelParameters).
43 [[nodiscard]] virtual std::vector<std::string> inputs() const = 0;
44
45 // Get the current input values. A given input will be unrolled into a flat vector,
46 // so, for example, if the input was an n x 3 vector of constraint targets, getInput
47 // would return a (3n x 1) VectorXf with the targets packed (t1x t1y t1z t2x t2y t2z ...)
48 [[nodiscard]] Eigen::VectorX<T> getInput(const std::string& name) const;
49 void getInput(const std::string& name, Eigen::Ref<Eigen::VectorX<T>> value) const;
50
51 // Efficiently get the size of the input (e.g., getInput(name).size()).
52 [[nodiscard]] virtual Eigen::Index getInputSize(const std::string& name) const = 0;
53
54 // Set the current input values:
55 void setInput(const std::string& name, Eigen::Ref<const Eigen::VectorX<T>> value);
56
57 // Compute the quantity
58 // d/dInput(dE/dTheta) . v
59 // where dE/dTheta is the gradient of the energy computed in getGradient.
60 // By applying the dot product inside this function we avoid dealing
61 // with tensor types, and it is possible to compute very efficiently
62 // in reverse-mode differentiation such as used by PyTorch.
63 //
64 // Note that because v is a constant here, we can rewrite this as
65 // d/dInput(dE/dTheta . v)
66 // Now it's a lot easier to understand (it's the derivative wrt the given input of a scalar,
67 // no tensors required) and very amenable to autodiff as described below.
68 virtual Eigen::VectorX<T> d_gradient_d_input_dot(
69 const std::string& inputName,
70 const ModelParametersT<T>& params,
71 const SkeletonStateT<T>& state,
72 Eigen::Ref<const Eigen::VectorX<T>> inputVec) = 0;
73
74 protected:
75 virtual void getInputImp(const std::string& name, Eigen::Ref<Eigen::VectorX<T>> value) const = 0;
76 virtual void setInputImp(const std::string& name, Eigen::Ref<const Eigen::VectorX<T>> value) = 0;
77
78 // Notes on implementing d_gradient_d_input_dot: After some experimentation, I have settled on the
79 // following procedure for implementing the d_gradient_d_input_dot() function. By using ceres
80 // autodiff, we can compute the derivatives for all the inputs without having to hand-implement
81 // them all.
82 //
83 // Note that I spent some time trying to convince ceres autodiff to compute both getGradient() and
84 // d_gradient_d_input_dot() straight from the error function; while I still think that might be
85 // possible it gets really nasty. This is partly because Ceres isn't really engineered to deal
86 // with second derivatives (you can do it with jets of jets but the tooling gets pretty poor) and
87 // partly because getting it to respect the right sparsity patterns gets really complicated.
88 //
89 // 1. For a typical constraint like a projection constraint, the inputs are sparse; that is,
90 // a given input only affects a few rows of the residual. For example: a projection constraint
91 // returns a (2n x 1) residual, but a given block of two is only affected by a single weight
92 // w_i, a single offset o_i, and a single target t_i.
93 // 2. Split the gradient function out into a separate function for the ith term of the residual.
94 // Example:
95 // void getGradient(...) {
96 // for (int i = 0; i < constraints.size(); ++i) {
97 // getConstraintGradient(constraints[i], gradient);
98 // }
99 // }
100 // void getContraintGradient(const Constraint& cons, Eigen::Ref<Eigen::VectorX<T>> gradient)
101 // {
102 // ...
103 // }
104 // See e.g. MarkerErrorFunction for an example.
105 // 3. Copy the getConstraintGradient function and make the following changes:
106 // a. Make it template <typename T>, where T will be a ceres::Jet<float, N>.
107 // b. Turn it into getConstraintGradient_dot(..., Eigen::Ref<const Eigen::VectorX<T>> vec).
108 // You will be applying the dot of the computed gradient against the vec as you go, and
109 // the ceres::Jet types will accumulate the derivatives.
110 // c. Pass all the constraint inputs in explicitly, templated on T. That is, the
111 // getConstraintGradient() function above becomes:
112 // template <typename T>
113 // void getConstraintGradient_dot(const T cons_weight,
114 // const Vector3<T> cons_target,
115 // Eigen::Ref<const Eigen::VectorX<T>> vec)
116 // d. Replace all the Vector3f/float with Vector3<T>/T or just use auto and .eval() a lot.
117 // Be wary of Eigen's use of temporaries.
118 // https://eigen.tuxfamily.org/dox/TopicPitfalls.html
119 // This is bad due to Eigen temporaries:
120 // auto foo = bar.cross(baz).normalized();
121 // This is okay:
122 // auto foo = bar.cross(baz).normalized().eval();
123 // e. Replace jointState.getRotationDerivative(...) with getRotationDerivative(jointState,
124 // ...) and
125 // jointState.getScaleDerivative(...) with getScaleDerivative(jointState, ...) from
126 // ceres_utility.h.
127 // f. Add the (grad . vec) dot product in the appropriate spot. There is a function
128 // times_parameterTransform_times_v() in CeresUtility too apply the dot product if your
129 // function computes the gradient wrt the joint parameters instead of the model
130 // parameters.
131 // auto result = T();
132 // for (size_t d = 0; d < 3; d++) {
133 // {
134 // const float grad_jointParam = ...
135 // result += times_parametersTransform_times_v(grad_jointParam, jointIndex *
136 // kParametersPerJoint + d, vec)
137 // }
138 //
139 // 4. Now, implement your d_gradient_d_input_dot() function.
140 // if(input == "target") {
141 // Eigen::VectorX<T> result(constraints.size()*3);
142 // for (int iCons = 0; iCons < constraints.size(); ++iCons)
143 // {
144 // typedef ceres::Jet<float,3> JetType;
145 // const auto& cons = constraints[iCons];
146 // // We don't actually care about the value of the dot product here, we only
147 // // care about the derivative, which is stored in the Jet dual number .v.
148 // auto dotProd = getConstraintGradient_dot<JetType>(JetType(cons.weight),
149 // buildJetVec(cons.target), vec); result.segment<3>(3*iCons) = dotProd.v;
150 // }
151 // }
152 // The tricky part is deciding what you're differentiating wrt to. The variables that are
153 // constant can get converted to jets in this way:
154 // v.cast<JetType>(), JetType(c)
155 // The variables that we _are_ differentiating wrt need to be converted to unit jets, like
156 // this:
157 // buildJetVec(v), JetType(c, 0)
158};
159
160} // namespace momentum
virtual std::vector< std::string > inputs() const =0
virtual Eigen::VectorX< T > d_gradient_d_input_dot(const std::string &inputName, const ModelParametersT< T > &params, const SkeletonStateT< T > &state, Eigen::Ref< const Eigen::VectorX< T > > inputVec)=0
virtual Eigen::Index getInputSize(const std::string &name) const =0
void getInput(const std::string &name, Eigen::Ref< Eigen::VectorX< T > > value) const
void setInput(const std::string &name, Eigen::Ref< const Eigen::VectorX< T > > value)
virtual void setInputImp(const std::string &name, Eigen::Ref< const Eigen::VectorX< T > > value)=0
virtual void getInputImp(const std::string &name, Eigen::Ref< Eigen::VectorX< T > > value) const =0
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
Represents the complete state of a skeleton.