Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs] add section and example on common subexpression elimination #3879

Merged
merged 3 commits into from
Nov 13, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions docs/src/manual/nonlinear.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,53 @@ julia> sin(sin(1.0))
0.7456241416655579
```

## Common subexpressions

JuMP does not perform common subexpression elimination. Instead, if you re-use
odow marked this conversation as resolved.
Show resolved Hide resolved
an expression in multiple places, JuMP will insert a copy of the expression.

JuMP's lack of common subexpression elimination is a common cause of performance
problems, particularly in nonlinear models with a pattern like
`sum(t / common_term for t in terms)`. One example is the logistic loss:

```jldoctest
julia> model = Model();

julia> @variable(model, x[1:2]);

julia> @expression(model, expr, sum(exp.(x)))
0.0 + exp(x[2]) + exp(x[1])

julia> @objective(model, Min, sum(exp(x[i]) / expr for i in 1:2))
(exp(x[1]) / (0.0 + exp(x[2]) + exp(x[1]))) + (exp(x[2]) / (0.0 + exp(x[2]) + exp(x[1])))
```
In this model, JuMP will compute the value (and derivatives) of the denominator
twice, without realizing that it is the same expression.

As a work-around, create a new [`@variable`](@ref) and use an `==`
[`@constraint`](@ref) to constrain the value of the variable to the
subexpression.

```jldoctest
julia> model = Model();

julia> @variable(model, x[1:2]);

julia> @variable(model, expr);

julia> @constraint(model, expr == sum(exp.(x)))
expr - (0.0 + exp(x[2]) + exp(x[1])) = 0

julia> @objective(model, Min, sum(exp(x[i]) / expr for i in 1:2))
(exp(x[1]) / expr) + (exp(x[2]) / expr)
```

The reason JuMP does not perform common subexpression elimination automatically
is for simplicity, and because there is a trade-off: for simple expressions, the
extra complexity of detecting and merging common subexpressions may outweigh
the cost of computing them independently. Instead, we leave it to the user to
decide which expressions to extract as common subexpressions.

## Automatic differentiation

JuMP computes first- and second-order derivatives using sparse reverse-mode
Expand Down
Loading