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 1 commit
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
Prev Previous commit
Next Next commit
dcem optimizer working
  • Loading branch information
dishank-b committed Mar 9, 2023
commit 245d80ca42b79f89fb65dabf5fc458c713d3a15e
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
1 change: 1 addition & 0 deletions theseus/optimizer/nonlinear/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# 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
from .gauss_newton import GaussNewton
from .levenberg_marquardt import LevenbergMarquardt
from .nonlinear_least_squares import NonlinearLeastSquares
Expand Down
92 changes: 55 additions & 37 deletions theseus/optimizer/nonlinear/dcem.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ def __init__(
self,
objective: Objective,
ordering: VariableOrdering = None,
n_batch=1,
n_sample=20,
n_elite=10,
n_batch: int = 1,
n_sample: int = 20,
n_elite: int = 10,
lb=None,
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
ub=None,
temp=1.0,
temp: float = 1.0,
normalize: bool = False,
lml_verbose: bool = False,
lml_eps: float = 1e-3,
Expand All @@ -53,6 +53,7 @@ def __init__(
self.normalize = normalize
self.lml_verbose = lml_verbose
self.lml_eps = lml_eps
self.tot_dof = sum([x.dof() for x in self.ordering])
self.sigma = {var.name: torch.ones(var.shape) for var in self.ordering}

def solve(self):
Expand All @@ -62,25 +63,35 @@ def solve(self):

dishank-b marked this conversation as resolved.
Show resolved Hide resolved
idx = 0
for var in self.ordering:
mu[:, idx + var.dof()] = var.tensor
mu[:, slice(idx, idx + var.dof())] = var.tensor
idx += var.dof()

# print("mu", mu)
# print("sigma", self.sigma)

X_samples = []
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
for i in self.n_samples:
for i in range(self.n_samples):
sample = {}
for var in self.ordering:
sample[var.name] = Normal(var.tensor, self.sigma).rsample().to(device)
assert sample[var.name].size() == var.size()
sample[var.name] = (
Normal(var.tensor, self.sigma[var.name]).rsample().to(device)
)
assert sample[var.name].size() == var.shape
sample[var.name] = sample[var.name].contiguous()
if self.lb is not None or self.ub is not None:
sample[var.name] = torch.clamp(sample[var.name], self.lb, self.ub)
# print("sample", sample)
X_samples.append(sample)

# TODO: Check that self.objective.error_squared_norm(X_samples[i]).size() == (n_batch,)
fX = torch.stack(
[self.objective.error_squared_norm(X_samples[i]) for i in self.n_samples],
[
self.objective.error_squared_norm(X_samples[i])
for i in range(self.n_samples)
],
dim=1,
)
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
# print("fx:", fX.shape)

assert fX.shape == (self.n_batch, self.n_samples)

Expand Down Expand Up @@ -113,22 +124,30 @@ def solve(self):
I = I.unsqueeze(2)
# I.shape should be (n_batch, n_sample, 1)

X = torch.zeros(
(self.n_batch, self.n_samples, sum([x.dof() for x in self.ordering]))
)
for i in self.n_samples:
X = torch.zeros((self.n_batch, self.n_samples, self.tot_dof))

for i in range(self.n_samples):
sample = X_samples[i]
idx = 0
for name, var in sample.items():
X[:, i, slice(idx, var.dof())] = var
for var in self.ordering:
X[:, i, slice(idx, idx + var.dof())] = sample[var.name]
idx += var.dof()

assert I.shape[:2] == X.shape[:2]

# print("Samples:", X)
X_I = I * X
old_mu = mu.clone()
mu = torch.sum(X_I, dim=1) / self.n_elite
self.sigma = ((I * (X - mu.unsqueeze(1)) ** 2).sum(dim=1) / self.n_elite).sqrt()

sigma = ((I * (X - mu.unsqueeze(1)) ** 2).sum(dim=1) / self.n_elite).sqrt()
# print("sigma_updates", sigma)

assert sigma.shape == (self.n_batch, self.tot_dof)

idx = 0
for var in self.ordering:
self.sigma[var.name] = sigma[:, slice(idx, idx + var.dof())]
idx += var.dof()

# not sure about the detach
return mu - old_mu.detach()
Expand All @@ -141,8 +160,8 @@ def __init__(
cem_solver: Optional[abc.ABC] = DCemSolver,
n_batch: int = 1,
n_sample: int = 20,
n_elite: int = 10,
n_iter: int = 10,
n_elite: int = 5,
n_iter: int = 50,
temp: float = 1.0,
lb=None,
ub=None,
Expand All @@ -151,20 +170,11 @@ def __init__(
lml_verbose: bool = False,
lml_eps: float = 1e-3,
normalize: bool = True,
iter_eps=1e-4,
iter_eps: float = 1e-4,
**kwargs,
) -> None:
super().__init__(objective, vectorize=Vectorize, **kwargs)
self.params = NonlinearOptimizerParams(
n_batch,
n_sample,
n_elite,
n_iter,
temp,
lb,
ub,
iter_eps,
)
self.params = NonlinearOptimizerParams(iter_eps, iter_eps * 100, n_iter, 1e-2)

self.ordering = VariableOrdering(objective)
self.solver = cem_solver(
Expand All @@ -173,16 +183,24 @@ def __init__(
n_batch,
n_sample,
n_elite,
n_iter,
temp,
lb,
ub,
temp,
normalize,
lml_verbose,
lml_eps,
normalize,
iter_eps,
)

def _maybe_init_best_solution(
self, do_init: bool = False
) -> Optional[Dict[str, torch.Tensor]]:
if not do_init:
return None
solution_dict = {}
for var in self.ordering:
solution_dict[var.name] = var.tensor.detach().clone().cpu()
return solution_dict

def _init_info(
self,
track_best_solution: bool,
Expand Down Expand Up @@ -266,7 +284,7 @@ def _update_info(
assert info.best_err is not None
good_indices = err < info.best_err
info.best_iter[good_indices] = current_iter
for var in self.linear_solver.linearization.ordering:
for var in self.ordering:
info.best_solution[var.name][good_indices] = (
var.tensor.detach().clone()[good_indices].cpu()
)
Expand Down Expand Up @@ -295,8 +313,8 @@ def _optimize_loop(
except RuntimeError as error:
raise RuntimeError(f"There is an error in update {error}")
dishank-b marked this conversation as resolved.
Show resolved Hide resolved

self.objective.retract_optim_var(
delta, self.ordering, ignore_mask=converged_indices, force_upate=False
self.objective.retract_optim_vars(
delta, self.ordering, ignore_mask=converged_indices, force_update=False
)

# check for convergence
Expand Down
Loading