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
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
removed _all_solve function and chnaged _solve name to _CEM_step
  • Loading branch information
dishank-b committed Mar 9, 2023
commit 126ee47ac3cdf0e4761769acb7d9d510887814b0
140 changes: 3 additions & 137 deletions theseus/optimizer/nonlinear/dcem.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,124 +95,7 @@ def _reinit_sigma(self, init_sigma=1.0, **kwargs):
* init_sigma
)

def _all_solve(
self,
num_iters,
init_sigma: Union[torch.Tensor, float] = 1.0,
info: NonlinearOptimizerInfo = None,
verbose: bool = False,
end_iter_callback: Optional[EndIterCallbackType] = None,
**kwargs,
):
converged_indices = torch.zeros_like(info.last_err).bool()

device = self.objective.device
n_batch = self.ordering[0].shape[0]

init_mu = torch.cat([var.tensor for var in self.ordering], dim=-1)
init_sigma = torch.ones((n_batch, self.tot_dof), device=device) * init_sigma

mu = init_mu.clone()
sigma = init_sigma.clone()

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

for itr in range(num_iters):
# X = Normal(mu, sigma + 1e-5).rsample((self.n_samples,))
X = Normal(mu, sigma).rsample((self.n_samples,))

X_samples = []
for sample in X:
X_samples.append(self._mu_vec_to_dict(sample))

fX = torch.stack(
[
self.objective.error_squared_norm(X_samples[i])
for i in range(self.n_samples)
],
dim=1,
)

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

if self.temp is not None and self.temp < np.infty:
if self.normalize:
fX_mu = fX.mean(dim=1).unsqueeze(1)
fX_sigma = fX.std(dim=1).unsqueeze(1)
_fX = (fX - fX_mu) / (fX_sigma + 1e-6)
else:
_fX = fX

if self.n_elite == 1:
# indexes = LML(N=n_elite, verbose=lml_verbose, eps=lml_eps)(-_fX*temp)
indexes = torch.softmax(-_fX * self.temp, dim=1)
else:
indexes = LML(N=self.n_elite, verbose=False, eps=self.lml_eps)(
-_fX * self.temp
)
indexes = indexes.unsqueeze(2)

else:
indexes_vals = fX.argsort(dim=1)[:, : self.n_elite]
# TODO: A scatter would be more efficient here.
indexes = torch.zeros(n_batch, self.n_samples, device=device)
for j in range(n_batch):
for v in indexes_vals[j]:
indexes[j, v] = 1.0
indexes = indexes.unsqueeze(2)
# indexes.shape should be (n_batch, n_sample, 1)

X = X.transpose(0, 1)

assert indexes.shape[:2] == X.shape[:2]
# print("Samples:", X)
X_I = indexes * X

# old_mu = mu.clone().detach()

mu = torch.sum(X_I, dim=1) / self.n_elite
sigma = (
(indexes * (X - mu.unsqueeze(1)) ** 2).sum(dim=1) / self.n_elite
).sqrt()

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

with torch.no_grad():
err = self.objective.error_squared_norm(self._mu_vec_to_dict(mu)) / 2
self._update_info(info, itr, err, converged_indices)
if verbose:
print(
f"Nonlinear optimizer. Iteration: {itr+1}. "
f"Error: {err.mean().item()}"
)
converged_indices = self._check_convergence(err, info.last_err)
info.status[
np.array(converged_indices.cpu().numpy())
] = NonlinearOptimizerStatus.CONVERGED

# TODO
# Doesn't work with lml_eps = 1e-5.
# and with lml_eps= 1e-4, gives suboptimal solution

# if converged_indices.all():
# break # nothing else will happen at this point

info.last_err = err

if end_iter_callback is not None:
end_iter_callback(self, info, mu, itr)

info.status[
info.status == NonlinearOptimizerStatus.START
] = NonlinearOptimizerStatus.MAX_ITERATIONS

self.objective.update(self._mu_vec_to_dict(mu))

# return self._mu_vec_to_dict(mu)
return itr

def _solve(self):
def _CEM_step(self):
dishank-b marked this conversation as resolved.
Show resolved Hide resolved
device = self.objective.device
n_batch = self.ordering[0].shape[0]

Expand Down Expand Up @@ -264,25 +147,8 @@ def _solve(self):
X = X.transpose(0, 1)

assert indexes.shape[:2] == X.shape[:2]
# print("Samples:", X)

X_I = indexes * X
# top_k_idx_11 = np.argsort(indexes[11].squeeze(1).cpu().numpy())[::-1][
# : self.n_elite
# ]
# top_k_idx_12 = np.argsort(indexes[12].squeeze(1).cpu().numpy())[::-1][
# : self.n_elite
# ]
# print(indexes[11][:50].squeeze(1), indexes[12][:50].squeeze(1))
# print("top K indices:", top_k_idx_11, top_k_idx_12)
# print(
# indexes[11].squeeze(1).cpu().numpy()[top_k_idx_11],
# indexes[12].squeeze(1).cpu().numpy()[top_k_idx_12],
# )
# print(X[11][top_k_idx_11.copy()])
# print(
# mu[11].cpu().numpy(),
# self.sigma[11].cpu().numpy(),
# )

mu = torch.sum(X_I, dim=1) / self.n_elite
self.sigma = (
Expand All @@ -307,7 +173,7 @@ def _optimize_loop(
for it_ in range(num_iter):
iters_done += 1
try:
mu = self._solve()
mu = self._CEM_step()
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

Expand Down