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

Add Differentiable CEM solver #329

Merged
merged 35 commits into from
Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from 31 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
31c277d
first implementation of dcem solver
dishank-b Oct 13, 2022
245d80c
dcem optimizer working
dishank-b Oct 14, 2022
11962c6
minor changes in dcem, added tests
dishank-b Oct 17, 2022
d069ee6
online calculatino of n_batch
dishank-b Oct 18, 2022
24d2fa9
initializing LML layer
dishank-b Oct 20, 2022
5632588
dcem working backwards tutorial 2
dishank-b Oct 28, 2022
655ba19
better vectorization in solver
dishank-b Oct 31, 2022
63a04cf
vectoriztion in solve method for itr loop in optimizer class
dishank-b Oct 31, 2022
fd93941
forward pass working perfectly with current set of hyperparams with b…
dishank-b Nov 3, 2022
976fb08
dcem backward unit test passed for one setting
dishank-b Nov 3, 2022
7547504
DCEM backward unit test working, not tested with leo, insanely slow w…
dishank-b Nov 4, 2022
3a22e09
refactoring, removed DcemSolver in favour of solve method in DCEM opt…
dishank-b Nov 4, 2022
89c8b39
correcting circle ci errors
dishank-b Nov 7, 2022
9bf03c4
corrected lml url for requirements.txt
dishank-b Nov 7, 2022
a1064a2
corrected reuirements.txt for lml
dishank-b Nov 7, 2022
c21dc69
removing -e from requirements
dishank-b Nov 8, 2022
c809e94
changing setup.py to install lml
dishank-b Nov 8, 2022
2bbf2db
changing setup.py to add lml
dishank-b Nov 8, 2022
4f3788c
commented dcem_test
dishank-b Nov 8, 2022
0f69df6
unit test working with both gpu, cpu with even less 10-2 error thres …
dishank-b Nov 9, 2022
0592f6f
testing with lml_eps=10-4
dishank-b Nov 10, 2022
7d68639
Revert "testing with lml_eps=10-4"
dishank-b Nov 10, 2022
044e881
reverting the common.py file
dishank-b Nov 10, 2022
769d483
dcem working, name changed from DCem to DCEM
dishank-b Mar 6, 2023
126ee47
removed _all_solve function and chnaged _solve name to _CEM_step
dishank-b Mar 6, 2023
f2ccf4b
changed dcem objective to use error_metric and edit __init files
dishank-b Mar 6, 2023
74a2a5d
dcem working, added dcem tutorial
dishank-b Mar 6, 2023
679dc3b
add lml as third party
dishank-b Mar 6, 2023
fab68be
or black pre-commit hook
dishank-b Mar 6, 2023
f4b345a
removeing abs in loss function since model chnaged test_theseus layer
dishank-b Mar 7, 2023
97c94b6
changes in test_theseus to make it compatible with DCEM
dishank-b Mar 9, 2023
bc32139
minor changes:styling, nits, typehinting, etc.
dishank-b Mar 17, 2023
50ea767
reverted minor changes, corrected test_theseus_layer argument logic f…
dishank-b Mar 20, 2023
ee75e95
using scatter for indexes with temp=None in dcem
dishank-b Mar 21, 2023
947e026
final changes, removing half-complete changes before merge
dishank-b Mar 22, 2023
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
1 change: 1 addition & 0 deletions requirements/dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ mock>=4.0.3
types-mock>=4.0.8
Sphinx==5.0.2
sphinx-rtd-theme==1.0.0
semantic-version==2.10.0
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions requirements/main.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ scikit-sparse>=0.4.5
pytest>=6.2.1
pybind11>=2.7.1
functorch==0.2.1 # > 0.2.1 will install torch1.13, which breaks CUDA 10.2
semantic-version==2.10.0
12 changes: 11 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@
sys.exit(1)


def _format(line):
line = line.split()[-1]
egg_name = line.split("#egg=")[-1]
fragment = line.split("#egg=")[0]
return f"{egg_name} @ {fragment}"


def parse_requirements_file(path):
with open(path) as f:
reqs = []
Expand All @@ -46,7 +53,10 @@ def parse_requirements_file(path):
# installed
continue
line = line.strip()
reqs.append(line)
if line[0] == "-":
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
reqs.append(_format(line))
else:
reqs.append(line.split("==")[0])
return reqs


Expand Down
15 changes: 15 additions & 0 deletions tests/optimizer/nonlinear/test_dcem.py
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import pytest # noqa: F401

# import theseus as th

# from theseus.constants import __FROM_THESEUS_LAYER_TOKEN__
# from .common import run_nonlinear_least_squares_check


# def test_DCEM():
# run_nonlinear_least_squares_check(th.DCEM, {__FROM_THESEUS_LAYER_TOKEN__: True})
25 changes: 18 additions & 7 deletions tests/test_theseus_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def create_qf_theseus_layer(
cost_weight=th.ScaleCostWeight(1.0),
nonlinear_optimizer_cls=th.GaussNewton,
linear_solver_cls=th.CholeskyDenseSolver,
max_iterations=10,
max_iterations=50,
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
use_learnable_error=False,
force_vectorization=False,
):
Expand Down Expand Up @@ -138,7 +138,7 @@ def error_fn(optim_vars, aux_vars):
linear_solver_cls=linear_solver_cls,
max_iterations=max_iterations,
)
assert isinstance(optimizer.linear_solver, linear_solver_cls)
# assert isinstance(optimizer.linear_solver, linear_solver_cls)
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
assert not objective.vectorized

if force_vectorization:
Expand Down Expand Up @@ -203,7 +203,7 @@ def _run_optimizer_test(
print(
f"testing for optimizer {nonlinear_optimizer_cls.__name__}, "
f"cost weight modeled as {cost_weight_model}, "
f"linear solver {linear_solver_cls.__name__} "
f"linear solver {linear_solver_cls.__name__ if linear_solver_cls is not None else None} "
f"learning method {learning_method}"
)

Expand Down Expand Up @@ -236,7 +236,9 @@ def _run_optimizer_test(
max_iterations=max_iterations,
)
layer_ref.to(device)
initial_coefficients = torch.ones(batch_size, 2, device=device) * 0.75
initial_coefficients = torch.ones(batch_size, 2, device=device) * torch.tensor(
[0.75, 7], device=device
)
with torch.no_grad():
input_values = {"coefficients": initial_coefficients}
target_vars, _ = layer_ref.forward(
Expand Down Expand Up @@ -306,6 +308,7 @@ def cost_weight_fn():
pred_vars, info = layer_to_learn.forward(
input_values, optimizer_kwargs=optimizer_kwargs
)

loss0 = F.mse_loss(
pred_vars["coefficients"], target_vars["coefficients"]
).item()
Expand Down Expand Up @@ -335,6 +338,7 @@ def cost_weight_fn():
},
},
)

assert not (
(info.status == th.NonlinearOptimizerStatus.START)
| (info.status == th.NonlinearOptimizerStatus.FAIL)
Expand Down Expand Up @@ -378,7 +382,7 @@ def cost_weight_fn():
optimizer.step()

loss_ratio = mse_loss.item() / loss0
print("Loss: ", mse_loss.item(), ". Loss ratio: ", loss_ratio)
print("Iteration: ", i, "Loss: ", mse_loss.item(), ". Loss ratio: ", loss_ratio)
if loss_ratio < loss_ratio_target:
solved = True
break
Expand All @@ -404,7 +408,7 @@ def _solver_can_be_run(lin_solver_cls):


@pytest.mark.parametrize(
"nonlinear_optim_cls", [th.Dogleg, th.GaussNewton, th.LevenbergMarquardt]
"nonlinear_optim_cls", [th.Dogleg, th.GaussNewton, th.LevenbergMarquardt, th.DCEM]
)
@pytest.mark.parametrize(
"lin_solver_cls",
Expand All @@ -414,6 +418,7 @@ def _solver_can_be_run(lin_solver_cls):
th.CholmodSparseSolver,
th.LUCudaSparseSolver,
th.BaspachoSparseSolver,
None,
],
)
@pytest.mark.parametrize("use_learnable_error", [True, False])
Expand All @@ -436,15 +441,21 @@ def test_backward(
and learning_method not in "leo",
},
th.Dogleg: {},
th.DCEM: {},
}[nonlinear_optim_cls]
if learning_method == "leo":
if lin_solver_cls not in [th.CholeskyDenseSolver, th.LUDenseSolver]:
# other solvers don't support sampling from system's covariance
return
if nonlinear_optim_cls == th.Dogleg:
return # LEO not working with Dogleg
if nonlinear_optim_cls == th.DCEM:
return
if nonlinear_optim_cls == th.Dogleg and lin_solver_cls != th.CholeskyDenseSolver:
return
if nonlinear_optim_cls == th.DCEM and lin_solver_cls is not None:
return

# test both vectorization on/off
force_vectorization = torch.rand(1).item() > 0.5
_run_optimizer_test(
Expand All @@ -455,7 +466,7 @@ def test_backward(
use_learnable_error=use_learnable_error,
force_vectorization=force_vectorization,
learning_method=learning_method,
max_iterations=10,
max_iterations=10 if nonlinear_optim_cls != th.DCEM else 50,
lr=1.0
if nonlinear_optim_cls == th.Dogleg and not torch.cuda.is_available()
else 0.075,
Expand Down
1 change: 1 addition & 0 deletions theseus/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
BackwardMode,
Dogleg,
GaussNewton,
DCEM,
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
LevenbergMarquardt,
NonlinearLeastSquares,
NonlinearOptimizerInfo,
Expand Down
2 changes: 2 additions & 0 deletions theseus/optimizer/nonlinear/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

from .dogleg import Dogleg
from .dcem import DCEM
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
from .gauss_newton import GaussNewton
from .levenberg_marquardt import LevenbergMarquardt
from .nonlinear_least_squares import NonlinearLeastSquares
Expand Down
Loading