Sleipnir C++ API
Loading...
Searching...
No Matches
expression.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <stdint.h>
6
7#include <algorithm>
8#include <array>
9#include <concepts>
10#include <cstddef>
11#include <memory>
12#include <string_view>
13#include <tuple>
14#include <type_traits>
15#include <utility>
16
17#include <gch/small_vector.hpp>
18
19#include "sleipnir/autodiff/expression_type.hpp"
20#include "sleipnir/util/force_inline.hpp"
21#include "sleipnir/util/function_ref.hpp"
22#include "sleipnir/util/intrusive_shared_ptr.hpp"
23#include "sleipnir/util/pool.hpp"
24
25namespace slp::detail {
26
27#ifdef _WIN32
28inline constexpr bool USE_POOL_ALLOCATOR = false;
29#else
30inline constexpr bool USE_POOL_ALLOCATOR = true;
31#endif
32
33template <typename Scalar>
34struct Expression;
35
39template <typename Scalar>
40using ExpressionPtr = IntrusiveSharedPtr<Expression<Scalar>>;
41
47template <typename Derived, typename... Args>
48static ExpressionPtr<typename Derived::Scalar> make_expression_ptr(
49 Args&&... args) {
50 if constexpr (USE_POOL_ALLOCATOR) {
51 return allocate_intrusive_shared<Derived>(global_pool_allocator<Derived>(),
52 std::forward<Args>(args)...);
53 } else {
54 return make_intrusive_shared<Derived>(std::forward<Args>(args)...);
55 }
56}
57
58template <typename Scalar, ExpressionType Type>
59struct BinaryMinusExpression;
60
61template <typename Scalar, ExpressionType Type>
62struct BinaryPlusExpression;
63
64template <typename Scalar, ExpressionType Type>
65struct DivExpression;
66
67template <typename Scalar, ExpressionType Type>
68struct MultExpression;
69
70template <typename Scalar, ExpressionType Type>
71struct UnaryMinusExpression;
72
81template <template <typename, ExpressionType> typename Derived, typename Scalar,
82 typename... Args>
83SLEIPNIR_FORCE_INLINE ExpressionPtr<Scalar> make_typed_expression_ptr(
84 ExpressionType type, const Args&... args) {
85 using enum ExpressionType;
86
87 if (type == PARAMETER) {
88 return make_expression_ptr<Derived<Scalar, PARAMETER>>(args...);
89 } else if (type == LINEAR) {
90 return make_expression_ptr<Derived<Scalar, LINEAR>>(args...);
91 } else if (type == QUADRATIC) {
92 return make_expression_ptr<Derived<Scalar, QUADRATIC>>(args...);
93 } else {
94 return make_expression_ptr<Derived<Scalar, NONLINEAR>>(args...);
95 }
96}
97
102template <typename Scalar>
103ExpressionPtr<Scalar> constant_ptr(Scalar value);
104
114template <typename Value, typename Scalar>
115Value lit(Scalar value) {
116 if constexpr (std::same_as<Value, Scalar>) {
117 return value;
118 } else {
119 return constant_ptr(value);
120 }
121}
122
126template <typename Scalar_>
130
133
136
140
151
154
161
163 constexpr Expression() = default;
164
168 explicit constexpr Expression(Scalar value) : val{value}, is_leaf{1} {}
169
170 virtual ~Expression() = default;
171
176 SLEIPNIR_FORCE_INLINE constexpr bool is_constant(Scalar constant) const {
177 return type() == ExpressionType::CONSTANT && val == constant;
178 }
179
185 const ExpressionPtr<Scalar>& rhs) {
186 using enum ExpressionType;
187
188 // Prune expression
189 if (lhs->is_constant(Scalar(0))) {
190 // Return zero, which lhs currently is
191 return lhs;
192 } else if (rhs->is_constant(Scalar(0))) {
193 // Return zero, which rhs currently is
194 return rhs;
195 } else if (lhs->is_constant(Scalar(1))) {
196 // Return rhs unmodified
197 return rhs;
198 } else if (rhs->is_constant(Scalar(1))) {
199 // Return lhs unmodified
200 return lhs;
201 }
202
203 // Evaluate constant
204 if (lhs->type() == CONSTANT && rhs->type() == CONSTANT) {
205 return constant_ptr(lhs->val * rhs->val);
206 }
207
208 // Evaluate expression type. Scaling by a constant or parameter keeps the
209 // other operand's type.
210 auto type = NONLINEAR;
211 if (lhs->type() <= PARAMETER || rhs->type() <= PARAMETER) {
212 type = std::max(lhs->type(), rhs->type());
213 } else if (lhs->type() == LINEAR && rhs->type() == LINEAR) {
214 type = QUADRATIC;
215 }
217 }
218
224 const ExpressionPtr<Scalar>& rhs) {
225 using enum ExpressionType;
226
227 // Prune expression
228 if (lhs->is_constant(Scalar(0))) {
229 // Return zero, which lhs currently is
230 return lhs;
231 } else if (rhs->is_constant(Scalar(1))) {
232 // Return lhs unmodified
233 return lhs;
234 }
235
236 // Evaluate constant
237 if (lhs->type() == CONSTANT && rhs->type() == CONSTANT) {
238 return constant_ptr(lhs->val / rhs->val);
239 }
240
241 // Evaluate expression type. Dividing by a constant or parameter keeps the
242 // numerator's type.
243 auto type = rhs->type() <= PARAMETER ? std::max(lhs->type(), rhs->type())
244 : NONLINEAR;
246 }
247
253 const ExpressionPtr<Scalar>& rhs) {
254 using enum ExpressionType;
255
256 // Prune expression. We check for nullptr because operator+ is used in
257 // adjoint accumulation, and child nodes can be null.
258 if (lhs == nullptr || lhs->is_constant(Scalar(0))) {
259 // Return rhs unmodified
260 return rhs;
261 } else if (rhs == nullptr || rhs->is_constant(Scalar(0))) {
262 // Return lhs unmodified
263 return lhs;
264 }
265
266 // Evaluate constant
267 if (lhs->type() == CONSTANT && rhs->type() == CONSTANT) {
268 return constant_ptr(lhs->val + rhs->val);
269 }
270
271 auto type = std::max(lhs->type(), rhs->type());
273 rhs);
274 }
275
284
290 const ExpressionPtr<Scalar>& rhs) {
291 using enum ExpressionType;
292
293 // Prune expression
294 if (lhs->is_constant(Scalar(0))) {
295 if (rhs->is_constant(Scalar(0))) {
296 // Return zero, which rhs currently is
297 return rhs;
298 } else {
299 // Return rhs negated
300 return -rhs;
301 }
302 } else if (rhs->is_constant(Scalar(0))) {
303 // Return lhs unmodified
304 return lhs;
305 }
306
307 // Evaluate constant
308 if (lhs->type() == CONSTANT && rhs->type() == CONSTANT) {
309 return constant_ptr(lhs->val - rhs->val);
310 }
311
312 auto type = std::max(lhs->type(), rhs->type());
314 rhs);
315 }
316
321 using enum ExpressionType;
322
323 // Prune expression
324 if (lhs->is_constant(Scalar(0))) {
325 // Return zero, which lhs currently is
326 return lhs;
327 }
328
329 // Evaluate constant
330 if (lhs->type() == CONSTANT) {
331 return constant_ptr(-lhs->val);
332 }
333
335 lhs);
336 }
337
342 return lhs;
343 }
344
348 virtual void visit_args(
350 }
351
357 virtual Scalar value() const = 0;
358
363 virtual ExpressionType type() const = 0;
364
368 virtual std::string_view name() const = 0;
369
375 virtual bool has_constant_partials() const { return true; }
376
378 virtual void accumulate_adjoints() const {}
379
381 virtual void accumulate_adjoints_expr() const {}
382};
383
405template <template <typename, ExpressionType> typename Derived, typename Scalar,
406 ExpressionType Type, size_t NumArgs>
409 static constexpr bool CONSTANT_PARTIALS = false;
410
412 std::array<ExpressionPtr<Scalar>, NumArgs> args;
413
417 template <typename... Args>
418 requires(sizeof...(Args) == NumArgs &&
419 (std::same_as<std::remove_cvref_t<Args>, ExpressionPtr<Scalar>> &&
420 ...))
421 explicit constexpr NonLeafExpression(Args&&... args)
422 : args{std::forward<Args>(args)...} {}
423
428 function_ref<void(Expression<Scalar>* arg)> func) const final {
429 [&]<size_t... Is>(std::index_sequence<Is...>) {
430 (func(args[Is].get()), ...);
431 }(std::make_index_sequence<NumArgs>{});
432 }
433
438 return [&]<size_t... Is>(std::index_sequence<Is...>) {
439 return static_cast<const Self&>(*this).eval(args[Is]->val...);
440 }(std::make_index_sequence<NumArgs>{});
441 }
442
446 ExpressionType type() const final { return Type; }
447
451 std::string_view name() const final { return Self::NAME; }
452
458 bool has_constant_partials() const final { return Self::CONSTANT_PARTIALS; }
459
462 [&]<size_t... Is>(std::index_sequence<Is...>) {
463 // Evaluate gradients
464 std::array<Scalar, NumArgs> g{};
465 grad(g, this->val, args[Is]->val...);
466
467 // Accumulate adjoints
468 ((args[Is]->adj += this->adj * g[Is]), ...);
469 }(std::make_index_sequence<NumArgs>{});
470 }
471
474 [&]<size_t... Is>(std::index_sequence<Is...>) {
475 // If the partial derivatives are constant, evaluate them as Scalars
476 // instead of building them as expressions
477 if constexpr (Self::CONSTANT_PARTIALS) {
478 // Evaluate gradients
479 std::array<Scalar, NumArgs> g{};
480 grad(g, this->val, args[Is]->val...);
481
482 // Accumulate adjoints
483 (
484 [&] {
485 // Fold the adjoint accumulation expression if the gradient is
486 // 1, -1, or 0
487 if (g[Is] == Scalar(1)) {
488 args[Is]->adj_expr += this->adj_expr;
489 } else if (g[Is] == Scalar(-1)) {
490 args[Is]->adj_expr += -this->adj_expr;
491 } else if (g[Is] != Scalar(0)) {
492 args[Is]->adj_expr += this->adj_expr * constant_ptr(g[Is]);
493 }
494 }(),
495 ...);
496 } else {
497 // Evaluate gradients
498 std::array<ExpressionPtr<Scalar>, NumArgs> g;
499 grad(g, ExpressionPtr<Scalar>{const_cast<NonLeafExpression*>(this)},
500 args[Is]...);
501
502 // Accumulate adjoints
503 (
504 [&] {
505 // A null partial derivative is structurally zero
506 if (g[Is] != nullptr) {
507 args[Is]->adj_expr += this->adj_expr * g[Is];
508 }
509 }(),
510 ...);
511 }
512 }(std::make_index_sequence<NumArgs>{});
513 }
514
515 private:
516 using Self = Derived<Scalar, Type>;
517
530 template <typename Value, typename... Args>
531 void grad(std::array<Value, NumArgs>& g, const Value& val,
532 const Args&... x) const {
533 if constexpr (requires(const Self& expr) {
534 expr.eval_grad(g, val, x...);
535 }) {
536 static_cast<const Self&>(*this).eval_grad(g, val, x...);
537 }
538 }
539};
540
551template <template <typename, ExpressionType> typename Derived, typename Scalar,
552 typename... Args>
553ExpressionPtr<Scalar> fold_or_make(const Args&... args) {
554 using enum ExpressionType;
555
556 if (((args->type() == CONSTANT) && ...)) {
557 Scalar val = Derived<Scalar, NONLINEAR>::eval(args->val...);
558 if constexpr (sizeof...(Args) == 1) {
559 const auto& x = std::get<0>(std::forward_as_tuple(args...));
560 if (x->val == val) {
561 return x;
562 }
563 }
564 return constant_ptr(val);
565 }
566
567 if (((args->type() <= PARAMETER) && ...)) {
568 return make_expression_ptr<Derived<Scalar, PARAMETER>>(args...);
569 } else {
570 return make_expression_ptr<Derived<Scalar, NONLINEAR>>(args...);
571 }
572}
573
578template <typename Scalar, ExpressionType Type>
580 : NonLeafExpression<BinaryMinusExpression, Scalar, Type, 2> {
581 using BinaryMinusExpression::NonLeafExpression::NonLeafExpression;
582
584 static constexpr std::string_view NAME = "binary minus";
585
587 static constexpr bool CONSTANT_PARTIALS = true;
588
589 static Scalar eval(Scalar lhs, Scalar rhs) { return lhs - rhs; }
590
591 template <typename Value>
592 static void eval_grad(std::array<Value, 2>& g,
593 [[maybe_unused]] const Value& val,
594 [[maybe_unused]] const Value& lhs,
595 [[maybe_unused]] const Value& rhs) {
596 g[0] = lit<Value>(Scalar(1));
597 g[1] = lit<Value>(Scalar(-1));
598 }
599};
600
605template <typename Scalar, ExpressionType Type>
607 : NonLeafExpression<BinaryPlusExpression, Scalar, Type, 2> {
608 using BinaryPlusExpression::NonLeafExpression::NonLeafExpression;
609
611 static constexpr std::string_view NAME = "binary plus";
612
614 static constexpr bool CONSTANT_PARTIALS = true;
615
616 static Scalar eval(Scalar lhs, Scalar rhs) { return lhs + rhs; }
617
618 template <typename Value>
619 static void eval_grad(std::array<Value, 2>& g,
620 [[maybe_unused]] const Value& val,
621 [[maybe_unused]] const Value& lhs,
622 [[maybe_unused]] const Value& rhs) {
623 g[0] = lit<Value>(Scalar(1));
624 g[1] = lit<Value>(Scalar(1));
625 }
626};
627
632template <typename Scalar, ExpressionType Type>
633struct DivExpression final : NonLeafExpression<DivExpression, Scalar, Type, 2> {
634 using DivExpression::NonLeafExpression::NonLeafExpression;
635
637 static constexpr std::string_view NAME = "division";
638
639 static Scalar eval(Scalar lhs, Scalar rhs) { return lhs / rhs; }
640
641 template <typename Value>
642 static void eval_grad(std::array<Value, 2>& g,
643 [[maybe_unused]] const Value& val, const Value& lhs,
644 const Value& rhs) {
645 g[0] = lit<Value>(Scalar(1)) / rhs;
646 g[1] = -lhs / (rhs * rhs);
647 }
648};
649
654template <typename Scalar, ExpressionType Type>
656 : NonLeafExpression<MultExpression, Scalar, Type, 2> {
657 using MultExpression::NonLeafExpression::NonLeafExpression;
658
660 static constexpr std::string_view NAME = "multiplication";
661
662 static Scalar eval(Scalar lhs, Scalar rhs) { return lhs * rhs; }
663
664 template <typename Value>
665 static void eval_grad(std::array<Value, 2>& g,
666 [[maybe_unused]] const Value& val, const Value& lhs,
667 const Value& rhs) {
668 g[0] = rhs;
669 g[1] = lhs;
670 }
671};
672
677template <typename Scalar, ExpressionType Type>
679 : NonLeafExpression<UnaryMinusExpression, Scalar, Type, 1> {
680 using UnaryMinusExpression::NonLeafExpression::NonLeafExpression;
681
683 static constexpr std::string_view NAME = "unary minus";
684
686 static constexpr bool CONSTANT_PARTIALS = true;
687
688 static Scalar eval(Scalar lhs) { return -lhs; }
689
690 template <typename Value>
691 static void eval_grad(std::array<Value, 1>& g,
692 [[maybe_unused]] const Value& val,
693 [[maybe_unused]] const Value& lhs) {
694 g[0] = lit<Value>(Scalar(-1));
695 }
696};
697
702template <typename Scalar>
703constexpr void inc_ref_count(Expression<Scalar>* expr) {
704 ++expr->ref_count;
705}
706
712template <typename Scalar>
713void deallocate_expression(Expression<Scalar>* expr) {
714 // If a deeply nested tree is being deallocated all at once, calling the
715 // Expression destructor when expr's refcount reaches zero can cause a stack
716 // overflow. Instead, we iterate over its children to decrement their
717 // refcounts and deallocate them.
718 gch::small_vector<Expression<Scalar>*> stack;
719 stack.emplace_back(expr);
720
721 // Decrements a child's refcount and enqueues it for deallocation if it
722 // reaches zero
723 auto release = [&stack](Expression<Scalar>* child) {
724 if (--child->ref_count == 0) {
725 stack.emplace_back(child);
726 }
727 };
728
729 while (!stack.empty()) {
730 auto elem = stack.back();
731 stack.pop_back();
732
733 if (elem->adj_expr != nullptr) {
734 release(elem->adj_expr.get());
735 }
736 elem->visit_args(release);
737
738 // Not calling the destructor here is safe because it only decrements
739 // refcounts, which was already done above
740 if constexpr (USE_POOL_ALLOCATOR) {
741 auto alloc = global_pool_allocator<Expression<Scalar>>();
742 std::allocator_traits<decltype(alloc)>::deallocate(alloc, elem, 1);
743 } else {
744 operator delete(elem);
745 }
746 }
747}
748
753template <typename Scalar>
754constexpr void dec_ref_count(Expression<Scalar>* expr) {
755 if (--expr->ref_count == 0) {
756 deallocate_expression(expr);
757 }
758}
759
763template <typename Scalar>
768 explicit constexpr ConstantExpression(Scalar value)
769 : Expression<Scalar>{value} {}
770
771 Scalar value() const override { return this->val; }
772
773 ExpressionType type() const override { return ExpressionType::CONSTANT; }
774
775 std::string_view name() const override { return "constant"; }
776};
777
778template <typename Scalar>
779ExpressionPtr<Scalar> constant_ptr(Scalar value) {
781}
782
786template <typename Scalar>
790
796
797 Scalar value() const override { return this->val; }
798
799 ExpressionType type() const override { return ExpressionType::LINEAR; }
800
801 std::string_view name() const override { return "decision variable"; }
802};
803
810template <typename Scalar>
814
818 explicit constexpr ParameterExpression(Scalar value)
819 : Expression<Scalar>{value} {}
820
821 Scalar value() const override { return this->val; }
822
823 ExpressionType type() const override { return ExpressionType::PARAMETER; }
824
825 std::string_view name() const override { return "parameter"; }
826};
827
828} // namespace slp::detail
Definition intrusive_shared_ptr.hpp:27
Definition function_ref.hpp:13
Definition expression.hpp:580
static constexpr bool CONSTANT_PARTIALS
Whether the partial derivatives are the same at every argument value.
Definition expression.hpp:587
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:584
Definition expression.hpp:607
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:611
static constexpr bool CONSTANT_PARTIALS
Whether the partial derivatives are the same at every argument value.
Definition expression.hpp:614
Definition expression.hpp:764
ExpressionType type() const override
Definition expression.hpp:773
Scalar value() const override
Definition expression.hpp:771
std::string_view name() const override
Definition expression.hpp:775
constexpr ConstantExpression(Scalar value)
Definition expression.hpp:768
Definition expression.hpp:787
Scalar value() const override
Definition expression.hpp:797
std::string_view name() const override
Definition expression.hpp:801
constexpr DecisionVariableExpression(Scalar value)
Definition expression.hpp:794
ExpressionType type() const override
Definition expression.hpp:799
constexpr DecisionVariableExpression()
Constructs a decision variable expression with a value of zero.
Definition expression.hpp:789
Definition expression.hpp:633
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:637
Definition expression.hpp:127
Scalar val
The value of the expression node.
Definition expression.hpp:132
virtual Scalar value() const =0
ExpressionPtr< Scalar > adj_expr
Definition expression.hpp:139
friend ExpressionPtr< Scalar > operator-(const ExpressionPtr< Scalar > &lhs)
Definition expression.hpp:320
virtual void accumulate_adjoints() const
Accumulates the child adjoints as Scalars.
Definition expression.hpp:378
uint32_t is_leaf
Definition expression.hpp:160
uint32_t ref_count
Reference count for intrusive shared pointer.
Definition expression.hpp:153
friend ExpressionPtr< Scalar > operator+(const ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:252
int32_t scratch
Definition expression.hpp:150
Scalar adj
The adjoint of the expression node, used during autodiff.
Definition expression.hpp:135
constexpr Expression()=default
Constructs a constant expression with a value of zero.
Scalar_ Scalar
Scalar type alias.
Definition expression.hpp:129
virtual ExpressionType type() const =0
friend ExpressionPtr< Scalar > operator/(const ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:223
friend ExpressionPtr< Scalar > operator-(const ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:289
friend ExpressionPtr< Scalar > operator*(const ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:184
virtual std::string_view name() const =0
virtual void accumulate_adjoints_expr() const
Accumulates the child adjoints as Expressions.
Definition expression.hpp:381
virtual void visit_args(function_ref< void(Expression< Scalar > *arg)> func) const
Definition expression.hpp:348
SLEIPNIR_FORCE_INLINE constexpr bool is_constant(Scalar constant) const
Definition expression.hpp:176
virtual bool has_constant_partials() const
Definition expression.hpp:375
friend ExpressionPtr< Scalar > operator+=(ExpressionPtr< Scalar > &lhs, const ExpressionPtr< Scalar > &rhs)
Definition expression.hpp:280
constexpr Expression(Scalar value)
Definition expression.hpp:168
friend ExpressionPtr< Scalar > operator+(const ExpressionPtr< Scalar > &lhs)
Definition expression.hpp:341
Definition expression.hpp:656
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:660
Definition expression.hpp:407
constexpr NonLeafExpression(Args &&... args)
Definition expression.hpp:421
bool has_constant_partials() const final
Definition expression.hpp:458
void accumulate_adjoints() const final
Accumulates the child adjoints as Scalars.
Definition expression.hpp:461
static constexpr bool CONSTANT_PARTIALS
Whether the partial derivatives are the same at every argument value.
Definition expression.hpp:409
ExpressionType type() const final
Definition expression.hpp:446
std::array< ExpressionPtr< Scalar >, NumArgs > args
The arguments in visit_args() order.
Definition expression.hpp:412
void accumulate_adjoints_expr() const final
Accumulates the child adjoints as Expressions.
Definition expression.hpp:473
std::string_view name() const final
Definition expression.hpp:451
void visit_args(function_ref< void(Expression< Scalar > *arg)> func) const final
Definition expression.hpp:427
Scalar value() const final
Definition expression.hpp:437
Definition expression.hpp:811
constexpr ParameterExpression(Scalar value)
Definition expression.hpp:818
ExpressionType type() const override
Definition expression.hpp:823
Scalar value() const override
Definition expression.hpp:821
constexpr ParameterExpression()
Constructs a parameter expression with a value of zero.
Definition expression.hpp:813
std::string_view name() const override
Definition expression.hpp:825
Definition expression.hpp:679
static constexpr std::string_view NAME
The expression's name.
Definition expression.hpp:683
static constexpr bool CONSTANT_PARTIALS
Whether the partial derivatives are the same at every argument value.
Definition expression.hpp:686